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_ITERATOR_RESULT_TYPE) \
435 V(JS_WEAK_MAP_TYPE) \
436 V(JS_WEAK_SET_TYPE) \
439 V(JS_FUNCTION_TYPE) \
440 V(JS_FUNCTION_PROXY_TYPE) \
442 V(BREAK_POINT_INFO_TYPE)
445 // Since string types are not consecutive, this macro is used to
446 // iterate over them.
447 #define STRING_TYPE_LIST(V) \
448 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
449 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
451 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
452 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
454 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
455 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
456 SlicedOneByteString) \
457 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
459 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
460 external_one_byte_string, ExternalOneByteString) \
461 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
462 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
463 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
464 short_external_string, ShortExternalString) \
465 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
466 short_external_one_byte_string, ShortExternalOneByteString) \
467 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
468 ExternalTwoByteString::kShortSize, \
469 short_external_string_with_one_byte_data, \
470 ShortExternalStringWithOneByteData) \
472 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
473 InternalizedString) \
474 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
475 one_byte_internalized_string, OneByteInternalizedString) \
476 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
477 external_internalized_string, ExternalInternalizedString) \
478 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
479 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
480 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
481 ExternalTwoByteString::kSize, \
482 external_internalized_string_with_one_byte_data, \
483 ExternalInternalizedStringWithOneByteData) \
484 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
485 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
486 ShortExternalInternalizedString) \
487 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
488 ExternalOneByteString::kShortSize, \
489 short_external_one_byte_internalized_string, \
490 ShortExternalOneByteInternalizedString) \
491 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
492 ExternalTwoByteString::kShortSize, \
493 short_external_internalized_string_with_one_byte_data, \
494 ShortExternalInternalizedStringWithOneByteData)
496 // A struct is a simple object a set of object-valued fields. Including an
497 // object type in this causes the compiler to generate most of the boilerplate
498 // code for the class including allocation and garbage collection routines,
499 // casts and predicates. All you need to define is the class, methods and
500 // object verification routines. Easy, no?
502 // Note that for subtle reasons related to the ordering or numerical values of
503 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
505 #define STRUCT_LIST(V) \
507 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
508 executable_accessor_info) \
509 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
510 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
511 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
512 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
513 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
514 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
515 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
516 V(SCRIPT, Script, script) \
517 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
518 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
519 V(CODE_CACHE, CodeCache, code_cache) \
520 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
521 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
522 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
523 V(DEBUG_INFO, DebugInfo, debug_info) \
524 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
525 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
526 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
527 SloppyBlockWithEvalContextExtension, \
528 sloppy_block_with_eval_context_extension)
530 // We use the full 8 bits of the instance_type field to encode heap object
531 // instance types. The high-order bit (bit 7) is set if the object is not a
532 // string, and cleared if it is a string.
533 const uint32_t kIsNotStringMask = 0x80;
534 const uint32_t kStringTag = 0x0;
535 const uint32_t kNotStringTag = 0x80;
537 // Bit 6 indicates that the object is an internalized string (if set) or not.
538 // Bit 7 has to be clear as well.
539 const uint32_t kIsNotInternalizedMask = 0x40;
540 const uint32_t kNotInternalizedTag = 0x40;
541 const uint32_t kInternalizedTag = 0x0;
543 // If bit 7 is clear then bit 2 indicates whether the string consists of
544 // two-byte characters or one-byte characters.
545 const uint32_t kStringEncodingMask = 0x4;
546 const uint32_t kTwoByteStringTag = 0x0;
547 const uint32_t kOneByteStringTag = 0x4;
549 // If bit 7 is clear, the low-order 2 bits indicate the representation
551 const uint32_t kStringRepresentationMask = 0x03;
552 enum StringRepresentationTag {
554 kConsStringTag = 0x1,
555 kExternalStringTag = 0x2,
556 kSlicedStringTag = 0x3
558 const uint32_t kIsIndirectStringMask = 0x1;
559 const uint32_t kIsIndirectStringTag = 0x1;
560 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
561 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
562 STATIC_ASSERT((kConsStringTag &
563 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
564 STATIC_ASSERT((kSlicedStringTag &
565 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
567 // Use this mask to distinguish between cons and slice only after making
568 // sure that the string is one of the two (an indirect string).
569 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
570 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
572 // If bit 7 is clear, then bit 3 indicates whether this two-byte
573 // string actually contains one byte data.
574 const uint32_t kOneByteDataHintMask = 0x08;
575 const uint32_t kOneByteDataHintTag = 0x08;
577 // If bit 7 is clear and string representation indicates an external string,
578 // then bit 4 indicates whether the data pointer is cached.
579 const uint32_t kShortExternalStringMask = 0x10;
580 const uint32_t kShortExternalStringTag = 0x10;
583 // A ConsString with an empty string as the right side is a candidate
584 // for being shortcut by the garbage collector. We don't allocate any
585 // non-flat internalized strings, so we do not shortcut them thereby
586 // avoiding turning internalized strings into strings. The bit-masks
587 // below contain the internalized bit as additional safety.
588 // See heap.cc, mark-compact.cc and objects-visiting.cc.
589 const uint32_t kShortcutTypeMask =
591 kIsNotInternalizedMask |
592 kStringRepresentationMask;
593 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
595 static inline bool IsShortcutCandidate(int type) {
596 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
602 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
603 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
604 ONE_BYTE_INTERNALIZED_STRING_TYPE =
605 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
606 EXTERNAL_INTERNALIZED_STRING_TYPE =
607 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
608 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
609 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
610 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
611 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
613 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
614 kShortExternalStringTag |
616 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
617 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
619 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
620 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
621 kShortExternalStringTag | kInternalizedTag,
622 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
623 ONE_BYTE_STRING_TYPE =
624 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
625 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
626 CONS_ONE_BYTE_STRING_TYPE =
627 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
629 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
630 SLICED_ONE_BYTE_STRING_TYPE =
631 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
632 EXTERNAL_STRING_TYPE =
633 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
634 EXTERNAL_ONE_BYTE_STRING_TYPE =
635 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
636 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
637 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
639 SHORT_EXTERNAL_STRING_TYPE =
640 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
641 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
642 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
643 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
644 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
648 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
650 // Other primitives (cannot contain non-map-word pointers to heap objects).
653 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
655 // Objects allocated in their own spaces (never in new space).
659 // "Data", objects that cannot contain non-map-word pointers to heap
661 MUTABLE_HEAP_NUMBER_TYPE,
666 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
667 FIXED_UINT8_ARRAY_TYPE,
668 FIXED_INT16_ARRAY_TYPE,
669 FIXED_UINT16_ARRAY_TYPE,
670 FIXED_INT32_ARRAY_TYPE,
671 FIXED_UINT32_ARRAY_TYPE,
672 FIXED_FLOAT32_ARRAY_TYPE,
673 FIXED_FLOAT64_ARRAY_TYPE,
674 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
675 FIXED_DOUBLE_ARRAY_TYPE,
676 FILLER_TYPE, // LAST_DATA_TYPE
679 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
680 DECLARED_ACCESSOR_INFO_TYPE,
681 EXECUTABLE_ACCESSOR_INFO_TYPE,
683 ACCESS_CHECK_INFO_TYPE,
684 INTERCEPTOR_INFO_TYPE,
685 CALL_HANDLER_INFO_TYPE,
686 FUNCTION_TEMPLATE_INFO_TYPE,
687 OBJECT_TEMPLATE_INFO_TYPE,
689 TYPE_SWITCH_INFO_TYPE,
690 ALLOCATION_SITE_TYPE,
691 ALLOCATION_MEMENTO_TYPE,
694 POLYMORPHIC_CODE_CACHE_TYPE,
695 TYPE_FEEDBACK_INFO_TYPE,
696 ALIASED_ARGUMENTS_ENTRY_TYPE,
699 BREAK_POINT_INFO_TYPE,
701 SHARED_FUNCTION_INFO_TYPE,
706 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
708 // All the following types are subtypes of JSReceiver, which corresponds to
709 // objects in the JS sense. The first and the last type in this range are
710 // the two forms of function. This organization enables using the same
711 // compares for checking the JS_RECEIVER/SPEC_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,
732 JS_ITERATOR_RESULT_TYPE,
736 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
740 LAST_TYPE = JS_FUNCTION_TYPE,
741 FIRST_NAME_TYPE = FIRST_TYPE,
742 LAST_NAME_TYPE = SYMBOL_TYPE,
743 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
744 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
745 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
746 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
747 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
748 // Boundaries for testing for a fixed typed array.
749 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
750 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
751 // Boundary for promotion to old space.
752 LAST_DATA_TYPE = FILLER_TYPE,
753 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
754 // Note that there is no range for JSObject or JSProxy, since their subtypes
755 // are not continuous in this enum! The enum ranges instead reflect the
756 // external class names, where proxies are treated as either ordinary objects,
758 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
759 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
760 // Boundaries for testing the types represented as JSObject
761 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
762 LAST_JS_OBJECT_TYPE = LAST_TYPE,
763 // Boundaries for testing the types represented as JSProxy
764 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
765 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
766 // Boundaries for testing whether the type is a JavaScript object.
767 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
768 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE
771 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
772 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
773 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
774 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
777 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
778 V(FAST_ELEMENTS_SUB_TYPE) \
779 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
780 V(FAST_PROPERTIES_SUB_TYPE) \
781 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
782 V(MAP_CODE_CACHE_SUB_TYPE) \
783 V(SCOPE_INFO_SUB_TYPE) \
784 V(STRING_TABLE_SUB_TYPE) \
785 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
786 V(TRANSITION_ARRAY_SUB_TYPE)
788 enum FixedArraySubInstanceType {
789 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
790 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
791 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
792 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
805 #define DECL_BOOLEAN_ACCESSORS(name) \
806 inline bool name() const; \
807 inline void set_##name(bool value); \
810 #define DECL_ACCESSORS(name, type) \
811 inline type* name() const; \
812 inline void set_##name(type* value, \
813 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
816 #define DECLARE_CAST(type) \
817 INLINE(static type* cast(Object* object)); \
818 INLINE(static const type* cast(const Object* object));
822 class AllocationSite;
823 class AllocationSiteCreationContext;
824 class AllocationSiteUsageContext;
827 class ElementsAccessor;
828 class FixedArrayBase;
829 class FunctionLiteral;
831 class JSBuiltinsObject;
832 class LayoutDescriptor;
833 class LookupIterator;
834 class ObjectHashTable;
837 class SafepointEntry;
838 class SharedFunctionInfo;
840 class TypeFeedbackInfo;
841 class TypeFeedbackVector;
844 // We cannot just say "class HeapType;" if it is created from a template... =8-?
845 template<class> class TypeImpl;
846 struct HeapTypeConfig;
847 typedef TypeImpl<HeapTypeConfig> HeapType;
850 // A template-ized version of the IsXXX functions.
851 template <class C> inline bool Is(Object* obj);
854 #define DECLARE_VERIFIER(Name) void Name##Verify();
856 #define DECLARE_VERIFIER(Name)
860 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
862 #define DECLARE_PRINTER(Name)
866 #define OBJECT_TYPE_LIST(V) \
871 #define HEAP_OBJECT_TYPE_LIST(V) \
873 V(MutableHeapNumber) \
892 V(ExternalTwoByteString) \
893 V(ExternalOneByteString) \
894 V(SeqTwoByteString) \
895 V(SeqOneByteString) \
896 V(InternalizedString) \
899 V(FixedTypedArrayBase) \
902 V(FixedUint16Array) \
904 V(FixedUint32Array) \
906 V(FixedFloat32Array) \
907 V(FixedFloat64Array) \
908 V(FixedUint8ClampedArray) \
914 V(JSContextExtensionObject) \
915 V(JSGeneratorObject) \
917 V(LayoutDescriptor) \
921 V(TypeFeedbackVector) \
922 V(DeoptimizationInputData) \
923 V(DeoptimizationOutputData) \
927 V(FixedDoubleArray) \
931 V(ScriptContextTable) \
937 V(SharedFunctionInfo) \
946 V(JSArrayBufferView) \
955 V(JSIteratorResult) \
956 V(JSWeakCollection) \
963 V(NormalizedMapCache) \
964 V(CompilationCacheTable) \
965 V(CodeCacheHashTable) \
966 V(PolymorphicCodeCacheHashTable) \
971 V(JSBuiltinsObject) \
973 V(UndetectableObject) \
974 V(AccessCheckNeeded) \
982 // Object is the abstract superclass for all classes in the
984 // Object does not use any virtual functions to avoid the
985 // allocation of the C++ vtable.
986 // Since both Smi and HeapObject are subclasses of Object no
987 // data members can be present in Object.
991 bool IsObject() const { return true; }
993 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
994 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
995 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
996 #undef IS_TYPE_FUNCTION_DECL
998 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
999 // a keyed store is of the form a[expression] = foo.
1000 enum StoreFromKeyed {
1001 MAY_BE_STORE_FROM_KEYED,
1002 CERTAINLY_NOT_STORE_FROM_KEYED
1005 INLINE(bool IsFixedArrayBase() const);
1006 INLINE(bool IsExternal() const);
1007 INLINE(bool IsAccessorInfo() const);
1009 INLINE(bool IsStruct() const);
1010 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1011 INLINE(bool Is##Name() const);
1012 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1013 #undef DECLARE_STRUCT_PREDICATE
1015 // ES6, section 7.2.3 IsCallable.
1016 INLINE(bool IsCallable() const);
1018 INLINE(bool IsSpecObject()) const;
1019 // TODO(rossberg): IsSpecFunction should be removed in favor of IsCallable.
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 static bool IsPromise(Handle<Object> object);
1031 INLINE(bool IsUndefined() const);
1032 INLINE(bool IsNull() const);
1033 INLINE(bool IsTheHole() const);
1034 INLINE(bool IsException() const);
1035 INLINE(bool IsUninitialized() const);
1036 INLINE(bool IsTrue() const);
1037 INLINE(bool IsFalse() const);
1038 INLINE(bool IsArgumentsMarker() const);
1040 // Filler objects (fillers and free space objects).
1041 INLINE(bool IsFiller() const);
1043 // Extract the number.
1044 inline double Number();
1045 INLINE(bool IsNaN() const);
1046 INLINE(bool IsMinusZero() const);
1047 bool ToInt32(int32_t* value);
1048 bool ToUint32(uint32_t* value);
1050 inline Representation OptimalRepresentation();
1052 inline ElementsKind OptimalElementsKind();
1054 inline bool FitsRepresentation(Representation representation);
1056 // Checks whether two valid primitive encodings of a property name resolve to
1057 // the same logical property. E.g., the smi 1, the string "1" and the double
1058 // 1 all refer to the same property, so this helper will return true.
1059 inline bool KeyEquals(Object* other);
1061 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1063 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1064 Handle<Object> object,
1065 Representation representation);
1067 inline static Handle<Object> WrapForRead(Isolate* isolate,
1068 Handle<Object> object,
1069 Representation representation);
1071 // Returns true if the object is of the correct type to be used as a
1072 // implementation of a JSObject's elements.
1073 inline bool HasValidElements();
1075 inline bool HasSpecificClassOf(String* name);
1077 bool BooleanValue(); // ECMA-262 9.2.
1079 // ES6 section 7.2.13 Strict Equality Comparison
1080 bool StrictEquals(Object* that);
1082 // Convert to a JSObject if needed.
1083 // native_context is used when creating wrapper object.
1084 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1085 Handle<Object> object);
1086 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1087 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1089 // ES6 section 7.1.14 ToPropertyKey
1090 MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1091 Handle<Object> input);
1093 // ES6 section 7.1.1 ToPrimitive
1094 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1095 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1097 // ES6 section 7.1.3 ToNumber
1098 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Isolate* isolate,
1099 Handle<Object> input);
1101 // ES6 section 7.1.12 ToString
1102 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1103 Handle<Object> input);
1105 // ES6 section 7.3.9 GetMethod
1106 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1107 Handle<JSReceiver> receiver, Handle<Name> name);
1109 // ES6 section 12.5.6 The typeof Operator
1110 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1112 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1113 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1115 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1116 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1117 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1118 LanguageMode language_mode,
1119 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1121 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1122 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1123 StoreFromKeyed store_mode);
1125 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1126 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1127 StoreFromKeyed store_mode);
1129 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1130 LookupIterator* it, LanguageMode language_mode);
1131 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1132 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1133 LanguageMode language_mode);
1134 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1135 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1136 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1137 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1138 Handle<Object> value, LanguageMode language_mode);
1139 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1140 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1141 LanguageMode language_mode);
1142 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1143 LookupIterator* it, Handle<Object> value);
1144 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1145 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1146 LanguageMode language_mode, StoreFromKeyed store_mode);
1147 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1148 Handle<Object> object, Handle<Name> name,
1149 LanguageMode language_mode = SLOPPY);
1150 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1151 Isolate* isolate, Handle<Object> object, const char* key,
1152 LanguageMode language_mode = SLOPPY);
1153 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1154 Handle<Object> object, Handle<Name> name,
1155 LanguageMode language_mode = SLOPPY);
1157 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1158 LookupIterator* it, LanguageMode language_mode);
1159 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1160 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1162 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1163 Handle<Object> receiver,
1164 Handle<JSReceiver> getter);
1165 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1166 Handle<Object> receiver,
1167 Handle<JSReceiver> setter,
1168 Handle<Object> value);
1170 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1171 Isolate* isolate, Handle<Object> object, uint32_t index,
1172 LanguageMode language_mode = SLOPPY);
1174 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1175 Isolate* isolate, Handle<Object> object, uint32_t index,
1176 Handle<Object> value, LanguageMode language_mode);
1178 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1179 Isolate* isolate, Handle<Object> receiver);
1181 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1183 // Returns the permanent hash code associated with this object. May return
1184 // undefined if not yet created.
1187 // Returns undefined for JSObjects, but returns the hash code for simple
1188 // objects. This avoids a double lookup in the cases where we know we will
1189 // add the hash to the JSObject if it does not already exist.
1190 Object* GetSimpleHash();
1192 // Returns the permanent hash code associated with this object depending on
1193 // the actual object type. May create and store a hash code if needed and none
1195 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1197 // Checks whether this object has the same value as the given one. This
1198 // function is implemented according to ES5, section 9.12 and can be used
1199 // to implement the Harmony "egal" function.
1200 bool SameValue(Object* other);
1202 // Checks whether this object has the same value as the given one.
1203 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1204 // This function is implemented according to ES6, section 7.2.4 and is used
1205 // by ES6 Map and Set.
1206 bool SameValueZero(Object* other);
1208 // Tries to convert an object to an array length. Returns true and sets the
1209 // output parameter if it succeeds.
1210 inline bool ToArrayLength(uint32_t* index);
1212 // Tries to convert an object to an array index. Returns true and sets the
1213 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1214 // allow kMaxUInt32.
1215 inline bool ToArrayIndex(uint32_t* index);
1217 // Returns true if this is a JSValue containing a string and the index is
1218 // < the length of the string. Used to implement [] on strings.
1219 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1221 DECLARE_VERIFIER(Object)
1223 // Verify a pointer is a valid object pointer.
1224 static void VerifyPointer(Object* p);
1227 inline void VerifyApiCallResultType();
1229 // Prints this object without details.
1230 void ShortPrint(FILE* out = stdout);
1232 // Prints this object without details to a message accumulator.
1233 void ShortPrint(StringStream* accumulator);
1235 void ShortPrint(std::ostream& os); // NOLINT
1237 DECLARE_CAST(Object)
1239 // Layout description.
1240 static const int kHeaderSize = 0; // Object does not take up any space.
1243 // For our gdb macros, we should perhaps change these in the future.
1246 // Prints this object with details.
1247 void Print(std::ostream& os); // NOLINT
1249 void Print() { ShortPrint(); }
1250 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1254 friend class LookupIterator;
1255 friend class PrototypeIterator;
1257 // Return the map of the root of object's prototype chain.
1258 Map* GetRootMap(Isolate* isolate);
1260 // Helper for SetProperty and SetSuperProperty.
1261 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1262 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1263 StoreFromKeyed store_mode, bool* found);
1265 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1269 // In objects.h to be usable without objects-inl.h inclusion.
1270 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1271 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1275 explicit Brief(const Object* const v) : value(v) {}
1276 const Object* value;
1280 std::ostream& operator<<(std::ostream& os, const Brief& v);
1283 // Smi represents integer Numbers that can be stored in 31 bits.
1284 // Smis are immediate which means they are NOT allocated in the heap.
1285 // The this pointer has the following format: [31 bit signed int] 0
1286 // For long smis it has the following format:
1287 // [32 bit signed int] [31 bits zero padding] 0
1288 // Smi stands for small integer.
1289 class Smi: public Object {
1291 // Returns the integer value.
1292 inline int value() const { return Internals::SmiValue(this); }
1294 // Convert a value to a Smi object.
1295 static inline Smi* FromInt(int value) {
1296 DCHECK(Smi::IsValid(value));
1297 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1300 static inline Smi* FromIntptr(intptr_t value) {
1301 DCHECK(Smi::IsValid(value));
1302 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1303 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1306 // Returns whether value can be represented in a Smi.
1307 static inline bool IsValid(intptr_t value) {
1308 bool result = Internals::IsValidSmi(value);
1309 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1315 // Dispatched behavior.
1316 void SmiPrint(std::ostream& os) const; // NOLINT
1317 DECLARE_VERIFIER(Smi)
1319 static const int kMinValue =
1320 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1321 static const int kMaxValue = -(kMinValue + 1);
1324 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1328 // Heap objects typically have a map pointer in their first word. However,
1329 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1330 // encoded in the first word. The class MapWord is an abstraction of the
1331 // value in a heap object's first word.
1332 class MapWord BASE_EMBEDDED {
1334 // Normal state: the map word contains a map pointer.
1336 // Create a map word from a map pointer.
1337 static inline MapWord FromMap(const Map* map);
1339 // View this map word as a map pointer.
1340 inline Map* ToMap();
1343 // Scavenge collection: the map word of live objects in the from space
1344 // contains a forwarding address (a heap object pointer in the to space).
1346 // True if this map word is a forwarding address for a scavenge
1347 // collection. Only valid during a scavenge collection (specifically,
1348 // when all map words are heap object pointers, i.e. not during a full GC).
1349 inline bool IsForwardingAddress();
1351 // Create a map word from a forwarding address.
1352 static inline MapWord FromForwardingAddress(HeapObject* object);
1354 // View this map word as a forwarding address.
1355 inline HeapObject* ToForwardingAddress();
1357 static inline MapWord FromRawValue(uintptr_t value) {
1358 return MapWord(value);
1361 inline uintptr_t ToRawValue() {
1366 // HeapObject calls the private constructor and directly reads the value.
1367 friend class HeapObject;
1369 explicit MapWord(uintptr_t value) : value_(value) {}
1375 // The content of an heap object (except for the map pointer). kTaggedValues
1376 // objects can contain both heap pointers and Smis, kMixedValues can contain
1377 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1378 // objects can contain raw values and Smis.
1379 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1382 // HeapObject is the superclass for all classes describing heap allocated
1384 class HeapObject: public Object {
1386 // [map]: Contains a map which contains the object's reflective
1388 inline Map* map() const;
1389 inline void set_map(Map* value);
1390 // The no-write-barrier version. This is OK if the object is white and in
1391 // new space, or if the value is an immortal immutable object, like the maps
1392 // of primitive (non-JS) objects like strings, heap numbers etc.
1393 inline void set_map_no_write_barrier(Map* value);
1395 // Get the map using acquire load.
1396 inline Map* synchronized_map();
1397 inline MapWord synchronized_map_word() const;
1399 // Set the map using release store
1400 inline void synchronized_set_map(Map* value);
1401 inline void synchronized_set_map_no_write_barrier(Map* value);
1402 inline void synchronized_set_map_word(MapWord map_word);
1404 // During garbage collection, the map word of a heap object does not
1405 // necessarily contain a map pointer.
1406 inline MapWord map_word() const;
1407 inline void set_map_word(MapWord map_word);
1409 // The Heap the object was allocated in. Used also to access Isolate.
1410 inline Heap* GetHeap() const;
1412 // Convenience method to get current isolate.
1413 inline Isolate* GetIsolate() const;
1415 // Converts an address to a HeapObject pointer.
1416 static inline HeapObject* FromAddress(Address address) {
1417 DCHECK_TAG_ALIGNED(address);
1418 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1421 // Returns the address of this HeapObject.
1422 inline Address address() {
1423 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1426 // Iterates over pointers contained in the object (including the Map)
1427 void Iterate(ObjectVisitor* v);
1429 // Iterates over all pointers contained in the object except the
1430 // first map pointer. The object type is given in the first
1431 // parameter. This function does not access the map pointer in the
1432 // object, and so is safe to call while the map pointer is modified.
1433 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1435 // Returns the heap object's size in bytes
1438 // Indicates what type of values this heap object may contain.
1439 inline HeapObjectContents ContentType();
1441 // Given a heap object's map pointer, returns the heap size in bytes
1442 // Useful when the map pointer field is used for other purposes.
1444 inline int SizeFromMap(Map* map);
1446 // Returns the field at offset in obj, as a read/write Object* reference.
1447 // Does no checking, and is safe to use during GC, while maps are invalid.
1448 // Does not invoke write barrier, so should only be assigned to
1449 // during marking GC.
1450 static inline Object** RawField(HeapObject* obj, int offset);
1452 // Adds the |code| object related to |name| to the code cache of this map. If
1453 // this map is a dictionary map that is shared, the map copied and installed
1455 static void UpdateMapCodeCache(Handle<HeapObject> object,
1459 DECLARE_CAST(HeapObject)
1461 // Return the write barrier mode for this. Callers of this function
1462 // must be able to present a reference to an DisallowHeapAllocation
1463 // object as a sign that they are not going to use this function
1464 // from code that allocates and thus invalidates the returned write
1466 inline WriteBarrierMode GetWriteBarrierMode(
1467 const DisallowHeapAllocation& promise);
1469 // Dispatched behavior.
1470 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1472 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1474 DECLARE_PRINTER(HeapObject)
1475 DECLARE_VERIFIER(HeapObject)
1477 inline void VerifyObjectField(int offset);
1478 inline void VerifySmiField(int offset);
1480 // Verify a pointer is a valid HeapObject pointer that points to object
1481 // areas in the heap.
1482 static void VerifyHeapPointer(Object* p);
1485 inline AllocationAlignment RequiredAlignment();
1487 // Layout description.
1488 // First field in a heap object is map.
1489 static const int kMapOffset = Object::kHeaderSize;
1490 static const int kHeaderSize = kMapOffset + kPointerSize;
1492 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1495 // helpers for calling an ObjectVisitor to iterate over pointers in the
1496 // half-open range [start, end) specified as integer offsets
1497 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1498 // as above, for the single element at "offset"
1499 inline void IteratePointer(ObjectVisitor* v, int offset);
1500 // as above, for the next code link of a code object.
1501 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1504 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1508 // This class describes a body of an object of a fixed size
1509 // in which all pointer fields are located in the [start_offset, end_offset)
1511 template<int start_offset, int end_offset, int size>
1512 class FixedBodyDescriptor {
1514 static const int kStartOffset = start_offset;
1515 static const int kEndOffset = end_offset;
1516 static const int kSize = size;
1518 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1520 template<typename StaticVisitor>
1521 static inline void IterateBody(HeapObject* obj) {
1522 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1523 HeapObject::RawField(obj, end_offset));
1528 // This class describes a body of an object of a variable size
1529 // in which all pointer fields are located in the [start_offset, object_size)
1531 template<int start_offset>
1532 class FlexibleBodyDescriptor {
1534 static const int kStartOffset = start_offset;
1536 static inline void IterateBody(HeapObject* obj,
1540 template<typename StaticVisitor>
1541 static inline void IterateBody(HeapObject* obj, int object_size) {
1542 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1543 HeapObject::RawField(obj, object_size));
1548 // The HeapNumber class describes heap allocated numbers that cannot be
1549 // represented in a Smi (small integer)
1550 class HeapNumber: public HeapObject {
1552 // [value]: number value.
1553 inline double value() const;
1554 inline void set_value(double value);
1556 DECLARE_CAST(HeapNumber)
1558 // Dispatched behavior.
1559 bool HeapNumberBooleanValue();
1561 void HeapNumberPrint(std::ostream& os); // NOLINT
1562 DECLARE_VERIFIER(HeapNumber)
1564 inline int get_exponent();
1565 inline int get_sign();
1567 // Layout description.
1568 static const int kValueOffset = HeapObject::kHeaderSize;
1569 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1570 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1571 // words within double numbers are endian dependent and they are set
1573 #if defined(V8_TARGET_LITTLE_ENDIAN)
1574 static const int kMantissaOffset = kValueOffset;
1575 static const int kExponentOffset = kValueOffset + 4;
1576 #elif defined(V8_TARGET_BIG_ENDIAN)
1577 static const int kMantissaOffset = kValueOffset + 4;
1578 static const int kExponentOffset = kValueOffset;
1580 #error Unknown byte ordering
1583 static const int kSize = kValueOffset + kDoubleSize;
1584 static const uint32_t kSignMask = 0x80000000u;
1585 static const uint32_t kExponentMask = 0x7ff00000u;
1586 static const uint32_t kMantissaMask = 0xfffffu;
1587 static const int kMantissaBits = 52;
1588 static const int kExponentBits = 11;
1589 static const int kExponentBias = 1023;
1590 static const int kExponentShift = 20;
1591 static const int kInfinityOrNanExponent =
1592 (kExponentMask >> kExponentShift) - kExponentBias;
1593 static const int kMantissaBitsInTopWord = 20;
1594 static const int kNonMantissaBitsInTopWord = 12;
1597 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1601 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1602 class Simd128Value : public HeapObject {
1604 DECLARE_CAST(Simd128Value)
1606 DECLARE_PRINTER(Simd128Value)
1607 DECLARE_VERIFIER(Simd128Value)
1609 static Handle<String> ToString(Handle<Simd128Value> input);
1611 // Equality operations.
1612 inline bool Equals(Simd128Value* that);
1614 // Checks that another instance is bit-wise equal.
1615 bool BitwiseEquals(const Simd128Value* other) const;
1616 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1617 uint32_t Hash() const;
1618 // Copies the 16 bytes of SIMD data to the destination address.
1619 void CopyBits(void* destination) const;
1621 // Layout description.
1622 static const int kValueOffset = HeapObject::kHeaderSize;
1623 static const int kSize = kValueOffset + kSimd128Size;
1626 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1630 // V has parameters (TYPE, Type, type, lane count, lane type)
1631 #define SIMD128_TYPES(V) \
1632 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1633 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1634 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1635 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1636 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1637 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1638 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1639 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1640 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1641 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1643 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1644 class Type final : public Simd128Value { \
1646 inline lane_type get_lane(int lane) const; \
1647 inline void set_lane(int lane, lane_type value); \
1649 DECLARE_CAST(Type) \
1651 DECLARE_PRINTER(Type) \
1653 static Handle<String> ToString(Handle<Type> input); \
1655 inline bool Equals(Type* that); \
1658 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1660 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1661 #undef SIMD128_VALUE_CLASS
1664 enum EnsureElementsMode {
1665 DONT_ALLOW_DOUBLE_ELEMENTS,
1666 ALLOW_COPIED_DOUBLE_ELEMENTS,
1667 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1671 // Indicator for one component of an AccessorPair.
1672 enum AccessorComponent {
1678 // JSReceiver includes types on which properties can be defined, i.e.,
1679 // JSObject and JSProxy.
1680 class JSReceiver: public HeapObject {
1682 DECLARE_CAST(JSReceiver)
1684 // ES6 section 7.1.1 ToPrimitive
1685 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1686 Handle<JSReceiver> receiver,
1687 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1688 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1689 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1691 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1692 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1693 Handle<JSReceiver> object, Handle<Name> name);
1694 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1696 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1697 Handle<JSReceiver> object, uint32_t index);
1698 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1699 Handle<JSReceiver> object, uint32_t index);
1701 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1702 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1703 Handle<JSReceiver> object, Handle<Name> name,
1704 LanguageMode language_mode = SLOPPY);
1705 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1706 Handle<JSReceiver> object, Handle<Name> name,
1707 LanguageMode language_mode = SLOPPY);
1708 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1709 LookupIterator* it, LanguageMode language_mode);
1710 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1711 Handle<JSReceiver> object, uint32_t index,
1712 LanguageMode language_mode = SLOPPY);
1714 // Tests for the fast common case for property enumeration.
1715 bool IsSimpleEnum();
1717 // Returns the class name ([[Class]] property in the specification).
1718 String* class_name();
1720 // Returns the constructor name (the name (possibly, inferred name) of the
1721 // function that was used to instantiate the object).
1722 String* constructor_name();
1724 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1725 Handle<JSReceiver> object, Handle<Name> name);
1726 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1727 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1729 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1730 Handle<JSReceiver> object, uint32_t index);
1731 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1732 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1734 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1735 LookupIterator* it);
1738 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1740 static Handle<Object> GetDataProperty(LookupIterator* it);
1743 // Retrieves a permanent object identity hash code. The undefined value might
1744 // be returned in case no hash was created yet.
1745 inline Object* GetIdentityHash();
1747 // Retrieves a permanent object identity hash code. May create and store a
1748 // hash code if needed and none exists.
1749 inline static Handle<Smi> GetOrCreateIdentityHash(
1750 Handle<JSReceiver> object);
1752 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1754 // Computes the enumerable keys for a JSObject. Used for implementing
1755 // "for (n in object) { }".
1756 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1757 Handle<JSReceiver> object,
1758 KeyCollectionType type);
1761 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1765 // The JSObject describes real heap allocated JavaScript objects with
1767 // Note that the map of JSObject changes during execution to enable inline
1769 class JSObject: public JSReceiver {
1771 // [properties]: Backing storage for properties.
1772 // properties is a FixedArray in the fast case and a Dictionary in the
1774 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1775 inline void initialize_properties();
1776 inline bool HasFastProperties();
1777 // Gets slow properties for non-global objects.
1778 inline NameDictionary* property_dictionary();
1779 // Gets global object properties.
1780 inline GlobalDictionary* global_dictionary();
1782 // [elements]: The elements (properties with names that are integers).
1784 // Elements can be in two general modes: fast and slow. Each mode
1785 // corrensponds to a set of object representations of elements that
1786 // have something in common.
1788 // In the fast mode elements is a FixedArray and so each element can
1789 // be quickly accessed. This fact is used in the generated code. The
1790 // elements array can have one of three maps in this mode:
1791 // fixed_array_map, sloppy_arguments_elements_map or
1792 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1793 // the elements array may be shared by a few objects and so before
1794 // writing to any element the array must be copied. Use
1795 // EnsureWritableFastElements in this case.
1797 // In the slow mode the elements is either a NumberDictionary, a
1798 // FixedArray parameter map for a (sloppy) arguments object.
1799 DECL_ACCESSORS(elements, FixedArrayBase)
1800 inline void initialize_elements();
1801 static void ResetElements(Handle<JSObject> object);
1802 static inline void SetMapAndElements(Handle<JSObject> object,
1804 Handle<FixedArrayBase> elements);
1805 inline ElementsKind GetElementsKind();
1806 ElementsAccessor* GetElementsAccessor();
1807 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1808 inline bool HasFastSmiElements();
1809 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1810 inline bool HasFastObjectElements();
1811 // Returns true if an object has elements of FAST_ELEMENTS or
1812 // FAST_SMI_ONLY_ELEMENTS.
1813 inline bool HasFastSmiOrObjectElements();
1814 // Returns true if an object has any of the fast elements kinds.
1815 inline bool HasFastElements();
1816 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1818 inline bool HasFastDoubleElements();
1819 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1821 inline bool HasFastHoleyElements();
1822 inline bool HasSloppyArgumentsElements();
1823 inline bool HasDictionaryElements();
1825 inline bool HasFixedTypedArrayElements();
1827 inline bool HasFixedUint8ClampedElements();
1828 inline bool HasFixedArrayElements();
1829 inline bool HasFixedInt8Elements();
1830 inline bool HasFixedUint8Elements();
1831 inline bool HasFixedInt16Elements();
1832 inline bool HasFixedUint16Elements();
1833 inline bool HasFixedInt32Elements();
1834 inline bool HasFixedUint32Elements();
1835 inline bool HasFixedFloat32Elements();
1836 inline bool HasFixedFloat64Elements();
1838 inline bool HasFastArgumentsElements();
1839 inline bool HasSlowArgumentsElements();
1840 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1842 // Requires: HasFastElements().
1843 static Handle<FixedArray> EnsureWritableFastElements(
1844 Handle<JSObject> object);
1846 // Collects elements starting at index 0.
1847 // Undefined values are placed after non-undefined values.
1848 // Returns the number of non-undefined values.
1849 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1851 // As PrepareElementsForSort, but only on objects where elements is
1852 // a dictionary, and it will stay a dictionary. Collates undefined and
1853 // unexisting elements below limit from position zero of the elements.
1854 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1857 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1858 LookupIterator* it, Handle<Object> value);
1860 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1861 // grant an exemption to ExecutableAccessor callbacks in some cases.
1862 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1864 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1865 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1866 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1868 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1869 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1870 PropertyAttributes attributes,
1871 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1873 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1874 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1875 PropertyAttributes attributes,
1876 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1878 // Equivalent to one of the above depending on whether |name| can be converted
1879 // to an array index.
1880 MUST_USE_RESULT static MaybeHandle<Object>
1881 DefinePropertyOrElementIgnoreAttributes(
1882 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1883 PropertyAttributes attributes = NONE,
1884 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1886 // Adds or reconfigures a property to attributes NONE. It will fail when it
1888 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1889 Handle<Object> value);
1891 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1892 Handle<Object> value, PropertyAttributes attributes);
1894 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1895 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1896 PropertyAttributes attributes);
1898 // Extend the receiver with a single fast property appeared first in the
1899 // passed map. This also extends the property backing store if necessary.
1900 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1902 // Migrates the given object to a map whose field representations are the
1903 // lowest upper bound of all known representations for that field.
1904 static void MigrateInstance(Handle<JSObject> instance);
1906 // Migrates the given object only if the target map is already available,
1907 // or returns false if such a map is not yet available.
1908 static bool TryMigrateInstance(Handle<JSObject> instance);
1910 // Sets the property value in a normalized object given (key, value, details).
1911 // Handles the special representation of JS global objects.
1912 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1913 Handle<Object> value,
1914 PropertyDetails details);
1915 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1916 Handle<Object> value,
1917 PropertyAttributes attributes);
1918 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1920 Handle<Object> value,
1921 PropertyAttributes attributes);
1923 static void OptimizeAsPrototype(Handle<JSObject> object,
1924 PrototypeOptimizationMode mode);
1925 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1926 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1927 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1928 static void InvalidatePrototypeChains(Map* map);
1930 // Alternative implementation of WeakFixedArray::NullCallback.
1931 class PrototypeRegistryCompactionCallback {
1933 static void Callback(Object* value, int old_index, int new_index);
1936 // Retrieve interceptors.
1937 InterceptorInfo* GetNamedInterceptor();
1938 InterceptorInfo* GetIndexedInterceptor();
1940 // Used from JSReceiver.
1941 MUST_USE_RESULT static Maybe<PropertyAttributes>
1942 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1943 MUST_USE_RESULT static Maybe<PropertyAttributes>
1944 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1946 // Retrieves an AccessorPair property from the given object. Might return
1947 // undefined if the property doesn't exist or is of a different kind.
1948 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1949 Handle<JSObject> object,
1951 AccessorComponent component);
1953 // Defines an AccessorPair property on the given object.
1954 // TODO(mstarzinger): Rename to SetAccessor().
1955 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1957 Handle<Object> getter,
1958 Handle<Object> setter,
1959 PropertyAttributes attributes);
1961 // Defines an AccessorInfo property on the given object.
1962 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1963 Handle<JSObject> object,
1964 Handle<AccessorInfo> info);
1966 // The result must be checked first for exceptions. If there's no exception,
1967 // the output parameter |done| indicates whether the interceptor has a result
1969 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1970 LookupIterator* it, bool* done);
1972 // Accessors for hidden properties object.
1974 // Hidden properties are not own properties of the object itself.
1975 // Instead they are stored in an auxiliary structure kept as an own
1976 // property with a special name Heap::hidden_string(). But if the
1977 // receiver is a JSGlobalProxy then the auxiliary object is a property
1978 // of its prototype, and if it's a detached proxy, then you can't have
1979 // hidden properties.
1981 // Sets a hidden property on this object. Returns this object if successful,
1982 // undefined if called on a detached proxy.
1983 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1985 Handle<Object> value);
1986 // Gets the value of a hidden property with the given key. Returns the hole
1987 // if the property doesn't exist (or if called on a detached proxy),
1988 // otherwise returns the value set for the key.
1989 Object* GetHiddenProperty(Handle<Name> key);
1990 // Deletes a hidden property. Deleting a non-existing property is
1991 // considered successful.
1992 static void DeleteHiddenProperty(Handle<JSObject> object,
1994 // Returns true if the object has a property with the hidden string as name.
1995 static bool HasHiddenProperties(Handle<JSObject> object);
1997 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1999 static void ValidateElements(Handle<JSObject> object);
2001 // Makes sure that this object can contain HeapObject as elements.
2002 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2004 // Makes sure that this object can contain the specified elements.
2005 static inline void EnsureCanContainElements(
2006 Handle<JSObject> object,
2009 EnsureElementsMode mode);
2010 static inline void EnsureCanContainElements(
2011 Handle<JSObject> object,
2012 Handle<FixedArrayBase> elements,
2014 EnsureElementsMode mode);
2015 static void EnsureCanContainElements(
2016 Handle<JSObject> object,
2017 Arguments* arguments,
2020 EnsureElementsMode mode);
2022 // Would we convert a fast elements array to dictionary mode given
2023 // an access at key?
2024 bool WouldConvertToSlowElements(uint32_t index);
2026 // Computes the new capacity when expanding the elements of a JSObject.
2027 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2028 // (old_capacity + 50%) + 16
2029 return old_capacity + (old_capacity >> 1) + 16;
2032 // These methods do not perform access checks!
2033 static void UpdateAllocationSite(Handle<JSObject> object,
2034 ElementsKind to_kind);
2036 // Lookup interceptors are used for handling properties controlled by host
2038 inline bool HasNamedInterceptor();
2039 inline bool HasIndexedInterceptor();
2041 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2042 // by JSReceiver::GetKeys.
2043 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2044 Handle<JSObject> object,
2045 Handle<JSReceiver> receiver);
2046 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2047 Handle<JSObject> object,
2048 Handle<JSReceiver> receiver);
2050 // Support functions for v8 api (needed for correct interceptor behavior).
2051 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2052 Handle<JSObject> object, Handle<Name> name);
2053 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2054 Handle<JSObject> object, uint32_t index);
2055 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2056 Handle<JSObject> object, Handle<Name> name);
2058 // Get the header size for a JSObject. Used to compute the index of
2059 // internal fields as well as the number of internal fields.
2060 inline int GetHeaderSize();
2062 inline int GetInternalFieldCount();
2063 inline int GetInternalFieldOffset(int index);
2064 inline Object* GetInternalField(int index);
2065 inline void SetInternalField(int index, Object* value);
2066 inline void SetInternalField(int index, Smi* value);
2068 // Returns the number of properties on this object filtering out properties
2069 // with the specified attributes (ignoring interceptors).
2070 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2071 // Fill in details for properties into storage starting at the specified
2072 // index. Returns the number of properties added.
2073 int GetOwnPropertyNames(FixedArray* storage, int index,
2074 PropertyAttributes filter = NONE);
2076 // Returns the number of properties on this object filtering out properties
2077 // with the specified attributes (ignoring interceptors).
2078 int NumberOfOwnElements(PropertyAttributes filter);
2079 // Returns the number of enumerable elements (ignoring interceptors).
2080 int NumberOfEnumElements();
2081 // Returns the number of elements on this object filtering out elements
2082 // with the specified attributes (ignoring interceptors).
2083 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2084 // Count and fill in the enumerable elements into storage.
2085 // (storage->length() == NumberOfEnumElements()).
2086 // If storage is NULL, will count the elements without adding
2087 // them to any storage.
2088 // Returns the number of enumerable elements.
2089 int GetEnumElementKeys(FixedArray* storage);
2091 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2094 // Returns a new map with all transitions dropped from the object's current
2095 // map and the ElementsKind set.
2096 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2097 ElementsKind to_kind);
2098 static void TransitionElementsKind(Handle<JSObject> object,
2099 ElementsKind to_kind);
2101 // Always use this to migrate an object to a new map.
2102 // |expected_additional_properties| is only used for fast-to-slow transitions
2103 // and ignored otherwise.
2104 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2105 int expected_additional_properties = 0);
2107 // Convert the object to use the canonical dictionary
2108 // representation. If the object is expected to have additional properties
2109 // added this number can be indicated to have the backing store allocated to
2110 // an initial capacity for holding these properties.
2111 static void NormalizeProperties(Handle<JSObject> object,
2112 PropertyNormalizationMode mode,
2113 int expected_additional_properties,
2114 const char* reason);
2116 // Convert and update the elements backing store to be a
2117 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2118 static Handle<SeededNumberDictionary> NormalizeElements(
2119 Handle<JSObject> object);
2121 void RequireSlowElements(SeededNumberDictionary* dictionary);
2123 // Transform slow named properties to fast variants.
2124 static void MigrateSlowToFast(Handle<JSObject> object,
2125 int unused_property_fields, const char* reason);
2127 inline bool IsUnboxedDoubleField(FieldIndex index);
2129 // Access fast-case object properties at index.
2130 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2131 Representation representation,
2133 inline Object* RawFastPropertyAt(FieldIndex index);
2134 inline double RawFastDoublePropertyAt(FieldIndex index);
2136 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2137 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2138 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2139 inline void WriteToField(int descriptor, Object* value);
2141 // Access to in object properties.
2142 inline int GetInObjectPropertyOffset(int index);
2143 inline Object* InObjectPropertyAt(int index);
2144 inline Object* InObjectPropertyAtPut(int index,
2146 WriteBarrierMode mode
2147 = UPDATE_WRITE_BARRIER);
2149 // Set the object's prototype (only JSReceiver and null are allowed values).
2150 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2151 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2153 // Initializes the body after properties slot, properties slot is
2154 // initialized by set_properties. Fill the pre-allocated fields with
2155 // pre_allocated_value and the rest with filler_value.
2156 // Note: this call does not update write barrier, the caller is responsible
2157 // to ensure that |filler_value| can be collected without WB here.
2158 inline void InitializeBody(Map* map,
2159 Object* pre_allocated_value,
2160 Object* filler_value);
2162 // Check whether this object references another object
2163 bool ReferencesObject(Object* obj);
2165 // Disalow further properties to be added to the oject.
2166 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2167 Handle<JSObject> object);
2169 bool IsExtensible();
2172 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2174 // ES5 Object.freeze
2175 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2177 // Called the first time an object is observed with ES7 Object.observe.
2178 static void SetObserved(Handle<JSObject> object);
2181 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2183 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2184 Handle<JSObject> object,
2185 AllocationSiteUsageContext* site_context,
2186 DeepCopyHints hints = kNoHints);
2187 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2188 Handle<JSObject> object,
2189 AllocationSiteCreationContext* site_context);
2191 DECLARE_CAST(JSObject)
2193 // Dispatched behavior.
2194 void JSObjectShortPrint(StringStream* accumulator);
2195 DECLARE_PRINTER(JSObject)
2196 DECLARE_VERIFIER(JSObject)
2198 void PrintProperties(std::ostream& os); // NOLINT
2199 void PrintElements(std::ostream& os); // NOLINT
2201 #if defined(DEBUG) || defined(OBJECT_PRINT)
2202 void PrintTransitions(std::ostream& os); // NOLINT
2205 static void PrintElementsTransition(
2206 FILE* file, Handle<JSObject> object,
2207 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2208 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2210 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2213 // Structure for collecting spill information about JSObjects.
2214 class SpillInformation {
2218 int number_of_objects_;
2219 int number_of_objects_with_fast_properties_;
2220 int number_of_objects_with_fast_elements_;
2221 int number_of_fast_used_fields_;
2222 int number_of_fast_unused_fields_;
2223 int number_of_slow_used_properties_;
2224 int number_of_slow_unused_properties_;
2225 int number_of_fast_used_elements_;
2226 int number_of_fast_unused_elements_;
2227 int number_of_slow_used_elements_;
2228 int number_of_slow_unused_elements_;
2231 void IncrementSpillStatistics(SpillInformation* info);
2235 // If a GC was caused while constructing this object, the elements pointer
2236 // may point to a one pointer filler map. The object won't be rooted, but
2237 // our heap verification code could stumble across it.
2238 bool ElementsAreSafeToExamine();
2241 Object* SlowReverseLookup(Object* value);
2243 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2244 // Also maximal value of JSArray's length property.
2245 static const uint32_t kMaxElementCount = 0xffffffffu;
2247 // Constants for heuristics controlling conversion of fast elements
2248 // to slow elements.
2250 // Maximal gap that can be introduced by adding an element beyond
2251 // the current elements length.
2252 static const uint32_t kMaxGap = 1024;
2254 // Maximal length of fast elements array that won't be checked for
2255 // being dense enough on expansion.
2256 static const int kMaxUncheckedFastElementsLength = 5000;
2258 // Same as above but for old arrays. This limit is more strict. We
2259 // don't want to be wasteful with long lived objects.
2260 static const int kMaxUncheckedOldFastElementsLength = 500;
2262 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2263 // permissible values (see the DCHECK in heap.cc).
2264 static const int kInitialMaxFastElementArray = 100000;
2266 // This constant applies only to the initial map of "global.Object" and
2267 // not to arbitrary other JSObject maps.
2268 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2270 static const int kMaxInstanceSize = 255 * kPointerSize;
2271 // When extending the backing storage for property values, we increase
2272 // its size by more than the 1 entry necessary, so sequentially adding fields
2273 // to the same object requires fewer allocations and copies.
2274 static const int kFieldsAdded = 3;
2276 // Layout description.
2277 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2278 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2279 static const int kHeaderSize = kElementsOffset + kPointerSize;
2281 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2283 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2285 static inline int SizeOf(Map* map, HeapObject* object);
2288 Context* GetCreationContext();
2290 // Enqueue change record for Object.observe. May cause GC.
2291 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2292 Handle<JSObject> object, const char* type, Handle<Name> name,
2293 Handle<Object> old_value);
2295 // Gets the number of currently used elements.
2296 int GetFastElementsUsage();
2298 // Deletes an existing named property in a normalized object.
2299 static void DeleteNormalizedProperty(Handle<JSObject> object,
2300 Handle<Name> name, int entry);
2302 static bool AllCanRead(LookupIterator* it);
2303 static bool AllCanWrite(LookupIterator* it);
2306 friend class JSReceiver;
2307 friend class Object;
2309 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2310 static void MigrateFastToSlow(Handle<JSObject> object,
2311 Handle<Map> new_map,
2312 int expected_additional_properties);
2314 // Used from Object::GetProperty().
2315 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2316 LookupIterator* it);
2318 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2319 LookupIterator* it, Handle<Object> value);
2321 // Add a property to a slow-case object.
2322 static void AddSlowProperty(Handle<JSObject> object,
2324 Handle<Object> value,
2325 PropertyAttributes attributes);
2327 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2328 LookupIterator* it);
2330 bool ReferencesObjectFromElements(FixedArray* elements,
2334 // Return the hash table backing store or the inline stored identity hash,
2335 // whatever is found.
2336 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2338 // Return the hash table backing store for hidden properties. If there is no
2339 // backing store, allocate one.
2340 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2341 Handle<JSObject> object);
2343 // Set the hidden property backing store to either a hash table or
2344 // the inline-stored identity hash.
2345 static Handle<Object> SetHiddenPropertiesHashTable(
2346 Handle<JSObject> object,
2347 Handle<Object> value);
2349 MUST_USE_RESULT Object* GetIdentityHash();
2351 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2353 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2354 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2356 // Helper for fast versions of preventExtensions, seal, and freeze.
2357 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2358 template <PropertyAttributes attrs>
2359 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2360 Handle<JSObject> object);
2362 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2366 // Common superclass for FixedArrays that allow implementations to share
2367 // common accessors and some code paths.
2368 class FixedArrayBase: public HeapObject {
2370 // [length]: length of the array.
2371 inline int length() const;
2372 inline void set_length(int value);
2374 // Get and set the length using acquire loads and release stores.
2375 inline int synchronized_length() const;
2376 inline void synchronized_set_length(int value);
2378 DECLARE_CAST(FixedArrayBase)
2380 // Layout description.
2381 // Length is smi tagged when it is stored.
2382 static const int kLengthOffset = HeapObject::kHeaderSize;
2383 static const int kHeaderSize = kLengthOffset + kPointerSize;
2387 class FixedDoubleArray;
2388 class IncrementalMarking;
2391 // FixedArray describes fixed-sized arrays with element type Object*.
2392 class FixedArray: public FixedArrayBase {
2394 // Setter and getter for elements.
2395 inline Object* get(int index) const;
2396 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2397 // Setter that uses write barrier.
2398 inline void set(int index, Object* value);
2399 inline bool is_the_hole(int index);
2401 // Setter that doesn't need write barrier.
2402 inline void set(int index, Smi* value);
2403 // Setter with explicit barrier mode.
2404 inline void set(int index, Object* value, WriteBarrierMode mode);
2406 // Setters for frequently used oddballs located in old space.
2407 inline void set_undefined(int index);
2408 inline void set_null(int index);
2409 inline void set_the_hole(int index);
2411 inline Object** GetFirstElementAddress();
2412 inline bool ContainsOnlySmisOrHoles();
2414 // Gives access to raw memory which stores the array's data.
2415 inline Object** data_start();
2417 inline void FillWithHoles(int from, int to);
2419 // Shrink length and insert filler objects.
2420 void Shrink(int length);
2422 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2424 // Add the elements of a JSArray to this FixedArray.
2425 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2426 Handle<FixedArray> content, Handle<JSObject> array,
2427 KeyFilter filter = ALL_KEYS);
2429 // Computes the union of keys and return the result.
2430 // Used for implementing "for (n in object) { }"
2431 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2432 Handle<FixedArray> first,
2433 Handle<FixedArray> second);
2435 // Copy a sub array from the receiver to dest.
2436 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2438 // Garbage collection support.
2439 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2441 // Code Generation support.
2442 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2444 // Garbage collection support.
2445 inline Object** RawFieldOfElementAt(int index);
2447 DECLARE_CAST(FixedArray)
2449 // Maximal allowed size, in bytes, of a single FixedArray.
2450 // Prevents overflowing size computations, as well as extreme memory
2452 static const int kMaxSize = 128 * MB * kPointerSize;
2453 // Maximally allowed length of a FixedArray.
2454 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2456 // Dispatched behavior.
2457 DECLARE_PRINTER(FixedArray)
2458 DECLARE_VERIFIER(FixedArray)
2460 // Checks if two FixedArrays have identical contents.
2461 bool IsEqualTo(FixedArray* other);
2464 // Swap two elements in a pair of arrays. If this array and the
2465 // numbers array are the same object, the elements are only swapped
2467 void SwapPairs(FixedArray* numbers, int i, int j);
2469 // Sort prefix of this array and the numbers array as pairs wrt. the
2470 // numbers. If the numbers array and the this array are the same
2471 // object, the prefix of this array is sorted.
2472 void SortPairs(FixedArray* numbers, uint32_t len);
2474 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2476 static inline int SizeOf(Map* map, HeapObject* object);
2480 // Set operation on FixedArray without using write barriers. Can
2481 // only be used for storing old space objects or smis.
2482 static inline void NoWriteBarrierSet(FixedArray* array,
2486 // Set operation on FixedArray without incremental write barrier. Can
2487 // only be used if the object is guaranteed to be white (whiteness witness
2489 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2494 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2496 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2500 // FixedDoubleArray describes fixed-sized arrays with element type double.
2501 class FixedDoubleArray: public FixedArrayBase {
2503 // Setter and getter for elements.
2504 inline double get_scalar(int index);
2505 inline uint64_t get_representation(int index);
2506 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2507 inline void set(int index, double value);
2508 inline void set_the_hole(int index);
2510 // Checking for the hole.
2511 inline bool is_the_hole(int index);
2513 // Garbage collection support.
2514 inline static int SizeFor(int length) {
2515 return kHeaderSize + length * kDoubleSize;
2518 // Gives access to raw memory which stores the array's data.
2519 inline double* data_start();
2521 inline void FillWithHoles(int from, int to);
2523 // Code Generation support.
2524 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2526 DECLARE_CAST(FixedDoubleArray)
2528 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2529 // Prevents overflowing size computations, as well as extreme memory
2531 static const int kMaxSize = 512 * MB;
2532 // Maximally allowed length of a FixedArray.
2533 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2535 // Dispatched behavior.
2536 DECLARE_PRINTER(FixedDoubleArray)
2537 DECLARE_VERIFIER(FixedDoubleArray)
2540 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2544 class WeakFixedArray : public FixedArray {
2546 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2547 // This function does not check if the value exists already, callers must
2548 // ensure this themselves if necessary.
2549 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2550 Handle<HeapObject> value,
2551 int* assigned_index = NULL);
2553 // Returns true if an entry was found and removed.
2554 bool Remove(Handle<HeapObject> value);
2556 class NullCallback {
2558 static void Callback(Object* value, int old_index, int new_index) {}
2561 template <class CompactionCallback>
2564 inline Object* Get(int index) const;
2565 inline void Clear(int index);
2566 inline int Length() const;
2568 inline bool IsEmptySlot(int index) const;
2569 static Object* Empty() { return Smi::FromInt(0); }
2573 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2574 void Reset(Object* maybe_array);
2581 WeakFixedArray* list_;
2583 int last_used_index_;
2584 DisallowHeapAllocation no_gc_;
2586 DISALLOW_COPY_AND_ASSIGN(Iterator);
2589 DECLARE_CAST(WeakFixedArray)
2592 static const int kLastUsedIndexIndex = 0;
2593 static const int kFirstIndex = 1;
2595 static Handle<WeakFixedArray> Allocate(
2596 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2598 static void Set(Handle<WeakFixedArray> array, int index,
2599 Handle<HeapObject> value);
2600 inline void clear(int index);
2602 inline int last_used_index() const;
2603 inline void set_last_used_index(int index);
2605 // Disallow inherited setters.
2606 void set(int index, Smi* value);
2607 void set(int index, Object* value);
2608 void set(int index, Object* value, WriteBarrierMode mode);
2609 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2613 // Generic array grows dynamically with O(1) amortized insertion.
2614 class ArrayList : public FixedArray {
2618 // Use this if GC can delete elements from the array.
2619 kReloadLengthAfterAllocation,
2621 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2622 AddMode mode = kNone);
2623 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2624 Handle<Object> obj2, AddMode = kNone);
2625 inline int Length();
2626 inline void SetLength(int length);
2627 inline Object* Get(int index);
2628 inline Object** Slot(int index);
2629 inline void Set(int index, Object* obj);
2630 inline void Clear(int index, Object* undefined);
2631 DECLARE_CAST(ArrayList)
2634 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2635 static const int kLengthIndex = 0;
2636 static const int kFirstIndex = 1;
2637 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2641 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2642 // The format of the these objects is:
2643 // [0]: Number of descriptors
2644 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2645 // [0]: pointer to fixed array with enum cache
2646 // [1]: either Smi(0) or pointer to fixed array with indices
2648 // [2 + number of descriptors * kDescriptorSize]: start of slack
2649 class DescriptorArray: public FixedArray {
2651 // Returns true for both shared empty_descriptor_array and for smis, which the
2652 // map uses to encode additional bit fields when the descriptor array is not
2654 inline bool IsEmpty();
2656 // Returns the number of descriptors in the array.
2657 inline int number_of_descriptors();
2659 inline int number_of_descriptors_storage();
2661 inline int NumberOfSlackDescriptors();
2663 inline void SetNumberOfDescriptors(int number_of_descriptors);
2664 inline int number_of_entries();
2666 inline bool HasEnumCache();
2668 inline void CopyEnumCacheFrom(DescriptorArray* array);
2670 inline FixedArray* GetEnumCache();
2672 inline bool HasEnumIndicesCache();
2674 inline FixedArray* GetEnumIndicesCache();
2676 inline Object** GetEnumCacheSlot();
2678 void ClearEnumCache();
2680 // Initialize or change the enum cache,
2681 // using the supplied storage for the small "bridge".
2682 void SetEnumCache(FixedArray* bridge_storage,
2683 FixedArray* new_cache,
2684 Object* new_index_cache);
2686 bool CanHoldValue(int descriptor, Object* value);
2688 // Accessors for fetching instance descriptor at descriptor number.
2689 inline Name* GetKey(int descriptor_number);
2690 inline Object** GetKeySlot(int descriptor_number);
2691 inline Object* GetValue(int descriptor_number);
2692 inline void SetValue(int descriptor_number, Object* value);
2693 inline Object** GetValueSlot(int descriptor_number);
2694 static inline int GetValueOffset(int descriptor_number);
2695 inline Object** GetDescriptorStartSlot(int descriptor_number);
2696 inline Object** GetDescriptorEndSlot(int descriptor_number);
2697 inline PropertyDetails GetDetails(int descriptor_number);
2698 inline PropertyType GetType(int descriptor_number);
2699 inline int GetFieldIndex(int descriptor_number);
2700 inline HeapType* GetFieldType(int descriptor_number);
2701 inline Object* GetConstant(int descriptor_number);
2702 inline Object* GetCallbacksObject(int descriptor_number);
2703 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2705 inline Name* GetSortedKey(int descriptor_number);
2706 inline int GetSortedKeyIndex(int descriptor_number);
2707 inline void SetSortedKey(int pointer, int descriptor_number);
2708 inline void SetRepresentation(int descriptor_number,
2709 Representation representation);
2711 // Accessor for complete descriptor.
2712 inline void Get(int descriptor_number, Descriptor* desc);
2713 inline void Set(int descriptor_number, Descriptor* desc);
2714 void Replace(int descriptor_number, Descriptor* descriptor);
2716 // Append automatically sets the enumeration index. This should only be used
2717 // to add descriptors in bulk at the end, followed by sorting the descriptor
2719 inline void Append(Descriptor* desc);
2721 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2722 int enumeration_index,
2725 static Handle<DescriptorArray> CopyUpToAddAttributes(
2726 Handle<DescriptorArray> desc,
2727 int enumeration_index,
2728 PropertyAttributes attributes,
2731 // Sort the instance descriptors by the hash codes of their keys.
2734 // Search the instance descriptors for given name.
2735 INLINE(int Search(Name* name, int number_of_own_descriptors));
2737 // As the above, but uses DescriptorLookupCache and updates it when
2739 INLINE(int SearchWithCache(Name* name, Map* map));
2741 // Allocates a DescriptorArray, but returns the singleton
2742 // empty descriptor array object if number_of_descriptors is 0.
2743 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2744 int number_of_descriptors,
2747 DECLARE_CAST(DescriptorArray)
2749 // Constant for denoting key was not found.
2750 static const int kNotFound = -1;
2752 static const int kDescriptorLengthIndex = 0;
2753 static const int kEnumCacheIndex = 1;
2754 static const int kFirstIndex = 2;
2756 // The length of the "bridge" to the enum cache.
2757 static const int kEnumCacheBridgeLength = 2;
2758 static const int kEnumCacheBridgeCacheIndex = 0;
2759 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2761 // Layout description.
2762 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2763 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2764 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2766 // Layout description for the bridge array.
2767 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2769 // Layout of descriptor.
2770 static const int kDescriptorKey = 0;
2771 static const int kDescriptorDetails = 1;
2772 static const int kDescriptorValue = 2;
2773 static const int kDescriptorSize = 3;
2775 #if defined(DEBUG) || defined(OBJECT_PRINT)
2776 // For our gdb macros, we should perhaps change these in the future.
2779 // Print all the descriptors.
2780 void PrintDescriptors(std::ostream& os); // NOLINT
2784 // Is the descriptor array sorted and without duplicates?
2785 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2787 // Is the descriptor array consistent with the back pointers in targets?
2788 bool IsConsistentWithBackPointers(Map* current_map);
2790 // Are two DescriptorArrays equal?
2791 bool IsEqualTo(DescriptorArray* other);
2794 // Returns the fixed array length required to hold number_of_descriptors
2796 static int LengthFor(int number_of_descriptors) {
2797 return ToKeyIndex(number_of_descriptors);
2801 // WhitenessWitness is used to prove that a descriptor array is white
2802 // (unmarked), so incremental write barriers can be skipped because the
2803 // marking invariant cannot be broken and slots pointing into evacuation
2804 // candidates will be discovered when the object is scanned. A witness is
2805 // always stack-allocated right after creating an array. By allocating a
2806 // witness, incremental marking is globally disabled. The witness is then
2807 // passed along wherever needed to statically prove that the array is known to
2809 class WhitenessWitness {
2811 inline explicit WhitenessWitness(DescriptorArray* array);
2812 inline ~WhitenessWitness();
2815 IncrementalMarking* marking_;
2818 // An entry in a DescriptorArray, represented as an (array, index) pair.
2821 inline explicit Entry(DescriptorArray* descs, int index) :
2822 descs_(descs), index_(index) { }
2824 inline PropertyType type();
2825 inline Object* GetCallbackObject();
2828 DescriptorArray* descs_;
2832 // Conversion from descriptor number to array indices.
2833 static int ToKeyIndex(int descriptor_number) {
2834 return kFirstIndex +
2835 (descriptor_number * kDescriptorSize) +
2839 static int ToDetailsIndex(int descriptor_number) {
2840 return kFirstIndex +
2841 (descriptor_number * kDescriptorSize) +
2845 static int ToValueIndex(int descriptor_number) {
2846 return kFirstIndex +
2847 (descriptor_number * kDescriptorSize) +
2851 // Transfer a complete descriptor from the src descriptor array to this
2852 // descriptor array.
2853 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2855 inline void Set(int descriptor_number,
2857 const WhitenessWitness&);
2859 // Swap first and second descriptor.
2860 inline void SwapSortedKeys(int first, int second);
2862 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2866 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2868 template <SearchMode search_mode, typename T>
2869 inline int Search(T* array, Name* name, int valid_entries = 0,
2870 int* out_insertion_index = NULL);
2873 // HashTable is a subclass of FixedArray that implements a hash table
2874 // that uses open addressing and quadratic probing.
2876 // In order for the quadratic probing to work, elements that have not
2877 // yet been used and elements that have been deleted are
2878 // distinguished. Probing continues when deleted elements are
2879 // encountered and stops when unused elements are encountered.
2881 // - Elements with key == undefined have not been used yet.
2882 // - Elements with key == the_hole have been deleted.
2884 // The hash table class is parameterized with a Shape and a Key.
2885 // Shape must be a class with the following interface:
2886 // class ExampleShape {
2888 // // Tells whether key matches other.
2889 // static bool IsMatch(Key key, Object* other);
2890 // // Returns the hash value for key.
2891 // static uint32_t Hash(Key key);
2892 // // Returns the hash value for object.
2893 // static uint32_t HashForObject(Key key, Object* object);
2894 // // Convert key to an object.
2895 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2896 // // The prefix size indicates number of elements in the beginning
2897 // // of the backing storage.
2898 // static const int kPrefixSize = ..;
2899 // // The Element size indicates number of elements per entry.
2900 // static const int kEntrySize = ..;
2902 // The prefix size indicates an amount of memory in the
2903 // beginning of the backing storage that can be used for non-element
2904 // information by subclasses.
2906 template<typename Key>
2909 static const bool UsesSeed = false;
2910 static uint32_t Hash(Key key) { return 0; }
2911 static uint32_t SeededHash(Key key, uint32_t seed) {
2915 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2916 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2918 return HashForObject(key, object);
2923 class HashTableBase : public FixedArray {
2925 // Returns the number of elements in the hash table.
2926 inline int NumberOfElements();
2928 // Returns the number of deleted elements in the hash table.
2929 inline int NumberOfDeletedElements();
2931 // Returns the capacity of the hash table.
2932 inline int Capacity();
2934 // ElementAdded should be called whenever an element is added to a
2936 inline void ElementAdded();
2938 // ElementRemoved should be called whenever an element is removed from
2940 inline void ElementRemoved();
2941 inline void ElementsRemoved(int n);
2943 // Computes the required capacity for a table holding the given
2944 // number of elements. May be more than HashTable::kMaxCapacity.
2945 static inline int ComputeCapacity(int at_least_space_for);
2947 // Tells whether k is a real key. The hole and undefined are not allowed
2948 // as keys and can be used to indicate missing or deleted elements.
2949 inline bool IsKey(Object* k);
2951 // Compute the probe offset (quadratic probing).
2952 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2953 return (n + n * n) >> 1;
2956 static const int kNumberOfElementsIndex = 0;
2957 static const int kNumberOfDeletedElementsIndex = 1;
2958 static const int kCapacityIndex = 2;
2959 static const int kPrefixStartIndex = 3;
2961 // Constant used for denoting a absent entry.
2962 static const int kNotFound = -1;
2965 // Update the number of elements in the hash table.
2966 inline void SetNumberOfElements(int nof);
2968 // Update the number of deleted elements in the hash table.
2969 inline void SetNumberOfDeletedElements(int nod);
2971 // Returns probe entry.
2972 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2973 DCHECK(base::bits::IsPowerOfTwo32(size));
2974 return (hash + GetProbeOffset(number)) & (size - 1);
2977 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2978 return hash & (size - 1);
2981 inline static uint32_t NextProbe(
2982 uint32_t last, uint32_t number, uint32_t size) {
2983 return (last + number) & (size - 1);
2988 template <typename Derived, typename Shape, typename Key>
2989 class HashTable : public HashTableBase {
2992 inline uint32_t Hash(Key key) {
2993 if (Shape::UsesSeed) {
2994 return Shape::SeededHash(key, GetHeap()->HashSeed());
2996 return Shape::Hash(key);
3000 inline uint32_t HashForObject(Key key, Object* object) {
3001 if (Shape::UsesSeed) {
3002 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3004 return Shape::HashForObject(key, object);
3008 // Returns a new HashTable object.
3009 MUST_USE_RESULT static Handle<Derived> New(
3010 Isolate* isolate, int at_least_space_for,
3011 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3012 PretenureFlag pretenure = NOT_TENURED);
3014 DECLARE_CAST(HashTable)
3016 // Garbage collection support.
3017 void IteratePrefix(ObjectVisitor* visitor);
3018 void IterateElements(ObjectVisitor* visitor);
3020 // Find entry for key otherwise return kNotFound.
3021 inline int FindEntry(Key key);
3022 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3023 int FindEntry(Isolate* isolate, Key key);
3025 // Rehashes the table in-place.
3026 void Rehash(Key key);
3028 // Returns the key at entry.
3029 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3031 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3032 static const int kEntrySize = Shape::kEntrySize;
3033 static const int kElementsStartOffset =
3034 kHeaderSize + kElementsStartIndex * kPointerSize;
3035 static const int kCapacityOffset =
3036 kHeaderSize + kCapacityIndex * kPointerSize;
3038 // Returns the index for an entry (of the key)
3039 static inline int EntryToIndex(int entry) {
3040 return (entry * kEntrySize) + kElementsStartIndex;
3044 friend class ObjectHashTable;
3046 // Find the entry at which to insert element with the given key that
3047 // has the given hash value.
3048 uint32_t FindInsertionEntry(uint32_t hash);
3050 // Attempt to shrink hash table after removal of key.
3051 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3053 // Ensure enough space for n additional elements.
3054 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3055 Handle<Derived> table,
3058 PretenureFlag pretenure = NOT_TENURED);
3060 // Sets the capacity of the hash table.
3061 void SetCapacity(int capacity) {
3062 // To scale a computed hash code to fit within the hash table, we
3063 // use bit-wise AND with a mask, so the capacity must be positive
3065 DCHECK(capacity > 0);
3066 DCHECK(capacity <= kMaxCapacity);
3067 set(kCapacityIndex, Smi::FromInt(capacity));
3070 // Maximal capacity of HashTable. Based on maximal length of underlying
3071 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3073 static const int kMaxCapacity =
3074 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3077 // Returns _expected_ if one of entries given by the first _probe_ probes is
3078 // equal to _expected_. Otherwise, returns the entry given by the probe
3080 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3082 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3084 // Rehashes this hash-table into the new table.
3085 void Rehash(Handle<Derived> new_table, Key key);
3089 // HashTableKey is an abstract superclass for virtual key behavior.
3090 class HashTableKey {
3092 // Returns whether the other object matches this key.
3093 virtual bool IsMatch(Object* other) = 0;
3094 // Returns the hash value for this key.
3095 virtual uint32_t Hash() = 0;
3096 // Returns the hash value for object.
3097 virtual uint32_t HashForObject(Object* key) = 0;
3098 // Returns the key object for storing into the hash table.
3099 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3101 virtual ~HashTableKey() {}
3105 class StringTableShape : public BaseShape<HashTableKey*> {
3107 static inline bool IsMatch(HashTableKey* key, Object* value) {
3108 return key->IsMatch(value);
3111 static inline uint32_t Hash(HashTableKey* key) {
3115 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3116 return key->HashForObject(object);
3119 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3121 static const int kPrefixSize = 0;
3122 static const int kEntrySize = 1;
3125 class SeqOneByteString;
3129 // No special elements in the prefix and the element size is 1
3130 // because only the string itself (the key) needs to be stored.
3131 class StringTable: public HashTable<StringTable,
3135 // Find string in the string table. If it is not there yet, it is
3136 // added. The return value is the string found.
3137 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3138 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3139 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3141 // Tries to internalize given string and returns string handle on success
3142 // or an empty handle otherwise.
3143 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3145 Handle<String> string);
3147 // Looks up a string that is equal to the given string and returns
3148 // string handle if it is found, or an empty handle otherwise.
3149 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3151 Handle<String> str);
3152 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3157 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3159 DECLARE_CAST(StringTable)
3162 template <bool seq_one_byte>
3163 friend class JsonParser;
3165 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3169 template <typename Derived, typename Shape, typename Key>
3170 class Dictionary: public HashTable<Derived, Shape, Key> {
3171 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3174 // Returns the value at entry.
3175 Object* ValueAt(int entry) {
3176 return this->get(Derived::EntryToIndex(entry) + 1);
3179 // Set the value for entry.
3180 void ValueAtPut(int entry, Object* value) {
3181 this->set(Derived::EntryToIndex(entry) + 1, value);
3184 // Returns the property details for the property at entry.
3185 PropertyDetails DetailsAt(int entry) {
3186 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3189 // Set the details for entry.
3190 void DetailsAtPut(int entry, PropertyDetails value) {
3191 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3194 // Returns true if property at given entry is deleted.
3195 bool IsDeleted(int entry) {
3196 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3199 // Delete a property from the dictionary.
3200 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3202 // Attempt to shrink the dictionary after deletion of key.
3203 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3204 Handle<Derived> dictionary,
3206 return DerivedHashTable::Shrink(dictionary, key);
3210 // TODO(dcarney): templatize or move to SeededNumberDictionary
3211 void CopyValuesTo(FixedArray* elements);
3213 // Returns the number of elements in the dictionary filtering out properties
3214 // with the specified attributes.
3215 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3217 // Returns the number of enumerable elements in the dictionary.
3218 int NumberOfEnumElements() {
3219 return NumberOfElementsFilterAttributes(
3220 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3223 // Returns true if the dictionary contains any elements that are non-writable,
3224 // non-configurable, non-enumerable, or have getters/setters.
3225 bool HasComplexElements();
3227 enum SortMode { UNSORTED, SORTED };
3229 // Fill in details for properties into storage.
3230 // Returns the number of properties added.
3231 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3232 SortMode sort_mode);
3234 // Copies enumerable keys to preallocated fixed array.
3235 void CopyEnumKeysTo(FixedArray* storage);
3237 // Accessors for next enumeration index.
3238 void SetNextEnumerationIndex(int index) {
3240 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3243 int NextEnumerationIndex() {
3244 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3247 // Creates a new dictionary.
3248 MUST_USE_RESULT static Handle<Derived> New(
3250 int at_least_space_for,
3251 PretenureFlag pretenure = NOT_TENURED);
3253 // Ensure enough space for n additional elements.
3254 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3257 void Print(std::ostream& os); // NOLINT
3259 // Returns the key (slow).
3260 Object* SlowReverseLookup(Object* value);
3262 // Sets the entry to (key, value) pair.
3263 inline void SetEntry(int entry,
3265 Handle<Object> value);
3266 inline void SetEntry(int entry,
3268 Handle<Object> value,
3269 PropertyDetails details);
3271 MUST_USE_RESULT static Handle<Derived> Add(
3272 Handle<Derived> dictionary,
3274 Handle<Object> value,
3275 PropertyDetails details);
3277 // Returns iteration indices array for the |dictionary|.
3278 // Values are direct indices in the |HashTable| array.
3279 static Handle<FixedArray> BuildIterationIndicesArray(
3280 Handle<Derived> dictionary);
3283 // Generic at put operation.
3284 MUST_USE_RESULT static Handle<Derived> AtPut(
3285 Handle<Derived> dictionary,
3287 Handle<Object> value);
3289 // Add entry to dictionary.
3290 static void AddEntry(
3291 Handle<Derived> dictionary,
3293 Handle<Object> value,
3294 PropertyDetails details,
3297 // Generate new enumeration indices to avoid enumeration index overflow.
3298 // Returns iteration indices array for the |dictionary|.
3299 static Handle<FixedArray> GenerateNewEnumerationIndices(
3300 Handle<Derived> dictionary);
3301 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3302 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3306 template <typename Derived, typename Shape>
3307 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3308 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3311 // Find entry for key, otherwise return kNotFound. Optimized version of
3312 // HashTable::FindEntry.
3313 int FindEntry(Handle<Name> key);
3317 template <typename Key>
3318 class BaseDictionaryShape : public BaseShape<Key> {
3320 template <typename Dictionary>
3321 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3322 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3323 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3324 return PropertyDetails(
3325 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3328 template <typename Dictionary>
3329 static inline void DetailsAtPut(Dictionary* dict, int entry,
3330 PropertyDetails value) {
3331 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3332 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3335 template <typename Dictionary>
3336 static bool IsDeleted(Dictionary* dict, int entry) {
3340 template <typename Dictionary>
3341 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3342 Handle<Object> value, PropertyDetails details);
3346 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3348 static inline bool IsMatch(Handle<Name> key, Object* other);
3349 static inline uint32_t Hash(Handle<Name> key);
3350 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3351 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3352 static const int kPrefixSize = 2;
3353 static const int kEntrySize = 3;
3354 static const bool kIsEnumerable = true;
3358 class NameDictionary
3359 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3360 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3364 DECLARE_CAST(NameDictionary)
3366 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3367 Handle<NameDictionary> dictionary);
3371 class GlobalDictionaryShape : public NameDictionaryShape {
3373 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3375 template <typename Dictionary>
3376 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3378 template <typename Dictionary>
3379 static inline void DetailsAtPut(Dictionary* dict, int entry,
3380 PropertyDetails value);
3382 template <typename Dictionary>
3383 static bool IsDeleted(Dictionary* dict, int entry);
3385 template <typename Dictionary>
3386 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3387 Handle<Object> value, PropertyDetails details);
3391 class GlobalDictionary
3392 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3394 DECLARE_CAST(GlobalDictionary)
3398 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3400 static inline bool IsMatch(uint32_t key, Object* other);
3401 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3402 static const int kEntrySize = 3;
3403 static const bool kIsEnumerable = false;
3407 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3409 static const bool UsesSeed = true;
3410 static const int kPrefixSize = 2;
3412 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3413 static inline uint32_t SeededHashForObject(uint32_t key,
3419 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3421 static const int kPrefixSize = 0;
3423 static inline uint32_t Hash(uint32_t key);
3424 static inline uint32_t HashForObject(uint32_t key, Object* object);
3428 class SeededNumberDictionary
3429 : public Dictionary<SeededNumberDictionary,
3430 SeededNumberDictionaryShape,
3433 DECLARE_CAST(SeededNumberDictionary)
3435 // Type specific at put (default NONE attributes is used when adding).
3436 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3437 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3438 Handle<Object> value, bool used_as_prototype);
3439 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3440 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3441 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3443 // Set an existing entry or add a new one if needed.
3444 // Return the updated dictionary.
3445 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3446 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3447 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3449 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3451 // If slow elements are required we will never go back to fast-case
3452 // for the elements kept in this dictionary. We require slow
3453 // elements if an element has been added at an index larger than
3454 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3455 // when defining a getter or setter with a number key.
3456 inline bool requires_slow_elements();
3457 inline void set_requires_slow_elements();
3459 // Get the value of the max number key that has been added to this
3460 // dictionary. max_number_key can only be called if
3461 // requires_slow_elements returns false.
3462 inline uint32_t max_number_key();
3465 static const int kRequiresSlowElementsMask = 1;
3466 static const int kRequiresSlowElementsTagSize = 1;
3467 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3471 class UnseededNumberDictionary
3472 : public Dictionary<UnseededNumberDictionary,
3473 UnseededNumberDictionaryShape,
3476 DECLARE_CAST(UnseededNumberDictionary)
3478 // Type specific at put (default NONE attributes is used when adding).
3479 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3480 Handle<UnseededNumberDictionary> dictionary,
3482 Handle<Object> value);
3483 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3484 Handle<UnseededNumberDictionary> dictionary,
3486 Handle<Object> value);
3488 // Set an existing entry or add a new one if needed.
3489 // Return the updated dictionary.
3490 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3491 Handle<UnseededNumberDictionary> dictionary,
3493 Handle<Object> value);
3497 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3499 static inline bool IsMatch(Handle<Object> key, Object* other);
3500 static inline uint32_t Hash(Handle<Object> key);
3501 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3502 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3503 static const int kPrefixSize = 0;
3504 static const int kEntrySize = 2;
3508 // ObjectHashTable maps keys that are arbitrary objects to object values by
3509 // using the identity hash of the key for hashing purposes.
3510 class ObjectHashTable: public HashTable<ObjectHashTable,
3511 ObjectHashTableShape,
3514 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3516 DECLARE_CAST(ObjectHashTable)
3518 // Attempt to shrink hash table after removal of key.
3519 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3520 Handle<ObjectHashTable> table,
3521 Handle<Object> key);
3523 // Looks up the value associated with the given key. The hole value is
3524 // returned in case the key is not present.
3525 Object* Lookup(Handle<Object> key);
3526 Object* Lookup(Handle<Object> key, int32_t hash);
3527 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3529 // Adds (or overwrites) the value associated with the given key.
3530 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3532 Handle<Object> value);
3533 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3534 Handle<Object> key, Handle<Object> value,
3537 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3538 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3541 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3542 Handle<Object> key, bool* was_present,
3546 friend class MarkCompactCollector;
3548 void AddEntry(int entry, Object* key, Object* value);
3549 void RemoveEntry(int entry);
3551 // Returns the index to the value of an entry.
3552 static inline int EntryToValueIndex(int entry) {
3553 return EntryToIndex(entry) + 1;
3558 // OrderedHashTable is a HashTable with Object keys that preserves
3559 // insertion order. There are Map and Set interfaces (OrderedHashMap
3560 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3562 // Only Object* keys are supported, with Object::SameValueZero() used as the
3563 // equality operator and Object::GetHash() for the hash function.
3565 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3566 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3567 // Originally attributed to Tyler Close.
3570 // [0]: bucket count
3571 // [1]: element count
3572 // [2]: deleted element count
3573 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3574 // offset into the data table (see below) where the
3575 // first item in this bucket is stored.
3576 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3577 // Capacity() * kEntrySize, where the first entrysize
3578 // items are handled by the derived class and the
3579 // item at kChainOffset is another entry into the
3580 // data table indicating the next entry in this hash
3583 // When we transition the table to a new version we obsolete it and reuse parts
3584 // of the memory to store information how to transition an iterator to the new
3587 // Memory layout for obsolete table:
3588 // [0]: bucket count
3589 // [1]: Next newer table
3590 // [2]: Number of removed holes or -1 when the table was cleared.
3591 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3592 // [3 + NumberOfRemovedHoles()..length]: Not used
3594 template<class Derived, class Iterator, int entrysize>
3595 class OrderedHashTable: public FixedArray {
3597 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3598 static Handle<Derived> Allocate(
3599 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3601 // Returns an OrderedHashTable (possibly |table|) with enough space
3602 // to add at least one new element.
3603 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3605 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3607 static Handle<Derived> Shrink(Handle<Derived> table);
3609 // Returns a new empty OrderedHashTable and records the clearing so that
3610 // exisiting iterators can be updated.
3611 static Handle<Derived> Clear(Handle<Derived> table);
3613 int NumberOfElements() {
3614 return Smi::cast(get(kNumberOfElementsIndex))->value();
3617 int NumberOfDeletedElements() {
3618 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3621 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3623 int NumberOfBuckets() {
3624 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3627 // Returns an index into |this| for the given entry.
3628 int EntryToIndex(int entry) {
3629 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3632 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3635 return !get(kNextTableIndex)->IsSmi();
3638 // The next newer table. This is only valid if the table is obsolete.
3639 Derived* NextTable() {
3640 return Derived::cast(get(kNextTableIndex));
3643 // When the table is obsolete we store the indexes of the removed holes.
3644 int RemovedIndexAt(int index) {
3645 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3648 static const int kNotFound = -1;
3649 static const int kMinCapacity = 4;
3651 static const int kNumberOfBucketsIndex = 0;
3652 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3653 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3654 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3655 static const int kNextTableIndex = kNumberOfElementsIndex;
3657 static const int kNumberOfBucketsOffset =
3658 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3659 static const int kNumberOfElementsOffset =
3660 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3661 static const int kNumberOfDeletedElementsOffset =
3662 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3663 static const int kHashTableStartOffset =
3664 kHeaderSize + kHashTableStartIndex * kPointerSize;
3665 static const int kNextTableOffset =
3666 kHeaderSize + kNextTableIndex * kPointerSize;
3668 static const int kEntrySize = entrysize + 1;
3669 static const int kChainOffset = entrysize;
3671 static const int kLoadFactor = 2;
3673 // NumberOfDeletedElements is set to kClearedTableSentinel when
3674 // the table is cleared, which allows iterator transitions to
3675 // optimize that case.
3676 static const int kClearedTableSentinel = -1;
3679 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3681 void SetNumberOfBuckets(int num) {
3682 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3685 void SetNumberOfElements(int num) {
3686 set(kNumberOfElementsIndex, Smi::FromInt(num));
3689 void SetNumberOfDeletedElements(int num) {
3690 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3694 return NumberOfBuckets() * kLoadFactor;
3697 void SetNextTable(Derived* next_table) {
3698 set(kNextTableIndex, next_table);
3701 void SetRemovedIndexAt(int index, int removed_index) {
3702 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3705 static const int kRemovedHolesIndex = kHashTableStartIndex;
3707 static const int kMaxCapacity =
3708 (FixedArray::kMaxLength - kHashTableStartIndex)
3709 / (1 + (kEntrySize * kLoadFactor));
3713 class JSSetIterator;
3716 class OrderedHashSet: public OrderedHashTable<
3717 OrderedHashSet, JSSetIterator, 1> {
3719 DECLARE_CAST(OrderedHashSet)
3723 class JSMapIterator;
3726 class OrderedHashMap
3727 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3729 DECLARE_CAST(OrderedHashMap)
3731 inline Object* ValueAt(int entry);
3733 static const int kValueOffset = 1;
3737 template <int entrysize>
3738 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3740 static inline bool IsMatch(Handle<Object> key, Object* other);
3741 static inline uint32_t Hash(Handle<Object> key);
3742 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3743 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3744 static const int kPrefixSize = 0;
3745 static const int kEntrySize = entrysize;
3749 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3750 // values. The table wraps the keys in weak cells and store values directly.
3751 // Thus it references keys weakly and values strongly.
3752 class WeakHashTable: public HashTable<WeakHashTable,
3753 WeakHashTableShape<2>,
3756 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3758 DECLARE_CAST(WeakHashTable)
3760 // Looks up the value associated with the given key. The hole value is
3761 // returned in case the key is not present.
3762 Object* Lookup(Handle<HeapObject> key);
3764 // Adds (or overwrites) the value associated with the given key. Mapping a
3765 // key to the hole value causes removal of the whole entry.
3766 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3767 Handle<HeapObject> key,
3768 Handle<HeapObject> value);
3770 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3773 friend class MarkCompactCollector;
3775 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3777 // Returns the index to the value of an entry.
3778 static inline int EntryToValueIndex(int entry) {
3779 return EntryToIndex(entry) + 1;
3784 // ScopeInfo represents information about different scopes of a source
3785 // program and the allocation of the scope's variables. Scope information
3786 // is stored in a compressed form in ScopeInfo objects and is used
3787 // at runtime (stack dumps, deoptimization, etc.).
3789 // This object provides quick access to scope info details for runtime
3791 class ScopeInfo : public FixedArray {
3793 DECLARE_CAST(ScopeInfo)
3795 // Return the type of this scope.
3796 ScopeType scope_type();
3798 // Does this scope call eval?
3801 // Return the language mode of this scope.
3802 LanguageMode language_mode();
3804 // True if this scope is a (var) declaration scope.
3805 bool is_declaration_scope();
3807 // Does this scope make a sloppy eval call?
3808 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3810 // Return the total number of locals allocated on the stack and in the
3811 // context. This includes the parameters that are allocated in the context.
3814 // Return the number of stack slots for code. This number consists of two
3816 // 1. One stack slot per stack allocated local.
3817 // 2. One stack slot for the function name if it is stack allocated.
3818 int StackSlotCount();
3820 // Return the number of context slots for code if a context is allocated. This
3821 // number consists of three parts:
3822 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3823 // 2. One context slot per context allocated local.
3824 // 3. One context slot for the function name if it is context allocated.
3825 // Parameters allocated in the context count as context allocated locals. If
3826 // no contexts are allocated for this scope ContextLength returns 0.
3827 int ContextLength();
3829 // Does this scope declare a "this" binding?
3832 // Does this scope declare a "this" binding, and the "this" binding is stack-
3833 // or context-allocated?
3834 bool HasAllocatedReceiver();
3836 // Is this scope the scope of a named function expression?
3837 bool HasFunctionName();
3839 // Return if this has context allocated locals.
3840 bool HasHeapAllocatedLocals();
3842 // Return if contexts are allocated for this scope.
3845 // Return if this is a function scope with "use asm".
3846 inline bool IsAsmModule();
3848 // Return if this is a nested function within an asm module scope.
3849 inline bool IsAsmFunction();
3851 inline bool HasSimpleParameters();
3853 // Return the function_name if present.
3854 String* FunctionName();
3856 // Return the name of the given parameter.
3857 String* ParameterName(int var);
3859 // Return the name of the given local.
3860 String* LocalName(int var);
3862 // Return the name of the given stack local.
3863 String* StackLocalName(int var);
3865 // Return the name of the given stack local.
3866 int StackLocalIndex(int var);
3868 // Return the name of the given context local.
3869 String* ContextLocalName(int var);
3871 // Return the mode of the given context local.
3872 VariableMode ContextLocalMode(int var);
3874 // Return the initialization flag of the given context local.
3875 InitializationFlag ContextLocalInitFlag(int var);
3877 // Return the initialization flag of the given context local.
3878 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3880 // Return true if this local was introduced by the compiler, and should not be
3881 // exposed to the user in a debugger.
3882 bool LocalIsSynthetic(int var);
3884 String* StrongModeFreeVariableName(int var);
3885 int StrongModeFreeVariableStartPosition(int var);
3886 int StrongModeFreeVariableEndPosition(int var);
3888 // Lookup support for serialized scope info. Returns the
3889 // the stack slot index for a given slot name if the slot is
3890 // present; otherwise returns a value < 0. The name must be an internalized
3892 int StackSlotIndex(String* name);
3894 // Lookup support for serialized scope info. Returns the
3895 // context slot index for a given slot name if the slot is present; otherwise
3896 // returns a value < 0. The name must be an internalized string.
3897 // If the slot is present and mode != NULL, sets *mode to the corresponding
3898 // mode for that variable.
3899 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3900 VariableMode* mode, VariableLocation* location,
3901 InitializationFlag* init_flag,
3902 MaybeAssignedFlag* maybe_assigned_flag);
3904 // Lookup the name of a certain context slot by its index.
3905 String* ContextSlotName(int slot_index);
3907 // Lookup support for serialized scope info. Returns the
3908 // parameter index for a given parameter name if the parameter is present;
3909 // otherwise returns a value < 0. The name must be an internalized string.
3910 int ParameterIndex(String* name);
3912 // Lookup support for serialized scope info. Returns the function context
3913 // slot index if the function name is present and context-allocated (named
3914 // function expressions, only), otherwise returns a value < 0. The name
3915 // must be an internalized string.
3916 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3918 // Lookup support for serialized scope info. Returns the receiver context
3919 // slot index if scope has a "this" binding, and the binding is
3920 // context-allocated. Otherwise returns a value < 0.
3921 int ReceiverContextSlotIndex();
3923 FunctionKind function_kind();
3925 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3926 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3928 // Serializes empty scope info.
3929 static ScopeInfo* Empty(Isolate* isolate);
3935 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3936 // numeric and occupies one array slot.
3937 // 1. A set of properties of the scope
3938 // 2. The number of parameters. This only applies to function scopes. For
3939 // non-function scopes this is 0.
3940 // 3. The number of non-parameter variables allocated on the stack.
3941 // 4. The number of non-parameter and parameter variables allocated in the
3943 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3946 V(StackLocalCount) \
3947 V(ContextLocalCount) \
3948 V(ContextGlobalCount) \
3949 V(StrongModeFreeVariableCount)
3951 #define FIELD_ACCESSORS(name) \
3952 inline void Set##name(int value); \
3954 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3955 #undef FIELD_ACCESSORS
3959 #define DECL_INDEX(name) k##name,
3960 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3965 // The layout of the variable part of a ScopeInfo is as follows:
3966 // 1. ParameterEntries:
3967 // This part stores the names of the parameters for function scopes. One
3968 // slot is used per parameter, so in total this part occupies
3969 // ParameterCount() slots in the array. For other scopes than function
3970 // scopes ParameterCount() is 0.
3971 // 2. StackLocalFirstSlot:
3972 // Index of a first stack slot for stack local. Stack locals belonging to
3973 // this scope are located on a stack at slots starting from this index.
3974 // 3. StackLocalEntries:
3975 // Contains the names of local variables that are allocated on the stack,
3976 // in increasing order of the stack slot index. First local variable has
3977 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3978 // One slot is used per stack local, so in total this part occupies
3979 // StackLocalCount() slots in the array.
3980 // 4. ContextLocalNameEntries:
3981 // Contains the names of local variables and parameters that are allocated
3982 // in the context. They are stored in increasing order of the context slot
3983 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3984 // context local, so in total this part occupies ContextLocalCount() slots
3986 // 5. ContextLocalInfoEntries:
3987 // Contains the variable modes and initialization flags corresponding to
3988 // the context locals in ContextLocalNameEntries. One slot is used per
3989 // context local, so in total this part occupies ContextLocalCount()
3990 // slots in the array.
3991 // 6. StrongModeFreeVariableNameEntries:
3992 // Stores the names of strong mode free variables.
3993 // 7. StrongModeFreeVariablePositionEntries:
3994 // Stores the locations (start and end position) of strong mode free
3996 // 8. RecieverEntryIndex:
3997 // If the scope binds a "this" value, one slot is reserved to hold the
3998 // context or stack slot index for the variable.
3999 // 9. FunctionNameEntryIndex:
4000 // If the scope belongs to a named function expression this part contains
4001 // information about the function variable. It always occupies two array
4002 // slots: a. The name of the function variable.
4003 // b. The context or stack slot index for the variable.
4004 int ParameterEntriesIndex();
4005 int StackLocalFirstSlotIndex();
4006 int StackLocalEntriesIndex();
4007 int ContextLocalNameEntriesIndex();
4008 int ContextGlobalNameEntriesIndex();
4009 int ContextLocalInfoEntriesIndex();
4010 int ContextGlobalInfoEntriesIndex();
4011 int StrongModeFreeVariableNameEntriesIndex();
4012 int StrongModeFreeVariablePositionEntriesIndex();
4013 int ReceiverEntryIndex();
4014 int FunctionNameEntryIndex();
4016 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4017 VariableLocation* location, InitializationFlag* init_flag,
4018 MaybeAssignedFlag* maybe_assigned_flag);
4020 // Used for the function name variable for named function expressions, and for
4022 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4024 // Properties of scopes.
4025 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4026 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4027 STATIC_ASSERT(LANGUAGE_END == 3);
4028 class LanguageModeField
4029 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4030 class DeclarationScopeField
4031 : public BitField<bool, LanguageModeField::kNext, 1> {};
4032 class ReceiverVariableField
4033 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4035 class FunctionVariableField
4036 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4038 class FunctionVariableMode
4039 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4040 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4042 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4043 class HasSimpleParametersField
4044 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4045 class FunctionKindField
4046 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4048 // BitFields representing the encoded information for context locals in the
4049 // ContextLocalInfoEntries part.
4050 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4051 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4052 class ContextLocalMaybeAssignedFlag
4053 : public BitField<MaybeAssignedFlag, 4, 1> {};
4055 friend class ScopeIterator;
4059 // The cache for maps used by normalized (dictionary mode) objects.
4060 // Such maps do not have property descriptors, so a typical program
4061 // needs very limited number of distinct normalized maps.
4062 class NormalizedMapCache: public FixedArray {
4064 static Handle<NormalizedMapCache> New(Isolate* isolate);
4066 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4067 PropertyNormalizationMode mode);
4068 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4072 DECLARE_CAST(NormalizedMapCache)
4074 static inline bool IsNormalizedMapCache(const Object* obj);
4076 DECLARE_VERIFIER(NormalizedMapCache)
4078 static const int kEntries = 64;
4080 static inline int GetIndex(Handle<Map> map);
4082 // The following declarations hide base class methods.
4083 Object* get(int index);
4084 void set(int index, Object* value);
4088 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4089 // that is attached to code objects.
4090 class ByteArray: public FixedArrayBase {
4094 // Setter and getter.
4095 inline byte get(int index);
4096 inline void set(int index, byte value);
4098 // Treat contents as an int array.
4099 inline int get_int(int index);
4101 static int SizeFor(int length) {
4102 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4104 // We use byte arrays for free blocks in the heap. Given a desired size in
4105 // bytes that is a multiple of the word size and big enough to hold a byte
4106 // array, this function returns the number of elements a byte array should
4108 static int LengthFor(int size_in_bytes) {
4109 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4110 DCHECK(size_in_bytes >= kHeaderSize);
4111 return size_in_bytes - kHeaderSize;
4114 // Returns data start address.
4115 inline Address GetDataStartAddress();
4117 // Returns a pointer to the ByteArray object for a given data start address.
4118 static inline ByteArray* FromDataStartAddress(Address address);
4120 DECLARE_CAST(ByteArray)
4122 // Dispatched behavior.
4123 inline int ByteArraySize();
4124 DECLARE_PRINTER(ByteArray)
4125 DECLARE_VERIFIER(ByteArray)
4127 // Layout description.
4128 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4130 // Maximal memory consumption for a single ByteArray.
4131 static const int kMaxSize = 512 * MB;
4132 // Maximal length of a single ByteArray.
4133 static const int kMaxLength = kMaxSize - kHeaderSize;
4136 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4140 // BytecodeArray represents a sequence of interpreter bytecodes.
4141 class BytecodeArray : public FixedArrayBase {
4143 static int SizeFor(int length) {
4144 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4147 // Setter and getter
4148 inline byte get(int index);
4149 inline void set(int index, byte value);
4151 // Returns data start address.
4152 inline Address GetFirstBytecodeAddress();
4154 // Accessors for frame size.
4155 inline int frame_size() const;
4156 inline void set_frame_size(int frame_size);
4158 // Accessors for parameter count (including implicit 'this' receiver).
4159 inline int parameter_count() const;
4160 inline void set_parameter_count(int number_of_parameters);
4162 // Accessors for the constant pool.
4163 DECL_ACCESSORS(constant_pool, FixedArray)
4165 DECLARE_CAST(BytecodeArray)
4167 // Dispatched behavior.
4168 inline int BytecodeArraySize();
4169 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4171 DECLARE_PRINTER(BytecodeArray)
4172 DECLARE_VERIFIER(BytecodeArray)
4174 void Disassemble(std::ostream& os);
4176 // Layout description.
4177 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4178 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4179 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4180 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4182 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4184 // Maximal memory consumption for a single BytecodeArray.
4185 static const int kMaxSize = 512 * MB;
4186 // Maximal length of a single BytecodeArray.
4187 static const int kMaxLength = kMaxSize - kHeaderSize;
4190 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4194 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4195 // They look like heap objects (are heap object tagged and have a map) so that
4196 // the heap remains iterable. They have a size and a next pointer.
4197 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4198 // in the free list.
4199 class FreeSpace: public HeapObject {
4201 // [size]: size of the free space including the header.
4202 inline int size() const;
4203 inline void set_size(int value);
4205 inline int nobarrier_size() const;
4206 inline void nobarrier_set_size(int value);
4210 // Accessors for the next field.
4211 inline FreeSpace* next();
4212 inline FreeSpace** next_address();
4213 inline void set_next(FreeSpace* next);
4215 inline static FreeSpace* cast(HeapObject* obj);
4217 // Dispatched behavior.
4218 DECLARE_PRINTER(FreeSpace)
4219 DECLARE_VERIFIER(FreeSpace)
4221 // Layout description.
4222 // Size is smi tagged when it is stored.
4223 static const int kSizeOffset = HeapObject::kHeaderSize;
4224 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4227 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4231 // V has parameters (Type, type, TYPE, C type, element_size)
4232 #define TYPED_ARRAYS(V) \
4233 V(Uint8, uint8, UINT8, uint8_t, 1) \
4234 V(Int8, int8, INT8, int8_t, 1) \
4235 V(Uint16, uint16, UINT16, uint16_t, 2) \
4236 V(Int16, int16, INT16, int16_t, 2) \
4237 V(Uint32, uint32, UINT32, uint32_t, 4) \
4238 V(Int32, int32, INT32, int32_t, 4) \
4239 V(Float32, float32, FLOAT32, float, 4) \
4240 V(Float64, float64, FLOAT64, double, 8) \
4241 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4244 class FixedTypedArrayBase: public FixedArrayBase {
4246 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4247 DECL_ACCESSORS(base_pointer, Object)
4249 // [external_pointer]: Contains the offset between base_pointer and the start
4250 // of the data. If the base_pointer is a nullptr, the external_pointer
4251 // therefore points to the actual backing store.
4252 DECL_ACCESSORS(external_pointer, void)
4254 // Dispatched behavior.
4255 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4257 template <typename StaticVisitor>
4258 inline void FixedTypedArrayBaseIterateBody();
4260 DECLARE_CAST(FixedTypedArrayBase)
4262 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4263 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4264 static const int kHeaderSize =
4265 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4267 static const int kDataOffset = kHeaderSize;
4271 static inline int TypedArraySize(InstanceType type, int length);
4272 inline int TypedArraySize(InstanceType type);
4274 // Use with care: returns raw pointer into heap.
4275 inline void* DataPtr();
4277 inline int DataSize();
4280 static inline int ElementSize(InstanceType type);
4282 inline int DataSize(InstanceType type);
4284 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4288 template <class Traits>
4289 class FixedTypedArray: public FixedTypedArrayBase {
4291 typedef typename Traits::ElementType ElementType;
4292 static const InstanceType kInstanceType = Traits::kInstanceType;
4294 DECLARE_CAST(FixedTypedArray<Traits>)
4296 inline ElementType get_scalar(int index);
4297 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4298 inline void set(int index, ElementType value);
4300 static inline ElementType from_int(int value);
4301 static inline ElementType from_double(double value);
4303 // This accessor applies the correct conversion from Smi, HeapNumber
4305 inline void SetValue(uint32_t index, Object* value);
4307 DECLARE_PRINTER(FixedTypedArray)
4308 DECLARE_VERIFIER(FixedTypedArray)
4311 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4314 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4315 class Type##ArrayTraits { \
4316 public: /* NOLINT */ \
4317 typedef elementType ElementType; \
4318 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4319 static const char* Designator() { return #type " array"; } \
4320 static inline Handle<Object> ToHandle(Isolate* isolate, \
4321 elementType scalar); \
4322 static inline elementType defaultValue(); \
4325 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4327 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4329 #undef FIXED_TYPED_ARRAY_TRAITS
4332 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4333 // data for code generated by the Hydrogen/Lithium compiler. It also
4334 // contains information about functions that were inlined. If N different
4335 // functions were inlined then first N elements of the literal array will
4336 // contain these functions.
4339 class DeoptimizationInputData: public FixedArray {
4341 // Layout description. Indices in the array.
4342 static const int kTranslationByteArrayIndex = 0;
4343 static const int kInlinedFunctionCountIndex = 1;
4344 static const int kLiteralArrayIndex = 2;
4345 static const int kOsrAstIdIndex = 3;
4346 static const int kOsrPcOffsetIndex = 4;
4347 static const int kOptimizationIdIndex = 5;
4348 static const int kSharedFunctionInfoIndex = 6;
4349 static const int kWeakCellCacheIndex = 7;
4350 static const int kFirstDeoptEntryIndex = 8;
4352 // Offsets of deopt entry elements relative to the start of the entry.
4353 static const int kAstIdRawOffset = 0;
4354 static const int kTranslationIndexOffset = 1;
4355 static const int kArgumentsStackHeightOffset = 2;
4356 static const int kPcOffset = 3;
4357 static const int kDeoptEntrySize = 4;
4359 // Simple element accessors.
4360 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4361 inline type* name(); \
4362 inline void Set##name(type* value);
4364 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4365 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4366 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4367 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4368 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4369 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4370 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4371 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4373 #undef DECLARE_ELEMENT_ACCESSORS
4375 // Accessors for elements of the ith deoptimization entry.
4376 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4377 inline type* name(int i); \
4378 inline void Set##name(int i, type* value);
4380 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4381 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4382 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4383 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4385 #undef DECLARE_ENTRY_ACCESSORS
4387 inline BailoutId AstId(int i);
4389 inline void SetAstId(int i, BailoutId value);
4391 inline int DeoptCount();
4393 // Allocates a DeoptimizationInputData.
4394 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4395 int deopt_entry_count,
4396 PretenureFlag pretenure);
4398 DECLARE_CAST(DeoptimizationInputData)
4400 #ifdef ENABLE_DISASSEMBLER
4401 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4405 static int IndexForEntry(int i) {
4406 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4410 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4414 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4415 // data for code generated by the full compiler.
4416 // The format of the these objects is
4417 // [i * 2]: Ast ID for ith deoptimization.
4418 // [i * 2 + 1]: PC and state of ith deoptimization
4419 class DeoptimizationOutputData: public FixedArray {
4421 inline int DeoptPoints();
4423 inline BailoutId AstId(int index);
4425 inline void SetAstId(int index, BailoutId id);
4427 inline Smi* PcAndState(int index);
4428 inline void SetPcAndState(int index, Smi* offset);
4430 static int LengthOfFixedArray(int deopt_points) {
4431 return deopt_points * 2;
4434 // Allocates a DeoptimizationOutputData.
4435 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4436 int number_of_deopt_points,
4437 PretenureFlag pretenure);
4439 DECLARE_CAST(DeoptimizationOutputData)
4441 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4442 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4447 // HandlerTable is a fixed array containing entries for exception handlers in
4448 // the code object it is associated with. The tables comes in two flavors:
4449 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4450 // exception handler and a range representing the try-block covered by that
4451 // handler. Layout looks as follows:
4452 // [ range-start , range-end , handler-offset , stack-depth ]
4453 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4454 // per call-site that could throw an exception. Layout looks as follows:
4455 // [ return-address-offset , handler-offset ]
4456 class HandlerTable : public FixedArray {
4458 // Conservative prediction whether a given handler will locally catch an
4459 // exception or cause a re-throw to outside the code boundary. Since this is
4460 // undecidable it is merely an approximation (e.g. useful for debugger).
4461 enum CatchPrediction { UNCAUGHT, CAUGHT };
4463 // Accessors for handler table based on ranges.
4464 inline void SetRangeStart(int index, int value);
4465 inline void SetRangeEnd(int index, int value);
4466 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4467 inline void SetRangeDepth(int index, int value);
4469 // Accessors for handler table based on return addresses.
4470 inline void SetReturnOffset(int index, int value);
4471 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4473 // Lookup handler in a table based on ranges.
4474 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4476 // Lookup handler in a table based on return addresses.
4477 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4479 // Returns the required length of the underlying fixed array.
4480 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4481 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4483 DECLARE_CAST(HandlerTable)
4485 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4486 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4487 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4491 // Layout description for handler table based on ranges.
4492 static const int kRangeStartIndex = 0;
4493 static const int kRangeEndIndex = 1;
4494 static const int kRangeHandlerIndex = 2;
4495 static const int kRangeDepthIndex = 3;
4496 static const int kRangeEntrySize = 4;
4498 // Layout description for handler table based on return addresses.
4499 static const int kReturnOffsetIndex = 0;
4500 static const int kReturnHandlerIndex = 1;
4501 static const int kReturnEntrySize = 2;
4503 // Encoding of the {handler} field.
4504 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4505 class HandlerOffsetField : public BitField<int, 1, 30> {};
4509 // Code describes objects with on-the-fly generated machine code.
4510 class Code: public HeapObject {
4512 // Opaque data type for encapsulating code flags like kind, inline
4513 // cache state, and arguments count.
4514 typedef uint32_t Flags;
4516 #define NON_IC_KIND_LIST(V) \
4518 V(OPTIMIZED_FUNCTION) \
4525 #define IC_KIND_LIST(V) \
4536 #define CODE_KIND_LIST(V) \
4537 NON_IC_KIND_LIST(V) \
4541 #define DEFINE_CODE_KIND_ENUM(name) name,
4542 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4543 #undef DEFINE_CODE_KIND_ENUM
4547 // No more than 16 kinds. The value is currently encoded in four bits in
4549 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4551 static const char* Kind2String(Kind kind);
4559 static const int kPrologueOffsetNotSet = -1;
4561 #ifdef ENABLE_DISASSEMBLER
4563 static const char* ICState2String(InlineCacheState state);
4564 static const char* StubType2String(StubType type);
4565 static void PrintExtraICState(std::ostream& os, // NOLINT
4566 Kind kind, ExtraICState extra);
4567 void Disassemble(const char* name, std::ostream& os); // NOLINT
4568 #endif // ENABLE_DISASSEMBLER
4570 // [instruction_size]: Size of the native instructions
4571 inline int instruction_size() const;
4572 inline void set_instruction_size(int value);
4574 // [relocation_info]: Code relocation information
4575 DECL_ACCESSORS(relocation_info, ByteArray)
4576 void InvalidateRelocation();
4577 void InvalidateEmbeddedObjects();
4579 // [handler_table]: Fixed array containing offsets of exception handlers.
4580 DECL_ACCESSORS(handler_table, FixedArray)
4582 // [deoptimization_data]: Array containing data for deopt.
4583 DECL_ACCESSORS(deoptimization_data, FixedArray)
4585 // [raw_type_feedback_info]: This field stores various things, depending on
4586 // the kind of the code object.
4587 // FUNCTION => type feedback information.
4588 // STUB and ICs => major/minor key as Smi.
4589 DECL_ACCESSORS(raw_type_feedback_info, Object)
4590 inline Object* type_feedback_info();
4591 inline void set_type_feedback_info(
4592 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4593 inline uint32_t stub_key();
4594 inline void set_stub_key(uint32_t key);
4596 // [next_code_link]: Link for lists of optimized or deoptimized code.
4597 // Note that storage for this field is overlapped with typefeedback_info.
4598 DECL_ACCESSORS(next_code_link, Object)
4600 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4601 // field does not have to be traced during garbage collection since
4602 // it is only used by the garbage collector itself.
4603 DECL_ACCESSORS(gc_metadata, Object)
4605 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4606 // at the moment when this object was created.
4607 inline void set_ic_age(int count);
4608 inline int ic_age() const;
4610 // [prologue_offset]: Offset of the function prologue, used for aging
4611 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4612 inline int prologue_offset() const;
4613 inline void set_prologue_offset(int offset);
4615 // [constant_pool offset]: Offset of the constant pool.
4616 // Valid for FLAG_enable_embedded_constant_pool only
4617 inline int constant_pool_offset() const;
4618 inline void set_constant_pool_offset(int offset);
4620 // Unchecked accessors to be used during GC.
4621 inline ByteArray* unchecked_relocation_info();
4623 inline int relocation_size();
4625 // [flags]: Various code flags.
4626 inline Flags flags();
4627 inline void set_flags(Flags flags);
4629 // [flags]: Access to specific code flags.
4631 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4632 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4634 inline StubType type(); // Only valid for monomorphic IC stubs.
4636 // Testers for IC stub kinds.
4637 inline bool is_inline_cache_stub();
4638 inline bool is_debug_stub();
4639 inline bool is_handler();
4640 inline bool is_load_stub();
4641 inline bool is_keyed_load_stub();
4642 inline bool is_store_stub();
4643 inline bool is_keyed_store_stub();
4644 inline bool is_call_stub();
4645 inline bool is_binary_op_stub();
4646 inline bool is_compare_ic_stub();
4647 inline bool is_compare_nil_ic_stub();
4648 inline bool is_to_boolean_ic_stub();
4649 inline bool is_keyed_stub();
4650 inline bool is_optimized_code();
4651 inline bool embeds_maps_weakly();
4653 inline bool IsCodeStubOrIC();
4654 inline bool IsJavaScriptCode();
4656 inline void set_raw_kind_specific_flags1(int value);
4657 inline void set_raw_kind_specific_flags2(int value);
4659 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4660 // object was generated by either the hydrogen or the TurboFan optimizing
4661 // compiler (but it may not be an optimized function).
4662 inline bool is_crankshafted();
4663 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4664 inline void set_is_crankshafted(bool value);
4666 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4667 // code object was generated by the TurboFan optimizing compiler.
4668 inline bool is_turbofanned();
4669 inline void set_is_turbofanned(bool value);
4671 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4672 // embedded objects in code should be treated weakly.
4673 inline bool can_have_weak_objects();
4674 inline void set_can_have_weak_objects(bool value);
4676 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4677 // deoptimization support.
4678 inline bool has_deoptimization_support();
4679 inline void set_has_deoptimization_support(bool value);
4681 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4682 // been compiled with debug break slots.
4683 inline bool has_debug_break_slots();
4684 inline void set_has_debug_break_slots(bool value);
4686 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4687 // reloc info includes runtime and external references to support
4688 // serialization/deserialization.
4689 inline bool has_reloc_info_for_serialization();
4690 inline void set_has_reloc_info_for_serialization(bool value);
4692 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4693 // how long the function has been marked for OSR and therefore which
4694 // level of loop nesting we are willing to do on-stack replacement
4696 inline void set_allow_osr_at_loop_nesting_level(int level);
4697 inline int allow_osr_at_loop_nesting_level();
4699 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4700 // the code object was seen on the stack with no IC patching going on.
4701 inline int profiler_ticks();
4702 inline void set_profiler_ticks(int ticks);
4704 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4705 // For builtins, tells which builtin index it has.
4706 // Note that builtins can have a code kind other than BUILTIN, which means
4707 // that for arbitrary code objects, this index value may be random garbage.
4708 // To verify in that case, compare the code object to the indexed builtin.
4709 inline int builtin_index();
4710 inline void set_builtin_index(int id);
4712 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4713 // reserved in the code prologue.
4714 inline unsigned stack_slots();
4715 inline void set_stack_slots(unsigned slots);
4717 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4718 // the instruction stream where the safepoint table starts.
4719 inline unsigned safepoint_table_offset();
4720 inline void set_safepoint_table_offset(unsigned offset);
4722 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4723 // instruction stream where the back edge table starts.
4724 inline unsigned back_edge_table_offset();
4725 inline void set_back_edge_table_offset(unsigned offset);
4727 inline bool back_edges_patched_for_osr();
4729 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4730 inline uint16_t to_boolean_state();
4732 // [has_function_cache]: For kind STUB tells whether there is a function
4733 // cache is passed to the stub.
4734 inline bool has_function_cache();
4735 inline void set_has_function_cache(bool flag);
4738 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4739 // the code is going to be deoptimized because of dead embedded maps.
4740 inline bool marked_for_deoptimization();
4741 inline void set_marked_for_deoptimization(bool flag);
4743 // [constant_pool]: The constant pool for this function.
4744 inline Address constant_pool();
4746 // Get the safepoint entry for the given pc.
4747 SafepointEntry GetSafepointEntry(Address pc);
4749 // Find an object in a stub with a specified map
4750 Object* FindNthObject(int n, Map* match_map);
4752 // Find the first allocation site in an IC stub.
4753 AllocationSite* FindFirstAllocationSite();
4755 // Find the first map in an IC stub.
4756 Map* FindFirstMap();
4757 void FindAllMaps(MapHandleList* maps);
4759 // Find the first handler in an IC stub.
4760 Code* FindFirstHandler();
4762 // Find |length| handlers and put them into |code_list|. Returns false if not
4763 // enough handlers can be found.
4764 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4766 // Find the handler for |map|.
4767 MaybeHandle<Code> FindHandlerForMap(Map* map);
4769 // Find the first name in an IC stub.
4770 Name* FindFirstName();
4772 class FindAndReplacePattern;
4773 // For each (map-to-find, object-to-replace) pair in the pattern, this
4774 // function replaces the corresponding placeholder in the code with the
4775 // object-to-replace. The function assumes that pairs in the pattern come in
4776 // the same order as the placeholders in the code.
4777 // If the placeholder is a weak cell, then the value of weak cell is matched
4778 // against the map-to-find.
4779 void FindAndReplace(const FindAndReplacePattern& pattern);
4781 // The entire code object including its header is copied verbatim to the
4782 // snapshot so that it can be written in one, fast, memcpy during
4783 // deserialization. The deserializer will overwrite some pointers, rather
4784 // like a runtime linker, but the random allocation addresses used in the
4785 // mksnapshot process would still be present in the unlinked snapshot data,
4786 // which would make snapshot production non-reproducible. This method wipes
4787 // out the to-be-overwritten header data for reproducible snapshots.
4788 inline void WipeOutHeader();
4790 // Flags operations.
4791 static inline Flags ComputeFlags(
4792 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4793 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4794 CacheHolderFlag holder = kCacheOnReceiver);
4796 static inline Flags ComputeMonomorphicFlags(
4797 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4798 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4800 static inline Flags ComputeHandlerFlags(
4801 Kind handler_kind, StubType type = NORMAL,
4802 CacheHolderFlag holder = kCacheOnReceiver);
4804 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4805 static inline StubType ExtractTypeFromFlags(Flags flags);
4806 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4807 static inline Kind ExtractKindFromFlags(Flags flags);
4808 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4810 static inline Flags RemoveTypeFromFlags(Flags flags);
4811 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4813 // Convert a target address into a code object.
4814 static inline Code* GetCodeFromTargetAddress(Address address);
4816 // Convert an entry address into an object.
4817 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4819 // Returns the address of the first instruction.
4820 inline byte* instruction_start();
4822 // Returns the address right after the last instruction.
4823 inline byte* instruction_end();
4825 // Returns the size of the instructions, padding, and relocation information.
4826 inline int body_size();
4828 // Returns the address of the first relocation info (read backwards!).
4829 inline byte* relocation_start();
4831 // Code entry point.
4832 inline byte* entry();
4834 // Returns true if pc is inside this object's instructions.
4835 inline bool contains(byte* pc);
4837 // Relocate the code by delta bytes. Called to signal that this code
4838 // object has been moved by delta bytes.
4839 void Relocate(intptr_t delta);
4841 // Migrate code described by desc.
4842 void CopyFrom(const CodeDesc& desc);
4844 // Returns the object size for a given body (used for allocation).
4845 static int SizeFor(int body_size) {
4846 DCHECK_SIZE_TAG_ALIGNED(body_size);
4847 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4850 // Calculate the size of the code object to report for log events. This takes
4851 // the layout of the code object into account.
4852 inline int ExecutableSize();
4854 // Locating source position.
4855 int SourcePosition(Address pc);
4856 int SourceStatementPosition(Address pc);
4860 // Dispatched behavior.
4861 inline int CodeSize();
4862 inline void CodeIterateBody(ObjectVisitor* v);
4864 template<typename StaticVisitor>
4865 inline void CodeIterateBody(Heap* heap);
4867 DECLARE_PRINTER(Code)
4868 DECLARE_VERIFIER(Code)
4870 void ClearInlineCaches();
4871 void ClearInlineCaches(Kind kind);
4873 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4874 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4876 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4878 kToBeExecutedOnceCodeAge = -3,
4879 kNotExecutedCodeAge = -2,
4880 kExecutedOnceCodeAge = -1,
4882 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4884 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4885 kLastCodeAge = kAfterLastCodeAge - 1,
4886 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4887 kIsOldCodeAge = kSexagenarianCodeAge,
4888 kPreAgedCodeAge = kIsOldCodeAge - 1
4890 #undef DECLARE_CODE_AGE_ENUM
4892 // Code aging. Indicates how many full GCs this code has survived without
4893 // being entered through the prologue. Used to determine when it is
4894 // relatively safe to flush this code object and replace it with the lazy
4895 // compilation stub.
4896 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4897 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4898 void MakeYoung(Isolate* isolate);
4899 void MarkToBeExecutedOnce(Isolate* isolate);
4900 void MakeOlder(MarkingParity);
4901 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4904 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4905 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4908 void PrintDeoptLocation(FILE* out, Address pc);
4909 bool CanDeoptAt(Address pc);
4912 void VerifyEmbeddedObjectsDependency();
4916 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4917 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4918 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4921 inline bool CanContainWeakObjects();
4923 inline bool IsWeakObject(Object* object);
4925 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4927 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4928 WeakCell* CachedWeakCell();
4930 // Max loop nesting marker used to postpose OSR. We don't take loop
4931 // nesting that is deeper than 5 levels into account.
4932 static const int kMaxLoopNestingMarker = 6;
4934 static const int kConstantPoolSize =
4935 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4937 // Layout description.
4938 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4939 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4940 static const int kDeoptimizationDataOffset =
4941 kHandlerTableOffset + kPointerSize;
4942 // For FUNCTION kind, we store the type feedback info here.
4943 static const int kTypeFeedbackInfoOffset =
4944 kDeoptimizationDataOffset + kPointerSize;
4945 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4946 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4947 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4948 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4949 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4950 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4951 static const int kKindSpecificFlags2Offset =
4952 kKindSpecificFlags1Offset + kIntSize;
4953 // Note: We might be able to squeeze this into the flags above.
4954 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4955 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4956 static const int kHeaderPaddingStart =
4957 kConstantPoolOffset + kConstantPoolSize;
4959 // Add padding to align the instruction start following right after
4960 // the Code object header.
4961 static const int kHeaderSize =
4962 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4964 // Byte offsets within kKindSpecificFlags1Offset.
4965 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4966 class FullCodeFlagsHasDeoptimizationSupportField:
4967 public BitField<bool, 0, 1> {}; // NOLINT
4968 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4969 class FullCodeFlagsHasRelocInfoForSerialization
4970 : public BitField<bool, 2, 1> {};
4971 // Bit 3 in this bitfield is unused.
4972 class ProfilerTicksField : public BitField<int, 4, 28> {};
4974 // Flags layout. BitField<type, shift, size>.
4975 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4976 class TypeField : public BitField<StubType, 4, 1> {};
4977 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4978 class KindField : public BitField<Kind, 7, 4> {};
4979 class ExtraICStateField: public BitField<ExtraICState, 11,
4980 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4982 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4983 static const int kStackSlotsFirstBit = 0;
4984 static const int kStackSlotsBitCount = 24;
4985 static const int kHasFunctionCacheBit =
4986 kStackSlotsFirstBit + kStackSlotsBitCount;
4987 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4988 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4989 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4991 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4992 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4994 class StackSlotsField: public BitField<int,
4995 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4996 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4998 class MarkedForDeoptimizationField
4999 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5000 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5002 class CanHaveWeakObjectsField
5003 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5005 // KindSpecificFlags2 layout (ALL)
5006 static const int kIsCrankshaftedBit = 0;
5007 class IsCrankshaftedField: public BitField<bool,
5008 kIsCrankshaftedBit, 1> {}; // NOLINT
5010 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5011 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5012 static const int kSafepointTableOffsetBitCount = 30;
5014 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5015 kSafepointTableOffsetBitCount <= 32);
5016 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5018 class SafepointTableOffsetField: public BitField<int,
5019 kSafepointTableOffsetFirstBit,
5020 kSafepointTableOffsetBitCount> {}; // NOLINT
5022 // KindSpecificFlags2 layout (FUNCTION)
5023 class BackEdgeTableOffsetField: public BitField<int,
5024 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5025 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5026 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5027 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5029 static const int kArgumentsBits = 16;
5030 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5032 // This constant should be encodable in an ARM instruction.
5033 static const int kFlagsNotUsedInLookup =
5034 TypeField::kMask | CacheHolderField::kMask;
5037 friend class RelocIterator;
5038 friend class Deoptimizer; // For FindCodeAgeSequence.
5040 void ClearInlineCaches(Kind* kind);
5043 byte* FindCodeAgeSequence();
5044 static void GetCodeAgeAndParity(Code* code, Age* age,
5045 MarkingParity* parity);
5046 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5047 MarkingParity* parity);
5048 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5050 // Code aging -- platform-specific
5051 static void PatchPlatformCodeAge(Isolate* isolate,
5052 byte* sequence, Age age,
5053 MarkingParity parity);
5055 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5059 // This class describes the layout of dependent codes array of a map. The
5060 // array is partitioned into several groups of dependent codes. Each group
5061 // contains codes with the same dependency on the map. The array has the
5062 // following layout for n dependency groups:
5064 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5065 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5066 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5068 // The first n elements are Smis, each of them specifies the number of codes
5069 // in the corresponding group. The subsequent elements contain grouped code
5070 // objects in weak cells. The suffix of the array can be filled with the
5071 // undefined value if the number of codes is less than the length of the
5072 // array. The order of the code objects within a group is not preserved.
5074 // All code indexes used in the class are counted starting from the first
5075 // code object of the first group. In other words, code index 0 corresponds
5076 // to array index n = kCodesStartIndex.
5078 class DependentCode: public FixedArray {
5080 enum DependencyGroup {
5081 // Group of code that weakly embed this map and depend on being
5082 // deoptimized when the map is garbage collected.
5084 // Group of code that embed a transition to this map, and depend on being
5085 // deoptimized when the transition is replaced by a new version.
5087 // Group of code that omit run-time prototype checks for prototypes
5088 // described by this map. The group is deoptimized whenever an object
5089 // described by this map changes shape (and transitions to a new map),
5090 // possibly invalidating the assumptions embedded in the code.
5091 kPrototypeCheckGroup,
5092 // Group of code that depends on global property values in property cells
5093 // not being changed.
5094 kPropertyCellChangedGroup,
5095 // Group of code that omit run-time type checks for the field(s) introduced
5098 // Group of code that omit run-time type checks for initial maps of
5100 kInitialMapChangedGroup,
5101 // Group of code that depends on tenuring information in AllocationSites
5102 // not being changed.
5103 kAllocationSiteTenuringChangedGroup,
5104 // Group of code that depends on element transition information in
5105 // AllocationSites not being changed.
5106 kAllocationSiteTransitionChangedGroup
5109 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5111 // Array for holding the index of the first code object of each group.
5112 // The last element stores the total number of code objects.
5113 class GroupStartIndexes {
5115 explicit GroupStartIndexes(DependentCode* entries);
5116 void Recompute(DependentCode* entries);
5117 int at(int i) { return start_indexes_[i]; }
5118 int number_of_entries() { return start_indexes_[kGroupCount]; }
5120 int start_indexes_[kGroupCount + 1];
5123 bool Contains(DependencyGroup group, WeakCell* code_cell);
5125 static Handle<DependentCode> InsertCompilationDependencies(
5126 Handle<DependentCode> entries, DependencyGroup group,
5127 Handle<Foreign> info);
5129 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5130 DependencyGroup group,
5131 Handle<WeakCell> code_cell);
5133 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5134 WeakCell* code_cell);
5136 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5139 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5140 DependentCode::DependencyGroup group);
5142 bool MarkCodeForDeoptimization(Isolate* isolate,
5143 DependentCode::DependencyGroup group);
5145 // The following low-level accessors should only be used by this class
5146 // and the mark compact collector.
5147 inline int number_of_entries(DependencyGroup group);
5148 inline void set_number_of_entries(DependencyGroup group, int value);
5149 inline Object* object_at(int i);
5150 inline void set_object_at(int i, Object* object);
5151 inline void clear_at(int i);
5152 inline void copy(int from, int to);
5153 DECLARE_CAST(DependentCode)
5155 static const char* DependencyGroupName(DependencyGroup group);
5156 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5159 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5160 DependencyGroup group,
5161 Handle<Object> object);
5162 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5163 // Make a room at the end of the given group by moving out the first
5164 // code objects of the subsequent groups.
5165 inline void ExtendGroup(DependencyGroup group);
5166 // Compact by removing cleared weak cells and return true if there was
5167 // any cleared weak cell.
5169 static int Grow(int number_of_entries) {
5170 if (number_of_entries < 5) return number_of_entries + 1;
5171 return number_of_entries * 5 / 4;
5173 static const int kCodesStartIndex = kGroupCount;
5177 class PrototypeInfo;
5180 // All heap objects have a Map that describes their structure.
5181 // A Map contains information about:
5182 // - Size information about the object
5183 // - How to iterate over an object (for garbage collection)
5184 class Map: public HeapObject {
5187 // Size in bytes or kVariableSizeSentinel if instances do not have
5189 inline int instance_size();
5190 inline void set_instance_size(int value);
5192 // Only to clear an unused byte, remove once byte is used.
5193 inline void clear_unused();
5195 // [inobject_properties_or_constructor_function_index]: Provides access
5196 // to the inobject properties in case of JSObject maps, or the constructor
5197 // function index in case of primitive maps.
5198 inline int inobject_properties_or_constructor_function_index();
5199 inline void set_inobject_properties_or_constructor_function_index(int value);
5200 // Count of properties allocated in the object (JSObject only).
5201 inline int GetInObjectProperties();
5202 inline void SetInObjectProperties(int value);
5203 // Index of the constructor function in the native context (primitives only),
5204 // or the special sentinel value to indicate that there is no object wrapper
5205 // for the primitive (i.e. in case of null or undefined).
5206 static const int kNoConstructorFunctionIndex = 0;
5207 inline int GetConstructorFunctionIndex();
5208 inline void SetConstructorFunctionIndex(int value);
5211 inline InstanceType instance_type();
5212 inline void set_instance_type(InstanceType value);
5214 // Tells how many unused property fields are available in the
5215 // instance (only used for JSObject in fast mode).
5216 inline int unused_property_fields();
5217 inline void set_unused_property_fields(int value);
5220 inline byte bit_field() const;
5221 inline void set_bit_field(byte value);
5224 inline byte bit_field2() const;
5225 inline void set_bit_field2(byte value);
5228 inline uint32_t bit_field3() const;
5229 inline void set_bit_field3(uint32_t bits);
5231 class EnumLengthBits: public BitField<int,
5232 0, kDescriptorIndexBitCount> {}; // NOLINT
5233 class NumberOfOwnDescriptorsBits: public BitField<int,
5234 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5235 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5236 class DictionaryMap : public BitField<bool, 20, 1> {};
5237 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5238 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5239 class Deprecated : public BitField<bool, 23, 1> {};
5240 class IsUnstable : public BitField<bool, 24, 1> {};
5241 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5242 class IsStrong : public BitField<bool, 26, 1> {};
5245 // Keep this bit field at the very end for better code in
5246 // Builtins::kJSConstructStubGeneric stub.
5247 // This counter is used for in-object slack tracking and for map aging.
5248 // The in-object slack tracking is considered enabled when the counter is
5249 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5250 class Counter : public BitField<int, 28, 4> {};
5251 static const int kSlackTrackingCounterStart = 14;
5252 static const int kSlackTrackingCounterEnd = 8;
5253 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5254 static const int kRetainingCounterEnd = 0;
5256 // Tells whether the object in the prototype property will be used
5257 // for instances created from this function. If the prototype
5258 // property is set to a value that is not a JSObject, the prototype
5259 // property will not be used to create instances of the function.
5260 // See ECMA-262, 13.2.2.
5261 inline void set_non_instance_prototype(bool value);
5262 inline bool has_non_instance_prototype();
5264 // Tells whether function has special prototype property. If not, prototype
5265 // property will not be created when accessed (will return undefined),
5266 // and construction from this function will not be allowed.
5267 inline void set_function_with_prototype(bool value);
5268 inline bool function_with_prototype();
5270 // Tells whether the instance with this map should be ignored by the
5271 // Object.getPrototypeOf() function and the __proto__ accessor.
5272 inline void set_is_hidden_prototype();
5273 inline bool is_hidden_prototype() const;
5275 // Records and queries whether the instance has a named interceptor.
5276 inline void set_has_named_interceptor();
5277 inline bool has_named_interceptor();
5279 // Records and queries whether the instance has an indexed interceptor.
5280 inline void set_has_indexed_interceptor();
5281 inline bool has_indexed_interceptor();
5283 // Tells whether the instance is undetectable.
5284 // An undetectable object is a special class of JSObject: 'typeof' operator
5285 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5286 // a normal JS object. It is useful for implementing undetectable
5287 // document.all in Firefox & Safari.
5288 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5289 inline void set_is_undetectable();
5290 inline bool is_undetectable();
5292 // Tells whether the instance has a call-as-function handler.
5293 inline void set_is_observed();
5294 inline bool is_observed();
5296 // Tells whether the instance has a [[Call]] internal field.
5297 // This property is implemented according to ES6, section 7.2.3.
5298 inline void set_is_callable();
5299 inline bool is_callable() const;
5301 inline void set_is_strong();
5302 inline bool is_strong();
5303 inline void set_is_extensible(bool value);
5304 inline bool is_extensible();
5305 inline void set_is_prototype_map(bool value);
5306 inline bool is_prototype_map() const;
5308 inline void set_elements_kind(ElementsKind elements_kind);
5309 inline ElementsKind elements_kind();
5311 // Tells whether the instance has fast elements that are only Smis.
5312 inline bool has_fast_smi_elements();
5314 // Tells whether the instance has fast elements.
5315 inline bool has_fast_object_elements();
5316 inline bool has_fast_smi_or_object_elements();
5317 inline bool has_fast_double_elements();
5318 inline bool has_fast_elements();
5319 inline bool has_sloppy_arguments_elements();
5320 inline bool has_fixed_typed_array_elements();
5321 inline bool has_dictionary_elements();
5323 static bool IsValidElementsTransition(ElementsKind from_kind,
5324 ElementsKind to_kind);
5326 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5327 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5328 bool DictionaryElementsInPrototypeChainOnly();
5330 inline Map* ElementsTransitionMap();
5332 inline FixedArrayBase* GetInitialElements();
5334 // [raw_transitions]: Provides access to the transitions storage field.
5335 // Don't call set_raw_transitions() directly to overwrite transitions, use
5336 // the TransitionArray::ReplaceTransitions() wrapper instead!
5337 DECL_ACCESSORS(raw_transitions, Object)
5338 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5339 // (which prototype maps don't have).
5340 DECL_ACCESSORS(prototype_info, Object)
5341 // PrototypeInfo is created lazily using this helper (which installs it on
5342 // the given prototype's map).
5343 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5344 Handle<JSObject> prototype, Isolate* isolate);
5345 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5346 Handle<Map> prototype_map, Isolate* isolate);
5348 // [prototype chain validity cell]: Associated with a prototype object,
5349 // stored in that object's map's PrototypeInfo, indicates that prototype
5350 // chains through this object are currently valid. The cell will be
5351 // invalidated and replaced when the prototype chain changes.
5352 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5354 static const int kPrototypeChainValid = 0;
5355 static const int kPrototypeChainInvalid = 1;
5358 Map* FindFieldOwner(int descriptor);
5360 inline int GetInObjectPropertyOffset(int index);
5362 int NumberOfFields();
5364 // TODO(ishell): candidate with JSObject::MigrateToMap().
5365 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5366 int target_inobject, int target_unused,
5367 int* old_number_of_fields);
5368 // TODO(ishell): moveit!
5369 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5370 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5371 Handle<HeapType> type1,
5372 Handle<HeapType> type2,
5374 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5375 Representation new_representation,
5376 Handle<HeapType> new_field_type);
5377 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5378 PropertyKind new_kind,
5379 PropertyAttributes new_attributes,
5380 Representation new_representation,
5381 Handle<HeapType> new_field_type,
5382 StoreMode store_mode);
5383 static Handle<Map> CopyGeneralizeAllRepresentations(
5384 Handle<Map> map, int modify_index, StoreMode store_mode,
5385 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5387 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5388 int descriptor_number,
5389 Handle<Object> value);
5391 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5392 const char* reason);
5394 // Returns the constructor name (the name (possibly, inferred name) of the
5395 // function that was used to instantiate the object).
5396 String* constructor_name();
5398 // Tells whether the map is used for JSObjects in dictionary mode (ie
5399 // normalized objects, ie objects for which HasFastProperties returns false).
5400 // A map can never be used for both dictionary mode and fast mode JSObjects.
5401 // False by default and for HeapObjects that are not JSObjects.
5402 inline void set_dictionary_map(bool value);
5403 inline bool is_dictionary_map();
5405 // Tells whether the instance needs security checks when accessing its
5407 inline void set_is_access_check_needed(bool access_check_needed);
5408 inline bool is_access_check_needed();
5410 // Returns true if map has a non-empty stub code cache.
5411 inline bool has_code_cache();
5413 // [prototype]: implicit prototype object.
5414 DECL_ACCESSORS(prototype, Object)
5415 // TODO(jkummerow): make set_prototype private.
5416 static void SetPrototype(
5417 Handle<Map> map, Handle<Object> prototype,
5418 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5420 // [constructor]: points back to the function responsible for this map.
5421 // The field overlaps with the back pointer. All maps in a transition tree
5422 // have the same constructor, so maps with back pointers can walk the
5423 // back pointer chain until they find the map holding their constructor.
5424 DECL_ACCESSORS(constructor_or_backpointer, Object)
5425 inline Object* GetConstructor() const;
5426 inline void SetConstructor(Object* constructor,
5427 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5428 // [back pointer]: points back to the parent map from which a transition
5429 // leads to this map. The field overlaps with the constructor (see above).
5430 inline Object* GetBackPointer();
5431 inline void SetBackPointer(Object* value,
5432 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5434 // [instance descriptors]: describes the object.
5435 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5437 // [layout descriptor]: describes the object layout.
5438 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5439 // |layout descriptor| accessor which can be used from GC.
5440 inline LayoutDescriptor* layout_descriptor_gc_safe();
5441 inline bool HasFastPointerLayout() const;
5443 // |layout descriptor| accessor that is safe to call even when
5444 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5445 // |layout_descriptor| field at all).
5446 inline LayoutDescriptor* GetLayoutDescriptor();
5448 inline void UpdateDescriptors(DescriptorArray* descriptors,
5449 LayoutDescriptor* layout_descriptor);
5450 inline void InitializeDescriptors(DescriptorArray* descriptors,
5451 LayoutDescriptor* layout_descriptor);
5453 // [stub cache]: contains stubs compiled for this map.
5454 DECL_ACCESSORS(code_cache, Object)
5456 // [dependent code]: list of optimized codes that weakly embed this map.
5457 DECL_ACCESSORS(dependent_code, DependentCode)
5459 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5460 DECL_ACCESSORS(weak_cell_cache, Object)
5462 inline PropertyDetails GetLastDescriptorDetails();
5464 inline int LastAdded();
5466 inline int NumberOfOwnDescriptors();
5467 inline void SetNumberOfOwnDescriptors(int number);
5469 inline Cell* RetrieveDescriptorsPointer();
5471 inline int EnumLength();
5472 inline void SetEnumLength(int length);
5474 inline bool owns_descriptors();
5475 inline void set_owns_descriptors(bool owns_descriptors);
5476 inline void mark_unstable();
5477 inline bool is_stable();
5478 inline void set_migration_target(bool value);
5479 inline bool is_migration_target();
5480 inline void set_counter(int value);
5481 inline int counter();
5482 inline void deprecate();
5483 inline bool is_deprecated();
5484 inline bool CanBeDeprecated();
5485 // Returns a non-deprecated version of the input. If the input was not
5486 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5487 // is found by re-transitioning from the root of the transition tree using the
5488 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5490 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5492 // Returns a non-deprecated version of the input. This method may deprecate
5493 // existing maps along the way if encodings conflict. Not for use while
5494 // gathering type feedback. Use TryUpdate in those cases instead.
5495 static Handle<Map> Update(Handle<Map> map);
5497 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5498 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5499 Descriptor* descriptor,
5500 TransitionFlag flag);
5502 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5505 Handle<HeapType> type,
5506 PropertyAttributes attributes,
5507 Representation representation,
5508 TransitionFlag flag);
5510 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5513 Handle<Object> constant,
5514 PropertyAttributes attributes,
5515 TransitionFlag flag);
5517 // Returns a new map with all transitions dropped from the given map and
5518 // the ElementsKind set.
5519 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5520 ElementsKind to_kind);
5522 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5524 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5526 TransitionFlag flag);
5528 static Handle<Map> CopyForObserved(Handle<Map> map);
5530 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5531 PropertyAttributes attrs_to_add,
5532 Handle<Symbol> transition_marker,
5533 const char* reason);
5535 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5538 // Maximal number of fast properties. Used to restrict the number of map
5539 // transitions to avoid an explosion in the number of maps for objects used as
5541 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5542 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5544 Handle<Object> value,
5545 PropertyAttributes attributes,
5546 StoreFromKeyed store_mode);
5547 static Handle<Map> TransitionToAccessorProperty(
5548 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5549 Handle<Object> accessor, PropertyAttributes attributes);
5550 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5553 PropertyAttributes attributes);
5555 inline void AppendDescriptor(Descriptor* desc);
5557 // Returns a copy of the map, prepared for inserting into the transition
5558 // tree (if the |map| owns descriptors then the new one will share
5559 // descriptors with |map|).
5560 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5562 // Returns a copy of the map, with all transitions dropped from the
5563 // instance descriptors.
5564 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5565 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5567 // Returns the next free property index (only valid for FAST MODE).
5568 int NextFreePropertyIndex();
5570 // Returns the number of properties described in instance_descriptors
5571 // filtering out properties with the specified attributes.
5572 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5573 PropertyAttributes filter = NONE);
5577 // Code cache operations.
5579 // Clears the code cache.
5580 inline void ClearCodeCache(Heap* heap);
5582 // Update code cache.
5583 static void UpdateCodeCache(Handle<Map> map,
5587 // Extend the descriptor array of the map with the list of descriptors.
5588 // In case of duplicates, the latest descriptor is used.
5589 static void AppendCallbackDescriptors(Handle<Map> map,
5590 Handle<Object> descriptors);
5592 static inline int SlackForArraySize(int old_size, int size_limit);
5594 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5596 // Returns the found code or undefined if absent.
5597 Object* FindInCodeCache(Name* name, Code::Flags flags);
5599 // Returns the non-negative index of the code object if it is in the
5600 // cache and -1 otherwise.
5601 int IndexInCodeCache(Object* name, Code* code);
5603 // Removes a code object from the code cache at the given index.
5604 void RemoveFromCodeCache(Name* name, Code* code, int index);
5606 // Computes a hash value for this map, to be used in HashTables and such.
5609 // Returns the map that this map transitions to if its elements_kind
5610 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5611 // |safe_to_add_transitions| is set to false if adding transitions is not
5613 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5615 // Returns the transitioned map for this map with the most generic
5616 // elements_kind that's found in |candidates|, or null handle if no match is
5618 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5619 MapHandleList* candidates);
5621 inline bool CanTransition();
5623 inline bool IsPrimitiveMap();
5624 inline bool IsJSObjectMap();
5625 inline bool IsJSArrayMap();
5626 inline bool IsStringMap();
5627 inline bool IsJSProxyMap();
5628 inline bool IsJSGlobalProxyMap();
5629 inline bool IsJSGlobalObjectMap();
5630 inline bool IsGlobalObjectMap();
5632 inline bool CanOmitMapChecks();
5634 static void AddDependentCode(Handle<Map> map,
5635 DependentCode::DependencyGroup group,
5638 bool IsMapInArrayPrototypeChain();
5640 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5642 // Dispatched behavior.
5643 DECLARE_PRINTER(Map)
5644 DECLARE_VERIFIER(Map)
5647 void DictionaryMapVerify();
5648 void VerifyOmittedMapChecks();
5651 inline int visitor_id();
5652 inline void set_visitor_id(int visitor_id);
5654 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5655 Handle<Object> prototype,
5656 PrototypeOptimizationMode mode);
5658 static const int kMaxPreAllocatedPropertyFields = 255;
5660 // Layout description.
5661 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5662 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5663 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5664 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5665 static const int kConstructorOrBackPointerOffset =
5666 kPrototypeOffset + kPointerSize;
5667 // When there is only one transition, it is stored directly in this field;
5668 // otherwise a transition array is used.
5669 // For prototype maps, this slot is used to store this map's PrototypeInfo
5671 static const int kTransitionsOrPrototypeInfoOffset =
5672 kConstructorOrBackPointerOffset + kPointerSize;
5673 static const int kDescriptorsOffset =
5674 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5675 #if V8_DOUBLE_FIELDS_UNBOXING
5676 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5677 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5679 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5680 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5682 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5683 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5684 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5686 // Layout of pointer fields. Heap iteration code relies on them
5687 // being continuously allocated.
5688 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5689 static const int kPointerFieldsEndOffset = kSize;
5691 // Byte offsets within kInstanceSizesOffset.
5692 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5693 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5694 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5695 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5696 // Note there is one byte available for use here.
5697 static const int kUnusedByte = 2;
5698 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5699 static const int kVisitorIdByte = 3;
5700 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5702 // Byte offsets within kInstanceAttributesOffset attributes.
5703 #if V8_TARGET_LITTLE_ENDIAN
5704 // Order instance type and bit field together such that they can be loaded
5705 // together as a 16-bit word with instance type in the lower 8 bits regardless
5706 // of endianess. Also provide endian-independent offset to that 16-bit word.
5707 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5708 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5710 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5711 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5713 static const int kInstanceTypeAndBitFieldOffset =
5714 kInstanceAttributesOffset + 0;
5715 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5716 static const int kUnusedPropertyFieldsByte = 3;
5717 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5719 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5720 Internals::kMapInstanceTypeAndBitFieldOffset);
5722 // Bit positions for bit field.
5723 static const int kHasNonInstancePrototype = 0;
5724 static const int kIsCallable = 1;
5725 static const int kHasNamedInterceptor = 2;
5726 static const int kHasIndexedInterceptor = 3;
5727 static const int kIsUndetectable = 4;
5728 static const int kIsObserved = 5;
5729 static const int kIsAccessCheckNeeded = 6;
5730 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5732 // Bit positions for bit field 2
5733 static const int kIsExtensible = 0;
5734 static const int kStringWrapperSafeForDefaultValueOf = 1;
5735 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5736 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5738 // Derived values from bit field 2
5739 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5740 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5741 static const int8_t kMaximumBitField2FastSmiElementValue =
5742 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5743 Map::ElementsKindBits::kShift) - 1;
5744 static const int8_t kMaximumBitField2FastHoleyElementValue =
5745 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5746 Map::ElementsKindBits::kShift) - 1;
5747 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5748 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5749 Map::ElementsKindBits::kShift) - 1;
5751 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5752 kPointerFieldsEndOffset,
5753 kSize> BodyDescriptor;
5755 // Compares this map to another to see if they describe equivalent objects.
5756 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5757 // it had exactly zero inobject properties.
5758 // The "shared" flags of both this map and |other| are ignored.
5759 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5761 // Returns true if given field is unboxed double.
5762 inline bool IsUnboxedDoubleField(FieldIndex index);
5765 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5766 static void TraceAllTransitions(Map* map);
5769 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5770 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5771 Handle<LayoutDescriptor> layout_descriptor);
5774 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5775 Handle<Name> name, SimpleTransitionFlag flag);
5777 bool EquivalentToForTransition(Map* other);
5778 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5779 static Handle<Map> ShareDescriptor(Handle<Map> map,
5780 Handle<DescriptorArray> descriptors,
5781 Descriptor* descriptor);
5782 static Handle<Map> CopyInstallDescriptors(
5783 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5784 Handle<LayoutDescriptor> layout_descriptor);
5785 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5786 Descriptor* descriptor,
5787 TransitionFlag flag);
5788 static Handle<Map> CopyReplaceDescriptors(
5789 Handle<Map> map, Handle<DescriptorArray> descriptors,
5790 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5791 MaybeHandle<Name> maybe_name, const char* reason,
5792 SimpleTransitionFlag simple_flag);
5794 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5795 Handle<DescriptorArray> descriptors,
5796 Descriptor* descriptor,
5798 TransitionFlag flag);
5799 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5800 Handle<Map> map, int descriptor, PropertyKind kind,
5801 PropertyAttributes attributes, const char** reason);
5803 static Handle<Map> CopyNormalized(Handle<Map> map,
5804 PropertyNormalizationMode mode);
5806 // Fires when the layout of an object with a leaf map changes.
5807 // This includes adding transitions to the leaf map or changing
5808 // the descriptor array.
5809 inline void NotifyLeafMapLayoutChange();
5811 void DeprecateTransitionTree();
5812 bool DeprecateTarget(PropertyKind kind, Name* key,
5813 PropertyAttributes attributes,
5814 DescriptorArray* new_descriptors,
5815 LayoutDescriptor* new_layout_descriptor);
5817 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5819 // Update field type of the given descriptor to new representation and new
5820 // type. The type must be prepared for storing in descriptor array:
5821 // it must be either a simple type or a map wrapped in a weak cell.
5822 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5823 Representation new_representation,
5824 Handle<Object> new_wrapped_type);
5826 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5827 PropertyAttributes attributes);
5828 void PrintGeneralization(FILE* file,
5833 bool constant_to_field,
5834 Representation old_representation,
5835 Representation new_representation,
5836 HeapType* old_field_type,
5837 HeapType* new_field_type);
5839 static const int kFastPropertiesSoftLimit = 12;
5840 static const int kMaxFastProperties = 128;
5842 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5846 // An abstract superclass, a marker class really, for simple structure classes.
5847 // It doesn't carry much functionality but allows struct classes to be
5848 // identified in the type system.
5849 class Struct: public HeapObject {
5851 inline void InitializeBody(int object_size);
5852 DECLARE_CAST(Struct)
5856 // A simple one-element struct, useful where smis need to be boxed.
5857 class Box : public Struct {
5859 // [value]: the boxed contents.
5860 DECL_ACCESSORS(value, Object)
5864 // Dispatched behavior.
5865 DECLARE_PRINTER(Box)
5866 DECLARE_VERIFIER(Box)
5868 static const int kValueOffset = HeapObject::kHeaderSize;
5869 static const int kSize = kValueOffset + kPointerSize;
5872 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5876 // Container for metadata stored on each prototype map.
5877 class PrototypeInfo : public Struct {
5879 static const int UNREGISTERED = -1;
5881 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5882 // or Smi(0) if uninitialized.
5883 DECL_ACCESSORS(prototype_users, Object)
5884 // [registry_slot]: Slot in prototype's user registry where this user
5885 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5886 inline int registry_slot() const;
5887 inline void set_registry_slot(int slot);
5888 // [validity_cell]: Cell containing the validity bit for prototype chains
5889 // going through this object, or Smi(0) if uninitialized.
5890 DECL_ACCESSORS(validity_cell, Object)
5891 // [constructor_name]: User-friendly name of the original constructor.
5892 DECL_ACCESSORS(constructor_name, Object)
5894 DECLARE_CAST(PrototypeInfo)
5896 // Dispatched behavior.
5897 DECLARE_PRINTER(PrototypeInfo)
5898 DECLARE_VERIFIER(PrototypeInfo)
5900 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5901 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5902 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5903 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5904 static const int kSize = kConstructorNameOffset + kPointerSize;
5907 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5911 // Pair used to store both a ScopeInfo and an extension object in the extension
5912 // slot of a block context. Needed in the rare case where a declaration block
5913 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5914 // a sloppy direct eval. (In no other case both are needed at the same time.)
5915 class SloppyBlockWithEvalContextExtension : public Struct {
5917 // [scope_info]: Scope info.
5918 DECL_ACCESSORS(scope_info, ScopeInfo)
5919 // [extension]: Extension object.
5920 DECL_ACCESSORS(extension, JSObject)
5922 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5924 // Dispatched behavior.
5925 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5926 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5928 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5929 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5930 static const int kSize = kExtensionOffset + kPointerSize;
5933 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5937 // Script describes a script which has been added to the VM.
5938 class Script: public Struct {
5947 // Script compilation types.
5948 enum CompilationType {
5949 COMPILATION_TYPE_HOST = 0,
5950 COMPILATION_TYPE_EVAL = 1
5953 // Script compilation state.
5954 enum CompilationState {
5955 COMPILATION_STATE_INITIAL = 0,
5956 COMPILATION_STATE_COMPILED = 1
5959 // [source]: the script source.
5960 DECL_ACCESSORS(source, Object)
5962 // [name]: the script name.
5963 DECL_ACCESSORS(name, Object)
5965 // [id]: the script id.
5966 DECL_ACCESSORS(id, Smi)
5968 // [line_offset]: script line offset in resource from where it was extracted.
5969 DECL_ACCESSORS(line_offset, Smi)
5971 // [column_offset]: script column offset in resource from where it was
5973 DECL_ACCESSORS(column_offset, Smi)
5975 // [context_data]: context data for the context this script was compiled in.
5976 DECL_ACCESSORS(context_data, Object)
5978 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5979 DECL_ACCESSORS(wrapper, HeapObject)
5981 // [type]: the script type.
5982 DECL_ACCESSORS(type, Smi)
5984 // [line_ends]: FixedArray of line ends positions.
5985 DECL_ACCESSORS(line_ends, Object)
5987 // [eval_from_shared]: for eval scripts the shared funcion info for the
5988 // function from which eval was called.
5989 DECL_ACCESSORS(eval_from_shared, Object)
5991 // [eval_from_instructions_offset]: the instruction offset in the code for the
5992 // function from which eval was called where eval was called.
5993 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5995 // [shared_function_infos]: weak fixed array containing all shared
5996 // function infos created from this script.
5997 DECL_ACCESSORS(shared_function_infos, Object)
5999 // [flags]: Holds an exciting bitfield.
6000 DECL_ACCESSORS(flags, Smi)
6002 // [source_url]: sourceURL from magic comment
6003 DECL_ACCESSORS(source_url, Object)
6005 // [source_url]: sourceMappingURL magic comment
6006 DECL_ACCESSORS(source_mapping_url, Object)
6008 // [compilation_type]: how the the script was compiled. Encoded in the
6010 inline CompilationType compilation_type();
6011 inline void set_compilation_type(CompilationType type);
6013 // [compilation_state]: determines whether the script has already been
6014 // compiled. Encoded in the 'flags' field.
6015 inline CompilationState compilation_state();
6016 inline void set_compilation_state(CompilationState state);
6018 // [hide_source]: determines whether the script source can be exposed as
6019 // function source. Encoded in the 'flags' field.
6020 inline bool hide_source();
6021 inline void set_hide_source(bool value);
6023 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6024 // and used by the embedder to make decisions about the script. V8 just passes
6025 // this through. Encoded in the 'flags' field.
6026 inline v8::ScriptOriginOptions origin_options();
6027 inline void set_origin_options(ScriptOriginOptions origin_options);
6029 DECLARE_CAST(Script)
6031 // If script source is an external string, check that the underlying
6032 // resource is accessible. Otherwise, always return true.
6033 inline bool HasValidSource();
6035 // Convert code position into column number.
6036 static int GetColumnNumber(Handle<Script> script, int code_pos);
6038 // Convert code position into (zero-based) line number.
6039 // The non-handlified version does not allocate, but may be much slower.
6040 static int GetLineNumber(Handle<Script> script, int code_pos);
6041 int GetLineNumber(int code_pos);
6043 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6045 // Init line_ends array with code positions of line ends inside script source.
6046 static void InitLineEnds(Handle<Script> script);
6048 // Get the JS object wrapping the given script; create it if none exists.
6049 static Handle<JSObject> GetWrapper(Handle<Script> script);
6051 // Look through the list of existing shared function infos to find one
6052 // that matches the function literal. Return empty handle if not found.
6053 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6055 // Iterate over all script objects on the heap.
6058 explicit Iterator(Isolate* isolate);
6062 WeakFixedArray::Iterator iterator_;
6063 DISALLOW_COPY_AND_ASSIGN(Iterator);
6066 // Dispatched behavior.
6067 DECLARE_PRINTER(Script)
6068 DECLARE_VERIFIER(Script)
6070 static const int kSourceOffset = HeapObject::kHeaderSize;
6071 static const int kNameOffset = kSourceOffset + kPointerSize;
6072 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6073 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6074 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6075 static const int kWrapperOffset = kContextOffset + kPointerSize;
6076 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6077 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6078 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6079 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6080 static const int kEvalFrominstructionsOffsetOffset =
6081 kEvalFromSharedOffset + kPointerSize;
6082 static const int kSharedFunctionInfosOffset =
6083 kEvalFrominstructionsOffsetOffset + kPointerSize;
6084 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6085 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6086 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6087 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6090 int GetLineNumberWithArray(int code_pos);
6092 // Bit positions in the flags field.
6093 static const int kCompilationTypeBit = 0;
6094 static const int kCompilationStateBit = 1;
6095 static const int kHideSourceBit = 2;
6096 static const int kOriginOptionsShift = 3;
6097 static const int kOriginOptionsSize = 3;
6098 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6099 << kOriginOptionsShift;
6101 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6105 // List of builtin functions we want to identify to improve code
6108 // Each entry has a name of a global object property holding an object
6109 // optionally followed by ".prototype", a name of a builtin function
6110 // on the object (the one the id is set for), and a label.
6112 // Installation of ids for the selected builtin functions is handled
6113 // by the bootstrapper.
6114 #define FUNCTIONS_WITH_ID_LIST(V) \
6115 V(Array.prototype, indexOf, ArrayIndexOf) \
6116 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6117 V(Array.prototype, push, ArrayPush) \
6118 V(Array.prototype, pop, ArrayPop) \
6119 V(Array.prototype, shift, ArrayShift) \
6120 V(Function.prototype, apply, FunctionApply) \
6121 V(Function.prototype, call, FunctionCall) \
6122 V(String.prototype, charCodeAt, StringCharCodeAt) \
6123 V(String.prototype, charAt, StringCharAt) \
6124 V(String, fromCharCode, StringFromCharCode) \
6125 V(Math, random, MathRandom) \
6126 V(Math, floor, MathFloor) \
6127 V(Math, round, MathRound) \
6128 V(Math, ceil, MathCeil) \
6129 V(Math, abs, MathAbs) \
6130 V(Math, log, MathLog) \
6131 V(Math, exp, MathExp) \
6132 V(Math, sqrt, MathSqrt) \
6133 V(Math, pow, MathPow) \
6134 V(Math, max, MathMax) \
6135 V(Math, min, MathMin) \
6136 V(Math, cos, MathCos) \
6137 V(Math, sin, MathSin) \
6138 V(Math, tan, MathTan) \
6139 V(Math, acos, MathAcos) \
6140 V(Math, asin, MathAsin) \
6141 V(Math, atan, MathAtan) \
6142 V(Math, atan2, MathAtan2) \
6143 V(Math, imul, MathImul) \
6144 V(Math, clz32, MathClz32) \
6145 V(Math, fround, MathFround)
6147 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6148 V(Atomics, load, AtomicsLoad) \
6149 V(Atomics, store, AtomicsStore)
6151 enum BuiltinFunctionId {
6153 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6155 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6156 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6157 #undef DECLARE_FUNCTION_ID
6158 // Fake id for a special case of Math.pow. Note, it continues the
6159 // list of math functions.
6164 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6165 // that both {code} and {literals} can be NULL to pass search result status.
6166 struct CodeAndLiterals {
6167 Code* code; // Cached optimized code.
6168 FixedArray* literals; // Cached literals array.
6172 // SharedFunctionInfo describes the JSFunction information that can be
6173 // shared by multiple instances of the function.
6174 class SharedFunctionInfo: public HeapObject {
6176 // [name]: Function name.
6177 DECL_ACCESSORS(name, Object)
6179 // [code]: Function code.
6180 DECL_ACCESSORS(code, Code)
6181 inline void ReplaceCode(Code* code);
6183 // [optimized_code_map]: Map from native context to optimized code
6184 // and a shared literals array or Smi(0) if none.
6185 DECL_ACCESSORS(optimized_code_map, Object)
6187 // Returns entry from optimized code map for specified context and OSR entry.
6188 // Note that {code == nullptr} indicates no matching entry has been found,
6189 // whereas {literals == nullptr} indicates the code is context-independent.
6190 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6191 BailoutId osr_ast_id);
6193 // Clear optimized code map.
6194 void ClearOptimizedCodeMap();
6196 // Removed a specific optimized code object from the optimized code map.
6197 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6199 // Trims the optimized code map after entries have been removed.
6200 void TrimOptimizedCodeMap(int shrink_by);
6202 // Add a new entry to the optimized code map for context-independent code.
6203 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6206 // Add a new entry to the optimized code map for context-dependent code.
6207 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6208 Handle<Context> native_context,
6210 Handle<FixedArray> literals,
6211 BailoutId osr_ast_id);
6213 // Set up the link between shared function info and the script. The shared
6214 // function info is added to the list on the script.
6215 static void SetScript(Handle<SharedFunctionInfo> shared,
6216 Handle<Object> script_object);
6218 // Layout description of the optimized code map.
6219 static const int kNextMapIndex = 0;
6220 static const int kSharedCodeIndex = 1;
6221 static const int kEntriesStart = 2;
6222 static const int kContextOffset = 0;
6223 static const int kCachedCodeOffset = 1;
6224 static const int kLiteralsOffset = 2;
6225 static const int kOsrAstIdOffset = 3;
6226 static const int kEntryLength = 4;
6227 static const int kInitialLength = kEntriesStart + kEntryLength;
6229 // [scope_info]: Scope info.
6230 DECL_ACCESSORS(scope_info, ScopeInfo)
6232 // [construct stub]: Code stub for constructing instances of this function.
6233 DECL_ACCESSORS(construct_stub, Code)
6235 // Returns if this function has been compiled to native code yet.
6236 inline bool is_compiled();
6238 // [length]: The function length - usually the number of declared parameters.
6239 // Use up to 2^30 parameters.
6240 inline int length() const;
6241 inline void set_length(int value);
6243 // [internal formal parameter count]: The declared number of parameters.
6244 // For subclass constructors, also includes new.target.
6245 // The size of function's frame is internal_formal_parameter_count + 1.
6246 inline int internal_formal_parameter_count() const;
6247 inline void set_internal_formal_parameter_count(int value);
6249 // Set the formal parameter count so the function code will be
6250 // called without using argument adaptor frames.
6251 inline void DontAdaptArguments();
6253 // [expected_nof_properties]: Expected number of properties for the function.
6254 inline int expected_nof_properties() const;
6255 inline void set_expected_nof_properties(int value);
6257 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6258 // (increasingly) from crankshafted code where sufficient feedback isn't
6260 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6262 // Unconditionally clear the type feedback vector (including vector ICs).
6263 void ClearTypeFeedbackInfo();
6265 // Clear the type feedback vector with a more subtle policy at GC time.
6266 void ClearTypeFeedbackInfoAtGCTime();
6269 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6270 // even if the GC moves this SharedFunctionInfo.
6271 inline int unique_id() const;
6272 inline void set_unique_id(int value);
6275 // [instance class name]: class name for instances.
6276 DECL_ACCESSORS(instance_class_name, Object)
6278 // [function data]: This field holds some additional data for function.
6279 // Currently it has one of:
6280 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6281 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6282 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6283 // In the long run we don't want all functions to have this field but
6284 // we can fix that when we have a better model for storing hidden data
6286 DECL_ACCESSORS(function_data, Object)
6288 inline bool IsApiFunction();
6289 inline FunctionTemplateInfo* get_api_func_data();
6290 inline bool HasBuiltinFunctionId();
6291 inline BuiltinFunctionId builtin_function_id();
6292 inline bool HasBytecodeArray();
6293 inline BytecodeArray* bytecode_array();
6295 // [script info]: Script from which the function originates.
6296 DECL_ACCESSORS(script, Object)
6298 // [num_literals]: Number of literals used by this function.
6299 inline int num_literals() const;
6300 inline void set_num_literals(int value);
6302 // [start_position_and_type]: Field used to store both the source code
6303 // position, whether or not the function is a function expression,
6304 // and whether or not the function is a toplevel function. The two
6305 // least significants bit indicates whether the function is an
6306 // expression and the rest contains the source code position.
6307 inline int start_position_and_type() const;
6308 inline void set_start_position_and_type(int value);
6310 // The function is subject to debugging if a debug info is attached.
6311 inline bool HasDebugInfo();
6312 inline DebugInfo* GetDebugInfo();
6314 // A function has debug code if the compiled code has debug break slots.
6315 inline bool HasDebugCode();
6317 // [debug info]: Debug information.
6318 DECL_ACCESSORS(debug_info, Object)
6320 // [inferred name]: Name inferred from variable or property
6321 // assignment of this function. Used to facilitate debugging and
6322 // profiling of JavaScript code written in OO style, where almost
6323 // all functions are anonymous but are assigned to object
6325 DECL_ACCESSORS(inferred_name, String)
6327 // The function's name if it is non-empty, otherwise the inferred name.
6328 String* DebugName();
6330 // Position of the 'function' token in the script source.
6331 inline int function_token_position() const;
6332 inline void set_function_token_position(int function_token_position);
6334 // Position of this function in the script source.
6335 inline int start_position() const;
6336 inline void set_start_position(int start_position);
6338 // End position of this function in the script source.
6339 inline int end_position() const;
6340 inline void set_end_position(int end_position);
6342 // Is this function a function expression in the source code.
6343 DECL_BOOLEAN_ACCESSORS(is_expression)
6345 // Is this function a top-level function (scripts, evals).
6346 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6348 // Bit field containing various information collected by the compiler to
6349 // drive optimization.
6350 inline int compiler_hints() const;
6351 inline void set_compiler_hints(int value);
6353 inline int ast_node_count() const;
6354 inline void set_ast_node_count(int count);
6356 inline int profiler_ticks() const;
6357 inline void set_profiler_ticks(int ticks);
6359 // Inline cache age is used to infer whether the function survived a context
6360 // disposal or not. In the former case we reset the opt_count.
6361 inline int ic_age();
6362 inline void set_ic_age(int age);
6364 // Indicates if this function can be lazy compiled.
6365 // This is used to determine if we can safely flush code from a function
6366 // when doing GC if we expect that the function will no longer be used.
6367 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6369 // Indicates if this function can be lazy compiled without a context.
6370 // This is used to determine if we can force compilation without reaching
6371 // the function through program execution but through other means (e.g. heap
6372 // iteration by the debugger).
6373 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6375 // Indicates whether optimizations have been disabled for this
6376 // shared function info. If a function is repeatedly optimized or if
6377 // we cannot optimize the function we disable optimization to avoid
6378 // spending time attempting to optimize it again.
6379 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6381 // Indicates the language mode.
6382 inline LanguageMode language_mode();
6383 inline void set_language_mode(LanguageMode language_mode);
6385 // False if the function definitely does not allocate an arguments object.
6386 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6388 // Indicates that this function uses a super property (or an eval that may
6389 // use a super property).
6390 // This is needed to set up the [[HomeObject]] on the function instance.
6391 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6393 // True if the function has any duplicated parameter names.
6394 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6396 // Indicates whether the function is a native function.
6397 // These needs special treatment in .call and .apply since
6398 // null passed as the receiver should not be translated to the
6400 DECL_BOOLEAN_ACCESSORS(native)
6402 // Indicate that this function should always be inlined in optimized code.
6403 DECL_BOOLEAN_ACCESSORS(force_inline)
6405 // Indicates that the function was created by the Function function.
6406 // Though it's anonymous, toString should treat it as if it had the name
6407 // "anonymous". We don't set the name itself so that the system does not
6408 // see a binding for it.
6409 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6411 // Indicates whether the function is a bound function created using
6412 // the bind function.
6413 DECL_BOOLEAN_ACCESSORS(bound)
6415 // Indicates that the function is anonymous (the name field can be set
6416 // through the API, which does not change this flag).
6417 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6419 // Is this a function or top-level/eval code.
6420 DECL_BOOLEAN_ACCESSORS(is_function)
6422 // Indicates that code for this function cannot be compiled with Crankshaft.
6423 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6425 // Indicates that code for this function cannot be flushed.
6426 DECL_BOOLEAN_ACCESSORS(dont_flush)
6428 // Indicates that this function is a generator.
6429 DECL_BOOLEAN_ACCESSORS(is_generator)
6431 // Indicates that this function is an arrow function.
6432 DECL_BOOLEAN_ACCESSORS(is_arrow)
6434 // Indicates that this function is a concise method.
6435 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6437 // Indicates that this function is an accessor (getter or setter).
6438 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6440 // Indicates that this function is a default constructor.
6441 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6443 // Indicates that this function is an asm function.
6444 DECL_BOOLEAN_ACCESSORS(asm_function)
6446 // Indicates that the the shared function info is deserialized from cache.
6447 DECL_BOOLEAN_ACCESSORS(deserialized)
6449 // Indicates that the the shared function info has never been compiled before.
6450 DECL_BOOLEAN_ACCESSORS(never_compiled)
6452 inline FunctionKind kind();
6453 inline void set_kind(FunctionKind kind);
6455 // Indicates whether or not the code in the shared function support
6457 inline bool has_deoptimization_support();
6459 // Enable deoptimization support through recompiled code.
6460 void EnableDeoptimizationSupport(Code* recompiled);
6462 // Disable (further) attempted optimization of all functions sharing this
6463 // shared function info.
6464 void DisableOptimization(BailoutReason reason);
6466 inline BailoutReason disable_optimization_reason();
6468 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6469 // code, returns whether it asserted (i.e., always true if assertions are
6471 bool VerifyBailoutId(BailoutId id);
6473 // [source code]: Source code for the function.
6474 bool HasSourceCode() const;
6475 Handle<Object> GetSourceCode();
6477 // Number of times the function was optimized.
6478 inline int opt_count();
6479 inline void set_opt_count(int opt_count);
6481 // Number of times the function was deoptimized.
6482 inline void set_deopt_count(int value);
6483 inline int deopt_count();
6484 inline void increment_deopt_count();
6486 // Number of time we tried to re-enable optimization after it
6487 // was disabled due to high number of deoptimizations.
6488 inline void set_opt_reenable_tries(int value);
6489 inline int opt_reenable_tries();
6491 inline void TryReenableOptimization();
6493 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6494 inline void set_counters(int value);
6495 inline int counters() const;
6497 // Stores opt_count and bailout_reason as bit-fields.
6498 inline void set_opt_count_and_bailout_reason(int value);
6499 inline int opt_count_and_bailout_reason() const;
6501 inline void set_disable_optimization_reason(BailoutReason reason);
6503 // Tells whether this function should be subject to debugging.
6504 inline bool IsSubjectToDebugging();
6506 // Whether this function is defined in native code or extensions.
6507 inline bool IsBuiltin();
6509 // Check whether or not this function is inlineable.
6510 bool IsInlineable();
6512 // Source size of this function.
6515 // Calculate the instance size.
6516 int CalculateInstanceSize();
6518 // Calculate the number of in-object properties.
6519 int CalculateInObjectProperties();
6521 inline bool has_simple_parameters();
6523 // Initialize a SharedFunctionInfo from a parsed function literal.
6524 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6525 FunctionLiteral* lit);
6527 // Dispatched behavior.
6528 DECLARE_PRINTER(SharedFunctionInfo)
6529 DECLARE_VERIFIER(SharedFunctionInfo)
6531 void ResetForNewContext(int new_ic_age);
6533 // Iterate over all shared function infos that are created from a script.
6534 // That excludes shared function infos created for API functions and C++
6538 explicit Iterator(Isolate* isolate);
6539 SharedFunctionInfo* Next();
6544 Script::Iterator script_iterator_;
6545 WeakFixedArray::Iterator sfi_iterator_;
6546 DisallowHeapAllocation no_gc_;
6547 DISALLOW_COPY_AND_ASSIGN(Iterator);
6550 DECLARE_CAST(SharedFunctionInfo)
6553 static const int kDontAdaptArgumentsSentinel = -1;
6555 // Layout description.
6557 static const int kNameOffset = HeapObject::kHeaderSize;
6558 static const int kCodeOffset = kNameOffset + kPointerSize;
6559 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6560 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6561 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6562 static const int kInstanceClassNameOffset =
6563 kConstructStubOffset + kPointerSize;
6564 static const int kFunctionDataOffset =
6565 kInstanceClassNameOffset + kPointerSize;
6566 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6567 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6568 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6569 static const int kFeedbackVectorOffset =
6570 kInferredNameOffset + kPointerSize;
6572 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6573 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6575 // Just to not break the postmortrem support with conditional offsets
6576 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6577 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6580 #if V8_HOST_ARCH_32_BIT
6582 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6583 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6584 static const int kExpectedNofPropertiesOffset =
6585 kFormalParameterCountOffset + kPointerSize;
6586 static const int kNumLiteralsOffset =
6587 kExpectedNofPropertiesOffset + kPointerSize;
6588 static const int kStartPositionAndTypeOffset =
6589 kNumLiteralsOffset + kPointerSize;
6590 static const int kEndPositionOffset =
6591 kStartPositionAndTypeOffset + kPointerSize;
6592 static const int kFunctionTokenPositionOffset =
6593 kEndPositionOffset + kPointerSize;
6594 static const int kCompilerHintsOffset =
6595 kFunctionTokenPositionOffset + kPointerSize;
6596 static const int kOptCountAndBailoutReasonOffset =
6597 kCompilerHintsOffset + kPointerSize;
6598 static const int kCountersOffset =
6599 kOptCountAndBailoutReasonOffset + kPointerSize;
6600 static const int kAstNodeCountOffset =
6601 kCountersOffset + kPointerSize;
6602 static const int kProfilerTicksOffset =
6603 kAstNodeCountOffset + kPointerSize;
6606 static const int kSize = kProfilerTicksOffset + kPointerSize;
6608 // The only reason to use smi fields instead of int fields
6609 // is to allow iteration without maps decoding during
6610 // garbage collections.
6611 // To avoid wasting space on 64-bit architectures we use
6612 // the following trick: we group integer fields into pairs
6613 // The least significant integer in each pair is shifted left by 1.
6614 // By doing this we guarantee that LSB of each kPointerSize aligned
6615 // word is not set and thus this word cannot be treated as pointer
6616 // to HeapObject during old space traversal.
6617 #if V8_TARGET_LITTLE_ENDIAN
6618 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6619 static const int kFormalParameterCountOffset =
6620 kLengthOffset + kIntSize;
6622 static const int kExpectedNofPropertiesOffset =
6623 kFormalParameterCountOffset + kIntSize;
6624 static const int kNumLiteralsOffset =
6625 kExpectedNofPropertiesOffset + kIntSize;
6627 static const int kEndPositionOffset =
6628 kNumLiteralsOffset + kIntSize;
6629 static const int kStartPositionAndTypeOffset =
6630 kEndPositionOffset + kIntSize;
6632 static const int kFunctionTokenPositionOffset =
6633 kStartPositionAndTypeOffset + kIntSize;
6634 static const int kCompilerHintsOffset =
6635 kFunctionTokenPositionOffset + kIntSize;
6637 static const int kOptCountAndBailoutReasonOffset =
6638 kCompilerHintsOffset + kIntSize;
6639 static const int kCountersOffset =
6640 kOptCountAndBailoutReasonOffset + kIntSize;
6642 static const int kAstNodeCountOffset =
6643 kCountersOffset + kIntSize;
6644 static const int kProfilerTicksOffset =
6645 kAstNodeCountOffset + kIntSize;
6648 static const int kSize = kProfilerTicksOffset + kIntSize;
6650 #elif V8_TARGET_BIG_ENDIAN
6651 static const int kFormalParameterCountOffset =
6652 kLastPointerFieldOffset + kPointerSize;
6653 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6655 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6656 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6658 static const int kStartPositionAndTypeOffset =
6659 kExpectedNofPropertiesOffset + kIntSize;
6660 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6662 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6663 static const int kFunctionTokenPositionOffset =
6664 kCompilerHintsOffset + kIntSize;
6666 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6667 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6669 static const int kProfilerTicksOffset =
6670 kOptCountAndBailoutReasonOffset + kIntSize;
6671 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6674 static const int kSize = kAstNodeCountOffset + kIntSize;
6677 #error Unknown byte ordering
6678 #endif // Big endian
6682 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6684 typedef FixedBodyDescriptor<kNameOffset,
6685 kLastPointerFieldOffset + kPointerSize,
6686 kSize> BodyDescriptor;
6688 // Bit positions in start_position_and_type.
6689 // The source code start position is in the 30 most significant bits of
6690 // the start_position_and_type field.
6691 static const int kIsExpressionBit = 0;
6692 static const int kIsTopLevelBit = 1;
6693 static const int kStartPositionShift = 2;
6694 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6696 // Bit positions in compiler_hints.
6697 enum CompilerHints {
6698 kAllowLazyCompilation,
6699 kAllowLazyCompilationWithoutContext,
6700 kOptimizationDisabled,
6701 kStrictModeFunction,
6702 kStrongModeFunction,
6705 kHasDuplicateParameters,
6710 kNameShouldPrintAsAnonymous,
6717 kIsAccessorFunction,
6718 kIsDefaultConstructor,
6719 kIsSubclassConstructor,
6725 kCompilerHintsCount // Pseudo entry
6727 // Add hints for other modes when they're added.
6728 STATIC_ASSERT(LANGUAGE_END == 3);
6730 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6732 class DeoptCountBits : public BitField<int, 0, 4> {};
6733 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6734 class ICAgeBits : public BitField<int, 22, 8> {};
6736 class OptCountBits : public BitField<int, 0, 22> {};
6737 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6740 #if V8_HOST_ARCH_32_BIT
6741 // On 32 bit platforms, compiler hints is a smi.
6742 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6743 static const int kCompilerHintsSize = kPointerSize;
6745 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6746 static const int kCompilerHintsSmiTagSize = 0;
6747 static const int kCompilerHintsSize = kIntSize;
6750 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6751 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6754 // Constants for optimizing codegen for strict mode function and
6756 // Allows to use byte-width instructions.
6757 static const int kStrictModeBitWithinByte =
6758 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6759 static const int kStrongModeBitWithinByte =
6760 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6762 static const int kNativeBitWithinByte =
6763 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6765 static const int kBoundBitWithinByte =
6766 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6768 #if defined(V8_TARGET_LITTLE_ENDIAN)
6769 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6770 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6771 static const int kStrongModeByteOffset =
6772 kCompilerHintsOffset +
6773 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6774 static const int kNativeByteOffset = kCompilerHintsOffset +
6775 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6776 static const int kBoundByteOffset =
6777 kCompilerHintsOffset +
6778 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6779 #elif defined(V8_TARGET_BIG_ENDIAN)
6780 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6781 (kCompilerHintsSize - 1) -
6782 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6783 static const int kStrongModeByteOffset =
6784 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6785 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6786 static const int kNativeByteOffset = kCompilerHintsOffset +
6787 (kCompilerHintsSize - 1) -
6788 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6789 static const int kBoundByteOffset =
6790 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6791 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6793 #error Unknown byte ordering
6797 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6801 // Printing support.
6802 struct SourceCodeOf {
6803 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6804 : value(v), max_length(max) {}
6805 const SharedFunctionInfo* value;
6810 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6813 class JSGeneratorObject: public JSObject {
6815 // [function]: The function corresponding to this generator object.
6816 DECL_ACCESSORS(function, JSFunction)
6818 // [context]: The context of the suspended computation.
6819 DECL_ACCESSORS(context, Context)
6821 // [receiver]: The receiver of the suspended computation.
6822 DECL_ACCESSORS(receiver, Object)
6824 // [continuation]: Offset into code of continuation.
6826 // A positive offset indicates a suspended generator. The special
6827 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6828 // cannot be resumed.
6829 inline int continuation() const;
6830 inline void set_continuation(int continuation);
6831 inline bool is_closed();
6832 inline bool is_executing();
6833 inline bool is_suspended();
6835 // [operand_stack]: Saved operand stack.
6836 DECL_ACCESSORS(operand_stack, FixedArray)
6838 DECLARE_CAST(JSGeneratorObject)
6840 // Dispatched behavior.
6841 DECLARE_PRINTER(JSGeneratorObject)
6842 DECLARE_VERIFIER(JSGeneratorObject)
6844 // Magic sentinel values for the continuation.
6845 static const int kGeneratorExecuting = -1;
6846 static const int kGeneratorClosed = 0;
6848 // Layout description.
6849 static const int kFunctionOffset = JSObject::kHeaderSize;
6850 static const int kContextOffset = kFunctionOffset + kPointerSize;
6851 static const int kReceiverOffset = kContextOffset + kPointerSize;
6852 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6853 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6854 static const int kSize = kOperandStackOffset + kPointerSize;
6856 // Resume mode, for use by runtime functions.
6857 enum ResumeMode { NEXT, THROW };
6860 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6864 // Representation for module instance objects.
6865 class JSModule: public JSObject {
6867 // [context]: the context holding the module's locals, or undefined if none.
6868 DECL_ACCESSORS(context, Object)
6870 // [scope_info]: Scope info.
6871 DECL_ACCESSORS(scope_info, ScopeInfo)
6873 DECLARE_CAST(JSModule)
6875 // Dispatched behavior.
6876 DECLARE_PRINTER(JSModule)
6877 DECLARE_VERIFIER(JSModule)
6879 // Layout description.
6880 static const int kContextOffset = JSObject::kHeaderSize;
6881 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6882 static const int kSize = kScopeInfoOffset + kPointerSize;
6885 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6889 // JSFunction describes JavaScript functions.
6890 class JSFunction: public JSObject {
6892 // [prototype_or_initial_map]:
6893 DECL_ACCESSORS(prototype_or_initial_map, Object)
6895 // [shared]: The information about the function that
6896 // can be shared by instances.
6897 DECL_ACCESSORS(shared, SharedFunctionInfo)
6899 // [context]: The context for this function.
6900 inline Context* context();
6901 inline void set_context(Object* context);
6902 inline JSObject* global_proxy();
6904 // [code]: The generated code object for this function. Executed
6905 // when the function is invoked, e.g. foo() or new foo(). See
6906 // [[Call]] and [[Construct]] description in ECMA-262, section
6908 inline Code* code();
6909 inline void set_code(Code* code);
6910 inline void set_code_no_write_barrier(Code* code);
6911 inline void ReplaceCode(Code* code);
6913 // Tells whether this function is builtin.
6914 inline bool IsBuiltin();
6916 // Tells whether this function inlines the given shared function info.
6917 bool Inlines(SharedFunctionInfo* candidate);
6919 // Tells whether this function should be subject to debugging.
6920 inline bool IsSubjectToDebugging();
6922 // Tells whether or not the function needs arguments adaption.
6923 inline bool NeedsArgumentsAdaption();
6925 // Tells whether or not this function has been optimized.
6926 inline bool IsOptimized();
6928 // Mark this function for lazy recompilation. The function will be
6929 // recompiled the next time it is executed.
6930 void MarkForOptimization();
6931 void AttemptConcurrentOptimization();
6933 // Tells whether or not the function is already marked for lazy
6935 inline bool IsMarkedForOptimization();
6936 inline bool IsMarkedForConcurrentOptimization();
6938 // Tells whether or not the function is on the concurrent recompilation queue.
6939 inline bool IsInOptimizationQueue();
6941 // Inobject slack tracking is the way to reclaim unused inobject space.
6943 // The instance size is initially determined by adding some slack to
6944 // expected_nof_properties (to allow for a few extra properties added
6945 // after the constructor). There is no guarantee that the extra space
6946 // will not be wasted.
6948 // Here is the algorithm to reclaim the unused inobject space:
6949 // - Detect the first constructor call for this JSFunction.
6950 // When it happens enter the "in progress" state: initialize construction
6951 // counter in the initial_map.
6952 // - While the tracking is in progress create objects filled with
6953 // one_pointer_filler_map instead of undefined_value. This way they can be
6954 // resized quickly and safely.
6955 // - Once enough objects have been created compute the 'slack'
6956 // (traverse the map transition tree starting from the
6957 // initial_map and find the lowest value of unused_property_fields).
6958 // - Traverse the transition tree again and decrease the instance size
6959 // of every map. Existing objects will resize automatically (they are
6960 // filled with one_pointer_filler_map). All further allocations will
6961 // use the adjusted instance size.
6962 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6963 // allocations made using different closures could actually create different
6964 // kind of objects (see prototype inheritance pattern).
6966 // Important: inobject slack tracking is not attempted during the snapshot
6969 // True if the initial_map is set and the object constructions countdown
6970 // counter is not zero.
6971 static const int kGenerousAllocationCount =
6972 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6973 inline bool IsInobjectSlackTrackingInProgress();
6975 // Starts the tracking.
6976 // Initializes object constructions countdown counter in the initial map.
6977 void StartInobjectSlackTracking();
6979 // Completes the tracking.
6980 void CompleteInobjectSlackTracking();
6982 // [literals_or_bindings]: Fixed array holding either
6983 // the materialized literals or the bindings of a bound function.
6985 // If the function contains object, regexp or array literals, the
6986 // literals array prefix contains the object, regexp, and array
6987 // function to be used when creating these literals. This is
6988 // necessary so that we do not dynamically lookup the object, regexp
6989 // or array functions. Performing a dynamic lookup, we might end up
6990 // using the functions from a new context that we should not have
6993 // On bound functions, the array is a (copy-on-write) fixed-array containing
6994 // the function that was bound, bound this-value and any bound
6995 // arguments. Bound functions never contain literals.
6996 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6998 inline FixedArray* literals();
6999 inline void set_literals(FixedArray* literals);
7001 inline FixedArray* function_bindings();
7002 inline void set_function_bindings(FixedArray* bindings);
7004 // The initial map for an object created by this constructor.
7005 inline Map* initial_map();
7006 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7007 Handle<Object> prototype);
7008 inline bool has_initial_map();
7009 static void EnsureHasInitialMap(Handle<JSFunction> function);
7011 // Get and set the prototype property on a JSFunction. If the
7012 // function has an initial map the prototype is set on the initial
7013 // map. Otherwise, the prototype is put in the initial map field
7014 // until an initial map is needed.
7015 inline bool has_prototype();
7016 inline bool has_instance_prototype();
7017 inline Object* prototype();
7018 inline Object* instance_prototype();
7019 static void SetPrototype(Handle<JSFunction> function,
7020 Handle<Object> value);
7021 static void SetInstancePrototype(Handle<JSFunction> function,
7022 Handle<Object> value);
7024 // Creates a new closure for the fucntion with the same bindings,
7025 // bound values, and prototype. An equivalent of spec operations
7026 // ``CloneMethod`` and ``CloneBoundFunction``.
7027 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7029 // After prototype is removed, it will not be created when accessed, and
7030 // [[Construct]] from this function will not be allowed.
7031 bool RemovePrototype();
7032 inline bool should_have_prototype();
7034 // Accessor for this function's initial map's [[class]]
7035 // property. This is primarily used by ECMA native functions. This
7036 // method sets the class_name field of this function's initial map
7037 // to a given value. It creates an initial map if this function does
7038 // not have one. Note that this method does not copy the initial map
7039 // if it has one already, but simply replaces it with the new value.
7040 // Instances created afterwards will have a map whose [[class]] is
7041 // set to 'value', but there is no guarantees on instances created
7043 void SetInstanceClassName(String* name);
7045 // Returns if this function has been compiled to native code yet.
7046 inline bool is_compiled();
7048 // Returns `false` if formal parameters include rest parameters, optional
7049 // parameters, or destructuring parameters.
7050 // TODO(caitp): make this a flag set during parsing
7051 inline bool has_simple_parameters();
7053 // [next_function_link]: Links functions into various lists, e.g. the list
7054 // of optimized functions hanging off the native_context. The CodeFlusher
7055 // uses this link to chain together flushing candidates. Treated weakly
7056 // by the garbage collector.
7057 DECL_ACCESSORS(next_function_link, Object)
7059 // Prints the name of the function using PrintF.
7060 void PrintName(FILE* out = stdout);
7062 DECLARE_CAST(JSFunction)
7064 // Iterates the objects, including code objects indirectly referenced
7065 // through pointers to the first instruction in the code object.
7066 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7068 // Dispatched behavior.
7069 DECLARE_PRINTER(JSFunction)
7070 DECLARE_VERIFIER(JSFunction)
7072 // Returns the number of allocated literals.
7073 inline int NumberOfLiterals();
7075 // Used for flags such as --hydrogen-filter.
7076 bool PassesFilter(const char* raw_filter);
7078 // The function's name if it is configured, otherwise shared function info
7080 static Handle<String> GetDebugName(Handle<JSFunction> function);
7082 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7083 // kSize) is weak and has special handling during garbage collection.
7084 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7085 static const int kPrototypeOrInitialMapOffset =
7086 kCodeEntryOffset + kPointerSize;
7087 static const int kSharedFunctionInfoOffset =
7088 kPrototypeOrInitialMapOffset + kPointerSize;
7089 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7090 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7091 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7092 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7093 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7095 // Layout of the bound-function binding array.
7096 static const int kBoundFunctionIndex = 0;
7097 static const int kBoundThisIndex = 1;
7098 static const int kBoundArgumentsStartIndex = 2;
7101 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7105 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7106 // and the prototype is hidden. JSGlobalProxy always delegates
7107 // property accesses to its prototype if the prototype is not null.
7109 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7111 // Accessing a JSGlobalProxy requires security check.
7113 class JSGlobalProxy : public JSObject {
7115 // [native_context]: the owner native context of this global proxy object.
7116 // It is null value if this object is not used by any context.
7117 DECL_ACCESSORS(native_context, Object)
7119 // [hash]: The hash code property (undefined if not initialized yet).
7120 DECL_ACCESSORS(hash, Object)
7122 DECLARE_CAST(JSGlobalProxy)
7124 inline bool IsDetachedFrom(GlobalObject* global) const;
7126 // Dispatched behavior.
7127 DECLARE_PRINTER(JSGlobalProxy)
7128 DECLARE_VERIFIER(JSGlobalProxy)
7130 // Layout description.
7131 static const int kNativeContextOffset = JSObject::kHeaderSize;
7132 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7133 static const int kSize = kHashOffset + kPointerSize;
7136 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7140 // Common super class for JavaScript global objects and the special
7141 // builtins global objects.
7142 class GlobalObject: public JSObject {
7144 // [builtins]: the object holding the runtime routines written in JS.
7145 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7147 // [native context]: the natives corresponding to this global object.
7148 DECL_ACCESSORS(native_context, Context)
7150 // [global proxy]: the global proxy object of the context
7151 DECL_ACCESSORS(global_proxy, JSObject)
7153 DECLARE_CAST(GlobalObject)
7155 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7157 // Ensure that the global object has a cell for the given property name.
7158 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7161 // Layout description.
7162 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7163 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7164 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7165 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7168 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7172 // JavaScript global object.
7173 class JSGlobalObject: public GlobalObject {
7175 DECLARE_CAST(JSGlobalObject)
7177 inline bool IsDetached();
7179 // Dispatched behavior.
7180 DECLARE_PRINTER(JSGlobalObject)
7181 DECLARE_VERIFIER(JSGlobalObject)
7183 // Layout description.
7184 static const int kSize = GlobalObject::kHeaderSize;
7187 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7191 // Builtins global object which holds the runtime routines written in
7193 class JSBuiltinsObject: public GlobalObject {
7195 DECLARE_CAST(JSBuiltinsObject)
7197 // Dispatched behavior.
7198 DECLARE_PRINTER(JSBuiltinsObject)
7199 DECLARE_VERIFIER(JSBuiltinsObject)
7201 // Layout description.
7202 static const int kSize = GlobalObject::kHeaderSize;
7205 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7209 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7210 class JSValue: public JSObject {
7212 // [value]: the object being wrapped.
7213 DECL_ACCESSORS(value, Object)
7215 DECLARE_CAST(JSValue)
7217 // Dispatched behavior.
7218 DECLARE_PRINTER(JSValue)
7219 DECLARE_VERIFIER(JSValue)
7221 // Layout description.
7222 static const int kValueOffset = JSObject::kHeaderSize;
7223 static const int kSize = kValueOffset + kPointerSize;
7226 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7232 // Representation for JS date objects.
7233 class JSDate: public JSObject {
7235 // If one component is NaN, all of them are, indicating a NaN time value.
7236 // [value]: the time value.
7237 DECL_ACCESSORS(value, Object)
7238 // [year]: caches year. Either undefined, smi, or NaN.
7239 DECL_ACCESSORS(year, Object)
7240 // [month]: caches month. Either undefined, smi, or NaN.
7241 DECL_ACCESSORS(month, Object)
7242 // [day]: caches day. Either undefined, smi, or NaN.
7243 DECL_ACCESSORS(day, Object)
7244 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7245 DECL_ACCESSORS(weekday, Object)
7246 // [hour]: caches hours. Either undefined, smi, or NaN.
7247 DECL_ACCESSORS(hour, Object)
7248 // [min]: caches minutes. Either undefined, smi, or NaN.
7249 DECL_ACCESSORS(min, Object)
7250 // [sec]: caches seconds. Either undefined, smi, or NaN.
7251 DECL_ACCESSORS(sec, Object)
7252 // [cache stamp]: sample of the date cache stamp at the
7253 // moment when chached fields were cached.
7254 DECL_ACCESSORS(cache_stamp, Object)
7256 DECLARE_CAST(JSDate)
7258 // Returns the date field with the specified index.
7259 // See FieldIndex for the list of date fields.
7260 static Object* GetField(Object* date, Smi* index);
7262 void SetValue(Object* value, bool is_value_nan);
7264 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7265 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7266 Handle<JSReceiver> receiver, Handle<Object> hint);
7268 // Dispatched behavior.
7269 DECLARE_PRINTER(JSDate)
7270 DECLARE_VERIFIER(JSDate)
7272 // The order is important. It must be kept in sync with date macros
7283 kFirstUncachedField,
7284 kMillisecond = kFirstUncachedField,
7288 kYearUTC = kFirstUTCField,
7301 // Layout description.
7302 static const int kValueOffset = JSObject::kHeaderSize;
7303 static const int kYearOffset = kValueOffset + kPointerSize;
7304 static const int kMonthOffset = kYearOffset + kPointerSize;
7305 static const int kDayOffset = kMonthOffset + kPointerSize;
7306 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7307 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7308 static const int kMinOffset = kHourOffset + kPointerSize;
7309 static const int kSecOffset = kMinOffset + kPointerSize;
7310 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7311 static const int kSize = kCacheStampOffset + kPointerSize;
7314 inline Object* DoGetField(FieldIndex index);
7316 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7318 // Computes and caches the cacheable fields of the date.
7319 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7322 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7326 // Representation of message objects used for error reporting through
7327 // the API. The messages are formatted in JavaScript so this object is
7328 // a real JavaScript object. The information used for formatting the
7329 // error messages are not directly accessible from JavaScript to
7330 // prevent leaking information to user code called during error
7332 class JSMessageObject: public JSObject {
7334 // [type]: the type of error message.
7335 inline int type() const;
7336 inline void set_type(int value);
7338 // [arguments]: the arguments for formatting the error message.
7339 DECL_ACCESSORS(argument, Object)
7341 // [script]: the script from which the error message originated.
7342 DECL_ACCESSORS(script, Object)
7344 // [stack_frames]: an array of stack frames for this error object.
7345 DECL_ACCESSORS(stack_frames, Object)
7347 // [start_position]: the start position in the script for the error message.
7348 inline int start_position() const;
7349 inline void set_start_position(int value);
7351 // [end_position]: the end position in the script for the error message.
7352 inline int end_position() const;
7353 inline void set_end_position(int value);
7355 DECLARE_CAST(JSMessageObject)
7357 // Dispatched behavior.
7358 DECLARE_PRINTER(JSMessageObject)
7359 DECLARE_VERIFIER(JSMessageObject)
7361 // Layout description.
7362 static const int kTypeOffset = JSObject::kHeaderSize;
7363 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7364 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7365 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7366 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7367 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7368 static const int kSize = kEndPositionOffset + kPointerSize;
7370 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7371 kStackFramesOffset + kPointerSize,
7372 kSize> BodyDescriptor;
7376 // Regular expressions
7377 // The regular expression holds a single reference to a FixedArray in
7378 // the kDataOffset field.
7379 // The FixedArray contains the following data:
7380 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7381 // - reference to the original source string
7382 // - reference to the original flag string
7383 // If it is an atom regexp
7384 // - a reference to a literal string to search for
7385 // If it is an irregexp regexp:
7386 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7387 // used for tracking the last usage (used for code flushing).
7388 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7389 // used for tracking the last usage (used for code flushing)..
7390 // - max number of registers used by irregexp implementations.
7391 // - number of capture registers (output values) of the regexp.
7392 class JSRegExp: public JSObject {
7395 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7396 // ATOM: A simple string to match against using an indexOf operation.
7397 // IRREGEXP: Compiled with Irregexp.
7398 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7399 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7406 UNICODE_ESCAPES = 16
7411 explicit Flags(uint32_t value) : value_(value) { }
7412 bool is_global() { return (value_ & GLOBAL) != 0; }
7413 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7414 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7415 bool is_sticky() { return (value_ & STICKY) != 0; }
7416 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7417 uint32_t value() { return value_; }
7422 DECL_ACCESSORS(data, Object)
7424 inline Type TypeTag();
7425 inline int CaptureCount();
7426 inline Flags GetFlags();
7427 inline String* Pattern();
7428 inline Object* DataAt(int index);
7429 // Set implementation data after the object has been prepared.
7430 inline void SetDataAt(int index, Object* value);
7432 static int code_index(bool is_latin1) {
7434 return kIrregexpLatin1CodeIndex;
7436 return kIrregexpUC16CodeIndex;
7440 static int saved_code_index(bool is_latin1) {
7442 return kIrregexpLatin1CodeSavedIndex;
7444 return kIrregexpUC16CodeSavedIndex;
7448 DECLARE_CAST(JSRegExp)
7450 // Dispatched behavior.
7451 DECLARE_VERIFIER(JSRegExp)
7453 static const int kDataOffset = JSObject::kHeaderSize;
7454 static const int kSize = kDataOffset + kPointerSize;
7456 // Indices in the data array.
7457 static const int kTagIndex = 0;
7458 static const int kSourceIndex = kTagIndex + 1;
7459 static const int kFlagsIndex = kSourceIndex + 1;
7460 static const int kDataIndex = kFlagsIndex + 1;
7461 // The data fields are used in different ways depending on the
7462 // value of the tag.
7463 // Atom regexps (literal strings).
7464 static const int kAtomPatternIndex = kDataIndex;
7466 static const int kAtomDataSize = kAtomPatternIndex + 1;
7468 // Irregexp compiled code or bytecode for Latin1. If compilation
7469 // fails, this fields hold an exception object that should be
7470 // thrown if the regexp is used again.
7471 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7472 // Irregexp compiled code or bytecode for UC16. If compilation
7473 // fails, this fields hold an exception object that should be
7474 // thrown if the regexp is used again.
7475 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7477 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7478 // is a potential candidate for flushing.
7479 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7480 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7481 // a potential candidate for flushing.
7482 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7484 // Maximal number of registers used by either Latin1 or UC16.
7485 // Only used to check that there is enough stack space
7486 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7487 // Number of captures in the compiled regexp.
7488 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7490 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7492 // Offsets directly into the data fixed array.
7493 static const int kDataTagOffset =
7494 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7495 static const int kDataOneByteCodeOffset =
7496 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7497 static const int kDataUC16CodeOffset =
7498 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7499 static const int kIrregexpCaptureCountOffset =
7500 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7502 // In-object fields.
7503 static const int kSourceFieldIndex = 0;
7504 static const int kGlobalFieldIndex = 1;
7505 static const int kIgnoreCaseFieldIndex = 2;
7506 static const int kMultilineFieldIndex = 3;
7507 static const int kLastIndexFieldIndex = 4;
7508 static const int kInObjectFieldCount = 5;
7510 // The uninitialized value for a regexp code object.
7511 static const int kUninitializedValue = -1;
7513 // The compilation error value for the regexp code object. The real error
7514 // object is in the saved code field.
7515 static const int kCompilationErrorValue = -2;
7517 // When we store the sweep generation at which we moved the code from the
7518 // code index to the saved code index we mask it of to be in the [0:255]
7520 static const int kCodeAgeMask = 0xff;
7524 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7526 static inline bool IsMatch(HashTableKey* key, Object* value) {
7527 return key->IsMatch(value);
7530 static inline uint32_t Hash(HashTableKey* key) {
7534 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7535 return key->HashForObject(object);
7538 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7540 static const int kPrefixSize = 0;
7541 static const int kEntrySize = 2;
7545 // This cache is used in two different variants. For regexp caching, it simply
7546 // maps identifying info of the regexp to the cached regexp object. Scripts and
7547 // eval code only gets cached after a second probe for the code object. To do
7548 // so, on first "put" only a hash identifying the source is entered into the
7549 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7550 // such lifetimes get reduced, and removed once they reach zero. If a second put
7551 // is called while such a hash is live in the cache, the hash gets replaced by
7552 // an actual cache entry. Age also removes stale live entries from the cache.
7553 // Such entries are identified by SharedFunctionInfos pointing to either the
7554 // recompilation stub, or to "old" code. This avoids memory leaks due to
7555 // premature caching of scripts and eval strings that are never needed later.
7556 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7557 CompilationCacheShape,
7560 // Find cached value for a string key, otherwise return null.
7561 Handle<Object> Lookup(
7562 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7563 Handle<Object> LookupEval(
7564 Handle<String> src, Handle<SharedFunctionInfo> shared,
7565 LanguageMode language_mode, int scope_position);
7566 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7567 static Handle<CompilationCacheTable> Put(
7568 Handle<CompilationCacheTable> cache, Handle<String> src,
7569 Handle<Context> context, LanguageMode language_mode,
7570 Handle<Object> value);
7571 static Handle<CompilationCacheTable> PutEval(
7572 Handle<CompilationCacheTable> cache, Handle<String> src,
7573 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7574 int scope_position);
7575 static Handle<CompilationCacheTable> PutRegExp(
7576 Handle<CompilationCacheTable> cache, Handle<String> src,
7577 JSRegExp::Flags flags, Handle<FixedArray> value);
7578 void Remove(Object* value);
7580 static const int kHashGenerations = 10;
7582 DECLARE_CAST(CompilationCacheTable)
7585 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7589 class CodeCache: public Struct {
7591 DECL_ACCESSORS(default_cache, FixedArray)
7592 DECL_ACCESSORS(normal_type_cache, Object)
7594 // Add the code object to the cache.
7596 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7598 // Lookup code object in the cache. Returns code object if found and undefined
7600 Object* Lookup(Name* name, Code::Flags flags);
7602 // Get the internal index of a code object in the cache. Returns -1 if the
7603 // code object is not in that cache. This index can be used to later call
7604 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7606 int GetIndex(Object* name, Code* code);
7608 // Remove an object from the cache with the provided internal index.
7609 void RemoveByIndex(Object* name, Code* code, int index);
7611 DECLARE_CAST(CodeCache)
7613 // Dispatched behavior.
7614 DECLARE_PRINTER(CodeCache)
7615 DECLARE_VERIFIER(CodeCache)
7617 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7618 static const int kNormalTypeCacheOffset =
7619 kDefaultCacheOffset + kPointerSize;
7620 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7623 static void UpdateDefaultCache(
7624 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7625 static void UpdateNormalTypeCache(
7626 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7627 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7628 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7630 // Code cache layout of the default cache. Elements are alternating name and
7631 // code objects for non normal load/store/call IC's.
7632 static const int kCodeCacheEntrySize = 2;
7633 static const int kCodeCacheEntryNameOffset = 0;
7634 static const int kCodeCacheEntryCodeOffset = 1;
7636 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7640 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7642 static inline bool IsMatch(HashTableKey* key, Object* value) {
7643 return key->IsMatch(value);
7646 static inline uint32_t Hash(HashTableKey* key) {
7650 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7651 return key->HashForObject(object);
7654 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7656 static const int kPrefixSize = 0;
7657 static const int kEntrySize = 2;
7661 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7662 CodeCacheHashTableShape,
7665 Object* Lookup(Name* name, Code::Flags flags);
7666 static Handle<CodeCacheHashTable> Put(
7667 Handle<CodeCacheHashTable> table,
7671 int GetIndex(Name* name, Code::Flags flags);
7672 void RemoveByIndex(int index);
7674 DECLARE_CAST(CodeCacheHashTable)
7676 // Initial size of the fixed array backing the hash table.
7677 static const int kInitialSize = 64;
7680 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7684 class PolymorphicCodeCache: public Struct {
7686 DECL_ACCESSORS(cache, Object)
7688 static void Update(Handle<PolymorphicCodeCache> cache,
7689 MapHandleList* maps,
7694 // Returns an undefined value if the entry is not found.
7695 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7697 DECLARE_CAST(PolymorphicCodeCache)
7699 // Dispatched behavior.
7700 DECLARE_PRINTER(PolymorphicCodeCache)
7701 DECLARE_VERIFIER(PolymorphicCodeCache)
7703 static const int kCacheOffset = HeapObject::kHeaderSize;
7704 static const int kSize = kCacheOffset + kPointerSize;
7707 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7711 class PolymorphicCodeCacheHashTable
7712 : public HashTable<PolymorphicCodeCacheHashTable,
7713 CodeCacheHashTableShape,
7716 Object* Lookup(MapHandleList* maps, int code_kind);
7718 static Handle<PolymorphicCodeCacheHashTable> Put(
7719 Handle<PolymorphicCodeCacheHashTable> hash_table,
7720 MapHandleList* maps,
7724 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7726 static const int kInitialSize = 64;
7728 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7732 class TypeFeedbackInfo: public Struct {
7734 inline int ic_total_count();
7735 inline void set_ic_total_count(int count);
7737 inline int ic_with_type_info_count();
7738 inline void change_ic_with_type_info_count(int delta);
7740 inline int ic_generic_count();
7741 inline void change_ic_generic_count(int delta);
7743 inline void initialize_storage();
7745 inline void change_own_type_change_checksum();
7746 inline int own_type_change_checksum();
7748 inline void set_inlined_type_change_checksum(int checksum);
7749 inline bool matches_inlined_type_change_checksum(int checksum);
7751 DECLARE_CAST(TypeFeedbackInfo)
7753 // Dispatched behavior.
7754 DECLARE_PRINTER(TypeFeedbackInfo)
7755 DECLARE_VERIFIER(TypeFeedbackInfo)
7757 static const int kStorage1Offset = HeapObject::kHeaderSize;
7758 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7759 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7760 static const int kSize = kStorage3Offset + kPointerSize;
7763 static const int kTypeChangeChecksumBits = 7;
7765 class ICTotalCountField: public BitField<int, 0,
7766 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7767 class OwnTypeChangeChecksum: public BitField<int,
7768 kSmiValueSize - kTypeChangeChecksumBits,
7769 kTypeChangeChecksumBits> {}; // NOLINT
7770 class ICsWithTypeInfoCountField: public BitField<int, 0,
7771 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7772 class InlinedTypeChangeChecksum: public BitField<int,
7773 kSmiValueSize - kTypeChangeChecksumBits,
7774 kTypeChangeChecksumBits> {}; // NOLINT
7776 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7780 enum AllocationSiteMode {
7781 DONT_TRACK_ALLOCATION_SITE,
7782 TRACK_ALLOCATION_SITE,
7783 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7787 class AllocationSite: public Struct {
7789 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7790 static const double kPretenureRatio;
7791 static const int kPretenureMinimumCreated = 100;
7793 // Values for pretenure decision field.
7794 enum PretenureDecision {
7800 kLastPretenureDecisionValue = kZombie
7803 const char* PretenureDecisionName(PretenureDecision decision);
7805 DECL_ACCESSORS(transition_info, Object)
7806 // nested_site threads a list of sites that represent nested literals
7807 // walked in a particular order. So [[1, 2], 1, 2] will have one
7808 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7809 DECL_ACCESSORS(nested_site, Object)
7810 DECL_ACCESSORS(pretenure_data, Smi)
7811 DECL_ACCESSORS(pretenure_create_count, Smi)
7812 DECL_ACCESSORS(dependent_code, DependentCode)
7813 DECL_ACCESSORS(weak_next, Object)
7815 inline void Initialize();
7817 // This method is expensive, it should only be called for reporting.
7818 bool IsNestedSite();
7820 // transition_info bitfields, for constructed array transition info.
7821 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7822 class UnusedBits: public BitField<int, 15, 14> {};
7823 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7825 // Bitfields for pretenure_data
7826 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7827 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7828 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7829 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7831 // Increments the mementos found counter and returns true when the first
7832 // memento was found for a given allocation site.
7833 inline bool IncrementMementoFoundCount();
7835 inline void IncrementMementoCreateCount();
7837 PretenureFlag GetPretenureMode();
7839 void ResetPretenureDecision();
7841 inline PretenureDecision pretenure_decision();
7842 inline void set_pretenure_decision(PretenureDecision decision);
7844 inline bool deopt_dependent_code();
7845 inline void set_deopt_dependent_code(bool deopt);
7847 inline int memento_found_count();
7848 inline void set_memento_found_count(int count);
7850 inline int memento_create_count();
7851 inline void set_memento_create_count(int count);
7853 // The pretenuring decision is made during gc, and the zombie state allows
7854 // us to recognize when an allocation site is just being kept alive because
7855 // a later traversal of new space may discover AllocationMementos that point
7856 // to this AllocationSite.
7857 inline bool IsZombie();
7859 inline bool IsMaybeTenure();
7861 inline void MarkZombie();
7863 inline bool MakePretenureDecision(PretenureDecision current_decision,
7865 bool maximum_size_scavenge);
7867 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7869 inline ElementsKind GetElementsKind();
7870 inline void SetElementsKind(ElementsKind kind);
7872 inline bool CanInlineCall();
7873 inline void SetDoNotInlineCall();
7875 inline bool SitePointsToLiteral();
7877 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7878 ElementsKind to_kind);
7880 DECLARE_PRINTER(AllocationSite)
7881 DECLARE_VERIFIER(AllocationSite)
7883 DECLARE_CAST(AllocationSite)
7884 static inline AllocationSiteMode GetMode(
7885 ElementsKind boilerplate_elements_kind);
7886 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7887 static inline bool CanTrack(InstanceType type);
7889 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7890 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7891 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7892 static const int kPretenureCreateCountOffset =
7893 kPretenureDataOffset + kPointerSize;
7894 static const int kDependentCodeOffset =
7895 kPretenureCreateCountOffset + kPointerSize;
7896 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7897 static const int kSize = kWeakNextOffset + kPointerSize;
7899 // During mark compact we need to take special care for the dependent code
7901 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7902 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7904 // For other visitors, use the fixed body descriptor below.
7905 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7906 kDependentCodeOffset + kPointerSize,
7907 kSize> BodyDescriptor;
7910 inline bool PretenuringDecisionMade();
7912 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7916 class AllocationMemento: public Struct {
7918 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7919 static const int kSize = kAllocationSiteOffset + kPointerSize;
7921 DECL_ACCESSORS(allocation_site, Object)
7923 inline bool IsValid();
7924 inline AllocationSite* GetAllocationSite();
7926 DECLARE_PRINTER(AllocationMemento)
7927 DECLARE_VERIFIER(AllocationMemento)
7929 DECLARE_CAST(AllocationMemento)
7932 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7936 // Representation of a slow alias as part of a sloppy arguments objects.
7937 // For fast aliases (if HasSloppyArgumentsElements()):
7938 // - the parameter map contains an index into the context
7939 // - all attributes of the element have default values
7940 // For slow aliases (if HasDictionaryArgumentsElements()):
7941 // - the parameter map contains no fast alias mapping (i.e. the hole)
7942 // - this struct (in the slow backing store) contains an index into the context
7943 // - all attributes are available as part if the property details
7944 class AliasedArgumentsEntry: public Struct {
7946 inline int aliased_context_slot() const;
7947 inline void set_aliased_context_slot(int count);
7949 DECLARE_CAST(AliasedArgumentsEntry)
7951 // Dispatched behavior.
7952 DECLARE_PRINTER(AliasedArgumentsEntry)
7953 DECLARE_VERIFIER(AliasedArgumentsEntry)
7955 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7956 static const int kSize = kAliasedContextSlot + kPointerSize;
7959 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7963 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7964 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7967 class StringHasher {
7969 explicit inline StringHasher(int length, uint32_t seed);
7971 template <typename schar>
7972 static inline uint32_t HashSequentialString(const schar* chars,
7976 // Reads all the data, even for long strings and computes the utf16 length.
7977 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7979 int* utf16_length_out);
7981 // Calculated hash value for a string consisting of 1 to
7982 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7983 // value is represented decimal value.
7984 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7986 // No string is allowed to have a hash of zero. That value is reserved
7987 // for internal properties. If the hash calculation yields zero then we
7989 static const int kZeroHash = 27;
7991 // Reusable parts of the hashing algorithm.
7992 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7993 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7994 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7995 const uc16* chars, int length));
7996 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8001 // Returns the value to store in the hash field of a string with
8002 // the given length and contents.
8003 uint32_t GetHashField();
8004 // Returns true if the hash of this string can be computed without
8005 // looking at the contents.
8006 inline bool has_trivial_hash();
8007 // Adds a block of characters to the hash.
8008 template<typename Char>
8009 inline void AddCharacters(const Char* chars, int len);
8012 // Add a character to the hash.
8013 inline void AddCharacter(uint16_t c);
8014 // Update index. Returns true if string is still an index.
8015 inline bool UpdateIndex(uint16_t c);
8018 uint32_t raw_running_hash_;
8019 uint32_t array_index_;
8020 bool is_array_index_;
8021 bool is_first_char_;
8022 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8026 class IteratingStringHasher : public StringHasher {
8028 static inline uint32_t Hash(String* string, uint32_t seed);
8029 inline void VisitOneByteString(const uint8_t* chars, int length);
8030 inline void VisitTwoByteString(const uint16_t* chars, int length);
8033 inline IteratingStringHasher(int len, uint32_t seed);
8034 void VisitConsString(ConsString* cons_string);
8035 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8039 // The characteristics of a string are stored in its map. Retrieving these
8040 // few bits of information is moderately expensive, involving two memory
8041 // loads where the second is dependent on the first. To improve efficiency
8042 // the shape of the string is given its own class so that it can be retrieved
8043 // once and used for several string operations. A StringShape is small enough
8044 // to be passed by value and is immutable, but be aware that flattening a
8045 // string can potentially alter its shape. Also be aware that a GC caused by
8046 // something else can alter the shape of a string due to ConsString
8047 // shortcutting. Keeping these restrictions in mind has proven to be error-
8048 // prone and so we no longer put StringShapes in variables unless there is a
8049 // concrete performance benefit at that particular point in the code.
8050 class StringShape BASE_EMBEDDED {
8052 inline explicit StringShape(const String* s);
8053 inline explicit StringShape(Map* s);
8054 inline explicit StringShape(InstanceType t);
8055 inline bool IsSequential();
8056 inline bool IsExternal();
8057 inline bool IsCons();
8058 inline bool IsSliced();
8059 inline bool IsIndirect();
8060 inline bool IsExternalOneByte();
8061 inline bool IsExternalTwoByte();
8062 inline bool IsSequentialOneByte();
8063 inline bool IsSequentialTwoByte();
8064 inline bool IsInternalized();
8065 inline StringRepresentationTag representation_tag();
8066 inline uint32_t encoding_tag();
8067 inline uint32_t full_representation_tag();
8068 inline uint32_t size_tag();
8070 inline uint32_t type() { return type_; }
8071 inline void invalidate() { valid_ = false; }
8072 inline bool valid() { return valid_; }
8074 inline void invalidate() { }
8080 inline void set_valid() { valid_ = true; }
8083 inline void set_valid() { }
8088 // The Name abstract class captures anything that can be used as a property
8089 // name, i.e., strings and symbols. All names store a hash value.
8090 class Name: public HeapObject {
8092 // Get and set the hash field of the name.
8093 inline uint32_t hash_field();
8094 inline void set_hash_field(uint32_t value);
8096 // Tells whether the hash code has been computed.
8097 inline bool HasHashCode();
8099 // Returns a hash value used for the property table
8100 inline uint32_t Hash();
8102 // Equality operations.
8103 inline bool Equals(Name* other);
8104 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8107 inline bool AsArrayIndex(uint32_t* index);
8109 // If the name is private, it can only name own properties.
8110 inline bool IsPrivate();
8112 // If the name is a non-flat string, this method returns a flat version of the
8113 // string. Otherwise it'll just return the input.
8114 static inline Handle<Name> Flatten(Handle<Name> name,
8115 PretenureFlag pretenure = NOT_TENURED);
8117 // Return a string version of this name that is converted according to the
8118 // rules described in ES6 section 9.2.11.
8119 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8123 DECLARE_PRINTER(Name)
8125 void NameShortPrint();
8126 int NameShortPrint(Vector<char> str);
8129 // Layout description.
8130 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8131 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8132 static const int kHashFieldOffset = kHashFieldSlot;
8134 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8136 static const int kSize = kHashFieldSlot + kPointerSize;
8138 // Mask constant for checking if a name has a computed hash code
8139 // and if it is a string that is an array index. The least significant bit
8140 // indicates whether a hash code has been computed. If the hash code has
8141 // been computed the 2nd bit tells whether the string can be used as an
8143 static const int kHashNotComputedMask = 1;
8144 static const int kIsNotArrayIndexMask = 1 << 1;
8145 static const int kNofHashBitFields = 2;
8147 // Shift constant retrieving hash code from hash field.
8148 static const int kHashShift = kNofHashBitFields;
8150 // Only these bits are relevant in the hash, since the top two are shifted
8152 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8154 // Array index strings this short can keep their index in the hash field.
8155 static const int kMaxCachedArrayIndexLength = 7;
8157 // For strings which are array indexes the hash value has the string length
8158 // mixed into the hash, mainly to avoid a hash value of zero which would be
8159 // the case for the string '0'. 24 bits are used for the array index value.
8160 static const int kArrayIndexValueBits = 24;
8161 static const int kArrayIndexLengthBits =
8162 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8164 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8166 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8167 kArrayIndexValueBits> {}; // NOLINT
8168 class ArrayIndexLengthBits : public BitField<unsigned int,
8169 kNofHashBitFields + kArrayIndexValueBits,
8170 kArrayIndexLengthBits> {}; // NOLINT
8172 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8173 // could use a mask to test if the length of string is less than or equal to
8174 // kMaxCachedArrayIndexLength.
8175 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8177 static const unsigned int kContainsCachedArrayIndexMask =
8178 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8179 << ArrayIndexLengthBits::kShift) |
8180 kIsNotArrayIndexMask;
8182 // Value of empty hash field indicating that the hash is not computed.
8183 static const int kEmptyHashField =
8184 kIsNotArrayIndexMask | kHashNotComputedMask;
8187 static inline bool IsHashFieldComputed(uint32_t field);
8190 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8195 class Symbol: public Name {
8197 // [name]: The print name of a symbol, or undefined if none.
8198 DECL_ACCESSORS(name, Object)
8200 DECL_ACCESSORS(flags, Smi)
8202 // [is_private]: Whether this is a private symbol. Private symbols can only
8203 // be used to designate own properties of objects.
8204 DECL_BOOLEAN_ACCESSORS(is_private)
8206 DECLARE_CAST(Symbol)
8208 // Dispatched behavior.
8209 DECLARE_PRINTER(Symbol)
8210 DECLARE_VERIFIER(Symbol)
8212 // Layout description.
8213 static const int kNameOffset = Name::kSize;
8214 static const int kFlagsOffset = kNameOffset + kPointerSize;
8215 static const int kSize = kFlagsOffset + kPointerSize;
8217 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8219 void SymbolShortPrint(std::ostream& os);
8222 static const int kPrivateBit = 0;
8224 const char* PrivateSymbolToName() const;
8227 friend class Name; // For PrivateSymbolToName.
8230 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8236 // The String abstract class captures JavaScript string values:
8239 // 4.3.16 String Value
8240 // A string value is a member of the type String and is a finite
8241 // ordered sequence of zero or more 16-bit unsigned integer values.
8243 // All string values have a length field.
8244 class String: public Name {
8246 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8248 // Array index strings this short can keep their index in the hash field.
8249 static const int kMaxCachedArrayIndexLength = 7;
8251 // For strings which are array indexes the hash value has the string length
8252 // mixed into the hash, mainly to avoid a hash value of zero which would be
8253 // the case for the string '0'. 24 bits are used for the array index value.
8254 static const int kArrayIndexValueBits = 24;
8255 static const int kArrayIndexLengthBits =
8256 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8258 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8260 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8261 kArrayIndexValueBits> {}; // NOLINT
8262 class ArrayIndexLengthBits : public BitField<unsigned int,
8263 kNofHashBitFields + kArrayIndexValueBits,
8264 kArrayIndexLengthBits> {}; // NOLINT
8266 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8267 // could use a mask to test if the length of string is less than or equal to
8268 // kMaxCachedArrayIndexLength.
8269 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8271 static const unsigned int kContainsCachedArrayIndexMask =
8272 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8273 << ArrayIndexLengthBits::kShift) |
8274 kIsNotArrayIndexMask;
8276 class SubStringRange {
8278 explicit inline SubStringRange(String* string, int first = 0,
8281 inline iterator begin();
8282 inline iterator end();
8290 // Representation of the flat content of a String.
8291 // A non-flat string doesn't have flat content.
8292 // A flat string has content that's encoded as a sequence of either
8293 // one-byte chars or two-byte UC16.
8294 // Returned by String::GetFlatContent().
8297 // Returns true if the string is flat and this structure contains content.
8298 bool IsFlat() { return state_ != NON_FLAT; }
8299 // Returns true if the structure contains one-byte content.
8300 bool IsOneByte() { return state_ == ONE_BYTE; }
8301 // Returns true if the structure contains two-byte content.
8302 bool IsTwoByte() { return state_ == TWO_BYTE; }
8304 // Return the one byte content of the string. Only use if IsOneByte()
8306 Vector<const uint8_t> ToOneByteVector() {
8307 DCHECK_EQ(ONE_BYTE, state_);
8308 return Vector<const uint8_t>(onebyte_start, length_);
8310 // Return the two-byte content of the string. Only use if IsTwoByte()
8312 Vector<const uc16> ToUC16Vector() {
8313 DCHECK_EQ(TWO_BYTE, state_);
8314 return Vector<const uc16>(twobyte_start, length_);
8318 DCHECK(i < length_);
8319 DCHECK(state_ != NON_FLAT);
8320 if (state_ == ONE_BYTE) return onebyte_start[i];
8321 return twobyte_start[i];
8324 bool UsesSameString(const FlatContent& other) const {
8325 return onebyte_start == other.onebyte_start;
8329 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8331 // Constructors only used by String::GetFlatContent().
8332 explicit FlatContent(const uint8_t* start, int length)
8333 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8334 explicit FlatContent(const uc16* start, int length)
8335 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8336 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8339 const uint8_t* onebyte_start;
8340 const uc16* twobyte_start;
8345 friend class String;
8346 friend class IterableSubString;
8349 template <typename Char>
8350 INLINE(Vector<const Char> GetCharVector());
8352 // Get and set the length of the string.
8353 inline int length() const;
8354 inline void set_length(int value);
8356 // Get and set the length of the string using acquire loads and release
8358 inline int synchronized_length() const;
8359 inline void synchronized_set_length(int value);
8361 // Returns whether this string has only one-byte chars, i.e. all of them can
8362 // be one-byte encoded. This might be the case even if the string is
8363 // two-byte. Such strings may appear when the embedder prefers
8364 // two-byte external representations even for one-byte data.
8365 inline bool IsOneByteRepresentation() const;
8366 inline bool IsTwoByteRepresentation() const;
8368 // Cons and slices have an encoding flag that may not represent the actual
8369 // encoding of the underlying string. This is taken into account here.
8370 // Requires: this->IsFlat()
8371 inline bool IsOneByteRepresentationUnderneath();
8372 inline bool IsTwoByteRepresentationUnderneath();
8374 // NOTE: this should be considered only a hint. False negatives are
8376 inline bool HasOnlyOneByteChars();
8378 // Get and set individual two byte chars in the string.
8379 inline void Set(int index, uint16_t value);
8380 // Get individual two byte char in the string. Repeated calls
8381 // to this method are not efficient unless the string is flat.
8382 INLINE(uint16_t Get(int index));
8384 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8385 static Handle<Object> ToNumber(Handle<String> subject);
8387 // Flattens the string. Checks first inline to see if it is
8388 // necessary. Does nothing if the string is not a cons string.
8389 // Flattening allocates a sequential string with the same data as
8390 // the given string and mutates the cons string to a degenerate
8391 // form, where the first component is the new sequential string and
8392 // the second component is the empty string. If allocation fails,
8393 // this function returns a failure. If flattening succeeds, this
8394 // function returns the sequential string that is now the first
8395 // component of the cons string.
8397 // Degenerate cons strings are handled specially by the garbage
8398 // collector (see IsShortcutCandidate).
8400 static inline Handle<String> Flatten(Handle<String> string,
8401 PretenureFlag pretenure = NOT_TENURED);
8403 // Tries to return the content of a flat string as a structure holding either
8404 // a flat vector of char or of uc16.
8405 // If the string isn't flat, and therefore doesn't have flat content, the
8406 // returned structure will report so, and can't provide a vector of either
8408 FlatContent GetFlatContent();
8410 // Returns the parent of a sliced string or first part of a flat cons string.
8411 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8412 inline String* GetUnderlying();
8414 // String equality operations.
8415 inline bool Equals(String* other);
8416 inline static bool Equals(Handle<String> one, Handle<String> two);
8417 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8418 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8419 bool IsTwoByteEqualTo(Vector<const uc16> str);
8421 // Return a UTF8 representation of the string. The string is null
8422 // terminated but may optionally contain nulls. Length is returned
8423 // in length_output if length_output is not a null pointer The string
8424 // should be nearly flat, otherwise the performance of this method may
8425 // be very slow (quadratic in the length). Setting robustness_flag to
8426 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8427 // handles unexpected data without causing assert failures and it does not
8428 // do any heap allocations. This is useful when printing stack traces.
8429 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8430 RobustnessFlag robustness_flag,
8431 int offset, int length,
8432 int* length_output = 0);
8433 base::SmartArrayPointer<char> ToCString(
8434 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8435 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8436 int* length_output = 0);
8438 // Return a 16 bit Unicode representation of the string.
8439 // The string should be nearly flat, otherwise the performance of
8440 // of this method may be very bad. Setting robustness_flag to
8441 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8442 // handles unexpected data without causing assert failures and it does not
8443 // do any heap allocations. This is useful when printing stack traces.
8444 base::SmartArrayPointer<uc16> ToWideCString(
8445 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8447 bool ComputeArrayIndex(uint32_t* index);
8450 bool MakeExternal(v8::String::ExternalStringResource* resource);
8451 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8454 inline bool AsArrayIndex(uint32_t* index);
8456 DECLARE_CAST(String)
8458 void PrintOn(FILE* out);
8460 // For use during stack traces. Performs rudimentary sanity check.
8463 // Dispatched behavior.
8464 void StringShortPrint(StringStream* accumulator);
8465 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8466 #if defined(DEBUG) || defined(OBJECT_PRINT)
8467 char* ToAsciiArray();
8469 DECLARE_PRINTER(String)
8470 DECLARE_VERIFIER(String)
8472 inline bool IsFlat();
8474 // Layout description.
8475 static const int kLengthOffset = Name::kSize;
8476 static const int kSize = kLengthOffset + kPointerSize;
8478 // Maximum number of characters to consider when trying to convert a string
8479 // value into an array index.
8480 static const int kMaxArrayIndexSize = 10;
8481 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8484 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8485 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8486 static const int kMaxUtf16CodeUnit = 0xffff;
8487 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8489 // Value of hash field containing computed hash equal to zero.
8490 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8492 // Maximal string length.
8493 static const int kMaxLength = (1 << 28) - 16;
8495 // Max length for computing hash. For strings longer than this limit the
8496 // string length is used as the hash value.
8497 static const int kMaxHashCalcLength = 16383;
8499 // Limit for truncation in short printing.
8500 static const int kMaxShortPrintLength = 1024;
8502 // Support for regular expressions.
8503 const uc16* GetTwoByteData(unsigned start);
8505 // Helper function for flattening strings.
8506 template <typename sinkchar>
8507 static void WriteToFlat(String* source,
8512 // The return value may point to the first aligned word containing the first
8513 // non-one-byte character, rather than directly to the non-one-byte character.
8514 // If the return value is >= the passed length, the entire string was
8516 static inline int NonAsciiStart(const char* chars, int length) {
8517 const char* start = chars;
8518 const char* limit = chars + length;
8520 if (length >= kIntptrSize) {
8521 // Check unaligned bytes.
8522 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8523 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8524 return static_cast<int>(chars - start);
8528 // Check aligned words.
8529 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8530 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8531 while (chars + sizeof(uintptr_t) <= limit) {
8532 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8533 return static_cast<int>(chars - start);
8535 chars += sizeof(uintptr_t);
8538 // Check remaining unaligned bytes.
8539 while (chars < limit) {
8540 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8541 return static_cast<int>(chars - start);
8546 return static_cast<int>(chars - start);
8549 static inline bool IsAscii(const char* chars, int length) {
8550 return NonAsciiStart(chars, length) >= length;
8553 static inline bool IsAscii(const uint8_t* chars, int length) {
8555 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8558 static inline int NonOneByteStart(const uc16* chars, int length) {
8559 const uc16* limit = chars + length;
8560 const uc16* start = chars;
8561 while (chars < limit) {
8562 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8565 return static_cast<int>(chars - start);
8568 static inline bool IsOneByte(const uc16* chars, int length) {
8569 return NonOneByteStart(chars, length) >= length;
8572 template<class Visitor>
8573 static inline ConsString* VisitFlat(Visitor* visitor,
8577 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8578 bool include_ending_line);
8580 // Use the hash field to forward to the canonical internalized string
8581 // when deserializing an internalized string.
8582 inline void SetForwardedInternalizedString(String* string);
8583 inline String* GetForwardedInternalizedString();
8587 friend class StringTableInsertionKey;
8589 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8590 PretenureFlag tenure);
8592 // Slow case of String::Equals. This implementation works on any strings
8593 // but it is most efficient on strings that are almost flat.
8594 bool SlowEquals(String* other);
8596 static bool SlowEquals(Handle<String> one, Handle<String> two);
8598 // Slow case of AsArrayIndex.
8599 bool SlowAsArrayIndex(uint32_t* index);
8601 // Compute and set the hash code.
8602 uint32_t ComputeAndSetHash();
8604 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8608 // The SeqString abstract class captures sequential string values.
8609 class SeqString: public String {
8611 DECLARE_CAST(SeqString)
8613 // Layout description.
8614 static const int kHeaderSize = String::kSize;
8616 // Truncate the string in-place if possible and return the result.
8617 // In case of new_length == 0, the empty string is returned without
8618 // truncating the original string.
8619 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8622 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8626 // The OneByteString class captures sequential one-byte string objects.
8627 // Each character in the OneByteString is an one-byte character.
8628 class SeqOneByteString: public SeqString {
8630 static const bool kHasOneByteEncoding = true;
8632 // Dispatched behavior.
8633 inline uint16_t SeqOneByteStringGet(int index);
8634 inline void SeqOneByteStringSet(int index, uint16_t value);
8636 // Get the address of the characters in this string.
8637 inline Address GetCharsAddress();
8639 inline uint8_t* GetChars();
8641 DECLARE_CAST(SeqOneByteString)
8643 // Garbage collection support. This method is called by the
8644 // garbage collector to compute the actual size of an OneByteString
8646 inline int SeqOneByteStringSize(InstanceType instance_type);
8648 // Computes the size for an OneByteString instance of a given length.
8649 static int SizeFor(int length) {
8650 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8653 // Maximal memory usage for a single sequential one-byte string.
8654 static const int kMaxSize = 512 * MB - 1;
8655 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8658 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8662 // The TwoByteString class captures sequential unicode string objects.
8663 // Each character in the TwoByteString is a two-byte uint16_t.
8664 class SeqTwoByteString: public SeqString {
8666 static const bool kHasOneByteEncoding = false;
8668 // Dispatched behavior.
8669 inline uint16_t SeqTwoByteStringGet(int index);
8670 inline void SeqTwoByteStringSet(int index, uint16_t value);
8672 // Get the address of the characters in this string.
8673 inline Address GetCharsAddress();
8675 inline uc16* GetChars();
8678 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8680 DECLARE_CAST(SeqTwoByteString)
8682 // Garbage collection support. This method is called by the
8683 // garbage collector to compute the actual size of a TwoByteString
8685 inline int SeqTwoByteStringSize(InstanceType instance_type);
8687 // Computes the size for a TwoByteString instance of a given length.
8688 static int SizeFor(int length) {
8689 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8692 // Maximal memory usage for a single sequential two-byte string.
8693 static const int kMaxSize = 512 * MB - 1;
8694 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8695 String::kMaxLength);
8698 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8702 // The ConsString class describes string values built by using the
8703 // addition operator on strings. A ConsString is a pair where the
8704 // first and second components are pointers to other string values.
8705 // One or both components of a ConsString can be pointers to other
8706 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8707 // are non-ConsString string values. The string value represented by
8708 // a ConsString can be obtained by concatenating the leaf string
8709 // values in a left-to-right depth-first traversal of the tree.
8710 class ConsString: public String {
8712 // First string of the cons cell.
8713 inline String* first();
8714 // Doesn't check that the result is a string, even in debug mode. This is
8715 // useful during GC where the mark bits confuse the checks.
8716 inline Object* unchecked_first();
8717 inline void set_first(String* first,
8718 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8720 // Second string of the cons cell.
8721 inline String* second();
8722 // Doesn't check that the result is a string, even in debug mode. This is
8723 // useful during GC where the mark bits confuse the checks.
8724 inline Object* unchecked_second();
8725 inline void set_second(String* second,
8726 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8728 // Dispatched behavior.
8729 uint16_t ConsStringGet(int index);
8731 DECLARE_CAST(ConsString)
8733 // Layout description.
8734 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8735 static const int kSecondOffset = kFirstOffset + kPointerSize;
8736 static const int kSize = kSecondOffset + kPointerSize;
8738 // Minimum length for a cons string.
8739 static const int kMinLength = 13;
8741 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8744 DECLARE_VERIFIER(ConsString)
8747 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8751 // The Sliced String class describes strings that are substrings of another
8752 // sequential string. The motivation is to save time and memory when creating
8753 // a substring. A Sliced String is described as a pointer to the parent,
8754 // the offset from the start of the parent string and the length. Using
8755 // a Sliced String therefore requires unpacking of the parent string and
8756 // adding the offset to the start address. A substring of a Sliced String
8757 // are not nested since the double indirection is simplified when creating
8758 // such a substring.
8759 // Currently missing features are:
8760 // - handling externalized parent strings
8761 // - external strings as parent
8762 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8763 class SlicedString: public String {
8765 inline String* parent();
8766 inline void set_parent(String* parent,
8767 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8768 inline int offset() const;
8769 inline void set_offset(int offset);
8771 // Dispatched behavior.
8772 uint16_t SlicedStringGet(int index);
8774 DECLARE_CAST(SlicedString)
8776 // Layout description.
8777 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8778 static const int kOffsetOffset = kParentOffset + kPointerSize;
8779 static const int kSize = kOffsetOffset + kPointerSize;
8781 // Minimum length for a sliced string.
8782 static const int kMinLength = 13;
8784 typedef FixedBodyDescriptor<kParentOffset,
8785 kOffsetOffset + kPointerSize, kSize>
8788 DECLARE_VERIFIER(SlicedString)
8791 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8795 // The ExternalString class describes string values that are backed by
8796 // a string resource that lies outside the V8 heap. ExternalStrings
8797 // consist of the length field common to all strings, a pointer to the
8798 // external resource. It is important to ensure (externally) that the
8799 // resource is not deallocated while the ExternalString is live in the
8802 // The API expects that all ExternalStrings are created through the
8803 // API. Therefore, ExternalStrings should not be used internally.
8804 class ExternalString: public String {
8806 DECLARE_CAST(ExternalString)
8808 // Layout description.
8809 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8810 static const int kShortSize = kResourceOffset + kPointerSize;
8811 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8812 static const int kSize = kResourceDataOffset + kPointerSize;
8814 static const int kMaxShortLength =
8815 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8817 // Return whether external string is short (data pointer is not cached).
8818 inline bool is_short();
8820 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8823 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8827 // The ExternalOneByteString class is an external string backed by an
8829 class ExternalOneByteString : public ExternalString {
8831 static const bool kHasOneByteEncoding = true;
8833 typedef v8::String::ExternalOneByteStringResource Resource;
8835 // The underlying resource.
8836 inline const Resource* resource();
8837 inline void set_resource(const Resource* buffer);
8839 // Update the pointer cache to the external character array.
8840 // The cached pointer is always valid, as the external character array does =
8841 // not move during lifetime. Deserialization is the only exception, after
8842 // which the pointer cache has to be refreshed.
8843 inline void update_data_cache();
8845 inline const uint8_t* GetChars();
8847 // Dispatched behavior.
8848 inline uint16_t ExternalOneByteStringGet(int index);
8850 DECLARE_CAST(ExternalOneByteString)
8852 // Garbage collection support.
8853 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8855 template <typename StaticVisitor>
8856 inline void ExternalOneByteStringIterateBody();
8859 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8863 // The ExternalTwoByteString class is an external string backed by a UTF-16
8865 class ExternalTwoByteString: public ExternalString {
8867 static const bool kHasOneByteEncoding = false;
8869 typedef v8::String::ExternalStringResource Resource;
8871 // The underlying string resource.
8872 inline const Resource* resource();
8873 inline void set_resource(const Resource* buffer);
8875 // Update the pointer cache to the external character array.
8876 // The cached pointer is always valid, as the external character array does =
8877 // not move during lifetime. Deserialization is the only exception, after
8878 // which the pointer cache has to be refreshed.
8879 inline void update_data_cache();
8881 inline const uint16_t* GetChars();
8883 // Dispatched behavior.
8884 inline uint16_t ExternalTwoByteStringGet(int index);
8887 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8889 DECLARE_CAST(ExternalTwoByteString)
8891 // Garbage collection support.
8892 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8894 template<typename StaticVisitor>
8895 inline void ExternalTwoByteStringIterateBody();
8898 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8902 // Utility superclass for stack-allocated objects that must be updated
8903 // on gc. It provides two ways for the gc to update instances, either
8904 // iterating or updating after gc.
8905 class Relocatable BASE_EMBEDDED {
8907 explicit inline Relocatable(Isolate* isolate);
8908 inline virtual ~Relocatable();
8909 virtual void IterateInstance(ObjectVisitor* v) { }
8910 virtual void PostGarbageCollection() { }
8912 static void PostGarbageCollectionProcessing(Isolate* isolate);
8913 static int ArchiveSpacePerThread();
8914 static char* ArchiveState(Isolate* isolate, char* to);
8915 static char* RestoreState(Isolate* isolate, char* from);
8916 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8917 static void Iterate(ObjectVisitor* v, Relocatable* top);
8918 static char* Iterate(ObjectVisitor* v, char* t);
8926 // A flat string reader provides random access to the contents of a
8927 // string independent of the character width of the string. The handle
8928 // must be valid as long as the reader is being used.
8929 class FlatStringReader : public Relocatable {
8931 FlatStringReader(Isolate* isolate, Handle<String> str);
8932 FlatStringReader(Isolate* isolate, Vector<const char> input);
8933 void PostGarbageCollection();
8934 inline uc32 Get(int index);
8935 template <typename Char>
8936 inline Char Get(int index);
8937 int length() { return length_; }
8946 // This maintains an off-stack representation of the stack frames required
8947 // to traverse a ConsString, allowing an entirely iterative and restartable
8948 // traversal of the entire string
8949 class ConsStringIterator {
8951 inline ConsStringIterator() {}
8952 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8953 Reset(cons_string, offset);
8955 inline void Reset(ConsString* cons_string, int offset = 0) {
8957 // Next will always return NULL.
8958 if (cons_string == NULL) return;
8959 Initialize(cons_string, offset);
8961 // Returns NULL when complete.
8962 inline String* Next(int* offset_out) {
8964 if (depth_ == 0) return NULL;
8965 return Continue(offset_out);
8969 static const int kStackSize = 32;
8970 // Use a mask instead of doing modulo operations for stack wrapping.
8971 static const int kDepthMask = kStackSize-1;
8972 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8973 static inline int OffsetForDepth(int depth);
8975 inline void PushLeft(ConsString* string);
8976 inline void PushRight(ConsString* string);
8977 inline void AdjustMaximumDepth();
8979 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8980 void Initialize(ConsString* cons_string, int offset);
8981 String* Continue(int* offset_out);
8982 String* NextLeaf(bool* blew_stack);
8983 String* Search(int* offset_out);
8985 // Stack must always contain only frames for which right traversal
8986 // has not yet been performed.
8987 ConsString* frames_[kStackSize];
8992 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8996 class StringCharacterStream {
8998 inline StringCharacterStream(String* string,
9000 inline uint16_t GetNext();
9001 inline bool HasMore();
9002 inline void Reset(String* string, int offset = 0);
9003 inline void VisitOneByteString(const uint8_t* chars, int length);
9004 inline void VisitTwoByteString(const uint16_t* chars, int length);
9007 ConsStringIterator iter_;
9010 const uint8_t* buffer8_;
9011 const uint16_t* buffer16_;
9013 const uint8_t* end_;
9014 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9018 template <typename T>
9019 class VectorIterator {
9021 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9022 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9023 T GetNext() { return data_[index_++]; }
9024 bool has_more() { return index_ < data_.length(); }
9026 Vector<const T> data_;
9031 // The Oddball describes objects null, undefined, true, and false.
9032 class Oddball: public HeapObject {
9034 // [to_string]: Cached to_string computed at startup.
9035 DECL_ACCESSORS(to_string, String)
9037 // [to_number]: Cached to_number computed at startup.
9038 DECL_ACCESSORS(to_number, Object)
9040 // [typeof]: Cached type_of computed at startup.
9041 DECL_ACCESSORS(type_of, String)
9043 inline byte kind() const;
9044 inline void set_kind(byte kind);
9046 DECLARE_CAST(Oddball)
9048 // Dispatched behavior.
9049 DECLARE_VERIFIER(Oddball)
9051 // Initialize the fields.
9052 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9053 const char* to_string, Handle<Object> to_number,
9054 const char* type_of, byte kind);
9056 // Layout description.
9057 static const int kToStringOffset = HeapObject::kHeaderSize;
9058 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9059 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9060 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9061 static const int kSize = kKindOffset + kPointerSize;
9063 static const byte kFalse = 0;
9064 static const byte kTrue = 1;
9065 static const byte kNotBooleanMask = ~1;
9066 static const byte kTheHole = 2;
9067 static const byte kNull = 3;
9068 static const byte kArgumentMarker = 4;
9069 static const byte kUndefined = 5;
9070 static const byte kUninitialized = 6;
9071 static const byte kOther = 7;
9072 static const byte kException = 8;
9074 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9075 kSize> BodyDescriptor;
9077 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9078 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9079 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9082 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9086 class Cell: public HeapObject {
9088 // [value]: value of the cell.
9089 DECL_ACCESSORS(value, Object)
9093 static inline Cell* FromValueAddress(Address value) {
9094 Object* result = FromAddress(value - kValueOffset);
9095 return static_cast<Cell*>(result);
9098 inline Address ValueAddress() {
9099 return address() + kValueOffset;
9102 // Dispatched behavior.
9103 DECLARE_PRINTER(Cell)
9104 DECLARE_VERIFIER(Cell)
9106 // Layout description.
9107 static const int kValueOffset = HeapObject::kHeaderSize;
9108 static const int kSize = kValueOffset + kPointerSize;
9110 typedef FixedBodyDescriptor<kValueOffset,
9111 kValueOffset + kPointerSize,
9112 kSize> BodyDescriptor;
9115 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9119 class PropertyCell : public HeapObject {
9121 // [property_details]: details of the global property.
9122 DECL_ACCESSORS(property_details_raw, Object)
9123 // [value]: value of the global property.
9124 DECL_ACCESSORS(value, Object)
9125 // [dependent_code]: dependent code that depends on the type of the global
9127 DECL_ACCESSORS(dependent_code, DependentCode)
9129 inline PropertyDetails property_details();
9130 inline void set_property_details(PropertyDetails details);
9132 PropertyCellConstantType GetConstantType();
9134 // Computes the new type of the cell's contents for the given value, but
9135 // without actually modifying the details.
9136 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9137 Handle<Object> value,
9138 PropertyDetails details);
9139 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9140 Handle<Object> value, PropertyDetails details);
9142 static Handle<PropertyCell> InvalidateEntry(
9143 Handle<GlobalDictionary> dictionary, int entry);
9145 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9146 Handle<Object> new_value);
9148 DECLARE_CAST(PropertyCell)
9150 // Dispatched behavior.
9151 DECLARE_PRINTER(PropertyCell)
9152 DECLARE_VERIFIER(PropertyCell)
9154 // Layout description.
9155 static const int kDetailsOffset = HeapObject::kHeaderSize;
9156 static const int kValueOffset = kDetailsOffset + kPointerSize;
9157 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9158 static const int kSize = kDependentCodeOffset + kPointerSize;
9160 static const int kPointerFieldsBeginOffset = kValueOffset;
9161 static const int kPointerFieldsEndOffset = kSize;
9163 typedef FixedBodyDescriptor<kValueOffset,
9165 kSize> BodyDescriptor;
9168 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9172 class WeakCell : public HeapObject {
9174 inline Object* value() const;
9176 // This should not be called by anyone except GC.
9177 inline void clear();
9179 // This should not be called by anyone except allocator.
9180 inline void initialize(HeapObject* value);
9182 inline bool cleared() const;
9184 DECL_ACCESSORS(next, Object)
9186 inline void clear_next(Heap* heap);
9188 inline bool next_cleared();
9190 DECLARE_CAST(WeakCell)
9192 DECLARE_PRINTER(WeakCell)
9193 DECLARE_VERIFIER(WeakCell)
9195 // Layout description.
9196 static const int kValueOffset = HeapObject::kHeaderSize;
9197 static const int kNextOffset = kValueOffset + kPointerSize;
9198 static const int kSize = kNextOffset + kPointerSize;
9200 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9203 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9207 // The JSProxy describes EcmaScript Harmony proxies
9208 class JSProxy: public JSReceiver {
9210 // [handler]: The handler property.
9211 DECL_ACCESSORS(handler, Object)
9213 // [hash]: The hash code property (undefined if not initialized yet).
9214 DECL_ACCESSORS(hash, Object)
9216 DECLARE_CAST(JSProxy)
9218 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9219 Handle<JSProxy> proxy,
9220 Handle<Object> receiver,
9223 // If the handler defines an accessor property with a setter, invoke it.
9224 // If it defines an accessor property without a setter, or a data property
9225 // that is read-only, throw. In all these cases set '*done' to true,
9226 // otherwise set it to false.
9228 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9229 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9230 Handle<Object> value, LanguageMode language_mode, bool* done);
9232 MUST_USE_RESULT static Maybe<PropertyAttributes>
9233 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9234 Handle<Object> receiver,
9236 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9237 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9238 Handle<Object> value, LanguageMode language_mode);
9240 // Turn the proxy into an (empty) JSObject.
9241 static void Fix(Handle<JSProxy> proxy);
9243 // Initializes the body after the handler slot.
9244 inline void InitializeBody(int object_size, Object* value);
9246 // Invoke a trap by name. If the trap does not exist on this's handler,
9247 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9248 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9249 Handle<JSProxy> proxy,
9251 Handle<Object> derived_trap,
9253 Handle<Object> args[]);
9255 // Dispatched behavior.
9256 DECLARE_PRINTER(JSProxy)
9257 DECLARE_VERIFIER(JSProxy)
9259 // Layout description. We add padding so that a proxy has the same
9260 // size as a virgin JSObject. This is essential for becoming a JSObject
9262 static const int kHandlerOffset = HeapObject::kHeaderSize;
9263 static const int kHashOffset = kHandlerOffset + kPointerSize;
9264 static const int kPaddingOffset = kHashOffset + kPointerSize;
9265 static const int kSize = JSObject::kHeaderSize;
9266 static const int kHeaderSize = kPaddingOffset;
9267 static const int kPaddingSize = kSize - kPaddingOffset;
9269 STATIC_ASSERT(kPaddingSize >= 0);
9271 typedef FixedBodyDescriptor<kHandlerOffset,
9273 kSize> BodyDescriptor;
9276 friend class JSReceiver;
9278 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9279 Handle<JSProxy> proxy, Handle<Name> name);
9281 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9282 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9284 MUST_USE_RESULT Object* GetIdentityHash();
9286 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9288 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9292 class JSFunctionProxy: public JSProxy {
9294 // [call_trap]: The call trap.
9295 DECL_ACCESSORS(call_trap, JSReceiver)
9297 // [construct_trap]: The construct trap.
9298 DECL_ACCESSORS(construct_trap, Object)
9300 DECLARE_CAST(JSFunctionProxy)
9302 // Dispatched behavior.
9303 DECLARE_PRINTER(JSFunctionProxy)
9304 DECLARE_VERIFIER(JSFunctionProxy)
9306 // Layout description.
9307 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9308 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9309 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9310 static const int kSize = JSFunction::kSize;
9311 static const int kPaddingSize = kSize - kPaddingOffset;
9313 STATIC_ASSERT(kPaddingSize >= 0);
9315 typedef FixedBodyDescriptor<kHandlerOffset,
9316 kConstructTrapOffset + kPointerSize,
9317 kSize> BodyDescriptor;
9320 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9324 class JSCollection : public JSObject {
9326 // [table]: the backing hash table
9327 DECL_ACCESSORS(table, Object)
9329 static const int kTableOffset = JSObject::kHeaderSize;
9330 static const int kSize = kTableOffset + kPointerSize;
9333 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9337 // The JSSet describes EcmaScript Harmony sets
9338 class JSSet : public JSCollection {
9342 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9343 static void Clear(Handle<JSSet> set);
9345 // Dispatched behavior.
9346 DECLARE_PRINTER(JSSet)
9347 DECLARE_VERIFIER(JSSet)
9350 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9354 // The JSMap describes EcmaScript Harmony maps
9355 class JSMap : public JSCollection {
9359 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9360 static void Clear(Handle<JSMap> map);
9362 // Dispatched behavior.
9363 DECLARE_PRINTER(JSMap)
9364 DECLARE_VERIFIER(JSMap)
9367 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9371 // OrderedHashTableIterator is an iterator that iterates over the keys and
9372 // values of an OrderedHashTable.
9374 // The iterator has a reference to the underlying OrderedHashTable data,
9375 // [table], as well as the current [index] the iterator is at.
9377 // When the OrderedHashTable is rehashed it adds a reference from the old table
9378 // to the new table as well as storing enough data about the changes so that the
9379 // iterator [index] can be adjusted accordingly.
9381 // When the [Next] result from the iterator is requested, the iterator checks if
9382 // there is a newer table that it needs to transition to.
9383 template<class Derived, class TableType>
9384 class OrderedHashTableIterator: public JSObject {
9386 // [table]: the backing hash table mapping keys to values.
9387 DECL_ACCESSORS(table, Object)
9389 // [index]: The index into the data table.
9390 DECL_ACCESSORS(index, Object)
9392 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9393 DECL_ACCESSORS(kind, Object)
9396 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9399 static const int kTableOffset = JSObject::kHeaderSize;
9400 static const int kIndexOffset = kTableOffset + kPointerSize;
9401 static const int kKindOffset = kIndexOffset + kPointerSize;
9402 static const int kSize = kKindOffset + kPointerSize;
9410 // Whether the iterator has more elements. This needs to be called before
9411 // calling |CurrentKey| and/or |CurrentValue|.
9414 // Move the index forward one.
9416 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9419 // Populates the array with the next key and value and then moves the iterator
9421 // This returns the |kind| or 0 if the iterator is already at the end.
9422 Smi* Next(JSArray* value_array);
9424 // Returns the current key of the iterator. This should only be called when
9425 // |HasMore| returns true.
9426 inline Object* CurrentKey();
9429 // Transitions the iterator to the non obsolete backing store. This is a NOP
9430 // if the [table] is not obsolete.
9433 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9437 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9440 // Dispatched behavior.
9441 DECLARE_PRINTER(JSSetIterator)
9442 DECLARE_VERIFIER(JSSetIterator)
9444 DECLARE_CAST(JSSetIterator)
9446 // Called by |Next| to populate the array. This allows the subclasses to
9447 // populate the array differently.
9448 inline void PopulateValueArray(FixedArray* array);
9451 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9455 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9458 // Dispatched behavior.
9459 DECLARE_PRINTER(JSMapIterator)
9460 DECLARE_VERIFIER(JSMapIterator)
9462 DECLARE_CAST(JSMapIterator)
9464 // Called by |Next| to populate the array. This allows the subclasses to
9465 // populate the array differently.
9466 inline void PopulateValueArray(FixedArray* array);
9469 // Returns the current value of the iterator. This should only be called when
9470 // |HasMore| returns true.
9471 inline Object* CurrentValue();
9473 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9477 // ES6 section 25.1.1.3 The IteratorResult Interface
9478 class JSIteratorResult final : public JSObject {
9480 // [done]: This is the result status of an iterator next method call. If the
9481 // end of the iterator was reached done is true. If the end was not reached
9482 // done is false and a [value] is available.
9483 DECL_ACCESSORS(done, Object)
9485 // [value]: If [done] is false, this is the current iteration element value.
9486 // If [done] is true, this is the return value of the iterator, if it supplied
9487 // one. If the iterator does not have a return value, value is undefined.
9488 // In that case, the value property may be absent from the conforming object
9489 // if it does not inherit an explicit value property.
9490 DECL_ACCESSORS(value, Object)
9492 // Dispatched behavior.
9493 DECLARE_PRINTER(JSIteratorResult)
9494 DECLARE_VERIFIER(JSIteratorResult)
9496 DECLARE_CAST(JSIteratorResult)
9498 static const int kValueOffset = JSObject::kHeaderSize;
9499 static const int kDoneOffset = kValueOffset + kPointerSize;
9500 static const int kSize = kDoneOffset + kPointerSize;
9502 // Indices of in-object properties.
9503 static const int kValueIndex = 0;
9504 static const int kDoneIndex = 1;
9507 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9511 // Base class for both JSWeakMap and JSWeakSet
9512 class JSWeakCollection: public JSObject {
9514 // [table]: the backing hash table mapping keys to values.
9515 DECL_ACCESSORS(table, Object)
9517 // [next]: linked list of encountered weak maps during GC.
9518 DECL_ACCESSORS(next, Object)
9520 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9521 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9522 Handle<Object> value, int32_t hash);
9523 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9526 static const int kTableOffset = JSObject::kHeaderSize;
9527 static const int kNextOffset = kTableOffset + kPointerSize;
9528 static const int kSize = kNextOffset + kPointerSize;
9531 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9535 // The JSWeakMap describes EcmaScript Harmony weak maps
9536 class JSWeakMap: public JSWeakCollection {
9538 DECLARE_CAST(JSWeakMap)
9540 // Dispatched behavior.
9541 DECLARE_PRINTER(JSWeakMap)
9542 DECLARE_VERIFIER(JSWeakMap)
9545 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9549 // The JSWeakSet describes EcmaScript Harmony weak sets
9550 class JSWeakSet: public JSWeakCollection {
9552 DECLARE_CAST(JSWeakSet)
9554 // Dispatched behavior.
9555 DECLARE_PRINTER(JSWeakSet)
9556 DECLARE_VERIFIER(JSWeakSet)
9559 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9563 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9564 enum class SharedFlag { kNotShared, kShared };
9567 class JSArrayBuffer: public JSObject {
9569 // [backing_store]: backing memory for this array
9570 DECL_ACCESSORS(backing_store, void)
9572 // [byte_length]: length in bytes
9573 DECL_ACCESSORS(byte_length, Object)
9575 inline uint32_t bit_field() const;
9576 inline void set_bit_field(uint32_t bits);
9578 inline bool is_external();
9579 inline void set_is_external(bool value);
9581 inline bool is_neuterable();
9582 inline void set_is_neuterable(bool value);
9584 inline bool was_neutered();
9585 inline void set_was_neutered(bool value);
9587 inline bool is_shared();
9588 inline void set_is_shared(bool value);
9590 DECLARE_CAST(JSArrayBuffer)
9594 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9595 bool is_external, void* data, size_t allocated_length,
9596 SharedFlag shared = SharedFlag::kNotShared);
9598 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9599 Isolate* isolate, size_t allocated_length,
9600 bool initialize = true,
9601 SharedFlag shared = SharedFlag::kNotShared);
9603 // Dispatched behavior.
9604 DECLARE_PRINTER(JSArrayBuffer)
9605 DECLARE_VERIFIER(JSArrayBuffer)
9607 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9608 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9609 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9610 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9611 static const int kBitFieldOffset = kBitFieldSlot;
9613 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9615 static const int kSize = kBitFieldSlot + kPointerSize;
9617 static const int kSizeWithInternalFields =
9618 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9620 class IsExternal : public BitField<bool, 1, 1> {};
9621 class IsNeuterable : public BitField<bool, 2, 1> {};
9622 class WasNeutered : public BitField<bool, 3, 1> {};
9623 class IsShared : public BitField<bool, 4, 1> {};
9626 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9630 class JSArrayBufferView: public JSObject {
9632 // [buffer]: ArrayBuffer that this typed array views.
9633 DECL_ACCESSORS(buffer, Object)
9635 // [byte_offset]: offset of typed array in bytes.
9636 DECL_ACCESSORS(byte_offset, Object)
9638 // [byte_length]: length of typed array in bytes.
9639 DECL_ACCESSORS(byte_length, Object)
9641 DECLARE_CAST(JSArrayBufferView)
9643 DECLARE_VERIFIER(JSArrayBufferView)
9645 inline bool WasNeutered() const;
9647 static const int kBufferOffset = JSObject::kHeaderSize;
9648 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9649 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9650 static const int kViewSize = kByteLengthOffset + kPointerSize;
9654 DECL_ACCESSORS(raw_byte_offset, Object)
9655 DECL_ACCESSORS(raw_byte_length, Object)
9658 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9662 class JSTypedArray: public JSArrayBufferView {
9664 // [length]: length of typed array in elements.
9665 DECL_ACCESSORS(length, Object)
9666 inline uint32_t length_value() const;
9668 DECLARE_CAST(JSTypedArray)
9670 ExternalArrayType type();
9671 size_t element_size();
9673 Handle<JSArrayBuffer> GetBuffer();
9675 // Dispatched behavior.
9676 DECLARE_PRINTER(JSTypedArray)
9677 DECLARE_VERIFIER(JSTypedArray)
9679 static const int kLengthOffset = kViewSize + kPointerSize;
9680 static const int kSize = kLengthOffset + kPointerSize;
9682 static const int kSizeWithInternalFields =
9683 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9686 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9687 Handle<JSTypedArray> typed_array);
9689 DECL_ACCESSORS(raw_length, Object)
9692 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9696 class JSDataView: public JSArrayBufferView {
9698 DECLARE_CAST(JSDataView)
9700 // Dispatched behavior.
9701 DECLARE_PRINTER(JSDataView)
9702 DECLARE_VERIFIER(JSDataView)
9704 static const int kSize = kViewSize;
9706 static const int kSizeWithInternalFields =
9707 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9710 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9714 // Foreign describes objects pointing from JavaScript to C structures.
9715 class Foreign: public HeapObject {
9717 // [address]: field containing the address.
9718 inline Address foreign_address();
9719 inline void set_foreign_address(Address value);
9721 DECLARE_CAST(Foreign)
9723 // Dispatched behavior.
9724 inline void ForeignIterateBody(ObjectVisitor* v);
9726 template<typename StaticVisitor>
9727 inline void ForeignIterateBody();
9729 // Dispatched behavior.
9730 DECLARE_PRINTER(Foreign)
9731 DECLARE_VERIFIER(Foreign)
9733 // Layout description.
9735 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9736 static const int kSize = kForeignAddressOffset + kPointerSize;
9738 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9741 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9745 // The JSArray describes JavaScript Arrays
9746 // Such an array can be in one of two modes:
9747 // - fast, backing storage is a FixedArray and length <= elements.length();
9748 // Please note: push and pop can be used to grow and shrink the array.
9749 // - slow, backing storage is a HashTable with numbers as keys.
9750 class JSArray: public JSObject {
9752 // [length]: The length property.
9753 DECL_ACCESSORS(length, Object)
9755 // Overload the length setter to skip write barrier when the length
9756 // is set to a smi. This matches the set function on FixedArray.
9757 inline void set_length(Smi* length);
9759 static bool HasReadOnlyLength(Handle<JSArray> array);
9760 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9761 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9763 // Initialize the array with the given capacity. The function may
9764 // fail due to out-of-memory situations, but only if the requested
9765 // capacity is non-zero.
9766 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9768 // If the JSArray has fast elements, and new_length would result in
9769 // normalization, returns true.
9770 bool SetLengthWouldNormalize(uint32_t new_length);
9771 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9773 // Initializes the array to a certain length.
9774 inline bool AllowsSetLength();
9776 static void SetLength(Handle<JSArray> array, uint32_t length);
9777 // Same as above but will also queue splice records if |array| is observed.
9778 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9781 // Set the content of the array to the content of storage.
9782 static inline void SetContent(Handle<JSArray> array,
9783 Handle<FixedArrayBase> storage);
9785 DECLARE_CAST(JSArray)
9787 // Dispatched behavior.
9788 DECLARE_PRINTER(JSArray)
9789 DECLARE_VERIFIER(JSArray)
9791 // Number of element slots to pre-allocate for an empty array.
9792 static const int kPreallocatedArrayElements = 4;
9794 // Layout description.
9795 static const int kLengthOffset = JSObject::kHeaderSize;
9796 static const int kSize = kLengthOffset + kPointerSize;
9799 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9803 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9804 Handle<Map> initial_map);
9807 // JSRegExpResult is just a JSArray with a specific initial map.
9808 // This initial map adds in-object properties for "index" and "input"
9809 // properties, as assigned by RegExp.prototype.exec, which allows
9810 // faster creation of RegExp exec results.
9811 // This class just holds constants used when creating the result.
9812 // After creation the result must be treated as a JSArray in all regards.
9813 class JSRegExpResult: public JSArray {
9815 // Offsets of object fields.
9816 static const int kIndexOffset = JSArray::kSize;
9817 static const int kInputOffset = kIndexOffset + kPointerSize;
9818 static const int kSize = kInputOffset + kPointerSize;
9819 // Indices of in-object properties.
9820 static const int kIndexIndex = 0;
9821 static const int kInputIndex = 1;
9823 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9827 class AccessorInfo: public Struct {
9829 DECL_ACCESSORS(name, Object)
9830 DECL_ACCESSORS(flag, Smi)
9831 DECL_ACCESSORS(expected_receiver_type, Object)
9833 inline bool all_can_read();
9834 inline void set_all_can_read(bool value);
9836 inline bool all_can_write();
9837 inline void set_all_can_write(bool value);
9839 inline bool is_special_data_property();
9840 inline void set_is_special_data_property(bool value);
9842 inline PropertyAttributes property_attributes();
9843 inline void set_property_attributes(PropertyAttributes attributes);
9845 // Checks whether the given receiver is compatible with this accessor.
9846 static bool IsCompatibleReceiverMap(Isolate* isolate,
9847 Handle<AccessorInfo> info,
9849 inline bool IsCompatibleReceiver(Object* receiver);
9851 DECLARE_CAST(AccessorInfo)
9853 // Dispatched behavior.
9854 DECLARE_VERIFIER(AccessorInfo)
9856 // Append all descriptors to the array that are not already there.
9857 // Return number added.
9858 static int AppendUnique(Handle<Object> descriptors,
9859 Handle<FixedArray> array,
9860 int valid_descriptors);
9862 static const int kNameOffset = HeapObject::kHeaderSize;
9863 static const int kFlagOffset = kNameOffset + kPointerSize;
9864 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9865 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9868 inline bool HasExpectedReceiverType();
9870 // Bit positions in flag.
9871 static const int kAllCanReadBit = 0;
9872 static const int kAllCanWriteBit = 1;
9873 static const int kSpecialDataProperty = 2;
9874 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9876 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9880 // An accessor must have a getter, but can have no setter.
9882 // When setting a property, V8 searches accessors in prototypes.
9883 // If an accessor was found and it does not have a setter,
9884 // the request is ignored.
9886 // If the accessor in the prototype has the READ_ONLY property attribute, then
9887 // a new value is added to the derived object when the property is set.
9888 // This shadows the accessor in the prototype.
9889 class ExecutableAccessorInfo: public AccessorInfo {
9891 DECL_ACCESSORS(getter, Object)
9892 DECL_ACCESSORS(setter, Object)
9893 DECL_ACCESSORS(data, Object)
9895 DECLARE_CAST(ExecutableAccessorInfo)
9897 // Dispatched behavior.
9898 DECLARE_PRINTER(ExecutableAccessorInfo)
9899 DECLARE_VERIFIER(ExecutableAccessorInfo)
9901 static const int kGetterOffset = AccessorInfo::kSize;
9902 static const int kSetterOffset = kGetterOffset + kPointerSize;
9903 static const int kDataOffset = kSetterOffset + kPointerSize;
9904 static const int kSize = kDataOffset + kPointerSize;
9906 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9909 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9913 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9914 // accessor can either be
9915 // * a pointer to a JavaScript function or proxy: a real accessor
9916 // * undefined: considered an accessor by the spec, too, strangely enough
9917 // * the hole: an accessor which has not been set
9918 // * a pointer to a map: a transition used to ensure map sharing
9919 class AccessorPair: public Struct {
9921 DECL_ACCESSORS(getter, Object)
9922 DECL_ACCESSORS(setter, Object)
9924 DECLARE_CAST(AccessorPair)
9926 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9928 inline Object* get(AccessorComponent component);
9929 inline void set(AccessorComponent component, Object* value);
9931 // Note: Returns undefined instead in case of a hole.
9932 Object* GetComponent(AccessorComponent component);
9934 // Set both components, skipping arguments which are a JavaScript null.
9935 inline void SetComponents(Object* getter, Object* setter);
9937 inline bool Equals(AccessorPair* pair);
9938 inline bool Equals(Object* getter_value, Object* setter_value);
9940 inline bool ContainsAccessor();
9942 // Dispatched behavior.
9943 DECLARE_PRINTER(AccessorPair)
9944 DECLARE_VERIFIER(AccessorPair)
9946 static const int kGetterOffset = HeapObject::kHeaderSize;
9947 static const int kSetterOffset = kGetterOffset + kPointerSize;
9948 static const int kSize = kSetterOffset + kPointerSize;
9951 // Strangely enough, in addition to functions and harmony proxies, the spec
9952 // requires us to consider undefined as a kind of accessor, too:
9954 // Object.defineProperty(obj, "foo", {get: undefined});
9955 // assertTrue("foo" in obj);
9956 inline bool IsJSAccessor(Object* obj);
9958 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9962 class AccessCheckInfo: public Struct {
9964 DECL_ACCESSORS(named_callback, Object)
9965 DECL_ACCESSORS(indexed_callback, Object)
9966 DECL_ACCESSORS(data, Object)
9968 DECLARE_CAST(AccessCheckInfo)
9970 // Dispatched behavior.
9971 DECLARE_PRINTER(AccessCheckInfo)
9972 DECLARE_VERIFIER(AccessCheckInfo)
9974 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9975 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9976 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9977 static const int kSize = kDataOffset + kPointerSize;
9980 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9984 class InterceptorInfo: public Struct {
9986 DECL_ACCESSORS(getter, Object)
9987 DECL_ACCESSORS(setter, Object)
9988 DECL_ACCESSORS(query, Object)
9989 DECL_ACCESSORS(deleter, Object)
9990 DECL_ACCESSORS(enumerator, Object)
9991 DECL_ACCESSORS(data, Object)
9992 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9993 DECL_BOOLEAN_ACCESSORS(all_can_read)
9994 DECL_BOOLEAN_ACCESSORS(non_masking)
9996 inline int flags() const;
9997 inline void set_flags(int flags);
9999 DECLARE_CAST(InterceptorInfo)
10001 // Dispatched behavior.
10002 DECLARE_PRINTER(InterceptorInfo)
10003 DECLARE_VERIFIER(InterceptorInfo)
10005 static const int kGetterOffset = HeapObject::kHeaderSize;
10006 static const int kSetterOffset = kGetterOffset + kPointerSize;
10007 static const int kQueryOffset = kSetterOffset + kPointerSize;
10008 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10009 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10010 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10011 static const int kFlagsOffset = kDataOffset + kPointerSize;
10012 static const int kSize = kFlagsOffset + kPointerSize;
10014 static const int kCanInterceptSymbolsBit = 0;
10015 static const int kAllCanReadBit = 1;
10016 static const int kNonMasking = 2;
10019 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10023 class CallHandlerInfo: public Struct {
10025 DECL_ACCESSORS(callback, Object)
10026 DECL_ACCESSORS(data, Object)
10028 DECLARE_CAST(CallHandlerInfo)
10030 // Dispatched behavior.
10031 DECLARE_PRINTER(CallHandlerInfo)
10032 DECLARE_VERIFIER(CallHandlerInfo)
10034 static const int kCallbackOffset = HeapObject::kHeaderSize;
10035 static const int kDataOffset = kCallbackOffset + kPointerSize;
10036 static const int kSize = kDataOffset + kPointerSize;
10039 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10043 class TemplateInfo: public Struct {
10045 DECL_ACCESSORS(tag, Object)
10046 inline int number_of_properties() const;
10047 inline void set_number_of_properties(int value);
10048 DECL_ACCESSORS(property_list, Object)
10049 DECL_ACCESSORS(property_accessors, Object)
10051 DECLARE_VERIFIER(TemplateInfo)
10053 static const int kTagOffset = HeapObject::kHeaderSize;
10054 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10055 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10056 static const int kPropertyAccessorsOffset =
10057 kPropertyListOffset + kPointerSize;
10058 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10061 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10065 class FunctionTemplateInfo: public TemplateInfo {
10067 DECL_ACCESSORS(serial_number, Object)
10068 DECL_ACCESSORS(call_code, Object)
10069 DECL_ACCESSORS(prototype_template, Object)
10070 DECL_ACCESSORS(parent_template, Object)
10071 DECL_ACCESSORS(named_property_handler, Object)
10072 DECL_ACCESSORS(indexed_property_handler, Object)
10073 DECL_ACCESSORS(instance_template, Object)
10074 DECL_ACCESSORS(class_name, Object)
10075 DECL_ACCESSORS(signature, Object)
10076 DECL_ACCESSORS(instance_call_handler, Object)
10077 DECL_ACCESSORS(access_check_info, Object)
10078 DECL_ACCESSORS(flag, Smi)
10080 inline int length() const;
10081 inline void set_length(int value);
10083 // Following properties use flag bits.
10084 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10085 DECL_BOOLEAN_ACCESSORS(undetectable)
10086 // If the bit is set, object instances created by this function
10087 // requires access check.
10088 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10089 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10090 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10091 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10092 DECL_BOOLEAN_ACCESSORS(instantiated)
10093 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10095 DECLARE_CAST(FunctionTemplateInfo)
10097 // Dispatched behavior.
10098 DECLARE_PRINTER(FunctionTemplateInfo)
10099 DECLARE_VERIFIER(FunctionTemplateInfo)
10101 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10102 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10103 static const int kPrototypeTemplateOffset =
10104 kCallCodeOffset + kPointerSize;
10105 static const int kParentTemplateOffset =
10106 kPrototypeTemplateOffset + kPointerSize;
10107 static const int kNamedPropertyHandlerOffset =
10108 kParentTemplateOffset + kPointerSize;
10109 static const int kIndexedPropertyHandlerOffset =
10110 kNamedPropertyHandlerOffset + kPointerSize;
10111 static const int kInstanceTemplateOffset =
10112 kIndexedPropertyHandlerOffset + kPointerSize;
10113 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10114 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10115 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10116 static const int kAccessCheckInfoOffset =
10117 kInstanceCallHandlerOffset + kPointerSize;
10118 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10119 static const int kLengthOffset = kFlagOffset + kPointerSize;
10120 static const int kSize = kLengthOffset + kPointerSize;
10122 // Returns true if |object| is an instance of this function template.
10123 bool IsTemplateFor(Object* object);
10124 bool IsTemplateFor(Map* map);
10126 // Returns the holder JSObject if the function can legally be called with this
10127 // receiver. Returns Heap::null_value() if the call is illegal.
10128 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10131 // Bit position in the flag, from least significant bit position.
10132 static const int kHiddenPrototypeBit = 0;
10133 static const int kUndetectableBit = 1;
10134 static const int kNeedsAccessCheckBit = 2;
10135 static const int kReadOnlyPrototypeBit = 3;
10136 static const int kRemovePrototypeBit = 4;
10137 static const int kDoNotCacheBit = 5;
10138 static const int kInstantiatedBit = 6;
10139 static const int kAcceptAnyReceiver = 7;
10141 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10145 class ObjectTemplateInfo: public TemplateInfo {
10147 DECL_ACCESSORS(constructor, Object)
10148 DECL_ACCESSORS(internal_field_count, Object)
10150 DECLARE_CAST(ObjectTemplateInfo)
10152 // Dispatched behavior.
10153 DECLARE_PRINTER(ObjectTemplateInfo)
10154 DECLARE_VERIFIER(ObjectTemplateInfo)
10156 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10157 static const int kInternalFieldCountOffset =
10158 kConstructorOffset + kPointerSize;
10159 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10163 class TypeSwitchInfo: public Struct {
10165 DECL_ACCESSORS(types, Object)
10167 DECLARE_CAST(TypeSwitchInfo)
10169 // Dispatched behavior.
10170 DECLARE_PRINTER(TypeSwitchInfo)
10171 DECLARE_VERIFIER(TypeSwitchInfo)
10173 static const int kTypesOffset = Struct::kHeaderSize;
10174 static const int kSize = kTypesOffset + kPointerSize;
10178 // The DebugInfo class holds additional information for a function being
10180 class DebugInfo: public Struct {
10182 // The shared function info for the source being debugged.
10183 DECL_ACCESSORS(shared, SharedFunctionInfo)
10184 // Code object for the patched code. This code object is the code object
10185 // currently active for the function.
10186 DECL_ACCESSORS(code, Code)
10187 // Fixed array holding status information for each active break point.
10188 DECL_ACCESSORS(break_points, FixedArray)
10190 // Check if there is a break point at a code position.
10191 bool HasBreakPoint(int code_position);
10192 // Get the break point info object for a code position.
10193 Object* GetBreakPointInfo(int code_position);
10194 // Clear a break point.
10195 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10197 Handle<Object> break_point_object);
10198 // Set a break point.
10199 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10200 int source_position, int statement_position,
10201 Handle<Object> break_point_object);
10202 // Get the break point objects for a code position.
10203 Handle<Object> GetBreakPointObjects(int code_position);
10204 // Find the break point info holding this break point object.
10205 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10206 Handle<Object> break_point_object);
10207 // Get the number of break points for this function.
10208 int GetBreakPointCount();
10210 DECLARE_CAST(DebugInfo)
10212 // Dispatched behavior.
10213 DECLARE_PRINTER(DebugInfo)
10214 DECLARE_VERIFIER(DebugInfo)
10216 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10217 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10218 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10219 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10221 static const int kEstimatedNofBreakPointsInFunction = 16;
10224 static const int kNoBreakPointInfo = -1;
10226 // Lookup the index in the break_points array for a code position.
10227 int GetBreakPointInfoIndex(int code_position);
10229 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10233 // The BreakPointInfo class holds information for break points set in a
10234 // function. The DebugInfo object holds a BreakPointInfo object for each code
10235 // position with one or more break points.
10236 class BreakPointInfo: public Struct {
10238 // The position in the code for the break point.
10239 DECL_ACCESSORS(code_position, Smi)
10240 // The position in the source for the break position.
10241 DECL_ACCESSORS(source_position, Smi)
10242 // The position in the source for the last statement before this break
10244 DECL_ACCESSORS(statement_position, Smi)
10245 // List of related JavaScript break points.
10246 DECL_ACCESSORS(break_point_objects, Object)
10248 // Removes a break point.
10249 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10250 Handle<Object> break_point_object);
10251 // Set a break point.
10252 static void SetBreakPoint(Handle<BreakPointInfo> info,
10253 Handle<Object> break_point_object);
10254 // Check if break point info has this break point object.
10255 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10256 Handle<Object> break_point_object);
10257 // Get the number of break points for this code position.
10258 int GetBreakPointCount();
10260 DECLARE_CAST(BreakPointInfo)
10262 // Dispatched behavior.
10263 DECLARE_PRINTER(BreakPointInfo)
10264 DECLARE_VERIFIER(BreakPointInfo)
10266 static const int kCodePositionIndex = Struct::kHeaderSize;
10267 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10268 static const int kStatementPositionIndex =
10269 kSourcePositionIndex + kPointerSize;
10270 static const int kBreakPointObjectsIndex =
10271 kStatementPositionIndex + kPointerSize;
10272 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10275 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10279 #undef DECL_BOOLEAN_ACCESSORS
10280 #undef DECL_ACCESSORS
10281 #undef DECLARE_CAST
10282 #undef DECLARE_VERIFIER
10284 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10285 V(kStringTable, "string_table", "(Internalized strings)") \
10286 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10287 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10288 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10289 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10290 V(kTop, "top", "(Isolate)") \
10291 V(kRelocatable, "relocatable", "(Relocatable)") \
10292 V(kDebug, "debug", "(Debugger)") \
10293 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10294 V(kHandleScope, "handlescope", "(Handle scope)") \
10295 V(kBuiltins, "builtins", "(Builtins)") \
10296 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10297 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10298 V(kThreadManager, "threadmanager", "(Thread manager)") \
10299 V(kStrongRoots, "strong roots", "(Strong roots)") \
10300 V(kExtensions, "Extensions", "(Extensions)")
10302 class VisitorSynchronization : public AllStatic {
10304 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10306 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10309 #undef DECLARE_ENUM
10311 static const char* const kTags[kNumberOfSyncTags];
10312 static const char* const kTagNames[kNumberOfSyncTags];
10315 // Abstract base class for visiting, and optionally modifying, the
10316 // pointers contained in Objects. Used in GC and serialization/deserialization.
10317 class ObjectVisitor BASE_EMBEDDED {
10319 virtual ~ObjectVisitor() {}
10321 // Visits a contiguous arrays of pointers in the half-open range
10322 // [start, end). Any or all of the values may be modified on return.
10323 virtual void VisitPointers(Object** start, Object** end) = 0;
10325 // Handy shorthand for visiting a single pointer.
10326 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10328 // Visit weak next_code_link in Code object.
10329 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10331 // To allow lazy clearing of inline caches the visitor has
10332 // a rich interface for iterating over Code objects..
10334 // Visits a code target in the instruction stream.
10335 virtual void VisitCodeTarget(RelocInfo* rinfo);
10337 // Visits a code entry in a JS function.
10338 virtual void VisitCodeEntry(Address entry_address);
10340 // Visits a global property cell reference in the instruction stream.
10341 virtual void VisitCell(RelocInfo* rinfo);
10343 // Visits a runtime entry in the instruction stream.
10344 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10346 // Visits the resource of an one-byte or two-byte string.
10347 virtual void VisitExternalOneByteString(
10348 v8::String::ExternalOneByteStringResource** resource) {}
10349 virtual void VisitExternalTwoByteString(
10350 v8::String::ExternalStringResource** resource) {}
10352 // Visits a debug call target in the instruction stream.
10353 virtual void VisitDebugTarget(RelocInfo* rinfo);
10355 // Visits the byte sequence in a function's prologue that contains information
10356 // about the code's age.
10357 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10359 // Visit pointer embedded into a code object.
10360 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10362 // Visits an external reference embedded into a code object.
10363 virtual void VisitExternalReference(RelocInfo* rinfo);
10365 // Visits an external reference.
10366 virtual void VisitExternalReference(Address* p) {}
10368 // Visits an (encoded) internal reference.
10369 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10371 // Visits a handle that has an embedder-assigned class ID.
10372 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10374 // Intended for serialization/deserialization checking: insert, or
10375 // check for the presence of, a tag at this position in the stream.
10376 // Also used for marking up GC roots in heap snapshots.
10377 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10381 class StructBodyDescriptor : public
10382 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10384 static inline int SizeOf(Map* map, HeapObject* object);
10388 // BooleanBit is a helper class for setting and getting a bit in an
10390 class BooleanBit : public AllStatic {
10392 static inline bool get(Smi* smi, int bit_position) {
10393 return get(smi->value(), bit_position);
10396 static inline bool get(int value, int bit_position) {
10397 return (value & (1 << bit_position)) != 0;
10400 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10401 return Smi::FromInt(set(smi->value(), bit_position, v));
10404 static inline int set(int value, int bit_position, bool v) {
10406 value |= (1 << bit_position);
10408 value &= ~(1 << bit_position);
10414 } } // namespace v8::internal
10416 #endif // V8_OBJECTS_H_