1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
92 // - ScriptContextTable
103 // - ExternalOneByteString
104 // - ExternalTwoByteString
105 // - InternalizedString
106 // - SeqInternalizedString
107 // - SeqOneByteInternalizedString
108 // - SeqTwoByteInternalizedString
109 // - ConsInternalizedString
110 // - ExternalInternalizedString
111 // - ExternalOneByteInternalizedString
112 // - ExternalTwoByteInternalizedString
132 // - SharedFunctionInfo
136 // - ExecutableAccessorInfo
142 // - FunctionTemplateInfo
143 // - ObjectTemplateInfo
152 // Formats of Object*:
153 // Smi: [31 bit signed int] 0
154 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
159 enum KeyedAccessStoreMode {
161 STORE_TRANSITION_TO_OBJECT,
162 STORE_TRANSITION_TO_DOUBLE,
163 STORE_AND_GROW_NO_TRANSITION,
164 STORE_AND_GROW_TRANSITION_TO_OBJECT,
165 STORE_AND_GROW_TRANSITION_TO_DOUBLE,
166 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
167 STORE_NO_TRANSITION_HANDLE_COW
171 // Valid hints for the abstract operation ToPrimitive,
172 // implemented according to ES6, section 7.1.1.
173 enum class ToPrimitiveHint { kDefault, kNumber, kString };
176 // Valid hints for the abstract operation OrdinaryToPrimitive,
177 // implemented according to ES6, section 7.1.1.
178 enum class OrdinaryToPrimitiveHint { kNumber, kString };
181 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
190 enum ExternalArrayType {
191 kExternalInt8Array = 1,
194 kExternalUint16Array,
196 kExternalUint32Array,
197 kExternalFloat32Array,
198 kExternalFloat64Array,
199 kExternalUint8ClampedArray,
203 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
204 return store_mode == STORE_TRANSITION_TO_OBJECT ||
205 store_mode == STORE_TRANSITION_TO_DOUBLE ||
206 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
207 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
211 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
212 KeyedAccessStoreMode store_mode) {
213 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
216 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
217 return STORE_AND_GROW_NO_TRANSITION;
219 return STANDARD_STORE;
223 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
224 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
225 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
229 enum IcCheckType { ELEMENT, PROPERTY };
232 // SKIP_WRITE_BARRIER skips the write barrier.
233 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
234 // only performs the generational part.
235 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
236 enum WriteBarrierMode {
238 UPDATE_WEAK_WRITE_BARRIER,
243 // Indicates whether a value can be loaded as a constant.
244 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
247 // PropertyNormalizationMode is used to specify whether to keep
248 // inobject properties when normalizing properties of a JSObject.
249 enum PropertyNormalizationMode {
250 CLEAR_INOBJECT_PROPERTIES,
251 KEEP_INOBJECT_PROPERTIES
255 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
256 // will give the fastest result by tailoring the map to the prototype, but that
257 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
258 // (at least for now) when dynamically modifying the prototype chain of an
259 // object using __proto__ or Object.setPrototypeOf.
260 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
263 // Indicates whether transitions can be added to a source map or not.
264 enum TransitionFlag {
270 // Indicates whether the transition is simple: the target map of the transition
271 // either extends the current map with a new property, or it modifies the
272 // property that was added last to the current map.
273 enum SimpleTransitionFlag {
274 SIMPLE_PROPERTY_TRANSITION,
280 // Indicates whether we are only interested in the descriptors of a particular
281 // map, or in all descriptors in the descriptor array.
282 enum DescriptorFlag {
287 // The GC maintains a bit of information, the MarkingParity, which toggles
288 // from odd to even and back every time marking is completed. Incremental
289 // marking can visit an object twice during a marking phase, so algorithms that
290 // that piggy-back on marking can use the parity to ensure that they only
291 // perform an operation on an object once per marking phase: they record the
292 // MarkingParity when they visit an object, and only re-visit the object when it
293 // is marked again and the MarkingParity changes.
300 // ICs store extra state in a Code object. The default extra state is
302 typedef int ExtraICState;
303 static const ExtraICState kNoExtraICState = 0;
305 // Instance size sentinel for objects of variable size.
306 const int kVariableSizeSentinel = 0;
308 // We may store the unsigned bit field as signed Smi value and do not
310 const int kStubMajorKeyBits = 7;
311 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
313 // All Maps have a field instance_type containing a InstanceType.
314 // It describes the type of the instances.
316 // As an example, a JavaScript object is a heap object and its map
317 // instance_type is JS_OBJECT_TYPE.
319 // The names of the string instance types are intended to systematically
320 // mirror their encoding in the instance_type field of the map. The default
321 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
322 // encoding is mentioned explicitly in the name. Likewise, the default
323 // representation is considered sequential. It is not mentioned in the
324 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
325 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
326 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
328 // NOTE: The following things are some that depend on the string types having
329 // instance_types that are less than those of all other types:
330 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
333 // NOTE: Everything following JS_VALUE_TYPE is considered a
334 // JSObject for GC purposes. The first four entries here have typeof
335 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
336 #define INSTANCE_TYPE_LIST(V) \
338 V(ONE_BYTE_STRING_TYPE) \
339 V(CONS_STRING_TYPE) \
340 V(CONS_ONE_BYTE_STRING_TYPE) \
341 V(SLICED_STRING_TYPE) \
342 V(SLICED_ONE_BYTE_STRING_TYPE) \
343 V(EXTERNAL_STRING_TYPE) \
344 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
345 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
346 V(SHORT_EXTERNAL_STRING_TYPE) \
347 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
348 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
350 V(INTERNALIZED_STRING_TYPE) \
351 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
352 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
353 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
354 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
355 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
356 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
357 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
360 V(SIMD128_VALUE_TYPE) \
366 V(PROPERTY_CELL_TYPE) \
368 V(HEAP_NUMBER_TYPE) \
369 V(MUTABLE_HEAP_NUMBER_TYPE) \
372 V(BYTECODE_ARRAY_TYPE) \
375 V(FIXED_INT8_ARRAY_TYPE) \
376 V(FIXED_UINT8_ARRAY_TYPE) \
377 V(FIXED_INT16_ARRAY_TYPE) \
378 V(FIXED_UINT16_ARRAY_TYPE) \
379 V(FIXED_INT32_ARRAY_TYPE) \
380 V(FIXED_UINT32_ARRAY_TYPE) \
381 V(FIXED_FLOAT32_ARRAY_TYPE) \
382 V(FIXED_FLOAT64_ARRAY_TYPE) \
383 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
387 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
388 V(DECLARED_ACCESSOR_INFO_TYPE) \
389 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
390 V(ACCESSOR_PAIR_TYPE) \
391 V(ACCESS_CHECK_INFO_TYPE) \
392 V(INTERCEPTOR_INFO_TYPE) \
393 V(CALL_HANDLER_INFO_TYPE) \
394 V(FUNCTION_TEMPLATE_INFO_TYPE) \
395 V(OBJECT_TEMPLATE_INFO_TYPE) \
396 V(SIGNATURE_INFO_TYPE) \
397 V(TYPE_SWITCH_INFO_TYPE) \
398 V(ALLOCATION_MEMENTO_TYPE) \
399 V(ALLOCATION_SITE_TYPE) \
402 V(POLYMORPHIC_CODE_CACHE_TYPE) \
403 V(TYPE_FEEDBACK_INFO_TYPE) \
404 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
406 V(PROTOTYPE_INFO_TYPE) \
407 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
409 V(FIXED_ARRAY_TYPE) \
410 V(FIXED_DOUBLE_ARRAY_TYPE) \
411 V(SHARED_FUNCTION_INFO_TYPE) \
414 V(JS_MESSAGE_OBJECT_TYPE) \
419 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
420 V(JS_GENERATOR_OBJECT_TYPE) \
422 V(JS_GLOBAL_OBJECT_TYPE) \
423 V(JS_BUILTINS_OBJECT_TYPE) \
424 V(JS_GLOBAL_PROXY_TYPE) \
426 V(JS_ARRAY_BUFFER_TYPE) \
427 V(JS_TYPED_ARRAY_TYPE) \
428 V(JS_DATA_VIEW_TYPE) \
432 V(JS_SET_ITERATOR_TYPE) \
433 V(JS_MAP_ITERATOR_TYPE) \
434 V(JS_WEAK_MAP_TYPE) \
435 V(JS_WEAK_SET_TYPE) \
438 V(JS_FUNCTION_TYPE) \
439 V(JS_FUNCTION_PROXY_TYPE) \
441 V(BREAK_POINT_INFO_TYPE)
444 // Since string types are not consecutive, this macro is used to
445 // iterate over them.
446 #define STRING_TYPE_LIST(V) \
447 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
448 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
450 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
451 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
453 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
454 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
455 SlicedOneByteString) \
456 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
458 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
459 external_one_byte_string, ExternalOneByteString) \
460 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
461 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
462 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
463 short_external_string, ShortExternalString) \
464 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
465 short_external_one_byte_string, ShortExternalOneByteString) \
466 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
467 ExternalTwoByteString::kShortSize, \
468 short_external_string_with_one_byte_data, \
469 ShortExternalStringWithOneByteData) \
471 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
472 InternalizedString) \
473 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
474 one_byte_internalized_string, OneByteInternalizedString) \
475 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
476 external_internalized_string, ExternalInternalizedString) \
477 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
478 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
479 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
480 ExternalTwoByteString::kSize, \
481 external_internalized_string_with_one_byte_data, \
482 ExternalInternalizedStringWithOneByteData) \
483 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
484 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
485 ShortExternalInternalizedString) \
486 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
487 ExternalOneByteString::kShortSize, \
488 short_external_one_byte_internalized_string, \
489 ShortExternalOneByteInternalizedString) \
490 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
491 ExternalTwoByteString::kShortSize, \
492 short_external_internalized_string_with_one_byte_data, \
493 ShortExternalInternalizedStringWithOneByteData)
495 // A struct is a simple object a set of object-valued fields. Including an
496 // object type in this causes the compiler to generate most of the boilerplate
497 // code for the class including allocation and garbage collection routines,
498 // casts and predicates. All you need to define is the class, methods and
499 // object verification routines. Easy, no?
501 // Note that for subtle reasons related to the ordering or numerical values of
502 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
504 #define STRUCT_LIST(V) \
506 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
507 executable_accessor_info) \
508 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
509 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
510 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
511 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
512 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
513 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
514 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
515 V(SCRIPT, Script, script) \
516 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
517 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
518 V(CODE_CACHE, CodeCache, code_cache) \
519 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
520 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
521 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
522 V(DEBUG_INFO, DebugInfo, debug_info) \
523 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
524 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
525 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
526 SloppyBlockWithEvalContextExtension, \
527 sloppy_block_with_eval_context_extension)
529 // We use the full 8 bits of the instance_type field to encode heap object
530 // instance types. The high-order bit (bit 7) is set if the object is not a
531 // string, and cleared if it is a string.
532 const uint32_t kIsNotStringMask = 0x80;
533 const uint32_t kStringTag = 0x0;
534 const uint32_t kNotStringTag = 0x80;
536 // Bit 6 indicates that the object is an internalized string (if set) or not.
537 // Bit 7 has to be clear as well.
538 const uint32_t kIsNotInternalizedMask = 0x40;
539 const uint32_t kNotInternalizedTag = 0x40;
540 const uint32_t kInternalizedTag = 0x0;
542 // If bit 7 is clear then bit 2 indicates whether the string consists of
543 // two-byte characters or one-byte characters.
544 const uint32_t kStringEncodingMask = 0x4;
545 const uint32_t kTwoByteStringTag = 0x0;
546 const uint32_t kOneByteStringTag = 0x4;
548 // If bit 7 is clear, the low-order 2 bits indicate the representation
550 const uint32_t kStringRepresentationMask = 0x03;
551 enum StringRepresentationTag {
553 kConsStringTag = 0x1,
554 kExternalStringTag = 0x2,
555 kSlicedStringTag = 0x3
557 const uint32_t kIsIndirectStringMask = 0x1;
558 const uint32_t kIsIndirectStringTag = 0x1;
559 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
560 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
561 STATIC_ASSERT((kConsStringTag &
562 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
563 STATIC_ASSERT((kSlicedStringTag &
564 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
566 // Use this mask to distinguish between cons and slice only after making
567 // sure that the string is one of the two (an indirect string).
568 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
569 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
571 // If bit 7 is clear, then bit 3 indicates whether this two-byte
572 // string actually contains one byte data.
573 const uint32_t kOneByteDataHintMask = 0x08;
574 const uint32_t kOneByteDataHintTag = 0x08;
576 // If bit 7 is clear and string representation indicates an external string,
577 // then bit 4 indicates whether the data pointer is cached.
578 const uint32_t kShortExternalStringMask = 0x10;
579 const uint32_t kShortExternalStringTag = 0x10;
582 // A ConsString with an empty string as the right side is a candidate
583 // for being shortcut by the garbage collector. We don't allocate any
584 // non-flat internalized strings, so we do not shortcut them thereby
585 // avoiding turning internalized strings into strings. The bit-masks
586 // below contain the internalized bit as additional safety.
587 // See heap.cc, mark-compact.cc and objects-visiting.cc.
588 const uint32_t kShortcutTypeMask =
590 kIsNotInternalizedMask |
591 kStringRepresentationMask;
592 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
594 static inline bool IsShortcutCandidate(int type) {
595 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
601 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
602 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
603 ONE_BYTE_INTERNALIZED_STRING_TYPE =
604 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
605 EXTERNAL_INTERNALIZED_STRING_TYPE =
606 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
607 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
608 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
609 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
610 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
612 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
613 kShortExternalStringTag |
615 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
616 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
618 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
619 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
620 kShortExternalStringTag | kInternalizedTag,
621 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
622 ONE_BYTE_STRING_TYPE =
623 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
624 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
625 CONS_ONE_BYTE_STRING_TYPE =
626 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
628 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
629 SLICED_ONE_BYTE_STRING_TYPE =
630 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
631 EXTERNAL_STRING_TYPE =
632 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
633 EXTERNAL_ONE_BYTE_STRING_TYPE =
634 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
635 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
636 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
638 SHORT_EXTERNAL_STRING_TYPE =
639 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
640 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
641 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
642 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
643 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
647 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
649 // Other primitives (cannot contain non-map-word pointers to heap objects).
652 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
654 // Objects allocated in their own spaces (never in new space).
658 // "Data", objects that cannot contain non-map-word pointers to heap
660 MUTABLE_HEAP_NUMBER_TYPE,
665 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
666 FIXED_UINT8_ARRAY_TYPE,
667 FIXED_INT16_ARRAY_TYPE,
668 FIXED_UINT16_ARRAY_TYPE,
669 FIXED_INT32_ARRAY_TYPE,
670 FIXED_UINT32_ARRAY_TYPE,
671 FIXED_FLOAT32_ARRAY_TYPE,
672 FIXED_FLOAT64_ARRAY_TYPE,
673 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
674 FIXED_DOUBLE_ARRAY_TYPE,
675 FILLER_TYPE, // LAST_DATA_TYPE
678 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
679 DECLARED_ACCESSOR_INFO_TYPE,
680 EXECUTABLE_ACCESSOR_INFO_TYPE,
682 ACCESS_CHECK_INFO_TYPE,
683 INTERCEPTOR_INFO_TYPE,
684 CALL_HANDLER_INFO_TYPE,
685 FUNCTION_TEMPLATE_INFO_TYPE,
686 OBJECT_TEMPLATE_INFO_TYPE,
688 TYPE_SWITCH_INFO_TYPE,
689 ALLOCATION_SITE_TYPE,
690 ALLOCATION_MEMENTO_TYPE,
693 POLYMORPHIC_CODE_CACHE_TYPE,
694 TYPE_FEEDBACK_INFO_TYPE,
695 ALIASED_ARGUMENTS_ENTRY_TYPE,
698 BREAK_POINT_INFO_TYPE,
700 SHARED_FUNCTION_INFO_TYPE,
705 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
707 // All the following types are subtypes of JSReceiver, which corresponds to
708 // objects in the JS sense. The first and the last type in this range are
709 // the two forms of function. This organization enables using the same
710 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
711 // NONCALLABLE_JS_OBJECT range.
712 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
713 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
714 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
715 JS_MESSAGE_OBJECT_TYPE,
718 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
719 JS_GENERATOR_OBJECT_TYPE,
721 JS_GLOBAL_OBJECT_TYPE,
722 JS_BUILTINS_OBJECT_TYPE,
723 JS_GLOBAL_PROXY_TYPE,
725 JS_ARRAY_BUFFER_TYPE,
730 JS_SET_ITERATOR_TYPE,
731 JS_MAP_ITERATOR_TYPE,
735 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
739 LAST_TYPE = JS_FUNCTION_TYPE,
740 FIRST_NAME_TYPE = FIRST_TYPE,
741 LAST_NAME_TYPE = SYMBOL_TYPE,
742 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
743 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
744 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
745 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
746 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
747 // Boundaries for testing for a fixed typed array.
748 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
749 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
750 // Boundary for promotion to old space.
751 LAST_DATA_TYPE = FILLER_TYPE,
752 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
753 // Note that there is no range for JSObject or JSProxy, since their subtypes
754 // are not continuous in this enum! The enum ranges instead reflect the
755 // external class names, where proxies are treated as either ordinary objects,
757 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
758 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
759 // Boundaries for testing the types represented as JSObject
760 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
761 LAST_JS_OBJECT_TYPE = LAST_TYPE,
762 // Boundaries for testing the types represented as JSProxy
763 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
764 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
765 // Boundaries for testing whether the type is a JavaScript object.
766 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
767 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
768 // Boundaries for testing the types for which typeof is "object".
769 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
770 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
771 // Note that the types for which typeof is "function" are not continuous.
772 // Define this so that we can put assertions on discrete checks.
773 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
776 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
777 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
778 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
779 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
782 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
783 V(FAST_ELEMENTS_SUB_TYPE) \
784 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
785 V(FAST_PROPERTIES_SUB_TYPE) \
786 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
787 V(MAP_CODE_CACHE_SUB_TYPE) \
788 V(SCOPE_INFO_SUB_TYPE) \
789 V(STRING_TABLE_SUB_TYPE) \
790 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
791 V(TRANSITION_ARRAY_SUB_TYPE)
793 enum FixedArraySubInstanceType {
794 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
795 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
796 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
797 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
810 #define DECL_BOOLEAN_ACCESSORS(name) \
811 inline bool name() const; \
812 inline void set_##name(bool value); \
815 #define DECL_ACCESSORS(name, type) \
816 inline type* name() const; \
817 inline void set_##name(type* value, \
818 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
821 #define DECLARE_CAST(type) \
822 INLINE(static type* cast(Object* object)); \
823 INLINE(static const type* cast(const Object* object));
827 class AllocationSite;
828 class AllocationSiteCreationContext;
829 class AllocationSiteUsageContext;
832 class ElementsAccessor;
833 class FixedArrayBase;
834 class FunctionLiteral;
836 class JSBuiltinsObject;
837 class LayoutDescriptor;
838 class LookupIterator;
839 class ObjectHashTable;
842 class SafepointEntry;
843 class SharedFunctionInfo;
845 class TypeFeedbackInfo;
846 class TypeFeedbackVector;
849 // We cannot just say "class HeapType;" if it is created from a template... =8-?
850 template<class> class TypeImpl;
851 struct HeapTypeConfig;
852 typedef TypeImpl<HeapTypeConfig> HeapType;
855 // A template-ized version of the IsXXX functions.
856 template <class C> inline bool Is(Object* obj);
859 #define DECLARE_VERIFIER(Name) void Name##Verify();
861 #define DECLARE_VERIFIER(Name)
865 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
867 #define DECLARE_PRINTER(Name)
871 #define OBJECT_TYPE_LIST(V) \
876 #define HEAP_OBJECT_TYPE_LIST(V) \
878 V(MutableHeapNumber) \
897 V(ExternalTwoByteString) \
898 V(ExternalOneByteString) \
899 V(SeqTwoByteString) \
900 V(SeqOneByteString) \
901 V(InternalizedString) \
904 V(FixedTypedArrayBase) \
907 V(FixedUint16Array) \
909 V(FixedUint32Array) \
911 V(FixedFloat32Array) \
912 V(FixedFloat64Array) \
913 V(FixedUint8ClampedArray) \
919 V(JSContextExtensionObject) \
920 V(JSGeneratorObject) \
922 V(LayoutDescriptor) \
926 V(TypeFeedbackVector) \
927 V(DeoptimizationInputData) \
928 V(DeoptimizationOutputData) \
932 V(FixedDoubleArray) \
936 V(ScriptContextTable) \
942 V(SharedFunctionInfo) \
951 V(JSArrayBufferView) \
960 V(JSWeakCollection) \
967 V(NormalizedMapCache) \
968 V(CompilationCacheTable) \
969 V(CodeCacheHashTable) \
970 V(PolymorphicCodeCacheHashTable) \
975 V(JSBuiltinsObject) \
977 V(UndetectableObject) \
978 V(AccessCheckNeeded) \
986 // Object is the abstract superclass for all classes in the
988 // Object does not use any virtual functions to avoid the
989 // allocation of the C++ vtable.
990 // Since both Smi and HeapObject are subclasses of Object no
991 // data members can be present in Object.
995 bool IsObject() const { return true; }
997 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
998 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
999 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1000 #undef IS_TYPE_FUNCTION_DECL
1002 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1003 // a keyed store is of the form a[expression] = foo.
1004 enum StoreFromKeyed {
1005 MAY_BE_STORE_FROM_KEYED,
1006 CERTAINLY_NOT_STORE_FROM_KEYED
1009 INLINE(bool IsFixedArrayBase() const);
1010 INLINE(bool IsExternal() const);
1011 INLINE(bool IsAccessorInfo() const);
1013 INLINE(bool IsStruct() const);
1014 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1015 INLINE(bool Is##Name() const);
1016 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1017 #undef DECLARE_STRUCT_PREDICATE
1019 INLINE(bool IsSpecObject()) const;
1020 INLINE(bool IsSpecFunction()) const;
1021 INLINE(bool IsTemplateInfo()) const;
1022 INLINE(bool IsNameDictionary() const);
1023 INLINE(bool IsGlobalDictionary() const);
1024 INLINE(bool IsSeededNumberDictionary() const);
1025 INLINE(bool IsUnseededNumberDictionary() const);
1026 INLINE(bool IsOrderedHashSet() const);
1027 INLINE(bool IsOrderedHashMap() const);
1028 bool IsCallable() const;
1029 static bool IsPromise(Handle<Object> object);
1032 INLINE(bool IsUndefined() const);
1033 INLINE(bool IsNull() const);
1034 INLINE(bool IsTheHole() const);
1035 INLINE(bool IsException() const);
1036 INLINE(bool IsUninitialized() const);
1037 INLINE(bool IsTrue() const);
1038 INLINE(bool IsFalse() const);
1039 INLINE(bool IsArgumentsMarker() const);
1041 // Filler objects (fillers and free space objects).
1042 INLINE(bool IsFiller() const);
1044 // Extract the number.
1045 inline double Number();
1046 INLINE(bool IsNaN() const);
1047 INLINE(bool IsMinusZero() const);
1048 bool ToInt32(int32_t* value);
1049 bool ToUint32(uint32_t* value);
1051 inline Representation OptimalRepresentation();
1053 inline ElementsKind OptimalElementsKind();
1055 inline bool FitsRepresentation(Representation representation);
1057 // Checks whether two valid primitive encodings of a property name resolve to
1058 // the same logical property. E.g., the smi 1, the string "1" and the double
1059 // 1 all refer to the same property, so this helper will return true.
1060 inline bool KeyEquals(Object* other);
1062 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1064 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1065 Handle<Object> object,
1066 Representation representation);
1068 inline static Handle<Object> WrapForRead(Isolate* isolate,
1069 Handle<Object> object,
1070 Representation representation);
1072 // Returns true if the object is of the correct type to be used as a
1073 // implementation of a JSObject's elements.
1074 inline bool HasValidElements();
1076 inline bool HasSpecificClassOf(String* name);
1078 bool BooleanValue(); // ECMA-262 9.2.
1080 // ES6 section 7.2.13 Strict Equality Comparison
1081 bool StrictEquals(Object* that);
1083 // Convert to a JSObject if needed.
1084 // native_context is used when creating wrapper object.
1085 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1086 Handle<Object> object);
1087 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1088 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1090 // ES6 section 7.1.14 ToPropertyKey
1091 MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1092 Handle<Object> input);
1094 // ES6 section 7.1.1 ToPrimitive
1095 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1096 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1098 // ES6 section 7.1.3 ToNumber
1099 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Isolate* isolate,
1100 Handle<Object> input);
1102 // ES6 section 7.1.12 ToString
1103 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1104 Handle<Object> input);
1106 // ES6 section 7.3.9 GetMethod
1107 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1108 Handle<JSReceiver> receiver, Handle<Name> name);
1110 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1111 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1113 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1114 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1115 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1116 LanguageMode language_mode,
1117 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1119 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1120 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1121 StoreFromKeyed store_mode);
1123 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1124 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1125 StoreFromKeyed store_mode);
1127 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1128 LookupIterator* it, LanguageMode language_mode);
1129 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1130 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1131 LanguageMode language_mode);
1132 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1133 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1134 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1135 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1136 Handle<Object> value, LanguageMode language_mode);
1137 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1138 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1139 LanguageMode language_mode);
1140 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1141 LookupIterator* it, Handle<Object> value);
1142 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1143 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1144 LanguageMode language_mode, StoreFromKeyed store_mode);
1145 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1146 Handle<Object> object, Handle<Name> name,
1147 LanguageMode language_mode = SLOPPY);
1148 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1149 Isolate* isolate, Handle<Object> object, const char* key,
1150 LanguageMode language_mode = SLOPPY);
1151 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1152 Handle<Object> object, Handle<Name> name,
1153 LanguageMode language_mode = SLOPPY);
1155 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1156 LookupIterator* it, LanguageMode language_mode);
1157 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1158 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1160 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1161 Handle<Object> receiver,
1162 Handle<JSReceiver> getter);
1163 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1164 Handle<Object> receiver,
1165 Handle<JSReceiver> setter,
1166 Handle<Object> value);
1168 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1169 Isolate* isolate, Handle<Object> object, uint32_t index,
1170 LanguageMode language_mode = SLOPPY);
1172 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1173 Isolate* isolate, Handle<Object> object, uint32_t index,
1174 Handle<Object> value, LanguageMode language_mode);
1176 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1177 Isolate* isolate, Handle<Object> receiver);
1179 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1181 // Returns the permanent hash code associated with this object. May return
1182 // undefined if not yet created.
1185 // Returns undefined for JSObjects, but returns the hash code for simple
1186 // objects. This avoids a double lookup in the cases where we know we will
1187 // add the hash to the JSObject if it does not already exist.
1188 Object* GetSimpleHash();
1190 // Returns the permanent hash code associated with this object depending on
1191 // the actual object type. May create and store a hash code if needed and none
1193 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1195 // Checks whether this object has the same value as the given one. This
1196 // function is implemented according to ES5, section 9.12 and can be used
1197 // to implement the Harmony "egal" function.
1198 bool SameValue(Object* other);
1200 // Checks whether this object has the same value as the given one.
1201 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1202 // This function is implemented according to ES6, section 7.2.4 and is used
1203 // by ES6 Map and Set.
1204 bool SameValueZero(Object* other);
1206 // Tries to convert an object to an array length. Returns true and sets the
1207 // output parameter if it succeeds.
1208 inline bool ToArrayLength(uint32_t* index);
1210 // Tries to convert an object to an array index. Returns true and sets the
1211 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1212 // allow kMaxUInt32.
1213 inline bool ToArrayIndex(uint32_t* index);
1215 // Returns true if this is a JSValue containing a string and the index is
1216 // < the length of the string. Used to implement [] on strings.
1217 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1219 DECLARE_VERIFIER(Object)
1221 // Verify a pointer is a valid object pointer.
1222 static void VerifyPointer(Object* p);
1225 inline void VerifyApiCallResultType();
1227 // Prints this object without details.
1228 void ShortPrint(FILE* out = stdout);
1230 // Prints this object without details to a message accumulator.
1231 void ShortPrint(StringStream* accumulator);
1233 void ShortPrint(std::ostream& os); // NOLINT
1235 DECLARE_CAST(Object)
1237 // Layout description.
1238 static const int kHeaderSize = 0; // Object does not take up any space.
1241 // For our gdb macros, we should perhaps change these in the future.
1244 // Prints this object with details.
1245 void Print(std::ostream& os); // NOLINT
1247 void Print() { ShortPrint(); }
1248 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1252 friend class LookupIterator;
1253 friend class PrototypeIterator;
1255 // Return the map of the root of object's prototype chain.
1256 Map* GetRootMap(Isolate* isolate);
1258 // Helper for SetProperty and SetSuperProperty.
1259 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1260 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1261 StoreFromKeyed store_mode, bool* found);
1263 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1267 // In objects.h to be usable without objects-inl.h inclusion.
1268 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1269 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1273 explicit Brief(const Object* const v) : value(v) {}
1274 const Object* value;
1278 std::ostream& operator<<(std::ostream& os, const Brief& v);
1281 // Smi represents integer Numbers that can be stored in 31 bits.
1282 // Smis are immediate which means they are NOT allocated in the heap.
1283 // The this pointer has the following format: [31 bit signed int] 0
1284 // For long smis it has the following format:
1285 // [32 bit signed int] [31 bits zero padding] 0
1286 // Smi stands for small integer.
1287 class Smi: public Object {
1289 // Returns the integer value.
1290 inline int value() const { return Internals::SmiValue(this); }
1292 // Convert a value to a Smi object.
1293 static inline Smi* FromInt(int value) {
1294 DCHECK(Smi::IsValid(value));
1295 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1298 static inline Smi* FromIntptr(intptr_t value) {
1299 DCHECK(Smi::IsValid(value));
1300 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1301 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1304 // Returns whether value can be represented in a Smi.
1305 static inline bool IsValid(intptr_t value) {
1306 bool result = Internals::IsValidSmi(value);
1307 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1313 // Dispatched behavior.
1314 void SmiPrint(std::ostream& os) const; // NOLINT
1315 DECLARE_VERIFIER(Smi)
1317 static const int kMinValue =
1318 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1319 static const int kMaxValue = -(kMinValue + 1);
1322 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1326 // Heap objects typically have a map pointer in their first word. However,
1327 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1328 // encoded in the first word. The class MapWord is an abstraction of the
1329 // value in a heap object's first word.
1330 class MapWord BASE_EMBEDDED {
1332 // Normal state: the map word contains a map pointer.
1334 // Create a map word from a map pointer.
1335 static inline MapWord FromMap(const Map* map);
1337 // View this map word as a map pointer.
1338 inline Map* ToMap();
1341 // Scavenge collection: the map word of live objects in the from space
1342 // contains a forwarding address (a heap object pointer in the to space).
1344 // True if this map word is a forwarding address for a scavenge
1345 // collection. Only valid during a scavenge collection (specifically,
1346 // when all map words are heap object pointers, i.e. not during a full GC).
1347 inline bool IsForwardingAddress();
1349 // Create a map word from a forwarding address.
1350 static inline MapWord FromForwardingAddress(HeapObject* object);
1352 // View this map word as a forwarding address.
1353 inline HeapObject* ToForwardingAddress();
1355 static inline MapWord FromRawValue(uintptr_t value) {
1356 return MapWord(value);
1359 inline uintptr_t ToRawValue() {
1364 // HeapObject calls the private constructor and directly reads the value.
1365 friend class HeapObject;
1367 explicit MapWord(uintptr_t value) : value_(value) {}
1373 // The content of an heap object (except for the map pointer). kTaggedValues
1374 // objects can contain both heap pointers and Smis, kMixedValues can contain
1375 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1376 // objects can contain raw values and Smis.
1377 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1380 // HeapObject is the superclass for all classes describing heap allocated
1382 class HeapObject: public Object {
1384 // [map]: Contains a map which contains the object's reflective
1386 inline Map* map() const;
1387 inline void set_map(Map* value);
1388 // The no-write-barrier version. This is OK if the object is white and in
1389 // new space, or if the value is an immortal immutable object, like the maps
1390 // of primitive (non-JS) objects like strings, heap numbers etc.
1391 inline void set_map_no_write_barrier(Map* value);
1393 // Get the map using acquire load.
1394 inline Map* synchronized_map();
1395 inline MapWord synchronized_map_word() const;
1397 // Set the map using release store
1398 inline void synchronized_set_map(Map* value);
1399 inline void synchronized_set_map_no_write_barrier(Map* value);
1400 inline void synchronized_set_map_word(MapWord map_word);
1402 // During garbage collection, the map word of a heap object does not
1403 // necessarily contain a map pointer.
1404 inline MapWord map_word() const;
1405 inline void set_map_word(MapWord map_word);
1407 // The Heap the object was allocated in. Used also to access Isolate.
1408 inline Heap* GetHeap() const;
1410 // Convenience method to get current isolate.
1411 inline Isolate* GetIsolate() const;
1413 // Converts an address to a HeapObject pointer.
1414 static inline HeapObject* FromAddress(Address address) {
1415 DCHECK_TAG_ALIGNED(address);
1416 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1419 // Returns the address of this HeapObject.
1420 inline Address address() {
1421 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1424 // Iterates over pointers contained in the object (including the Map)
1425 void Iterate(ObjectVisitor* v);
1427 // Iterates over all pointers contained in the object except the
1428 // first map pointer. The object type is given in the first
1429 // parameter. This function does not access the map pointer in the
1430 // object, and so is safe to call while the map pointer is modified.
1431 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1433 // Returns the heap object's size in bytes
1436 // Indicates what type of values this heap object may contain.
1437 inline HeapObjectContents ContentType();
1439 // Given a heap object's map pointer, returns the heap size in bytes
1440 // Useful when the map pointer field is used for other purposes.
1442 inline int SizeFromMap(Map* map);
1444 // Returns the field at offset in obj, as a read/write Object* reference.
1445 // Does no checking, and is safe to use during GC, while maps are invalid.
1446 // Does not invoke write barrier, so should only be assigned to
1447 // during marking GC.
1448 static inline Object** RawField(HeapObject* obj, int offset);
1450 // Adds the |code| object related to |name| to the code cache of this map. If
1451 // this map is a dictionary map that is shared, the map copied and installed
1453 static void UpdateMapCodeCache(Handle<HeapObject> object,
1457 DECLARE_CAST(HeapObject)
1459 // Return the write barrier mode for this. Callers of this function
1460 // must be able to present a reference to an DisallowHeapAllocation
1461 // object as a sign that they are not going to use this function
1462 // from code that allocates and thus invalidates the returned write
1464 inline WriteBarrierMode GetWriteBarrierMode(
1465 const DisallowHeapAllocation& promise);
1467 // Dispatched behavior.
1468 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1470 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1472 DECLARE_PRINTER(HeapObject)
1473 DECLARE_VERIFIER(HeapObject)
1475 inline void VerifyObjectField(int offset);
1476 inline void VerifySmiField(int offset);
1478 // Verify a pointer is a valid HeapObject pointer that points to object
1479 // areas in the heap.
1480 static void VerifyHeapPointer(Object* p);
1483 inline AllocationAlignment RequiredAlignment();
1485 // Layout description.
1486 // First field in a heap object is map.
1487 static const int kMapOffset = Object::kHeaderSize;
1488 static const int kHeaderSize = kMapOffset + kPointerSize;
1490 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1493 // helpers for calling an ObjectVisitor to iterate over pointers in the
1494 // half-open range [start, end) specified as integer offsets
1495 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1496 // as above, for the single element at "offset"
1497 inline void IteratePointer(ObjectVisitor* v, int offset);
1498 // as above, for the next code link of a code object.
1499 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1502 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1506 // This class describes a body of an object of a fixed size
1507 // in which all pointer fields are located in the [start_offset, end_offset)
1509 template<int start_offset, int end_offset, int size>
1510 class FixedBodyDescriptor {
1512 static const int kStartOffset = start_offset;
1513 static const int kEndOffset = end_offset;
1514 static const int kSize = size;
1516 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1518 template<typename StaticVisitor>
1519 static inline void IterateBody(HeapObject* obj) {
1520 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1521 HeapObject::RawField(obj, end_offset));
1526 // This class describes a body of an object of a variable size
1527 // in which all pointer fields are located in the [start_offset, object_size)
1529 template<int start_offset>
1530 class FlexibleBodyDescriptor {
1532 static const int kStartOffset = start_offset;
1534 static inline void IterateBody(HeapObject* obj,
1538 template<typename StaticVisitor>
1539 static inline void IterateBody(HeapObject* obj, int object_size) {
1540 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1541 HeapObject::RawField(obj, object_size));
1546 // The HeapNumber class describes heap allocated numbers that cannot be
1547 // represented in a Smi (small integer)
1548 class HeapNumber: public HeapObject {
1550 // [value]: number value.
1551 inline double value() const;
1552 inline void set_value(double value);
1554 DECLARE_CAST(HeapNumber)
1556 // Dispatched behavior.
1557 bool HeapNumberBooleanValue();
1559 void HeapNumberPrint(std::ostream& os); // NOLINT
1560 DECLARE_VERIFIER(HeapNumber)
1562 inline int get_exponent();
1563 inline int get_sign();
1565 // Layout description.
1566 static const int kValueOffset = HeapObject::kHeaderSize;
1567 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1568 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1569 // words within double numbers are endian dependent and they are set
1571 #if defined(V8_TARGET_LITTLE_ENDIAN)
1572 static const int kMantissaOffset = kValueOffset;
1573 static const int kExponentOffset = kValueOffset + 4;
1574 #elif defined(V8_TARGET_BIG_ENDIAN)
1575 static const int kMantissaOffset = kValueOffset + 4;
1576 static const int kExponentOffset = kValueOffset;
1578 #error Unknown byte ordering
1581 static const int kSize = kValueOffset + kDoubleSize;
1582 static const uint32_t kSignMask = 0x80000000u;
1583 static const uint32_t kExponentMask = 0x7ff00000u;
1584 static const uint32_t kMantissaMask = 0xfffffu;
1585 static const int kMantissaBits = 52;
1586 static const int kExponentBits = 11;
1587 static const int kExponentBias = 1023;
1588 static const int kExponentShift = 20;
1589 static const int kInfinityOrNanExponent =
1590 (kExponentMask >> kExponentShift) - kExponentBias;
1591 static const int kMantissaBitsInTopWord = 20;
1592 static const int kNonMantissaBitsInTopWord = 12;
1595 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1599 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1600 class Simd128Value : public HeapObject {
1602 DECLARE_CAST(Simd128Value)
1604 DECLARE_PRINTER(Simd128Value)
1605 DECLARE_VERIFIER(Simd128Value)
1607 static Handle<String> ToString(Handle<Simd128Value> input);
1609 // Equality operations.
1610 inline bool Equals(Simd128Value* that);
1612 // Checks that another instance is bit-wise equal.
1613 bool BitwiseEquals(const Simd128Value* other) const;
1614 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1615 uint32_t Hash() const;
1616 // Copies the 16 bytes of SIMD data to the destination address.
1617 void CopyBits(void* destination) const;
1619 // Layout description.
1620 static const int kValueOffset = HeapObject::kHeaderSize;
1621 static const int kSize = kValueOffset + kSimd128Size;
1624 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1628 // V has parameters (TYPE, Type, type, lane count, lane type)
1629 #define SIMD128_TYPES(V) \
1630 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1631 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1632 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1633 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1634 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1635 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1636 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1637 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1638 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1639 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1641 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1642 class Type final : public Simd128Value { \
1644 inline lane_type get_lane(int lane) const; \
1645 inline void set_lane(int lane, lane_type value); \
1647 DECLARE_CAST(Type) \
1649 DECLARE_PRINTER(Type) \
1651 static Handle<String> ToString(Handle<Type> input); \
1653 inline bool Equals(Type* that); \
1656 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1658 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1659 #undef SIMD128_VALUE_CLASS
1662 enum EnsureElementsMode {
1663 DONT_ALLOW_DOUBLE_ELEMENTS,
1664 ALLOW_COPIED_DOUBLE_ELEMENTS,
1665 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1669 // Indicator for one component of an AccessorPair.
1670 enum AccessorComponent {
1676 // JSReceiver includes types on which properties can be defined, i.e.,
1677 // JSObject and JSProxy.
1678 class JSReceiver: public HeapObject {
1680 DECLARE_CAST(JSReceiver)
1682 // ES6 section 7.1.1 ToPrimitive
1683 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1684 Handle<JSReceiver> receiver,
1685 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1686 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1687 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1689 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1690 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1691 Handle<JSReceiver> object, Handle<Name> name);
1692 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1694 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1695 Handle<JSReceiver> object, uint32_t index);
1696 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1697 Handle<JSReceiver> object, uint32_t index);
1699 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1700 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1701 Handle<JSReceiver> object, Handle<Name> name,
1702 LanguageMode language_mode = SLOPPY);
1703 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1704 Handle<JSReceiver> object, Handle<Name> name,
1705 LanguageMode language_mode = SLOPPY);
1706 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1707 LookupIterator* it, LanguageMode language_mode);
1708 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1709 Handle<JSReceiver> object, uint32_t index,
1710 LanguageMode language_mode = SLOPPY);
1712 // Tests for the fast common case for property enumeration.
1713 bool IsSimpleEnum();
1715 // Returns the class name ([[Class]] property in the specification).
1716 String* class_name();
1718 // Returns the constructor name (the name (possibly, inferred name) of the
1719 // function that was used to instantiate the object).
1720 String* constructor_name();
1722 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1723 Handle<JSReceiver> object, Handle<Name> name);
1724 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1725 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1727 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1728 Handle<JSReceiver> object, uint32_t index);
1729 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1730 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1732 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1733 LookupIterator* it);
1736 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1738 static Handle<Object> GetDataProperty(LookupIterator* it);
1741 // Retrieves a permanent object identity hash code. The undefined value might
1742 // be returned in case no hash was created yet.
1743 inline Object* GetIdentityHash();
1745 // Retrieves a permanent object identity hash code. May create and store a
1746 // hash code if needed and none exists.
1747 inline static Handle<Smi> GetOrCreateIdentityHash(
1748 Handle<JSReceiver> object);
1750 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1752 // Computes the enumerable keys for a JSObject. Used for implementing
1753 // "for (n in object) { }".
1754 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1755 Handle<JSReceiver> object,
1756 KeyCollectionType type);
1759 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1763 // The JSObject describes real heap allocated JavaScript objects with
1765 // Note that the map of JSObject changes during execution to enable inline
1767 class JSObject: public JSReceiver {
1769 // [properties]: Backing storage for properties.
1770 // properties is a FixedArray in the fast case and a Dictionary in the
1772 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1773 inline void initialize_properties();
1774 inline bool HasFastProperties();
1775 // Gets slow properties for non-global objects.
1776 inline NameDictionary* property_dictionary();
1777 // Gets global object properties.
1778 inline GlobalDictionary* global_dictionary();
1780 // [elements]: The elements (properties with names that are integers).
1782 // Elements can be in two general modes: fast and slow. Each mode
1783 // corrensponds to a set of object representations of elements that
1784 // have something in common.
1786 // In the fast mode elements is a FixedArray and so each element can
1787 // be quickly accessed. This fact is used in the generated code. The
1788 // elements array can have one of three maps in this mode:
1789 // fixed_array_map, sloppy_arguments_elements_map or
1790 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1791 // the elements array may be shared by a few objects and so before
1792 // writing to any element the array must be copied. Use
1793 // EnsureWritableFastElements in this case.
1795 // In the slow mode the elements is either a NumberDictionary, a
1796 // FixedArray parameter map for a (sloppy) arguments object.
1797 DECL_ACCESSORS(elements, FixedArrayBase)
1798 inline void initialize_elements();
1799 static void ResetElements(Handle<JSObject> object);
1800 static inline void SetMapAndElements(Handle<JSObject> object,
1802 Handle<FixedArrayBase> elements);
1803 inline ElementsKind GetElementsKind();
1804 ElementsAccessor* GetElementsAccessor();
1805 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1806 inline bool HasFastSmiElements();
1807 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1808 inline bool HasFastObjectElements();
1809 // Returns true if an object has elements of FAST_ELEMENTS or
1810 // FAST_SMI_ONLY_ELEMENTS.
1811 inline bool HasFastSmiOrObjectElements();
1812 // Returns true if an object has any of the fast elements kinds.
1813 inline bool HasFastElements();
1814 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1816 inline bool HasFastDoubleElements();
1817 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1819 inline bool HasFastHoleyElements();
1820 inline bool HasSloppyArgumentsElements();
1821 inline bool HasDictionaryElements();
1823 inline bool HasFixedTypedArrayElements();
1825 inline bool HasFixedUint8ClampedElements();
1826 inline bool HasFixedArrayElements();
1827 inline bool HasFixedInt8Elements();
1828 inline bool HasFixedUint8Elements();
1829 inline bool HasFixedInt16Elements();
1830 inline bool HasFixedUint16Elements();
1831 inline bool HasFixedInt32Elements();
1832 inline bool HasFixedUint32Elements();
1833 inline bool HasFixedFloat32Elements();
1834 inline bool HasFixedFloat64Elements();
1836 inline bool HasFastArgumentsElements();
1837 inline bool HasSlowArgumentsElements();
1838 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1840 // Requires: HasFastElements().
1841 static Handle<FixedArray> EnsureWritableFastElements(
1842 Handle<JSObject> object);
1844 // Collects elements starting at index 0.
1845 // Undefined values are placed after non-undefined values.
1846 // Returns the number of non-undefined values.
1847 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1849 // As PrepareElementsForSort, but only on objects where elements is
1850 // a dictionary, and it will stay a dictionary. Collates undefined and
1851 // unexisting elements below limit from position zero of the elements.
1852 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1855 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1856 LookupIterator* it, Handle<Object> value);
1858 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1859 // grant an exemption to ExecutableAccessor callbacks in some cases.
1860 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1862 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1863 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1864 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1866 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1867 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1868 PropertyAttributes attributes,
1869 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1871 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1872 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1873 PropertyAttributes attributes,
1874 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1876 // Equivalent to one of the above depending on whether |name| can be converted
1877 // to an array index.
1878 MUST_USE_RESULT static MaybeHandle<Object>
1879 DefinePropertyOrElementIgnoreAttributes(
1880 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1881 PropertyAttributes attributes = NONE,
1882 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1884 // Adds or reconfigures a property to attributes NONE. It will fail when it
1886 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1887 Handle<Object> value);
1889 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1890 Handle<Object> value, PropertyAttributes attributes);
1892 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1893 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1894 PropertyAttributes attributes);
1896 // Extend the receiver with a single fast property appeared first in the
1897 // passed map. This also extends the property backing store if necessary.
1898 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1900 // Migrates the given object to a map whose field representations are the
1901 // lowest upper bound of all known representations for that field.
1902 static void MigrateInstance(Handle<JSObject> instance);
1904 // Migrates the given object only if the target map is already available,
1905 // or returns false if such a map is not yet available.
1906 static bool TryMigrateInstance(Handle<JSObject> instance);
1908 // Sets the property value in a normalized object given (key, value, details).
1909 // Handles the special representation of JS global objects.
1910 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1911 Handle<Object> value,
1912 PropertyDetails details);
1913 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1914 Handle<Object> value,
1915 PropertyAttributes attributes);
1916 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1918 Handle<Object> value,
1919 PropertyAttributes attributes);
1921 static void OptimizeAsPrototype(Handle<JSObject> object,
1922 PrototypeOptimizationMode mode);
1923 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1924 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1925 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1926 static void InvalidatePrototypeChains(Map* map);
1928 // Alternative implementation of WeakFixedArray::NullCallback.
1929 class PrototypeRegistryCompactionCallback {
1931 static void Callback(Object* value, int old_index, int new_index);
1934 // Retrieve interceptors.
1935 InterceptorInfo* GetNamedInterceptor();
1936 InterceptorInfo* GetIndexedInterceptor();
1938 // Used from JSReceiver.
1939 MUST_USE_RESULT static Maybe<PropertyAttributes>
1940 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1941 MUST_USE_RESULT static Maybe<PropertyAttributes>
1942 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1944 // Retrieves an AccessorPair property from the given object. Might return
1945 // undefined if the property doesn't exist or is of a different kind.
1946 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1947 Handle<JSObject> object,
1949 AccessorComponent component);
1951 // Defines an AccessorPair property on the given object.
1952 // TODO(mstarzinger): Rename to SetAccessor().
1953 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1955 Handle<Object> getter,
1956 Handle<Object> setter,
1957 PropertyAttributes attributes);
1959 // Defines an AccessorInfo property on the given object.
1960 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1961 Handle<JSObject> object,
1962 Handle<AccessorInfo> info);
1964 // The result must be checked first for exceptions. If there's no exception,
1965 // the output parameter |done| indicates whether the interceptor has a result
1967 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1968 LookupIterator* it, bool* done);
1970 // Accessors for hidden properties object.
1972 // Hidden properties are not own properties of the object itself.
1973 // Instead they are stored in an auxiliary structure kept as an own
1974 // property with a special name Heap::hidden_string(). But if the
1975 // receiver is a JSGlobalProxy then the auxiliary object is a property
1976 // of its prototype, and if it's a detached proxy, then you can't have
1977 // hidden properties.
1979 // Sets a hidden property on this object. Returns this object if successful,
1980 // undefined if called on a detached proxy.
1981 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1983 Handle<Object> value);
1984 // Gets the value of a hidden property with the given key. Returns the hole
1985 // if the property doesn't exist (or if called on a detached proxy),
1986 // otherwise returns the value set for the key.
1987 Object* GetHiddenProperty(Handle<Name> key);
1988 // Deletes a hidden property. Deleting a non-existing property is
1989 // considered successful.
1990 static void DeleteHiddenProperty(Handle<JSObject> object,
1992 // Returns true if the object has a property with the hidden string as name.
1993 static bool HasHiddenProperties(Handle<JSObject> object);
1995 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1997 static void ValidateElements(Handle<JSObject> object);
1999 // Makes sure that this object can contain HeapObject as elements.
2000 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2002 // Makes sure that this object can contain the specified elements.
2003 static inline void EnsureCanContainElements(
2004 Handle<JSObject> object,
2007 EnsureElementsMode mode);
2008 static inline void EnsureCanContainElements(
2009 Handle<JSObject> object,
2010 Handle<FixedArrayBase> elements,
2012 EnsureElementsMode mode);
2013 static void EnsureCanContainElements(
2014 Handle<JSObject> object,
2015 Arguments* arguments,
2018 EnsureElementsMode mode);
2020 // Would we convert a fast elements array to dictionary mode given
2021 // an access at key?
2022 bool WouldConvertToSlowElements(uint32_t index);
2024 // Computes the new capacity when expanding the elements of a JSObject.
2025 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2026 // (old_capacity + 50%) + 16
2027 return old_capacity + (old_capacity >> 1) + 16;
2030 // These methods do not perform access checks!
2031 static void UpdateAllocationSite(Handle<JSObject> object,
2032 ElementsKind to_kind);
2034 // Lookup interceptors are used for handling properties controlled by host
2036 inline bool HasNamedInterceptor();
2037 inline bool HasIndexedInterceptor();
2039 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2040 // by JSReceiver::GetKeys.
2041 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2042 Handle<JSObject> object,
2043 Handle<JSReceiver> receiver);
2044 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2045 Handle<JSObject> object,
2046 Handle<JSReceiver> receiver);
2048 // Support functions for v8 api (needed for correct interceptor behavior).
2049 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2050 Handle<JSObject> object, Handle<Name> name);
2051 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2052 Handle<JSObject> object, uint32_t index);
2053 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2054 Handle<JSObject> object, Handle<Name> name);
2056 // Get the header size for a JSObject. Used to compute the index of
2057 // internal fields as well as the number of internal fields.
2058 inline int GetHeaderSize();
2060 inline int GetInternalFieldCount();
2061 inline int GetInternalFieldOffset(int index);
2062 inline Object* GetInternalField(int index);
2063 inline void SetInternalField(int index, Object* value);
2064 inline void SetInternalField(int index, Smi* value);
2066 // Returns the number of properties on this object filtering out properties
2067 // with the specified attributes (ignoring interceptors).
2068 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2069 // Fill in details for properties into storage starting at the specified
2070 // index. Returns the number of properties added.
2071 int GetOwnPropertyNames(FixedArray* storage, int index,
2072 PropertyAttributes filter = NONE);
2074 // Returns the number of properties on this object filtering out properties
2075 // with the specified attributes (ignoring interceptors).
2076 int NumberOfOwnElements(PropertyAttributes filter);
2077 // Returns the number of enumerable elements (ignoring interceptors).
2078 int NumberOfEnumElements();
2079 // Returns the number of elements on this object filtering out elements
2080 // with the specified attributes (ignoring interceptors).
2081 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2082 // Count and fill in the enumerable elements into storage.
2083 // (storage->length() == NumberOfEnumElements()).
2084 // If storage is NULL, will count the elements without adding
2085 // them to any storage.
2086 // Returns the number of enumerable elements.
2087 int GetEnumElementKeys(FixedArray* storage);
2089 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2092 // Returns a new map with all transitions dropped from the object's current
2093 // map and the ElementsKind set.
2094 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2095 ElementsKind to_kind);
2096 static void TransitionElementsKind(Handle<JSObject> object,
2097 ElementsKind to_kind);
2099 // Always use this to migrate an object to a new map.
2100 // |expected_additional_properties| is only used for fast-to-slow transitions
2101 // and ignored otherwise.
2102 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2103 int expected_additional_properties = 0);
2105 // Convert the object to use the canonical dictionary
2106 // representation. If the object is expected to have additional properties
2107 // added this number can be indicated to have the backing store allocated to
2108 // an initial capacity for holding these properties.
2109 static void NormalizeProperties(Handle<JSObject> object,
2110 PropertyNormalizationMode mode,
2111 int expected_additional_properties,
2112 const char* reason);
2114 // Convert and update the elements backing store to be a
2115 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2116 static Handle<SeededNumberDictionary> NormalizeElements(
2117 Handle<JSObject> object);
2119 void RequireSlowElements(SeededNumberDictionary* dictionary);
2121 // Transform slow named properties to fast variants.
2122 static void MigrateSlowToFast(Handle<JSObject> object,
2123 int unused_property_fields, const char* reason);
2125 inline bool IsUnboxedDoubleField(FieldIndex index);
2127 // Access fast-case object properties at index.
2128 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2129 Representation representation,
2131 inline Object* RawFastPropertyAt(FieldIndex index);
2132 inline double RawFastDoublePropertyAt(FieldIndex index);
2134 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2135 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2136 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2137 inline void WriteToField(int descriptor, Object* value);
2139 // Access to in object properties.
2140 inline int GetInObjectPropertyOffset(int index);
2141 inline Object* InObjectPropertyAt(int index);
2142 inline Object* InObjectPropertyAtPut(int index,
2144 WriteBarrierMode mode
2145 = UPDATE_WRITE_BARRIER);
2147 // Set the object's prototype (only JSReceiver and null are allowed values).
2148 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2149 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2151 // Initializes the body after properties slot, properties slot is
2152 // initialized by set_properties. Fill the pre-allocated fields with
2153 // pre_allocated_value and the rest with filler_value.
2154 // Note: this call does not update write barrier, the caller is responsible
2155 // to ensure that |filler_value| can be collected without WB here.
2156 inline void InitializeBody(Map* map,
2157 Object* pre_allocated_value,
2158 Object* filler_value);
2160 // Check whether this object references another object
2161 bool ReferencesObject(Object* obj);
2163 // Disalow further properties to be added to the oject.
2164 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2165 Handle<JSObject> object);
2167 bool IsExtensible();
2170 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2172 // ES5 Object.freeze
2173 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2175 // Called the first time an object is observed with ES7 Object.observe.
2176 static void SetObserved(Handle<JSObject> object);
2179 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2181 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2182 Handle<JSObject> object,
2183 AllocationSiteUsageContext* site_context,
2184 DeepCopyHints hints = kNoHints);
2185 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2186 Handle<JSObject> object,
2187 AllocationSiteCreationContext* site_context);
2189 DECLARE_CAST(JSObject)
2191 // Dispatched behavior.
2192 void JSObjectShortPrint(StringStream* accumulator);
2193 DECLARE_PRINTER(JSObject)
2194 DECLARE_VERIFIER(JSObject)
2196 void PrintProperties(std::ostream& os); // NOLINT
2197 void PrintElements(std::ostream& os); // NOLINT
2199 #if defined(DEBUG) || defined(OBJECT_PRINT)
2200 void PrintTransitions(std::ostream& os); // NOLINT
2203 static void PrintElementsTransition(
2204 FILE* file, Handle<JSObject> object,
2205 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2206 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2208 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2211 // Structure for collecting spill information about JSObjects.
2212 class SpillInformation {
2216 int number_of_objects_;
2217 int number_of_objects_with_fast_properties_;
2218 int number_of_objects_with_fast_elements_;
2219 int number_of_fast_used_fields_;
2220 int number_of_fast_unused_fields_;
2221 int number_of_slow_used_properties_;
2222 int number_of_slow_unused_properties_;
2223 int number_of_fast_used_elements_;
2224 int number_of_fast_unused_elements_;
2225 int number_of_slow_used_elements_;
2226 int number_of_slow_unused_elements_;
2229 void IncrementSpillStatistics(SpillInformation* info);
2233 // If a GC was caused while constructing this object, the elements pointer
2234 // may point to a one pointer filler map. The object won't be rooted, but
2235 // our heap verification code could stumble across it.
2236 bool ElementsAreSafeToExamine();
2239 Object* SlowReverseLookup(Object* value);
2241 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2242 // Also maximal value of JSArray's length property.
2243 static const uint32_t kMaxElementCount = 0xffffffffu;
2245 // Constants for heuristics controlling conversion of fast elements
2246 // to slow elements.
2248 // Maximal gap that can be introduced by adding an element beyond
2249 // the current elements length.
2250 static const uint32_t kMaxGap = 1024;
2252 // Maximal length of fast elements array that won't be checked for
2253 // being dense enough on expansion.
2254 static const int kMaxUncheckedFastElementsLength = 5000;
2256 // Same as above but for old arrays. This limit is more strict. We
2257 // don't want to be wasteful with long lived objects.
2258 static const int kMaxUncheckedOldFastElementsLength = 500;
2260 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2261 // permissible values (see the DCHECK in heap.cc).
2262 static const int kInitialMaxFastElementArray = 100000;
2264 // This constant applies only to the initial map of "global.Object" and
2265 // not to arbitrary other JSObject maps.
2266 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2268 static const int kMaxInstanceSize = 255 * kPointerSize;
2269 // When extending the backing storage for property values, we increase
2270 // its size by more than the 1 entry necessary, so sequentially adding fields
2271 // to the same object requires fewer allocations and copies.
2272 static const int kFieldsAdded = 3;
2274 // Layout description.
2275 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2276 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2277 static const int kHeaderSize = kElementsOffset + kPointerSize;
2279 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2281 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2283 static inline int SizeOf(Map* map, HeapObject* object);
2286 Context* GetCreationContext();
2288 // Enqueue change record for Object.observe. May cause GC.
2289 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2290 Handle<JSObject> object, const char* type, Handle<Name> name,
2291 Handle<Object> old_value);
2293 // Gets the number of currently used elements.
2294 int GetFastElementsUsage();
2296 // Deletes an existing named property in a normalized object.
2297 static void DeleteNormalizedProperty(Handle<JSObject> object,
2298 Handle<Name> name, int entry);
2300 static bool AllCanRead(LookupIterator* it);
2301 static bool AllCanWrite(LookupIterator* it);
2304 friend class JSReceiver;
2305 friend class Object;
2307 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2308 static void MigrateFastToSlow(Handle<JSObject> object,
2309 Handle<Map> new_map,
2310 int expected_additional_properties);
2312 // Used from Object::GetProperty().
2313 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2314 LookupIterator* it);
2316 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2317 LookupIterator* it, Handle<Object> value);
2319 // Add a property to a slow-case object.
2320 static void AddSlowProperty(Handle<JSObject> object,
2322 Handle<Object> value,
2323 PropertyAttributes attributes);
2325 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2326 LookupIterator* it);
2328 bool ReferencesObjectFromElements(FixedArray* elements,
2332 // Return the hash table backing store or the inline stored identity hash,
2333 // whatever is found.
2334 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2336 // Return the hash table backing store for hidden properties. If there is no
2337 // backing store, allocate one.
2338 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2339 Handle<JSObject> object);
2341 // Set the hidden property backing store to either a hash table or
2342 // the inline-stored identity hash.
2343 static Handle<Object> SetHiddenPropertiesHashTable(
2344 Handle<JSObject> object,
2345 Handle<Object> value);
2347 MUST_USE_RESULT Object* GetIdentityHash();
2349 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2351 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2352 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2354 // Helper for fast versions of preventExtensions, seal, and freeze.
2355 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2356 template <PropertyAttributes attrs>
2357 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2358 Handle<JSObject> object);
2360 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2364 // Common superclass for FixedArrays that allow implementations to share
2365 // common accessors and some code paths.
2366 class FixedArrayBase: public HeapObject {
2368 // [length]: length of the array.
2369 inline int length() const;
2370 inline void set_length(int value);
2372 // Get and set the length using acquire loads and release stores.
2373 inline int synchronized_length() const;
2374 inline void synchronized_set_length(int value);
2376 DECLARE_CAST(FixedArrayBase)
2378 // Layout description.
2379 // Length is smi tagged when it is stored.
2380 static const int kLengthOffset = HeapObject::kHeaderSize;
2381 static const int kHeaderSize = kLengthOffset + kPointerSize;
2385 class FixedDoubleArray;
2386 class IncrementalMarking;
2389 // FixedArray describes fixed-sized arrays with element type Object*.
2390 class FixedArray: public FixedArrayBase {
2392 // Setter and getter for elements.
2393 inline Object* get(int index) const;
2394 void SetValue(uint32_t index, Object* value);
2395 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2396 // Setter that uses write barrier.
2397 inline void set(int index, Object* value);
2398 inline bool is_the_hole(int index);
2400 // Setter that doesn't need write barrier.
2401 inline void set(int index, Smi* value);
2402 // Setter with explicit barrier mode.
2403 inline void set(int index, Object* value, WriteBarrierMode mode);
2405 // Setters for frequently used oddballs located in old space.
2406 inline void set_undefined(int index);
2407 inline void set_null(int index);
2408 inline void set_the_hole(int index);
2410 inline Object** GetFirstElementAddress();
2411 inline bool ContainsOnlySmisOrHoles();
2413 // Gives access to raw memory which stores the array's data.
2414 inline Object** data_start();
2416 inline void FillWithHoles(int from, int to);
2418 // Shrink length and insert filler objects.
2419 void Shrink(int length);
2421 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2423 // Add the elements of a JSArray to this FixedArray.
2424 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2425 Handle<FixedArray> content, Handle<JSObject> array,
2426 KeyFilter filter = ALL_KEYS);
2428 // Computes the union of keys and return the result.
2429 // Used for implementing "for (n in object) { }"
2430 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2431 Handle<FixedArray> first,
2432 Handle<FixedArray> second);
2434 // Copy a sub array from the receiver to dest.
2435 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2437 // Garbage collection support.
2438 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2440 // Code Generation support.
2441 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2443 // Garbage collection support.
2444 inline Object** RawFieldOfElementAt(int index);
2446 DECLARE_CAST(FixedArray)
2448 // Maximal allowed size, in bytes, of a single FixedArray.
2449 // Prevents overflowing size computations, as well as extreme memory
2451 static const int kMaxSize = 128 * MB * kPointerSize;
2452 // Maximally allowed length of a FixedArray.
2453 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2455 // Dispatched behavior.
2456 DECLARE_PRINTER(FixedArray)
2457 DECLARE_VERIFIER(FixedArray)
2459 // Checks if two FixedArrays have identical contents.
2460 bool IsEqualTo(FixedArray* other);
2463 // Swap two elements in a pair of arrays. If this array and the
2464 // numbers array are the same object, the elements are only swapped
2466 void SwapPairs(FixedArray* numbers, int i, int j);
2468 // Sort prefix of this array and the numbers array as pairs wrt. the
2469 // numbers. If the numbers array and the this array are the same
2470 // object, the prefix of this array is sorted.
2471 void SortPairs(FixedArray* numbers, uint32_t len);
2473 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2475 static inline int SizeOf(Map* map, HeapObject* object);
2479 // Set operation on FixedArray without using write barriers. Can
2480 // only be used for storing old space objects or smis.
2481 static inline void NoWriteBarrierSet(FixedArray* array,
2485 // Set operation on FixedArray without incremental write barrier. Can
2486 // only be used if the object is guaranteed to be white (whiteness witness
2488 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2493 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2495 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2499 // FixedDoubleArray describes fixed-sized arrays with element type double.
2500 class FixedDoubleArray: public FixedArrayBase {
2502 // Setter and getter for elements.
2503 inline double get_scalar(int index);
2504 inline uint64_t get_representation(int index);
2505 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2506 // This accessor has to get a Number as |value|.
2507 void SetValue(uint32_t index, Object* value);
2508 inline void set(int index, double value);
2509 inline void set_the_hole(int index);
2511 // Checking for the hole.
2512 inline bool is_the_hole(int index);
2514 // Garbage collection support.
2515 inline static int SizeFor(int length) {
2516 return kHeaderSize + length * kDoubleSize;
2519 // Gives access to raw memory which stores the array's data.
2520 inline double* data_start();
2522 inline void FillWithHoles(int from, int to);
2524 // Code Generation support.
2525 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2527 DECLARE_CAST(FixedDoubleArray)
2529 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2530 // Prevents overflowing size computations, as well as extreme memory
2532 static const int kMaxSize = 512 * MB;
2533 // Maximally allowed length of a FixedArray.
2534 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2536 // Dispatched behavior.
2537 DECLARE_PRINTER(FixedDoubleArray)
2538 DECLARE_VERIFIER(FixedDoubleArray)
2541 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2545 class WeakFixedArray : public FixedArray {
2547 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2548 // This function does not check if the value exists already, callers must
2549 // ensure this themselves if necessary.
2550 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2551 Handle<HeapObject> value,
2552 int* assigned_index = NULL);
2554 // Returns true if an entry was found and removed.
2555 bool Remove(Handle<HeapObject> value);
2557 class NullCallback {
2559 static void Callback(Object* value, int old_index, int new_index) {}
2562 template <class CompactionCallback>
2565 inline Object* Get(int index) const;
2566 inline void Clear(int index);
2567 inline int Length() const;
2569 inline bool IsEmptySlot(int index) const;
2570 static Object* Empty() { return Smi::FromInt(0); }
2574 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2575 void Reset(Object* maybe_array);
2582 WeakFixedArray* list_;
2584 int last_used_index_;
2585 DisallowHeapAllocation no_gc_;
2587 DISALLOW_COPY_AND_ASSIGN(Iterator);
2590 DECLARE_CAST(WeakFixedArray)
2593 static const int kLastUsedIndexIndex = 0;
2594 static const int kFirstIndex = 1;
2596 static Handle<WeakFixedArray> Allocate(
2597 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2599 static void Set(Handle<WeakFixedArray> array, int index,
2600 Handle<HeapObject> value);
2601 inline void clear(int index);
2603 inline int last_used_index() const;
2604 inline void set_last_used_index(int index);
2606 // Disallow inherited setters.
2607 void set(int index, Smi* value);
2608 void set(int index, Object* value);
2609 void set(int index, Object* value, WriteBarrierMode mode);
2610 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2614 // Generic array grows dynamically with O(1) amortized insertion.
2615 class ArrayList : public FixedArray {
2619 // Use this if GC can delete elements from the array.
2620 kReloadLengthAfterAllocation,
2622 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2623 AddMode mode = kNone);
2624 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2625 Handle<Object> obj2, AddMode = kNone);
2626 inline int Length();
2627 inline void SetLength(int length);
2628 inline Object* Get(int index);
2629 inline Object** Slot(int index);
2630 inline void Set(int index, Object* obj);
2631 inline void Clear(int index, Object* undefined);
2632 DECLARE_CAST(ArrayList)
2635 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2636 static const int kLengthIndex = 0;
2637 static const int kFirstIndex = 1;
2638 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2642 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2643 // The format of the these objects is:
2644 // [0]: Number of descriptors
2645 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2646 // [0]: pointer to fixed array with enum cache
2647 // [1]: either Smi(0) or pointer to fixed array with indices
2649 // [2 + number of descriptors * kDescriptorSize]: start of slack
2650 class DescriptorArray: public FixedArray {
2652 // Returns true for both shared empty_descriptor_array and for smis, which the
2653 // map uses to encode additional bit fields when the descriptor array is not
2655 inline bool IsEmpty();
2657 // Returns the number of descriptors in the array.
2658 inline int number_of_descriptors();
2660 inline int number_of_descriptors_storage();
2662 inline int NumberOfSlackDescriptors();
2664 inline void SetNumberOfDescriptors(int number_of_descriptors);
2665 inline int number_of_entries();
2667 inline bool HasEnumCache();
2669 inline void CopyEnumCacheFrom(DescriptorArray* array);
2671 inline FixedArray* GetEnumCache();
2673 inline bool HasEnumIndicesCache();
2675 inline FixedArray* GetEnumIndicesCache();
2677 inline Object** GetEnumCacheSlot();
2679 void ClearEnumCache();
2681 // Initialize or change the enum cache,
2682 // using the supplied storage for the small "bridge".
2683 void SetEnumCache(FixedArray* bridge_storage,
2684 FixedArray* new_cache,
2685 Object* new_index_cache);
2687 bool CanHoldValue(int descriptor, Object* value);
2689 // Accessors for fetching instance descriptor at descriptor number.
2690 inline Name* GetKey(int descriptor_number);
2691 inline Object** GetKeySlot(int descriptor_number);
2692 inline Object* GetValue(int descriptor_number);
2693 inline void SetValue(int descriptor_number, Object* value);
2694 inline Object** GetValueSlot(int descriptor_number);
2695 static inline int GetValueOffset(int descriptor_number);
2696 inline Object** GetDescriptorStartSlot(int descriptor_number);
2697 inline Object** GetDescriptorEndSlot(int descriptor_number);
2698 inline PropertyDetails GetDetails(int descriptor_number);
2699 inline PropertyType GetType(int descriptor_number);
2700 inline int GetFieldIndex(int descriptor_number);
2701 inline HeapType* GetFieldType(int descriptor_number);
2702 inline Object* GetConstant(int descriptor_number);
2703 inline Object* GetCallbacksObject(int descriptor_number);
2704 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2706 inline Name* GetSortedKey(int descriptor_number);
2707 inline int GetSortedKeyIndex(int descriptor_number);
2708 inline void SetSortedKey(int pointer, int descriptor_number);
2709 inline void SetRepresentation(int descriptor_number,
2710 Representation representation);
2712 // Accessor for complete descriptor.
2713 inline void Get(int descriptor_number, Descriptor* desc);
2714 inline void Set(int descriptor_number, Descriptor* desc);
2715 void Replace(int descriptor_number, Descriptor* descriptor);
2717 // Append automatically sets the enumeration index. This should only be used
2718 // to add descriptors in bulk at the end, followed by sorting the descriptor
2720 inline void Append(Descriptor* desc);
2722 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2723 int enumeration_index,
2726 static Handle<DescriptorArray> CopyUpToAddAttributes(
2727 Handle<DescriptorArray> desc,
2728 int enumeration_index,
2729 PropertyAttributes attributes,
2732 // Sort the instance descriptors by the hash codes of their keys.
2735 // Search the instance descriptors for given name.
2736 INLINE(int Search(Name* name, int number_of_own_descriptors));
2738 // As the above, but uses DescriptorLookupCache and updates it when
2740 INLINE(int SearchWithCache(Name* name, Map* map));
2742 // Allocates a DescriptorArray, but returns the singleton
2743 // empty descriptor array object if number_of_descriptors is 0.
2744 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2745 int number_of_descriptors,
2748 DECLARE_CAST(DescriptorArray)
2750 // Constant for denoting key was not found.
2751 static const int kNotFound = -1;
2753 static const int kDescriptorLengthIndex = 0;
2754 static const int kEnumCacheIndex = 1;
2755 static const int kFirstIndex = 2;
2757 // The length of the "bridge" to the enum cache.
2758 static const int kEnumCacheBridgeLength = 2;
2759 static const int kEnumCacheBridgeCacheIndex = 0;
2760 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2762 // Layout description.
2763 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2764 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2765 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2767 // Layout description for the bridge array.
2768 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2770 // Layout of descriptor.
2771 static const int kDescriptorKey = 0;
2772 static const int kDescriptorDetails = 1;
2773 static const int kDescriptorValue = 2;
2774 static const int kDescriptorSize = 3;
2776 #if defined(DEBUG) || defined(OBJECT_PRINT)
2777 // For our gdb macros, we should perhaps change these in the future.
2780 // Print all the descriptors.
2781 void PrintDescriptors(std::ostream& os); // NOLINT
2785 // Is the descriptor array sorted and without duplicates?
2786 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2788 // Is the descriptor array consistent with the back pointers in targets?
2789 bool IsConsistentWithBackPointers(Map* current_map);
2791 // Are two DescriptorArrays equal?
2792 bool IsEqualTo(DescriptorArray* other);
2795 // Returns the fixed array length required to hold number_of_descriptors
2797 static int LengthFor(int number_of_descriptors) {
2798 return ToKeyIndex(number_of_descriptors);
2802 // WhitenessWitness is used to prove that a descriptor array is white
2803 // (unmarked), so incremental write barriers can be skipped because the
2804 // marking invariant cannot be broken and slots pointing into evacuation
2805 // candidates will be discovered when the object is scanned. A witness is
2806 // always stack-allocated right after creating an array. By allocating a
2807 // witness, incremental marking is globally disabled. The witness is then
2808 // passed along wherever needed to statically prove that the array is known to
2810 class WhitenessWitness {
2812 inline explicit WhitenessWitness(DescriptorArray* array);
2813 inline ~WhitenessWitness();
2816 IncrementalMarking* marking_;
2819 // An entry in a DescriptorArray, represented as an (array, index) pair.
2822 inline explicit Entry(DescriptorArray* descs, int index) :
2823 descs_(descs), index_(index) { }
2825 inline PropertyType type();
2826 inline Object* GetCallbackObject();
2829 DescriptorArray* descs_;
2833 // Conversion from descriptor number to array indices.
2834 static int ToKeyIndex(int descriptor_number) {
2835 return kFirstIndex +
2836 (descriptor_number * kDescriptorSize) +
2840 static int ToDetailsIndex(int descriptor_number) {
2841 return kFirstIndex +
2842 (descriptor_number * kDescriptorSize) +
2846 static int ToValueIndex(int descriptor_number) {
2847 return kFirstIndex +
2848 (descriptor_number * kDescriptorSize) +
2852 // Transfer a complete descriptor from the src descriptor array to this
2853 // descriptor array.
2854 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2856 inline void Set(int descriptor_number,
2858 const WhitenessWitness&);
2860 // Swap first and second descriptor.
2861 inline void SwapSortedKeys(int first, int second);
2863 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2867 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2869 template <SearchMode search_mode, typename T>
2870 inline int Search(T* array, Name* name, int valid_entries = 0,
2871 int* out_insertion_index = NULL);
2874 // HashTable is a subclass of FixedArray that implements a hash table
2875 // that uses open addressing and quadratic probing.
2877 // In order for the quadratic probing to work, elements that have not
2878 // yet been used and elements that have been deleted are
2879 // distinguished. Probing continues when deleted elements are
2880 // encountered and stops when unused elements are encountered.
2882 // - Elements with key == undefined have not been used yet.
2883 // - Elements with key == the_hole have been deleted.
2885 // The hash table class is parameterized with a Shape and a Key.
2886 // Shape must be a class with the following interface:
2887 // class ExampleShape {
2889 // // Tells whether key matches other.
2890 // static bool IsMatch(Key key, Object* other);
2891 // // Returns the hash value for key.
2892 // static uint32_t Hash(Key key);
2893 // // Returns the hash value for object.
2894 // static uint32_t HashForObject(Key key, Object* object);
2895 // // Convert key to an object.
2896 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2897 // // The prefix size indicates number of elements in the beginning
2898 // // of the backing storage.
2899 // static const int kPrefixSize = ..;
2900 // // The Element size indicates number of elements per entry.
2901 // static const int kEntrySize = ..;
2903 // The prefix size indicates an amount of memory in the
2904 // beginning of the backing storage that can be used for non-element
2905 // information by subclasses.
2907 template<typename Key>
2910 static const bool UsesSeed = false;
2911 static uint32_t Hash(Key key) { return 0; }
2912 static uint32_t SeededHash(Key key, uint32_t seed) {
2916 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2917 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2919 return HashForObject(key, object);
2924 class HashTableBase : public FixedArray {
2926 // Returns the number of elements in the hash table.
2927 inline int NumberOfElements();
2929 // Returns the number of deleted elements in the hash table.
2930 inline int NumberOfDeletedElements();
2932 // Returns the capacity of the hash table.
2933 inline int Capacity();
2935 // ElementAdded should be called whenever an element is added to a
2937 inline void ElementAdded();
2939 // ElementRemoved should be called whenever an element is removed from
2941 inline void ElementRemoved();
2942 inline void ElementsRemoved(int n);
2944 // Computes the required capacity for a table holding the given
2945 // number of elements. May be more than HashTable::kMaxCapacity.
2946 static inline int ComputeCapacity(int at_least_space_for);
2948 // Tells whether k is a real key. The hole and undefined are not allowed
2949 // as keys and can be used to indicate missing or deleted elements.
2950 inline bool IsKey(Object* k);
2952 // Compute the probe offset (quadratic probing).
2953 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2954 return (n + n * n) >> 1;
2957 static const int kNumberOfElementsIndex = 0;
2958 static const int kNumberOfDeletedElementsIndex = 1;
2959 static const int kCapacityIndex = 2;
2960 static const int kPrefixStartIndex = 3;
2962 // Constant used for denoting a absent entry.
2963 static const int kNotFound = -1;
2966 // Update the number of elements in the hash table.
2967 inline void SetNumberOfElements(int nof);
2969 // Update the number of deleted elements in the hash table.
2970 inline void SetNumberOfDeletedElements(int nod);
2972 // Returns probe entry.
2973 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2974 DCHECK(base::bits::IsPowerOfTwo32(size));
2975 return (hash + GetProbeOffset(number)) & (size - 1);
2978 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2979 return hash & (size - 1);
2982 inline static uint32_t NextProbe(
2983 uint32_t last, uint32_t number, uint32_t size) {
2984 return (last + number) & (size - 1);
2989 template <typename Derived, typename Shape, typename Key>
2990 class HashTable : public HashTableBase {
2993 inline uint32_t Hash(Key key) {
2994 if (Shape::UsesSeed) {
2995 return Shape::SeededHash(key, GetHeap()->HashSeed());
2997 return Shape::Hash(key);
3001 inline uint32_t HashForObject(Key key, Object* object) {
3002 if (Shape::UsesSeed) {
3003 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3005 return Shape::HashForObject(key, object);
3009 // Returns a new HashTable object.
3010 MUST_USE_RESULT static Handle<Derived> New(
3011 Isolate* isolate, int at_least_space_for,
3012 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3013 PretenureFlag pretenure = NOT_TENURED);
3015 DECLARE_CAST(HashTable)
3017 // Garbage collection support.
3018 void IteratePrefix(ObjectVisitor* visitor);
3019 void IterateElements(ObjectVisitor* visitor);
3021 // Find entry for key otherwise return kNotFound.
3022 inline int FindEntry(Key key);
3023 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3024 int FindEntry(Isolate* isolate, Key key);
3026 // Rehashes the table in-place.
3027 void Rehash(Key key);
3029 // Returns the key at entry.
3030 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3032 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3033 static const int kEntrySize = Shape::kEntrySize;
3034 static const int kElementsStartOffset =
3035 kHeaderSize + kElementsStartIndex * kPointerSize;
3036 static const int kCapacityOffset =
3037 kHeaderSize + kCapacityIndex * kPointerSize;
3039 // Returns the index for an entry (of the key)
3040 static inline int EntryToIndex(int entry) {
3041 return (entry * kEntrySize) + kElementsStartIndex;
3045 friend class ObjectHashTable;
3047 // Find the entry at which to insert element with the given key that
3048 // has the given hash value.
3049 uint32_t FindInsertionEntry(uint32_t hash);
3051 // Attempt to shrink hash table after removal of key.
3052 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3054 // Ensure enough space for n additional elements.
3055 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3056 Handle<Derived> table,
3059 PretenureFlag pretenure = NOT_TENURED);
3061 // Sets the capacity of the hash table.
3062 void SetCapacity(int capacity) {
3063 // To scale a computed hash code to fit within the hash table, we
3064 // use bit-wise AND with a mask, so the capacity must be positive
3066 DCHECK(capacity > 0);
3067 DCHECK(capacity <= kMaxCapacity);
3068 set(kCapacityIndex, Smi::FromInt(capacity));
3071 // Maximal capacity of HashTable. Based on maximal length of underlying
3072 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3074 static const int kMaxCapacity =
3075 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3078 // Returns _expected_ if one of entries given by the first _probe_ probes is
3079 // equal to _expected_. Otherwise, returns the entry given by the probe
3081 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3083 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3085 // Rehashes this hash-table into the new table.
3086 void Rehash(Handle<Derived> new_table, Key key);
3090 // HashTableKey is an abstract superclass for virtual key behavior.
3091 class HashTableKey {
3093 // Returns whether the other object matches this key.
3094 virtual bool IsMatch(Object* other) = 0;
3095 // Returns the hash value for this key.
3096 virtual uint32_t Hash() = 0;
3097 // Returns the hash value for object.
3098 virtual uint32_t HashForObject(Object* key) = 0;
3099 // Returns the key object for storing into the hash table.
3100 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3102 virtual ~HashTableKey() {}
3106 class StringTableShape : public BaseShape<HashTableKey*> {
3108 static inline bool IsMatch(HashTableKey* key, Object* value) {
3109 return key->IsMatch(value);
3112 static inline uint32_t Hash(HashTableKey* key) {
3116 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3117 return key->HashForObject(object);
3120 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3122 static const int kPrefixSize = 0;
3123 static const int kEntrySize = 1;
3126 class SeqOneByteString;
3130 // No special elements in the prefix and the element size is 1
3131 // because only the string itself (the key) needs to be stored.
3132 class StringTable: public HashTable<StringTable,
3136 // Find string in the string table. If it is not there yet, it is
3137 // added. The return value is the string found.
3138 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3139 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3140 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3142 // Tries to internalize given string and returns string handle on success
3143 // or an empty handle otherwise.
3144 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3146 Handle<String> string);
3148 // Looks up a string that is equal to the given string and returns
3149 // string handle if it is found, or an empty handle otherwise.
3150 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3152 Handle<String> str);
3153 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3158 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3160 DECLARE_CAST(StringTable)
3163 template <bool seq_one_byte>
3164 friend class JsonParser;
3166 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3170 template <typename Derived, typename Shape, typename Key>
3171 class Dictionary: public HashTable<Derived, Shape, Key> {
3172 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3175 // Returns the value at entry.
3176 Object* ValueAt(int entry) {
3177 return this->get(Derived::EntryToIndex(entry) + 1);
3180 // Set the value for entry.
3181 void ValueAtPut(int entry, Object* value) {
3182 this->set(Derived::EntryToIndex(entry) + 1, value);
3185 // Returns the property details for the property at entry.
3186 PropertyDetails DetailsAt(int entry) {
3187 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3190 // Set the details for entry.
3191 void DetailsAtPut(int entry, PropertyDetails value) {
3192 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3195 // Returns true if property at given entry is deleted.
3196 bool IsDeleted(int entry) {
3197 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3200 // Delete a property from the dictionary.
3201 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3203 // Attempt to shrink the dictionary after deletion of key.
3204 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3205 Handle<Derived> dictionary,
3207 return DerivedHashTable::Shrink(dictionary, key);
3211 // TODO(dcarney): templatize or move to SeededNumberDictionary
3212 void CopyValuesTo(FixedArray* elements);
3214 // Returns the number of elements in the dictionary filtering out properties
3215 // with the specified attributes.
3216 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3218 // Returns the number of enumerable elements in the dictionary.
3219 int NumberOfEnumElements() {
3220 return NumberOfElementsFilterAttributes(
3221 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3224 // Returns true if the dictionary contains any elements that are non-writable,
3225 // non-configurable, non-enumerable, or have getters/setters.
3226 bool HasComplexElements();
3228 enum SortMode { UNSORTED, SORTED };
3230 // Fill in details for properties into storage.
3231 // Returns the number of properties added.
3232 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3233 SortMode sort_mode);
3235 // Copies enumerable keys to preallocated fixed array.
3236 void CopyEnumKeysTo(FixedArray* storage);
3238 // Accessors for next enumeration index.
3239 void SetNextEnumerationIndex(int index) {
3241 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3244 int NextEnumerationIndex() {
3245 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3248 // Creates a new dictionary.
3249 MUST_USE_RESULT static Handle<Derived> New(
3251 int at_least_space_for,
3252 PretenureFlag pretenure = NOT_TENURED);
3254 // Ensure enough space for n additional elements.
3255 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3258 void Print(std::ostream& os); // NOLINT
3260 // Returns the key (slow).
3261 Object* SlowReverseLookup(Object* value);
3263 // Sets the entry to (key, value) pair.
3264 inline void SetEntry(int entry,
3266 Handle<Object> value);
3267 inline void SetEntry(int entry,
3269 Handle<Object> value,
3270 PropertyDetails details);
3272 MUST_USE_RESULT static Handle<Derived> Add(
3273 Handle<Derived> dictionary,
3275 Handle<Object> value,
3276 PropertyDetails details);
3278 // Returns iteration indices array for the |dictionary|.
3279 // Values are direct indices in the |HashTable| array.
3280 static Handle<FixedArray> BuildIterationIndicesArray(
3281 Handle<Derived> dictionary);
3284 // Generic at put operation.
3285 MUST_USE_RESULT static Handle<Derived> AtPut(
3286 Handle<Derived> dictionary,
3288 Handle<Object> value);
3290 // Add entry to dictionary.
3291 static void AddEntry(
3292 Handle<Derived> dictionary,
3294 Handle<Object> value,
3295 PropertyDetails details,
3298 // Generate new enumeration indices to avoid enumeration index overflow.
3299 // Returns iteration indices array for the |dictionary|.
3300 static Handle<FixedArray> GenerateNewEnumerationIndices(
3301 Handle<Derived> dictionary);
3302 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3303 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3307 template <typename Derived, typename Shape>
3308 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3309 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3312 // Find entry for key, otherwise return kNotFound. Optimized version of
3313 // HashTable::FindEntry.
3314 int FindEntry(Handle<Name> key);
3318 template <typename Key>
3319 class BaseDictionaryShape : public BaseShape<Key> {
3321 template <typename Dictionary>
3322 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3323 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3324 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3325 return PropertyDetails(
3326 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3329 template <typename Dictionary>
3330 static inline void DetailsAtPut(Dictionary* dict, int entry,
3331 PropertyDetails value) {
3332 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3333 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3336 template <typename Dictionary>
3337 static bool IsDeleted(Dictionary* dict, int entry) {
3341 template <typename Dictionary>
3342 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3343 Handle<Object> value, PropertyDetails details);
3347 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3349 static inline bool IsMatch(Handle<Name> key, Object* other);
3350 static inline uint32_t Hash(Handle<Name> key);
3351 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3352 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3353 static const int kPrefixSize = 2;
3354 static const int kEntrySize = 3;
3355 static const bool kIsEnumerable = true;
3359 class NameDictionary
3360 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3361 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3365 DECLARE_CAST(NameDictionary)
3367 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3368 Handle<NameDictionary> dictionary);
3372 class GlobalDictionaryShape : public NameDictionaryShape {
3374 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3376 template <typename Dictionary>
3377 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3379 template <typename Dictionary>
3380 static inline void DetailsAtPut(Dictionary* dict, int entry,
3381 PropertyDetails value);
3383 template <typename Dictionary>
3384 static bool IsDeleted(Dictionary* dict, int entry);
3386 template <typename Dictionary>
3387 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3388 Handle<Object> value, PropertyDetails details);
3392 class GlobalDictionary
3393 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3395 DECLARE_CAST(GlobalDictionary)
3399 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3401 static inline bool IsMatch(uint32_t key, Object* other);
3402 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3403 static const int kEntrySize = 3;
3404 static const bool kIsEnumerable = false;
3408 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3410 static const bool UsesSeed = true;
3411 static const int kPrefixSize = 2;
3413 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3414 static inline uint32_t SeededHashForObject(uint32_t key,
3420 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3422 static const int kPrefixSize = 0;
3424 static inline uint32_t Hash(uint32_t key);
3425 static inline uint32_t HashForObject(uint32_t key, Object* object);
3429 class SeededNumberDictionary
3430 : public Dictionary<SeededNumberDictionary,
3431 SeededNumberDictionaryShape,
3434 DECLARE_CAST(SeededNumberDictionary)
3436 // Type specific at put (default NONE attributes is used when adding).
3437 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3438 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3439 Handle<Object> value, bool used_as_prototype);
3440 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3441 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3442 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3444 // Set an existing entry or add a new one if needed.
3445 // Return the updated dictionary.
3446 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3447 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3448 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3450 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3452 // If slow elements are required we will never go back to fast-case
3453 // for the elements kept in this dictionary. We require slow
3454 // elements if an element has been added at an index larger than
3455 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3456 // when defining a getter or setter with a number key.
3457 inline bool requires_slow_elements();
3458 inline void set_requires_slow_elements();
3460 // Get the value of the max number key that has been added to this
3461 // dictionary. max_number_key can only be called if
3462 // requires_slow_elements returns false.
3463 inline uint32_t max_number_key();
3466 static const int kRequiresSlowElementsMask = 1;
3467 static const int kRequiresSlowElementsTagSize = 1;
3468 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3472 class UnseededNumberDictionary
3473 : public Dictionary<UnseededNumberDictionary,
3474 UnseededNumberDictionaryShape,
3477 DECLARE_CAST(UnseededNumberDictionary)
3479 // Type specific at put (default NONE attributes is used when adding).
3480 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3481 Handle<UnseededNumberDictionary> dictionary,
3483 Handle<Object> value);
3484 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3485 Handle<UnseededNumberDictionary> dictionary,
3487 Handle<Object> value);
3489 // Set an existing entry or add a new one if needed.
3490 // Return the updated dictionary.
3491 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3492 Handle<UnseededNumberDictionary> dictionary,
3494 Handle<Object> value);
3498 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3500 static inline bool IsMatch(Handle<Object> key, Object* other);
3501 static inline uint32_t Hash(Handle<Object> key);
3502 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3503 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3504 static const int kPrefixSize = 0;
3505 static const int kEntrySize = 2;
3509 // ObjectHashTable maps keys that are arbitrary objects to object values by
3510 // using the identity hash of the key for hashing purposes.
3511 class ObjectHashTable: public HashTable<ObjectHashTable,
3512 ObjectHashTableShape,
3515 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3517 DECLARE_CAST(ObjectHashTable)
3519 // Attempt to shrink hash table after removal of key.
3520 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3521 Handle<ObjectHashTable> table,
3522 Handle<Object> key);
3524 // Looks up the value associated with the given key. The hole value is
3525 // returned in case the key is not present.
3526 Object* Lookup(Handle<Object> key);
3527 Object* Lookup(Handle<Object> key, int32_t hash);
3528 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3530 // Adds (or overwrites) the value associated with the given key.
3531 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3533 Handle<Object> value);
3534 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3535 Handle<Object> key, Handle<Object> value,
3538 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3539 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3542 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3543 Handle<Object> key, bool* was_present,
3547 friend class MarkCompactCollector;
3549 void AddEntry(int entry, Object* key, Object* value);
3550 void RemoveEntry(int entry);
3552 // Returns the index to the value of an entry.
3553 static inline int EntryToValueIndex(int entry) {
3554 return EntryToIndex(entry) + 1;
3559 // OrderedHashTable is a HashTable with Object keys that preserves
3560 // insertion order. There are Map and Set interfaces (OrderedHashMap
3561 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3563 // Only Object* keys are supported, with Object::SameValueZero() used as the
3564 // equality operator and Object::GetHash() for the hash function.
3566 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3567 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3568 // Originally attributed to Tyler Close.
3571 // [0]: bucket count
3572 // [1]: element count
3573 // [2]: deleted element count
3574 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3575 // offset into the data table (see below) where the
3576 // first item in this bucket is stored.
3577 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3578 // Capacity() * kEntrySize, where the first entrysize
3579 // items are handled by the derived class and the
3580 // item at kChainOffset is another entry into the
3581 // data table indicating the next entry in this hash
3584 // When we transition the table to a new version we obsolete it and reuse parts
3585 // of the memory to store information how to transition an iterator to the new
3588 // Memory layout for obsolete table:
3589 // [0]: bucket count
3590 // [1]: Next newer table
3591 // [2]: Number of removed holes or -1 when the table was cleared.
3592 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3593 // [3 + NumberOfRemovedHoles()..length]: Not used
3595 template<class Derived, class Iterator, int entrysize>
3596 class OrderedHashTable: public FixedArray {
3598 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3599 static Handle<Derived> Allocate(
3600 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3602 // Returns an OrderedHashTable (possibly |table|) with enough space
3603 // to add at least one new element.
3604 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3606 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3608 static Handle<Derived> Shrink(Handle<Derived> table);
3610 // Returns a new empty OrderedHashTable and records the clearing so that
3611 // exisiting iterators can be updated.
3612 static Handle<Derived> Clear(Handle<Derived> table);
3614 int NumberOfElements() {
3615 return Smi::cast(get(kNumberOfElementsIndex))->value();
3618 int NumberOfDeletedElements() {
3619 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3622 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3624 int NumberOfBuckets() {
3625 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3628 // Returns an index into |this| for the given entry.
3629 int EntryToIndex(int entry) {
3630 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3633 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3636 return !get(kNextTableIndex)->IsSmi();
3639 // The next newer table. This is only valid if the table is obsolete.
3640 Derived* NextTable() {
3641 return Derived::cast(get(kNextTableIndex));
3644 // When the table is obsolete we store the indexes of the removed holes.
3645 int RemovedIndexAt(int index) {
3646 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3649 static const int kNotFound = -1;
3650 static const int kMinCapacity = 4;
3652 static const int kNumberOfBucketsIndex = 0;
3653 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3654 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3655 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3656 static const int kNextTableIndex = kNumberOfElementsIndex;
3658 static const int kNumberOfBucketsOffset =
3659 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3660 static const int kNumberOfElementsOffset =
3661 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3662 static const int kNumberOfDeletedElementsOffset =
3663 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3664 static const int kHashTableStartOffset =
3665 kHeaderSize + kHashTableStartIndex * kPointerSize;
3666 static const int kNextTableOffset =
3667 kHeaderSize + kNextTableIndex * kPointerSize;
3669 static const int kEntrySize = entrysize + 1;
3670 static const int kChainOffset = entrysize;
3672 static const int kLoadFactor = 2;
3674 // NumberOfDeletedElements is set to kClearedTableSentinel when
3675 // the table is cleared, which allows iterator transitions to
3676 // optimize that case.
3677 static const int kClearedTableSentinel = -1;
3680 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3682 void SetNumberOfBuckets(int num) {
3683 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3686 void SetNumberOfElements(int num) {
3687 set(kNumberOfElementsIndex, Smi::FromInt(num));
3690 void SetNumberOfDeletedElements(int num) {
3691 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3695 return NumberOfBuckets() * kLoadFactor;
3698 void SetNextTable(Derived* next_table) {
3699 set(kNextTableIndex, next_table);
3702 void SetRemovedIndexAt(int index, int removed_index) {
3703 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3706 static const int kRemovedHolesIndex = kHashTableStartIndex;
3708 static const int kMaxCapacity =
3709 (FixedArray::kMaxLength - kHashTableStartIndex)
3710 / (1 + (kEntrySize * kLoadFactor));
3714 class JSSetIterator;
3717 class OrderedHashSet: public OrderedHashTable<
3718 OrderedHashSet, JSSetIterator, 1> {
3720 DECLARE_CAST(OrderedHashSet)
3724 class JSMapIterator;
3727 class OrderedHashMap
3728 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3730 DECLARE_CAST(OrderedHashMap)
3732 inline Object* ValueAt(int entry);
3734 static const int kValueOffset = 1;
3738 template <int entrysize>
3739 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3741 static inline bool IsMatch(Handle<Object> key, Object* other);
3742 static inline uint32_t Hash(Handle<Object> key);
3743 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3744 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3745 static const int kPrefixSize = 0;
3746 static const int kEntrySize = entrysize;
3750 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3751 // values. The table wraps the keys in weak cells and store values directly.
3752 // Thus it references keys weakly and values strongly.
3753 class WeakHashTable: public HashTable<WeakHashTable,
3754 WeakHashTableShape<2>,
3757 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3759 DECLARE_CAST(WeakHashTable)
3761 // Looks up the value associated with the given key. The hole value is
3762 // returned in case the key is not present.
3763 Object* Lookup(Handle<HeapObject> key);
3765 // Adds (or overwrites) the value associated with the given key. Mapping a
3766 // key to the hole value causes removal of the whole entry.
3767 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3768 Handle<HeapObject> key,
3769 Handle<HeapObject> value);
3771 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3774 friend class MarkCompactCollector;
3776 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3778 // Returns the index to the value of an entry.
3779 static inline int EntryToValueIndex(int entry) {
3780 return EntryToIndex(entry) + 1;
3785 // ScopeInfo represents information about different scopes of a source
3786 // program and the allocation of the scope's variables. Scope information
3787 // is stored in a compressed form in ScopeInfo objects and is used
3788 // at runtime (stack dumps, deoptimization, etc.).
3790 // This object provides quick access to scope info details for runtime
3792 class ScopeInfo : public FixedArray {
3794 DECLARE_CAST(ScopeInfo)
3796 // Return the type of this scope.
3797 ScopeType scope_type();
3799 // Does this scope call eval?
3802 // Return the language mode of this scope.
3803 LanguageMode language_mode();
3805 // True if this scope is a (var) declaration scope.
3806 bool is_declaration_scope();
3808 // Does this scope make a sloppy eval call?
3809 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3811 // Return the total number of locals allocated on the stack and in the
3812 // context. This includes the parameters that are allocated in the context.
3815 // Return the number of stack slots for code. This number consists of two
3817 // 1. One stack slot per stack allocated local.
3818 // 2. One stack slot for the function name if it is stack allocated.
3819 int StackSlotCount();
3821 // Return the number of context slots for code if a context is allocated. This
3822 // number consists of three parts:
3823 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3824 // 2. One context slot per context allocated local.
3825 // 3. One context slot for the function name if it is context allocated.
3826 // Parameters allocated in the context count as context allocated locals. If
3827 // no contexts are allocated for this scope ContextLength returns 0.
3828 int ContextLength();
3830 // Does this scope declare a "this" binding?
3833 // Does this scope declare a "this" binding, and the "this" binding is stack-
3834 // or context-allocated?
3835 bool HasAllocatedReceiver();
3837 // Is this scope the scope of a named function expression?
3838 bool HasFunctionName();
3840 // Return if this has context allocated locals.
3841 bool HasHeapAllocatedLocals();
3843 // Return if contexts are allocated for this scope.
3846 // Return if this is a function scope with "use asm".
3847 inline bool IsAsmModule();
3849 // Return if this is a nested function within an asm module scope.
3850 inline bool IsAsmFunction();
3852 inline bool HasSimpleParameters();
3854 // Return the function_name if present.
3855 String* FunctionName();
3857 // Return the name of the given parameter.
3858 String* ParameterName(int var);
3860 // Return the name of the given local.
3861 String* LocalName(int var);
3863 // Return the name of the given stack local.
3864 String* StackLocalName(int var);
3866 // Return the name of the given stack local.
3867 int StackLocalIndex(int var);
3869 // Return the name of the given context local.
3870 String* ContextLocalName(int var);
3872 // Return the mode of the given context local.
3873 VariableMode ContextLocalMode(int var);
3875 // Return the initialization flag of the given context local.
3876 InitializationFlag ContextLocalInitFlag(int var);
3878 // Return the initialization flag of the given context local.
3879 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3881 // Return true if this local was introduced by the compiler, and should not be
3882 // exposed to the user in a debugger.
3883 bool LocalIsSynthetic(int var);
3885 String* StrongModeFreeVariableName(int var);
3886 int StrongModeFreeVariableStartPosition(int var);
3887 int StrongModeFreeVariableEndPosition(int var);
3889 // Lookup support for serialized scope info. Returns the
3890 // the stack slot index for a given slot name if the slot is
3891 // present; otherwise returns a value < 0. The name must be an internalized
3893 int StackSlotIndex(String* name);
3895 // Lookup support for serialized scope info. Returns the
3896 // context slot index for a given slot name if the slot is present; otherwise
3897 // returns a value < 0. The name must be an internalized string.
3898 // If the slot is present and mode != NULL, sets *mode to the corresponding
3899 // mode for that variable.
3900 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3901 VariableMode* mode, VariableLocation* location,
3902 InitializationFlag* init_flag,
3903 MaybeAssignedFlag* maybe_assigned_flag);
3905 // Lookup the name of a certain context slot by its index.
3906 String* ContextSlotName(int slot_index);
3908 // Lookup support for serialized scope info. Returns the
3909 // parameter index for a given parameter name if the parameter is present;
3910 // otherwise returns a value < 0. The name must be an internalized string.
3911 int ParameterIndex(String* name);
3913 // Lookup support for serialized scope info. Returns the function context
3914 // slot index if the function name is present and context-allocated (named
3915 // function expressions, only), otherwise returns a value < 0. The name
3916 // must be an internalized string.
3917 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3919 // Lookup support for serialized scope info. Returns the receiver context
3920 // slot index if scope has a "this" binding, and the binding is
3921 // context-allocated. Otherwise returns a value < 0.
3922 int ReceiverContextSlotIndex();
3924 FunctionKind function_kind();
3926 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3927 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3929 // Serializes empty scope info.
3930 static ScopeInfo* Empty(Isolate* isolate);
3936 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3937 // numeric and occupies one array slot.
3938 // 1. A set of properties of the scope
3939 // 2. The number of parameters. This only applies to function scopes. For
3940 // non-function scopes this is 0.
3941 // 3. The number of non-parameter variables allocated on the stack.
3942 // 4. The number of non-parameter and parameter variables allocated in the
3944 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3947 V(StackLocalCount) \
3948 V(ContextLocalCount) \
3949 V(ContextGlobalCount) \
3950 V(StrongModeFreeVariableCount)
3952 #define FIELD_ACCESSORS(name) \
3953 inline void Set##name(int value); \
3955 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3956 #undef FIELD_ACCESSORS
3960 #define DECL_INDEX(name) k##name,
3961 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3966 // The layout of the variable part of a ScopeInfo is as follows:
3967 // 1. ParameterEntries:
3968 // This part stores the names of the parameters for function scopes. One
3969 // slot is used per parameter, so in total this part occupies
3970 // ParameterCount() slots in the array. For other scopes than function
3971 // scopes ParameterCount() is 0.
3972 // 2. StackLocalFirstSlot:
3973 // Index of a first stack slot for stack local. Stack locals belonging to
3974 // this scope are located on a stack at slots starting from this index.
3975 // 3. StackLocalEntries:
3976 // Contains the names of local variables that are allocated on the stack,
3977 // in increasing order of the stack slot index. First local variable has
3978 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3979 // One slot is used per stack local, so in total this part occupies
3980 // StackLocalCount() slots in the array.
3981 // 4. ContextLocalNameEntries:
3982 // Contains the names of local variables and parameters that are allocated
3983 // in the context. They are stored in increasing order of the context slot
3984 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3985 // context local, so in total this part occupies ContextLocalCount() slots
3987 // 5. ContextLocalInfoEntries:
3988 // Contains the variable modes and initialization flags corresponding to
3989 // the context locals in ContextLocalNameEntries. One slot is used per
3990 // context local, so in total this part occupies ContextLocalCount()
3991 // slots in the array.
3992 // 6. StrongModeFreeVariableNameEntries:
3993 // Stores the names of strong mode free variables.
3994 // 7. StrongModeFreeVariablePositionEntries:
3995 // Stores the locations (start and end position) of strong mode free
3997 // 8. RecieverEntryIndex:
3998 // If the scope binds a "this" value, one slot is reserved to hold the
3999 // context or stack slot index for the variable.
4000 // 9. FunctionNameEntryIndex:
4001 // If the scope belongs to a named function expression this part contains
4002 // information about the function variable. It always occupies two array
4003 // slots: a. The name of the function variable.
4004 // b. The context or stack slot index for the variable.
4005 int ParameterEntriesIndex();
4006 int StackLocalFirstSlotIndex();
4007 int StackLocalEntriesIndex();
4008 int ContextLocalNameEntriesIndex();
4009 int ContextGlobalNameEntriesIndex();
4010 int ContextLocalInfoEntriesIndex();
4011 int ContextGlobalInfoEntriesIndex();
4012 int StrongModeFreeVariableNameEntriesIndex();
4013 int StrongModeFreeVariablePositionEntriesIndex();
4014 int ReceiverEntryIndex();
4015 int FunctionNameEntryIndex();
4017 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4018 VariableLocation* location, InitializationFlag* init_flag,
4019 MaybeAssignedFlag* maybe_assigned_flag);
4021 // Used for the function name variable for named function expressions, and for
4023 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4025 // Properties of scopes.
4026 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4027 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4028 STATIC_ASSERT(LANGUAGE_END == 3);
4029 class LanguageModeField
4030 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4031 class DeclarationScopeField
4032 : public BitField<bool, LanguageModeField::kNext, 1> {};
4033 class ReceiverVariableField
4034 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4036 class FunctionVariableField
4037 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4039 class FunctionVariableMode
4040 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4041 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4043 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4044 class HasSimpleParametersField
4045 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4046 class FunctionKindField
4047 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4049 // BitFields representing the encoded information for context locals in the
4050 // ContextLocalInfoEntries part.
4051 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4052 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4053 class ContextLocalMaybeAssignedFlag
4054 : public BitField<MaybeAssignedFlag, 4, 1> {};
4056 friend class ScopeIterator;
4060 // The cache for maps used by normalized (dictionary mode) objects.
4061 // Such maps do not have property descriptors, so a typical program
4062 // needs very limited number of distinct normalized maps.
4063 class NormalizedMapCache: public FixedArray {
4065 static Handle<NormalizedMapCache> New(Isolate* isolate);
4067 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4068 PropertyNormalizationMode mode);
4069 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4073 DECLARE_CAST(NormalizedMapCache)
4075 static inline bool IsNormalizedMapCache(const Object* obj);
4077 DECLARE_VERIFIER(NormalizedMapCache)
4079 static const int kEntries = 64;
4081 static inline int GetIndex(Handle<Map> map);
4083 // The following declarations hide base class methods.
4084 Object* get(int index);
4085 void set(int index, Object* value);
4089 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4090 // that is attached to code objects.
4091 class ByteArray: public FixedArrayBase {
4095 // Setter and getter.
4096 inline byte get(int index);
4097 inline void set(int index, byte value);
4099 // Treat contents as an int array.
4100 inline int get_int(int index);
4102 static int SizeFor(int length) {
4103 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4105 // We use byte arrays for free blocks in the heap. Given a desired size in
4106 // bytes that is a multiple of the word size and big enough to hold a byte
4107 // array, this function returns the number of elements a byte array should
4109 static int LengthFor(int size_in_bytes) {
4110 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4111 DCHECK(size_in_bytes >= kHeaderSize);
4112 return size_in_bytes - kHeaderSize;
4115 // Returns data start address.
4116 inline Address GetDataStartAddress();
4118 // Returns a pointer to the ByteArray object for a given data start address.
4119 static inline ByteArray* FromDataStartAddress(Address address);
4121 DECLARE_CAST(ByteArray)
4123 // Dispatched behavior.
4124 inline int ByteArraySize();
4125 DECLARE_PRINTER(ByteArray)
4126 DECLARE_VERIFIER(ByteArray)
4128 // Layout description.
4129 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4131 // Maximal memory consumption for a single ByteArray.
4132 static const int kMaxSize = 512 * MB;
4133 // Maximal length of a single ByteArray.
4134 static const int kMaxLength = kMaxSize - kHeaderSize;
4137 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4141 // BytecodeArray represents a sequence of interpreter bytecodes.
4142 class BytecodeArray : public FixedArrayBase {
4144 static int SizeFor(int length) {
4145 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4148 // Setter and getter
4149 inline byte get(int index);
4150 inline void set(int index, byte value);
4152 // Returns data start address.
4153 inline Address GetFirstBytecodeAddress();
4155 // Accessors for frame size.
4156 inline int frame_size() const;
4157 inline void set_frame_size(int frame_size);
4159 // Accessors for parameter count (including implicit 'this' receiver).
4160 inline int parameter_count() const;
4161 inline void set_parameter_count(int number_of_parameters);
4163 // Accessors for the constant pool.
4164 DECL_ACCESSORS(constant_pool, FixedArray)
4166 DECLARE_CAST(BytecodeArray)
4168 // Dispatched behavior.
4169 inline int BytecodeArraySize();
4170 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4172 DECLARE_PRINTER(BytecodeArray)
4173 DECLARE_VERIFIER(BytecodeArray)
4175 void Disassemble(std::ostream& os);
4177 // Layout description.
4178 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4179 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4180 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4181 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4183 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4185 // Maximal memory consumption for a single BytecodeArray.
4186 static const int kMaxSize = 512 * MB;
4187 // Maximal length of a single BytecodeArray.
4188 static const int kMaxLength = kMaxSize - kHeaderSize;
4191 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4195 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4196 // They look like heap objects (are heap object tagged and have a map) so that
4197 // the heap remains iterable. They have a size and a next pointer.
4198 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4199 // in the free list.
4200 class FreeSpace: public HeapObject {
4202 // [size]: size of the free space including the header.
4203 inline int size() const;
4204 inline void set_size(int value);
4206 inline int nobarrier_size() const;
4207 inline void nobarrier_set_size(int value);
4211 // Accessors for the next field.
4212 inline FreeSpace* next();
4213 inline FreeSpace** next_address();
4214 inline void set_next(FreeSpace* next);
4216 inline static FreeSpace* cast(HeapObject* obj);
4218 // Dispatched behavior.
4219 DECLARE_PRINTER(FreeSpace)
4220 DECLARE_VERIFIER(FreeSpace)
4222 // Layout description.
4223 // Size is smi tagged when it is stored.
4224 static const int kSizeOffset = HeapObject::kHeaderSize;
4225 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4228 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4232 // V has parameters (Type, type, TYPE, C type, element_size)
4233 #define TYPED_ARRAYS(V) \
4234 V(Uint8, uint8, UINT8, uint8_t, 1) \
4235 V(Int8, int8, INT8, int8_t, 1) \
4236 V(Uint16, uint16, UINT16, uint16_t, 2) \
4237 V(Int16, int16, INT16, int16_t, 2) \
4238 V(Uint32, uint32, UINT32, uint32_t, 4) \
4239 V(Int32, int32, INT32, int32_t, 4) \
4240 V(Float32, float32, FLOAT32, float, 4) \
4241 V(Float64, float64, FLOAT64, double, 8) \
4242 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4245 class FixedTypedArrayBase: public FixedArrayBase {
4247 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4248 DECL_ACCESSORS(base_pointer, Object)
4250 // [external_pointer]: Contains the offset between base_pointer and the start
4251 // of the data. If the base_pointer is a nullptr, the external_pointer
4252 // therefore points to the actual backing store.
4253 DECL_ACCESSORS(external_pointer, void)
4255 // Dispatched behavior.
4256 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4258 template <typename StaticVisitor>
4259 inline void FixedTypedArrayBaseIterateBody();
4261 DECLARE_CAST(FixedTypedArrayBase)
4263 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4264 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4265 static const int kHeaderSize =
4266 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4268 static const int kDataOffset = kHeaderSize;
4272 static inline int TypedArraySize(InstanceType type, int length);
4273 inline int TypedArraySize(InstanceType type);
4275 // Use with care: returns raw pointer into heap.
4276 inline void* DataPtr();
4278 inline int DataSize();
4281 static inline int ElementSize(InstanceType type);
4283 inline int DataSize(InstanceType type);
4285 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4289 template <class Traits>
4290 class FixedTypedArray: public FixedTypedArrayBase {
4292 typedef typename Traits::ElementType ElementType;
4293 static const InstanceType kInstanceType = Traits::kInstanceType;
4295 DECLARE_CAST(FixedTypedArray<Traits>)
4297 inline ElementType get_scalar(int index);
4298 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4299 inline void set(int index, ElementType value);
4301 static inline ElementType from_int(int value);
4302 static inline ElementType from_double(double value);
4304 // This accessor applies the correct conversion from Smi, HeapNumber
4306 void SetValue(uint32_t index, Object* value);
4308 DECLARE_PRINTER(FixedTypedArray)
4309 DECLARE_VERIFIER(FixedTypedArray)
4312 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4315 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4316 class Type##ArrayTraits { \
4317 public: /* NOLINT */ \
4318 typedef elementType ElementType; \
4319 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4320 static const char* Designator() { return #type " array"; } \
4321 static inline Handle<Object> ToHandle(Isolate* isolate, \
4322 elementType scalar); \
4323 static inline elementType defaultValue(); \
4326 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4328 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4330 #undef FIXED_TYPED_ARRAY_TRAITS
4333 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4334 // data for code generated by the Hydrogen/Lithium compiler. It also
4335 // contains information about functions that were inlined. If N different
4336 // functions were inlined then first N elements of the literal array will
4337 // contain these functions.
4340 class DeoptimizationInputData: public FixedArray {
4342 // Layout description. Indices in the array.
4343 static const int kTranslationByteArrayIndex = 0;
4344 static const int kInlinedFunctionCountIndex = 1;
4345 static const int kLiteralArrayIndex = 2;
4346 static const int kOsrAstIdIndex = 3;
4347 static const int kOsrPcOffsetIndex = 4;
4348 static const int kOptimizationIdIndex = 5;
4349 static const int kSharedFunctionInfoIndex = 6;
4350 static const int kWeakCellCacheIndex = 7;
4351 static const int kFirstDeoptEntryIndex = 8;
4353 // Offsets of deopt entry elements relative to the start of the entry.
4354 static const int kAstIdRawOffset = 0;
4355 static const int kTranslationIndexOffset = 1;
4356 static const int kArgumentsStackHeightOffset = 2;
4357 static const int kPcOffset = 3;
4358 static const int kDeoptEntrySize = 4;
4360 // Simple element accessors.
4361 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4362 inline type* name(); \
4363 inline void Set##name(type* value);
4365 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4366 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4367 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4368 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4369 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4370 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4371 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4372 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4374 #undef DECLARE_ELEMENT_ACCESSORS
4376 // Accessors for elements of the ith deoptimization entry.
4377 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4378 inline type* name(int i); \
4379 inline void Set##name(int i, type* value);
4381 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4382 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4383 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4384 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4386 #undef DECLARE_ENTRY_ACCESSORS
4388 inline BailoutId AstId(int i);
4390 inline void SetAstId(int i, BailoutId value);
4392 inline int DeoptCount();
4394 // Allocates a DeoptimizationInputData.
4395 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4396 int deopt_entry_count,
4397 PretenureFlag pretenure);
4399 DECLARE_CAST(DeoptimizationInputData)
4401 #ifdef ENABLE_DISASSEMBLER
4402 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4406 static int IndexForEntry(int i) {
4407 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4411 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4415 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4416 // data for code generated by the full compiler.
4417 // The format of the these objects is
4418 // [i * 2]: Ast ID for ith deoptimization.
4419 // [i * 2 + 1]: PC and state of ith deoptimization
4420 class DeoptimizationOutputData: public FixedArray {
4422 inline int DeoptPoints();
4424 inline BailoutId AstId(int index);
4426 inline void SetAstId(int index, BailoutId id);
4428 inline Smi* PcAndState(int index);
4429 inline void SetPcAndState(int index, Smi* offset);
4431 static int LengthOfFixedArray(int deopt_points) {
4432 return deopt_points * 2;
4435 // Allocates a DeoptimizationOutputData.
4436 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4437 int number_of_deopt_points,
4438 PretenureFlag pretenure);
4440 DECLARE_CAST(DeoptimizationOutputData)
4442 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4443 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4448 // HandlerTable is a fixed array containing entries for exception handlers in
4449 // the code object it is associated with. The tables comes in two flavors:
4450 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4451 // exception handler and a range representing the try-block covered by that
4452 // handler. Layout looks as follows:
4453 // [ range-start , range-end , handler-offset , stack-depth ]
4454 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4455 // per call-site that could throw an exception. Layout looks as follows:
4456 // [ return-address-offset , handler-offset ]
4457 class HandlerTable : public FixedArray {
4459 // Conservative prediction whether a given handler will locally catch an
4460 // exception or cause a re-throw to outside the code boundary. Since this is
4461 // undecidable it is merely an approximation (e.g. useful for debugger).
4462 enum CatchPrediction { UNCAUGHT, CAUGHT };
4464 // Accessors for handler table based on ranges.
4465 inline void SetRangeStart(int index, int value);
4466 inline void SetRangeEnd(int index, int value);
4467 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4468 inline void SetRangeDepth(int index, int value);
4470 // Accessors for handler table based on return addresses.
4471 inline void SetReturnOffset(int index, int value);
4472 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4474 // Lookup handler in a table based on ranges.
4475 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4477 // Lookup handler in a table based on return addresses.
4478 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4480 // Returns the required length of the underlying fixed array.
4481 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4482 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4484 DECLARE_CAST(HandlerTable)
4486 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4487 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4488 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4492 // Layout description for handler table based on ranges.
4493 static const int kRangeStartIndex = 0;
4494 static const int kRangeEndIndex = 1;
4495 static const int kRangeHandlerIndex = 2;
4496 static const int kRangeDepthIndex = 3;
4497 static const int kRangeEntrySize = 4;
4499 // Layout description for handler table based on return addresses.
4500 static const int kReturnOffsetIndex = 0;
4501 static const int kReturnHandlerIndex = 1;
4502 static const int kReturnEntrySize = 2;
4504 // Encoding of the {handler} field.
4505 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4506 class HandlerOffsetField : public BitField<int, 1, 30> {};
4510 // Code describes objects with on-the-fly generated machine code.
4511 class Code: public HeapObject {
4513 // Opaque data type for encapsulating code flags like kind, inline
4514 // cache state, and arguments count.
4515 typedef uint32_t Flags;
4517 #define NON_IC_KIND_LIST(V) \
4519 V(OPTIMIZED_FUNCTION) \
4526 #define IC_KIND_LIST(V) \
4537 #define CODE_KIND_LIST(V) \
4538 NON_IC_KIND_LIST(V) \
4542 #define DEFINE_CODE_KIND_ENUM(name) name,
4543 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4544 #undef DEFINE_CODE_KIND_ENUM
4548 // No more than 16 kinds. The value is currently encoded in four bits in
4550 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4552 static const char* Kind2String(Kind kind);
4560 static const int kPrologueOffsetNotSet = -1;
4562 #ifdef ENABLE_DISASSEMBLER
4564 static const char* ICState2String(InlineCacheState state);
4565 static const char* StubType2String(StubType type);
4566 static void PrintExtraICState(std::ostream& os, // NOLINT
4567 Kind kind, ExtraICState extra);
4568 void Disassemble(const char* name, std::ostream& os); // NOLINT
4569 #endif // ENABLE_DISASSEMBLER
4571 // [instruction_size]: Size of the native instructions
4572 inline int instruction_size() const;
4573 inline void set_instruction_size(int value);
4575 // [relocation_info]: Code relocation information
4576 DECL_ACCESSORS(relocation_info, ByteArray)
4577 void InvalidateRelocation();
4578 void InvalidateEmbeddedObjects();
4580 // [handler_table]: Fixed array containing offsets of exception handlers.
4581 DECL_ACCESSORS(handler_table, FixedArray)
4583 // [deoptimization_data]: Array containing data for deopt.
4584 DECL_ACCESSORS(deoptimization_data, FixedArray)
4586 // [raw_type_feedback_info]: This field stores various things, depending on
4587 // the kind of the code object.
4588 // FUNCTION => type feedback information.
4589 // STUB and ICs => major/minor key as Smi.
4590 DECL_ACCESSORS(raw_type_feedback_info, Object)
4591 inline Object* type_feedback_info();
4592 inline void set_type_feedback_info(
4593 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4594 inline uint32_t stub_key();
4595 inline void set_stub_key(uint32_t key);
4597 // [next_code_link]: Link for lists of optimized or deoptimized code.
4598 // Note that storage for this field is overlapped with typefeedback_info.
4599 DECL_ACCESSORS(next_code_link, Object)
4601 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4602 // field does not have to be traced during garbage collection since
4603 // it is only used by the garbage collector itself.
4604 DECL_ACCESSORS(gc_metadata, Object)
4606 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4607 // at the moment when this object was created.
4608 inline void set_ic_age(int count);
4609 inline int ic_age() const;
4611 // [prologue_offset]: Offset of the function prologue, used for aging
4612 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4613 inline int prologue_offset() const;
4614 inline void set_prologue_offset(int offset);
4616 // [constant_pool offset]: Offset of the constant pool.
4617 // Valid for FLAG_enable_embedded_constant_pool only
4618 inline int constant_pool_offset() const;
4619 inline void set_constant_pool_offset(int offset);
4621 // Unchecked accessors to be used during GC.
4622 inline ByteArray* unchecked_relocation_info();
4624 inline int relocation_size();
4626 // [flags]: Various code flags.
4627 inline Flags flags();
4628 inline void set_flags(Flags flags);
4630 // [flags]: Access to specific code flags.
4632 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4633 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4635 inline StubType type(); // Only valid for monomorphic IC stubs.
4637 // Testers for IC stub kinds.
4638 inline bool is_inline_cache_stub();
4639 inline bool is_debug_stub();
4640 inline bool is_handler();
4641 inline bool is_load_stub();
4642 inline bool is_keyed_load_stub();
4643 inline bool is_store_stub();
4644 inline bool is_keyed_store_stub();
4645 inline bool is_call_stub();
4646 inline bool is_binary_op_stub();
4647 inline bool is_compare_ic_stub();
4648 inline bool is_compare_nil_ic_stub();
4649 inline bool is_to_boolean_ic_stub();
4650 inline bool is_keyed_stub();
4651 inline bool is_optimized_code();
4652 inline bool embeds_maps_weakly();
4654 inline bool IsCodeStubOrIC();
4655 inline bool IsJavaScriptCode();
4657 inline void set_raw_kind_specific_flags1(int value);
4658 inline void set_raw_kind_specific_flags2(int value);
4660 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4661 // object was generated by either the hydrogen or the TurboFan optimizing
4662 // compiler (but it may not be an optimized function).
4663 inline bool is_crankshafted();
4664 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4665 inline void set_is_crankshafted(bool value);
4667 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4668 // code object was generated by the TurboFan optimizing compiler.
4669 inline bool is_turbofanned();
4670 inline void set_is_turbofanned(bool value);
4672 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4673 // embedded objects in code should be treated weakly.
4674 inline bool can_have_weak_objects();
4675 inline void set_can_have_weak_objects(bool value);
4677 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4678 // deoptimization support.
4679 inline bool has_deoptimization_support();
4680 inline void set_has_deoptimization_support(bool value);
4682 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4683 // been compiled with debug break slots.
4684 inline bool has_debug_break_slots();
4685 inline void set_has_debug_break_slots(bool value);
4687 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4688 // reloc info includes runtime and external references to support
4689 // serialization/deserialization.
4690 inline bool has_reloc_info_for_serialization();
4691 inline void set_has_reloc_info_for_serialization(bool value);
4693 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4694 // how long the function has been marked for OSR and therefore which
4695 // level of loop nesting we are willing to do on-stack replacement
4697 inline void set_allow_osr_at_loop_nesting_level(int level);
4698 inline int allow_osr_at_loop_nesting_level();
4700 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4701 // the code object was seen on the stack with no IC patching going on.
4702 inline int profiler_ticks();
4703 inline void set_profiler_ticks(int ticks);
4705 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4706 // For builtins, tells which builtin index it has.
4707 // Note that builtins can have a code kind other than BUILTIN, which means
4708 // that for arbitrary code objects, this index value may be random garbage.
4709 // To verify in that case, compare the code object to the indexed builtin.
4710 inline int builtin_index();
4711 inline void set_builtin_index(int id);
4713 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4714 // reserved in the code prologue.
4715 inline unsigned stack_slots();
4716 inline void set_stack_slots(unsigned slots);
4718 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4719 // the instruction stream where the safepoint table starts.
4720 inline unsigned safepoint_table_offset();
4721 inline void set_safepoint_table_offset(unsigned offset);
4723 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4724 // instruction stream where the back edge table starts.
4725 inline unsigned back_edge_table_offset();
4726 inline void set_back_edge_table_offset(unsigned offset);
4728 inline bool back_edges_patched_for_osr();
4730 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4731 inline uint16_t to_boolean_state();
4733 // [has_function_cache]: For kind STUB tells whether there is a function
4734 // cache is passed to the stub.
4735 inline bool has_function_cache();
4736 inline void set_has_function_cache(bool flag);
4739 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4740 // the code is going to be deoptimized because of dead embedded maps.
4741 inline bool marked_for_deoptimization();
4742 inline void set_marked_for_deoptimization(bool flag);
4744 // [constant_pool]: The constant pool for this function.
4745 inline Address constant_pool();
4747 // Get the safepoint entry for the given pc.
4748 SafepointEntry GetSafepointEntry(Address pc);
4750 // Find an object in a stub with a specified map
4751 Object* FindNthObject(int n, Map* match_map);
4753 // Find the first allocation site in an IC stub.
4754 AllocationSite* FindFirstAllocationSite();
4756 // Find the first map in an IC stub.
4757 Map* FindFirstMap();
4758 void FindAllMaps(MapHandleList* maps);
4760 // Find the first handler in an IC stub.
4761 Code* FindFirstHandler();
4763 // Find |length| handlers and put them into |code_list|. Returns false if not
4764 // enough handlers can be found.
4765 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4767 // Find the handler for |map|.
4768 MaybeHandle<Code> FindHandlerForMap(Map* map);
4770 // Find the first name in an IC stub.
4771 Name* FindFirstName();
4773 class FindAndReplacePattern;
4774 // For each (map-to-find, object-to-replace) pair in the pattern, this
4775 // function replaces the corresponding placeholder in the code with the
4776 // object-to-replace. The function assumes that pairs in the pattern come in
4777 // the same order as the placeholders in the code.
4778 // If the placeholder is a weak cell, then the value of weak cell is matched
4779 // against the map-to-find.
4780 void FindAndReplace(const FindAndReplacePattern& pattern);
4782 // The entire code object including its header is copied verbatim to the
4783 // snapshot so that it can be written in one, fast, memcpy during
4784 // deserialization. The deserializer will overwrite some pointers, rather
4785 // like a runtime linker, but the random allocation addresses used in the
4786 // mksnapshot process would still be present in the unlinked snapshot data,
4787 // which would make snapshot production non-reproducible. This method wipes
4788 // out the to-be-overwritten header data for reproducible snapshots.
4789 inline void WipeOutHeader();
4791 // Flags operations.
4792 static inline Flags ComputeFlags(
4793 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4794 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4795 CacheHolderFlag holder = kCacheOnReceiver);
4797 static inline Flags ComputeMonomorphicFlags(
4798 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4799 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4801 static inline Flags ComputeHandlerFlags(
4802 Kind handler_kind, StubType type = NORMAL,
4803 CacheHolderFlag holder = kCacheOnReceiver);
4805 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4806 static inline StubType ExtractTypeFromFlags(Flags flags);
4807 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4808 static inline Kind ExtractKindFromFlags(Flags flags);
4809 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4811 static inline Flags RemoveTypeFromFlags(Flags flags);
4812 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4814 // Convert a target address into a code object.
4815 static inline Code* GetCodeFromTargetAddress(Address address);
4817 // Convert an entry address into an object.
4818 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4820 // Returns the address of the first instruction.
4821 inline byte* instruction_start();
4823 // Returns the address right after the last instruction.
4824 inline byte* instruction_end();
4826 // Returns the size of the instructions, padding, and relocation information.
4827 inline int body_size();
4829 // Returns the address of the first relocation info (read backwards!).
4830 inline byte* relocation_start();
4832 // Code entry point.
4833 inline byte* entry();
4835 // Returns true if pc is inside this object's instructions.
4836 inline bool contains(byte* pc);
4838 // Relocate the code by delta bytes. Called to signal that this code
4839 // object has been moved by delta bytes.
4840 void Relocate(intptr_t delta);
4842 // Migrate code described by desc.
4843 void CopyFrom(const CodeDesc& desc);
4845 // Returns the object size for a given body (used for allocation).
4846 static int SizeFor(int body_size) {
4847 DCHECK_SIZE_TAG_ALIGNED(body_size);
4848 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4851 // Calculate the size of the code object to report for log events. This takes
4852 // the layout of the code object into account.
4853 inline int ExecutableSize();
4855 // Locating source position.
4856 int SourcePosition(Address pc);
4857 int SourceStatementPosition(Address pc);
4861 // Dispatched behavior.
4862 inline int CodeSize();
4863 inline void CodeIterateBody(ObjectVisitor* v);
4865 template<typename StaticVisitor>
4866 inline void CodeIterateBody(Heap* heap);
4868 DECLARE_PRINTER(Code)
4869 DECLARE_VERIFIER(Code)
4871 void ClearInlineCaches();
4872 void ClearInlineCaches(Kind kind);
4874 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4875 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4877 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4879 kToBeExecutedOnceCodeAge = -3,
4880 kNotExecutedCodeAge = -2,
4881 kExecutedOnceCodeAge = -1,
4883 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4885 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4886 kLastCodeAge = kAfterLastCodeAge - 1,
4887 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4888 kIsOldCodeAge = kSexagenarianCodeAge,
4889 kPreAgedCodeAge = kIsOldCodeAge - 1
4891 #undef DECLARE_CODE_AGE_ENUM
4893 // Code aging. Indicates how many full GCs this code has survived without
4894 // being entered through the prologue. Used to determine when it is
4895 // relatively safe to flush this code object and replace it with the lazy
4896 // compilation stub.
4897 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4898 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4899 void MakeYoung(Isolate* isolate);
4900 void MarkToBeExecutedOnce(Isolate* isolate);
4901 void MakeOlder(MarkingParity);
4902 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4905 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4906 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4909 void PrintDeoptLocation(FILE* out, Address pc);
4910 bool CanDeoptAt(Address pc);
4913 void VerifyEmbeddedObjectsDependency();
4917 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4918 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4919 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4922 inline bool CanContainWeakObjects();
4924 inline bool IsWeakObject(Object* object);
4926 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4928 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4929 WeakCell* CachedWeakCell();
4931 // Max loop nesting marker used to postpose OSR. We don't take loop
4932 // nesting that is deeper than 5 levels into account.
4933 static const int kMaxLoopNestingMarker = 6;
4935 static const int kConstantPoolSize =
4936 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4938 // Layout description.
4939 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4940 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4941 static const int kDeoptimizationDataOffset =
4942 kHandlerTableOffset + kPointerSize;
4943 // For FUNCTION kind, we store the type feedback info here.
4944 static const int kTypeFeedbackInfoOffset =
4945 kDeoptimizationDataOffset + kPointerSize;
4946 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4947 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4948 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4949 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4950 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4951 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4952 static const int kKindSpecificFlags2Offset =
4953 kKindSpecificFlags1Offset + kIntSize;
4954 // Note: We might be able to squeeze this into the flags above.
4955 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4956 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4957 static const int kHeaderPaddingStart =
4958 kConstantPoolOffset + kConstantPoolSize;
4960 // Add padding to align the instruction start following right after
4961 // the Code object header.
4962 static const int kHeaderSize =
4963 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4965 // Byte offsets within kKindSpecificFlags1Offset.
4966 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4967 class FullCodeFlagsHasDeoptimizationSupportField:
4968 public BitField<bool, 0, 1> {}; // NOLINT
4969 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4970 class FullCodeFlagsHasRelocInfoForSerialization
4971 : public BitField<bool, 2, 1> {};
4972 // Bit 3 in this bitfield is unused.
4973 class ProfilerTicksField : public BitField<int, 4, 28> {};
4975 // Flags layout. BitField<type, shift, size>.
4976 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4977 class TypeField : public BitField<StubType, 4, 1> {};
4978 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4979 class KindField : public BitField<Kind, 7, 4> {};
4980 class ExtraICStateField: public BitField<ExtraICState, 11,
4981 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4983 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4984 static const int kStackSlotsFirstBit = 0;
4985 static const int kStackSlotsBitCount = 24;
4986 static const int kHasFunctionCacheBit =
4987 kStackSlotsFirstBit + kStackSlotsBitCount;
4988 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4989 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4990 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4992 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4993 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4995 class StackSlotsField: public BitField<int,
4996 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4997 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4999 class MarkedForDeoptimizationField
5000 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5001 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5003 class CanHaveWeakObjectsField
5004 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5006 // KindSpecificFlags2 layout (ALL)
5007 static const int kIsCrankshaftedBit = 0;
5008 class IsCrankshaftedField: public BitField<bool,
5009 kIsCrankshaftedBit, 1> {}; // NOLINT
5011 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5012 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5013 static const int kSafepointTableOffsetBitCount = 30;
5015 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5016 kSafepointTableOffsetBitCount <= 32);
5017 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5019 class SafepointTableOffsetField: public BitField<int,
5020 kSafepointTableOffsetFirstBit,
5021 kSafepointTableOffsetBitCount> {}; // NOLINT
5023 // KindSpecificFlags2 layout (FUNCTION)
5024 class BackEdgeTableOffsetField: public BitField<int,
5025 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5026 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5027 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5028 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5030 static const int kArgumentsBits = 16;
5031 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5033 // This constant should be encodable in an ARM instruction.
5034 static const int kFlagsNotUsedInLookup =
5035 TypeField::kMask | CacheHolderField::kMask;
5038 friend class RelocIterator;
5039 friend class Deoptimizer; // For FindCodeAgeSequence.
5041 void ClearInlineCaches(Kind* kind);
5044 byte* FindCodeAgeSequence();
5045 static void GetCodeAgeAndParity(Code* code, Age* age,
5046 MarkingParity* parity);
5047 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5048 MarkingParity* parity);
5049 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5051 // Code aging -- platform-specific
5052 static void PatchPlatformCodeAge(Isolate* isolate,
5053 byte* sequence, Age age,
5054 MarkingParity parity);
5056 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5060 // This class describes the layout of dependent codes array of a map. The
5061 // array is partitioned into several groups of dependent codes. Each group
5062 // contains codes with the same dependency on the map. The array has the
5063 // following layout for n dependency groups:
5065 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5066 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5067 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5069 // The first n elements are Smis, each of them specifies the number of codes
5070 // in the corresponding group. The subsequent elements contain grouped code
5071 // objects in weak cells. The suffix of the array can be filled with the
5072 // undefined value if the number of codes is less than the length of the
5073 // array. The order of the code objects within a group is not preserved.
5075 // All code indexes used in the class are counted starting from the first
5076 // code object of the first group. In other words, code index 0 corresponds
5077 // to array index n = kCodesStartIndex.
5079 class DependentCode: public FixedArray {
5081 enum DependencyGroup {
5082 // Group of code that weakly embed this map and depend on being
5083 // deoptimized when the map is garbage collected.
5085 // Group of code that embed a transition to this map, and depend on being
5086 // deoptimized when the transition is replaced by a new version.
5088 // Group of code that omit run-time prototype checks for prototypes
5089 // described by this map. The group is deoptimized whenever an object
5090 // described by this map changes shape (and transitions to a new map),
5091 // possibly invalidating the assumptions embedded in the code.
5092 kPrototypeCheckGroup,
5093 // Group of code that depends on global property values in property cells
5094 // not being changed.
5095 kPropertyCellChangedGroup,
5096 // Group of code that omit run-time type checks for the field(s) introduced
5099 // Group of code that omit run-time type checks for initial maps of
5101 kInitialMapChangedGroup,
5102 // Group of code that depends on tenuring information in AllocationSites
5103 // not being changed.
5104 kAllocationSiteTenuringChangedGroup,
5105 // Group of code that depends on element transition information in
5106 // AllocationSites not being changed.
5107 kAllocationSiteTransitionChangedGroup
5110 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5112 // Array for holding the index of the first code object of each group.
5113 // The last element stores the total number of code objects.
5114 class GroupStartIndexes {
5116 explicit GroupStartIndexes(DependentCode* entries);
5117 void Recompute(DependentCode* entries);
5118 int at(int i) { return start_indexes_[i]; }
5119 int number_of_entries() { return start_indexes_[kGroupCount]; }
5121 int start_indexes_[kGroupCount + 1];
5124 bool Contains(DependencyGroup group, WeakCell* code_cell);
5126 static Handle<DependentCode> InsertCompilationDependencies(
5127 Handle<DependentCode> entries, DependencyGroup group,
5128 Handle<Foreign> info);
5130 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5131 DependencyGroup group,
5132 Handle<WeakCell> code_cell);
5134 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5135 WeakCell* code_cell);
5137 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5140 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5141 DependentCode::DependencyGroup group);
5143 bool MarkCodeForDeoptimization(Isolate* isolate,
5144 DependentCode::DependencyGroup group);
5146 // The following low-level accessors should only be used by this class
5147 // and the mark compact collector.
5148 inline int number_of_entries(DependencyGroup group);
5149 inline void set_number_of_entries(DependencyGroup group, int value);
5150 inline Object* object_at(int i);
5151 inline void set_object_at(int i, Object* object);
5152 inline void clear_at(int i);
5153 inline void copy(int from, int to);
5154 DECLARE_CAST(DependentCode)
5156 static const char* DependencyGroupName(DependencyGroup group);
5157 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5160 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5161 DependencyGroup group,
5162 Handle<Object> object);
5163 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5164 // Make a room at the end of the given group by moving out the first
5165 // code objects of the subsequent groups.
5166 inline void ExtendGroup(DependencyGroup group);
5167 // Compact by removing cleared weak cells and return true if there was
5168 // any cleared weak cell.
5170 static int Grow(int number_of_entries) {
5171 if (number_of_entries < 5) return number_of_entries + 1;
5172 return number_of_entries * 5 / 4;
5174 static const int kCodesStartIndex = kGroupCount;
5178 class PrototypeInfo;
5181 // All heap objects have a Map that describes their structure.
5182 // A Map contains information about:
5183 // - Size information about the object
5184 // - How to iterate over an object (for garbage collection)
5185 class Map: public HeapObject {
5188 // Size in bytes or kVariableSizeSentinel if instances do not have
5190 inline int instance_size();
5191 inline void set_instance_size(int value);
5193 // Only to clear an unused byte, remove once byte is used.
5194 inline void clear_unused();
5196 // [inobject_properties_or_constructor_function_index]: Provides access
5197 // to the inobject properties in case of JSObject maps, or the constructor
5198 // function index in case of primitive maps.
5199 inline int inobject_properties_or_constructor_function_index();
5200 inline void set_inobject_properties_or_constructor_function_index(int value);
5201 // Count of properties allocated in the object (JSObject only).
5202 inline int GetInObjectProperties();
5203 inline void SetInObjectProperties(int value);
5204 // Index of the constructor function in the native context (primitives only),
5205 // or the special sentinel value to indicate that there is no object wrapper
5206 // for the primitive (i.e. in case of null or undefined).
5207 static const int kNoConstructorFunctionIndex = 0;
5208 inline int GetConstructorFunctionIndex();
5209 inline void SetConstructorFunctionIndex(int value);
5212 inline InstanceType instance_type();
5213 inline void set_instance_type(InstanceType value);
5215 // Tells how many unused property fields are available in the
5216 // instance (only used for JSObject in fast mode).
5217 inline int unused_property_fields();
5218 inline void set_unused_property_fields(int value);
5221 inline byte bit_field() const;
5222 inline void set_bit_field(byte value);
5225 inline byte bit_field2() const;
5226 inline void set_bit_field2(byte value);
5229 inline uint32_t bit_field3() const;
5230 inline void set_bit_field3(uint32_t bits);
5232 class EnumLengthBits: public BitField<int,
5233 0, kDescriptorIndexBitCount> {}; // NOLINT
5234 class NumberOfOwnDescriptorsBits: public BitField<int,
5235 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5236 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5237 class DictionaryMap : public BitField<bool, 20, 1> {};
5238 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5239 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5240 class Deprecated : public BitField<bool, 23, 1> {};
5241 class IsUnstable : public BitField<bool, 24, 1> {};
5242 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5243 class IsStrong : public BitField<bool, 26, 1> {};
5246 // Keep this bit field at the very end for better code in
5247 // Builtins::kJSConstructStubGeneric stub.
5248 // This counter is used for in-object slack tracking and for map aging.
5249 // The in-object slack tracking is considered enabled when the counter is
5250 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5251 class Counter : public BitField<int, 28, 4> {};
5252 static const int kSlackTrackingCounterStart = 14;
5253 static const int kSlackTrackingCounterEnd = 8;
5254 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5255 static const int kRetainingCounterEnd = 0;
5257 // Tells whether the object in the prototype property will be used
5258 // for instances created from this function. If the prototype
5259 // property is set to a value that is not a JSObject, the prototype
5260 // property will not be used to create instances of the function.
5261 // See ECMA-262, 13.2.2.
5262 inline void set_non_instance_prototype(bool value);
5263 inline bool has_non_instance_prototype();
5265 // Tells whether function has special prototype property. If not, prototype
5266 // property will not be created when accessed (will return undefined),
5267 // and construction from this function will not be allowed.
5268 inline void set_function_with_prototype(bool value);
5269 inline bool function_with_prototype();
5271 // Tells whether the instance with this map should be ignored by the
5272 // Object.getPrototypeOf() function and the __proto__ accessor.
5273 inline void set_is_hidden_prototype();
5274 inline bool is_hidden_prototype();
5276 // Records and queries whether the instance has a named interceptor.
5277 inline void set_has_named_interceptor();
5278 inline bool has_named_interceptor();
5280 // Records and queries whether the instance has an indexed interceptor.
5281 inline void set_has_indexed_interceptor();
5282 inline bool has_indexed_interceptor();
5284 // Tells whether the instance is undetectable.
5285 // An undetectable object is a special class of JSObject: 'typeof' operator
5286 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5287 // a normal JS object. It is useful for implementing undetectable
5288 // document.all in Firefox & Safari.
5289 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5290 inline void set_is_undetectable();
5291 inline bool is_undetectable();
5293 // Tells whether the instance has a call-as-function handler.
5294 inline void set_is_observed();
5295 inline bool is_observed();
5297 inline void set_is_strong();
5298 inline bool is_strong();
5299 inline void set_is_extensible(bool value);
5300 inline bool is_extensible();
5301 inline void set_is_prototype_map(bool value);
5302 inline bool is_prototype_map() const;
5304 inline void set_elements_kind(ElementsKind elements_kind);
5305 inline ElementsKind elements_kind();
5307 // Tells whether the instance has fast elements that are only Smis.
5308 inline bool has_fast_smi_elements();
5310 // Tells whether the instance has fast elements.
5311 inline bool has_fast_object_elements();
5312 inline bool has_fast_smi_or_object_elements();
5313 inline bool has_fast_double_elements();
5314 inline bool has_fast_elements();
5315 inline bool has_sloppy_arguments_elements();
5316 inline bool has_fixed_typed_array_elements();
5317 inline bool has_dictionary_elements();
5319 static bool IsValidElementsTransition(ElementsKind from_kind,
5320 ElementsKind to_kind);
5322 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5323 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5324 bool DictionaryElementsInPrototypeChainOnly();
5326 inline Map* ElementsTransitionMap();
5328 inline FixedArrayBase* GetInitialElements();
5330 // [raw_transitions]: Provides access to the transitions storage field.
5331 // Don't call set_raw_transitions() directly to overwrite transitions, use
5332 // the TransitionArray::ReplaceTransitions() wrapper instead!
5333 DECL_ACCESSORS(raw_transitions, Object)
5334 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5335 // (which prototype maps don't have).
5336 DECL_ACCESSORS(prototype_info, Object)
5337 // PrototypeInfo is created lazily using this helper (which installs it on
5338 // the given prototype's map).
5339 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5340 Handle<JSObject> prototype, Isolate* isolate);
5341 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5342 Handle<Map> prototype_map, Isolate* isolate);
5344 // [prototype chain validity cell]: Associated with a prototype object,
5345 // stored in that object's map's PrototypeInfo, indicates that prototype
5346 // chains through this object are currently valid. The cell will be
5347 // invalidated and replaced when the prototype chain changes.
5348 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5350 static const int kPrototypeChainValid = 0;
5351 static const int kPrototypeChainInvalid = 1;
5354 Map* FindFieldOwner(int descriptor);
5356 inline int GetInObjectPropertyOffset(int index);
5358 int NumberOfFields();
5360 // TODO(ishell): candidate with JSObject::MigrateToMap().
5361 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5362 int target_inobject, int target_unused,
5363 int* old_number_of_fields);
5364 // TODO(ishell): moveit!
5365 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5366 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5367 Handle<HeapType> type1,
5368 Handle<HeapType> type2,
5370 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5371 Representation new_representation,
5372 Handle<HeapType> new_field_type);
5373 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5374 PropertyKind new_kind,
5375 PropertyAttributes new_attributes,
5376 Representation new_representation,
5377 Handle<HeapType> new_field_type,
5378 StoreMode store_mode);
5379 static Handle<Map> CopyGeneralizeAllRepresentations(
5380 Handle<Map> map, int modify_index, StoreMode store_mode,
5381 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5383 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5384 int descriptor_number,
5385 Handle<Object> value);
5387 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5388 const char* reason);
5390 // Returns the constructor name (the name (possibly, inferred name) of the
5391 // function that was used to instantiate the object).
5392 String* constructor_name();
5394 // Tells whether the map is used for JSObjects in dictionary mode (ie
5395 // normalized objects, ie objects for which HasFastProperties returns false).
5396 // A map can never be used for both dictionary mode and fast mode JSObjects.
5397 // False by default and for HeapObjects that are not JSObjects.
5398 inline void set_dictionary_map(bool value);
5399 inline bool is_dictionary_map();
5401 // Tells whether the instance needs security checks when accessing its
5403 inline void set_is_access_check_needed(bool access_check_needed);
5404 inline bool is_access_check_needed();
5406 // Returns true if map has a non-empty stub code cache.
5407 inline bool has_code_cache();
5409 // [prototype]: implicit prototype object.
5410 DECL_ACCESSORS(prototype, Object)
5411 // TODO(jkummerow): make set_prototype private.
5412 static void SetPrototype(
5413 Handle<Map> map, Handle<Object> prototype,
5414 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5416 // [constructor]: points back to the function responsible for this map.
5417 // The field overlaps with the back pointer. All maps in a transition tree
5418 // have the same constructor, so maps with back pointers can walk the
5419 // back pointer chain until they find the map holding their constructor.
5420 DECL_ACCESSORS(constructor_or_backpointer, Object)
5421 inline Object* GetConstructor() const;
5422 inline void SetConstructor(Object* constructor,
5423 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5424 // [back pointer]: points back to the parent map from which a transition
5425 // leads to this map. The field overlaps with the constructor (see above).
5426 inline Object* GetBackPointer();
5427 inline void SetBackPointer(Object* value,
5428 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5430 // [instance descriptors]: describes the object.
5431 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5433 // [layout descriptor]: describes the object layout.
5434 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5435 // |layout descriptor| accessor which can be used from GC.
5436 inline LayoutDescriptor* layout_descriptor_gc_safe();
5437 inline bool HasFastPointerLayout() const;
5439 // |layout descriptor| accessor that is safe to call even when
5440 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5441 // |layout_descriptor| field at all).
5442 inline LayoutDescriptor* GetLayoutDescriptor();
5444 inline void UpdateDescriptors(DescriptorArray* descriptors,
5445 LayoutDescriptor* layout_descriptor);
5446 inline void InitializeDescriptors(DescriptorArray* descriptors,
5447 LayoutDescriptor* layout_descriptor);
5449 // [stub cache]: contains stubs compiled for this map.
5450 DECL_ACCESSORS(code_cache, Object)
5452 // [dependent code]: list of optimized codes that weakly embed this map.
5453 DECL_ACCESSORS(dependent_code, DependentCode)
5455 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5456 DECL_ACCESSORS(weak_cell_cache, Object)
5458 inline PropertyDetails GetLastDescriptorDetails();
5460 inline int LastAdded();
5462 inline int NumberOfOwnDescriptors();
5463 inline void SetNumberOfOwnDescriptors(int number);
5465 inline Cell* RetrieveDescriptorsPointer();
5467 inline int EnumLength();
5468 inline void SetEnumLength(int length);
5470 inline bool owns_descriptors();
5471 inline void set_owns_descriptors(bool owns_descriptors);
5472 inline bool has_instance_call_handler();
5473 inline void set_has_instance_call_handler();
5474 inline void mark_unstable();
5475 inline bool is_stable();
5476 inline void set_migration_target(bool value);
5477 inline bool is_migration_target();
5478 inline void set_counter(int value);
5479 inline int counter();
5480 inline void deprecate();
5481 inline bool is_deprecated();
5482 inline bool CanBeDeprecated();
5483 // Returns a non-deprecated version of the input. If the input was not
5484 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5485 // is found by re-transitioning from the root of the transition tree using the
5486 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5488 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5490 // Returns a non-deprecated version of the input. This method may deprecate
5491 // existing maps along the way if encodings conflict. Not for use while
5492 // gathering type feedback. Use TryUpdate in those cases instead.
5493 static Handle<Map> Update(Handle<Map> map);
5495 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5496 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5497 Descriptor* descriptor,
5498 TransitionFlag flag);
5500 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5503 Handle<HeapType> type,
5504 PropertyAttributes attributes,
5505 Representation representation,
5506 TransitionFlag flag);
5508 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5511 Handle<Object> constant,
5512 PropertyAttributes attributes,
5513 TransitionFlag flag);
5515 // Returns a new map with all transitions dropped from the given map and
5516 // the ElementsKind set.
5517 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5518 ElementsKind to_kind);
5520 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5522 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5524 TransitionFlag flag);
5526 static Handle<Map> CopyForObserved(Handle<Map> map);
5528 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5529 PropertyAttributes attrs_to_add,
5530 Handle<Symbol> transition_marker,
5531 const char* reason);
5533 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5536 // Maximal number of fast properties. Used to restrict the number of map
5537 // transitions to avoid an explosion in the number of maps for objects used as
5539 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5540 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5542 Handle<Object> value,
5543 PropertyAttributes attributes,
5544 StoreFromKeyed store_mode);
5545 static Handle<Map> TransitionToAccessorProperty(
5546 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5547 Handle<Object> accessor, PropertyAttributes attributes);
5548 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5551 PropertyAttributes attributes);
5553 inline void AppendDescriptor(Descriptor* desc);
5555 // Returns a copy of the map, prepared for inserting into the transition
5556 // tree (if the |map| owns descriptors then the new one will share
5557 // descriptors with |map|).
5558 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5560 // Returns a copy of the map, with all transitions dropped from the
5561 // instance descriptors.
5562 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5563 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5565 // Returns the next free property index (only valid for FAST MODE).
5566 int NextFreePropertyIndex();
5568 // Returns the number of properties described in instance_descriptors
5569 // filtering out properties with the specified attributes.
5570 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5571 PropertyAttributes filter = NONE);
5575 // Code cache operations.
5577 // Clears the code cache.
5578 inline void ClearCodeCache(Heap* heap);
5580 // Update code cache.
5581 static void UpdateCodeCache(Handle<Map> map,
5585 // Extend the descriptor array of the map with the list of descriptors.
5586 // In case of duplicates, the latest descriptor is used.
5587 static void AppendCallbackDescriptors(Handle<Map> map,
5588 Handle<Object> descriptors);
5590 static inline int SlackForArraySize(int old_size, int size_limit);
5592 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5594 // Returns the found code or undefined if absent.
5595 Object* FindInCodeCache(Name* name, Code::Flags flags);
5597 // Returns the non-negative index of the code object if it is in the
5598 // cache and -1 otherwise.
5599 int IndexInCodeCache(Object* name, Code* code);
5601 // Removes a code object from the code cache at the given index.
5602 void RemoveFromCodeCache(Name* name, Code* code, int index);
5604 // Computes a hash value for this map, to be used in HashTables and such.
5607 // Returns the map that this map transitions to if its elements_kind
5608 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5609 // |safe_to_add_transitions| is set to false if adding transitions is not
5611 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5613 // Returns the transitioned map for this map with the most generic
5614 // elements_kind that's found in |candidates|, or null handle if no match is
5616 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5617 MapHandleList* candidates);
5619 inline bool CanTransition();
5621 inline bool IsPrimitiveMap();
5622 inline bool IsJSObjectMap();
5623 inline bool IsJSArrayMap();
5624 inline bool IsStringMap();
5625 inline bool IsJSProxyMap();
5626 inline bool IsJSGlobalProxyMap();
5627 inline bool IsJSGlobalObjectMap();
5628 inline bool IsGlobalObjectMap();
5630 inline bool CanOmitMapChecks();
5632 static void AddDependentCode(Handle<Map> map,
5633 DependentCode::DependencyGroup group,
5636 bool IsMapInArrayPrototypeChain();
5638 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5640 // Dispatched behavior.
5641 DECLARE_PRINTER(Map)
5642 DECLARE_VERIFIER(Map)
5645 void DictionaryMapVerify();
5646 void VerifyOmittedMapChecks();
5649 inline int visitor_id();
5650 inline void set_visitor_id(int visitor_id);
5652 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5653 Handle<Object> prototype,
5654 PrototypeOptimizationMode mode);
5656 static const int kMaxPreAllocatedPropertyFields = 255;
5658 // Layout description.
5659 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5660 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5661 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5662 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5663 static const int kConstructorOrBackPointerOffset =
5664 kPrototypeOffset + kPointerSize;
5665 // When there is only one transition, it is stored directly in this field;
5666 // otherwise a transition array is used.
5667 // For prototype maps, this slot is used to store this map's PrototypeInfo
5669 static const int kTransitionsOrPrototypeInfoOffset =
5670 kConstructorOrBackPointerOffset + kPointerSize;
5671 static const int kDescriptorsOffset =
5672 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5673 #if V8_DOUBLE_FIELDS_UNBOXING
5674 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5675 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5677 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5678 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5680 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5681 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5682 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5684 // Layout of pointer fields. Heap iteration code relies on them
5685 // being continuously allocated.
5686 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5687 static const int kPointerFieldsEndOffset = kSize;
5689 // Byte offsets within kInstanceSizesOffset.
5690 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5691 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5692 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5693 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5694 // Note there is one byte available for use here.
5695 static const int kUnusedByte = 2;
5696 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5697 static const int kVisitorIdByte = 3;
5698 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5700 // Byte offsets within kInstanceAttributesOffset attributes.
5701 #if V8_TARGET_LITTLE_ENDIAN
5702 // Order instance type and bit field together such that they can be loaded
5703 // together as a 16-bit word with instance type in the lower 8 bits regardless
5704 // of endianess. Also provide endian-independent offset to that 16-bit word.
5705 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5706 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5708 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5709 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5711 static const int kInstanceTypeAndBitFieldOffset =
5712 kInstanceAttributesOffset + 0;
5713 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5714 static const int kUnusedPropertyFieldsByte = 3;
5715 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5717 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5718 Internals::kMapInstanceTypeAndBitFieldOffset);
5720 // Bit positions for bit field.
5721 static const int kHasNonInstancePrototype = 0;
5722 static const int kIsHiddenPrototype = 1;
5723 static const int kHasNamedInterceptor = 2;
5724 static const int kHasIndexedInterceptor = 3;
5725 static const int kIsUndetectable = 4;
5726 static const int kIsObserved = 5;
5727 static const int kIsAccessCheckNeeded = 6;
5728 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5730 // Bit positions for bit field 2
5731 static const int kIsExtensible = 0;
5732 static const int kStringWrapperSafeForDefaultValueOf = 1;
5733 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5734 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5736 // Derived values from bit field 2
5737 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5738 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5739 static const int8_t kMaximumBitField2FastSmiElementValue =
5740 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5741 Map::ElementsKindBits::kShift) - 1;
5742 static const int8_t kMaximumBitField2FastHoleyElementValue =
5743 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5744 Map::ElementsKindBits::kShift) - 1;
5745 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5746 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5747 Map::ElementsKindBits::kShift) - 1;
5749 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5750 kPointerFieldsEndOffset,
5751 kSize> BodyDescriptor;
5753 // Compares this map to another to see if they describe equivalent objects.
5754 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5755 // it had exactly zero inobject properties.
5756 // The "shared" flags of both this map and |other| are ignored.
5757 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5759 // Returns true if given field is unboxed double.
5760 inline bool IsUnboxedDoubleField(FieldIndex index);
5763 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5764 static void TraceAllTransitions(Map* map);
5767 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5768 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5769 Handle<LayoutDescriptor> layout_descriptor);
5772 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5773 Handle<Name> name, SimpleTransitionFlag flag);
5775 bool EquivalentToForTransition(Map* other);
5776 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5777 static Handle<Map> ShareDescriptor(Handle<Map> map,
5778 Handle<DescriptorArray> descriptors,
5779 Descriptor* descriptor);
5780 static Handle<Map> CopyInstallDescriptors(
5781 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5782 Handle<LayoutDescriptor> layout_descriptor);
5783 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5784 Descriptor* descriptor,
5785 TransitionFlag flag);
5786 static Handle<Map> CopyReplaceDescriptors(
5787 Handle<Map> map, Handle<DescriptorArray> descriptors,
5788 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5789 MaybeHandle<Name> maybe_name, const char* reason,
5790 SimpleTransitionFlag simple_flag);
5792 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5793 Handle<DescriptorArray> descriptors,
5794 Descriptor* descriptor,
5796 TransitionFlag flag);
5797 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5798 Handle<Map> map, int descriptor, PropertyKind kind,
5799 PropertyAttributes attributes, const char** reason);
5801 static Handle<Map> CopyNormalized(Handle<Map> map,
5802 PropertyNormalizationMode mode);
5804 // Fires when the layout of an object with a leaf map changes.
5805 // This includes adding transitions to the leaf map or changing
5806 // the descriptor array.
5807 inline void NotifyLeafMapLayoutChange();
5809 void DeprecateTransitionTree();
5810 bool DeprecateTarget(PropertyKind kind, Name* key,
5811 PropertyAttributes attributes,
5812 DescriptorArray* new_descriptors,
5813 LayoutDescriptor* new_layout_descriptor);
5815 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5817 // Update field type of the given descriptor to new representation and new
5818 // type. The type must be prepared for storing in descriptor array:
5819 // it must be either a simple type or a map wrapped in a weak cell.
5820 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5821 Representation new_representation,
5822 Handle<Object> new_wrapped_type);
5824 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5825 PropertyAttributes attributes);
5826 void PrintGeneralization(FILE* file,
5831 bool constant_to_field,
5832 Representation old_representation,
5833 Representation new_representation,
5834 HeapType* old_field_type,
5835 HeapType* new_field_type);
5837 static const int kFastPropertiesSoftLimit = 12;
5838 static const int kMaxFastProperties = 128;
5840 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5844 // An abstract superclass, a marker class really, for simple structure classes.
5845 // It doesn't carry much functionality but allows struct classes to be
5846 // identified in the type system.
5847 class Struct: public HeapObject {
5849 inline void InitializeBody(int object_size);
5850 DECLARE_CAST(Struct)
5854 // A simple one-element struct, useful where smis need to be boxed.
5855 class Box : public Struct {
5857 // [value]: the boxed contents.
5858 DECL_ACCESSORS(value, Object)
5862 // Dispatched behavior.
5863 DECLARE_PRINTER(Box)
5864 DECLARE_VERIFIER(Box)
5866 static const int kValueOffset = HeapObject::kHeaderSize;
5867 static const int kSize = kValueOffset + kPointerSize;
5870 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5874 // Container for metadata stored on each prototype map.
5875 class PrototypeInfo : public Struct {
5877 static const int UNREGISTERED = -1;
5879 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5880 // or Smi(0) if uninitialized.
5881 DECL_ACCESSORS(prototype_users, Object)
5882 // [registry_slot]: Slot in prototype's user registry where this user
5883 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5884 inline int registry_slot() const;
5885 inline void set_registry_slot(int slot);
5886 // [validity_cell]: Cell containing the validity bit for prototype chains
5887 // going through this object, or Smi(0) if uninitialized.
5888 DECL_ACCESSORS(validity_cell, Object)
5889 // [constructor_name]: User-friendly name of the original constructor.
5890 DECL_ACCESSORS(constructor_name, Object)
5892 DECLARE_CAST(PrototypeInfo)
5894 // Dispatched behavior.
5895 DECLARE_PRINTER(PrototypeInfo)
5896 DECLARE_VERIFIER(PrototypeInfo)
5898 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5899 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5900 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5901 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5902 static const int kSize = kConstructorNameOffset + kPointerSize;
5905 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5909 // Pair used to store both a ScopeInfo and an extension object in the extension
5910 // slot of a block context. Needed in the rare case where a declaration block
5911 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5912 // a sloppy direct eval. (In no other case both are needed at the same time.)
5913 class SloppyBlockWithEvalContextExtension : public Struct {
5915 // [scope_info]: Scope info.
5916 DECL_ACCESSORS(scope_info, ScopeInfo)
5917 // [extension]: Extension object.
5918 DECL_ACCESSORS(extension, JSObject)
5920 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5922 // Dispatched behavior.
5923 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5924 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5926 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5927 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5928 static const int kSize = kExtensionOffset + kPointerSize;
5931 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5935 // Script describes a script which has been added to the VM.
5936 class Script: public Struct {
5945 // Script compilation types.
5946 enum CompilationType {
5947 COMPILATION_TYPE_HOST = 0,
5948 COMPILATION_TYPE_EVAL = 1
5951 // Script compilation state.
5952 enum CompilationState {
5953 COMPILATION_STATE_INITIAL = 0,
5954 COMPILATION_STATE_COMPILED = 1
5957 // [source]: the script source.
5958 DECL_ACCESSORS(source, Object)
5960 // [name]: the script name.
5961 DECL_ACCESSORS(name, Object)
5963 // [id]: the script id.
5964 DECL_ACCESSORS(id, Smi)
5966 // [line_offset]: script line offset in resource from where it was extracted.
5967 DECL_ACCESSORS(line_offset, Smi)
5969 // [column_offset]: script column offset in resource from where it was
5971 DECL_ACCESSORS(column_offset, Smi)
5973 // [context_data]: context data for the context this script was compiled in.
5974 DECL_ACCESSORS(context_data, Object)
5976 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5977 DECL_ACCESSORS(wrapper, HeapObject)
5979 // [type]: the script type.
5980 DECL_ACCESSORS(type, Smi)
5982 // [line_ends]: FixedArray of line ends positions.
5983 DECL_ACCESSORS(line_ends, Object)
5985 // [eval_from_shared]: for eval scripts the shared funcion info for the
5986 // function from which eval was called.
5987 DECL_ACCESSORS(eval_from_shared, Object)
5989 // [eval_from_instructions_offset]: the instruction offset in the code for the
5990 // function from which eval was called where eval was called.
5991 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5993 // [shared_function_infos]: weak fixed array containing all shared
5994 // function infos created from this script.
5995 DECL_ACCESSORS(shared_function_infos, Object)
5997 // [flags]: Holds an exciting bitfield.
5998 DECL_ACCESSORS(flags, Smi)
6000 // [source_url]: sourceURL from magic comment
6001 DECL_ACCESSORS(source_url, Object)
6003 // [source_url]: sourceMappingURL magic comment
6004 DECL_ACCESSORS(source_mapping_url, Object)
6006 // [compilation_type]: how the the script was compiled. Encoded in the
6008 inline CompilationType compilation_type();
6009 inline void set_compilation_type(CompilationType type);
6011 // [compilation_state]: determines whether the script has already been
6012 // compiled. Encoded in the 'flags' field.
6013 inline CompilationState compilation_state();
6014 inline void set_compilation_state(CompilationState state);
6016 // [hide_source]: determines whether the script source can be exposed as
6017 // function source. Encoded in the 'flags' field.
6018 inline bool hide_source();
6019 inline void set_hide_source(bool value);
6021 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6022 // and used by the embedder to make decisions about the script. V8 just passes
6023 // this through. Encoded in the 'flags' field.
6024 inline v8::ScriptOriginOptions origin_options();
6025 inline void set_origin_options(ScriptOriginOptions origin_options);
6027 DECLARE_CAST(Script)
6029 // If script source is an external string, check that the underlying
6030 // resource is accessible. Otherwise, always return true.
6031 inline bool HasValidSource();
6033 // Convert code position into column number.
6034 static int GetColumnNumber(Handle<Script> script, int code_pos);
6036 // Convert code position into (zero-based) line number.
6037 // The non-handlified version does not allocate, but may be much slower.
6038 static int GetLineNumber(Handle<Script> script, int code_pos);
6039 int GetLineNumber(int code_pos);
6041 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6043 // Init line_ends array with code positions of line ends inside script source.
6044 static void InitLineEnds(Handle<Script> script);
6046 // Get the JS object wrapping the given script; create it if none exists.
6047 static Handle<JSObject> GetWrapper(Handle<Script> script);
6049 // Look through the list of existing shared function infos to find one
6050 // that matches the function literal. Return empty handle if not found.
6051 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6053 // Iterate over all script objects on the heap.
6056 explicit Iterator(Isolate* isolate);
6060 WeakFixedArray::Iterator iterator_;
6061 DISALLOW_COPY_AND_ASSIGN(Iterator);
6064 // Dispatched behavior.
6065 DECLARE_PRINTER(Script)
6066 DECLARE_VERIFIER(Script)
6068 static const int kSourceOffset = HeapObject::kHeaderSize;
6069 static const int kNameOffset = kSourceOffset + kPointerSize;
6070 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6071 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6072 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6073 static const int kWrapperOffset = kContextOffset + kPointerSize;
6074 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6075 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6076 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6077 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6078 static const int kEvalFrominstructionsOffsetOffset =
6079 kEvalFromSharedOffset + kPointerSize;
6080 static const int kSharedFunctionInfosOffset =
6081 kEvalFrominstructionsOffsetOffset + kPointerSize;
6082 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6083 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6084 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6085 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6088 int GetLineNumberWithArray(int code_pos);
6090 // Bit positions in the flags field.
6091 static const int kCompilationTypeBit = 0;
6092 static const int kCompilationStateBit = 1;
6093 static const int kHideSourceBit = 2;
6094 static const int kOriginOptionsShift = 3;
6095 static const int kOriginOptionsSize = 3;
6096 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6097 << kOriginOptionsShift;
6099 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6103 // List of builtin functions we want to identify to improve code
6106 // Each entry has a name of a global object property holding an object
6107 // optionally followed by ".prototype", a name of a builtin function
6108 // on the object (the one the id is set for), and a label.
6110 // Installation of ids for the selected builtin functions is handled
6111 // by the bootstrapper.
6112 #define FUNCTIONS_WITH_ID_LIST(V) \
6113 V(Array.prototype, indexOf, ArrayIndexOf) \
6114 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6115 V(Array.prototype, push, ArrayPush) \
6116 V(Array.prototype, pop, ArrayPop) \
6117 V(Array.prototype, shift, ArrayShift) \
6118 V(Function.prototype, apply, FunctionApply) \
6119 V(Function.prototype, call, FunctionCall) \
6120 V(String.prototype, charCodeAt, StringCharCodeAt) \
6121 V(String.prototype, charAt, StringCharAt) \
6122 V(String, fromCharCode, StringFromCharCode) \
6123 V(Math, random, MathRandom) \
6124 V(Math, floor, MathFloor) \
6125 V(Math, round, MathRound) \
6126 V(Math, ceil, MathCeil) \
6127 V(Math, abs, MathAbs) \
6128 V(Math, log, MathLog) \
6129 V(Math, exp, MathExp) \
6130 V(Math, sqrt, MathSqrt) \
6131 V(Math, pow, MathPow) \
6132 V(Math, max, MathMax) \
6133 V(Math, min, MathMin) \
6134 V(Math, cos, MathCos) \
6135 V(Math, sin, MathSin) \
6136 V(Math, tan, MathTan) \
6137 V(Math, acos, MathAcos) \
6138 V(Math, asin, MathAsin) \
6139 V(Math, atan, MathAtan) \
6140 V(Math, atan2, MathAtan2) \
6141 V(Math, imul, MathImul) \
6142 V(Math, clz32, MathClz32) \
6143 V(Math, fround, MathFround)
6145 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6146 V(Atomics, load, AtomicsLoad) \
6147 V(Atomics, store, AtomicsStore)
6149 enum BuiltinFunctionId {
6151 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6153 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6154 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6155 #undef DECLARE_FUNCTION_ID
6156 // Fake id for a special case of Math.pow. Note, it continues the
6157 // list of math functions.
6162 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6163 // that both {code} and {literals} can be NULL to pass search result status.
6164 struct CodeAndLiterals {
6165 Code* code; // Cached optimized code.
6166 FixedArray* literals; // Cached literals array.
6170 // SharedFunctionInfo describes the JSFunction information that can be
6171 // shared by multiple instances of the function.
6172 class SharedFunctionInfo: public HeapObject {
6174 // [name]: Function name.
6175 DECL_ACCESSORS(name, Object)
6177 // [code]: Function code.
6178 DECL_ACCESSORS(code, Code)
6179 inline void ReplaceCode(Code* code);
6181 // [optimized_code_map]: Map from native context to optimized code
6182 // and a shared literals array or Smi(0) if none.
6183 DECL_ACCESSORS(optimized_code_map, Object)
6185 // Returns entry from optimized code map for specified context and OSR entry.
6186 // Note that {code == nullptr} indicates no matching entry has been found,
6187 // whereas {literals == nullptr} indicates the code is context-independent.
6188 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6189 BailoutId osr_ast_id);
6191 // Clear optimized code map.
6192 void ClearOptimizedCodeMap();
6194 // Removed a specific optimized code object from the optimized code map.
6195 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6197 // Trims the optimized code map after entries have been removed.
6198 void TrimOptimizedCodeMap(int shrink_by);
6200 // Add a new entry to the optimized code map for context-independent code.
6201 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6204 // Add a new entry to the optimized code map for context-dependent code.
6205 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6206 Handle<Context> native_context,
6208 Handle<FixedArray> literals,
6209 BailoutId osr_ast_id);
6211 // Set up the link between shared function info and the script. The shared
6212 // function info is added to the list on the script.
6213 static void SetScript(Handle<SharedFunctionInfo> shared,
6214 Handle<Object> script_object);
6216 // Layout description of the optimized code map.
6217 static const int kNextMapIndex = 0;
6218 static const int kSharedCodeIndex = 1;
6219 static const int kEntriesStart = 2;
6220 static const int kContextOffset = 0;
6221 static const int kCachedCodeOffset = 1;
6222 static const int kLiteralsOffset = 2;
6223 static const int kOsrAstIdOffset = 3;
6224 static const int kEntryLength = 4;
6225 static const int kInitialLength = kEntriesStart + kEntryLength;
6227 // [scope_info]: Scope info.
6228 DECL_ACCESSORS(scope_info, ScopeInfo)
6230 // [construct stub]: Code stub for constructing instances of this function.
6231 DECL_ACCESSORS(construct_stub, Code)
6233 // Returns if this function has been compiled to native code yet.
6234 inline bool is_compiled();
6236 // [length]: The function length - usually the number of declared parameters.
6237 // Use up to 2^30 parameters.
6238 inline int length() const;
6239 inline void set_length(int value);
6241 // [internal formal parameter count]: The declared number of parameters.
6242 // For subclass constructors, also includes new.target.
6243 // The size of function's frame is internal_formal_parameter_count + 1.
6244 inline int internal_formal_parameter_count() const;
6245 inline void set_internal_formal_parameter_count(int value);
6247 // Set the formal parameter count so the function code will be
6248 // called without using argument adaptor frames.
6249 inline void DontAdaptArguments();
6251 // [expected_nof_properties]: Expected number of properties for the function.
6252 inline int expected_nof_properties() const;
6253 inline void set_expected_nof_properties(int value);
6255 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6256 // (increasingly) from crankshafted code where sufficient feedback isn't
6258 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6260 // Unconditionally clear the type feedback vector (including vector ICs).
6261 void ClearTypeFeedbackInfo();
6263 // Clear the type feedback vector with a more subtle policy at GC time.
6264 void ClearTypeFeedbackInfoAtGCTime();
6267 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6268 // even if the GC moves this SharedFunctionInfo.
6269 inline int unique_id() const;
6270 inline void set_unique_id(int value);
6273 // [instance class name]: class name for instances.
6274 DECL_ACCESSORS(instance_class_name, Object)
6276 // [function data]: This field holds some additional data for function.
6277 // Currently it has one of:
6278 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6279 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6280 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6281 // In the long run we don't want all functions to have this field but
6282 // we can fix that when we have a better model for storing hidden data
6284 DECL_ACCESSORS(function_data, Object)
6286 inline bool IsApiFunction();
6287 inline FunctionTemplateInfo* get_api_func_data();
6288 inline bool HasBuiltinFunctionId();
6289 inline BuiltinFunctionId builtin_function_id();
6290 inline bool HasBytecodeArray();
6291 inline BytecodeArray* bytecode_array();
6293 // [script info]: Script from which the function originates.
6294 DECL_ACCESSORS(script, Object)
6296 // [num_literals]: Number of literals used by this function.
6297 inline int num_literals() const;
6298 inline void set_num_literals(int value);
6300 // [start_position_and_type]: Field used to store both the source code
6301 // position, whether or not the function is a function expression,
6302 // and whether or not the function is a toplevel function. The two
6303 // least significants bit indicates whether the function is an
6304 // expression and the rest contains the source code position.
6305 inline int start_position_and_type() const;
6306 inline void set_start_position_and_type(int value);
6308 // The function is subject to debugging if a debug info is attached.
6309 inline bool HasDebugInfo();
6310 inline DebugInfo* GetDebugInfo();
6312 // A function has debug code if the compiled code has debug break slots.
6313 inline bool HasDebugCode();
6315 // [debug info]: Debug information.
6316 DECL_ACCESSORS(debug_info, Object)
6318 // [inferred name]: Name inferred from variable or property
6319 // assignment of this function. Used to facilitate debugging and
6320 // profiling of JavaScript code written in OO style, where almost
6321 // all functions are anonymous but are assigned to object
6323 DECL_ACCESSORS(inferred_name, String)
6325 // The function's name if it is non-empty, otherwise the inferred name.
6326 String* DebugName();
6328 // Position of the 'function' token in the script source.
6329 inline int function_token_position() const;
6330 inline void set_function_token_position(int function_token_position);
6332 // Position of this function in the script source.
6333 inline int start_position() const;
6334 inline void set_start_position(int start_position);
6336 // End position of this function in the script source.
6337 inline int end_position() const;
6338 inline void set_end_position(int end_position);
6340 // Is this function a function expression in the source code.
6341 DECL_BOOLEAN_ACCESSORS(is_expression)
6343 // Is this function a top-level function (scripts, evals).
6344 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6346 // Bit field containing various information collected by the compiler to
6347 // drive optimization.
6348 inline int compiler_hints() const;
6349 inline void set_compiler_hints(int value);
6351 inline int ast_node_count() const;
6352 inline void set_ast_node_count(int count);
6354 inline int profiler_ticks() const;
6355 inline void set_profiler_ticks(int ticks);
6357 // Inline cache age is used to infer whether the function survived a context
6358 // disposal or not. In the former case we reset the opt_count.
6359 inline int ic_age();
6360 inline void set_ic_age(int age);
6362 // Indicates if this function can be lazy compiled.
6363 // This is used to determine if we can safely flush code from a function
6364 // when doing GC if we expect that the function will no longer be used.
6365 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6367 // Indicates if this function can be lazy compiled without a context.
6368 // This is used to determine if we can force compilation without reaching
6369 // the function through program execution but through other means (e.g. heap
6370 // iteration by the debugger).
6371 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6373 // Indicates whether optimizations have been disabled for this
6374 // shared function info. If a function is repeatedly optimized or if
6375 // we cannot optimize the function we disable optimization to avoid
6376 // spending time attempting to optimize it again.
6377 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6379 // Indicates the language mode.
6380 inline LanguageMode language_mode();
6381 inline void set_language_mode(LanguageMode language_mode);
6383 // False if the function definitely does not allocate an arguments object.
6384 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6386 // Indicates that this function uses a super property (or an eval that may
6387 // use a super property).
6388 // This is needed to set up the [[HomeObject]] on the function instance.
6389 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6391 // True if the function has any duplicated parameter names.
6392 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6394 // Indicates whether the function is a native function.
6395 // These needs special treatment in .call and .apply since
6396 // null passed as the receiver should not be translated to the
6398 DECL_BOOLEAN_ACCESSORS(native)
6400 // Indicate that this function should always be inlined in optimized code.
6401 DECL_BOOLEAN_ACCESSORS(force_inline)
6403 // Indicates that the function was created by the Function function.
6404 // Though it's anonymous, toString should treat it as if it had the name
6405 // "anonymous". We don't set the name itself so that the system does not
6406 // see a binding for it.
6407 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6409 // Indicates whether the function is a bound function created using
6410 // the bind function.
6411 DECL_BOOLEAN_ACCESSORS(bound)
6413 // Indicates that the function is anonymous (the name field can be set
6414 // through the API, which does not change this flag).
6415 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6417 // Is this a function or top-level/eval code.
6418 DECL_BOOLEAN_ACCESSORS(is_function)
6420 // Indicates that code for this function cannot be compiled with Crankshaft.
6421 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6423 // Indicates that code for this function cannot be flushed.
6424 DECL_BOOLEAN_ACCESSORS(dont_flush)
6426 // Indicates that this function is a generator.
6427 DECL_BOOLEAN_ACCESSORS(is_generator)
6429 // Indicates that this function is an arrow function.
6430 DECL_BOOLEAN_ACCESSORS(is_arrow)
6432 // Indicates that this function is a concise method.
6433 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6435 // Indicates that this function is an accessor (getter or setter).
6436 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6438 // Indicates that this function is a default constructor.
6439 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6441 // Indicates that this function is an asm function.
6442 DECL_BOOLEAN_ACCESSORS(asm_function)
6444 // Indicates that the the shared function info is deserialized from cache.
6445 DECL_BOOLEAN_ACCESSORS(deserialized)
6447 // Indicates that the the shared function info has never been compiled before.
6448 DECL_BOOLEAN_ACCESSORS(never_compiled)
6450 inline FunctionKind kind();
6451 inline void set_kind(FunctionKind kind);
6453 // Indicates whether or not the code in the shared function support
6455 inline bool has_deoptimization_support();
6457 // Enable deoptimization support through recompiled code.
6458 void EnableDeoptimizationSupport(Code* recompiled);
6460 // Disable (further) attempted optimization of all functions sharing this
6461 // shared function info.
6462 void DisableOptimization(BailoutReason reason);
6464 inline BailoutReason disable_optimization_reason();
6466 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6467 // code, returns whether it asserted (i.e., always true if assertions are
6469 bool VerifyBailoutId(BailoutId id);
6471 // [source code]: Source code for the function.
6472 bool HasSourceCode() const;
6473 Handle<Object> GetSourceCode();
6475 // Number of times the function was optimized.
6476 inline int opt_count();
6477 inline void set_opt_count(int opt_count);
6479 // Number of times the function was deoptimized.
6480 inline void set_deopt_count(int value);
6481 inline int deopt_count();
6482 inline void increment_deopt_count();
6484 // Number of time we tried to re-enable optimization after it
6485 // was disabled due to high number of deoptimizations.
6486 inline void set_opt_reenable_tries(int value);
6487 inline int opt_reenable_tries();
6489 inline void TryReenableOptimization();
6491 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6492 inline void set_counters(int value);
6493 inline int counters() const;
6495 // Stores opt_count and bailout_reason as bit-fields.
6496 inline void set_opt_count_and_bailout_reason(int value);
6497 inline int opt_count_and_bailout_reason() const;
6499 inline void set_disable_optimization_reason(BailoutReason reason);
6501 // Tells whether this function should be subject to debugging.
6502 inline bool IsSubjectToDebugging();
6504 // Whether this function is defined in native code or extensions.
6505 inline bool IsBuiltin();
6507 // Check whether or not this function is inlineable.
6508 bool IsInlineable();
6510 // Source size of this function.
6513 // Calculate the instance size.
6514 int CalculateInstanceSize();
6516 // Calculate the number of in-object properties.
6517 int CalculateInObjectProperties();
6519 inline bool has_simple_parameters();
6521 // Initialize a SharedFunctionInfo from a parsed function literal.
6522 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6523 FunctionLiteral* lit);
6525 // Dispatched behavior.
6526 DECLARE_PRINTER(SharedFunctionInfo)
6527 DECLARE_VERIFIER(SharedFunctionInfo)
6529 void ResetForNewContext(int new_ic_age);
6531 // Iterate over all shared function infos that are created from a script.
6532 // That excludes shared function infos created for API functions and C++
6536 explicit Iterator(Isolate* isolate);
6537 SharedFunctionInfo* Next();
6542 Script::Iterator script_iterator_;
6543 WeakFixedArray::Iterator sfi_iterator_;
6544 DisallowHeapAllocation no_gc_;
6545 DISALLOW_COPY_AND_ASSIGN(Iterator);
6548 DECLARE_CAST(SharedFunctionInfo)
6551 static const int kDontAdaptArgumentsSentinel = -1;
6553 // Layout description.
6555 static const int kNameOffset = HeapObject::kHeaderSize;
6556 static const int kCodeOffset = kNameOffset + kPointerSize;
6557 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6558 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6559 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6560 static const int kInstanceClassNameOffset =
6561 kConstructStubOffset + kPointerSize;
6562 static const int kFunctionDataOffset =
6563 kInstanceClassNameOffset + kPointerSize;
6564 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6565 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6566 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6567 static const int kFeedbackVectorOffset =
6568 kInferredNameOffset + kPointerSize;
6570 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6571 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6573 // Just to not break the postmortrem support with conditional offsets
6574 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6575 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6578 #if V8_HOST_ARCH_32_BIT
6580 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6581 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6582 static const int kExpectedNofPropertiesOffset =
6583 kFormalParameterCountOffset + kPointerSize;
6584 static const int kNumLiteralsOffset =
6585 kExpectedNofPropertiesOffset + kPointerSize;
6586 static const int kStartPositionAndTypeOffset =
6587 kNumLiteralsOffset + kPointerSize;
6588 static const int kEndPositionOffset =
6589 kStartPositionAndTypeOffset + kPointerSize;
6590 static const int kFunctionTokenPositionOffset =
6591 kEndPositionOffset + kPointerSize;
6592 static const int kCompilerHintsOffset =
6593 kFunctionTokenPositionOffset + kPointerSize;
6594 static const int kOptCountAndBailoutReasonOffset =
6595 kCompilerHintsOffset + kPointerSize;
6596 static const int kCountersOffset =
6597 kOptCountAndBailoutReasonOffset + kPointerSize;
6598 static const int kAstNodeCountOffset =
6599 kCountersOffset + kPointerSize;
6600 static const int kProfilerTicksOffset =
6601 kAstNodeCountOffset + kPointerSize;
6604 static const int kSize = kProfilerTicksOffset + kPointerSize;
6606 // The only reason to use smi fields instead of int fields
6607 // is to allow iteration without maps decoding during
6608 // garbage collections.
6609 // To avoid wasting space on 64-bit architectures we use
6610 // the following trick: we group integer fields into pairs
6611 // The least significant integer in each pair is shifted left by 1.
6612 // By doing this we guarantee that LSB of each kPointerSize aligned
6613 // word is not set and thus this word cannot be treated as pointer
6614 // to HeapObject during old space traversal.
6615 #if V8_TARGET_LITTLE_ENDIAN
6616 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6617 static const int kFormalParameterCountOffset =
6618 kLengthOffset + kIntSize;
6620 static const int kExpectedNofPropertiesOffset =
6621 kFormalParameterCountOffset + kIntSize;
6622 static const int kNumLiteralsOffset =
6623 kExpectedNofPropertiesOffset + kIntSize;
6625 static const int kEndPositionOffset =
6626 kNumLiteralsOffset + kIntSize;
6627 static const int kStartPositionAndTypeOffset =
6628 kEndPositionOffset + kIntSize;
6630 static const int kFunctionTokenPositionOffset =
6631 kStartPositionAndTypeOffset + kIntSize;
6632 static const int kCompilerHintsOffset =
6633 kFunctionTokenPositionOffset + kIntSize;
6635 static const int kOptCountAndBailoutReasonOffset =
6636 kCompilerHintsOffset + kIntSize;
6637 static const int kCountersOffset =
6638 kOptCountAndBailoutReasonOffset + kIntSize;
6640 static const int kAstNodeCountOffset =
6641 kCountersOffset + kIntSize;
6642 static const int kProfilerTicksOffset =
6643 kAstNodeCountOffset + kIntSize;
6646 static const int kSize = kProfilerTicksOffset + kIntSize;
6648 #elif V8_TARGET_BIG_ENDIAN
6649 static const int kFormalParameterCountOffset =
6650 kLastPointerFieldOffset + kPointerSize;
6651 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6653 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6654 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6656 static const int kStartPositionAndTypeOffset =
6657 kExpectedNofPropertiesOffset + kIntSize;
6658 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6660 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6661 static const int kFunctionTokenPositionOffset =
6662 kCompilerHintsOffset + kIntSize;
6664 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6665 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6667 static const int kProfilerTicksOffset =
6668 kOptCountAndBailoutReasonOffset + kIntSize;
6669 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6672 static const int kSize = kAstNodeCountOffset + kIntSize;
6675 #error Unknown byte ordering
6676 #endif // Big endian
6680 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6682 typedef FixedBodyDescriptor<kNameOffset,
6683 kLastPointerFieldOffset + kPointerSize,
6684 kSize> BodyDescriptor;
6686 // Bit positions in start_position_and_type.
6687 // The source code start position is in the 30 most significant bits of
6688 // the start_position_and_type field.
6689 static const int kIsExpressionBit = 0;
6690 static const int kIsTopLevelBit = 1;
6691 static const int kStartPositionShift = 2;
6692 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6694 // Bit positions in compiler_hints.
6695 enum CompilerHints {
6696 kAllowLazyCompilation,
6697 kAllowLazyCompilationWithoutContext,
6698 kOptimizationDisabled,
6699 kStrictModeFunction,
6700 kStrongModeFunction,
6703 kHasDuplicateParameters,
6708 kNameShouldPrintAsAnonymous,
6715 kIsAccessorFunction,
6716 kIsDefaultConstructor,
6717 kIsSubclassConstructor,
6723 kCompilerHintsCount // Pseudo entry
6725 // Add hints for other modes when they're added.
6726 STATIC_ASSERT(LANGUAGE_END == 3);
6728 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6730 class DeoptCountBits : public BitField<int, 0, 4> {};
6731 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6732 class ICAgeBits : public BitField<int, 22, 8> {};
6734 class OptCountBits : public BitField<int, 0, 22> {};
6735 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6738 #if V8_HOST_ARCH_32_BIT
6739 // On 32 bit platforms, compiler hints is a smi.
6740 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6741 static const int kCompilerHintsSize = kPointerSize;
6743 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6744 static const int kCompilerHintsSmiTagSize = 0;
6745 static const int kCompilerHintsSize = kIntSize;
6748 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6749 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6752 // Constants for optimizing codegen for strict mode function and
6754 // Allows to use byte-width instructions.
6755 static const int kStrictModeBitWithinByte =
6756 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6757 static const int kStrongModeBitWithinByte =
6758 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6760 static const int kNativeBitWithinByte =
6761 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6763 static const int kBoundBitWithinByte =
6764 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6766 #if defined(V8_TARGET_LITTLE_ENDIAN)
6767 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6768 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6769 static const int kStrongModeByteOffset =
6770 kCompilerHintsOffset +
6771 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6772 static const int kNativeByteOffset = kCompilerHintsOffset +
6773 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6774 static const int kBoundByteOffset =
6775 kCompilerHintsOffset +
6776 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6777 #elif defined(V8_TARGET_BIG_ENDIAN)
6778 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6779 (kCompilerHintsSize - 1) -
6780 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6781 static const int kStrongModeByteOffset =
6782 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6783 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6784 static const int kNativeByteOffset = kCompilerHintsOffset +
6785 (kCompilerHintsSize - 1) -
6786 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6787 static const int kBoundByteOffset =
6788 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6789 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6791 #error Unknown byte ordering
6795 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6799 // Printing support.
6800 struct SourceCodeOf {
6801 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6802 : value(v), max_length(max) {}
6803 const SharedFunctionInfo* value;
6808 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6811 class JSGeneratorObject: public JSObject {
6813 // [function]: The function corresponding to this generator object.
6814 DECL_ACCESSORS(function, JSFunction)
6816 // [context]: The context of the suspended computation.
6817 DECL_ACCESSORS(context, Context)
6819 // [receiver]: The receiver of the suspended computation.
6820 DECL_ACCESSORS(receiver, Object)
6822 // [continuation]: Offset into code of continuation.
6824 // A positive offset indicates a suspended generator. The special
6825 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6826 // cannot be resumed.
6827 inline int continuation() const;
6828 inline void set_continuation(int continuation);
6829 inline bool is_closed();
6830 inline bool is_executing();
6831 inline bool is_suspended();
6833 // [operand_stack]: Saved operand stack.
6834 DECL_ACCESSORS(operand_stack, FixedArray)
6836 DECLARE_CAST(JSGeneratorObject)
6838 // Dispatched behavior.
6839 DECLARE_PRINTER(JSGeneratorObject)
6840 DECLARE_VERIFIER(JSGeneratorObject)
6842 // Magic sentinel values for the continuation.
6843 static const int kGeneratorExecuting = -1;
6844 static const int kGeneratorClosed = 0;
6846 // Layout description.
6847 static const int kFunctionOffset = JSObject::kHeaderSize;
6848 static const int kContextOffset = kFunctionOffset + kPointerSize;
6849 static const int kReceiverOffset = kContextOffset + kPointerSize;
6850 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6851 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6852 static const int kSize = kOperandStackOffset + kPointerSize;
6854 // Resume mode, for use by runtime functions.
6855 enum ResumeMode { NEXT, THROW };
6857 // Yielding from a generator returns an object with the following inobject
6858 // properties. See Context::iterator_result_map() for the map.
6859 static const int kResultValuePropertyIndex = 0;
6860 static const int kResultDonePropertyIndex = 1;
6861 static const int kResultPropertyCount = 2;
6863 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6864 static const int kResultDonePropertyOffset =
6865 kResultValuePropertyOffset + kPointerSize;
6866 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6869 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6873 // Representation for module instance objects.
6874 class JSModule: public JSObject {
6876 // [context]: the context holding the module's locals, or undefined if none.
6877 DECL_ACCESSORS(context, Object)
6879 // [scope_info]: Scope info.
6880 DECL_ACCESSORS(scope_info, ScopeInfo)
6882 DECLARE_CAST(JSModule)
6884 // Dispatched behavior.
6885 DECLARE_PRINTER(JSModule)
6886 DECLARE_VERIFIER(JSModule)
6888 // Layout description.
6889 static const int kContextOffset = JSObject::kHeaderSize;
6890 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6891 static const int kSize = kScopeInfoOffset + kPointerSize;
6894 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6898 // JSFunction describes JavaScript functions.
6899 class JSFunction: public JSObject {
6901 // [prototype_or_initial_map]:
6902 DECL_ACCESSORS(prototype_or_initial_map, Object)
6904 // [shared]: The information about the function that
6905 // can be shared by instances.
6906 DECL_ACCESSORS(shared, SharedFunctionInfo)
6908 // [context]: The context for this function.
6909 inline Context* context();
6910 inline void set_context(Object* context);
6911 inline JSObject* global_proxy();
6913 // [code]: The generated code object for this function. Executed
6914 // when the function is invoked, e.g. foo() or new foo(). See
6915 // [[Call]] and [[Construct]] description in ECMA-262, section
6917 inline Code* code();
6918 inline void set_code(Code* code);
6919 inline void set_code_no_write_barrier(Code* code);
6920 inline void ReplaceCode(Code* code);
6922 // Tells whether this function is builtin.
6923 inline bool IsBuiltin();
6925 // Tells whether this function inlines the given shared function info.
6926 bool Inlines(SharedFunctionInfo* candidate);
6928 // Tells whether this function should be subject to debugging.
6929 inline bool IsSubjectToDebugging();
6931 // Tells whether or not the function needs arguments adaption.
6932 inline bool NeedsArgumentsAdaption();
6934 // Tells whether or not this function has been optimized.
6935 inline bool IsOptimized();
6937 // Mark this function for lazy recompilation. The function will be
6938 // recompiled the next time it is executed.
6939 void MarkForOptimization();
6940 void AttemptConcurrentOptimization();
6942 // Tells whether or not the function is already marked for lazy
6944 inline bool IsMarkedForOptimization();
6945 inline bool IsMarkedForConcurrentOptimization();
6947 // Tells whether or not the function is on the concurrent recompilation queue.
6948 inline bool IsInOptimizationQueue();
6950 // Inobject slack tracking is the way to reclaim unused inobject space.
6952 // The instance size is initially determined by adding some slack to
6953 // expected_nof_properties (to allow for a few extra properties added
6954 // after the constructor). There is no guarantee that the extra space
6955 // will not be wasted.
6957 // Here is the algorithm to reclaim the unused inobject space:
6958 // - Detect the first constructor call for this JSFunction.
6959 // When it happens enter the "in progress" state: initialize construction
6960 // counter in the initial_map.
6961 // - While the tracking is in progress create objects filled with
6962 // one_pointer_filler_map instead of undefined_value. This way they can be
6963 // resized quickly and safely.
6964 // - Once enough objects have been created compute the 'slack'
6965 // (traverse the map transition tree starting from the
6966 // initial_map and find the lowest value of unused_property_fields).
6967 // - Traverse the transition tree again and decrease the instance size
6968 // of every map. Existing objects will resize automatically (they are
6969 // filled with one_pointer_filler_map). All further allocations will
6970 // use the adjusted instance size.
6971 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6972 // allocations made using different closures could actually create different
6973 // kind of objects (see prototype inheritance pattern).
6975 // Important: inobject slack tracking is not attempted during the snapshot
6978 // True if the initial_map is set and the object constructions countdown
6979 // counter is not zero.
6980 static const int kGenerousAllocationCount =
6981 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6982 inline bool IsInobjectSlackTrackingInProgress();
6984 // Starts the tracking.
6985 // Initializes object constructions countdown counter in the initial map.
6986 void StartInobjectSlackTracking();
6988 // Completes the tracking.
6989 void CompleteInobjectSlackTracking();
6991 // [literals_or_bindings]: Fixed array holding either
6992 // the materialized literals or the bindings of a bound function.
6994 // If the function contains object, regexp or array literals, the
6995 // literals array prefix contains the object, regexp, and array
6996 // function to be used when creating these literals. This is
6997 // necessary so that we do not dynamically lookup the object, regexp
6998 // or array functions. Performing a dynamic lookup, we might end up
6999 // using the functions from a new context that we should not have
7002 // On bound functions, the array is a (copy-on-write) fixed-array containing
7003 // the function that was bound, bound this-value and any bound
7004 // arguments. Bound functions never contain literals.
7005 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7007 inline FixedArray* literals();
7008 inline void set_literals(FixedArray* literals);
7010 inline FixedArray* function_bindings();
7011 inline void set_function_bindings(FixedArray* bindings);
7013 // The initial map for an object created by this constructor.
7014 inline Map* initial_map();
7015 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7016 Handle<Object> prototype);
7017 inline bool has_initial_map();
7018 static void EnsureHasInitialMap(Handle<JSFunction> function);
7020 // Get and set the prototype property on a JSFunction. If the
7021 // function has an initial map the prototype is set on the initial
7022 // map. Otherwise, the prototype is put in the initial map field
7023 // until an initial map is needed.
7024 inline bool has_prototype();
7025 inline bool has_instance_prototype();
7026 inline Object* prototype();
7027 inline Object* instance_prototype();
7028 static void SetPrototype(Handle<JSFunction> function,
7029 Handle<Object> value);
7030 static void SetInstancePrototype(Handle<JSFunction> function,
7031 Handle<Object> value);
7033 // Creates a new closure for the fucntion with the same bindings,
7034 // bound values, and prototype. An equivalent of spec operations
7035 // ``CloneMethod`` and ``CloneBoundFunction``.
7036 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7038 // After prototype is removed, it will not be created when accessed, and
7039 // [[Construct]] from this function will not be allowed.
7040 bool RemovePrototype();
7041 inline bool should_have_prototype();
7043 // Accessor for this function's initial map's [[class]]
7044 // property. This is primarily used by ECMA native functions. This
7045 // method sets the class_name field of this function's initial map
7046 // to a given value. It creates an initial map if this function does
7047 // not have one. Note that this method does not copy the initial map
7048 // if it has one already, but simply replaces it with the new value.
7049 // Instances created afterwards will have a map whose [[class]] is
7050 // set to 'value', but there is no guarantees on instances created
7052 void SetInstanceClassName(String* name);
7054 // Returns if this function has been compiled to native code yet.
7055 inline bool is_compiled();
7057 // Returns `false` if formal parameters include rest parameters, optional
7058 // parameters, or destructuring parameters.
7059 // TODO(caitp): make this a flag set during parsing
7060 inline bool has_simple_parameters();
7062 // [next_function_link]: Links functions into various lists, e.g. the list
7063 // of optimized functions hanging off the native_context. The CodeFlusher
7064 // uses this link to chain together flushing candidates. Treated weakly
7065 // by the garbage collector.
7066 DECL_ACCESSORS(next_function_link, Object)
7068 // Prints the name of the function using PrintF.
7069 void PrintName(FILE* out = stdout);
7071 DECLARE_CAST(JSFunction)
7073 // Iterates the objects, including code objects indirectly referenced
7074 // through pointers to the first instruction in the code object.
7075 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7077 // Dispatched behavior.
7078 DECLARE_PRINTER(JSFunction)
7079 DECLARE_VERIFIER(JSFunction)
7081 // Returns the number of allocated literals.
7082 inline int NumberOfLiterals();
7084 // Used for flags such as --hydrogen-filter.
7085 bool PassesFilter(const char* raw_filter);
7087 // The function's name if it is configured, otherwise shared function info
7089 static Handle<String> GetDebugName(Handle<JSFunction> function);
7091 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7092 // kSize) is weak and has special handling during garbage collection.
7093 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7094 static const int kPrototypeOrInitialMapOffset =
7095 kCodeEntryOffset + kPointerSize;
7096 static const int kSharedFunctionInfoOffset =
7097 kPrototypeOrInitialMapOffset + kPointerSize;
7098 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7099 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7100 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7101 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7102 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7104 // Layout of the bound-function binding array.
7105 static const int kBoundFunctionIndex = 0;
7106 static const int kBoundThisIndex = 1;
7107 static const int kBoundArgumentsStartIndex = 2;
7110 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7114 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7115 // and the prototype is hidden. JSGlobalProxy always delegates
7116 // property accesses to its prototype if the prototype is not null.
7118 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7120 // Accessing a JSGlobalProxy requires security check.
7122 class JSGlobalProxy : public JSObject {
7124 // [native_context]: the owner native context of this global proxy object.
7125 // It is null value if this object is not used by any context.
7126 DECL_ACCESSORS(native_context, Object)
7128 // [hash]: The hash code property (undefined if not initialized yet).
7129 DECL_ACCESSORS(hash, Object)
7131 DECLARE_CAST(JSGlobalProxy)
7133 inline bool IsDetachedFrom(GlobalObject* global) const;
7135 // Dispatched behavior.
7136 DECLARE_PRINTER(JSGlobalProxy)
7137 DECLARE_VERIFIER(JSGlobalProxy)
7139 // Layout description.
7140 static const int kNativeContextOffset = JSObject::kHeaderSize;
7141 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7142 static const int kSize = kHashOffset + kPointerSize;
7145 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7149 // Common super class for JavaScript global objects and the special
7150 // builtins global objects.
7151 class GlobalObject: public JSObject {
7153 // [builtins]: the object holding the runtime routines written in JS.
7154 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7156 // [native context]: the natives corresponding to this global object.
7157 DECL_ACCESSORS(native_context, Context)
7159 // [global proxy]: the global proxy object of the context
7160 DECL_ACCESSORS(global_proxy, JSObject)
7162 DECLARE_CAST(GlobalObject)
7164 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7166 // Ensure that the global object has a cell for the given property name.
7167 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7170 // Layout description.
7171 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7172 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7173 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7174 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7177 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7181 // JavaScript global object.
7182 class JSGlobalObject: public GlobalObject {
7184 DECLARE_CAST(JSGlobalObject)
7186 inline bool IsDetached();
7188 // Dispatched behavior.
7189 DECLARE_PRINTER(JSGlobalObject)
7190 DECLARE_VERIFIER(JSGlobalObject)
7192 // Layout description.
7193 static const int kSize = GlobalObject::kHeaderSize;
7196 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7200 // Builtins global object which holds the runtime routines written in
7202 class JSBuiltinsObject: public GlobalObject {
7204 DECLARE_CAST(JSBuiltinsObject)
7206 // Dispatched behavior.
7207 DECLARE_PRINTER(JSBuiltinsObject)
7208 DECLARE_VERIFIER(JSBuiltinsObject)
7210 // Layout description.
7211 static const int kSize = GlobalObject::kHeaderSize;
7214 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7218 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7219 class JSValue: public JSObject {
7221 // [value]: the object being wrapped.
7222 DECL_ACCESSORS(value, Object)
7224 DECLARE_CAST(JSValue)
7226 // Dispatched behavior.
7227 DECLARE_PRINTER(JSValue)
7228 DECLARE_VERIFIER(JSValue)
7230 // Layout description.
7231 static const int kValueOffset = JSObject::kHeaderSize;
7232 static const int kSize = kValueOffset + kPointerSize;
7235 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7241 // Representation for JS date objects.
7242 class JSDate: public JSObject {
7244 // If one component is NaN, all of them are, indicating a NaN time value.
7245 // [value]: the time value.
7246 DECL_ACCESSORS(value, Object)
7247 // [year]: caches year. Either undefined, smi, or NaN.
7248 DECL_ACCESSORS(year, Object)
7249 // [month]: caches month. Either undefined, smi, or NaN.
7250 DECL_ACCESSORS(month, Object)
7251 // [day]: caches day. Either undefined, smi, or NaN.
7252 DECL_ACCESSORS(day, Object)
7253 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7254 DECL_ACCESSORS(weekday, Object)
7255 // [hour]: caches hours. Either undefined, smi, or NaN.
7256 DECL_ACCESSORS(hour, Object)
7257 // [min]: caches minutes. Either undefined, smi, or NaN.
7258 DECL_ACCESSORS(min, Object)
7259 // [sec]: caches seconds. Either undefined, smi, or NaN.
7260 DECL_ACCESSORS(sec, Object)
7261 // [cache stamp]: sample of the date cache stamp at the
7262 // moment when chached fields were cached.
7263 DECL_ACCESSORS(cache_stamp, Object)
7265 DECLARE_CAST(JSDate)
7267 // Returns the date field with the specified index.
7268 // See FieldIndex for the list of date fields.
7269 static Object* GetField(Object* date, Smi* index);
7271 void SetValue(Object* value, bool is_value_nan);
7273 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7274 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7275 Handle<JSReceiver> receiver, Handle<Object> hint);
7277 // Dispatched behavior.
7278 DECLARE_PRINTER(JSDate)
7279 DECLARE_VERIFIER(JSDate)
7281 // The order is important. It must be kept in sync with date macros
7292 kFirstUncachedField,
7293 kMillisecond = kFirstUncachedField,
7297 kYearUTC = kFirstUTCField,
7310 // Layout description.
7311 static const int kValueOffset = JSObject::kHeaderSize;
7312 static const int kYearOffset = kValueOffset + kPointerSize;
7313 static const int kMonthOffset = kYearOffset + kPointerSize;
7314 static const int kDayOffset = kMonthOffset + kPointerSize;
7315 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7316 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7317 static const int kMinOffset = kHourOffset + kPointerSize;
7318 static const int kSecOffset = kMinOffset + kPointerSize;
7319 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7320 static const int kSize = kCacheStampOffset + kPointerSize;
7323 inline Object* DoGetField(FieldIndex index);
7325 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7327 // Computes and caches the cacheable fields of the date.
7328 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7331 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7335 // Representation of message objects used for error reporting through
7336 // the API. The messages are formatted in JavaScript so this object is
7337 // a real JavaScript object. The information used for formatting the
7338 // error messages are not directly accessible from JavaScript to
7339 // prevent leaking information to user code called during error
7341 class JSMessageObject: public JSObject {
7343 // [type]: the type of error message.
7344 inline int type() const;
7345 inline void set_type(int value);
7347 // [arguments]: the arguments for formatting the error message.
7348 DECL_ACCESSORS(argument, Object)
7350 // [script]: the script from which the error message originated.
7351 DECL_ACCESSORS(script, Object)
7353 // [stack_frames]: an array of stack frames for this error object.
7354 DECL_ACCESSORS(stack_frames, Object)
7356 // [start_position]: the start position in the script for the error message.
7357 inline int start_position() const;
7358 inline void set_start_position(int value);
7360 // [end_position]: the end position in the script for the error message.
7361 inline int end_position() const;
7362 inline void set_end_position(int value);
7364 DECLARE_CAST(JSMessageObject)
7366 // Dispatched behavior.
7367 DECLARE_PRINTER(JSMessageObject)
7368 DECLARE_VERIFIER(JSMessageObject)
7370 // Layout description.
7371 static const int kTypeOffset = JSObject::kHeaderSize;
7372 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7373 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7374 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7375 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7376 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7377 static const int kSize = kEndPositionOffset + kPointerSize;
7379 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7380 kStackFramesOffset + kPointerSize,
7381 kSize> BodyDescriptor;
7385 // Regular expressions
7386 // The regular expression holds a single reference to a FixedArray in
7387 // the kDataOffset field.
7388 // The FixedArray contains the following data:
7389 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7390 // - reference to the original source string
7391 // - reference to the original flag string
7392 // If it is an atom regexp
7393 // - a reference to a literal string to search for
7394 // If it is an irregexp regexp:
7395 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7396 // used for tracking the last usage (used for code flushing).
7397 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7398 // used for tracking the last usage (used for code flushing)..
7399 // - max number of registers used by irregexp implementations.
7400 // - number of capture registers (output values) of the regexp.
7401 class JSRegExp: public JSObject {
7404 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7405 // ATOM: A simple string to match against using an indexOf operation.
7406 // IRREGEXP: Compiled with Irregexp.
7407 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7408 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7415 UNICODE_ESCAPES = 16
7420 explicit Flags(uint32_t value) : value_(value) { }
7421 bool is_global() { return (value_ & GLOBAL) != 0; }
7422 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7423 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7424 bool is_sticky() { return (value_ & STICKY) != 0; }
7425 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7426 uint32_t value() { return value_; }
7431 DECL_ACCESSORS(data, Object)
7433 inline Type TypeTag();
7434 inline int CaptureCount();
7435 inline Flags GetFlags();
7436 inline String* Pattern();
7437 inline Object* DataAt(int index);
7438 // Set implementation data after the object has been prepared.
7439 inline void SetDataAt(int index, Object* value);
7441 static int code_index(bool is_latin1) {
7443 return kIrregexpLatin1CodeIndex;
7445 return kIrregexpUC16CodeIndex;
7449 static int saved_code_index(bool is_latin1) {
7451 return kIrregexpLatin1CodeSavedIndex;
7453 return kIrregexpUC16CodeSavedIndex;
7457 DECLARE_CAST(JSRegExp)
7459 // Dispatched behavior.
7460 DECLARE_VERIFIER(JSRegExp)
7462 static const int kDataOffset = JSObject::kHeaderSize;
7463 static const int kSize = kDataOffset + kPointerSize;
7465 // Indices in the data array.
7466 static const int kTagIndex = 0;
7467 static const int kSourceIndex = kTagIndex + 1;
7468 static const int kFlagsIndex = kSourceIndex + 1;
7469 static const int kDataIndex = kFlagsIndex + 1;
7470 // The data fields are used in different ways depending on the
7471 // value of the tag.
7472 // Atom regexps (literal strings).
7473 static const int kAtomPatternIndex = kDataIndex;
7475 static const int kAtomDataSize = kAtomPatternIndex + 1;
7477 // Irregexp compiled code or bytecode for Latin1. If compilation
7478 // fails, this fields hold an exception object that should be
7479 // thrown if the regexp is used again.
7480 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7481 // Irregexp compiled code or bytecode for UC16. If compilation
7482 // fails, this fields hold an exception object that should be
7483 // thrown if the regexp is used again.
7484 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7486 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7487 // is a potential candidate for flushing.
7488 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7489 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7490 // a potential candidate for flushing.
7491 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7493 // Maximal number of registers used by either Latin1 or UC16.
7494 // Only used to check that there is enough stack space
7495 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7496 // Number of captures in the compiled regexp.
7497 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7499 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7501 // Offsets directly into the data fixed array.
7502 static const int kDataTagOffset =
7503 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7504 static const int kDataOneByteCodeOffset =
7505 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7506 static const int kDataUC16CodeOffset =
7507 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7508 static const int kIrregexpCaptureCountOffset =
7509 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7511 // In-object fields.
7512 static const int kSourceFieldIndex = 0;
7513 static const int kGlobalFieldIndex = 1;
7514 static const int kIgnoreCaseFieldIndex = 2;
7515 static const int kMultilineFieldIndex = 3;
7516 static const int kLastIndexFieldIndex = 4;
7517 static const int kInObjectFieldCount = 5;
7519 // The uninitialized value for a regexp code object.
7520 static const int kUninitializedValue = -1;
7522 // The compilation error value for the regexp code object. The real error
7523 // object is in the saved code field.
7524 static const int kCompilationErrorValue = -2;
7526 // When we store the sweep generation at which we moved the code from the
7527 // code index to the saved code index we mask it of to be in the [0:255]
7529 static const int kCodeAgeMask = 0xff;
7533 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7535 static inline bool IsMatch(HashTableKey* key, Object* value) {
7536 return key->IsMatch(value);
7539 static inline uint32_t Hash(HashTableKey* key) {
7543 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7544 return key->HashForObject(object);
7547 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7549 static const int kPrefixSize = 0;
7550 static const int kEntrySize = 2;
7554 // This cache is used in two different variants. For regexp caching, it simply
7555 // maps identifying info of the regexp to the cached regexp object. Scripts and
7556 // eval code only gets cached after a second probe for the code object. To do
7557 // so, on first "put" only a hash identifying the source is entered into the
7558 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7559 // such lifetimes get reduced, and removed once they reach zero. If a second put
7560 // is called while such a hash is live in the cache, the hash gets replaced by
7561 // an actual cache entry. Age also removes stale live entries from the cache.
7562 // Such entries are identified by SharedFunctionInfos pointing to either the
7563 // recompilation stub, or to "old" code. This avoids memory leaks due to
7564 // premature caching of scripts and eval strings that are never needed later.
7565 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7566 CompilationCacheShape,
7569 // Find cached value for a string key, otherwise return null.
7570 Handle<Object> Lookup(
7571 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7572 Handle<Object> LookupEval(
7573 Handle<String> src, Handle<SharedFunctionInfo> shared,
7574 LanguageMode language_mode, int scope_position);
7575 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7576 static Handle<CompilationCacheTable> Put(
7577 Handle<CompilationCacheTable> cache, Handle<String> src,
7578 Handle<Context> context, LanguageMode language_mode,
7579 Handle<Object> value);
7580 static Handle<CompilationCacheTable> PutEval(
7581 Handle<CompilationCacheTable> cache, Handle<String> src,
7582 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7583 int scope_position);
7584 static Handle<CompilationCacheTable> PutRegExp(
7585 Handle<CompilationCacheTable> cache, Handle<String> src,
7586 JSRegExp::Flags flags, Handle<FixedArray> value);
7587 void Remove(Object* value);
7589 static const int kHashGenerations = 10;
7591 DECLARE_CAST(CompilationCacheTable)
7594 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7598 class CodeCache: public Struct {
7600 DECL_ACCESSORS(default_cache, FixedArray)
7601 DECL_ACCESSORS(normal_type_cache, Object)
7603 // Add the code object to the cache.
7605 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7607 // Lookup code object in the cache. Returns code object if found and undefined
7609 Object* Lookup(Name* name, Code::Flags flags);
7611 // Get the internal index of a code object in the cache. Returns -1 if the
7612 // code object is not in that cache. This index can be used to later call
7613 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7615 int GetIndex(Object* name, Code* code);
7617 // Remove an object from the cache with the provided internal index.
7618 void RemoveByIndex(Object* name, Code* code, int index);
7620 DECLARE_CAST(CodeCache)
7622 // Dispatched behavior.
7623 DECLARE_PRINTER(CodeCache)
7624 DECLARE_VERIFIER(CodeCache)
7626 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7627 static const int kNormalTypeCacheOffset =
7628 kDefaultCacheOffset + kPointerSize;
7629 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7632 static void UpdateDefaultCache(
7633 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7634 static void UpdateNormalTypeCache(
7635 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7636 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7637 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7639 // Code cache layout of the default cache. Elements are alternating name and
7640 // code objects for non normal load/store/call IC's.
7641 static const int kCodeCacheEntrySize = 2;
7642 static const int kCodeCacheEntryNameOffset = 0;
7643 static const int kCodeCacheEntryCodeOffset = 1;
7645 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7649 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7651 static inline bool IsMatch(HashTableKey* key, Object* value) {
7652 return key->IsMatch(value);
7655 static inline uint32_t Hash(HashTableKey* key) {
7659 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7660 return key->HashForObject(object);
7663 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7665 static const int kPrefixSize = 0;
7666 static const int kEntrySize = 2;
7670 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7671 CodeCacheHashTableShape,
7674 Object* Lookup(Name* name, Code::Flags flags);
7675 static Handle<CodeCacheHashTable> Put(
7676 Handle<CodeCacheHashTable> table,
7680 int GetIndex(Name* name, Code::Flags flags);
7681 void RemoveByIndex(int index);
7683 DECLARE_CAST(CodeCacheHashTable)
7685 // Initial size of the fixed array backing the hash table.
7686 static const int kInitialSize = 64;
7689 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7693 class PolymorphicCodeCache: public Struct {
7695 DECL_ACCESSORS(cache, Object)
7697 static void Update(Handle<PolymorphicCodeCache> cache,
7698 MapHandleList* maps,
7703 // Returns an undefined value if the entry is not found.
7704 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7706 DECLARE_CAST(PolymorphicCodeCache)
7708 // Dispatched behavior.
7709 DECLARE_PRINTER(PolymorphicCodeCache)
7710 DECLARE_VERIFIER(PolymorphicCodeCache)
7712 static const int kCacheOffset = HeapObject::kHeaderSize;
7713 static const int kSize = kCacheOffset + kPointerSize;
7716 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7720 class PolymorphicCodeCacheHashTable
7721 : public HashTable<PolymorphicCodeCacheHashTable,
7722 CodeCacheHashTableShape,
7725 Object* Lookup(MapHandleList* maps, int code_kind);
7727 static Handle<PolymorphicCodeCacheHashTable> Put(
7728 Handle<PolymorphicCodeCacheHashTable> hash_table,
7729 MapHandleList* maps,
7733 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7735 static const int kInitialSize = 64;
7737 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7741 class TypeFeedbackInfo: public Struct {
7743 inline int ic_total_count();
7744 inline void set_ic_total_count(int count);
7746 inline int ic_with_type_info_count();
7747 inline void change_ic_with_type_info_count(int delta);
7749 inline int ic_generic_count();
7750 inline void change_ic_generic_count(int delta);
7752 inline void initialize_storage();
7754 inline void change_own_type_change_checksum();
7755 inline int own_type_change_checksum();
7757 inline void set_inlined_type_change_checksum(int checksum);
7758 inline bool matches_inlined_type_change_checksum(int checksum);
7760 DECLARE_CAST(TypeFeedbackInfo)
7762 // Dispatched behavior.
7763 DECLARE_PRINTER(TypeFeedbackInfo)
7764 DECLARE_VERIFIER(TypeFeedbackInfo)
7766 static const int kStorage1Offset = HeapObject::kHeaderSize;
7767 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7768 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7769 static const int kSize = kStorage3Offset + kPointerSize;
7772 static const int kTypeChangeChecksumBits = 7;
7774 class ICTotalCountField: public BitField<int, 0,
7775 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7776 class OwnTypeChangeChecksum: public BitField<int,
7777 kSmiValueSize - kTypeChangeChecksumBits,
7778 kTypeChangeChecksumBits> {}; // NOLINT
7779 class ICsWithTypeInfoCountField: public BitField<int, 0,
7780 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7781 class InlinedTypeChangeChecksum: public BitField<int,
7782 kSmiValueSize - kTypeChangeChecksumBits,
7783 kTypeChangeChecksumBits> {}; // NOLINT
7785 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7789 enum AllocationSiteMode {
7790 DONT_TRACK_ALLOCATION_SITE,
7791 TRACK_ALLOCATION_SITE,
7792 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7796 class AllocationSite: public Struct {
7798 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7799 static const double kPretenureRatio;
7800 static const int kPretenureMinimumCreated = 100;
7802 // Values for pretenure decision field.
7803 enum PretenureDecision {
7809 kLastPretenureDecisionValue = kZombie
7812 const char* PretenureDecisionName(PretenureDecision decision);
7814 DECL_ACCESSORS(transition_info, Object)
7815 // nested_site threads a list of sites that represent nested literals
7816 // walked in a particular order. So [[1, 2], 1, 2] will have one
7817 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7818 DECL_ACCESSORS(nested_site, Object)
7819 DECL_ACCESSORS(pretenure_data, Smi)
7820 DECL_ACCESSORS(pretenure_create_count, Smi)
7821 DECL_ACCESSORS(dependent_code, DependentCode)
7822 DECL_ACCESSORS(weak_next, Object)
7824 inline void Initialize();
7826 // This method is expensive, it should only be called for reporting.
7827 bool IsNestedSite();
7829 // transition_info bitfields, for constructed array transition info.
7830 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7831 class UnusedBits: public BitField<int, 15, 14> {};
7832 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7834 // Bitfields for pretenure_data
7835 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7836 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7837 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7838 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7840 // Increments the mementos found counter and returns true when the first
7841 // memento was found for a given allocation site.
7842 inline bool IncrementMementoFoundCount();
7844 inline void IncrementMementoCreateCount();
7846 PretenureFlag GetPretenureMode();
7848 void ResetPretenureDecision();
7850 inline PretenureDecision pretenure_decision();
7851 inline void set_pretenure_decision(PretenureDecision decision);
7853 inline bool deopt_dependent_code();
7854 inline void set_deopt_dependent_code(bool deopt);
7856 inline int memento_found_count();
7857 inline void set_memento_found_count(int count);
7859 inline int memento_create_count();
7860 inline void set_memento_create_count(int count);
7862 // The pretenuring decision is made during gc, and the zombie state allows
7863 // us to recognize when an allocation site is just being kept alive because
7864 // a later traversal of new space may discover AllocationMementos that point
7865 // to this AllocationSite.
7866 inline bool IsZombie();
7868 inline bool IsMaybeTenure();
7870 inline void MarkZombie();
7872 inline bool MakePretenureDecision(PretenureDecision current_decision,
7874 bool maximum_size_scavenge);
7876 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7878 inline ElementsKind GetElementsKind();
7879 inline void SetElementsKind(ElementsKind kind);
7881 inline bool CanInlineCall();
7882 inline void SetDoNotInlineCall();
7884 inline bool SitePointsToLiteral();
7886 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7887 ElementsKind to_kind);
7889 DECLARE_PRINTER(AllocationSite)
7890 DECLARE_VERIFIER(AllocationSite)
7892 DECLARE_CAST(AllocationSite)
7893 static inline AllocationSiteMode GetMode(
7894 ElementsKind boilerplate_elements_kind);
7895 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7896 static inline bool CanTrack(InstanceType type);
7898 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7899 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7900 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7901 static const int kPretenureCreateCountOffset =
7902 kPretenureDataOffset + kPointerSize;
7903 static const int kDependentCodeOffset =
7904 kPretenureCreateCountOffset + kPointerSize;
7905 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7906 static const int kSize = kWeakNextOffset + kPointerSize;
7908 // During mark compact we need to take special care for the dependent code
7910 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7911 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7913 // For other visitors, use the fixed body descriptor below.
7914 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7915 kDependentCodeOffset + kPointerSize,
7916 kSize> BodyDescriptor;
7919 inline bool PretenuringDecisionMade();
7921 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7925 class AllocationMemento: public Struct {
7927 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7928 static const int kSize = kAllocationSiteOffset + kPointerSize;
7930 DECL_ACCESSORS(allocation_site, Object)
7932 inline bool IsValid();
7933 inline AllocationSite* GetAllocationSite();
7935 DECLARE_PRINTER(AllocationMemento)
7936 DECLARE_VERIFIER(AllocationMemento)
7938 DECLARE_CAST(AllocationMemento)
7941 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7945 // Representation of a slow alias as part of a sloppy arguments objects.
7946 // For fast aliases (if HasSloppyArgumentsElements()):
7947 // - the parameter map contains an index into the context
7948 // - all attributes of the element have default values
7949 // For slow aliases (if HasDictionaryArgumentsElements()):
7950 // - the parameter map contains no fast alias mapping (i.e. the hole)
7951 // - this struct (in the slow backing store) contains an index into the context
7952 // - all attributes are available as part if the property details
7953 class AliasedArgumentsEntry: public Struct {
7955 inline int aliased_context_slot() const;
7956 inline void set_aliased_context_slot(int count);
7958 DECLARE_CAST(AliasedArgumentsEntry)
7960 // Dispatched behavior.
7961 DECLARE_PRINTER(AliasedArgumentsEntry)
7962 DECLARE_VERIFIER(AliasedArgumentsEntry)
7964 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7965 static const int kSize = kAliasedContextSlot + kPointerSize;
7968 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7972 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7973 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7976 class StringHasher {
7978 explicit inline StringHasher(int length, uint32_t seed);
7980 template <typename schar>
7981 static inline uint32_t HashSequentialString(const schar* chars,
7985 // Reads all the data, even for long strings and computes the utf16 length.
7986 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7988 int* utf16_length_out);
7990 // Calculated hash value for a string consisting of 1 to
7991 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7992 // value is represented decimal value.
7993 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7995 // No string is allowed to have a hash of zero. That value is reserved
7996 // for internal properties. If the hash calculation yields zero then we
7998 static const int kZeroHash = 27;
8000 // Reusable parts of the hashing algorithm.
8001 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8002 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8003 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8004 const uc16* chars, int length));
8005 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8010 // Returns the value to store in the hash field of a string with
8011 // the given length and contents.
8012 uint32_t GetHashField();
8013 // Returns true if the hash of this string can be computed without
8014 // looking at the contents.
8015 inline bool has_trivial_hash();
8016 // Adds a block of characters to the hash.
8017 template<typename Char>
8018 inline void AddCharacters(const Char* chars, int len);
8021 // Add a character to the hash.
8022 inline void AddCharacter(uint16_t c);
8023 // Update index. Returns true if string is still an index.
8024 inline bool UpdateIndex(uint16_t c);
8027 uint32_t raw_running_hash_;
8028 uint32_t array_index_;
8029 bool is_array_index_;
8030 bool is_first_char_;
8031 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8035 class IteratingStringHasher : public StringHasher {
8037 static inline uint32_t Hash(String* string, uint32_t seed);
8038 inline void VisitOneByteString(const uint8_t* chars, int length);
8039 inline void VisitTwoByteString(const uint16_t* chars, int length);
8042 inline IteratingStringHasher(int len, uint32_t seed);
8043 void VisitConsString(ConsString* cons_string);
8044 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8048 // The characteristics of a string are stored in its map. Retrieving these
8049 // few bits of information is moderately expensive, involving two memory
8050 // loads where the second is dependent on the first. To improve efficiency
8051 // the shape of the string is given its own class so that it can be retrieved
8052 // once and used for several string operations. A StringShape is small enough
8053 // to be passed by value and is immutable, but be aware that flattening a
8054 // string can potentially alter its shape. Also be aware that a GC caused by
8055 // something else can alter the shape of a string due to ConsString
8056 // shortcutting. Keeping these restrictions in mind has proven to be error-
8057 // prone and so we no longer put StringShapes in variables unless there is a
8058 // concrete performance benefit at that particular point in the code.
8059 class StringShape BASE_EMBEDDED {
8061 inline explicit StringShape(const String* s);
8062 inline explicit StringShape(Map* s);
8063 inline explicit StringShape(InstanceType t);
8064 inline bool IsSequential();
8065 inline bool IsExternal();
8066 inline bool IsCons();
8067 inline bool IsSliced();
8068 inline bool IsIndirect();
8069 inline bool IsExternalOneByte();
8070 inline bool IsExternalTwoByte();
8071 inline bool IsSequentialOneByte();
8072 inline bool IsSequentialTwoByte();
8073 inline bool IsInternalized();
8074 inline StringRepresentationTag representation_tag();
8075 inline uint32_t encoding_tag();
8076 inline uint32_t full_representation_tag();
8077 inline uint32_t size_tag();
8079 inline uint32_t type() { return type_; }
8080 inline void invalidate() { valid_ = false; }
8081 inline bool valid() { return valid_; }
8083 inline void invalidate() { }
8089 inline void set_valid() { valid_ = true; }
8092 inline void set_valid() { }
8097 // The Name abstract class captures anything that can be used as a property
8098 // name, i.e., strings and symbols. All names store a hash value.
8099 class Name: public HeapObject {
8101 // Get and set the hash field of the name.
8102 inline uint32_t hash_field();
8103 inline void set_hash_field(uint32_t value);
8105 // Tells whether the hash code has been computed.
8106 inline bool HasHashCode();
8108 // Returns a hash value used for the property table
8109 inline uint32_t Hash();
8111 // Equality operations.
8112 inline bool Equals(Name* other);
8113 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8116 inline bool AsArrayIndex(uint32_t* index);
8118 // If the name is private, it can only name own properties.
8119 inline bool IsPrivate();
8121 // If the name is a non-flat string, this method returns a flat version of the
8122 // string. Otherwise it'll just return the input.
8123 static inline Handle<Name> Flatten(Handle<Name> name,
8124 PretenureFlag pretenure = NOT_TENURED);
8126 // Return a string version of this name that is converted according to the
8127 // rules described in ES6 section 9.2.11.
8128 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8132 DECLARE_PRINTER(Name)
8134 void NameShortPrint();
8135 int NameShortPrint(Vector<char> str);
8138 // Layout description.
8139 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8140 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8141 static const int kHashFieldOffset = kHashFieldSlot;
8143 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8145 static const int kSize = kHashFieldSlot + kPointerSize;
8147 // Mask constant for checking if a name has a computed hash code
8148 // and if it is a string that is an array index. The least significant bit
8149 // indicates whether a hash code has been computed. If the hash code has
8150 // been computed the 2nd bit tells whether the string can be used as an
8152 static const int kHashNotComputedMask = 1;
8153 static const int kIsNotArrayIndexMask = 1 << 1;
8154 static const int kNofHashBitFields = 2;
8156 // Shift constant retrieving hash code from hash field.
8157 static const int kHashShift = kNofHashBitFields;
8159 // Only these bits are relevant in the hash, since the top two are shifted
8161 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8163 // Array index strings this short can keep their index in the hash field.
8164 static const int kMaxCachedArrayIndexLength = 7;
8166 // For strings which are array indexes the hash value has the string length
8167 // mixed into the hash, mainly to avoid a hash value of zero which would be
8168 // the case for the string '0'. 24 bits are used for the array index value.
8169 static const int kArrayIndexValueBits = 24;
8170 static const int kArrayIndexLengthBits =
8171 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8173 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8175 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8176 kArrayIndexValueBits> {}; // NOLINT
8177 class ArrayIndexLengthBits : public BitField<unsigned int,
8178 kNofHashBitFields + kArrayIndexValueBits,
8179 kArrayIndexLengthBits> {}; // NOLINT
8181 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8182 // could use a mask to test if the length of string is less than or equal to
8183 // kMaxCachedArrayIndexLength.
8184 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8186 static const unsigned int kContainsCachedArrayIndexMask =
8187 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8188 << ArrayIndexLengthBits::kShift) |
8189 kIsNotArrayIndexMask;
8191 // Value of empty hash field indicating that the hash is not computed.
8192 static const int kEmptyHashField =
8193 kIsNotArrayIndexMask | kHashNotComputedMask;
8196 static inline bool IsHashFieldComputed(uint32_t field);
8199 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8204 class Symbol: public Name {
8206 // [name]: The print name of a symbol, or undefined if none.
8207 DECL_ACCESSORS(name, Object)
8209 DECL_ACCESSORS(flags, Smi)
8211 // [is_private]: Whether this is a private symbol. Private symbols can only
8212 // be used to designate own properties of objects.
8213 DECL_BOOLEAN_ACCESSORS(is_private)
8215 DECLARE_CAST(Symbol)
8217 // Dispatched behavior.
8218 DECLARE_PRINTER(Symbol)
8219 DECLARE_VERIFIER(Symbol)
8221 // Layout description.
8222 static const int kNameOffset = Name::kSize;
8223 static const int kFlagsOffset = kNameOffset + kPointerSize;
8224 static const int kSize = kFlagsOffset + kPointerSize;
8226 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8228 void SymbolShortPrint(std::ostream& os);
8231 static const int kPrivateBit = 0;
8233 const char* PrivateSymbolToName() const;
8236 friend class Name; // For PrivateSymbolToName.
8239 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8245 // The String abstract class captures JavaScript string values:
8248 // 4.3.16 String Value
8249 // A string value is a member of the type String and is a finite
8250 // ordered sequence of zero or more 16-bit unsigned integer values.
8252 // All string values have a length field.
8253 class String: public Name {
8255 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8257 // Array index strings this short can keep their index in the hash field.
8258 static const int kMaxCachedArrayIndexLength = 7;
8260 // For strings which are array indexes the hash value has the string length
8261 // mixed into the hash, mainly to avoid a hash value of zero which would be
8262 // the case for the string '0'. 24 bits are used for the array index value.
8263 static const int kArrayIndexValueBits = 24;
8264 static const int kArrayIndexLengthBits =
8265 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8267 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8269 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8270 kArrayIndexValueBits> {}; // NOLINT
8271 class ArrayIndexLengthBits : public BitField<unsigned int,
8272 kNofHashBitFields + kArrayIndexValueBits,
8273 kArrayIndexLengthBits> {}; // NOLINT
8275 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8276 // could use a mask to test if the length of string is less than or equal to
8277 // kMaxCachedArrayIndexLength.
8278 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8280 static const unsigned int kContainsCachedArrayIndexMask =
8281 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8282 << ArrayIndexLengthBits::kShift) |
8283 kIsNotArrayIndexMask;
8285 class SubStringRange {
8287 explicit inline SubStringRange(String* string, int first = 0,
8290 inline iterator begin();
8291 inline iterator end();
8299 // Representation of the flat content of a String.
8300 // A non-flat string doesn't have flat content.
8301 // A flat string has content that's encoded as a sequence of either
8302 // one-byte chars or two-byte UC16.
8303 // Returned by String::GetFlatContent().
8306 // Returns true if the string is flat and this structure contains content.
8307 bool IsFlat() { return state_ != NON_FLAT; }
8308 // Returns true if the structure contains one-byte content.
8309 bool IsOneByte() { return state_ == ONE_BYTE; }
8310 // Returns true if the structure contains two-byte content.
8311 bool IsTwoByte() { return state_ == TWO_BYTE; }
8313 // Return the one byte content of the string. Only use if IsOneByte()
8315 Vector<const uint8_t> ToOneByteVector() {
8316 DCHECK_EQ(ONE_BYTE, state_);
8317 return Vector<const uint8_t>(onebyte_start, length_);
8319 // Return the two-byte content of the string. Only use if IsTwoByte()
8321 Vector<const uc16> ToUC16Vector() {
8322 DCHECK_EQ(TWO_BYTE, state_);
8323 return Vector<const uc16>(twobyte_start, length_);
8327 DCHECK(i < length_);
8328 DCHECK(state_ != NON_FLAT);
8329 if (state_ == ONE_BYTE) return onebyte_start[i];
8330 return twobyte_start[i];
8333 bool UsesSameString(const FlatContent& other) const {
8334 return onebyte_start == other.onebyte_start;
8338 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8340 // Constructors only used by String::GetFlatContent().
8341 explicit FlatContent(const uint8_t* start, int length)
8342 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8343 explicit FlatContent(const uc16* start, int length)
8344 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8345 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8348 const uint8_t* onebyte_start;
8349 const uc16* twobyte_start;
8354 friend class String;
8355 friend class IterableSubString;
8358 template <typename Char>
8359 INLINE(Vector<const Char> GetCharVector());
8361 // Get and set the length of the string.
8362 inline int length() const;
8363 inline void set_length(int value);
8365 // Get and set the length of the string using acquire loads and release
8367 inline int synchronized_length() const;
8368 inline void synchronized_set_length(int value);
8370 // Returns whether this string has only one-byte chars, i.e. all of them can
8371 // be one-byte encoded. This might be the case even if the string is
8372 // two-byte. Such strings may appear when the embedder prefers
8373 // two-byte external representations even for one-byte data.
8374 inline bool IsOneByteRepresentation() const;
8375 inline bool IsTwoByteRepresentation() const;
8377 // Cons and slices have an encoding flag that may not represent the actual
8378 // encoding of the underlying string. This is taken into account here.
8379 // Requires: this->IsFlat()
8380 inline bool IsOneByteRepresentationUnderneath();
8381 inline bool IsTwoByteRepresentationUnderneath();
8383 // NOTE: this should be considered only a hint. False negatives are
8385 inline bool HasOnlyOneByteChars();
8387 // Get and set individual two byte chars in the string.
8388 inline void Set(int index, uint16_t value);
8389 // Get individual two byte char in the string. Repeated calls
8390 // to this method are not efficient unless the string is flat.
8391 INLINE(uint16_t Get(int index));
8393 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8394 static Handle<Object> ToNumber(Handle<String> subject);
8396 // Flattens the string. Checks first inline to see if it is
8397 // necessary. Does nothing if the string is not a cons string.
8398 // Flattening allocates a sequential string with the same data as
8399 // the given string and mutates the cons string to a degenerate
8400 // form, where the first component is the new sequential string and
8401 // the second component is the empty string. If allocation fails,
8402 // this function returns a failure. If flattening succeeds, this
8403 // function returns the sequential string that is now the first
8404 // component of the cons string.
8406 // Degenerate cons strings are handled specially by the garbage
8407 // collector (see IsShortcutCandidate).
8409 static inline Handle<String> Flatten(Handle<String> string,
8410 PretenureFlag pretenure = NOT_TENURED);
8412 // Tries to return the content of a flat string as a structure holding either
8413 // a flat vector of char or of uc16.
8414 // If the string isn't flat, and therefore doesn't have flat content, the
8415 // returned structure will report so, and can't provide a vector of either
8417 FlatContent GetFlatContent();
8419 // Returns the parent of a sliced string or first part of a flat cons string.
8420 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8421 inline String* GetUnderlying();
8423 // String equality operations.
8424 inline bool Equals(String* other);
8425 inline static bool Equals(Handle<String> one, Handle<String> two);
8426 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8427 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8428 bool IsTwoByteEqualTo(Vector<const uc16> str);
8430 // Return a UTF8 representation of the string. The string is null
8431 // terminated but may optionally contain nulls. Length is returned
8432 // in length_output if length_output is not a null pointer The string
8433 // should be nearly flat, otherwise the performance of this method may
8434 // be very slow (quadratic in the length). Setting robustness_flag to
8435 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8436 // handles unexpected data without causing assert failures and it does not
8437 // do any heap allocations. This is useful when printing stack traces.
8438 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8439 RobustnessFlag robustness_flag,
8440 int offset, int length,
8441 int* length_output = 0);
8442 base::SmartArrayPointer<char> ToCString(
8443 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8444 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8445 int* length_output = 0);
8447 // Return a 16 bit Unicode representation of the string.
8448 // The string should be nearly flat, otherwise the performance of
8449 // of this method may be very bad. Setting robustness_flag to
8450 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8451 // handles unexpected data without causing assert failures and it does not
8452 // do any heap allocations. This is useful when printing stack traces.
8453 base::SmartArrayPointer<uc16> ToWideCString(
8454 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8456 bool ComputeArrayIndex(uint32_t* index);
8459 bool MakeExternal(v8::String::ExternalStringResource* resource);
8460 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8463 inline bool AsArrayIndex(uint32_t* index);
8465 DECLARE_CAST(String)
8467 void PrintOn(FILE* out);
8469 // For use during stack traces. Performs rudimentary sanity check.
8472 // Dispatched behavior.
8473 void StringShortPrint(StringStream* accumulator);
8474 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8475 #if defined(DEBUG) || defined(OBJECT_PRINT)
8476 char* ToAsciiArray();
8478 DECLARE_PRINTER(String)
8479 DECLARE_VERIFIER(String)
8481 inline bool IsFlat();
8483 // Layout description.
8484 static const int kLengthOffset = Name::kSize;
8485 static const int kSize = kLengthOffset + kPointerSize;
8487 // Maximum number of characters to consider when trying to convert a string
8488 // value into an array index.
8489 static const int kMaxArrayIndexSize = 10;
8490 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8493 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8494 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8495 static const int kMaxUtf16CodeUnit = 0xffff;
8496 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8498 // Value of hash field containing computed hash equal to zero.
8499 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8501 // Maximal string length.
8502 static const int kMaxLength = (1 << 28) - 16;
8504 // Max length for computing hash. For strings longer than this limit the
8505 // string length is used as the hash value.
8506 static const int kMaxHashCalcLength = 16383;
8508 // Limit for truncation in short printing.
8509 static const int kMaxShortPrintLength = 1024;
8511 // Support for regular expressions.
8512 const uc16* GetTwoByteData(unsigned start);
8514 // Helper function for flattening strings.
8515 template <typename sinkchar>
8516 static void WriteToFlat(String* source,
8521 // The return value may point to the first aligned word containing the first
8522 // non-one-byte character, rather than directly to the non-one-byte character.
8523 // If the return value is >= the passed length, the entire string was
8525 static inline int NonAsciiStart(const char* chars, int length) {
8526 const char* start = chars;
8527 const char* limit = chars + length;
8529 if (length >= kIntptrSize) {
8530 // Check unaligned bytes.
8531 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8532 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8533 return static_cast<int>(chars - start);
8537 // Check aligned words.
8538 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8539 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8540 while (chars + sizeof(uintptr_t) <= limit) {
8541 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8542 return static_cast<int>(chars - start);
8544 chars += sizeof(uintptr_t);
8547 // Check remaining unaligned bytes.
8548 while (chars < limit) {
8549 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8550 return static_cast<int>(chars - start);
8555 return static_cast<int>(chars - start);
8558 static inline bool IsAscii(const char* chars, int length) {
8559 return NonAsciiStart(chars, length) >= length;
8562 static inline bool IsAscii(const uint8_t* chars, int length) {
8564 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8567 static inline int NonOneByteStart(const uc16* chars, int length) {
8568 const uc16* limit = chars + length;
8569 const uc16* start = chars;
8570 while (chars < limit) {
8571 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8574 return static_cast<int>(chars - start);
8577 static inline bool IsOneByte(const uc16* chars, int length) {
8578 return NonOneByteStart(chars, length) >= length;
8581 template<class Visitor>
8582 static inline ConsString* VisitFlat(Visitor* visitor,
8586 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8587 bool include_ending_line);
8589 // Use the hash field to forward to the canonical internalized string
8590 // when deserializing an internalized string.
8591 inline void SetForwardedInternalizedString(String* string);
8592 inline String* GetForwardedInternalizedString();
8596 friend class StringTableInsertionKey;
8598 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8599 PretenureFlag tenure);
8601 // Slow case of String::Equals. This implementation works on any strings
8602 // but it is most efficient on strings that are almost flat.
8603 bool SlowEquals(String* other);
8605 static bool SlowEquals(Handle<String> one, Handle<String> two);
8607 // Slow case of AsArrayIndex.
8608 bool SlowAsArrayIndex(uint32_t* index);
8610 // Compute and set the hash code.
8611 uint32_t ComputeAndSetHash();
8613 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8617 // The SeqString abstract class captures sequential string values.
8618 class SeqString: public String {
8620 DECLARE_CAST(SeqString)
8622 // Layout description.
8623 static const int kHeaderSize = String::kSize;
8625 // Truncate the string in-place if possible and return the result.
8626 // In case of new_length == 0, the empty string is returned without
8627 // truncating the original string.
8628 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8631 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8635 // The OneByteString class captures sequential one-byte string objects.
8636 // Each character in the OneByteString is an one-byte character.
8637 class SeqOneByteString: public SeqString {
8639 static const bool kHasOneByteEncoding = true;
8641 // Dispatched behavior.
8642 inline uint16_t SeqOneByteStringGet(int index);
8643 inline void SeqOneByteStringSet(int index, uint16_t value);
8645 // Get the address of the characters in this string.
8646 inline Address GetCharsAddress();
8648 inline uint8_t* GetChars();
8650 DECLARE_CAST(SeqOneByteString)
8652 // Garbage collection support. This method is called by the
8653 // garbage collector to compute the actual size of an OneByteString
8655 inline int SeqOneByteStringSize(InstanceType instance_type);
8657 // Computes the size for an OneByteString instance of a given length.
8658 static int SizeFor(int length) {
8659 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8662 // Maximal memory usage for a single sequential one-byte string.
8663 static const int kMaxSize = 512 * MB - 1;
8664 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8667 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8671 // The TwoByteString class captures sequential unicode string objects.
8672 // Each character in the TwoByteString is a two-byte uint16_t.
8673 class SeqTwoByteString: public SeqString {
8675 static const bool kHasOneByteEncoding = false;
8677 // Dispatched behavior.
8678 inline uint16_t SeqTwoByteStringGet(int index);
8679 inline void SeqTwoByteStringSet(int index, uint16_t value);
8681 // Get the address of the characters in this string.
8682 inline Address GetCharsAddress();
8684 inline uc16* GetChars();
8687 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8689 DECLARE_CAST(SeqTwoByteString)
8691 // Garbage collection support. This method is called by the
8692 // garbage collector to compute the actual size of a TwoByteString
8694 inline int SeqTwoByteStringSize(InstanceType instance_type);
8696 // Computes the size for a TwoByteString instance of a given length.
8697 static int SizeFor(int length) {
8698 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8701 // Maximal memory usage for a single sequential two-byte string.
8702 static const int kMaxSize = 512 * MB - 1;
8703 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8704 String::kMaxLength);
8707 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8711 // The ConsString class describes string values built by using the
8712 // addition operator on strings. A ConsString is a pair where the
8713 // first and second components are pointers to other string values.
8714 // One or both components of a ConsString can be pointers to other
8715 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8716 // are non-ConsString string values. The string value represented by
8717 // a ConsString can be obtained by concatenating the leaf string
8718 // values in a left-to-right depth-first traversal of the tree.
8719 class ConsString: public String {
8721 // First string of the cons cell.
8722 inline String* first();
8723 // Doesn't check that the result is a string, even in debug mode. This is
8724 // useful during GC where the mark bits confuse the checks.
8725 inline Object* unchecked_first();
8726 inline void set_first(String* first,
8727 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8729 // Second string of the cons cell.
8730 inline String* second();
8731 // Doesn't check that the result is a string, even in debug mode. This is
8732 // useful during GC where the mark bits confuse the checks.
8733 inline Object* unchecked_second();
8734 inline void set_second(String* second,
8735 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8737 // Dispatched behavior.
8738 uint16_t ConsStringGet(int index);
8740 DECLARE_CAST(ConsString)
8742 // Layout description.
8743 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8744 static const int kSecondOffset = kFirstOffset + kPointerSize;
8745 static const int kSize = kSecondOffset + kPointerSize;
8747 // Minimum length for a cons string.
8748 static const int kMinLength = 13;
8750 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8753 DECLARE_VERIFIER(ConsString)
8756 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8760 // The Sliced String class describes strings that are substrings of another
8761 // sequential string. The motivation is to save time and memory when creating
8762 // a substring. A Sliced String is described as a pointer to the parent,
8763 // the offset from the start of the parent string and the length. Using
8764 // a Sliced String therefore requires unpacking of the parent string and
8765 // adding the offset to the start address. A substring of a Sliced String
8766 // are not nested since the double indirection is simplified when creating
8767 // such a substring.
8768 // Currently missing features are:
8769 // - handling externalized parent strings
8770 // - external strings as parent
8771 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8772 class SlicedString: public String {
8774 inline String* parent();
8775 inline void set_parent(String* parent,
8776 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8777 inline int offset() const;
8778 inline void set_offset(int offset);
8780 // Dispatched behavior.
8781 uint16_t SlicedStringGet(int index);
8783 DECLARE_CAST(SlicedString)
8785 // Layout description.
8786 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8787 static const int kOffsetOffset = kParentOffset + kPointerSize;
8788 static const int kSize = kOffsetOffset + kPointerSize;
8790 // Minimum length for a sliced string.
8791 static const int kMinLength = 13;
8793 typedef FixedBodyDescriptor<kParentOffset,
8794 kOffsetOffset + kPointerSize, kSize>
8797 DECLARE_VERIFIER(SlicedString)
8800 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8804 // The ExternalString class describes string values that are backed by
8805 // a string resource that lies outside the V8 heap. ExternalStrings
8806 // consist of the length field common to all strings, a pointer to the
8807 // external resource. It is important to ensure (externally) that the
8808 // resource is not deallocated while the ExternalString is live in the
8811 // The API expects that all ExternalStrings are created through the
8812 // API. Therefore, ExternalStrings should not be used internally.
8813 class ExternalString: public String {
8815 DECLARE_CAST(ExternalString)
8817 // Layout description.
8818 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8819 static const int kShortSize = kResourceOffset + kPointerSize;
8820 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8821 static const int kSize = kResourceDataOffset + kPointerSize;
8823 static const int kMaxShortLength =
8824 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8826 // Return whether external string is short (data pointer is not cached).
8827 inline bool is_short();
8829 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8832 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8836 // The ExternalOneByteString class is an external string backed by an
8838 class ExternalOneByteString : public ExternalString {
8840 static const bool kHasOneByteEncoding = true;
8842 typedef v8::String::ExternalOneByteStringResource Resource;
8844 // The underlying resource.
8845 inline const Resource* resource();
8846 inline void set_resource(const Resource* buffer);
8848 // Update the pointer cache to the external character array.
8849 // The cached pointer is always valid, as the external character array does =
8850 // not move during lifetime. Deserialization is the only exception, after
8851 // which the pointer cache has to be refreshed.
8852 inline void update_data_cache();
8854 inline const uint8_t* GetChars();
8856 // Dispatched behavior.
8857 inline uint16_t ExternalOneByteStringGet(int index);
8859 DECLARE_CAST(ExternalOneByteString)
8861 // Garbage collection support.
8862 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8864 template <typename StaticVisitor>
8865 inline void ExternalOneByteStringIterateBody();
8868 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8872 // The ExternalTwoByteString class is an external string backed by a UTF-16
8874 class ExternalTwoByteString: public ExternalString {
8876 static const bool kHasOneByteEncoding = false;
8878 typedef v8::String::ExternalStringResource Resource;
8880 // The underlying string resource.
8881 inline const Resource* resource();
8882 inline void set_resource(const Resource* buffer);
8884 // Update the pointer cache to the external character array.
8885 // The cached pointer is always valid, as the external character array does =
8886 // not move during lifetime. Deserialization is the only exception, after
8887 // which the pointer cache has to be refreshed.
8888 inline void update_data_cache();
8890 inline const uint16_t* GetChars();
8892 // Dispatched behavior.
8893 inline uint16_t ExternalTwoByteStringGet(int index);
8896 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8898 DECLARE_CAST(ExternalTwoByteString)
8900 // Garbage collection support.
8901 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8903 template<typename StaticVisitor>
8904 inline void ExternalTwoByteStringIterateBody();
8907 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8911 // Utility superclass for stack-allocated objects that must be updated
8912 // on gc. It provides two ways for the gc to update instances, either
8913 // iterating or updating after gc.
8914 class Relocatable BASE_EMBEDDED {
8916 explicit inline Relocatable(Isolate* isolate);
8917 inline virtual ~Relocatable();
8918 virtual void IterateInstance(ObjectVisitor* v) { }
8919 virtual void PostGarbageCollection() { }
8921 static void PostGarbageCollectionProcessing(Isolate* isolate);
8922 static int ArchiveSpacePerThread();
8923 static char* ArchiveState(Isolate* isolate, char* to);
8924 static char* RestoreState(Isolate* isolate, char* from);
8925 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8926 static void Iterate(ObjectVisitor* v, Relocatable* top);
8927 static char* Iterate(ObjectVisitor* v, char* t);
8935 // A flat string reader provides random access to the contents of a
8936 // string independent of the character width of the string. The handle
8937 // must be valid as long as the reader is being used.
8938 class FlatStringReader : public Relocatable {
8940 FlatStringReader(Isolate* isolate, Handle<String> str);
8941 FlatStringReader(Isolate* isolate, Vector<const char> input);
8942 void PostGarbageCollection();
8943 inline uc32 Get(int index);
8944 template <typename Char>
8945 inline Char Get(int index);
8946 int length() { return length_; }
8955 // This maintains an off-stack representation of the stack frames required
8956 // to traverse a ConsString, allowing an entirely iterative and restartable
8957 // traversal of the entire string
8958 class ConsStringIterator {
8960 inline ConsStringIterator() {}
8961 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8962 Reset(cons_string, offset);
8964 inline void Reset(ConsString* cons_string, int offset = 0) {
8966 // Next will always return NULL.
8967 if (cons_string == NULL) return;
8968 Initialize(cons_string, offset);
8970 // Returns NULL when complete.
8971 inline String* Next(int* offset_out) {
8973 if (depth_ == 0) return NULL;
8974 return Continue(offset_out);
8978 static const int kStackSize = 32;
8979 // Use a mask instead of doing modulo operations for stack wrapping.
8980 static const int kDepthMask = kStackSize-1;
8981 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8982 static inline int OffsetForDepth(int depth);
8984 inline void PushLeft(ConsString* string);
8985 inline void PushRight(ConsString* string);
8986 inline void AdjustMaximumDepth();
8988 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8989 void Initialize(ConsString* cons_string, int offset);
8990 String* Continue(int* offset_out);
8991 String* NextLeaf(bool* blew_stack);
8992 String* Search(int* offset_out);
8994 // Stack must always contain only frames for which right traversal
8995 // has not yet been performed.
8996 ConsString* frames_[kStackSize];
9001 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9005 class StringCharacterStream {
9007 inline StringCharacterStream(String* string,
9009 inline uint16_t GetNext();
9010 inline bool HasMore();
9011 inline void Reset(String* string, int offset = 0);
9012 inline void VisitOneByteString(const uint8_t* chars, int length);
9013 inline void VisitTwoByteString(const uint16_t* chars, int length);
9016 ConsStringIterator iter_;
9019 const uint8_t* buffer8_;
9020 const uint16_t* buffer16_;
9022 const uint8_t* end_;
9023 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9027 template <typename T>
9028 class VectorIterator {
9030 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9031 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9032 T GetNext() { return data_[index_++]; }
9033 bool has_more() { return index_ < data_.length(); }
9035 Vector<const T> data_;
9040 // The Oddball describes objects null, undefined, true, and false.
9041 class Oddball: public HeapObject {
9043 // [to_string]: Cached to_string computed at startup.
9044 DECL_ACCESSORS(to_string, String)
9046 // [to_number]: Cached to_number computed at startup.
9047 DECL_ACCESSORS(to_number, Object)
9049 // [typeof]: Cached type_of computed at startup.
9050 DECL_ACCESSORS(type_of, String)
9052 inline byte kind() const;
9053 inline void set_kind(byte kind);
9055 DECLARE_CAST(Oddball)
9057 // Dispatched behavior.
9058 DECLARE_VERIFIER(Oddball)
9060 // Initialize the fields.
9061 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9062 const char* to_string, Handle<Object> to_number,
9063 const char* type_of, byte kind);
9065 // Layout description.
9066 static const int kToStringOffset = HeapObject::kHeaderSize;
9067 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9068 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9069 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9070 static const int kSize = kKindOffset + kPointerSize;
9072 static const byte kFalse = 0;
9073 static const byte kTrue = 1;
9074 static const byte kNotBooleanMask = ~1;
9075 static const byte kTheHole = 2;
9076 static const byte kNull = 3;
9077 static const byte kArgumentMarker = 4;
9078 static const byte kUndefined = 5;
9079 static const byte kUninitialized = 6;
9080 static const byte kOther = 7;
9081 static const byte kException = 8;
9083 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9084 kSize> BodyDescriptor;
9086 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9087 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9088 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9091 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9095 class Cell: public HeapObject {
9097 // [value]: value of the cell.
9098 DECL_ACCESSORS(value, Object)
9102 static inline Cell* FromValueAddress(Address value) {
9103 Object* result = FromAddress(value - kValueOffset);
9104 return static_cast<Cell*>(result);
9107 inline Address ValueAddress() {
9108 return address() + kValueOffset;
9111 // Dispatched behavior.
9112 DECLARE_PRINTER(Cell)
9113 DECLARE_VERIFIER(Cell)
9115 // Layout description.
9116 static const int kValueOffset = HeapObject::kHeaderSize;
9117 static const int kSize = kValueOffset + kPointerSize;
9119 typedef FixedBodyDescriptor<kValueOffset,
9120 kValueOffset + kPointerSize,
9121 kSize> BodyDescriptor;
9124 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9128 class PropertyCell : public HeapObject {
9130 // [property_details]: details of the global property.
9131 DECL_ACCESSORS(property_details_raw, Object)
9132 // [value]: value of the global property.
9133 DECL_ACCESSORS(value, Object)
9134 // [dependent_code]: dependent code that depends on the type of the global
9136 DECL_ACCESSORS(dependent_code, DependentCode)
9138 inline PropertyDetails property_details();
9139 inline void set_property_details(PropertyDetails details);
9141 PropertyCellConstantType GetConstantType();
9143 // Computes the new type of the cell's contents for the given value, but
9144 // without actually modifying the details.
9145 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9146 Handle<Object> value,
9147 PropertyDetails details);
9148 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9149 Handle<Object> value, PropertyDetails details);
9151 static Handle<PropertyCell> InvalidateEntry(
9152 Handle<GlobalDictionary> dictionary, int entry);
9154 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9155 Handle<Object> new_value);
9157 DECLARE_CAST(PropertyCell)
9159 // Dispatched behavior.
9160 DECLARE_PRINTER(PropertyCell)
9161 DECLARE_VERIFIER(PropertyCell)
9163 // Layout description.
9164 static const int kDetailsOffset = HeapObject::kHeaderSize;
9165 static const int kValueOffset = kDetailsOffset + kPointerSize;
9166 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9167 static const int kSize = kDependentCodeOffset + kPointerSize;
9169 static const int kPointerFieldsBeginOffset = kValueOffset;
9170 static const int kPointerFieldsEndOffset = kSize;
9172 typedef FixedBodyDescriptor<kValueOffset,
9174 kSize> BodyDescriptor;
9177 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9181 class WeakCell : public HeapObject {
9183 inline Object* value() const;
9185 // This should not be called by anyone except GC.
9186 inline void clear();
9188 // This should not be called by anyone except allocator.
9189 inline void initialize(HeapObject* value);
9191 inline bool cleared() const;
9193 DECL_ACCESSORS(next, Object)
9195 inline void clear_next(Heap* heap);
9197 inline bool next_cleared();
9199 DECLARE_CAST(WeakCell)
9201 DECLARE_PRINTER(WeakCell)
9202 DECLARE_VERIFIER(WeakCell)
9204 // Layout description.
9205 static const int kValueOffset = HeapObject::kHeaderSize;
9206 static const int kNextOffset = kValueOffset + kPointerSize;
9207 static const int kSize = kNextOffset + kPointerSize;
9209 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9212 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9216 // The JSProxy describes EcmaScript Harmony proxies
9217 class JSProxy: public JSReceiver {
9219 // [handler]: The handler property.
9220 DECL_ACCESSORS(handler, Object)
9222 // [hash]: The hash code property (undefined if not initialized yet).
9223 DECL_ACCESSORS(hash, Object)
9225 DECLARE_CAST(JSProxy)
9227 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9228 Handle<JSProxy> proxy,
9229 Handle<Object> receiver,
9232 // If the handler defines an accessor property with a setter, invoke it.
9233 // If it defines an accessor property without a setter, or a data property
9234 // that is read-only, throw. In all these cases set '*done' to true,
9235 // otherwise set it to false.
9237 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9238 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9239 Handle<Object> value, LanguageMode language_mode, bool* done);
9241 MUST_USE_RESULT static Maybe<PropertyAttributes>
9242 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9243 Handle<Object> receiver,
9245 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9246 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9247 Handle<Object> value, LanguageMode language_mode);
9249 // Turn the proxy into an (empty) JSObject.
9250 static void Fix(Handle<JSProxy> proxy);
9252 // Initializes the body after the handler slot.
9253 inline void InitializeBody(int object_size, Object* value);
9255 // Invoke a trap by name. If the trap does not exist on this's handler,
9256 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9257 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9258 Handle<JSProxy> proxy,
9260 Handle<Object> derived_trap,
9262 Handle<Object> args[]);
9264 // Dispatched behavior.
9265 DECLARE_PRINTER(JSProxy)
9266 DECLARE_VERIFIER(JSProxy)
9268 // Layout description. We add padding so that a proxy has the same
9269 // size as a virgin JSObject. This is essential for becoming a JSObject
9271 static const int kHandlerOffset = HeapObject::kHeaderSize;
9272 static const int kHashOffset = kHandlerOffset + kPointerSize;
9273 static const int kPaddingOffset = kHashOffset + kPointerSize;
9274 static const int kSize = JSObject::kHeaderSize;
9275 static const int kHeaderSize = kPaddingOffset;
9276 static const int kPaddingSize = kSize - kPaddingOffset;
9278 STATIC_ASSERT(kPaddingSize >= 0);
9280 typedef FixedBodyDescriptor<kHandlerOffset,
9282 kSize> BodyDescriptor;
9285 friend class JSReceiver;
9287 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9288 Handle<JSProxy> proxy, Handle<Name> name);
9290 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9291 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9293 MUST_USE_RESULT Object* GetIdentityHash();
9295 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9297 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9301 class JSFunctionProxy: public JSProxy {
9303 // [call_trap]: The call trap.
9304 DECL_ACCESSORS(call_trap, Object)
9306 // [construct_trap]: The construct trap.
9307 DECL_ACCESSORS(construct_trap, Object)
9309 DECLARE_CAST(JSFunctionProxy)
9311 // Dispatched behavior.
9312 DECLARE_PRINTER(JSFunctionProxy)
9313 DECLARE_VERIFIER(JSFunctionProxy)
9315 // Layout description.
9316 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9317 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9318 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9319 static const int kSize = JSFunction::kSize;
9320 static const int kPaddingSize = kSize - kPaddingOffset;
9322 STATIC_ASSERT(kPaddingSize >= 0);
9324 typedef FixedBodyDescriptor<kHandlerOffset,
9325 kConstructTrapOffset + kPointerSize,
9326 kSize> BodyDescriptor;
9329 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9333 class JSCollection : public JSObject {
9335 // [table]: the backing hash table
9336 DECL_ACCESSORS(table, Object)
9338 static const int kTableOffset = JSObject::kHeaderSize;
9339 static const int kSize = kTableOffset + kPointerSize;
9342 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9346 // The JSSet describes EcmaScript Harmony sets
9347 class JSSet : public JSCollection {
9351 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9352 static void Clear(Handle<JSSet> set);
9354 // Dispatched behavior.
9355 DECLARE_PRINTER(JSSet)
9356 DECLARE_VERIFIER(JSSet)
9359 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9363 // The JSMap describes EcmaScript Harmony maps
9364 class JSMap : public JSCollection {
9368 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9369 static void Clear(Handle<JSMap> map);
9371 // Dispatched behavior.
9372 DECLARE_PRINTER(JSMap)
9373 DECLARE_VERIFIER(JSMap)
9376 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9380 // OrderedHashTableIterator is an iterator that iterates over the keys and
9381 // values of an OrderedHashTable.
9383 // The iterator has a reference to the underlying OrderedHashTable data,
9384 // [table], as well as the current [index] the iterator is at.
9386 // When the OrderedHashTable is rehashed it adds a reference from the old table
9387 // to the new table as well as storing enough data about the changes so that the
9388 // iterator [index] can be adjusted accordingly.
9390 // When the [Next] result from the iterator is requested, the iterator checks if
9391 // there is a newer table that it needs to transition to.
9392 template<class Derived, class TableType>
9393 class OrderedHashTableIterator: public JSObject {
9395 // [table]: the backing hash table mapping keys to values.
9396 DECL_ACCESSORS(table, Object)
9398 // [index]: The index into the data table.
9399 DECL_ACCESSORS(index, Object)
9401 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9402 DECL_ACCESSORS(kind, Object)
9405 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9408 static const int kTableOffset = JSObject::kHeaderSize;
9409 static const int kIndexOffset = kTableOffset + kPointerSize;
9410 static const int kKindOffset = kIndexOffset + kPointerSize;
9411 static const int kSize = kKindOffset + kPointerSize;
9419 // Whether the iterator has more elements. This needs to be called before
9420 // calling |CurrentKey| and/or |CurrentValue|.
9423 // Move the index forward one.
9425 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9428 // Populates the array with the next key and value and then moves the iterator
9430 // This returns the |kind| or 0 if the iterator is already at the end.
9431 Smi* Next(JSArray* value_array);
9433 // Returns the current key of the iterator. This should only be called when
9434 // |HasMore| returns true.
9435 inline Object* CurrentKey();
9438 // Transitions the iterator to the non obsolete backing store. This is a NOP
9439 // if the [table] is not obsolete.
9442 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9446 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9449 // Dispatched behavior.
9450 DECLARE_PRINTER(JSSetIterator)
9451 DECLARE_VERIFIER(JSSetIterator)
9453 DECLARE_CAST(JSSetIterator)
9455 // Called by |Next| to populate the array. This allows the subclasses to
9456 // populate the array differently.
9457 inline void PopulateValueArray(FixedArray* array);
9460 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9464 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9467 // Dispatched behavior.
9468 DECLARE_PRINTER(JSMapIterator)
9469 DECLARE_VERIFIER(JSMapIterator)
9471 DECLARE_CAST(JSMapIterator)
9473 // Called by |Next| to populate the array. This allows the subclasses to
9474 // populate the array differently.
9475 inline void PopulateValueArray(FixedArray* array);
9478 // Returns the current value of the iterator. This should only be called when
9479 // |HasMore| returns true.
9480 inline Object* CurrentValue();
9482 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9486 // Base class for both JSWeakMap and JSWeakSet
9487 class JSWeakCollection: public JSObject {
9489 // [table]: the backing hash table mapping keys to values.
9490 DECL_ACCESSORS(table, Object)
9492 // [next]: linked list of encountered weak maps during GC.
9493 DECL_ACCESSORS(next, Object)
9495 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9496 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9497 Handle<Object> value, int32_t hash);
9498 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9501 static const int kTableOffset = JSObject::kHeaderSize;
9502 static const int kNextOffset = kTableOffset + kPointerSize;
9503 static const int kSize = kNextOffset + kPointerSize;
9506 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9510 // The JSWeakMap describes EcmaScript Harmony weak maps
9511 class JSWeakMap: public JSWeakCollection {
9513 DECLARE_CAST(JSWeakMap)
9515 // Dispatched behavior.
9516 DECLARE_PRINTER(JSWeakMap)
9517 DECLARE_VERIFIER(JSWeakMap)
9520 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9524 // The JSWeakSet describes EcmaScript Harmony weak sets
9525 class JSWeakSet: public JSWeakCollection {
9527 DECLARE_CAST(JSWeakSet)
9529 // Dispatched behavior.
9530 DECLARE_PRINTER(JSWeakSet)
9531 DECLARE_VERIFIER(JSWeakSet)
9534 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9538 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9539 enum class SharedFlag { kNotShared, kShared };
9542 class JSArrayBuffer: public JSObject {
9544 // [backing_store]: backing memory for this array
9545 DECL_ACCESSORS(backing_store, void)
9547 // [byte_length]: length in bytes
9548 DECL_ACCESSORS(byte_length, Object)
9550 inline uint32_t bit_field() const;
9551 inline void set_bit_field(uint32_t bits);
9553 inline bool is_external();
9554 inline void set_is_external(bool value);
9556 inline bool is_neuterable();
9557 inline void set_is_neuterable(bool value);
9559 inline bool was_neutered();
9560 inline void set_was_neutered(bool value);
9562 inline bool is_shared();
9563 inline void set_is_shared(bool value);
9565 DECLARE_CAST(JSArrayBuffer)
9569 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9570 bool is_external, void* data, size_t allocated_length,
9571 SharedFlag shared = SharedFlag::kNotShared);
9573 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9574 Isolate* isolate, size_t allocated_length,
9575 bool initialize = true,
9576 SharedFlag shared = SharedFlag::kNotShared);
9578 // Dispatched behavior.
9579 DECLARE_PRINTER(JSArrayBuffer)
9580 DECLARE_VERIFIER(JSArrayBuffer)
9582 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9583 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9584 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9585 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9586 static const int kBitFieldOffset = kBitFieldSlot;
9588 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9590 static const int kSize = kBitFieldSlot + kPointerSize;
9592 static const int kSizeWithInternalFields =
9593 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9595 class IsExternal : public BitField<bool, 1, 1> {};
9596 class IsNeuterable : public BitField<bool, 2, 1> {};
9597 class WasNeutered : public BitField<bool, 3, 1> {};
9598 class IsShared : public BitField<bool, 4, 1> {};
9601 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9605 class JSArrayBufferView: public JSObject {
9607 // [buffer]: ArrayBuffer that this typed array views.
9608 DECL_ACCESSORS(buffer, Object)
9610 // [byte_offset]: offset of typed array in bytes.
9611 DECL_ACCESSORS(byte_offset, Object)
9613 // [byte_length]: length of typed array in bytes.
9614 DECL_ACCESSORS(byte_length, Object)
9616 DECLARE_CAST(JSArrayBufferView)
9618 DECLARE_VERIFIER(JSArrayBufferView)
9620 inline bool WasNeutered() const;
9622 static const int kBufferOffset = JSObject::kHeaderSize;
9623 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9624 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9625 static const int kViewSize = kByteLengthOffset + kPointerSize;
9629 DECL_ACCESSORS(raw_byte_offset, Object)
9630 DECL_ACCESSORS(raw_byte_length, Object)
9633 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9637 class JSTypedArray: public JSArrayBufferView {
9639 // [length]: length of typed array in elements.
9640 DECL_ACCESSORS(length, Object)
9641 inline uint32_t length_value() const;
9643 DECLARE_CAST(JSTypedArray)
9645 ExternalArrayType type();
9646 size_t element_size();
9648 Handle<JSArrayBuffer> GetBuffer();
9650 // Dispatched behavior.
9651 DECLARE_PRINTER(JSTypedArray)
9652 DECLARE_VERIFIER(JSTypedArray)
9654 static const int kLengthOffset = kViewSize + kPointerSize;
9655 static const int kSize = kLengthOffset + kPointerSize;
9657 static const int kSizeWithInternalFields =
9658 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9661 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9662 Handle<JSTypedArray> typed_array);
9664 DECL_ACCESSORS(raw_length, Object)
9667 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9671 class JSDataView: public JSArrayBufferView {
9673 DECLARE_CAST(JSDataView)
9675 // Dispatched behavior.
9676 DECLARE_PRINTER(JSDataView)
9677 DECLARE_VERIFIER(JSDataView)
9679 static const int kSize = kViewSize;
9681 static const int kSizeWithInternalFields =
9682 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9685 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9689 // Foreign describes objects pointing from JavaScript to C structures.
9690 class Foreign: public HeapObject {
9692 // [address]: field containing the address.
9693 inline Address foreign_address();
9694 inline void set_foreign_address(Address value);
9696 DECLARE_CAST(Foreign)
9698 // Dispatched behavior.
9699 inline void ForeignIterateBody(ObjectVisitor* v);
9701 template<typename StaticVisitor>
9702 inline void ForeignIterateBody();
9704 // Dispatched behavior.
9705 DECLARE_PRINTER(Foreign)
9706 DECLARE_VERIFIER(Foreign)
9708 // Layout description.
9710 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9711 static const int kSize = kForeignAddressOffset + kPointerSize;
9713 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9716 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9720 // The JSArray describes JavaScript Arrays
9721 // Such an array can be in one of two modes:
9722 // - fast, backing storage is a FixedArray and length <= elements.length();
9723 // Please note: push and pop can be used to grow and shrink the array.
9724 // - slow, backing storage is a HashTable with numbers as keys.
9725 class JSArray: public JSObject {
9727 // [length]: The length property.
9728 DECL_ACCESSORS(length, Object)
9730 // Overload the length setter to skip write barrier when the length
9731 // is set to a smi. This matches the set function on FixedArray.
9732 inline void set_length(Smi* length);
9734 static bool HasReadOnlyLength(Handle<JSArray> array);
9735 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9736 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9738 // Initialize the array with the given capacity. The function may
9739 // fail due to out-of-memory situations, but only if the requested
9740 // capacity is non-zero.
9741 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9743 // If the JSArray has fast elements, and new_length would result in
9744 // normalization, returns true.
9745 bool SetLengthWouldNormalize(uint32_t new_length);
9746 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9748 // Initializes the array to a certain length.
9749 inline bool AllowsSetLength();
9751 static void SetLength(Handle<JSArray> array, uint32_t length);
9752 // Same as above but will also queue splice records if |array| is observed.
9753 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9756 // Set the content of the array to the content of storage.
9757 static inline void SetContent(Handle<JSArray> array,
9758 Handle<FixedArrayBase> storage);
9760 DECLARE_CAST(JSArray)
9762 // Dispatched behavior.
9763 DECLARE_PRINTER(JSArray)
9764 DECLARE_VERIFIER(JSArray)
9766 // Number of element slots to pre-allocate for an empty array.
9767 static const int kPreallocatedArrayElements = 4;
9769 // Layout description.
9770 static const int kLengthOffset = JSObject::kHeaderSize;
9771 static const int kSize = kLengthOffset + kPointerSize;
9774 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9778 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9779 Handle<Map> initial_map);
9782 // JSRegExpResult is just a JSArray with a specific initial map.
9783 // This initial map adds in-object properties for "index" and "input"
9784 // properties, as assigned by RegExp.prototype.exec, which allows
9785 // faster creation of RegExp exec results.
9786 // This class just holds constants used when creating the result.
9787 // After creation the result must be treated as a JSArray in all regards.
9788 class JSRegExpResult: public JSArray {
9790 // Offsets of object fields.
9791 static const int kIndexOffset = JSArray::kSize;
9792 static const int kInputOffset = kIndexOffset + kPointerSize;
9793 static const int kSize = kInputOffset + kPointerSize;
9794 // Indices of in-object properties.
9795 static const int kIndexIndex = 0;
9796 static const int kInputIndex = 1;
9798 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9802 class AccessorInfo: public Struct {
9804 DECL_ACCESSORS(name, Object)
9805 DECL_ACCESSORS(flag, Smi)
9806 DECL_ACCESSORS(expected_receiver_type, Object)
9808 inline bool all_can_read();
9809 inline void set_all_can_read(bool value);
9811 inline bool all_can_write();
9812 inline void set_all_can_write(bool value);
9814 inline bool is_special_data_property();
9815 inline void set_is_special_data_property(bool value);
9817 inline PropertyAttributes property_attributes();
9818 inline void set_property_attributes(PropertyAttributes attributes);
9820 // Checks whether the given receiver is compatible with this accessor.
9821 static bool IsCompatibleReceiverMap(Isolate* isolate,
9822 Handle<AccessorInfo> info,
9824 inline bool IsCompatibleReceiver(Object* receiver);
9826 DECLARE_CAST(AccessorInfo)
9828 // Dispatched behavior.
9829 DECLARE_VERIFIER(AccessorInfo)
9831 // Append all descriptors to the array that are not already there.
9832 // Return number added.
9833 static int AppendUnique(Handle<Object> descriptors,
9834 Handle<FixedArray> array,
9835 int valid_descriptors);
9837 static const int kNameOffset = HeapObject::kHeaderSize;
9838 static const int kFlagOffset = kNameOffset + kPointerSize;
9839 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9840 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9843 inline bool HasExpectedReceiverType();
9845 // Bit positions in flag.
9846 static const int kAllCanReadBit = 0;
9847 static const int kAllCanWriteBit = 1;
9848 static const int kSpecialDataProperty = 2;
9849 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9851 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9855 // An accessor must have a getter, but can have no setter.
9857 // When setting a property, V8 searches accessors in prototypes.
9858 // If an accessor was found and it does not have a setter,
9859 // the request is ignored.
9861 // If the accessor in the prototype has the READ_ONLY property attribute, then
9862 // a new value is added to the derived object when the property is set.
9863 // This shadows the accessor in the prototype.
9864 class ExecutableAccessorInfo: public AccessorInfo {
9866 DECL_ACCESSORS(getter, Object)
9867 DECL_ACCESSORS(setter, Object)
9868 DECL_ACCESSORS(data, Object)
9870 DECLARE_CAST(ExecutableAccessorInfo)
9872 // Dispatched behavior.
9873 DECLARE_PRINTER(ExecutableAccessorInfo)
9874 DECLARE_VERIFIER(ExecutableAccessorInfo)
9876 static const int kGetterOffset = AccessorInfo::kSize;
9877 static const int kSetterOffset = kGetterOffset + kPointerSize;
9878 static const int kDataOffset = kSetterOffset + kPointerSize;
9879 static const int kSize = kDataOffset + kPointerSize;
9881 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9884 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9888 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9889 // accessor can either be
9890 // * a pointer to a JavaScript function or proxy: a real accessor
9891 // * undefined: considered an accessor by the spec, too, strangely enough
9892 // * the hole: an accessor which has not been set
9893 // * a pointer to a map: a transition used to ensure map sharing
9894 class AccessorPair: public Struct {
9896 DECL_ACCESSORS(getter, Object)
9897 DECL_ACCESSORS(setter, Object)
9899 DECLARE_CAST(AccessorPair)
9901 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9903 inline Object* get(AccessorComponent component);
9904 inline void set(AccessorComponent component, Object* value);
9906 // Note: Returns undefined instead in case of a hole.
9907 Object* GetComponent(AccessorComponent component);
9909 // Set both components, skipping arguments which are a JavaScript null.
9910 inline void SetComponents(Object* getter, Object* setter);
9912 inline bool Equals(AccessorPair* pair);
9913 inline bool Equals(Object* getter_value, Object* setter_value);
9915 inline bool ContainsAccessor();
9917 // Dispatched behavior.
9918 DECLARE_PRINTER(AccessorPair)
9919 DECLARE_VERIFIER(AccessorPair)
9921 static const int kGetterOffset = HeapObject::kHeaderSize;
9922 static const int kSetterOffset = kGetterOffset + kPointerSize;
9923 static const int kSize = kSetterOffset + kPointerSize;
9926 // Strangely enough, in addition to functions and harmony proxies, the spec
9927 // requires us to consider undefined as a kind of accessor, too:
9929 // Object.defineProperty(obj, "foo", {get: undefined});
9930 // assertTrue("foo" in obj);
9931 inline bool IsJSAccessor(Object* obj);
9933 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9937 class AccessCheckInfo: public Struct {
9939 DECL_ACCESSORS(named_callback, Object)
9940 DECL_ACCESSORS(indexed_callback, Object)
9941 DECL_ACCESSORS(data, Object)
9943 DECLARE_CAST(AccessCheckInfo)
9945 // Dispatched behavior.
9946 DECLARE_PRINTER(AccessCheckInfo)
9947 DECLARE_VERIFIER(AccessCheckInfo)
9949 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9950 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9951 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9952 static const int kSize = kDataOffset + kPointerSize;
9955 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9959 class InterceptorInfo: public Struct {
9961 DECL_ACCESSORS(getter, Object)
9962 DECL_ACCESSORS(setter, Object)
9963 DECL_ACCESSORS(query, Object)
9964 DECL_ACCESSORS(deleter, Object)
9965 DECL_ACCESSORS(enumerator, Object)
9966 DECL_ACCESSORS(data, Object)
9967 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9968 DECL_BOOLEAN_ACCESSORS(all_can_read)
9969 DECL_BOOLEAN_ACCESSORS(non_masking)
9971 inline int flags() const;
9972 inline void set_flags(int flags);
9974 DECLARE_CAST(InterceptorInfo)
9976 // Dispatched behavior.
9977 DECLARE_PRINTER(InterceptorInfo)
9978 DECLARE_VERIFIER(InterceptorInfo)
9980 static const int kGetterOffset = HeapObject::kHeaderSize;
9981 static const int kSetterOffset = kGetterOffset + kPointerSize;
9982 static const int kQueryOffset = kSetterOffset + kPointerSize;
9983 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9984 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9985 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9986 static const int kFlagsOffset = kDataOffset + kPointerSize;
9987 static const int kSize = kFlagsOffset + kPointerSize;
9989 static const int kCanInterceptSymbolsBit = 0;
9990 static const int kAllCanReadBit = 1;
9991 static const int kNonMasking = 2;
9994 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9998 class CallHandlerInfo: public Struct {
10000 DECL_ACCESSORS(callback, Object)
10001 DECL_ACCESSORS(data, Object)
10003 DECLARE_CAST(CallHandlerInfo)
10005 // Dispatched behavior.
10006 DECLARE_PRINTER(CallHandlerInfo)
10007 DECLARE_VERIFIER(CallHandlerInfo)
10009 static const int kCallbackOffset = HeapObject::kHeaderSize;
10010 static const int kDataOffset = kCallbackOffset + kPointerSize;
10011 static const int kSize = kDataOffset + kPointerSize;
10014 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10018 class TemplateInfo: public Struct {
10020 DECL_ACCESSORS(tag, Object)
10021 inline int number_of_properties() const;
10022 inline void set_number_of_properties(int value);
10023 DECL_ACCESSORS(property_list, Object)
10024 DECL_ACCESSORS(property_accessors, Object)
10026 DECLARE_VERIFIER(TemplateInfo)
10028 static const int kTagOffset = HeapObject::kHeaderSize;
10029 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10030 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10031 static const int kPropertyAccessorsOffset =
10032 kPropertyListOffset + kPointerSize;
10033 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10036 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10040 class FunctionTemplateInfo: public TemplateInfo {
10042 DECL_ACCESSORS(serial_number, Object)
10043 DECL_ACCESSORS(call_code, Object)
10044 DECL_ACCESSORS(prototype_template, Object)
10045 DECL_ACCESSORS(parent_template, Object)
10046 DECL_ACCESSORS(named_property_handler, Object)
10047 DECL_ACCESSORS(indexed_property_handler, Object)
10048 DECL_ACCESSORS(instance_template, Object)
10049 DECL_ACCESSORS(class_name, Object)
10050 DECL_ACCESSORS(signature, Object)
10051 DECL_ACCESSORS(instance_call_handler, Object)
10052 DECL_ACCESSORS(access_check_info, Object)
10053 DECL_ACCESSORS(flag, Smi)
10055 inline int length() const;
10056 inline void set_length(int value);
10058 // Following properties use flag bits.
10059 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10060 DECL_BOOLEAN_ACCESSORS(undetectable)
10061 // If the bit is set, object instances created by this function
10062 // requires access check.
10063 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10064 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10065 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10066 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10067 DECL_BOOLEAN_ACCESSORS(instantiated)
10068 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10070 DECLARE_CAST(FunctionTemplateInfo)
10072 // Dispatched behavior.
10073 DECLARE_PRINTER(FunctionTemplateInfo)
10074 DECLARE_VERIFIER(FunctionTemplateInfo)
10076 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10077 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10078 static const int kPrototypeTemplateOffset =
10079 kCallCodeOffset + kPointerSize;
10080 static const int kParentTemplateOffset =
10081 kPrototypeTemplateOffset + kPointerSize;
10082 static const int kNamedPropertyHandlerOffset =
10083 kParentTemplateOffset + kPointerSize;
10084 static const int kIndexedPropertyHandlerOffset =
10085 kNamedPropertyHandlerOffset + kPointerSize;
10086 static const int kInstanceTemplateOffset =
10087 kIndexedPropertyHandlerOffset + kPointerSize;
10088 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10089 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10090 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10091 static const int kAccessCheckInfoOffset =
10092 kInstanceCallHandlerOffset + kPointerSize;
10093 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10094 static const int kLengthOffset = kFlagOffset + kPointerSize;
10095 static const int kSize = kLengthOffset + kPointerSize;
10097 // Returns true if |object| is an instance of this function template.
10098 bool IsTemplateFor(Object* object);
10099 bool IsTemplateFor(Map* map);
10101 // Returns the holder JSObject if the function can legally be called with this
10102 // receiver. Returns Heap::null_value() if the call is illegal.
10103 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10106 // Bit position in the flag, from least significant bit position.
10107 static const int kHiddenPrototypeBit = 0;
10108 static const int kUndetectableBit = 1;
10109 static const int kNeedsAccessCheckBit = 2;
10110 static const int kReadOnlyPrototypeBit = 3;
10111 static const int kRemovePrototypeBit = 4;
10112 static const int kDoNotCacheBit = 5;
10113 static const int kInstantiatedBit = 6;
10114 static const int kAcceptAnyReceiver = 7;
10116 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10120 class ObjectTemplateInfo: public TemplateInfo {
10122 DECL_ACCESSORS(constructor, Object)
10123 DECL_ACCESSORS(internal_field_count, Object)
10125 DECLARE_CAST(ObjectTemplateInfo)
10127 // Dispatched behavior.
10128 DECLARE_PRINTER(ObjectTemplateInfo)
10129 DECLARE_VERIFIER(ObjectTemplateInfo)
10131 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10132 static const int kInternalFieldCountOffset =
10133 kConstructorOffset + kPointerSize;
10134 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10138 class TypeSwitchInfo: public Struct {
10140 DECL_ACCESSORS(types, Object)
10142 DECLARE_CAST(TypeSwitchInfo)
10144 // Dispatched behavior.
10145 DECLARE_PRINTER(TypeSwitchInfo)
10146 DECLARE_VERIFIER(TypeSwitchInfo)
10148 static const int kTypesOffset = Struct::kHeaderSize;
10149 static const int kSize = kTypesOffset + kPointerSize;
10153 // The DebugInfo class holds additional information for a function being
10155 class DebugInfo: public Struct {
10157 // The shared function info for the source being debugged.
10158 DECL_ACCESSORS(shared, SharedFunctionInfo)
10159 // Code object for the patched code. This code object is the code object
10160 // currently active for the function.
10161 DECL_ACCESSORS(code, Code)
10162 // Fixed array holding status information for each active break point.
10163 DECL_ACCESSORS(break_points, FixedArray)
10165 // Check if there is a break point at a code position.
10166 bool HasBreakPoint(int code_position);
10167 // Get the break point info object for a code position.
10168 Object* GetBreakPointInfo(int code_position);
10169 // Clear a break point.
10170 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10172 Handle<Object> break_point_object);
10173 // Set a break point.
10174 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10175 int source_position, int statement_position,
10176 Handle<Object> break_point_object);
10177 // Get the break point objects for a code position.
10178 Handle<Object> GetBreakPointObjects(int code_position);
10179 // Find the break point info holding this break point object.
10180 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10181 Handle<Object> break_point_object);
10182 // Get the number of break points for this function.
10183 int GetBreakPointCount();
10185 DECLARE_CAST(DebugInfo)
10187 // Dispatched behavior.
10188 DECLARE_PRINTER(DebugInfo)
10189 DECLARE_VERIFIER(DebugInfo)
10191 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10192 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10193 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10194 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10196 static const int kEstimatedNofBreakPointsInFunction = 16;
10199 static const int kNoBreakPointInfo = -1;
10201 // Lookup the index in the break_points array for a code position.
10202 int GetBreakPointInfoIndex(int code_position);
10204 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10208 // The BreakPointInfo class holds information for break points set in a
10209 // function. The DebugInfo object holds a BreakPointInfo object for each code
10210 // position with one or more break points.
10211 class BreakPointInfo: public Struct {
10213 // The position in the code for the break point.
10214 DECL_ACCESSORS(code_position, Smi)
10215 // The position in the source for the break position.
10216 DECL_ACCESSORS(source_position, Smi)
10217 // The position in the source for the last statement before this break
10219 DECL_ACCESSORS(statement_position, Smi)
10220 // List of related JavaScript break points.
10221 DECL_ACCESSORS(break_point_objects, Object)
10223 // Removes a break point.
10224 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10225 Handle<Object> break_point_object);
10226 // Set a break point.
10227 static void SetBreakPoint(Handle<BreakPointInfo> info,
10228 Handle<Object> break_point_object);
10229 // Check if break point info has this break point object.
10230 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10231 Handle<Object> break_point_object);
10232 // Get the number of break points for this code position.
10233 int GetBreakPointCount();
10235 DECLARE_CAST(BreakPointInfo)
10237 // Dispatched behavior.
10238 DECLARE_PRINTER(BreakPointInfo)
10239 DECLARE_VERIFIER(BreakPointInfo)
10241 static const int kCodePositionIndex = Struct::kHeaderSize;
10242 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10243 static const int kStatementPositionIndex =
10244 kSourcePositionIndex + kPointerSize;
10245 static const int kBreakPointObjectsIndex =
10246 kStatementPositionIndex + kPointerSize;
10247 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10250 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10254 #undef DECL_BOOLEAN_ACCESSORS
10255 #undef DECL_ACCESSORS
10256 #undef DECLARE_CAST
10257 #undef DECLARE_VERIFIER
10259 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10260 V(kStringTable, "string_table", "(Internalized strings)") \
10261 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10262 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10263 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10264 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10265 V(kTop, "top", "(Isolate)") \
10266 V(kRelocatable, "relocatable", "(Relocatable)") \
10267 V(kDebug, "debug", "(Debugger)") \
10268 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10269 V(kHandleScope, "handlescope", "(Handle scope)") \
10270 V(kBuiltins, "builtins", "(Builtins)") \
10271 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10272 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10273 V(kThreadManager, "threadmanager", "(Thread manager)") \
10274 V(kStrongRoots, "strong roots", "(Strong roots)") \
10275 V(kExtensions, "Extensions", "(Extensions)")
10277 class VisitorSynchronization : public AllStatic {
10279 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10281 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10284 #undef DECLARE_ENUM
10286 static const char* const kTags[kNumberOfSyncTags];
10287 static const char* const kTagNames[kNumberOfSyncTags];
10290 // Abstract base class for visiting, and optionally modifying, the
10291 // pointers contained in Objects. Used in GC and serialization/deserialization.
10292 class ObjectVisitor BASE_EMBEDDED {
10294 virtual ~ObjectVisitor() {}
10296 // Visits a contiguous arrays of pointers in the half-open range
10297 // [start, end). Any or all of the values may be modified on return.
10298 virtual void VisitPointers(Object** start, Object** end) = 0;
10300 // Handy shorthand for visiting a single pointer.
10301 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10303 // Visit weak next_code_link in Code object.
10304 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10306 // To allow lazy clearing of inline caches the visitor has
10307 // a rich interface for iterating over Code objects..
10309 // Visits a code target in the instruction stream.
10310 virtual void VisitCodeTarget(RelocInfo* rinfo);
10312 // Visits a code entry in a JS function.
10313 virtual void VisitCodeEntry(Address entry_address);
10315 // Visits a global property cell reference in the instruction stream.
10316 virtual void VisitCell(RelocInfo* rinfo);
10318 // Visits a runtime entry in the instruction stream.
10319 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10321 // Visits the resource of an one-byte or two-byte string.
10322 virtual void VisitExternalOneByteString(
10323 v8::String::ExternalOneByteStringResource** resource) {}
10324 virtual void VisitExternalTwoByteString(
10325 v8::String::ExternalStringResource** resource) {}
10327 // Visits a debug call target in the instruction stream.
10328 virtual void VisitDebugTarget(RelocInfo* rinfo);
10330 // Visits the byte sequence in a function's prologue that contains information
10331 // about the code's age.
10332 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10334 // Visit pointer embedded into a code object.
10335 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10337 // Visits an external reference embedded into a code object.
10338 virtual void VisitExternalReference(RelocInfo* rinfo);
10340 // Visits an external reference.
10341 virtual void VisitExternalReference(Address* p) {}
10343 // Visits an (encoded) internal reference.
10344 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10346 // Visits a handle that has an embedder-assigned class ID.
10347 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10349 // Intended for serialization/deserialization checking: insert, or
10350 // check for the presence of, a tag at this position in the stream.
10351 // Also used for marking up GC roots in heap snapshots.
10352 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10356 class StructBodyDescriptor : public
10357 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10359 static inline int SizeOf(Map* map, HeapObject* object);
10363 // BooleanBit is a helper class for setting and getting a bit in an
10365 class BooleanBit : public AllStatic {
10367 static inline bool get(Smi* smi, int bit_position) {
10368 return get(smi->value(), bit_position);
10371 static inline bool get(int value, int bit_position) {
10372 return (value & (1 << bit_position)) != 0;
10375 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10376 return Smi::FromInt(set(smi->value(), bit_position, v));
10379 static inline int set(int value, int bit_position, bool v) {
10381 value |= (1 << bit_position);
10383 value &= ~(1 << bit_position);
10389 } } // namespace v8::internal
10391 #endif // V8_OBJECTS_H_