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 and the
712 // NONCALLABLE_JS_OBJECT range.
713 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
714 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
715 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
716 JS_MESSAGE_OBJECT_TYPE,
719 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
720 JS_GENERATOR_OBJECT_TYPE,
722 JS_GLOBAL_OBJECT_TYPE,
723 JS_BUILTINS_OBJECT_TYPE,
724 JS_GLOBAL_PROXY_TYPE,
726 JS_ARRAY_BUFFER_TYPE,
731 JS_SET_ITERATOR_TYPE,
732 JS_MAP_ITERATOR_TYPE,
733 JS_ITERATOR_RESULT_TYPE,
737 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
741 LAST_TYPE = JS_FUNCTION_TYPE,
742 FIRST_NAME_TYPE = FIRST_TYPE,
743 LAST_NAME_TYPE = SYMBOL_TYPE,
744 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
745 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
746 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
747 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
748 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
749 // Boundaries for testing for a fixed typed array.
750 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
751 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
752 // Boundary for promotion to old space.
753 LAST_DATA_TYPE = FILLER_TYPE,
754 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
755 // Note that there is no range for JSObject or JSProxy, since their subtypes
756 // are not continuous in this enum! The enum ranges instead reflect the
757 // external class names, where proxies are treated as either ordinary objects,
759 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
760 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
761 // Boundaries for testing the types represented as JSObject
762 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
763 LAST_JS_OBJECT_TYPE = LAST_TYPE,
764 // Boundaries for testing the types represented as JSProxy
765 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
766 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
767 // Boundaries for testing whether the type is a JavaScript object.
768 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
769 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
770 // Boundaries for testing the types for which typeof is "object".
771 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
772 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
773 // Note that the types for which typeof is "function" are not continuous.
774 // Define this so that we can put assertions on discrete checks.
775 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
778 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
779 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
780 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
781 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
784 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
785 V(FAST_ELEMENTS_SUB_TYPE) \
786 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
787 V(FAST_PROPERTIES_SUB_TYPE) \
788 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
789 V(MAP_CODE_CACHE_SUB_TYPE) \
790 V(SCOPE_INFO_SUB_TYPE) \
791 V(STRING_TABLE_SUB_TYPE) \
792 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
793 V(TRANSITION_ARRAY_SUB_TYPE)
795 enum FixedArraySubInstanceType {
796 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
797 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
798 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
799 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
803 // TODO(bmeurer): Remove this in favor of the ComparisonResult below.
813 // Result of an abstract relational comparison of x and y, implemented according
814 // to ES6 section 7.2.11 Abstract Relational Comparison.
815 enum class ComparisonResult {
818 kGreaterThan, // x > y
819 kUndefined // at least one of x or y was undefined or NaN
823 #define DECL_BOOLEAN_ACCESSORS(name) \
824 inline bool name() const; \
825 inline void set_##name(bool value);
827 #define DECL_INT_ACCESSORS(name) \
828 inline int name() const; \
829 inline void set_##name(int value);
832 #define DECL_ACCESSORS(name, type) \
833 inline type* name() const; \
834 inline void set_##name(type* value, \
835 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
838 #define DECLARE_CAST(type) \
839 INLINE(static type* cast(Object* object)); \
840 INLINE(static const type* cast(const Object* object));
844 class AllocationSite;
845 class AllocationSiteCreationContext;
846 class AllocationSiteUsageContext;
849 class ElementsAccessor;
850 class FixedArrayBase;
851 class FunctionLiteral;
853 class JSBuiltinsObject;
854 class LayoutDescriptor;
855 class LookupIterator;
856 class ObjectHashTable;
859 class SafepointEntry;
860 class SharedFunctionInfo;
862 class TypeFeedbackInfo;
863 class TypeFeedbackVector;
866 // We cannot just say "class HeapType;" if it is created from a template... =8-?
867 template<class> class TypeImpl;
868 struct HeapTypeConfig;
869 typedef TypeImpl<HeapTypeConfig> HeapType;
872 // A template-ized version of the IsXXX functions.
873 template <class C> inline bool Is(Object* obj);
876 #define DECLARE_VERIFIER(Name) void Name##Verify();
878 #define DECLARE_VERIFIER(Name)
882 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
884 #define DECLARE_PRINTER(Name)
888 #define OBJECT_TYPE_LIST(V) \
893 #define HEAP_OBJECT_TYPE_LIST(V) \
895 V(MutableHeapNumber) \
914 V(ExternalTwoByteString) \
915 V(ExternalOneByteString) \
916 V(SeqTwoByteString) \
917 V(SeqOneByteString) \
918 V(InternalizedString) \
921 V(FixedTypedArrayBase) \
924 V(FixedUint16Array) \
926 V(FixedUint32Array) \
928 V(FixedFloat32Array) \
929 V(FixedFloat64Array) \
930 V(FixedUint8ClampedArray) \
936 V(JSContextExtensionObject) \
937 V(JSGeneratorObject) \
939 V(LayoutDescriptor) \
943 V(TypeFeedbackVector) \
944 V(DeoptimizationInputData) \
945 V(DeoptimizationOutputData) \
949 V(FixedDoubleArray) \
953 V(ScriptContextTable) \
959 V(SharedFunctionInfo) \
968 V(JSArrayBufferView) \
977 V(JSIteratorResult) \
978 V(JSWeakCollection) \
985 V(NormalizedMapCache) \
986 V(CompilationCacheTable) \
987 V(CodeCacheHashTable) \
988 V(PolymorphicCodeCacheHashTable) \
993 V(JSBuiltinsObject) \
995 V(UndetectableObject) \
996 V(AccessCheckNeeded) \
1000 V(ObjectHashTable) \
1004 // Object is the abstract superclass for all classes in the
1005 // object hierarchy.
1006 // Object does not use any virtual functions to avoid the
1007 // allocation of the C++ vtable.
1008 // Since both Smi and HeapObject are subclasses of Object no
1009 // data members can be present in Object.
1013 bool IsObject() const { return true; }
1015 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1016 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1017 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1018 #undef IS_TYPE_FUNCTION_DECL
1020 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1021 // a keyed store is of the form a[expression] = foo.
1022 enum StoreFromKeyed {
1023 MAY_BE_STORE_FROM_KEYED,
1024 CERTAINLY_NOT_STORE_FROM_KEYED
1027 INLINE(bool IsFixedArrayBase() const);
1028 INLINE(bool IsExternal() const);
1029 INLINE(bool IsAccessorInfo() const);
1031 INLINE(bool IsStruct() const);
1032 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1033 INLINE(bool Is##Name() const);
1034 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1035 #undef DECLARE_STRUCT_PREDICATE
1037 // ES6, section 7.2.3 IsCallable.
1038 INLINE(bool IsCallable() const);
1040 // ES6, section 7.2.4 IsConstructor.
1041 INLINE(bool IsConstructor() const);
1043 INLINE(bool IsSpecObject()) const;
1044 INLINE(bool IsTemplateInfo()) const;
1045 INLINE(bool IsNameDictionary() const);
1046 INLINE(bool IsGlobalDictionary() const);
1047 INLINE(bool IsSeededNumberDictionary() const);
1048 INLINE(bool IsUnseededNumberDictionary() const);
1049 INLINE(bool IsOrderedHashSet() const);
1050 INLINE(bool IsOrderedHashMap() const);
1051 static bool IsPromise(Handle<Object> object);
1054 INLINE(bool IsUndefined() const);
1055 INLINE(bool IsNull() const);
1056 INLINE(bool IsTheHole() const);
1057 INLINE(bool IsException() const);
1058 INLINE(bool IsUninitialized() const);
1059 INLINE(bool IsTrue() const);
1060 INLINE(bool IsFalse() const);
1061 INLINE(bool IsArgumentsMarker() const);
1063 // Filler objects (fillers and free space objects).
1064 INLINE(bool IsFiller() const);
1066 // Extract the number.
1067 inline double Number() const;
1068 INLINE(bool IsNaN() const);
1069 INLINE(bool IsMinusZero() const);
1070 bool ToInt32(int32_t* value);
1071 bool ToUint32(uint32_t* value);
1073 inline Representation OptimalRepresentation();
1075 inline ElementsKind OptimalElementsKind();
1077 inline bool FitsRepresentation(Representation representation);
1079 // Checks whether two valid primitive encodings of a property name resolve to
1080 // the same logical property. E.g., the smi 1, the string "1" and the double
1081 // 1 all refer to the same property, so this helper will return true.
1082 inline bool KeyEquals(Object* other);
1084 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1086 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1087 Handle<Object> object,
1088 Representation representation);
1090 inline static Handle<Object> WrapForRead(Isolate* isolate,
1091 Handle<Object> object,
1092 Representation representation);
1094 // Returns true if the object is of the correct type to be used as a
1095 // implementation of a JSObject's elements.
1096 inline bool HasValidElements();
1098 inline bool HasSpecificClassOf(String* name);
1100 bool BooleanValue(); // ECMA-262 9.2.
1102 // ES6 section 7.2.11 Abstract Relational Comparison
1103 MUST_USE_RESULT static Maybe<ComparisonResult> Compare(
1104 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1106 // ES6 section 7.2.12 Abstract Equality Comparison
1107 MUST_USE_RESULT static Maybe<bool> Equals(Handle<Object> x, Handle<Object> y);
1109 // ES6 section 7.2.13 Strict Equality Comparison
1110 bool StrictEquals(Object* that);
1112 // Convert to a JSObject if needed.
1113 // native_context is used when creating wrapper object.
1114 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1115 Handle<Object> object);
1116 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1117 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1119 // ES6 section 7.1.14 ToPropertyKey
1120 MUST_USE_RESULT static MaybeHandle<Name> ToName(Isolate* isolate,
1121 Handle<Object> input);
1123 // ES6 section 7.1.1 ToPrimitive
1124 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1125 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1127 // ES6 section 7.1.3 ToNumber
1128 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Handle<Object> input);
1130 // ES6 section 7.1.4 ToInteger
1131 MUST_USE_RESULT static MaybeHandle<Object> ToInteger(Isolate* isolate,
1132 Handle<Object> input);
1134 // ES6 section 7.1.5 ToInt32
1135 MUST_USE_RESULT static MaybeHandle<Object> ToInt32(Isolate* isolate,
1136 Handle<Object> input);
1138 // ES6 section 7.1.6 ToUint32
1139 MUST_USE_RESULT static MaybeHandle<Object> ToUint32(Isolate* isolate,
1140 Handle<Object> input);
1142 // ES6 section 7.1.12 ToString
1143 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1144 Handle<Object> input);
1146 // ES6 section 7.1.15 ToLength
1147 MUST_USE_RESULT static MaybeHandle<Object> ToLength(Isolate* isolate,
1148 Handle<Object> input);
1150 // ES6 section 7.3.9 GetMethod
1151 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1152 Handle<JSReceiver> receiver, Handle<Name> name);
1154 // ES6 section 12.5.6 The typeof Operator
1155 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1157 // ES6 section 12.6 Multiplicative Operators
1158 MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1159 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1160 Strength strength = Strength::WEAK);
1161 MUST_USE_RESULT static MaybeHandle<Object> Divide(
1162 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1163 Strength strength = Strength::WEAK);
1164 MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1165 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1166 Strength strength = Strength::WEAK);
1168 // ES6 section 12.7 Additive Operators
1169 MUST_USE_RESULT static MaybeHandle<Object> Add(
1170 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1171 Strength strength = Strength::WEAK);
1172 MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1173 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1174 Strength strength = Strength::WEAK);
1176 // ES6 section 12.8 Bitwise Shift Operators
1177 MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1178 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1179 Strength strength = Strength::WEAK);
1180 MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1181 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1182 Strength strength = Strength::WEAK);
1183 MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1184 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1185 Strength strength = Strength::WEAK);
1187 // ES6 section 12.9 Relational Operators
1188 MUST_USE_RESULT static inline Maybe<bool> GreaterThan(
1189 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1190 MUST_USE_RESULT static inline Maybe<bool> GreaterThanOrEqual(
1191 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1192 MUST_USE_RESULT static inline Maybe<bool> LessThan(
1193 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1194 MUST_USE_RESULT static inline Maybe<bool> LessThanOrEqual(
1195 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1197 // ES6 section 12.11 Binary Bitwise Operators
1198 MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1199 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1200 Strength strength = Strength::WEAK);
1201 MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1202 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1203 Strength strength = Strength::WEAK);
1204 MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1205 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1206 Strength strength = Strength::WEAK);
1208 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1209 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1211 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1212 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1213 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1214 LanguageMode language_mode,
1215 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1217 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1218 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1219 StoreFromKeyed store_mode);
1221 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1222 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1223 StoreFromKeyed store_mode);
1225 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1226 LookupIterator* it, LanguageMode language_mode);
1227 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1228 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1229 LanguageMode language_mode);
1230 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1231 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1232 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1233 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1234 Handle<Object> value, LanguageMode language_mode);
1235 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1236 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1237 LanguageMode language_mode);
1238 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1239 LookupIterator* it, Handle<Object> value);
1240 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1241 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1242 LanguageMode language_mode, StoreFromKeyed store_mode);
1243 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1244 Handle<Object> object, Handle<Name> name,
1245 LanguageMode language_mode = SLOPPY);
1246 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1247 Isolate* isolate, Handle<Object> object, const char* key,
1248 LanguageMode language_mode = SLOPPY);
1249 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1250 Handle<Object> object, Handle<Name> name,
1251 LanguageMode language_mode = SLOPPY);
1253 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1254 LookupIterator* it, LanguageMode language_mode);
1255 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1256 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1258 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1259 Handle<Object> receiver,
1260 Handle<JSReceiver> getter);
1261 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1262 Handle<Object> receiver,
1263 Handle<JSReceiver> setter,
1264 Handle<Object> value);
1266 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1267 Isolate* isolate, Handle<Object> object, uint32_t index,
1268 LanguageMode language_mode = SLOPPY);
1270 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1271 Isolate* isolate, Handle<Object> object, uint32_t index,
1272 Handle<Object> value, LanguageMode language_mode);
1274 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1275 Isolate* isolate, Handle<Object> receiver);
1277 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1279 // Returns the permanent hash code associated with this object. May return
1280 // undefined if not yet created.
1283 // Returns undefined for JSObjects, but returns the hash code for simple
1284 // objects. This avoids a double lookup in the cases where we know we will
1285 // add the hash to the JSObject if it does not already exist.
1286 Object* GetSimpleHash();
1288 // Returns the permanent hash code associated with this object depending on
1289 // the actual object type. May create and store a hash code if needed and none
1291 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1293 // Checks whether this object has the same value as the given one. This
1294 // function is implemented according to ES5, section 9.12 and can be used
1295 // to implement the Harmony "egal" function.
1296 bool SameValue(Object* other);
1298 // Checks whether this object has the same value as the given one.
1299 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1300 // This function is implemented according to ES6, section 7.2.4 and is used
1301 // by ES6 Map and Set.
1302 bool SameValueZero(Object* other);
1304 // Tries to convert an object to an array length. Returns true and sets the
1305 // output parameter if it succeeds.
1306 inline bool ToArrayLength(uint32_t* index);
1308 // Tries to convert an object to an array index. Returns true and sets the
1309 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1310 // allow kMaxUInt32.
1311 inline bool ToArrayIndex(uint32_t* index);
1313 // Returns true if this is a JSValue containing a string and the index is
1314 // < the length of the string. Used to implement [] on strings.
1315 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1317 DECLARE_VERIFIER(Object)
1319 // Verify a pointer is a valid object pointer.
1320 static void VerifyPointer(Object* p);
1323 inline void VerifyApiCallResultType();
1325 // Prints this object without details.
1326 void ShortPrint(FILE* out = stdout);
1328 // Prints this object without details to a message accumulator.
1329 void ShortPrint(StringStream* accumulator);
1331 void ShortPrint(std::ostream& os); // NOLINT
1333 DECLARE_CAST(Object)
1335 // Layout description.
1336 static const int kHeaderSize = 0; // Object does not take up any space.
1339 // For our gdb macros, we should perhaps change these in the future.
1342 // Prints this object with details.
1343 void Print(std::ostream& os); // NOLINT
1345 void Print() { ShortPrint(); }
1346 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1350 friend class LookupIterator;
1351 friend class PrototypeIterator;
1353 // Return the map of the root of object's prototype chain.
1354 Map* GetRootMap(Isolate* isolate);
1356 // Helper for SetProperty and SetSuperProperty.
1357 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1358 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1359 StoreFromKeyed store_mode, bool* found);
1361 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1365 // In objects.h to be usable without objects-inl.h inclusion.
1366 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1367 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1371 explicit Brief(const Object* const v) : value(v) {}
1372 const Object* value;
1376 std::ostream& operator<<(std::ostream& os, const Brief& v);
1379 // Smi represents integer Numbers that can be stored in 31 bits.
1380 // Smis are immediate which means they are NOT allocated in the heap.
1381 // The this pointer has the following format: [31 bit signed int] 0
1382 // For long smis it has the following format:
1383 // [32 bit signed int] [31 bits zero padding] 0
1384 // Smi stands for small integer.
1385 class Smi: public Object {
1387 // Returns the integer value.
1388 inline int value() const { return Internals::SmiValue(this); }
1390 // Convert a value to a Smi object.
1391 static inline Smi* FromInt(int value) {
1392 DCHECK(Smi::IsValid(value));
1393 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1396 static inline Smi* FromIntptr(intptr_t value) {
1397 DCHECK(Smi::IsValid(value));
1398 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1399 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1402 // Returns whether value can be represented in a Smi.
1403 static inline bool IsValid(intptr_t value) {
1404 bool result = Internals::IsValidSmi(value);
1405 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1411 // Dispatched behavior.
1412 void SmiPrint(std::ostream& os) const; // NOLINT
1413 DECLARE_VERIFIER(Smi)
1415 static const int kMinValue =
1416 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1417 static const int kMaxValue = -(kMinValue + 1);
1420 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1424 // Heap objects typically have a map pointer in their first word. However,
1425 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1426 // encoded in the first word. The class MapWord is an abstraction of the
1427 // value in a heap object's first word.
1428 class MapWord BASE_EMBEDDED {
1430 // Normal state: the map word contains a map pointer.
1432 // Create a map word from a map pointer.
1433 static inline MapWord FromMap(const Map* map);
1435 // View this map word as a map pointer.
1436 inline Map* ToMap();
1439 // Scavenge collection: the map word of live objects in the from space
1440 // contains a forwarding address (a heap object pointer in the to space).
1442 // True if this map word is a forwarding address for a scavenge
1443 // collection. Only valid during a scavenge collection (specifically,
1444 // when all map words are heap object pointers, i.e. not during a full GC).
1445 inline bool IsForwardingAddress();
1447 // Create a map word from a forwarding address.
1448 static inline MapWord FromForwardingAddress(HeapObject* object);
1450 // View this map word as a forwarding address.
1451 inline HeapObject* ToForwardingAddress();
1453 static inline MapWord FromRawValue(uintptr_t value) {
1454 return MapWord(value);
1457 inline uintptr_t ToRawValue() {
1462 // HeapObject calls the private constructor and directly reads the value.
1463 friend class HeapObject;
1465 explicit MapWord(uintptr_t value) : value_(value) {}
1471 // The content of an heap object (except for the map pointer). kTaggedValues
1472 // objects can contain both heap pointers and Smis, kMixedValues can contain
1473 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1474 // objects can contain raw values and Smis.
1475 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1478 // HeapObject is the superclass for all classes describing heap allocated
1480 class HeapObject: public Object {
1482 // [map]: Contains a map which contains the object's reflective
1484 inline Map* map() const;
1485 inline void set_map(Map* value);
1486 // The no-write-barrier version. This is OK if the object is white and in
1487 // new space, or if the value is an immortal immutable object, like the maps
1488 // of primitive (non-JS) objects like strings, heap numbers etc.
1489 inline void set_map_no_write_barrier(Map* value);
1491 // Get the map using acquire load.
1492 inline Map* synchronized_map();
1493 inline MapWord synchronized_map_word() const;
1495 // Set the map using release store
1496 inline void synchronized_set_map(Map* value);
1497 inline void synchronized_set_map_no_write_barrier(Map* value);
1498 inline void synchronized_set_map_word(MapWord map_word);
1500 // During garbage collection, the map word of a heap object does not
1501 // necessarily contain a map pointer.
1502 inline MapWord map_word() const;
1503 inline void set_map_word(MapWord map_word);
1505 // The Heap the object was allocated in. Used also to access Isolate.
1506 inline Heap* GetHeap() const;
1508 // Convenience method to get current isolate.
1509 inline Isolate* GetIsolate() const;
1511 // Converts an address to a HeapObject pointer.
1512 static inline HeapObject* FromAddress(Address address) {
1513 DCHECK_TAG_ALIGNED(address);
1514 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1517 // Returns the address of this HeapObject.
1518 inline Address address() {
1519 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1522 // Iterates over pointers contained in the object (including the Map)
1523 void Iterate(ObjectVisitor* v);
1525 // Iterates over all pointers contained in the object except the
1526 // first map pointer. The object type is given in the first
1527 // parameter. This function does not access the map pointer in the
1528 // object, and so is safe to call while the map pointer is modified.
1529 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1531 // Returns the heap object's size in bytes
1534 // Indicates what type of values this heap object may contain.
1535 inline HeapObjectContents ContentType();
1537 // Given a heap object's map pointer, returns the heap size in bytes
1538 // Useful when the map pointer field is used for other purposes.
1540 inline int SizeFromMap(Map* map);
1542 // Returns the field at offset in obj, as a read/write Object* reference.
1543 // Does no checking, and is safe to use during GC, while maps are invalid.
1544 // Does not invoke write barrier, so should only be assigned to
1545 // during marking GC.
1546 static inline Object** RawField(HeapObject* obj, int offset);
1548 // Adds the |code| object related to |name| to the code cache of this map. If
1549 // this map is a dictionary map that is shared, the map copied and installed
1551 static void UpdateMapCodeCache(Handle<HeapObject> object,
1555 DECLARE_CAST(HeapObject)
1557 // Return the write barrier mode for this. Callers of this function
1558 // must be able to present a reference to an DisallowHeapAllocation
1559 // object as a sign that they are not going to use this function
1560 // from code that allocates and thus invalidates the returned write
1562 inline WriteBarrierMode GetWriteBarrierMode(
1563 const DisallowHeapAllocation& promise);
1565 // Dispatched behavior.
1566 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1568 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1570 DECLARE_PRINTER(HeapObject)
1571 DECLARE_VERIFIER(HeapObject)
1573 inline void VerifyObjectField(int offset);
1574 inline void VerifySmiField(int offset);
1576 // Verify a pointer is a valid HeapObject pointer that points to object
1577 // areas in the heap.
1578 static void VerifyHeapPointer(Object* p);
1581 inline AllocationAlignment RequiredAlignment();
1583 // Layout description.
1584 // First field in a heap object is map.
1585 static const int kMapOffset = Object::kHeaderSize;
1586 static const int kHeaderSize = kMapOffset + kPointerSize;
1588 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1591 // helpers for calling an ObjectVisitor to iterate over pointers in the
1592 // half-open range [start, end) specified as integer offsets
1593 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1594 // as above, for the single element at "offset"
1595 inline void IteratePointer(ObjectVisitor* v, int offset);
1596 // as above, for the next code link of a code object.
1597 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1600 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1604 // This class describes a body of an object of a fixed size
1605 // in which all pointer fields are located in the [start_offset, end_offset)
1607 template<int start_offset, int end_offset, int size>
1608 class FixedBodyDescriptor {
1610 static const int kStartOffset = start_offset;
1611 static const int kEndOffset = end_offset;
1612 static const int kSize = size;
1614 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1616 template<typename StaticVisitor>
1617 static inline void IterateBody(HeapObject* obj) {
1618 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1619 HeapObject::RawField(obj, end_offset));
1624 // This class describes a body of an object of a variable size
1625 // in which all pointer fields are located in the [start_offset, object_size)
1627 template<int start_offset>
1628 class FlexibleBodyDescriptor {
1630 static const int kStartOffset = start_offset;
1632 static inline void IterateBody(HeapObject* obj,
1636 template<typename StaticVisitor>
1637 static inline void IterateBody(HeapObject* obj, int object_size) {
1638 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1639 HeapObject::RawField(obj, object_size));
1644 // The HeapNumber class describes heap allocated numbers that cannot be
1645 // represented in a Smi (small integer)
1646 class HeapNumber: public HeapObject {
1648 // [value]: number value.
1649 inline double value() const;
1650 inline void set_value(double value);
1652 DECLARE_CAST(HeapNumber)
1654 // Dispatched behavior.
1655 bool HeapNumberBooleanValue();
1657 void HeapNumberPrint(std::ostream& os); // NOLINT
1658 DECLARE_VERIFIER(HeapNumber)
1660 inline int get_exponent();
1661 inline int get_sign();
1663 // Layout description.
1664 static const int kValueOffset = HeapObject::kHeaderSize;
1665 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1666 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1667 // words within double numbers are endian dependent and they are set
1669 #if defined(V8_TARGET_LITTLE_ENDIAN)
1670 static const int kMantissaOffset = kValueOffset;
1671 static const int kExponentOffset = kValueOffset + 4;
1672 #elif defined(V8_TARGET_BIG_ENDIAN)
1673 static const int kMantissaOffset = kValueOffset + 4;
1674 static const int kExponentOffset = kValueOffset;
1676 #error Unknown byte ordering
1679 static const int kSize = kValueOffset + kDoubleSize;
1680 static const uint32_t kSignMask = 0x80000000u;
1681 static const uint32_t kExponentMask = 0x7ff00000u;
1682 static const uint32_t kMantissaMask = 0xfffffu;
1683 static const int kMantissaBits = 52;
1684 static const int kExponentBits = 11;
1685 static const int kExponentBias = 1023;
1686 static const int kExponentShift = 20;
1687 static const int kInfinityOrNanExponent =
1688 (kExponentMask >> kExponentShift) - kExponentBias;
1689 static const int kMantissaBitsInTopWord = 20;
1690 static const int kNonMantissaBitsInTopWord = 12;
1693 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1697 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1698 class Simd128Value : public HeapObject {
1700 DECLARE_CAST(Simd128Value)
1702 DECLARE_PRINTER(Simd128Value)
1703 DECLARE_VERIFIER(Simd128Value)
1705 static Handle<String> ToString(Handle<Simd128Value> input);
1707 // Equality operations.
1708 inline bool Equals(Simd128Value* that);
1709 static inline bool Equals(Handle<Simd128Value> one, Handle<Simd128Value> two);
1711 // Checks that another instance is bit-wise equal.
1712 bool BitwiseEquals(const Simd128Value* other) const;
1713 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1714 uint32_t Hash() const;
1715 // Copies the 16 bytes of SIMD data to the destination address.
1716 void CopyBits(void* destination) const;
1718 // Layout description.
1719 static const int kValueOffset = HeapObject::kHeaderSize;
1720 static const int kSize = kValueOffset + kSimd128Size;
1723 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1727 // V has parameters (TYPE, Type, type, lane count, lane type)
1728 #define SIMD128_TYPES(V) \
1729 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1730 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1731 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1732 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1733 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1734 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1735 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1736 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1737 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1738 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1740 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1741 class Type final : public Simd128Value { \
1743 inline lane_type get_lane(int lane) const; \
1744 inline void set_lane(int lane, lane_type value); \
1746 DECLARE_CAST(Type) \
1748 DECLARE_PRINTER(Type) \
1750 static Handle<String> ToString(Handle<Type> input); \
1752 inline bool Equals(Type* that); \
1755 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1757 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1758 #undef SIMD128_VALUE_CLASS
1761 enum EnsureElementsMode {
1762 DONT_ALLOW_DOUBLE_ELEMENTS,
1763 ALLOW_COPIED_DOUBLE_ELEMENTS,
1764 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1768 // Indicator for one component of an AccessorPair.
1769 enum AccessorComponent {
1775 // JSReceiver includes types on which properties can be defined, i.e.,
1776 // JSObject and JSProxy.
1777 class JSReceiver: public HeapObject {
1779 DECLARE_CAST(JSReceiver)
1781 // ES6 section 7.1.1 ToPrimitive
1782 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1783 Handle<JSReceiver> receiver,
1784 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1785 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1786 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1788 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1789 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1790 Handle<JSReceiver> object, Handle<Name> name);
1791 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1793 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1794 Handle<JSReceiver> object, uint32_t index);
1795 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1796 Handle<JSReceiver> object, uint32_t index);
1798 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1799 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1800 Handle<JSReceiver> object, Handle<Name> name,
1801 LanguageMode language_mode = SLOPPY);
1802 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1803 Handle<JSReceiver> object, Handle<Name> name,
1804 LanguageMode language_mode = SLOPPY);
1805 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1806 LookupIterator* it, LanguageMode language_mode);
1807 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1808 Handle<JSReceiver> object, uint32_t index,
1809 LanguageMode language_mode = SLOPPY);
1811 // Tests for the fast common case for property enumeration.
1812 bool IsSimpleEnum();
1814 // Returns the class name ([[Class]] property in the specification).
1815 String* class_name();
1817 // Returns the constructor name (the name (possibly, inferred name) of the
1818 // function that was used to instantiate the object).
1819 String* constructor_name();
1821 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1822 Handle<JSReceiver> object, Handle<Name> name);
1823 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1824 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1826 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1827 Handle<JSReceiver> object, uint32_t index);
1828 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1829 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1831 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1832 LookupIterator* it);
1835 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1837 static Handle<Object> GetDataProperty(LookupIterator* it);
1840 // Retrieves a permanent object identity hash code. The undefined value might
1841 // be returned in case no hash was created yet.
1842 inline Object* GetIdentityHash();
1844 // Retrieves a permanent object identity hash code. May create and store a
1845 // hash code if needed and none exists.
1846 inline static Handle<Smi> GetOrCreateIdentityHash(
1847 Handle<JSReceiver> object);
1849 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1851 // Computes the enumerable keys for a JSObject. Used for implementing
1852 // "for (n in object) { }".
1853 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1854 Handle<JSReceiver> object,
1855 KeyCollectionType type);
1858 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1862 // The JSObject describes real heap allocated JavaScript objects with
1864 // Note that the map of JSObject changes during execution to enable inline
1866 class JSObject: public JSReceiver {
1868 // [properties]: Backing storage for properties.
1869 // properties is a FixedArray in the fast case and a Dictionary in the
1871 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1872 inline void initialize_properties();
1873 inline bool HasFastProperties();
1874 // Gets slow properties for non-global objects.
1875 inline NameDictionary* property_dictionary();
1876 // Gets global object properties.
1877 inline GlobalDictionary* global_dictionary();
1879 // [elements]: The elements (properties with names that are integers).
1881 // Elements can be in two general modes: fast and slow. Each mode
1882 // corrensponds to a set of object representations of elements that
1883 // have something in common.
1885 // In the fast mode elements is a FixedArray and so each element can
1886 // be quickly accessed. This fact is used in the generated code. The
1887 // elements array can have one of three maps in this mode:
1888 // fixed_array_map, sloppy_arguments_elements_map or
1889 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1890 // the elements array may be shared by a few objects and so before
1891 // writing to any element the array must be copied. Use
1892 // EnsureWritableFastElements in this case.
1894 // In the slow mode the elements is either a NumberDictionary, a
1895 // FixedArray parameter map for a (sloppy) arguments object.
1896 DECL_ACCESSORS(elements, FixedArrayBase)
1897 inline void initialize_elements();
1898 static void ResetElements(Handle<JSObject> object);
1899 static inline void SetMapAndElements(Handle<JSObject> object,
1901 Handle<FixedArrayBase> elements);
1902 inline ElementsKind GetElementsKind();
1903 ElementsAccessor* GetElementsAccessor();
1904 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1905 inline bool HasFastSmiElements();
1906 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1907 inline bool HasFastObjectElements();
1908 // Returns true if an object has elements of FAST_ELEMENTS or
1909 // FAST_SMI_ONLY_ELEMENTS.
1910 inline bool HasFastSmiOrObjectElements();
1911 // Returns true if an object has any of the fast elements kinds.
1912 inline bool HasFastElements();
1913 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1915 inline bool HasFastDoubleElements();
1916 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1918 inline bool HasFastHoleyElements();
1919 inline bool HasSloppyArgumentsElements();
1920 inline bool HasDictionaryElements();
1922 inline bool HasFixedTypedArrayElements();
1924 inline bool HasFixedUint8ClampedElements();
1925 inline bool HasFixedArrayElements();
1926 inline bool HasFixedInt8Elements();
1927 inline bool HasFixedUint8Elements();
1928 inline bool HasFixedInt16Elements();
1929 inline bool HasFixedUint16Elements();
1930 inline bool HasFixedInt32Elements();
1931 inline bool HasFixedUint32Elements();
1932 inline bool HasFixedFloat32Elements();
1933 inline bool HasFixedFloat64Elements();
1935 inline bool HasFastArgumentsElements();
1936 inline bool HasSlowArgumentsElements();
1937 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1939 // Requires: HasFastElements().
1940 static Handle<FixedArray> EnsureWritableFastElements(
1941 Handle<JSObject> object);
1943 // Collects elements starting at index 0.
1944 // Undefined values are placed after non-undefined values.
1945 // Returns the number of non-undefined values.
1946 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1948 // As PrepareElementsForSort, but only on objects where elements is
1949 // a dictionary, and it will stay a dictionary. Collates undefined and
1950 // unexisting elements below limit from position zero of the elements.
1951 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1954 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1955 LookupIterator* it, Handle<Object> value);
1957 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1958 // grant an exemption to ExecutableAccessor callbacks in some cases.
1959 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1961 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1962 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1963 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1965 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1966 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1967 PropertyAttributes attributes,
1968 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1970 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1971 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1972 PropertyAttributes attributes,
1973 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1975 // Equivalent to one of the above depending on whether |name| can be converted
1976 // to an array index.
1977 MUST_USE_RESULT static MaybeHandle<Object>
1978 DefinePropertyOrElementIgnoreAttributes(
1979 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1980 PropertyAttributes attributes = NONE,
1981 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1983 // Adds or reconfigures a property to attributes NONE. It will fail when it
1985 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1986 Handle<Object> value);
1988 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1989 Handle<Object> value, PropertyAttributes attributes);
1991 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1992 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1993 PropertyAttributes attributes);
1995 // Extend the receiver with a single fast property appeared first in the
1996 // passed map. This also extends the property backing store if necessary.
1997 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1999 // Migrates the given object to a map whose field representations are the
2000 // lowest upper bound of all known representations for that field.
2001 static void MigrateInstance(Handle<JSObject> instance);
2003 // Migrates the given object only if the target map is already available,
2004 // or returns false if such a map is not yet available.
2005 static bool TryMigrateInstance(Handle<JSObject> instance);
2007 // Sets the property value in a normalized object given (key, value, details).
2008 // Handles the special representation of JS global objects.
2009 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
2010 Handle<Object> value,
2011 PropertyDetails details);
2012 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
2013 Handle<Object> value,
2014 PropertyAttributes attributes);
2015 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
2017 Handle<Object> value,
2018 PropertyAttributes attributes);
2020 static void OptimizeAsPrototype(Handle<JSObject> object,
2021 PrototypeOptimizationMode mode);
2022 static void ReoptimizeIfPrototype(Handle<JSObject> object);
2023 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2024 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2025 static void InvalidatePrototypeChains(Map* map);
2027 // Alternative implementation of WeakFixedArray::NullCallback.
2028 class PrototypeRegistryCompactionCallback {
2030 static void Callback(Object* value, int old_index, int new_index);
2033 // Retrieve interceptors.
2034 InterceptorInfo* GetNamedInterceptor();
2035 InterceptorInfo* GetIndexedInterceptor();
2037 // Used from JSReceiver.
2038 MUST_USE_RESULT static Maybe<PropertyAttributes>
2039 GetPropertyAttributesWithInterceptor(LookupIterator* it);
2040 MUST_USE_RESULT static Maybe<PropertyAttributes>
2041 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
2043 // Retrieves an AccessorPair property from the given object. Might return
2044 // undefined if the property doesn't exist or is of a different kind.
2045 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
2046 Handle<JSObject> object,
2048 AccessorComponent component);
2050 // Defines an AccessorPair property on the given object.
2051 // TODO(mstarzinger): Rename to SetAccessor().
2052 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2054 Handle<Object> getter,
2055 Handle<Object> setter,
2056 PropertyAttributes attributes);
2058 // Defines an AccessorInfo property on the given object.
2059 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2060 Handle<JSObject> object,
2061 Handle<AccessorInfo> info);
2063 // The result must be checked first for exceptions. If there's no exception,
2064 // the output parameter |done| indicates whether the interceptor has a result
2066 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2067 LookupIterator* it, bool* done);
2069 // Accessors for hidden properties object.
2071 // Hidden properties are not own properties of the object itself.
2072 // Instead they are stored in an auxiliary structure kept as an own
2073 // property with a special name Heap::hidden_string(). But if the
2074 // receiver is a JSGlobalProxy then the auxiliary object is a property
2075 // of its prototype, and if it's a detached proxy, then you can't have
2076 // hidden properties.
2078 // Sets a hidden property on this object. Returns this object if successful,
2079 // undefined if called on a detached proxy.
2080 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2082 Handle<Object> value);
2083 // Gets the value of a hidden property with the given key. Returns the hole
2084 // if the property doesn't exist (or if called on a detached proxy),
2085 // otherwise returns the value set for the key.
2086 Object* GetHiddenProperty(Handle<Name> key);
2087 // Deletes a hidden property. Deleting a non-existing property is
2088 // considered successful.
2089 static void DeleteHiddenProperty(Handle<JSObject> object,
2091 // Returns true if the object has a property with the hidden string as name.
2092 static bool HasHiddenProperties(Handle<JSObject> object);
2094 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2096 static void ValidateElements(Handle<JSObject> object);
2098 // Makes sure that this object can contain HeapObject as elements.
2099 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2101 // Makes sure that this object can contain the specified elements.
2102 static inline void EnsureCanContainElements(
2103 Handle<JSObject> object,
2106 EnsureElementsMode mode);
2107 static inline void EnsureCanContainElements(
2108 Handle<JSObject> object,
2109 Handle<FixedArrayBase> elements,
2111 EnsureElementsMode mode);
2112 static void EnsureCanContainElements(
2113 Handle<JSObject> object,
2114 Arguments* arguments,
2117 EnsureElementsMode mode);
2119 // Would we convert a fast elements array to dictionary mode given
2120 // an access at key?
2121 bool WouldConvertToSlowElements(uint32_t index);
2123 // Computes the new capacity when expanding the elements of a JSObject.
2124 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2125 // (old_capacity + 50%) + 16
2126 return old_capacity + (old_capacity >> 1) + 16;
2129 // These methods do not perform access checks!
2130 static void UpdateAllocationSite(Handle<JSObject> object,
2131 ElementsKind to_kind);
2133 // Lookup interceptors are used for handling properties controlled by host
2135 inline bool HasNamedInterceptor();
2136 inline bool HasIndexedInterceptor();
2138 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2139 // by JSReceiver::GetKeys.
2140 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2141 Handle<JSObject> object,
2142 Handle<JSReceiver> receiver);
2143 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2144 Handle<JSObject> object,
2145 Handle<JSReceiver> receiver);
2147 // Support functions for v8 api (needed for correct interceptor behavior).
2148 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2149 Handle<JSObject> object, Handle<Name> name);
2150 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2151 Handle<JSObject> object, uint32_t index);
2152 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2153 Handle<JSObject> object, Handle<Name> name);
2155 // Get the header size for a JSObject. Used to compute the index of
2156 // internal fields as well as the number of internal fields.
2157 inline int GetHeaderSize();
2159 inline int GetInternalFieldCount();
2160 inline int GetInternalFieldOffset(int index);
2161 inline Object* GetInternalField(int index);
2162 inline void SetInternalField(int index, Object* value);
2163 inline void SetInternalField(int index, Smi* value);
2165 // Returns the number of properties on this object filtering out properties
2166 // with the specified attributes (ignoring interceptors).
2167 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2168 // Fill in details for properties into storage starting at the specified
2169 // index. Returns the number of properties added.
2170 int GetOwnPropertyNames(FixedArray* storage, int index,
2171 PropertyAttributes filter = NONE);
2173 // Returns the number of properties on this object filtering out properties
2174 // with the specified attributes (ignoring interceptors).
2175 int NumberOfOwnElements(PropertyAttributes filter);
2176 // Returns the number of enumerable elements (ignoring interceptors).
2177 int NumberOfEnumElements();
2178 // Returns the number of elements on this object filtering out elements
2179 // with the specified attributes (ignoring interceptors).
2180 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2181 // Count and fill in the enumerable elements into storage.
2182 // (storage->length() == NumberOfEnumElements()).
2183 // If storage is NULL, will count the elements without adding
2184 // them to any storage.
2185 // Returns the number of enumerable elements.
2186 int GetEnumElementKeys(FixedArray* storage);
2188 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2191 // Returns a new map with all transitions dropped from the object's current
2192 // map and the ElementsKind set.
2193 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2194 ElementsKind to_kind);
2195 static void TransitionElementsKind(Handle<JSObject> object,
2196 ElementsKind to_kind);
2198 // Always use this to migrate an object to a new map.
2199 // |expected_additional_properties| is only used for fast-to-slow transitions
2200 // and ignored otherwise.
2201 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2202 int expected_additional_properties = 0);
2204 // Convert the object to use the canonical dictionary
2205 // representation. If the object is expected to have additional properties
2206 // added this number can be indicated to have the backing store allocated to
2207 // an initial capacity for holding these properties.
2208 static void NormalizeProperties(Handle<JSObject> object,
2209 PropertyNormalizationMode mode,
2210 int expected_additional_properties,
2211 const char* reason);
2213 // Convert and update the elements backing store to be a
2214 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2215 static Handle<SeededNumberDictionary> NormalizeElements(
2216 Handle<JSObject> object);
2218 void RequireSlowElements(SeededNumberDictionary* dictionary);
2220 // Transform slow named properties to fast variants.
2221 static void MigrateSlowToFast(Handle<JSObject> object,
2222 int unused_property_fields, const char* reason);
2224 inline bool IsUnboxedDoubleField(FieldIndex index);
2226 // Access fast-case object properties at index.
2227 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2228 Representation representation,
2230 inline Object* RawFastPropertyAt(FieldIndex index);
2231 inline double RawFastDoublePropertyAt(FieldIndex index);
2233 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2234 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2235 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2236 inline void WriteToField(int descriptor, Object* value);
2238 // Access to in object properties.
2239 inline int GetInObjectPropertyOffset(int index);
2240 inline Object* InObjectPropertyAt(int index);
2241 inline Object* InObjectPropertyAtPut(int index,
2243 WriteBarrierMode mode
2244 = UPDATE_WRITE_BARRIER);
2246 // Set the object's prototype (only JSReceiver and null are allowed values).
2247 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2248 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2250 // Initializes the body after properties slot, properties slot is
2251 // initialized by set_properties. Fill the pre-allocated fields with
2252 // pre_allocated_value and the rest with filler_value.
2253 // Note: this call does not update write barrier, the caller is responsible
2254 // to ensure that |filler_value| can be collected without WB here.
2255 inline void InitializeBody(Map* map,
2256 Object* pre_allocated_value,
2257 Object* filler_value);
2259 // Check whether this object references another object
2260 bool ReferencesObject(Object* obj);
2262 // Disalow further properties to be added to the oject.
2263 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2264 Handle<JSObject> object);
2266 bool IsExtensible();
2269 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2271 // ES5 Object.freeze
2272 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2274 // Called the first time an object is observed with ES7 Object.observe.
2275 static void SetObserved(Handle<JSObject> object);
2278 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2280 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2281 Handle<JSObject> object,
2282 AllocationSiteUsageContext* site_context,
2283 DeepCopyHints hints = kNoHints);
2284 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2285 Handle<JSObject> object,
2286 AllocationSiteCreationContext* site_context);
2288 DECLARE_CAST(JSObject)
2290 // Dispatched behavior.
2291 void JSObjectShortPrint(StringStream* accumulator);
2292 DECLARE_PRINTER(JSObject)
2293 DECLARE_VERIFIER(JSObject)
2295 void PrintProperties(std::ostream& os); // NOLINT
2296 void PrintElements(std::ostream& os); // NOLINT
2298 #if defined(DEBUG) || defined(OBJECT_PRINT)
2299 void PrintTransitions(std::ostream& os); // NOLINT
2302 static void PrintElementsTransition(
2303 FILE* file, Handle<JSObject> object,
2304 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2305 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2307 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2310 // Structure for collecting spill information about JSObjects.
2311 class SpillInformation {
2315 int number_of_objects_;
2316 int number_of_objects_with_fast_properties_;
2317 int number_of_objects_with_fast_elements_;
2318 int number_of_fast_used_fields_;
2319 int number_of_fast_unused_fields_;
2320 int number_of_slow_used_properties_;
2321 int number_of_slow_unused_properties_;
2322 int number_of_fast_used_elements_;
2323 int number_of_fast_unused_elements_;
2324 int number_of_slow_used_elements_;
2325 int number_of_slow_unused_elements_;
2328 void IncrementSpillStatistics(SpillInformation* info);
2332 // If a GC was caused while constructing this object, the elements pointer
2333 // may point to a one pointer filler map. The object won't be rooted, but
2334 // our heap verification code could stumble across it.
2335 bool ElementsAreSafeToExamine();
2338 Object* SlowReverseLookup(Object* value);
2340 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2341 // Also maximal value of JSArray's length property.
2342 static const uint32_t kMaxElementCount = 0xffffffffu;
2344 // Constants for heuristics controlling conversion of fast elements
2345 // to slow elements.
2347 // Maximal gap that can be introduced by adding an element beyond
2348 // the current elements length.
2349 static const uint32_t kMaxGap = 1024;
2351 // Maximal length of fast elements array that won't be checked for
2352 // being dense enough on expansion.
2353 static const int kMaxUncheckedFastElementsLength = 5000;
2355 // Same as above but for old arrays. This limit is more strict. We
2356 // don't want to be wasteful with long lived objects.
2357 static const int kMaxUncheckedOldFastElementsLength = 500;
2359 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2360 // permissible values (see the DCHECK in heap.cc).
2361 static const int kInitialMaxFastElementArray = 100000;
2363 // This constant applies only to the initial map of "global.Object" and
2364 // not to arbitrary other JSObject maps.
2365 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2367 static const int kMaxInstanceSize = 255 * kPointerSize;
2368 // When extending the backing storage for property values, we increase
2369 // its size by more than the 1 entry necessary, so sequentially adding fields
2370 // to the same object requires fewer allocations and copies.
2371 static const int kFieldsAdded = 3;
2373 // Layout description.
2374 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2375 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2376 static const int kHeaderSize = kElementsOffset + kPointerSize;
2378 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2380 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2382 static inline int SizeOf(Map* map, HeapObject* object);
2385 Context* GetCreationContext();
2387 // Enqueue change record for Object.observe. May cause GC.
2388 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2389 Handle<JSObject> object, const char* type, Handle<Name> name,
2390 Handle<Object> old_value);
2392 // Gets the number of currently used elements.
2393 int GetFastElementsUsage();
2395 // Deletes an existing named property in a normalized object.
2396 static void DeleteNormalizedProperty(Handle<JSObject> object,
2397 Handle<Name> name, int entry);
2399 static bool AllCanRead(LookupIterator* it);
2400 static bool AllCanWrite(LookupIterator* it);
2403 friend class JSReceiver;
2404 friend class Object;
2406 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2407 static void MigrateFastToSlow(Handle<JSObject> object,
2408 Handle<Map> new_map,
2409 int expected_additional_properties);
2411 // Used from Object::GetProperty().
2412 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2413 LookupIterator* it);
2415 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2416 LookupIterator* it, Handle<Object> value);
2418 // Add a property to a slow-case object.
2419 static void AddSlowProperty(Handle<JSObject> object,
2421 Handle<Object> value,
2422 PropertyAttributes attributes);
2424 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2425 LookupIterator* it);
2427 bool ReferencesObjectFromElements(FixedArray* elements,
2431 // Return the hash table backing store or the inline stored identity hash,
2432 // whatever is found.
2433 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2435 // Return the hash table backing store for hidden properties. If there is no
2436 // backing store, allocate one.
2437 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2438 Handle<JSObject> object);
2440 // Set the hidden property backing store to either a hash table or
2441 // the inline-stored identity hash.
2442 static Handle<Object> SetHiddenPropertiesHashTable(
2443 Handle<JSObject> object,
2444 Handle<Object> value);
2446 MUST_USE_RESULT Object* GetIdentityHash();
2448 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2450 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2451 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2453 // Helper for fast versions of preventExtensions, seal, and freeze.
2454 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2455 template <PropertyAttributes attrs>
2456 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2457 Handle<JSObject> object);
2459 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2463 // Common superclass for FixedArrays that allow implementations to share
2464 // common accessors and some code paths.
2465 class FixedArrayBase: public HeapObject {
2467 // [length]: length of the array.
2468 inline int length() const;
2469 inline void set_length(int value);
2471 // Get and set the length using acquire loads and release stores.
2472 inline int synchronized_length() const;
2473 inline void synchronized_set_length(int value);
2475 DECLARE_CAST(FixedArrayBase)
2477 // Layout description.
2478 // Length is smi tagged when it is stored.
2479 static const int kLengthOffset = HeapObject::kHeaderSize;
2480 static const int kHeaderSize = kLengthOffset + kPointerSize;
2484 class FixedDoubleArray;
2485 class IncrementalMarking;
2488 // FixedArray describes fixed-sized arrays with element type Object*.
2489 class FixedArray: public FixedArrayBase {
2491 // Setter and getter for elements.
2492 inline Object* get(int index) const;
2493 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2494 // Setter that uses write barrier.
2495 inline void set(int index, Object* value);
2496 inline bool is_the_hole(int index);
2498 // Setter that doesn't need write barrier.
2499 inline void set(int index, Smi* value);
2500 // Setter with explicit barrier mode.
2501 inline void set(int index, Object* value, WriteBarrierMode mode);
2503 // Setters for frequently used oddballs located in old space.
2504 inline void set_undefined(int index);
2505 inline void set_null(int index);
2506 inline void set_the_hole(int index);
2508 inline Object** GetFirstElementAddress();
2509 inline bool ContainsOnlySmisOrHoles();
2511 // Gives access to raw memory which stores the array's data.
2512 inline Object** data_start();
2514 inline void FillWithHoles(int from, int to);
2516 // Shrink length and insert filler objects.
2517 void Shrink(int length);
2519 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2521 // Copy a sub array from the receiver to dest.
2522 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2524 // Garbage collection support.
2525 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2527 // Code Generation support.
2528 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2530 // Garbage collection support.
2531 inline Object** RawFieldOfElementAt(int index);
2533 DECLARE_CAST(FixedArray)
2535 // Maximal allowed size, in bytes, of a single FixedArray.
2536 // Prevents overflowing size computations, as well as extreme memory
2538 static const int kMaxSize = 128 * MB * kPointerSize;
2539 // Maximally allowed length of a FixedArray.
2540 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2542 // Dispatched behavior.
2543 DECLARE_PRINTER(FixedArray)
2544 DECLARE_VERIFIER(FixedArray)
2546 // Checks if two FixedArrays have identical contents.
2547 bool IsEqualTo(FixedArray* other);
2550 // Swap two elements in a pair of arrays. If this array and the
2551 // numbers array are the same object, the elements are only swapped
2553 void SwapPairs(FixedArray* numbers, int i, int j);
2555 // Sort prefix of this array and the numbers array as pairs wrt. the
2556 // numbers. If the numbers array and the this array are the same
2557 // object, the prefix of this array is sorted.
2558 void SortPairs(FixedArray* numbers, uint32_t len);
2560 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2562 static inline int SizeOf(Map* map, HeapObject* object);
2566 // Set operation on FixedArray without using write barriers. Can
2567 // only be used for storing old space objects or smis.
2568 static inline void NoWriteBarrierSet(FixedArray* array,
2572 // Set operation on FixedArray without incremental write barrier. Can
2573 // only be used if the object is guaranteed to be white (whiteness witness
2575 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2580 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2582 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2586 // FixedDoubleArray describes fixed-sized arrays with element type double.
2587 class FixedDoubleArray: public FixedArrayBase {
2589 // Setter and getter for elements.
2590 inline double get_scalar(int index);
2591 inline uint64_t get_representation(int index);
2592 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2593 inline void set(int index, double value);
2594 inline void set_the_hole(int index);
2596 // Checking for the hole.
2597 inline bool is_the_hole(int index);
2599 // Garbage collection support.
2600 inline static int SizeFor(int length) {
2601 return kHeaderSize + length * kDoubleSize;
2604 // Gives access to raw memory which stores the array's data.
2605 inline double* data_start();
2607 inline void FillWithHoles(int from, int to);
2609 // Code Generation support.
2610 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2612 DECLARE_CAST(FixedDoubleArray)
2614 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2615 // Prevents overflowing size computations, as well as extreme memory
2617 static const int kMaxSize = 512 * MB;
2618 // Maximally allowed length of a FixedArray.
2619 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2621 // Dispatched behavior.
2622 DECLARE_PRINTER(FixedDoubleArray)
2623 DECLARE_VERIFIER(FixedDoubleArray)
2626 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2630 class WeakFixedArray : public FixedArray {
2632 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2633 // This function does not check if the value exists already, callers must
2634 // ensure this themselves if necessary.
2635 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2636 Handle<HeapObject> value,
2637 int* assigned_index = NULL);
2639 // Returns true if an entry was found and removed.
2640 bool Remove(Handle<HeapObject> value);
2642 class NullCallback {
2644 static void Callback(Object* value, int old_index, int new_index) {}
2647 template <class CompactionCallback>
2650 inline Object* Get(int index) const;
2651 inline void Clear(int index);
2652 inline int Length() const;
2654 inline bool IsEmptySlot(int index) const;
2655 static Object* Empty() { return Smi::FromInt(0); }
2659 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2660 void Reset(Object* maybe_array);
2667 WeakFixedArray* list_;
2669 int last_used_index_;
2670 DisallowHeapAllocation no_gc_;
2672 DISALLOW_COPY_AND_ASSIGN(Iterator);
2675 DECLARE_CAST(WeakFixedArray)
2678 static const int kLastUsedIndexIndex = 0;
2679 static const int kFirstIndex = 1;
2681 static Handle<WeakFixedArray> Allocate(
2682 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2684 static void Set(Handle<WeakFixedArray> array, int index,
2685 Handle<HeapObject> value);
2686 inline void clear(int index);
2688 inline int last_used_index() const;
2689 inline void set_last_used_index(int index);
2691 // Disallow inherited setters.
2692 void set(int index, Smi* value);
2693 void set(int index, Object* value);
2694 void set(int index, Object* value, WriteBarrierMode mode);
2695 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2699 // Generic array grows dynamically with O(1) amortized insertion.
2700 class ArrayList : public FixedArray {
2704 // Use this if GC can delete elements from the array.
2705 kReloadLengthAfterAllocation,
2707 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2708 AddMode mode = kNone);
2709 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2710 Handle<Object> obj2, AddMode = kNone);
2711 inline int Length();
2712 inline void SetLength(int length);
2713 inline Object* Get(int index);
2714 inline Object** Slot(int index);
2715 inline void Set(int index, Object* obj);
2716 inline void Clear(int index, Object* undefined);
2717 DECLARE_CAST(ArrayList)
2720 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2721 static const int kLengthIndex = 0;
2722 static const int kFirstIndex = 1;
2723 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2727 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2728 // The format of the these objects is:
2729 // [0]: Number of descriptors
2730 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2731 // [0]: pointer to fixed array with enum cache
2732 // [1]: either Smi(0) or pointer to fixed array with indices
2734 // [2 + number of descriptors * kDescriptorSize]: start of slack
2735 class DescriptorArray: public FixedArray {
2737 // Returns true for both shared empty_descriptor_array and for smis, which the
2738 // map uses to encode additional bit fields when the descriptor array is not
2740 inline bool IsEmpty();
2742 // Returns the number of descriptors in the array.
2743 inline int number_of_descriptors();
2745 inline int number_of_descriptors_storage();
2747 inline int NumberOfSlackDescriptors();
2749 inline void SetNumberOfDescriptors(int number_of_descriptors);
2750 inline int number_of_entries();
2752 inline bool HasEnumCache();
2754 inline void CopyEnumCacheFrom(DescriptorArray* array);
2756 inline FixedArray* GetEnumCache();
2758 inline bool HasEnumIndicesCache();
2760 inline FixedArray* GetEnumIndicesCache();
2762 inline Object** GetEnumCacheSlot();
2764 void ClearEnumCache();
2766 // Initialize or change the enum cache,
2767 // using the supplied storage for the small "bridge".
2768 void SetEnumCache(FixedArray* bridge_storage,
2769 FixedArray* new_cache,
2770 Object* new_index_cache);
2772 bool CanHoldValue(int descriptor, Object* value);
2774 // Accessors for fetching instance descriptor at descriptor number.
2775 inline Name* GetKey(int descriptor_number);
2776 inline Object** GetKeySlot(int descriptor_number);
2777 inline Object* GetValue(int descriptor_number);
2778 inline void SetValue(int descriptor_number, Object* value);
2779 inline Object** GetValueSlot(int descriptor_number);
2780 static inline int GetValueOffset(int descriptor_number);
2781 inline Object** GetDescriptorStartSlot(int descriptor_number);
2782 inline Object** GetDescriptorEndSlot(int descriptor_number);
2783 inline PropertyDetails GetDetails(int descriptor_number);
2784 inline PropertyType GetType(int descriptor_number);
2785 inline int GetFieldIndex(int descriptor_number);
2786 inline HeapType* GetFieldType(int descriptor_number);
2787 inline Object* GetConstant(int descriptor_number);
2788 inline Object* GetCallbacksObject(int descriptor_number);
2789 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2791 inline Name* GetSortedKey(int descriptor_number);
2792 inline int GetSortedKeyIndex(int descriptor_number);
2793 inline void SetSortedKey(int pointer, int descriptor_number);
2794 inline void SetRepresentation(int descriptor_number,
2795 Representation representation);
2797 // Accessor for complete descriptor.
2798 inline void Get(int descriptor_number, Descriptor* desc);
2799 inline void Set(int descriptor_number, Descriptor* desc);
2800 void Replace(int descriptor_number, Descriptor* descriptor);
2802 // Append automatically sets the enumeration index. This should only be used
2803 // to add descriptors in bulk at the end, followed by sorting the descriptor
2805 inline void Append(Descriptor* desc);
2807 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2808 int enumeration_index,
2811 static Handle<DescriptorArray> CopyUpToAddAttributes(
2812 Handle<DescriptorArray> desc,
2813 int enumeration_index,
2814 PropertyAttributes attributes,
2817 // Sort the instance descriptors by the hash codes of their keys.
2820 // Search the instance descriptors for given name.
2821 INLINE(int Search(Name* name, int number_of_own_descriptors));
2823 // As the above, but uses DescriptorLookupCache and updates it when
2825 INLINE(int SearchWithCache(Name* name, Map* map));
2827 // Allocates a DescriptorArray, but returns the singleton
2828 // empty descriptor array object if number_of_descriptors is 0.
2829 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2830 int number_of_descriptors,
2833 DECLARE_CAST(DescriptorArray)
2835 // Constant for denoting key was not found.
2836 static const int kNotFound = -1;
2838 static const int kDescriptorLengthIndex = 0;
2839 static const int kEnumCacheIndex = 1;
2840 static const int kFirstIndex = 2;
2842 // The length of the "bridge" to the enum cache.
2843 static const int kEnumCacheBridgeLength = 2;
2844 static const int kEnumCacheBridgeCacheIndex = 0;
2845 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2847 // Layout description.
2848 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2849 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2850 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2852 // Layout description for the bridge array.
2853 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2855 // Layout of descriptor.
2856 static const int kDescriptorKey = 0;
2857 static const int kDescriptorDetails = 1;
2858 static const int kDescriptorValue = 2;
2859 static const int kDescriptorSize = 3;
2861 #if defined(DEBUG) || defined(OBJECT_PRINT)
2862 // For our gdb macros, we should perhaps change these in the future.
2865 // Print all the descriptors.
2866 void PrintDescriptors(std::ostream& os); // NOLINT
2870 // Is the descriptor array sorted and without duplicates?
2871 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2873 // Is the descriptor array consistent with the back pointers in targets?
2874 bool IsConsistentWithBackPointers(Map* current_map);
2876 // Are two DescriptorArrays equal?
2877 bool IsEqualTo(DescriptorArray* other);
2880 // Returns the fixed array length required to hold number_of_descriptors
2882 static int LengthFor(int number_of_descriptors) {
2883 return ToKeyIndex(number_of_descriptors);
2887 // WhitenessWitness is used to prove that a descriptor array is white
2888 // (unmarked), so incremental write barriers can be skipped because the
2889 // marking invariant cannot be broken and slots pointing into evacuation
2890 // candidates will be discovered when the object is scanned. A witness is
2891 // always stack-allocated right after creating an array. By allocating a
2892 // witness, incremental marking is globally disabled. The witness is then
2893 // passed along wherever needed to statically prove that the array is known to
2895 class WhitenessWitness {
2897 inline explicit WhitenessWitness(DescriptorArray* array);
2898 inline ~WhitenessWitness();
2901 IncrementalMarking* marking_;
2904 // An entry in a DescriptorArray, represented as an (array, index) pair.
2907 inline explicit Entry(DescriptorArray* descs, int index) :
2908 descs_(descs), index_(index) { }
2910 inline PropertyType type();
2911 inline Object* GetCallbackObject();
2914 DescriptorArray* descs_;
2918 // Conversion from descriptor number to array indices.
2919 static int ToKeyIndex(int descriptor_number) {
2920 return kFirstIndex +
2921 (descriptor_number * kDescriptorSize) +
2925 static int ToDetailsIndex(int descriptor_number) {
2926 return kFirstIndex +
2927 (descriptor_number * kDescriptorSize) +
2931 static int ToValueIndex(int descriptor_number) {
2932 return kFirstIndex +
2933 (descriptor_number * kDescriptorSize) +
2937 // Transfer a complete descriptor from the src descriptor array to this
2938 // descriptor array.
2939 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2941 inline void Set(int descriptor_number,
2943 const WhitenessWitness&);
2945 // Swap first and second descriptor.
2946 inline void SwapSortedKeys(int first, int second);
2948 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2952 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2954 template <SearchMode search_mode, typename T>
2955 inline int Search(T* array, Name* name, int valid_entries = 0,
2956 int* out_insertion_index = NULL);
2959 // HashTable is a subclass of FixedArray that implements a hash table
2960 // that uses open addressing and quadratic probing.
2962 // In order for the quadratic probing to work, elements that have not
2963 // yet been used and elements that have been deleted are
2964 // distinguished. Probing continues when deleted elements are
2965 // encountered and stops when unused elements are encountered.
2967 // - Elements with key == undefined have not been used yet.
2968 // - Elements with key == the_hole have been deleted.
2970 // The hash table class is parameterized with a Shape and a Key.
2971 // Shape must be a class with the following interface:
2972 // class ExampleShape {
2974 // // Tells whether key matches other.
2975 // static bool IsMatch(Key key, Object* other);
2976 // // Returns the hash value for key.
2977 // static uint32_t Hash(Key key);
2978 // // Returns the hash value for object.
2979 // static uint32_t HashForObject(Key key, Object* object);
2980 // // Convert key to an object.
2981 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2982 // // The prefix size indicates number of elements in the beginning
2983 // // of the backing storage.
2984 // static const int kPrefixSize = ..;
2985 // // The Element size indicates number of elements per entry.
2986 // static const int kEntrySize = ..;
2988 // The prefix size indicates an amount of memory in the
2989 // beginning of the backing storage that can be used for non-element
2990 // information by subclasses.
2992 template<typename Key>
2995 static const bool UsesSeed = false;
2996 static uint32_t Hash(Key key) { return 0; }
2997 static uint32_t SeededHash(Key key, uint32_t seed) {
3001 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3002 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3004 return HashForObject(key, object);
3009 class HashTableBase : public FixedArray {
3011 // Returns the number of elements in the hash table.
3012 inline int NumberOfElements();
3014 // Returns the number of deleted elements in the hash table.
3015 inline int NumberOfDeletedElements();
3017 // Returns the capacity of the hash table.
3018 inline int Capacity();
3020 // ElementAdded should be called whenever an element is added to a
3022 inline void ElementAdded();
3024 // ElementRemoved should be called whenever an element is removed from
3026 inline void ElementRemoved();
3027 inline void ElementsRemoved(int n);
3029 // Computes the required capacity for a table holding the given
3030 // number of elements. May be more than HashTable::kMaxCapacity.
3031 static inline int ComputeCapacity(int at_least_space_for);
3033 // Tells whether k is a real key. The hole and undefined are not allowed
3034 // as keys and can be used to indicate missing or deleted elements.
3035 inline bool IsKey(Object* k);
3037 // Compute the probe offset (quadratic probing).
3038 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3039 return (n + n * n) >> 1;
3042 static const int kNumberOfElementsIndex = 0;
3043 static const int kNumberOfDeletedElementsIndex = 1;
3044 static const int kCapacityIndex = 2;
3045 static const int kPrefixStartIndex = 3;
3047 // Constant used for denoting a absent entry.
3048 static const int kNotFound = -1;
3051 // Update the number of elements in the hash table.
3052 inline void SetNumberOfElements(int nof);
3054 // Update the number of deleted elements in the hash table.
3055 inline void SetNumberOfDeletedElements(int nod);
3057 // Returns probe entry.
3058 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3059 DCHECK(base::bits::IsPowerOfTwo32(size));
3060 return (hash + GetProbeOffset(number)) & (size - 1);
3063 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3064 return hash & (size - 1);
3067 inline static uint32_t NextProbe(
3068 uint32_t last, uint32_t number, uint32_t size) {
3069 return (last + number) & (size - 1);
3074 template <typename Derived, typename Shape, typename Key>
3075 class HashTable : public HashTableBase {
3078 inline uint32_t Hash(Key key) {
3079 if (Shape::UsesSeed) {
3080 return Shape::SeededHash(key, GetHeap()->HashSeed());
3082 return Shape::Hash(key);
3086 inline uint32_t HashForObject(Key key, Object* object) {
3087 if (Shape::UsesSeed) {
3088 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3090 return Shape::HashForObject(key, object);
3094 // Returns a new HashTable object.
3095 MUST_USE_RESULT static Handle<Derived> New(
3096 Isolate* isolate, int at_least_space_for,
3097 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3098 PretenureFlag pretenure = NOT_TENURED);
3100 DECLARE_CAST(HashTable)
3102 // Garbage collection support.
3103 void IteratePrefix(ObjectVisitor* visitor);
3104 void IterateElements(ObjectVisitor* visitor);
3106 // Find entry for key otherwise return kNotFound.
3107 inline int FindEntry(Key key);
3108 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3109 int FindEntry(Isolate* isolate, Key key);
3111 // Rehashes the table in-place.
3112 void Rehash(Key key);
3114 // Returns the key at entry.
3115 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3117 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3118 static const int kEntrySize = Shape::kEntrySize;
3119 static const int kElementsStartOffset =
3120 kHeaderSize + kElementsStartIndex * kPointerSize;
3121 static const int kCapacityOffset =
3122 kHeaderSize + kCapacityIndex * kPointerSize;
3124 // Returns the index for an entry (of the key)
3125 static inline int EntryToIndex(int entry) {
3126 return (entry * kEntrySize) + kElementsStartIndex;
3130 friend class ObjectHashTable;
3132 // Find the entry at which to insert element with the given key that
3133 // has the given hash value.
3134 uint32_t FindInsertionEntry(uint32_t hash);
3136 // Attempt to shrink hash table after removal of key.
3137 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3139 // Ensure enough space for n additional elements.
3140 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3141 Handle<Derived> table,
3144 PretenureFlag pretenure = NOT_TENURED);
3146 // Sets the capacity of the hash table.
3147 void SetCapacity(int capacity) {
3148 // To scale a computed hash code to fit within the hash table, we
3149 // use bit-wise AND with a mask, so the capacity must be positive
3151 DCHECK(capacity > 0);
3152 DCHECK(capacity <= kMaxCapacity);
3153 set(kCapacityIndex, Smi::FromInt(capacity));
3156 // Maximal capacity of HashTable. Based on maximal length of underlying
3157 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3159 static const int kMaxCapacity =
3160 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3163 // Returns _expected_ if one of entries given by the first _probe_ probes is
3164 // equal to _expected_. Otherwise, returns the entry given by the probe
3166 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3168 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3170 // Rehashes this hash-table into the new table.
3171 void Rehash(Handle<Derived> new_table, Key key);
3175 // HashTableKey is an abstract superclass for virtual key behavior.
3176 class HashTableKey {
3178 // Returns whether the other object matches this key.
3179 virtual bool IsMatch(Object* other) = 0;
3180 // Returns the hash value for this key.
3181 virtual uint32_t Hash() = 0;
3182 // Returns the hash value for object.
3183 virtual uint32_t HashForObject(Object* key) = 0;
3184 // Returns the key object for storing into the hash table.
3185 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3187 virtual ~HashTableKey() {}
3191 class StringTableShape : public BaseShape<HashTableKey*> {
3193 static inline bool IsMatch(HashTableKey* key, Object* value) {
3194 return key->IsMatch(value);
3197 static inline uint32_t Hash(HashTableKey* key) {
3201 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3202 return key->HashForObject(object);
3205 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3207 static const int kPrefixSize = 0;
3208 static const int kEntrySize = 1;
3211 class SeqOneByteString;
3215 // No special elements in the prefix and the element size is 1
3216 // because only the string itself (the key) needs to be stored.
3217 class StringTable: public HashTable<StringTable,
3221 // Find string in the string table. If it is not there yet, it is
3222 // added. The return value is the string found.
3223 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3224 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3225 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3227 // Tries to internalize given string and returns string handle on success
3228 // or an empty handle otherwise.
3229 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3231 Handle<String> string);
3233 // Looks up a string that is equal to the given string and returns
3234 // string handle if it is found, or an empty handle otherwise.
3235 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3237 Handle<String> str);
3238 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3243 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3245 DECLARE_CAST(StringTable)
3248 template <bool seq_one_byte>
3249 friend class JsonParser;
3251 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3255 template <typename Derived, typename Shape, typename Key>
3256 class Dictionary: public HashTable<Derived, Shape, Key> {
3257 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3260 // Returns the value at entry.
3261 Object* ValueAt(int entry) {
3262 return this->get(Derived::EntryToIndex(entry) + 1);
3265 // Set the value for entry.
3266 void ValueAtPut(int entry, Object* value) {
3267 this->set(Derived::EntryToIndex(entry) + 1, value);
3270 // Returns the property details for the property at entry.
3271 PropertyDetails DetailsAt(int entry) {
3272 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3275 // Set the details for entry.
3276 void DetailsAtPut(int entry, PropertyDetails value) {
3277 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3280 // Returns true if property at given entry is deleted.
3281 bool IsDeleted(int entry) {
3282 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3285 // Delete a property from the dictionary.
3286 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3288 // Attempt to shrink the dictionary after deletion of key.
3289 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3290 Handle<Derived> dictionary,
3292 return DerivedHashTable::Shrink(dictionary, key);
3296 // TODO(dcarney): templatize or move to SeededNumberDictionary
3297 void CopyValuesTo(FixedArray* elements);
3299 // Returns the number of elements in the dictionary filtering out properties
3300 // with the specified attributes.
3301 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3303 // Returns the number of enumerable elements in the dictionary.
3304 int NumberOfEnumElements() {
3305 return NumberOfElementsFilterAttributes(
3306 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3309 // Returns true if the dictionary contains any elements that are non-writable,
3310 // non-configurable, non-enumerable, or have getters/setters.
3311 bool HasComplexElements();
3313 enum SortMode { UNSORTED, SORTED };
3315 // Fill in details for properties into storage.
3316 // Returns the number of properties added.
3317 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3318 SortMode sort_mode);
3320 // Copies enumerable keys to preallocated fixed array.
3321 void CopyEnumKeysTo(FixedArray* storage);
3323 // Accessors for next enumeration index.
3324 void SetNextEnumerationIndex(int index) {
3326 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3329 int NextEnumerationIndex() {
3330 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3333 // Creates a new dictionary.
3334 MUST_USE_RESULT static Handle<Derived> New(
3336 int at_least_space_for,
3337 PretenureFlag pretenure = NOT_TENURED);
3339 // Ensure enough space for n additional elements.
3340 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3343 void Print(std::ostream& os); // NOLINT
3345 // Returns the key (slow).
3346 Object* SlowReverseLookup(Object* value);
3348 // Sets the entry to (key, value) pair.
3349 inline void SetEntry(int entry,
3351 Handle<Object> value);
3352 inline void SetEntry(int entry,
3354 Handle<Object> value,
3355 PropertyDetails details);
3357 MUST_USE_RESULT static Handle<Derived> Add(
3358 Handle<Derived> dictionary,
3360 Handle<Object> value,
3361 PropertyDetails details);
3363 // Returns iteration indices array for the |dictionary|.
3364 // Values are direct indices in the |HashTable| array.
3365 static Handle<FixedArray> BuildIterationIndicesArray(
3366 Handle<Derived> dictionary);
3369 // Generic at put operation.
3370 MUST_USE_RESULT static Handle<Derived> AtPut(
3371 Handle<Derived> dictionary,
3373 Handle<Object> value);
3375 // Add entry to dictionary.
3376 static void AddEntry(
3377 Handle<Derived> dictionary,
3379 Handle<Object> value,
3380 PropertyDetails details,
3383 // Generate new enumeration indices to avoid enumeration index overflow.
3384 // Returns iteration indices array for the |dictionary|.
3385 static Handle<FixedArray> GenerateNewEnumerationIndices(
3386 Handle<Derived> dictionary);
3387 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3388 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3392 template <typename Derived, typename Shape>
3393 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3394 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3397 // Find entry for key, otherwise return kNotFound. Optimized version of
3398 // HashTable::FindEntry.
3399 int FindEntry(Handle<Name> key);
3403 template <typename Key>
3404 class BaseDictionaryShape : public BaseShape<Key> {
3406 template <typename Dictionary>
3407 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3408 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3409 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3410 return PropertyDetails(
3411 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3414 template <typename Dictionary>
3415 static inline void DetailsAtPut(Dictionary* dict, int entry,
3416 PropertyDetails value) {
3417 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3418 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3421 template <typename Dictionary>
3422 static bool IsDeleted(Dictionary* dict, int entry) {
3426 template <typename Dictionary>
3427 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3428 Handle<Object> value, PropertyDetails details);
3432 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3434 static inline bool IsMatch(Handle<Name> key, Object* other);
3435 static inline uint32_t Hash(Handle<Name> key);
3436 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3437 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3438 static const int kPrefixSize = 2;
3439 static const int kEntrySize = 3;
3440 static const bool kIsEnumerable = true;
3444 class NameDictionary
3445 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3446 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3450 DECLARE_CAST(NameDictionary)
3452 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3453 Handle<NameDictionary> dictionary);
3457 class GlobalDictionaryShape : public NameDictionaryShape {
3459 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3461 template <typename Dictionary>
3462 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3464 template <typename Dictionary>
3465 static inline void DetailsAtPut(Dictionary* dict, int entry,
3466 PropertyDetails value);
3468 template <typename Dictionary>
3469 static bool IsDeleted(Dictionary* dict, int entry);
3471 template <typename Dictionary>
3472 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3473 Handle<Object> value, PropertyDetails details);
3477 class GlobalDictionary
3478 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3480 DECLARE_CAST(GlobalDictionary)
3484 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3486 static inline bool IsMatch(uint32_t key, Object* other);
3487 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3488 static const int kEntrySize = 3;
3489 static const bool kIsEnumerable = false;
3493 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3495 static const bool UsesSeed = true;
3496 static const int kPrefixSize = 2;
3498 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3499 static inline uint32_t SeededHashForObject(uint32_t key,
3505 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3507 static const int kPrefixSize = 0;
3509 static inline uint32_t Hash(uint32_t key);
3510 static inline uint32_t HashForObject(uint32_t key, Object* object);
3514 class SeededNumberDictionary
3515 : public Dictionary<SeededNumberDictionary,
3516 SeededNumberDictionaryShape,
3519 DECLARE_CAST(SeededNumberDictionary)
3521 // Type specific at put (default NONE attributes is used when adding).
3522 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3523 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3524 Handle<Object> value, bool used_as_prototype);
3525 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3526 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3527 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3529 // Set an existing entry or add a new one if needed.
3530 // Return the updated dictionary.
3531 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3532 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3533 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3535 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3537 // If slow elements are required we will never go back to fast-case
3538 // for the elements kept in this dictionary. We require slow
3539 // elements if an element has been added at an index larger than
3540 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3541 // when defining a getter or setter with a number key.
3542 inline bool requires_slow_elements();
3543 inline void set_requires_slow_elements();
3545 // Get the value of the max number key that has been added to this
3546 // dictionary. max_number_key can only be called if
3547 // requires_slow_elements returns false.
3548 inline uint32_t max_number_key();
3551 static const int kRequiresSlowElementsMask = 1;
3552 static const int kRequiresSlowElementsTagSize = 1;
3553 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3557 class UnseededNumberDictionary
3558 : public Dictionary<UnseededNumberDictionary,
3559 UnseededNumberDictionaryShape,
3562 DECLARE_CAST(UnseededNumberDictionary)
3564 // Type specific at put (default NONE attributes is used when adding).
3565 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3566 Handle<UnseededNumberDictionary> dictionary,
3568 Handle<Object> value);
3569 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3570 Handle<UnseededNumberDictionary> dictionary,
3572 Handle<Object> value);
3574 // Set an existing entry or add a new one if needed.
3575 // Return the updated dictionary.
3576 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3577 Handle<UnseededNumberDictionary> dictionary,
3579 Handle<Object> value);
3583 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3585 static inline bool IsMatch(Handle<Object> key, Object* other);
3586 static inline uint32_t Hash(Handle<Object> key);
3587 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3588 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3589 static const int kPrefixSize = 0;
3590 static const int kEntrySize = 2;
3594 // ObjectHashTable maps keys that are arbitrary objects to object values by
3595 // using the identity hash of the key for hashing purposes.
3596 class ObjectHashTable: public HashTable<ObjectHashTable,
3597 ObjectHashTableShape,
3600 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3602 DECLARE_CAST(ObjectHashTable)
3604 // Attempt to shrink hash table after removal of key.
3605 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3606 Handle<ObjectHashTable> table,
3607 Handle<Object> key);
3609 // Looks up the value associated with the given key. The hole value is
3610 // returned in case the key is not present.
3611 Object* Lookup(Handle<Object> key);
3612 Object* Lookup(Handle<Object> key, int32_t hash);
3613 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3615 // Adds (or overwrites) the value associated with the given key.
3616 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3618 Handle<Object> value);
3619 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3620 Handle<Object> key, Handle<Object> value,
3623 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3624 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3627 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3628 Handle<Object> key, bool* was_present,
3632 friend class MarkCompactCollector;
3634 void AddEntry(int entry, Object* key, Object* value);
3635 void RemoveEntry(int entry);
3637 // Returns the index to the value of an entry.
3638 static inline int EntryToValueIndex(int entry) {
3639 return EntryToIndex(entry) + 1;
3644 // OrderedHashTable is a HashTable with Object keys that preserves
3645 // insertion order. There are Map and Set interfaces (OrderedHashMap
3646 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3648 // Only Object* keys are supported, with Object::SameValueZero() used as the
3649 // equality operator and Object::GetHash() for the hash function.
3651 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3652 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3653 // Originally attributed to Tyler Close.
3656 // [0]: bucket count
3657 // [1]: element count
3658 // [2]: deleted element count
3659 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3660 // offset into the data table (see below) where the
3661 // first item in this bucket is stored.
3662 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3663 // Capacity() * kEntrySize, where the first entrysize
3664 // items are handled by the derived class and the
3665 // item at kChainOffset is another entry into the
3666 // data table indicating the next entry in this hash
3669 // When we transition the table to a new version we obsolete it and reuse parts
3670 // of the memory to store information how to transition an iterator to the new
3673 // Memory layout for obsolete table:
3674 // [0]: bucket count
3675 // [1]: Next newer table
3676 // [2]: Number of removed holes or -1 when the table was cleared.
3677 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3678 // [3 + NumberOfRemovedHoles()..length]: Not used
3680 template<class Derived, class Iterator, int entrysize>
3681 class OrderedHashTable: public FixedArray {
3683 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3684 static Handle<Derived> Allocate(
3685 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3687 // Returns an OrderedHashTable (possibly |table|) with enough space
3688 // to add at least one new element.
3689 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3691 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3693 static Handle<Derived> Shrink(Handle<Derived> table);
3695 // Returns a new empty OrderedHashTable and records the clearing so that
3696 // exisiting iterators can be updated.
3697 static Handle<Derived> Clear(Handle<Derived> table);
3699 // Returns a true if the OrderedHashTable contains the key
3700 static bool HasKey(Handle<Derived> table, Handle<Object> key);
3702 int NumberOfElements() {
3703 return Smi::cast(get(kNumberOfElementsIndex))->value();
3706 int NumberOfDeletedElements() {
3707 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3710 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3712 int NumberOfBuckets() {
3713 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3716 // Returns an index into |this| for the given entry.
3717 int EntryToIndex(int entry) {
3718 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3721 int HashToBucket(int hash) { return hash & (NumberOfBuckets() - 1); }
3723 int HashToEntry(int hash) {
3724 int bucket = HashToBucket(hash);
3725 Object* entry = this->get(kHashTableStartIndex + bucket);
3726 return Smi::cast(entry)->value();
3729 int KeyToFirstEntry(Object* key) {
3730 Object* hash = key->GetHash();
3731 // If the object does not have an identity hash, it was never used as a key
3732 if (hash->IsUndefined()) return kNotFound;
3733 return HashToEntry(Smi::cast(hash)->value());
3736 int NextChainEntry(int entry) {
3737 Object* next_entry = get(EntryToIndex(entry) + kChainOffset);
3738 return Smi::cast(next_entry)->value();
3741 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3744 return !get(kNextTableIndex)->IsSmi();
3747 // The next newer table. This is only valid if the table is obsolete.
3748 Derived* NextTable() {
3749 return Derived::cast(get(kNextTableIndex));
3752 // When the table is obsolete we store the indexes of the removed holes.
3753 int RemovedIndexAt(int index) {
3754 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3757 static const int kNotFound = -1;
3758 static const int kMinCapacity = 4;
3760 static const int kNumberOfBucketsIndex = 0;
3761 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3762 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3763 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3764 static const int kNextTableIndex = kNumberOfElementsIndex;
3766 static const int kNumberOfBucketsOffset =
3767 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3768 static const int kNumberOfElementsOffset =
3769 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3770 static const int kNumberOfDeletedElementsOffset =
3771 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3772 static const int kHashTableStartOffset =
3773 kHeaderSize + kHashTableStartIndex * kPointerSize;
3774 static const int kNextTableOffset =
3775 kHeaderSize + kNextTableIndex * kPointerSize;
3777 static const int kEntrySize = entrysize + 1;
3778 static const int kChainOffset = entrysize;
3780 static const int kLoadFactor = 2;
3782 // NumberOfDeletedElements is set to kClearedTableSentinel when
3783 // the table is cleared, which allows iterator transitions to
3784 // optimize that case.
3785 static const int kClearedTableSentinel = -1;
3788 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3790 void SetNumberOfBuckets(int num) {
3791 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3794 void SetNumberOfElements(int num) {
3795 set(kNumberOfElementsIndex, Smi::FromInt(num));
3798 void SetNumberOfDeletedElements(int num) {
3799 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3803 return NumberOfBuckets() * kLoadFactor;
3806 void SetNextTable(Derived* next_table) {
3807 set(kNextTableIndex, next_table);
3810 void SetRemovedIndexAt(int index, int removed_index) {
3811 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3814 static const int kRemovedHolesIndex = kHashTableStartIndex;
3816 static const int kMaxCapacity =
3817 (FixedArray::kMaxLength - kHashTableStartIndex)
3818 / (1 + (kEntrySize * kLoadFactor));
3822 class JSSetIterator;
3825 class OrderedHashSet: public OrderedHashTable<
3826 OrderedHashSet, JSSetIterator, 1> {
3828 DECLARE_CAST(OrderedHashSet)
3830 static Handle<OrderedHashSet> Add(Handle<OrderedHashSet> table,
3831 Handle<Object> value);
3835 class JSMapIterator;
3838 class OrderedHashMap
3839 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3841 DECLARE_CAST(OrderedHashMap)
3843 inline Object* ValueAt(int entry);
3845 static const int kValueOffset = 1;
3849 template <int entrysize>
3850 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3852 static inline bool IsMatch(Handle<Object> key, Object* other);
3853 static inline uint32_t Hash(Handle<Object> key);
3854 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3855 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3856 static const int kPrefixSize = 0;
3857 static const int kEntrySize = entrysize;
3861 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3862 // values. The table wraps the keys in weak cells and store values directly.
3863 // Thus it references keys weakly and values strongly.
3864 class WeakHashTable: public HashTable<WeakHashTable,
3865 WeakHashTableShape<2>,
3868 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3870 DECLARE_CAST(WeakHashTable)
3872 // Looks up the value associated with the given key. The hole value is
3873 // returned in case the key is not present.
3874 Object* Lookup(Handle<HeapObject> key);
3876 // Adds (or overwrites) the value associated with the given key. Mapping a
3877 // key to the hole value causes removal of the whole entry.
3878 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3879 Handle<HeapObject> key,
3880 Handle<HeapObject> value);
3882 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3885 friend class MarkCompactCollector;
3887 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3889 // Returns the index to the value of an entry.
3890 static inline int EntryToValueIndex(int entry) {
3891 return EntryToIndex(entry) + 1;
3896 // ScopeInfo represents information about different scopes of a source
3897 // program and the allocation of the scope's variables. Scope information
3898 // is stored in a compressed form in ScopeInfo objects and is used
3899 // at runtime (stack dumps, deoptimization, etc.).
3901 // This object provides quick access to scope info details for runtime
3903 class ScopeInfo : public FixedArray {
3905 DECLARE_CAST(ScopeInfo)
3907 // Return the type of this scope.
3908 ScopeType scope_type();
3910 // Does this scope call eval?
3913 // Return the language mode of this scope.
3914 LanguageMode language_mode();
3916 // True if this scope is a (var) declaration scope.
3917 bool is_declaration_scope();
3919 // Does this scope make a sloppy eval call?
3920 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3922 // Return the total number of locals allocated on the stack and in the
3923 // context. This includes the parameters that are allocated in the context.
3926 // Return the number of stack slots for code. This number consists of two
3928 // 1. One stack slot per stack allocated local.
3929 // 2. One stack slot for the function name if it is stack allocated.
3930 int StackSlotCount();
3932 // Return the number of context slots for code if a context is allocated. This
3933 // number consists of three parts:
3934 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3935 // 2. One context slot per context allocated local.
3936 // 3. One context slot for the function name if it is context allocated.
3937 // Parameters allocated in the context count as context allocated locals. If
3938 // no contexts are allocated for this scope ContextLength returns 0.
3939 int ContextLength();
3941 // Does this scope declare a "this" binding?
3944 // Does this scope declare a "this" binding, and the "this" binding is stack-
3945 // or context-allocated?
3946 bool HasAllocatedReceiver();
3948 // Is this scope the scope of a named function expression?
3949 bool HasFunctionName();
3951 // Return if this has context allocated locals.
3952 bool HasHeapAllocatedLocals();
3954 // Return if contexts are allocated for this scope.
3957 // Return if this is a function scope with "use asm".
3958 inline bool IsAsmModule();
3960 // Return if this is a nested function within an asm module scope.
3961 inline bool IsAsmFunction();
3963 inline bool HasSimpleParameters();
3965 // Return the function_name if present.
3966 String* FunctionName();
3968 // Return the name of the given parameter.
3969 String* ParameterName(int var);
3971 // Return the name of the given local.
3972 String* LocalName(int var);
3974 // Return the name of the given stack local.
3975 String* StackLocalName(int var);
3977 // Return the name of the given stack local.
3978 int StackLocalIndex(int var);
3980 // Return the name of the given context local.
3981 String* ContextLocalName(int var);
3983 // Return the mode of the given context local.
3984 VariableMode ContextLocalMode(int var);
3986 // Return the initialization flag of the given context local.
3987 InitializationFlag ContextLocalInitFlag(int var);
3989 // Return the initialization flag of the given context local.
3990 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3992 // Return true if this local was introduced by the compiler, and should not be
3993 // exposed to the user in a debugger.
3994 bool LocalIsSynthetic(int var);
3996 String* StrongModeFreeVariableName(int var);
3997 int StrongModeFreeVariableStartPosition(int var);
3998 int StrongModeFreeVariableEndPosition(int var);
4000 // Lookup support for serialized scope info. Returns the
4001 // the stack slot index for a given slot name if the slot is
4002 // present; otherwise returns a value < 0. The name must be an internalized
4004 int StackSlotIndex(String* name);
4006 // Lookup support for serialized scope info. Returns the local context slot
4007 // index for a given slot name if the slot is present; otherwise
4008 // returns a value < 0. The name must be an internalized string.
4009 // If the slot is present and mode != NULL, sets *mode to the corresponding
4010 // mode for that variable.
4011 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
4012 VariableMode* mode, InitializationFlag* init_flag,
4013 MaybeAssignedFlag* maybe_assigned_flag);
4015 // Similar to ContextSlotIndex() but this method searches only among
4016 // global slots of the serialized scope info. Returns the context slot index
4017 // for a given slot name if the slot is present; otherwise returns a
4018 // value < 0. The name must be an internalized string. If the slot is present
4019 // and mode != NULL, sets *mode to the corresponding mode for that variable.
4020 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
4021 Handle<String> name, VariableMode* mode,
4022 InitializationFlag* init_flag,
4023 MaybeAssignedFlag* maybe_assigned_flag);
4025 // Lookup the name of a certain context slot by its index.
4026 String* ContextSlotName(int slot_index);
4028 // Lookup support for serialized scope info. Returns the
4029 // parameter index for a given parameter name if the parameter is present;
4030 // otherwise returns a value < 0. The name must be an internalized string.
4031 int ParameterIndex(String* name);
4033 // Lookup support for serialized scope info. Returns the function context
4034 // slot index if the function name is present and context-allocated (named
4035 // function expressions, only), otherwise returns a value < 0. The name
4036 // must be an internalized string.
4037 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4039 // Lookup support for serialized scope info. Returns the receiver context
4040 // slot index if scope has a "this" binding, and the binding is
4041 // context-allocated. Otherwise returns a value < 0.
4042 int ReceiverContextSlotIndex();
4044 FunctionKind function_kind();
4046 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4047 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4049 // Serializes empty scope info.
4050 static ScopeInfo* Empty(Isolate* isolate);
4056 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4057 // numeric and occupies one array slot.
4058 // 1. A set of properties of the scope
4059 // 2. The number of parameters. This only applies to function scopes. For
4060 // non-function scopes this is 0.
4061 // 3. The number of non-parameter variables allocated on the stack.
4062 // 4. The number of non-parameter and parameter variables allocated in the
4064 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4067 V(StackLocalCount) \
4068 V(ContextLocalCount) \
4069 V(ContextGlobalCount) \
4070 V(StrongModeFreeVariableCount)
4072 #define FIELD_ACCESSORS(name) \
4073 inline void Set##name(int value); \
4075 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4076 #undef FIELD_ACCESSORS
4079 #define DECL_INDEX(name) k##name,
4080 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4086 // The layout of the variable part of a ScopeInfo is as follows:
4087 // 1. ParameterEntries:
4088 // This part stores the names of the parameters for function scopes. One
4089 // slot is used per parameter, so in total this part occupies
4090 // ParameterCount() slots in the array. For other scopes than function
4091 // scopes ParameterCount() is 0.
4092 // 2. StackLocalFirstSlot:
4093 // Index of a first stack slot for stack local. Stack locals belonging to
4094 // this scope are located on a stack at slots starting from this index.
4095 // 3. StackLocalEntries:
4096 // Contains the names of local variables that are allocated on the stack,
4097 // in increasing order of the stack slot index. First local variable has
4098 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4099 // One slot is used per stack local, so in total this part occupies
4100 // StackLocalCount() slots in the array.
4101 // 4. ContextLocalNameEntries:
4102 // Contains the names of local variables and parameters that are allocated
4103 // in the context. They are stored in increasing order of the context slot
4104 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4105 // context local, so in total this part occupies ContextLocalCount() slots
4107 // 5. ContextLocalInfoEntries:
4108 // Contains the variable modes and initialization flags corresponding to
4109 // the context locals in ContextLocalNameEntries. One slot is used per
4110 // context local, so in total this part occupies ContextLocalCount()
4111 // slots in the array.
4112 // 6. StrongModeFreeVariableNameEntries:
4113 // Stores the names of strong mode free variables.
4114 // 7. StrongModeFreeVariablePositionEntries:
4115 // Stores the locations (start and end position) of strong mode free
4117 // 8. RecieverEntryIndex:
4118 // If the scope binds a "this" value, one slot is reserved to hold the
4119 // context or stack slot index for the variable.
4120 // 9. FunctionNameEntryIndex:
4121 // If the scope belongs to a named function expression this part contains
4122 // information about the function variable. It always occupies two array
4123 // slots: a. The name of the function variable.
4124 // b. The context or stack slot index for the variable.
4125 int ParameterEntriesIndex();
4126 int StackLocalFirstSlotIndex();
4127 int StackLocalEntriesIndex();
4128 int ContextLocalNameEntriesIndex();
4129 int ContextGlobalNameEntriesIndex();
4130 int ContextLocalInfoEntriesIndex();
4131 int ContextGlobalInfoEntriesIndex();
4132 int StrongModeFreeVariableNameEntriesIndex();
4133 int StrongModeFreeVariablePositionEntriesIndex();
4134 int ReceiverEntryIndex();
4135 int FunctionNameEntryIndex();
4137 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4138 VariableLocation* location, InitializationFlag* init_flag,
4139 MaybeAssignedFlag* maybe_assigned_flag);
4141 // Used for the function name variable for named function expressions, and for
4143 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4145 // Properties of scopes.
4146 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4147 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4148 STATIC_ASSERT(LANGUAGE_END == 3);
4149 class LanguageModeField
4150 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4151 class DeclarationScopeField
4152 : public BitField<bool, LanguageModeField::kNext, 1> {};
4153 class ReceiverVariableField
4154 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4156 class FunctionVariableField
4157 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4159 class FunctionVariableMode
4160 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4161 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4163 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4164 class HasSimpleParametersField
4165 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4166 class FunctionKindField
4167 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4169 // BitFields representing the encoded information for context locals in the
4170 // ContextLocalInfoEntries part.
4171 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4172 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4173 class ContextLocalMaybeAssignedFlag
4174 : public BitField<MaybeAssignedFlag, 4, 1> {};
4176 friend class ScopeIterator;
4180 // The cache for maps used by normalized (dictionary mode) objects.
4181 // Such maps do not have property descriptors, so a typical program
4182 // needs very limited number of distinct normalized maps.
4183 class NormalizedMapCache: public FixedArray {
4185 static Handle<NormalizedMapCache> New(Isolate* isolate);
4187 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4188 PropertyNormalizationMode mode);
4189 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4193 DECLARE_CAST(NormalizedMapCache)
4195 static inline bool IsNormalizedMapCache(const Object* obj);
4197 DECLARE_VERIFIER(NormalizedMapCache)
4199 static const int kEntries = 64;
4201 static inline int GetIndex(Handle<Map> map);
4203 // The following declarations hide base class methods.
4204 Object* get(int index);
4205 void set(int index, Object* value);
4209 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4210 // that is attached to code objects.
4211 class ByteArray: public FixedArrayBase {
4215 // Setter and getter.
4216 inline byte get(int index);
4217 inline void set(int index, byte value);
4219 // Treat contents as an int array.
4220 inline int get_int(int index);
4222 static int SizeFor(int length) {
4223 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4225 // We use byte arrays for free blocks in the heap. Given a desired size in
4226 // bytes that is a multiple of the word size and big enough to hold a byte
4227 // array, this function returns the number of elements a byte array should
4229 static int LengthFor(int size_in_bytes) {
4230 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4231 DCHECK(size_in_bytes >= kHeaderSize);
4232 return size_in_bytes - kHeaderSize;
4235 // Returns data start address.
4236 inline Address GetDataStartAddress();
4238 // Returns a pointer to the ByteArray object for a given data start address.
4239 static inline ByteArray* FromDataStartAddress(Address address);
4241 DECLARE_CAST(ByteArray)
4243 // Dispatched behavior.
4244 inline int ByteArraySize();
4245 DECLARE_PRINTER(ByteArray)
4246 DECLARE_VERIFIER(ByteArray)
4248 // Layout description.
4249 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4251 // Maximal memory consumption for a single ByteArray.
4252 static const int kMaxSize = 512 * MB;
4253 // Maximal length of a single ByteArray.
4254 static const int kMaxLength = kMaxSize - kHeaderSize;
4257 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4261 // BytecodeArray represents a sequence of interpreter bytecodes.
4262 class BytecodeArray : public FixedArrayBase {
4264 static int SizeFor(int length) {
4265 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4268 // Setter and getter
4269 inline byte get(int index);
4270 inline void set(int index, byte value);
4272 // Returns data start address.
4273 inline Address GetFirstBytecodeAddress();
4275 // Accessors for frame size.
4276 inline int frame_size() const;
4277 inline void set_frame_size(int frame_size);
4279 // Accessor for register count (derived from frame_size).
4280 inline int register_count() const;
4282 // Accessors for parameter count (including implicit 'this' receiver).
4283 inline int parameter_count() const;
4284 inline void set_parameter_count(int number_of_parameters);
4286 // Accessors for the constant pool.
4287 DECL_ACCESSORS(constant_pool, FixedArray)
4289 DECLARE_CAST(BytecodeArray)
4291 // Dispatched behavior.
4292 inline int BytecodeArraySize();
4293 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4295 DECLARE_PRINTER(BytecodeArray)
4296 DECLARE_VERIFIER(BytecodeArray)
4298 void Disassemble(std::ostream& os);
4300 // Layout description.
4301 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4302 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4303 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4304 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4306 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4308 // Maximal memory consumption for a single BytecodeArray.
4309 static const int kMaxSize = 512 * MB;
4310 // Maximal length of a single BytecodeArray.
4311 static const int kMaxLength = kMaxSize - kHeaderSize;
4314 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4318 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4319 // They look like heap objects (are heap object tagged and have a map) so that
4320 // the heap remains iterable. They have a size and a next pointer.
4321 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4322 // in the free list.
4323 class FreeSpace: public HeapObject {
4325 // [size]: size of the free space including the header.
4326 inline int size() const;
4327 inline void set_size(int value);
4329 inline int nobarrier_size() const;
4330 inline void nobarrier_set_size(int value);
4334 // Accessors for the next field.
4335 inline FreeSpace* next();
4336 inline FreeSpace** next_address();
4337 inline void set_next(FreeSpace* next);
4339 inline static FreeSpace* cast(HeapObject* obj);
4341 // Dispatched behavior.
4342 DECLARE_PRINTER(FreeSpace)
4343 DECLARE_VERIFIER(FreeSpace)
4345 // Layout description.
4346 // Size is smi tagged when it is stored.
4347 static const int kSizeOffset = HeapObject::kHeaderSize;
4348 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4351 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4355 // V has parameters (Type, type, TYPE, C type, element_size)
4356 #define TYPED_ARRAYS(V) \
4357 V(Uint8, uint8, UINT8, uint8_t, 1) \
4358 V(Int8, int8, INT8, int8_t, 1) \
4359 V(Uint16, uint16, UINT16, uint16_t, 2) \
4360 V(Int16, int16, INT16, int16_t, 2) \
4361 V(Uint32, uint32, UINT32, uint32_t, 4) \
4362 V(Int32, int32, INT32, int32_t, 4) \
4363 V(Float32, float32, FLOAT32, float, 4) \
4364 V(Float64, float64, FLOAT64, double, 8) \
4365 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4368 class FixedTypedArrayBase: public FixedArrayBase {
4370 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4371 DECL_ACCESSORS(base_pointer, Object)
4373 // [external_pointer]: Contains the offset between base_pointer and the start
4374 // of the data. If the base_pointer is a nullptr, the external_pointer
4375 // therefore points to the actual backing store.
4376 DECL_ACCESSORS(external_pointer, void)
4378 // Dispatched behavior.
4379 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4381 template <typename StaticVisitor>
4382 inline void FixedTypedArrayBaseIterateBody();
4384 DECLARE_CAST(FixedTypedArrayBase)
4386 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4387 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4388 static const int kHeaderSize =
4389 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4391 static const int kDataOffset = kHeaderSize;
4395 static inline int TypedArraySize(InstanceType type, int length);
4396 inline int TypedArraySize(InstanceType type);
4398 // Use with care: returns raw pointer into heap.
4399 inline void* DataPtr();
4401 inline int DataSize();
4404 static inline int ElementSize(InstanceType type);
4406 inline int DataSize(InstanceType type);
4408 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4412 template <class Traits>
4413 class FixedTypedArray: public FixedTypedArrayBase {
4415 typedef typename Traits::ElementType ElementType;
4416 static const InstanceType kInstanceType = Traits::kInstanceType;
4418 DECLARE_CAST(FixedTypedArray<Traits>)
4420 inline ElementType get_scalar(int index);
4421 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4422 inline void set(int index, ElementType value);
4424 static inline ElementType from_int(int value);
4425 static inline ElementType from_double(double value);
4427 // This accessor applies the correct conversion from Smi, HeapNumber
4429 inline void SetValue(uint32_t index, Object* value);
4431 DECLARE_PRINTER(FixedTypedArray)
4432 DECLARE_VERIFIER(FixedTypedArray)
4435 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4438 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4439 class Type##ArrayTraits { \
4440 public: /* NOLINT */ \
4441 typedef elementType ElementType; \
4442 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4443 static const char* Designator() { return #type " array"; } \
4444 static inline Handle<Object> ToHandle(Isolate* isolate, \
4445 elementType scalar); \
4446 static inline elementType defaultValue(); \
4449 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4451 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4453 #undef FIXED_TYPED_ARRAY_TRAITS
4456 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4457 // data for code generated by the Hydrogen/Lithium compiler. It also
4458 // contains information about functions that were inlined. If N different
4459 // functions were inlined then first N elements of the literal array will
4460 // contain these functions.
4463 class DeoptimizationInputData: public FixedArray {
4465 // Layout description. Indices in the array.
4466 static const int kTranslationByteArrayIndex = 0;
4467 static const int kInlinedFunctionCountIndex = 1;
4468 static const int kLiteralArrayIndex = 2;
4469 static const int kOsrAstIdIndex = 3;
4470 static const int kOsrPcOffsetIndex = 4;
4471 static const int kOptimizationIdIndex = 5;
4472 static const int kSharedFunctionInfoIndex = 6;
4473 static const int kWeakCellCacheIndex = 7;
4474 static const int kFirstDeoptEntryIndex = 8;
4476 // Offsets of deopt entry elements relative to the start of the entry.
4477 static const int kAstIdRawOffset = 0;
4478 static const int kTranslationIndexOffset = 1;
4479 static const int kArgumentsStackHeightOffset = 2;
4480 static const int kPcOffset = 3;
4481 static const int kDeoptEntrySize = 4;
4483 // Simple element accessors.
4484 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4485 inline type* name(); \
4486 inline void Set##name(type* value);
4488 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4489 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4490 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4491 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4492 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4493 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4494 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4495 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4497 #undef DECLARE_ELEMENT_ACCESSORS
4499 // Accessors for elements of the ith deoptimization entry.
4500 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4501 inline type* name(int i); \
4502 inline void Set##name(int i, type* value);
4504 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4505 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4506 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4507 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4509 #undef DECLARE_ENTRY_ACCESSORS
4511 inline BailoutId AstId(int i);
4513 inline void SetAstId(int i, BailoutId value);
4515 inline int DeoptCount();
4517 // Allocates a DeoptimizationInputData.
4518 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4519 int deopt_entry_count,
4520 PretenureFlag pretenure);
4522 DECLARE_CAST(DeoptimizationInputData)
4524 #ifdef ENABLE_DISASSEMBLER
4525 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4529 static int IndexForEntry(int i) {
4530 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4534 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4538 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4539 // data for code generated by the full compiler.
4540 // The format of the these objects is
4541 // [i * 2]: Ast ID for ith deoptimization.
4542 // [i * 2 + 1]: PC and state of ith deoptimization
4543 class DeoptimizationOutputData: public FixedArray {
4545 inline int DeoptPoints();
4547 inline BailoutId AstId(int index);
4549 inline void SetAstId(int index, BailoutId id);
4551 inline Smi* PcAndState(int index);
4552 inline void SetPcAndState(int index, Smi* offset);
4554 static int LengthOfFixedArray(int deopt_points) {
4555 return deopt_points * 2;
4558 // Allocates a DeoptimizationOutputData.
4559 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4560 int number_of_deopt_points,
4561 PretenureFlag pretenure);
4563 DECLARE_CAST(DeoptimizationOutputData)
4565 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4566 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4571 // HandlerTable is a fixed array containing entries for exception handlers in
4572 // the code object it is associated with. The tables comes in two flavors:
4573 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4574 // exception handler and a range representing the try-block covered by that
4575 // handler. Layout looks as follows:
4576 // [ range-start , range-end , handler-offset , stack-depth ]
4577 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4578 // per call-site that could throw an exception. Layout looks as follows:
4579 // [ return-address-offset , handler-offset ]
4580 class HandlerTable : public FixedArray {
4582 // Conservative prediction whether a given handler will locally catch an
4583 // exception or cause a re-throw to outside the code boundary. Since this is
4584 // undecidable it is merely an approximation (e.g. useful for debugger).
4585 enum CatchPrediction { UNCAUGHT, CAUGHT };
4587 // Accessors for handler table based on ranges.
4588 inline void SetRangeStart(int index, int value);
4589 inline void SetRangeEnd(int index, int value);
4590 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4591 inline void SetRangeDepth(int index, int value);
4593 // Accessors for handler table based on return addresses.
4594 inline void SetReturnOffset(int index, int value);
4595 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4597 // Lookup handler in a table based on ranges.
4598 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4600 // Lookup handler in a table based on return addresses.
4601 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4603 // Returns the required length of the underlying fixed array.
4604 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4605 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4607 DECLARE_CAST(HandlerTable)
4609 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4610 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4611 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4615 // Layout description for handler table based on ranges.
4616 static const int kRangeStartIndex = 0;
4617 static const int kRangeEndIndex = 1;
4618 static const int kRangeHandlerIndex = 2;
4619 static const int kRangeDepthIndex = 3;
4620 static const int kRangeEntrySize = 4;
4622 // Layout description for handler table based on return addresses.
4623 static const int kReturnOffsetIndex = 0;
4624 static const int kReturnHandlerIndex = 1;
4625 static const int kReturnEntrySize = 2;
4627 // Encoding of the {handler} field.
4628 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4629 class HandlerOffsetField : public BitField<int, 1, 30> {};
4633 // Code describes objects with on-the-fly generated machine code.
4634 class Code: public HeapObject {
4636 // Opaque data type for encapsulating code flags like kind, inline
4637 // cache state, and arguments count.
4638 typedef uint32_t Flags;
4640 #define NON_IC_KIND_LIST(V) \
4642 V(OPTIMIZED_FUNCTION) \
4649 #define IC_KIND_LIST(V) \
4660 #define CODE_KIND_LIST(V) \
4661 NON_IC_KIND_LIST(V) \
4665 #define DEFINE_CODE_KIND_ENUM(name) name,
4666 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4667 #undef DEFINE_CODE_KIND_ENUM
4671 // No more than 16 kinds. The value is currently encoded in four bits in
4673 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4675 static const char* Kind2String(Kind kind);
4683 static const int kPrologueOffsetNotSet = -1;
4685 #ifdef ENABLE_DISASSEMBLER
4687 static const char* ICState2String(InlineCacheState state);
4688 static const char* StubType2String(StubType type);
4689 static void PrintExtraICState(std::ostream& os, // NOLINT
4690 Kind kind, ExtraICState extra);
4691 void Disassemble(const char* name, std::ostream& os); // NOLINT
4692 #endif // ENABLE_DISASSEMBLER
4694 // [instruction_size]: Size of the native instructions
4695 inline int instruction_size() const;
4696 inline void set_instruction_size(int value);
4698 // [relocation_info]: Code relocation information
4699 DECL_ACCESSORS(relocation_info, ByteArray)
4700 void InvalidateRelocation();
4701 void InvalidateEmbeddedObjects();
4703 // [handler_table]: Fixed array containing offsets of exception handlers.
4704 DECL_ACCESSORS(handler_table, FixedArray)
4706 // [deoptimization_data]: Array containing data for deopt.
4707 DECL_ACCESSORS(deoptimization_data, FixedArray)
4709 // [raw_type_feedback_info]: This field stores various things, depending on
4710 // the kind of the code object.
4711 // FUNCTION => type feedback information.
4712 // STUB and ICs => major/minor key as Smi.
4713 DECL_ACCESSORS(raw_type_feedback_info, Object)
4714 inline Object* type_feedback_info();
4715 inline void set_type_feedback_info(
4716 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4717 inline uint32_t stub_key();
4718 inline void set_stub_key(uint32_t key);
4720 // [next_code_link]: Link for lists of optimized or deoptimized code.
4721 // Note that storage for this field is overlapped with typefeedback_info.
4722 DECL_ACCESSORS(next_code_link, Object)
4724 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4725 // field does not have to be traced during garbage collection since
4726 // it is only used by the garbage collector itself.
4727 DECL_ACCESSORS(gc_metadata, Object)
4729 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4730 // at the moment when this object was created.
4731 inline void set_ic_age(int count);
4732 inline int ic_age() const;
4734 // [prologue_offset]: Offset of the function prologue, used for aging
4735 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4736 inline int prologue_offset() const;
4737 inline void set_prologue_offset(int offset);
4739 // [constant_pool offset]: Offset of the constant pool.
4740 // Valid for FLAG_enable_embedded_constant_pool only
4741 inline int constant_pool_offset() const;
4742 inline void set_constant_pool_offset(int offset);
4744 // Unchecked accessors to be used during GC.
4745 inline ByteArray* unchecked_relocation_info();
4747 inline int relocation_size();
4749 // [flags]: Various code flags.
4750 inline Flags flags();
4751 inline void set_flags(Flags flags);
4753 // [flags]: Access to specific code flags.
4755 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4756 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4758 inline StubType type(); // Only valid for monomorphic IC stubs.
4760 // Testers for IC stub kinds.
4761 inline bool is_inline_cache_stub();
4762 inline bool is_debug_stub();
4763 inline bool is_handler();
4764 inline bool is_load_stub();
4765 inline bool is_keyed_load_stub();
4766 inline bool is_store_stub();
4767 inline bool is_keyed_store_stub();
4768 inline bool is_call_stub();
4769 inline bool is_binary_op_stub();
4770 inline bool is_compare_ic_stub();
4771 inline bool is_compare_nil_ic_stub();
4772 inline bool is_to_boolean_ic_stub();
4773 inline bool is_keyed_stub();
4774 inline bool is_optimized_code();
4775 inline bool embeds_maps_weakly();
4777 inline bool IsCodeStubOrIC();
4778 inline bool IsJavaScriptCode();
4780 inline void set_raw_kind_specific_flags1(int value);
4781 inline void set_raw_kind_specific_flags2(int value);
4783 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4784 // object was generated by either the hydrogen or the TurboFan optimizing
4785 // compiler (but it may not be an optimized function).
4786 inline bool is_crankshafted();
4787 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4788 inline void set_is_crankshafted(bool value);
4790 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4791 // code object was generated by the TurboFan optimizing compiler.
4792 inline bool is_turbofanned();
4793 inline void set_is_turbofanned(bool value);
4795 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4796 // embedded objects in code should be treated weakly.
4797 inline bool can_have_weak_objects();
4798 inline void set_can_have_weak_objects(bool value);
4800 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4801 // deoptimization support.
4802 inline bool has_deoptimization_support();
4803 inline void set_has_deoptimization_support(bool value);
4805 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4806 // been compiled with debug break slots.
4807 inline bool has_debug_break_slots();
4808 inline void set_has_debug_break_slots(bool value);
4810 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4811 // reloc info includes runtime and external references to support
4812 // serialization/deserialization.
4813 inline bool has_reloc_info_for_serialization();
4814 inline void set_has_reloc_info_for_serialization(bool value);
4816 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4817 // how long the function has been marked for OSR and therefore which
4818 // level of loop nesting we are willing to do on-stack replacement
4820 inline void set_allow_osr_at_loop_nesting_level(int level);
4821 inline int allow_osr_at_loop_nesting_level();
4823 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4824 // the code object was seen on the stack with no IC patching going on.
4825 inline int profiler_ticks();
4826 inline void set_profiler_ticks(int ticks);
4828 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4829 // For builtins, tells which builtin index it has.
4830 // Note that builtins can have a code kind other than BUILTIN, which means
4831 // that for arbitrary code objects, this index value may be random garbage.
4832 // To verify in that case, compare the code object to the indexed builtin.
4833 inline int builtin_index();
4834 inline void set_builtin_index(int id);
4836 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4837 // reserved in the code prologue.
4838 inline unsigned stack_slots();
4839 inline void set_stack_slots(unsigned slots);
4841 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4842 // the instruction stream where the safepoint table starts.
4843 inline unsigned safepoint_table_offset();
4844 inline void set_safepoint_table_offset(unsigned offset);
4846 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4847 // instruction stream where the back edge table starts.
4848 inline unsigned back_edge_table_offset();
4849 inline void set_back_edge_table_offset(unsigned offset);
4851 inline bool back_edges_patched_for_osr();
4853 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4854 inline uint16_t to_boolean_state();
4856 // [has_function_cache]: For kind STUB tells whether there is a function
4857 // cache is passed to the stub.
4858 inline bool has_function_cache();
4859 inline void set_has_function_cache(bool flag);
4862 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4863 // the code is going to be deoptimized because of dead embedded maps.
4864 inline bool marked_for_deoptimization();
4865 inline void set_marked_for_deoptimization(bool flag);
4867 // [constant_pool]: The constant pool for this function.
4868 inline Address constant_pool();
4870 // Get the safepoint entry for the given pc.
4871 SafepointEntry GetSafepointEntry(Address pc);
4873 // Find an object in a stub with a specified map
4874 Object* FindNthObject(int n, Map* match_map);
4876 // Find the first allocation site in an IC stub.
4877 AllocationSite* FindFirstAllocationSite();
4879 // Find the first map in an IC stub.
4880 Map* FindFirstMap();
4881 void FindAllMaps(MapHandleList* maps);
4883 // Find the first handler in an IC stub.
4884 Code* FindFirstHandler();
4886 // Find |length| handlers and put them into |code_list|. Returns false if not
4887 // enough handlers can be found.
4888 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4890 // Find the handler for |map|.
4891 MaybeHandle<Code> FindHandlerForMap(Map* map);
4893 // Find the first name in an IC stub.
4894 Name* FindFirstName();
4896 class FindAndReplacePattern;
4897 // For each (map-to-find, object-to-replace) pair in the pattern, this
4898 // function replaces the corresponding placeholder in the code with the
4899 // object-to-replace. The function assumes that pairs in the pattern come in
4900 // the same order as the placeholders in the code.
4901 // If the placeholder is a weak cell, then the value of weak cell is matched
4902 // against the map-to-find.
4903 void FindAndReplace(const FindAndReplacePattern& pattern);
4905 // The entire code object including its header is copied verbatim to the
4906 // snapshot so that it can be written in one, fast, memcpy during
4907 // deserialization. The deserializer will overwrite some pointers, rather
4908 // like a runtime linker, but the random allocation addresses used in the
4909 // mksnapshot process would still be present in the unlinked snapshot data,
4910 // which would make snapshot production non-reproducible. This method wipes
4911 // out the to-be-overwritten header data for reproducible snapshots.
4912 inline void WipeOutHeader();
4914 // Flags operations.
4915 static inline Flags ComputeFlags(
4916 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4917 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4918 CacheHolderFlag holder = kCacheOnReceiver);
4920 static inline Flags ComputeMonomorphicFlags(
4921 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4922 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4924 static inline Flags ComputeHandlerFlags(
4925 Kind handler_kind, StubType type = NORMAL,
4926 CacheHolderFlag holder = kCacheOnReceiver);
4928 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4929 static inline StubType ExtractTypeFromFlags(Flags flags);
4930 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4931 static inline Kind ExtractKindFromFlags(Flags flags);
4932 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4934 static inline Flags RemoveTypeFromFlags(Flags flags);
4935 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4937 // Convert a target address into a code object.
4938 static inline Code* GetCodeFromTargetAddress(Address address);
4940 // Convert an entry address into an object.
4941 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4943 // Returns the address of the first instruction.
4944 inline byte* instruction_start();
4946 // Returns the address right after the last instruction.
4947 inline byte* instruction_end();
4949 // Returns the size of the instructions, padding, and relocation information.
4950 inline int body_size();
4952 // Returns the address of the first relocation info (read backwards!).
4953 inline byte* relocation_start();
4955 // Code entry point.
4956 inline byte* entry();
4958 // Returns true if pc is inside this object's instructions.
4959 inline bool contains(byte* pc);
4961 // Relocate the code by delta bytes. Called to signal that this code
4962 // object has been moved by delta bytes.
4963 void Relocate(intptr_t delta);
4965 // Migrate code described by desc.
4966 void CopyFrom(const CodeDesc& desc);
4968 // Returns the object size for a given body (used for allocation).
4969 static int SizeFor(int body_size) {
4970 DCHECK_SIZE_TAG_ALIGNED(body_size);
4971 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4974 // Calculate the size of the code object to report for log events. This takes
4975 // the layout of the code object into account.
4976 inline int ExecutableSize();
4978 // Locating source position.
4979 int SourcePosition(Address pc);
4980 int SourceStatementPosition(Address pc);
4984 // Dispatched behavior.
4985 inline int CodeSize();
4986 inline void CodeIterateBody(ObjectVisitor* v);
4988 template<typename StaticVisitor>
4989 inline void CodeIterateBody(Heap* heap);
4991 DECLARE_PRINTER(Code)
4992 DECLARE_VERIFIER(Code)
4994 void ClearInlineCaches();
4995 void ClearInlineCaches(Kind kind);
4997 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4998 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5000 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5002 kToBeExecutedOnceCodeAge = -3,
5003 kNotExecutedCodeAge = -2,
5004 kExecutedOnceCodeAge = -1,
5006 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5008 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5009 kLastCodeAge = kAfterLastCodeAge - 1,
5010 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5011 kIsOldCodeAge = kSexagenarianCodeAge,
5012 kPreAgedCodeAge = kIsOldCodeAge - 1
5014 #undef DECLARE_CODE_AGE_ENUM
5016 // Code aging. Indicates how many full GCs this code has survived without
5017 // being entered through the prologue. Used to determine when it is
5018 // relatively safe to flush this code object and replace it with the lazy
5019 // compilation stub.
5020 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5021 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5022 void MakeYoung(Isolate* isolate);
5023 void MarkToBeExecutedOnce(Isolate* isolate);
5024 void MakeOlder(MarkingParity);
5025 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5028 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5029 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5032 void PrintDeoptLocation(FILE* out, Address pc);
5033 bool CanDeoptAt(Address pc);
5036 void VerifyEmbeddedObjectsDependency();
5040 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5041 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5042 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
5045 inline bool CanContainWeakObjects();
5047 inline bool IsWeakObject(Object* object);
5049 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5051 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5052 WeakCell* CachedWeakCell();
5054 // Max loop nesting marker used to postpose OSR. We don't take loop
5055 // nesting that is deeper than 5 levels into account.
5056 static const int kMaxLoopNestingMarker = 6;
5058 static const int kConstantPoolSize =
5059 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5061 // Layout description.
5062 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5063 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5064 static const int kDeoptimizationDataOffset =
5065 kHandlerTableOffset + kPointerSize;
5066 // For FUNCTION kind, we store the type feedback info here.
5067 static const int kTypeFeedbackInfoOffset =
5068 kDeoptimizationDataOffset + kPointerSize;
5069 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5070 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5071 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5072 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5073 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5074 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5075 static const int kKindSpecificFlags2Offset =
5076 kKindSpecificFlags1Offset + kIntSize;
5077 // Note: We might be able to squeeze this into the flags above.
5078 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5079 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5080 static const int kHeaderPaddingStart =
5081 kConstantPoolOffset + kConstantPoolSize;
5083 // Add padding to align the instruction start following right after
5084 // the Code object header.
5085 static const int kHeaderSize =
5086 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5088 // Byte offsets within kKindSpecificFlags1Offset.
5089 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5090 class FullCodeFlagsHasDeoptimizationSupportField:
5091 public BitField<bool, 0, 1> {}; // NOLINT
5092 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5093 class FullCodeFlagsHasRelocInfoForSerialization
5094 : public BitField<bool, 2, 1> {};
5095 // Bit 3 in this bitfield is unused.
5096 class ProfilerTicksField : public BitField<int, 4, 28> {};
5098 // Flags layout. BitField<type, shift, size>.
5099 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5100 class TypeField : public BitField<StubType, 4, 1> {};
5101 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5102 class KindField : public BitField<Kind, 7, 4> {};
5103 class ExtraICStateField: public BitField<ExtraICState, 11,
5104 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5106 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5107 static const int kStackSlotsFirstBit = 0;
5108 static const int kStackSlotsBitCount = 24;
5109 static const int kHasFunctionCacheBit =
5110 kStackSlotsFirstBit + kStackSlotsBitCount;
5111 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5112 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5113 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5115 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5116 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5118 class StackSlotsField: public BitField<int,
5119 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5120 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5122 class MarkedForDeoptimizationField
5123 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5124 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5126 class CanHaveWeakObjectsField
5127 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5129 // KindSpecificFlags2 layout (ALL)
5130 static const int kIsCrankshaftedBit = 0;
5131 class IsCrankshaftedField: public BitField<bool,
5132 kIsCrankshaftedBit, 1> {}; // NOLINT
5134 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5135 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5136 static const int kSafepointTableOffsetBitCount = 30;
5138 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5139 kSafepointTableOffsetBitCount <= 32);
5140 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5142 class SafepointTableOffsetField: public BitField<int,
5143 kSafepointTableOffsetFirstBit,
5144 kSafepointTableOffsetBitCount> {}; // NOLINT
5146 // KindSpecificFlags2 layout (FUNCTION)
5147 class BackEdgeTableOffsetField: public BitField<int,
5148 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5149 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5150 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5151 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5153 static const int kArgumentsBits = 16;
5154 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5156 // This constant should be encodable in an ARM instruction.
5157 static const int kFlagsNotUsedInLookup =
5158 TypeField::kMask | CacheHolderField::kMask;
5161 friend class RelocIterator;
5162 friend class Deoptimizer; // For FindCodeAgeSequence.
5164 void ClearInlineCaches(Kind* kind);
5167 byte* FindCodeAgeSequence();
5168 static void GetCodeAgeAndParity(Code* code, Age* age,
5169 MarkingParity* parity);
5170 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5171 MarkingParity* parity);
5172 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5174 // Code aging -- platform-specific
5175 static void PatchPlatformCodeAge(Isolate* isolate,
5176 byte* sequence, Age age,
5177 MarkingParity parity);
5179 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5183 // This class describes the layout of dependent codes array of a map. The
5184 // array is partitioned into several groups of dependent codes. Each group
5185 // contains codes with the same dependency on the map. The array has the
5186 // following layout for n dependency groups:
5188 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5189 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5190 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5192 // The first n elements are Smis, each of them specifies the number of codes
5193 // in the corresponding group. The subsequent elements contain grouped code
5194 // objects in weak cells. The suffix of the array can be filled with the
5195 // undefined value if the number of codes is less than the length of the
5196 // array. The order of the code objects within a group is not preserved.
5198 // All code indexes used in the class are counted starting from the first
5199 // code object of the first group. In other words, code index 0 corresponds
5200 // to array index n = kCodesStartIndex.
5202 class DependentCode: public FixedArray {
5204 enum DependencyGroup {
5205 // Group of code that weakly embed this map and depend on being
5206 // deoptimized when the map is garbage collected.
5208 // Group of code that embed a transition to this map, and depend on being
5209 // deoptimized when the transition is replaced by a new version.
5211 // Group of code that omit run-time prototype checks for prototypes
5212 // described by this map. The group is deoptimized whenever an object
5213 // described by this map changes shape (and transitions to a new map),
5214 // possibly invalidating the assumptions embedded in the code.
5215 kPrototypeCheckGroup,
5216 // Group of code that depends on global property values in property cells
5217 // not being changed.
5218 kPropertyCellChangedGroup,
5219 // Group of code that omit run-time type checks for the field(s) introduced
5222 // Group of code that omit run-time type checks for initial maps of
5224 kInitialMapChangedGroup,
5225 // Group of code that depends on tenuring information in AllocationSites
5226 // not being changed.
5227 kAllocationSiteTenuringChangedGroup,
5228 // Group of code that depends on element transition information in
5229 // AllocationSites not being changed.
5230 kAllocationSiteTransitionChangedGroup
5233 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5235 // Array for holding the index of the first code object of each group.
5236 // The last element stores the total number of code objects.
5237 class GroupStartIndexes {
5239 explicit GroupStartIndexes(DependentCode* entries);
5240 void Recompute(DependentCode* entries);
5241 int at(int i) { return start_indexes_[i]; }
5242 int number_of_entries() { return start_indexes_[kGroupCount]; }
5244 int start_indexes_[kGroupCount + 1];
5247 bool Contains(DependencyGroup group, WeakCell* code_cell);
5249 static Handle<DependentCode> InsertCompilationDependencies(
5250 Handle<DependentCode> entries, DependencyGroup group,
5251 Handle<Foreign> info);
5253 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5254 DependencyGroup group,
5255 Handle<WeakCell> code_cell);
5257 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5258 WeakCell* code_cell);
5260 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5263 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5264 DependentCode::DependencyGroup group);
5266 bool MarkCodeForDeoptimization(Isolate* isolate,
5267 DependentCode::DependencyGroup group);
5269 // The following low-level accessors should only be used by this class
5270 // and the mark compact collector.
5271 inline int number_of_entries(DependencyGroup group);
5272 inline void set_number_of_entries(DependencyGroup group, int value);
5273 inline Object* object_at(int i);
5274 inline void set_object_at(int i, Object* object);
5275 inline void clear_at(int i);
5276 inline void copy(int from, int to);
5277 DECLARE_CAST(DependentCode)
5279 static const char* DependencyGroupName(DependencyGroup group);
5280 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5283 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5284 DependencyGroup group,
5285 Handle<Object> object);
5286 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5287 // Make a room at the end of the given group by moving out the first
5288 // code objects of the subsequent groups.
5289 inline void ExtendGroup(DependencyGroup group);
5290 // Compact by removing cleared weak cells and return true if there was
5291 // any cleared weak cell.
5293 static int Grow(int number_of_entries) {
5294 if (number_of_entries < 5) return number_of_entries + 1;
5295 return number_of_entries * 5 / 4;
5297 static const int kCodesStartIndex = kGroupCount;
5301 class PrototypeInfo;
5304 // All heap objects have a Map that describes their structure.
5305 // A Map contains information about:
5306 // - Size information about the object
5307 // - How to iterate over an object (for garbage collection)
5308 class Map: public HeapObject {
5311 // Size in bytes or kVariableSizeSentinel if instances do not have
5313 inline int instance_size();
5314 inline void set_instance_size(int value);
5316 // Only to clear an unused byte, remove once byte is used.
5317 inline void clear_unused();
5319 // [inobject_properties_or_constructor_function_index]: Provides access
5320 // to the inobject properties in case of JSObject maps, or the constructor
5321 // function index in case of primitive maps.
5322 inline int inobject_properties_or_constructor_function_index();
5323 inline void set_inobject_properties_or_constructor_function_index(int value);
5324 // Count of properties allocated in the object (JSObject only).
5325 inline int GetInObjectProperties();
5326 inline void SetInObjectProperties(int value);
5327 // Index of the constructor function in the native context (primitives only),
5328 // or the special sentinel value to indicate that there is no object wrapper
5329 // for the primitive (i.e. in case of null or undefined).
5330 static const int kNoConstructorFunctionIndex = 0;
5331 inline int GetConstructorFunctionIndex();
5332 inline void SetConstructorFunctionIndex(int value);
5335 inline InstanceType instance_type();
5336 inline void set_instance_type(InstanceType value);
5338 // Tells how many unused property fields are available in the
5339 // instance (only used for JSObject in fast mode).
5340 inline int unused_property_fields();
5341 inline void set_unused_property_fields(int value);
5344 inline byte bit_field() const;
5345 inline void set_bit_field(byte value);
5348 inline byte bit_field2() const;
5349 inline void set_bit_field2(byte value);
5352 inline uint32_t bit_field3() const;
5353 inline void set_bit_field3(uint32_t bits);
5355 class EnumLengthBits: public BitField<int,
5356 0, kDescriptorIndexBitCount> {}; // NOLINT
5357 class NumberOfOwnDescriptorsBits: public BitField<int,
5358 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5359 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5360 class DictionaryMap : public BitField<bool, 20, 1> {};
5361 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5362 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5363 class Deprecated : public BitField<bool, 23, 1> {};
5364 class IsUnstable : public BitField<bool, 24, 1> {};
5365 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5366 class IsStrong : public BitField<bool, 26, 1> {};
5369 // Keep this bit field at the very end for better code in
5370 // Builtins::kJSConstructStubGeneric stub.
5371 // This counter is used for in-object slack tracking and for map aging.
5372 // The in-object slack tracking is considered enabled when the counter is
5373 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5374 class Counter : public BitField<int, 28, 4> {};
5375 static const int kSlackTrackingCounterStart = 14;
5376 static const int kSlackTrackingCounterEnd = 8;
5377 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5378 static const int kRetainingCounterEnd = 0;
5380 // Tells whether the object in the prototype property will be used
5381 // for instances created from this function. If the prototype
5382 // property is set to a value that is not a JSObject, the prototype
5383 // property will not be used to create instances of the function.
5384 // See ECMA-262, 13.2.2.
5385 inline void set_non_instance_prototype(bool value);
5386 inline bool has_non_instance_prototype();
5388 // Tells whether the instance has a [[Construct]] internal method.
5389 // This property is implemented according to ES6, section 7.2.4.
5390 inline void set_is_constructor(bool value);
5391 inline bool is_constructor() const;
5393 // Tells whether the instance with this map should be ignored by the
5394 // Object.getPrototypeOf() function and the __proto__ accessor.
5395 inline void set_is_hidden_prototype();
5396 inline bool is_hidden_prototype() const;
5398 // Records and queries whether the instance has a named interceptor.
5399 inline void set_has_named_interceptor();
5400 inline bool has_named_interceptor();
5402 // Records and queries whether the instance has an indexed interceptor.
5403 inline void set_has_indexed_interceptor();
5404 inline bool has_indexed_interceptor();
5406 // Tells whether the instance is undetectable.
5407 // An undetectable object is a special class of JSObject: 'typeof' operator
5408 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5409 // a normal JS object. It is useful for implementing undetectable
5410 // document.all in Firefox & Safari.
5411 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5412 inline void set_is_undetectable();
5413 inline bool is_undetectable();
5415 // Tells whether the instance has a call-as-function handler.
5416 inline void set_is_observed();
5417 inline bool is_observed();
5419 // Tells whether the instance has a [[Call]] internal method.
5420 // This property is implemented according to ES6, section 7.2.3.
5421 inline void set_is_callable();
5422 inline bool is_callable() const;
5424 inline void set_is_strong();
5425 inline bool is_strong();
5426 inline void set_is_extensible(bool value);
5427 inline bool is_extensible();
5428 inline void set_is_prototype_map(bool value);
5429 inline bool is_prototype_map() const;
5431 inline void set_elements_kind(ElementsKind elements_kind);
5432 inline ElementsKind elements_kind();
5434 // Tells whether the instance has fast elements that are only Smis.
5435 inline bool has_fast_smi_elements();
5437 // Tells whether the instance has fast elements.
5438 inline bool has_fast_object_elements();
5439 inline bool has_fast_smi_or_object_elements();
5440 inline bool has_fast_double_elements();
5441 inline bool has_fast_elements();
5442 inline bool has_sloppy_arguments_elements();
5443 inline bool has_fixed_typed_array_elements();
5444 inline bool has_dictionary_elements();
5446 static bool IsValidElementsTransition(ElementsKind from_kind,
5447 ElementsKind to_kind);
5449 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5450 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5451 bool DictionaryElementsInPrototypeChainOnly();
5453 inline Map* ElementsTransitionMap();
5455 inline FixedArrayBase* GetInitialElements();
5457 // [raw_transitions]: Provides access to the transitions storage field.
5458 // Don't call set_raw_transitions() directly to overwrite transitions, use
5459 // the TransitionArray::ReplaceTransitions() wrapper instead!
5460 DECL_ACCESSORS(raw_transitions, Object)
5461 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5462 // (which prototype maps don't have).
5463 DECL_ACCESSORS(prototype_info, Object)
5464 // PrototypeInfo is created lazily using this helper (which installs it on
5465 // the given prototype's map).
5466 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5467 Handle<JSObject> prototype, Isolate* isolate);
5468 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5469 Handle<Map> prototype_map, Isolate* isolate);
5471 // [prototype chain validity cell]: Associated with a prototype object,
5472 // stored in that object's map's PrototypeInfo, indicates that prototype
5473 // chains through this object are currently valid. The cell will be
5474 // invalidated and replaced when the prototype chain changes.
5475 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5477 static const int kPrototypeChainValid = 0;
5478 static const int kPrototypeChainInvalid = 1;
5481 Map* FindFieldOwner(int descriptor);
5483 inline int GetInObjectPropertyOffset(int index);
5485 int NumberOfFields();
5487 // TODO(ishell): candidate with JSObject::MigrateToMap().
5488 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5489 int target_inobject, int target_unused,
5490 int* old_number_of_fields);
5491 // TODO(ishell): moveit!
5492 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5493 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5494 Representation rep1, Handle<HeapType> type1, Representation rep2,
5495 Handle<HeapType> type2, Isolate* isolate);
5496 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5497 Representation new_representation,
5498 Handle<HeapType> new_field_type);
5499 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5500 PropertyKind new_kind,
5501 PropertyAttributes new_attributes,
5502 Representation new_representation,
5503 Handle<HeapType> new_field_type,
5504 StoreMode store_mode);
5505 static Handle<Map> CopyGeneralizeAllRepresentations(
5506 Handle<Map> map, int modify_index, StoreMode store_mode,
5507 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5509 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5510 int descriptor_number,
5511 Handle<Object> value);
5513 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5514 const char* reason);
5516 // Returns the constructor name (the name (possibly, inferred name) of the
5517 // function that was used to instantiate the object).
5518 String* constructor_name();
5520 // Tells whether the map is used for JSObjects in dictionary mode (ie
5521 // normalized objects, ie objects for which HasFastProperties returns false).
5522 // A map can never be used for both dictionary mode and fast mode JSObjects.
5523 // False by default and for HeapObjects that are not JSObjects.
5524 inline void set_dictionary_map(bool value);
5525 inline bool is_dictionary_map();
5527 // Tells whether the instance needs security checks when accessing its
5529 inline void set_is_access_check_needed(bool access_check_needed);
5530 inline bool is_access_check_needed();
5532 // Returns true if map has a non-empty stub code cache.
5533 inline bool has_code_cache();
5535 // [prototype]: implicit prototype object.
5536 DECL_ACCESSORS(prototype, Object)
5537 // TODO(jkummerow): make set_prototype private.
5538 static void SetPrototype(
5539 Handle<Map> map, Handle<Object> prototype,
5540 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5542 // [constructor]: points back to the function responsible for this map.
5543 // The field overlaps with the back pointer. All maps in a transition tree
5544 // have the same constructor, so maps with back pointers can walk the
5545 // back pointer chain until they find the map holding their constructor.
5546 DECL_ACCESSORS(constructor_or_backpointer, Object)
5547 inline Object* GetConstructor() const;
5548 inline void SetConstructor(Object* constructor,
5549 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5550 // [back pointer]: points back to the parent map from which a transition
5551 // leads to this map. The field overlaps with the constructor (see above).
5552 inline Object* GetBackPointer();
5553 inline void SetBackPointer(Object* value,
5554 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5556 // [instance descriptors]: describes the object.
5557 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5559 // [layout descriptor]: describes the object layout.
5560 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5561 // |layout descriptor| accessor which can be used from GC.
5562 inline LayoutDescriptor* layout_descriptor_gc_safe();
5563 inline bool HasFastPointerLayout() const;
5565 // |layout descriptor| accessor that is safe to call even when
5566 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5567 // |layout_descriptor| field at all).
5568 inline LayoutDescriptor* GetLayoutDescriptor();
5570 inline void UpdateDescriptors(DescriptorArray* descriptors,
5571 LayoutDescriptor* layout_descriptor);
5572 inline void InitializeDescriptors(DescriptorArray* descriptors,
5573 LayoutDescriptor* layout_descriptor);
5575 // [stub cache]: contains stubs compiled for this map.
5576 DECL_ACCESSORS(code_cache, Object)
5578 // [dependent code]: list of optimized codes that weakly embed this map.
5579 DECL_ACCESSORS(dependent_code, DependentCode)
5581 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5582 DECL_ACCESSORS(weak_cell_cache, Object)
5584 inline PropertyDetails GetLastDescriptorDetails();
5586 inline int LastAdded();
5588 inline int NumberOfOwnDescriptors();
5589 inline void SetNumberOfOwnDescriptors(int number);
5591 inline Cell* RetrieveDescriptorsPointer();
5593 inline int EnumLength();
5594 inline void SetEnumLength(int length);
5596 inline bool owns_descriptors();
5597 inline void set_owns_descriptors(bool owns_descriptors);
5598 inline void mark_unstable();
5599 inline bool is_stable();
5600 inline void set_migration_target(bool value);
5601 inline bool is_migration_target();
5602 inline void set_counter(int value);
5603 inline int counter();
5604 inline void deprecate();
5605 inline bool is_deprecated();
5606 inline bool CanBeDeprecated();
5607 // Returns a non-deprecated version of the input. If the input was not
5608 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5609 // is found by re-transitioning from the root of the transition tree using the
5610 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5612 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5614 // Returns a non-deprecated version of the input. This method may deprecate
5615 // existing maps along the way if encodings conflict. Not for use while
5616 // gathering type feedback. Use TryUpdate in those cases instead.
5617 static Handle<Map> Update(Handle<Map> map);
5619 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5620 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5621 Descriptor* descriptor,
5622 TransitionFlag flag);
5624 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5627 Handle<HeapType> type,
5628 PropertyAttributes attributes,
5629 Representation representation,
5630 TransitionFlag flag);
5632 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5635 Handle<Object> constant,
5636 PropertyAttributes attributes,
5637 TransitionFlag flag);
5639 // Returns a new map with all transitions dropped from the given map and
5640 // the ElementsKind set.
5641 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5642 ElementsKind to_kind);
5644 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5646 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5648 TransitionFlag flag);
5650 static Handle<Map> CopyForObserved(Handle<Map> map);
5652 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5653 PropertyAttributes attrs_to_add,
5654 Handle<Symbol> transition_marker,
5655 const char* reason);
5657 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5660 // Maximal number of fast properties. Used to restrict the number of map
5661 // transitions to avoid an explosion in the number of maps for objects used as
5663 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5664 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5666 Handle<Object> value,
5667 PropertyAttributes attributes,
5668 StoreFromKeyed store_mode);
5669 static Handle<Map> TransitionToAccessorProperty(
5670 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5671 Handle<Object> accessor, PropertyAttributes attributes);
5672 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5675 PropertyAttributes attributes);
5677 inline void AppendDescriptor(Descriptor* desc);
5679 // Returns a copy of the map, prepared for inserting into the transition
5680 // tree (if the |map| owns descriptors then the new one will share
5681 // descriptors with |map|).
5682 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5684 // Returns a copy of the map, with all transitions dropped from the
5685 // instance descriptors.
5686 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5687 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5689 // Returns the next free property index (only valid for FAST MODE).
5690 int NextFreePropertyIndex();
5692 // Returns the number of properties described in instance_descriptors
5693 // filtering out properties with the specified attributes.
5694 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5695 PropertyAttributes filter = NONE);
5699 // Code cache operations.
5701 // Clears the code cache.
5702 inline void ClearCodeCache(Heap* heap);
5704 // Update code cache.
5705 static void UpdateCodeCache(Handle<Map> map,
5709 // Extend the descriptor array of the map with the list of descriptors.
5710 // In case of duplicates, the latest descriptor is used.
5711 static void AppendCallbackDescriptors(Handle<Map> map,
5712 Handle<Object> descriptors);
5714 static inline int SlackForArraySize(int old_size, int size_limit);
5716 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5718 // Returns the found code or undefined if absent.
5719 Object* FindInCodeCache(Name* name, Code::Flags flags);
5721 // Returns the non-negative index of the code object if it is in the
5722 // cache and -1 otherwise.
5723 int IndexInCodeCache(Object* name, Code* code);
5725 // Removes a code object from the code cache at the given index.
5726 void RemoveFromCodeCache(Name* name, Code* code, int index);
5728 // Computes a hash value for this map, to be used in HashTables and such.
5731 // Returns the map that this map transitions to if its elements_kind
5732 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5733 // |safe_to_add_transitions| is set to false if adding transitions is not
5735 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5737 // Returns the transitioned map for this map with the most generic
5738 // elements_kind that's found in |candidates|, or null handle if no match is
5740 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5741 MapHandleList* candidates);
5743 inline bool CanTransition();
5745 inline bool IsPrimitiveMap();
5746 inline bool IsJSObjectMap();
5747 inline bool IsJSArrayMap();
5748 inline bool IsJSFunctionMap();
5749 inline bool IsStringMap();
5750 inline bool IsJSProxyMap();
5751 inline bool IsJSGlobalProxyMap();
5752 inline bool IsJSGlobalObjectMap();
5753 inline bool IsGlobalObjectMap();
5755 inline bool CanOmitMapChecks();
5757 static void AddDependentCode(Handle<Map> map,
5758 DependentCode::DependencyGroup group,
5761 bool IsMapInArrayPrototypeChain();
5763 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5765 // Dispatched behavior.
5766 DECLARE_PRINTER(Map)
5767 DECLARE_VERIFIER(Map)
5770 void DictionaryMapVerify();
5771 void VerifyOmittedMapChecks();
5774 inline int visitor_id();
5775 inline void set_visitor_id(int visitor_id);
5777 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5778 Handle<Object> prototype,
5779 PrototypeOptimizationMode mode);
5781 static const int kMaxPreAllocatedPropertyFields = 255;
5783 // Layout description.
5784 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5785 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5786 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5787 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5788 static const int kConstructorOrBackPointerOffset =
5789 kPrototypeOffset + kPointerSize;
5790 // When there is only one transition, it is stored directly in this field;
5791 // otherwise a transition array is used.
5792 // For prototype maps, this slot is used to store this map's PrototypeInfo
5794 static const int kTransitionsOrPrototypeInfoOffset =
5795 kConstructorOrBackPointerOffset + kPointerSize;
5796 static const int kDescriptorsOffset =
5797 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5798 #if V8_DOUBLE_FIELDS_UNBOXING
5799 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5800 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5802 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5803 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5805 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5806 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5807 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5809 // Layout of pointer fields. Heap iteration code relies on them
5810 // being continuously allocated.
5811 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5812 static const int kPointerFieldsEndOffset = kSize;
5814 // Byte offsets within kInstanceSizesOffset.
5815 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5816 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5817 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5818 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5819 // Note there is one byte available for use here.
5820 static const int kUnusedByte = 2;
5821 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5822 static const int kVisitorIdByte = 3;
5823 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5825 // Byte offsets within kInstanceAttributesOffset attributes.
5826 #if V8_TARGET_LITTLE_ENDIAN
5827 // Order instance type and bit field together such that they can be loaded
5828 // together as a 16-bit word with instance type in the lower 8 bits regardless
5829 // of endianess. Also provide endian-independent offset to that 16-bit word.
5830 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5831 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5833 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5834 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5836 static const int kInstanceTypeAndBitFieldOffset =
5837 kInstanceAttributesOffset + 0;
5838 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5839 static const int kUnusedPropertyFieldsByte = 3;
5840 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5842 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5843 Internals::kMapInstanceTypeAndBitFieldOffset);
5845 // Bit positions for bit field.
5846 static const int kHasNonInstancePrototype = 0;
5847 static const int kIsCallable = 1;
5848 static const int kHasNamedInterceptor = 2;
5849 static const int kHasIndexedInterceptor = 3;
5850 static const int kIsUndetectable = 4;
5851 static const int kIsObserved = 5;
5852 static const int kIsAccessCheckNeeded = 6;
5853 static const int kIsConstructor = 7;
5855 // Bit positions for bit field 2
5856 static const int kIsExtensible = 0;
5858 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5859 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5861 // Derived values from bit field 2
5862 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5863 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5864 static const int8_t kMaximumBitField2FastSmiElementValue =
5865 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5866 Map::ElementsKindBits::kShift) - 1;
5867 static const int8_t kMaximumBitField2FastHoleyElementValue =
5868 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5869 Map::ElementsKindBits::kShift) - 1;
5870 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5871 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5872 Map::ElementsKindBits::kShift) - 1;
5874 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5875 kPointerFieldsEndOffset,
5876 kSize> BodyDescriptor;
5878 // Compares this map to another to see if they describe equivalent objects.
5879 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5880 // it had exactly zero inobject properties.
5881 // The "shared" flags of both this map and |other| are ignored.
5882 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5884 // Returns true if given field is unboxed double.
5885 inline bool IsUnboxedDoubleField(FieldIndex index);
5888 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5889 static void TraceAllTransitions(Map* map);
5892 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5893 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5894 Handle<LayoutDescriptor> layout_descriptor);
5897 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5898 Handle<Name> name, SimpleTransitionFlag flag);
5900 bool EquivalentToForTransition(Map* other);
5901 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5902 static Handle<Map> ShareDescriptor(Handle<Map> map,
5903 Handle<DescriptorArray> descriptors,
5904 Descriptor* descriptor);
5905 static Handle<Map> CopyInstallDescriptors(
5906 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5907 Handle<LayoutDescriptor> layout_descriptor);
5908 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5909 Descriptor* descriptor,
5910 TransitionFlag flag);
5911 static Handle<Map> CopyReplaceDescriptors(
5912 Handle<Map> map, Handle<DescriptorArray> descriptors,
5913 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5914 MaybeHandle<Name> maybe_name, const char* reason,
5915 SimpleTransitionFlag simple_flag);
5917 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5918 Handle<DescriptorArray> descriptors,
5919 Descriptor* descriptor,
5921 TransitionFlag flag);
5922 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5923 Handle<Map> map, int descriptor, PropertyKind kind,
5924 PropertyAttributes attributes, const char** reason);
5926 static Handle<Map> CopyNormalized(Handle<Map> map,
5927 PropertyNormalizationMode mode);
5929 // Fires when the layout of an object with a leaf map changes.
5930 // This includes adding transitions to the leaf map or changing
5931 // the descriptor array.
5932 inline void NotifyLeafMapLayoutChange();
5934 void DeprecateTransitionTree();
5935 bool DeprecateTarget(PropertyKind kind, Name* key,
5936 PropertyAttributes attributes,
5937 DescriptorArray* new_descriptors,
5938 LayoutDescriptor* new_layout_descriptor);
5940 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5942 // Update field type of the given descriptor to new representation and new
5943 // type. The type must be prepared for storing in descriptor array:
5944 // it must be either a simple type or a map wrapped in a weak cell.
5945 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5946 Representation new_representation,
5947 Handle<Object> new_wrapped_type);
5949 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5950 PropertyAttributes attributes);
5951 void PrintGeneralization(FILE* file,
5956 bool constant_to_field,
5957 Representation old_representation,
5958 Representation new_representation,
5959 HeapType* old_field_type,
5960 HeapType* new_field_type);
5962 static const int kFastPropertiesSoftLimit = 12;
5963 static const int kMaxFastProperties = 128;
5965 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5969 // An abstract superclass, a marker class really, for simple structure classes.
5970 // It doesn't carry much functionality but allows struct classes to be
5971 // identified in the type system.
5972 class Struct: public HeapObject {
5974 inline void InitializeBody(int object_size);
5975 DECLARE_CAST(Struct)
5979 // A simple one-element struct, useful where smis need to be boxed.
5980 class Box : public Struct {
5982 // [value]: the boxed contents.
5983 DECL_ACCESSORS(value, Object)
5987 // Dispatched behavior.
5988 DECLARE_PRINTER(Box)
5989 DECLARE_VERIFIER(Box)
5991 static const int kValueOffset = HeapObject::kHeaderSize;
5992 static const int kSize = kValueOffset + kPointerSize;
5995 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5999 // Container for metadata stored on each prototype map.
6000 class PrototypeInfo : public Struct {
6002 static const int UNREGISTERED = -1;
6004 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6005 // or Smi(0) if uninitialized.
6006 DECL_ACCESSORS(prototype_users, Object)
6007 // [registry_slot]: Slot in prototype's user registry where this user
6008 // is stored. Returns UNREGISTERED if this prototype has not been registered.
6009 inline int registry_slot() const;
6010 inline void set_registry_slot(int slot);
6011 // [validity_cell]: Cell containing the validity bit for prototype chains
6012 // going through this object, or Smi(0) if uninitialized.
6013 // When a prototype object changes its map, then both its own validity cell
6014 // and those of all "downstream" prototypes are invalidated; handlers for a
6015 // given receiver embed the currently valid cell for that receiver's prototype
6016 // during their compilation and check it on execution.
6017 DECL_ACCESSORS(validity_cell, Object)
6018 // [constructor_name]: User-friendly name of the original constructor.
6019 DECL_ACCESSORS(constructor_name, Object)
6021 DECLARE_CAST(PrototypeInfo)
6023 // Dispatched behavior.
6024 DECLARE_PRINTER(PrototypeInfo)
6025 DECLARE_VERIFIER(PrototypeInfo)
6027 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6028 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
6029 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
6030 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6031 static const int kSize = kConstructorNameOffset + kPointerSize;
6034 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6038 // Pair used to store both a ScopeInfo and an extension object in the extension
6039 // slot of a block context. Needed in the rare case where a declaration block
6040 // scope (a "varblock" as used to desugar parameter destructuring) also contains
6041 // a sloppy direct eval. (In no other case both are needed at the same time.)
6042 class SloppyBlockWithEvalContextExtension : public Struct {
6044 // [scope_info]: Scope info.
6045 DECL_ACCESSORS(scope_info, ScopeInfo)
6046 // [extension]: Extension object.
6047 DECL_ACCESSORS(extension, JSObject)
6049 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
6051 // Dispatched behavior.
6052 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
6053 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
6055 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
6056 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
6057 static const int kSize = kExtensionOffset + kPointerSize;
6060 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
6064 // Script describes a script which has been added to the VM.
6065 class Script: public Struct {
6074 // Script compilation types.
6075 enum CompilationType {
6076 COMPILATION_TYPE_HOST = 0,
6077 COMPILATION_TYPE_EVAL = 1
6080 // Script compilation state.
6081 enum CompilationState {
6082 COMPILATION_STATE_INITIAL = 0,
6083 COMPILATION_STATE_COMPILED = 1
6086 // [source]: the script source.
6087 DECL_ACCESSORS(source, Object)
6089 // [name]: the script name.
6090 DECL_ACCESSORS(name, Object)
6092 // [id]: the script id.
6093 DECL_INT_ACCESSORS(id)
6095 // [line_offset]: script line offset in resource from where it was extracted.
6096 DECL_INT_ACCESSORS(line_offset)
6098 // [column_offset]: script column offset in resource from where it was
6100 DECL_INT_ACCESSORS(column_offset)
6102 // [context_data]: context data for the context this script was compiled in.
6103 DECL_ACCESSORS(context_data, Object)
6105 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6106 DECL_ACCESSORS(wrapper, HeapObject)
6108 // [type]: the script type.
6109 DECL_INT_ACCESSORS(type)
6111 // [line_ends]: FixedArray of line ends positions.
6112 DECL_ACCESSORS(line_ends, Object)
6114 // [eval_from_shared]: for eval scripts the shared funcion info for the
6115 // function from which eval was called.
6116 DECL_ACCESSORS(eval_from_shared, Object)
6118 // [eval_from_instructions_offset]: the instruction offset in the code for the
6119 // function from which eval was called where eval was called.
6120 DECL_INT_ACCESSORS(eval_from_instructions_offset)
6122 // [shared_function_infos]: weak fixed array containing all shared
6123 // function infos created from this script.
6124 DECL_ACCESSORS(shared_function_infos, Object)
6126 // [flags]: Holds an exciting bitfield.
6127 DECL_INT_ACCESSORS(flags)
6129 // [source_url]: sourceURL from magic comment
6130 DECL_ACCESSORS(source_url, Object)
6132 // [source_url]: sourceMappingURL magic comment
6133 DECL_ACCESSORS(source_mapping_url, Object)
6135 // [compilation_type]: how the the script was compiled. Encoded in the
6137 inline CompilationType compilation_type();
6138 inline void set_compilation_type(CompilationType type);
6140 // [compilation_state]: determines whether the script has already been
6141 // compiled. Encoded in the 'flags' field.
6142 inline CompilationState compilation_state();
6143 inline void set_compilation_state(CompilationState state);
6145 // [hide_source]: determines whether the script source can be exposed as
6146 // function source. Encoded in the 'flags' field.
6147 inline bool hide_source();
6148 inline void set_hide_source(bool value);
6150 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6151 // and used by the embedder to make decisions about the script. V8 just passes
6152 // this through. Encoded in the 'flags' field.
6153 inline v8::ScriptOriginOptions origin_options();
6154 inline void set_origin_options(ScriptOriginOptions origin_options);
6156 DECLARE_CAST(Script)
6158 // If script source is an external string, check that the underlying
6159 // resource is accessible. Otherwise, always return true.
6160 inline bool HasValidSource();
6162 // Convert code position into column number.
6163 static int GetColumnNumber(Handle<Script> script, int code_pos);
6165 // Convert code position into (zero-based) line number.
6166 // The non-handlified version does not allocate, but may be much slower.
6167 static int GetLineNumber(Handle<Script> script, int code_pos);
6168 int GetLineNumber(int code_pos);
6170 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6172 // Init line_ends array with code positions of line ends inside script source.
6173 static void InitLineEnds(Handle<Script> script);
6175 // Get the JS object wrapping the given script; create it if none exists.
6176 static Handle<JSObject> GetWrapper(Handle<Script> script);
6178 // Look through the list of existing shared function infos to find one
6179 // that matches the function literal. Return empty handle if not found.
6180 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6182 // Iterate over all script objects on the heap.
6185 explicit Iterator(Isolate* isolate);
6189 WeakFixedArray::Iterator iterator_;
6190 DISALLOW_COPY_AND_ASSIGN(Iterator);
6193 // Dispatched behavior.
6194 DECLARE_PRINTER(Script)
6195 DECLARE_VERIFIER(Script)
6197 static const int kSourceOffset = HeapObject::kHeaderSize;
6198 static const int kNameOffset = kSourceOffset + kPointerSize;
6199 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6200 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6201 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6202 static const int kWrapperOffset = kContextOffset + kPointerSize;
6203 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6204 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6205 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6206 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6207 static const int kEvalFrominstructionsOffsetOffset =
6208 kEvalFromSharedOffset + kPointerSize;
6209 static const int kSharedFunctionInfosOffset =
6210 kEvalFrominstructionsOffsetOffset + kPointerSize;
6211 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6212 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6213 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6214 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6217 int GetLineNumberWithArray(int code_pos);
6219 // Bit positions in the flags field.
6220 static const int kCompilationTypeBit = 0;
6221 static const int kCompilationStateBit = 1;
6222 static const int kHideSourceBit = 2;
6223 static const int kOriginOptionsShift = 3;
6224 static const int kOriginOptionsSize = 3;
6225 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6226 << kOriginOptionsShift;
6228 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6232 // List of builtin functions we want to identify to improve code
6235 // Each entry has a name of a global object property holding an object
6236 // optionally followed by ".prototype", a name of a builtin function
6237 // on the object (the one the id is set for), and a label.
6239 // Installation of ids for the selected builtin functions is handled
6240 // by the bootstrapper.
6241 #define FUNCTIONS_WITH_ID_LIST(V) \
6242 V(Array.prototype, indexOf, ArrayIndexOf) \
6243 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6244 V(Array.prototype, push, ArrayPush) \
6245 V(Array.prototype, pop, ArrayPop) \
6246 V(Array.prototype, shift, ArrayShift) \
6247 V(Function.prototype, apply, FunctionApply) \
6248 V(Function.prototype, call, FunctionCall) \
6249 V(String.prototype, charCodeAt, StringCharCodeAt) \
6250 V(String.prototype, charAt, StringCharAt) \
6251 V(String, fromCharCode, StringFromCharCode) \
6252 V(Math, random, MathRandom) \
6253 V(Math, floor, MathFloor) \
6254 V(Math, round, MathRound) \
6255 V(Math, ceil, MathCeil) \
6256 V(Math, abs, MathAbs) \
6257 V(Math, log, MathLog) \
6258 V(Math, exp, MathExp) \
6259 V(Math, sqrt, MathSqrt) \
6260 V(Math, pow, MathPow) \
6261 V(Math, max, MathMax) \
6262 V(Math, min, MathMin) \
6263 V(Math, cos, MathCos) \
6264 V(Math, sin, MathSin) \
6265 V(Math, tan, MathTan) \
6266 V(Math, acos, MathAcos) \
6267 V(Math, asin, MathAsin) \
6268 V(Math, atan, MathAtan) \
6269 V(Math, atan2, MathAtan2) \
6270 V(Math, imul, MathImul) \
6271 V(Math, clz32, MathClz32) \
6272 V(Math, fround, MathFround)
6274 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6275 V(Atomics, load, AtomicsLoad) \
6276 V(Atomics, store, AtomicsStore)
6278 enum BuiltinFunctionId {
6280 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6282 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6283 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6284 #undef DECLARE_FUNCTION_ID
6285 // Fake id for a special case of Math.pow. Note, it continues the
6286 // list of math functions.
6291 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6292 // that both {code} and {literals} can be NULL to pass search result status.
6293 struct CodeAndLiterals {
6294 Code* code; // Cached optimized code.
6295 FixedArray* literals; // Cached literals array.
6299 // SharedFunctionInfo describes the JSFunction information that can be
6300 // shared by multiple instances of the function.
6301 class SharedFunctionInfo: public HeapObject {
6303 // [name]: Function name.
6304 DECL_ACCESSORS(name, Object)
6306 // [code]: Function code.
6307 DECL_ACCESSORS(code, Code)
6308 inline void ReplaceCode(Code* code);
6310 // [optimized_code_map]: Map from native context to optimized code
6311 // and a shared literals array or Smi(0) if none.
6312 DECL_ACCESSORS(optimized_code_map, Object)
6314 // Returns entry from optimized code map for specified context and OSR entry.
6315 // Note that {code == nullptr, literals == nullptr} indicates no matching
6316 // entry has been found, whereas {code, literals == nullptr} indicates that
6317 // code is context-independent.
6318 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6319 BailoutId osr_ast_id);
6321 // Clear optimized code map.
6322 void ClearOptimizedCodeMap();
6324 // Removes a specific optimized code object from the optimized code map.
6325 // In case of non-OSR the code reference is cleared from the cache entry but
6326 // the entry itself is left in the map in order to proceed sharing literals.
6327 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6329 // Trims the optimized code map after entries have been removed.
6330 void TrimOptimizedCodeMap(int shrink_by);
6332 // Add a new entry to the optimized code map for context-independent code.
6333 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6336 // Add a new entry to the optimized code map for context-dependent code.
6337 // |code| is either a code object or an undefined value. In the latter case
6338 // the entry just maps |native_context, osr_ast_id| pair to |literals| array.
6339 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6340 Handle<Context> native_context,
6341 Handle<HeapObject> code,
6342 Handle<FixedArray> literals,
6343 BailoutId osr_ast_id);
6345 // Set up the link between shared function info and the script. The shared
6346 // function info is added to the list on the script.
6347 static void SetScript(Handle<SharedFunctionInfo> shared,
6348 Handle<Object> script_object);
6350 // Layout description of the optimized code map.
6351 static const int kNextMapIndex = 0;
6352 static const int kSharedCodeIndex = 1;
6353 static const int kEntriesStart = 2;
6354 static const int kContextOffset = 0;
6355 static const int kCachedCodeOffset = 1;
6356 static const int kLiteralsOffset = 2;
6357 static const int kOsrAstIdOffset = 3;
6358 static const int kEntryLength = 4;
6359 static const int kInitialLength = kEntriesStart + kEntryLength;
6361 static const int kNotFound = -1;
6363 // [scope_info]: Scope info.
6364 DECL_ACCESSORS(scope_info, ScopeInfo)
6366 // [construct stub]: Code stub for constructing instances of this function.
6367 DECL_ACCESSORS(construct_stub, Code)
6369 // Returns if this function has been compiled to native code yet.
6370 inline bool is_compiled();
6372 // [length]: The function length - usually the number of declared parameters.
6373 // Use up to 2^30 parameters.
6374 inline int length() const;
6375 inline void set_length(int value);
6377 // [internal formal parameter count]: The declared number of parameters.
6378 // For subclass constructors, also includes new.target.
6379 // The size of function's frame is internal_formal_parameter_count + 1.
6380 inline int internal_formal_parameter_count() const;
6381 inline void set_internal_formal_parameter_count(int value);
6383 // Set the formal parameter count so the function code will be
6384 // called without using argument adaptor frames.
6385 inline void DontAdaptArguments();
6387 // [expected_nof_properties]: Expected number of properties for the function.
6388 inline int expected_nof_properties() const;
6389 inline void set_expected_nof_properties(int value);
6391 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6392 // (increasingly) from crankshafted code where sufficient feedback isn't
6394 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6396 // Unconditionally clear the type feedback vector (including vector ICs).
6397 void ClearTypeFeedbackInfo();
6399 // Clear the type feedback vector with a more subtle policy at GC time.
6400 void ClearTypeFeedbackInfoAtGCTime();
6403 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6404 // even if the GC moves this SharedFunctionInfo.
6405 inline int unique_id() const;
6406 inline void set_unique_id(int value);
6409 // [instance class name]: class name for instances.
6410 DECL_ACCESSORS(instance_class_name, Object)
6412 // [function data]: This field holds some additional data for function.
6413 // Currently it has one of:
6414 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6415 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6416 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6417 // In the long run we don't want all functions to have this field but
6418 // we can fix that when we have a better model for storing hidden data
6420 DECL_ACCESSORS(function_data, Object)
6422 inline bool IsApiFunction();
6423 inline FunctionTemplateInfo* get_api_func_data();
6424 inline bool HasBuiltinFunctionId();
6425 inline BuiltinFunctionId builtin_function_id();
6426 inline bool HasBytecodeArray();
6427 inline BytecodeArray* bytecode_array();
6429 // [script info]: Script from which the function originates.
6430 DECL_ACCESSORS(script, Object)
6432 // [num_literals]: Number of literals used by this function.
6433 inline int num_literals() const;
6434 inline void set_num_literals(int value);
6436 // [start_position_and_type]: Field used to store both the source code
6437 // position, whether or not the function is a function expression,
6438 // and whether or not the function is a toplevel function. The two
6439 // least significants bit indicates whether the function is an
6440 // expression and the rest contains the source code position.
6441 inline int start_position_and_type() const;
6442 inline void set_start_position_and_type(int value);
6444 // The function is subject to debugging if a debug info is attached.
6445 inline bool HasDebugInfo();
6446 inline DebugInfo* GetDebugInfo();
6448 // A function has debug code if the compiled code has debug break slots.
6449 inline bool HasDebugCode();
6451 // [debug info]: Debug information.
6452 DECL_ACCESSORS(debug_info, Object)
6454 // [inferred name]: Name inferred from variable or property
6455 // assignment of this function. Used to facilitate debugging and
6456 // profiling of JavaScript code written in OO style, where almost
6457 // all functions are anonymous but are assigned to object
6459 DECL_ACCESSORS(inferred_name, String)
6461 // The function's name if it is non-empty, otherwise the inferred name.
6462 String* DebugName();
6464 // Position of the 'function' token in the script source.
6465 inline int function_token_position() const;
6466 inline void set_function_token_position(int function_token_position);
6468 // Position of this function in the script source.
6469 inline int start_position() const;
6470 inline void set_start_position(int start_position);
6472 // End position of this function in the script source.
6473 inline int end_position() const;
6474 inline void set_end_position(int end_position);
6476 // Is this function a function expression in the source code.
6477 DECL_BOOLEAN_ACCESSORS(is_expression)
6479 // Is this function a top-level function (scripts, evals).
6480 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6482 // Bit field containing various information collected by the compiler to
6483 // drive optimization.
6484 inline int compiler_hints() const;
6485 inline void set_compiler_hints(int value);
6487 inline int ast_node_count() const;
6488 inline void set_ast_node_count(int count);
6490 inline int profiler_ticks() const;
6491 inline void set_profiler_ticks(int ticks);
6493 // Inline cache age is used to infer whether the function survived a context
6494 // disposal or not. In the former case we reset the opt_count.
6495 inline int ic_age();
6496 inline void set_ic_age(int age);
6498 // Indicates if this function can be lazy compiled.
6499 // This is used to determine if we can safely flush code from a function
6500 // when doing GC if we expect that the function will no longer be used.
6501 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6503 // Indicates if this function can be lazy compiled without a context.
6504 // This is used to determine if we can force compilation without reaching
6505 // the function through program execution but through other means (e.g. heap
6506 // iteration by the debugger).
6507 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6509 // Indicates whether optimizations have been disabled for this
6510 // shared function info. If a function is repeatedly optimized or if
6511 // we cannot optimize the function we disable optimization to avoid
6512 // spending time attempting to optimize it again.
6513 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6515 // Indicates the language mode.
6516 inline LanguageMode language_mode();
6517 inline void set_language_mode(LanguageMode language_mode);
6519 // False if the function definitely does not allocate an arguments object.
6520 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6522 // Indicates that this function uses a super property (or an eval that may
6523 // use a super property).
6524 // This is needed to set up the [[HomeObject]] on the function instance.
6525 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6527 // True if the function has any duplicated parameter names.
6528 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6530 // Indicates whether the function is a native function.
6531 // These needs special treatment in .call and .apply since
6532 // null passed as the receiver should not be translated to the
6534 DECL_BOOLEAN_ACCESSORS(native)
6536 // Indicate that this function should always be inlined in optimized code.
6537 DECL_BOOLEAN_ACCESSORS(force_inline)
6539 // Indicates that the function was created by the Function function.
6540 // Though it's anonymous, toString should treat it as if it had the name
6541 // "anonymous". We don't set the name itself so that the system does not
6542 // see a binding for it.
6543 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6545 // Indicates whether the function is a bound function created using
6546 // the bind function.
6547 DECL_BOOLEAN_ACCESSORS(bound)
6549 // Indicates that the function is anonymous (the name field can be set
6550 // through the API, which does not change this flag).
6551 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6553 // Is this a function or top-level/eval code.
6554 DECL_BOOLEAN_ACCESSORS(is_function)
6556 // Indicates that code for this function cannot be compiled with Crankshaft.
6557 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6559 // Indicates that code for this function cannot be flushed.
6560 DECL_BOOLEAN_ACCESSORS(dont_flush)
6562 // Indicates that this function is a generator.
6563 DECL_BOOLEAN_ACCESSORS(is_generator)
6565 // Indicates that this function is an arrow function.
6566 DECL_BOOLEAN_ACCESSORS(is_arrow)
6568 // Indicates that this function is a concise method.
6569 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6571 // Indicates that this function is an accessor (getter or setter).
6572 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6574 // Indicates that this function is a default constructor.
6575 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6577 // Indicates that this function is an asm function.
6578 DECL_BOOLEAN_ACCESSORS(asm_function)
6580 // Indicates that the the shared function info is deserialized from cache.
6581 DECL_BOOLEAN_ACCESSORS(deserialized)
6583 // Indicates that the the shared function info has never been compiled before.
6584 DECL_BOOLEAN_ACCESSORS(never_compiled)
6586 inline FunctionKind kind();
6587 inline void set_kind(FunctionKind kind);
6589 // Indicates whether or not the code in the shared function support
6591 inline bool has_deoptimization_support();
6593 // Enable deoptimization support through recompiled code.
6594 void EnableDeoptimizationSupport(Code* recompiled);
6596 // Disable (further) attempted optimization of all functions sharing this
6597 // shared function info.
6598 void DisableOptimization(BailoutReason reason);
6600 inline BailoutReason disable_optimization_reason();
6602 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6603 // code, returns whether it asserted (i.e., always true if assertions are
6605 bool VerifyBailoutId(BailoutId id);
6607 // [source code]: Source code for the function.
6608 bool HasSourceCode() const;
6609 Handle<Object> GetSourceCode();
6611 // Number of times the function was optimized.
6612 inline int opt_count();
6613 inline void set_opt_count(int opt_count);
6615 // Number of times the function was deoptimized.
6616 inline void set_deopt_count(int value);
6617 inline int deopt_count();
6618 inline void increment_deopt_count();
6620 // Number of time we tried to re-enable optimization after it
6621 // was disabled due to high number of deoptimizations.
6622 inline void set_opt_reenable_tries(int value);
6623 inline int opt_reenable_tries();
6625 inline void TryReenableOptimization();
6627 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6628 inline void set_counters(int value);
6629 inline int counters() const;
6631 // Stores opt_count and bailout_reason as bit-fields.
6632 inline void set_opt_count_and_bailout_reason(int value);
6633 inline int opt_count_and_bailout_reason() const;
6635 inline void set_disable_optimization_reason(BailoutReason reason);
6637 // Tells whether this function should be subject to debugging.
6638 inline bool IsSubjectToDebugging();
6640 // Whether this function is defined in native code or extensions.
6641 inline bool IsBuiltin();
6643 // Check whether or not this function is inlineable.
6644 bool IsInlineable();
6646 // Source size of this function.
6649 // Calculate the instance size.
6650 int CalculateInstanceSize();
6652 // Calculate the number of in-object properties.
6653 int CalculateInObjectProperties();
6655 inline bool has_simple_parameters();
6657 // Initialize a SharedFunctionInfo from a parsed function literal.
6658 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6659 FunctionLiteral* lit);
6661 // Dispatched behavior.
6662 DECLARE_PRINTER(SharedFunctionInfo)
6663 DECLARE_VERIFIER(SharedFunctionInfo)
6665 void ResetForNewContext(int new_ic_age);
6667 // Iterate over all shared function infos that are created from a script.
6668 // That excludes shared function infos created for API functions and C++
6672 explicit Iterator(Isolate* isolate);
6673 SharedFunctionInfo* Next();
6678 Script::Iterator script_iterator_;
6679 WeakFixedArray::Iterator sfi_iterator_;
6680 DisallowHeapAllocation no_gc_;
6681 DISALLOW_COPY_AND_ASSIGN(Iterator);
6684 DECLARE_CAST(SharedFunctionInfo)
6687 static const int kDontAdaptArgumentsSentinel = -1;
6689 // Layout description.
6691 static const int kNameOffset = HeapObject::kHeaderSize;
6692 static const int kCodeOffset = kNameOffset + kPointerSize;
6693 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6694 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6695 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6696 static const int kInstanceClassNameOffset =
6697 kConstructStubOffset + kPointerSize;
6698 static const int kFunctionDataOffset =
6699 kInstanceClassNameOffset + kPointerSize;
6700 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6701 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6702 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6703 static const int kFeedbackVectorOffset =
6704 kInferredNameOffset + kPointerSize;
6706 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6707 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6709 // Just to not break the postmortrem support with conditional offsets
6710 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6711 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6714 #if V8_HOST_ARCH_32_BIT
6716 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6717 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6718 static const int kExpectedNofPropertiesOffset =
6719 kFormalParameterCountOffset + kPointerSize;
6720 static const int kNumLiteralsOffset =
6721 kExpectedNofPropertiesOffset + kPointerSize;
6722 static const int kStartPositionAndTypeOffset =
6723 kNumLiteralsOffset + kPointerSize;
6724 static const int kEndPositionOffset =
6725 kStartPositionAndTypeOffset + kPointerSize;
6726 static const int kFunctionTokenPositionOffset =
6727 kEndPositionOffset + kPointerSize;
6728 static const int kCompilerHintsOffset =
6729 kFunctionTokenPositionOffset + kPointerSize;
6730 static const int kOptCountAndBailoutReasonOffset =
6731 kCompilerHintsOffset + kPointerSize;
6732 static const int kCountersOffset =
6733 kOptCountAndBailoutReasonOffset + kPointerSize;
6734 static const int kAstNodeCountOffset =
6735 kCountersOffset + kPointerSize;
6736 static const int kProfilerTicksOffset =
6737 kAstNodeCountOffset + kPointerSize;
6740 static const int kSize = kProfilerTicksOffset + kPointerSize;
6742 // The only reason to use smi fields instead of int fields
6743 // is to allow iteration without maps decoding during
6744 // garbage collections.
6745 // To avoid wasting space on 64-bit architectures we use
6746 // the following trick: we group integer fields into pairs
6747 // The least significant integer in each pair is shifted left by 1.
6748 // By doing this we guarantee that LSB of each kPointerSize aligned
6749 // word is not set and thus this word cannot be treated as pointer
6750 // to HeapObject during old space traversal.
6751 #if V8_TARGET_LITTLE_ENDIAN
6752 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6753 static const int kFormalParameterCountOffset =
6754 kLengthOffset + kIntSize;
6756 static const int kExpectedNofPropertiesOffset =
6757 kFormalParameterCountOffset + kIntSize;
6758 static const int kNumLiteralsOffset =
6759 kExpectedNofPropertiesOffset + kIntSize;
6761 static const int kEndPositionOffset =
6762 kNumLiteralsOffset + kIntSize;
6763 static const int kStartPositionAndTypeOffset =
6764 kEndPositionOffset + kIntSize;
6766 static const int kFunctionTokenPositionOffset =
6767 kStartPositionAndTypeOffset + kIntSize;
6768 static const int kCompilerHintsOffset =
6769 kFunctionTokenPositionOffset + kIntSize;
6771 static const int kOptCountAndBailoutReasonOffset =
6772 kCompilerHintsOffset + kIntSize;
6773 static const int kCountersOffset =
6774 kOptCountAndBailoutReasonOffset + kIntSize;
6776 static const int kAstNodeCountOffset =
6777 kCountersOffset + kIntSize;
6778 static const int kProfilerTicksOffset =
6779 kAstNodeCountOffset + kIntSize;
6782 static const int kSize = kProfilerTicksOffset + kIntSize;
6784 #elif V8_TARGET_BIG_ENDIAN
6785 static const int kFormalParameterCountOffset =
6786 kLastPointerFieldOffset + kPointerSize;
6787 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6789 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6790 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6792 static const int kStartPositionAndTypeOffset =
6793 kExpectedNofPropertiesOffset + kIntSize;
6794 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6796 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6797 static const int kFunctionTokenPositionOffset =
6798 kCompilerHintsOffset + kIntSize;
6800 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6801 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6803 static const int kProfilerTicksOffset =
6804 kOptCountAndBailoutReasonOffset + kIntSize;
6805 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6808 static const int kSize = kAstNodeCountOffset + kIntSize;
6811 #error Unknown byte ordering
6812 #endif // Big endian
6816 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6818 typedef FixedBodyDescriptor<kNameOffset,
6819 kLastPointerFieldOffset + kPointerSize,
6820 kSize> BodyDescriptor;
6822 // Bit positions in start_position_and_type.
6823 // The source code start position is in the 30 most significant bits of
6824 // the start_position_and_type field.
6825 static const int kIsExpressionBit = 0;
6826 static const int kIsTopLevelBit = 1;
6827 static const int kStartPositionShift = 2;
6828 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6830 // Bit positions in compiler_hints.
6831 enum CompilerHints {
6832 kAllowLazyCompilation,
6833 kAllowLazyCompilationWithoutContext,
6834 kOptimizationDisabled,
6836 kStrictModeFunction,
6837 kStrongModeFunction,
6840 kHasDuplicateParameters,
6844 kNameShouldPrintAsAnonymous,
6851 kIsAccessorFunction,
6852 kIsDefaultConstructor,
6853 kIsSubclassConstructor,
6859 kCompilerHintsCount // Pseudo entry
6861 // Add hints for other modes when they're added.
6862 STATIC_ASSERT(LANGUAGE_END == 3);
6864 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6866 class DeoptCountBits : public BitField<int, 0, 4> {};
6867 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6868 class ICAgeBits : public BitField<int, 22, 8> {};
6870 class OptCountBits : public BitField<int, 0, 22> {};
6871 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6874 #if V8_HOST_ARCH_32_BIT
6875 // On 32 bit platforms, compiler hints is a smi.
6876 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6877 static const int kCompilerHintsSize = kPointerSize;
6879 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6880 static const int kCompilerHintsSmiTagSize = 0;
6881 static const int kCompilerHintsSize = kIntSize;
6884 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6885 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6888 // Constants for optimizing codegen for strict mode function and
6890 // Allows to use byte-width instructions.
6891 static const int kStrictModeBitWithinByte =
6892 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6893 static const int kStrongModeBitWithinByte =
6894 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6896 static const int kNativeBitWithinByte =
6897 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6899 static const int kBoundBitWithinByte =
6900 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6902 #if defined(V8_TARGET_LITTLE_ENDIAN)
6903 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6904 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6905 static const int kStrongModeByteOffset =
6906 kCompilerHintsOffset +
6907 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6908 static const int kNativeByteOffset = kCompilerHintsOffset +
6909 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6910 static const int kBoundByteOffset =
6911 kCompilerHintsOffset +
6912 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6913 #elif defined(V8_TARGET_BIG_ENDIAN)
6914 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6915 (kCompilerHintsSize - 1) -
6916 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6917 static const int kStrongModeByteOffset =
6918 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6919 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6920 static const int kNativeByteOffset = kCompilerHintsOffset +
6921 (kCompilerHintsSize - 1) -
6922 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6923 static const int kBoundByteOffset =
6924 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6925 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6927 #error Unknown byte ordering
6931 // Returns entry from optimized code map for specified context and OSR entry.
6932 // The result is either kNotFound, kSharedCodeIndex for context-independent
6933 // entry or a start index of the context-dependent entry.
6934 int SearchOptimizedCodeMapEntry(Context* native_context,
6935 BailoutId osr_ast_id);
6937 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6941 // Printing support.
6942 struct SourceCodeOf {
6943 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6944 : value(v), max_length(max) {}
6945 const SharedFunctionInfo* value;
6950 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6953 class JSGeneratorObject: public JSObject {
6955 // [function]: The function corresponding to this generator object.
6956 DECL_ACCESSORS(function, JSFunction)
6958 // [context]: The context of the suspended computation.
6959 DECL_ACCESSORS(context, Context)
6961 // [receiver]: The receiver of the suspended computation.
6962 DECL_ACCESSORS(receiver, Object)
6964 // [continuation]: Offset into code of continuation.
6966 // A positive offset indicates a suspended generator. The special
6967 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6968 // cannot be resumed.
6969 inline int continuation() const;
6970 inline void set_continuation(int continuation);
6971 inline bool is_closed();
6972 inline bool is_executing();
6973 inline bool is_suspended();
6975 // [operand_stack]: Saved operand stack.
6976 DECL_ACCESSORS(operand_stack, FixedArray)
6978 DECLARE_CAST(JSGeneratorObject)
6980 // Dispatched behavior.
6981 DECLARE_PRINTER(JSGeneratorObject)
6982 DECLARE_VERIFIER(JSGeneratorObject)
6984 // Magic sentinel values for the continuation.
6985 static const int kGeneratorExecuting = -1;
6986 static const int kGeneratorClosed = 0;
6988 // Layout description.
6989 static const int kFunctionOffset = JSObject::kHeaderSize;
6990 static const int kContextOffset = kFunctionOffset + kPointerSize;
6991 static const int kReceiverOffset = kContextOffset + kPointerSize;
6992 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6993 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6994 static const int kSize = kOperandStackOffset + kPointerSize;
6996 // Resume mode, for use by runtime functions.
6997 enum ResumeMode { NEXT, THROW };
7000 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7004 // Representation for module instance objects.
7005 class JSModule: public JSObject {
7007 // [context]: the context holding the module's locals, or undefined if none.
7008 DECL_ACCESSORS(context, Object)
7010 // [scope_info]: Scope info.
7011 DECL_ACCESSORS(scope_info, ScopeInfo)
7013 DECLARE_CAST(JSModule)
7015 // Dispatched behavior.
7016 DECLARE_PRINTER(JSModule)
7017 DECLARE_VERIFIER(JSModule)
7019 // Layout description.
7020 static const int kContextOffset = JSObject::kHeaderSize;
7021 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7022 static const int kSize = kScopeInfoOffset + kPointerSize;
7025 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7029 // JSFunction describes JavaScript functions.
7030 class JSFunction: public JSObject {
7032 // [prototype_or_initial_map]:
7033 DECL_ACCESSORS(prototype_or_initial_map, Object)
7035 // [shared]: The information about the function that
7036 // can be shared by instances.
7037 DECL_ACCESSORS(shared, SharedFunctionInfo)
7039 // [context]: The context for this function.
7040 inline Context* context();
7041 inline void set_context(Object* context);
7042 inline JSObject* global_proxy();
7044 // [code]: The generated code object for this function. Executed
7045 // when the function is invoked, e.g. foo() or new foo(). See
7046 // [[Call]] and [[Construct]] description in ECMA-262, section
7048 inline Code* code();
7049 inline void set_code(Code* code);
7050 inline void set_code_no_write_barrier(Code* code);
7051 inline void ReplaceCode(Code* code);
7053 // Tells whether this function is builtin.
7054 inline bool IsBuiltin();
7056 // Tells whether this function inlines the given shared function info.
7057 bool Inlines(SharedFunctionInfo* candidate);
7059 // Tells whether this function should be subject to debugging.
7060 inline bool IsSubjectToDebugging();
7062 // Tells whether or not the function needs arguments adaption.
7063 inline bool NeedsArgumentsAdaption();
7065 // Tells whether or not this function has been optimized.
7066 inline bool IsOptimized();
7068 // Mark this function for lazy recompilation. The function will be
7069 // recompiled the next time it is executed.
7070 void MarkForOptimization();
7071 void AttemptConcurrentOptimization();
7073 // Tells whether or not the function is already marked for lazy
7075 inline bool IsMarkedForOptimization();
7076 inline bool IsMarkedForConcurrentOptimization();
7078 // Tells whether or not the function is on the concurrent recompilation queue.
7079 inline bool IsInOptimizationQueue();
7081 // Inobject slack tracking is the way to reclaim unused inobject space.
7083 // The instance size is initially determined by adding some slack to
7084 // expected_nof_properties (to allow for a few extra properties added
7085 // after the constructor). There is no guarantee that the extra space
7086 // will not be wasted.
7088 // Here is the algorithm to reclaim the unused inobject space:
7089 // - Detect the first constructor call for this JSFunction.
7090 // When it happens enter the "in progress" state: initialize construction
7091 // counter in the initial_map.
7092 // - While the tracking is in progress create objects filled with
7093 // one_pointer_filler_map instead of undefined_value. This way they can be
7094 // resized quickly and safely.
7095 // - Once enough objects have been created compute the 'slack'
7096 // (traverse the map transition tree starting from the
7097 // initial_map and find the lowest value of unused_property_fields).
7098 // - Traverse the transition tree again and decrease the instance size
7099 // of every map. Existing objects will resize automatically (they are
7100 // filled with one_pointer_filler_map). All further allocations will
7101 // use the adjusted instance size.
7102 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7103 // allocations made using different closures could actually create different
7104 // kind of objects (see prototype inheritance pattern).
7106 // Important: inobject slack tracking is not attempted during the snapshot
7109 // True if the initial_map is set and the object constructions countdown
7110 // counter is not zero.
7111 static const int kGenerousAllocationCount =
7112 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7113 inline bool IsInobjectSlackTrackingInProgress();
7115 // Starts the tracking.
7116 // Initializes object constructions countdown counter in the initial map.
7117 void StartInobjectSlackTracking();
7119 // Completes the tracking.
7120 void CompleteInobjectSlackTracking();
7122 // [literals_or_bindings]: Fixed array holding either
7123 // the materialized literals or the bindings of a bound function.
7125 // If the function contains object, regexp or array literals, the
7126 // literals array prefix contains the object, regexp, and array
7127 // function to be used when creating these literals. This is
7128 // necessary so that we do not dynamically lookup the object, regexp
7129 // or array functions. Performing a dynamic lookup, we might end up
7130 // using the functions from a new context that we should not have
7133 // On bound functions, the array is a (copy-on-write) fixed-array containing
7134 // the function that was bound, bound this-value and any bound
7135 // arguments. Bound functions never contain literals.
7136 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7138 inline FixedArray* literals();
7139 inline void set_literals(FixedArray* literals);
7141 inline FixedArray* function_bindings();
7142 inline void set_function_bindings(FixedArray* bindings);
7144 // The initial map for an object created by this constructor.
7145 inline Map* initial_map();
7146 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7147 Handle<Object> prototype);
7148 inline bool has_initial_map();
7149 static void EnsureHasInitialMap(Handle<JSFunction> function);
7151 // Get and set the prototype property on a JSFunction. If the
7152 // function has an initial map the prototype is set on the initial
7153 // map. Otherwise, the prototype is put in the initial map field
7154 // until an initial map is needed.
7155 inline bool has_prototype();
7156 inline bool has_instance_prototype();
7157 inline Object* prototype();
7158 inline Object* instance_prototype();
7159 static void SetPrototype(Handle<JSFunction> function,
7160 Handle<Object> value);
7161 static void SetInstancePrototype(Handle<JSFunction> function,
7162 Handle<Object> value);
7164 // After prototype is removed, it will not be created when accessed, and
7165 // [[Construct]] from this function will not be allowed.
7166 bool RemovePrototype();
7168 // Accessor for this function's initial map's [[class]]
7169 // property. This is primarily used by ECMA native functions. This
7170 // method sets the class_name field of this function's initial map
7171 // to a given value. It creates an initial map if this function does
7172 // not have one. Note that this method does not copy the initial map
7173 // if it has one already, but simply replaces it with the new value.
7174 // Instances created afterwards will have a map whose [[class]] is
7175 // set to 'value', but there is no guarantees on instances created
7177 void SetInstanceClassName(String* name);
7179 // Returns if this function has been compiled to native code yet.
7180 inline bool is_compiled();
7182 // Returns `false` if formal parameters include rest parameters, optional
7183 // parameters, or destructuring parameters.
7184 // TODO(caitp): make this a flag set during parsing
7185 inline bool has_simple_parameters();
7187 // [next_function_link]: Links functions into various lists, e.g. the list
7188 // of optimized functions hanging off the native_context. The CodeFlusher
7189 // uses this link to chain together flushing candidates. Treated weakly
7190 // by the garbage collector.
7191 DECL_ACCESSORS(next_function_link, Object)
7193 // Prints the name of the function using PrintF.
7194 void PrintName(FILE* out = stdout);
7196 DECLARE_CAST(JSFunction)
7198 // Iterates the objects, including code objects indirectly referenced
7199 // through pointers to the first instruction in the code object.
7200 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7202 // Dispatched behavior.
7203 DECLARE_PRINTER(JSFunction)
7204 DECLARE_VERIFIER(JSFunction)
7206 // Returns the number of allocated literals.
7207 inline int NumberOfLiterals();
7209 // Used for flags such as --hydrogen-filter.
7210 bool PassesFilter(const char* raw_filter);
7212 // The function's name if it is configured, otherwise shared function info
7214 static Handle<String> GetDebugName(Handle<JSFunction> function);
7216 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7217 // kSize) is weak and has special handling during garbage collection.
7218 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7219 static const int kPrototypeOrInitialMapOffset =
7220 kCodeEntryOffset + kPointerSize;
7221 static const int kSharedFunctionInfoOffset =
7222 kPrototypeOrInitialMapOffset + kPointerSize;
7223 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7224 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7225 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7226 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7227 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7229 // Layout of the bound-function binding array.
7230 static const int kBoundFunctionIndex = 0;
7231 static const int kBoundThisIndex = 1;
7232 static const int kBoundArgumentsStartIndex = 2;
7235 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7239 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7240 // and the prototype is hidden. JSGlobalProxy always delegates
7241 // property accesses to its prototype if the prototype is not null.
7243 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7245 // Accessing a JSGlobalProxy requires security check.
7247 class JSGlobalProxy : public JSObject {
7249 // [native_context]: the owner native context of this global proxy object.
7250 // It is null value if this object is not used by any context.
7251 DECL_ACCESSORS(native_context, Object)
7253 // [hash]: The hash code property (undefined if not initialized yet).
7254 DECL_ACCESSORS(hash, Object)
7256 DECLARE_CAST(JSGlobalProxy)
7258 inline bool IsDetachedFrom(GlobalObject* global) const;
7260 // Dispatched behavior.
7261 DECLARE_PRINTER(JSGlobalProxy)
7262 DECLARE_VERIFIER(JSGlobalProxy)
7264 // Layout description.
7265 static const int kNativeContextOffset = JSObject::kHeaderSize;
7266 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7267 static const int kSize = kHashOffset + kPointerSize;
7270 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7274 // Common super class for JavaScript global objects and the special
7275 // builtins global objects.
7276 class GlobalObject: public JSObject {
7278 // [builtins]: the object holding the runtime routines written in JS.
7279 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7281 // [native context]: the natives corresponding to this global object.
7282 DECL_ACCESSORS(native_context, Context)
7284 // [global proxy]: the global proxy object of the context
7285 DECL_ACCESSORS(global_proxy, JSObject)
7287 DECLARE_CAST(GlobalObject)
7289 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7291 // Ensure that the global object has a cell for the given property name.
7292 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7295 // Layout description.
7296 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7297 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7298 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7299 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7302 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7306 // JavaScript global object.
7307 class JSGlobalObject: public GlobalObject {
7309 DECLARE_CAST(JSGlobalObject)
7311 inline bool IsDetached();
7313 // Dispatched behavior.
7314 DECLARE_PRINTER(JSGlobalObject)
7315 DECLARE_VERIFIER(JSGlobalObject)
7317 // Layout description.
7318 static const int kSize = GlobalObject::kHeaderSize;
7321 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7325 // Builtins global object which holds the runtime routines written in
7327 class JSBuiltinsObject: public GlobalObject {
7329 DECLARE_CAST(JSBuiltinsObject)
7331 // Dispatched behavior.
7332 DECLARE_PRINTER(JSBuiltinsObject)
7333 DECLARE_VERIFIER(JSBuiltinsObject)
7335 // Layout description.
7336 static const int kSize = GlobalObject::kHeaderSize;
7339 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7343 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7344 class JSValue: public JSObject {
7346 // [value]: the object being wrapped.
7347 DECL_ACCESSORS(value, Object)
7349 DECLARE_CAST(JSValue)
7351 // Dispatched behavior.
7352 DECLARE_PRINTER(JSValue)
7353 DECLARE_VERIFIER(JSValue)
7355 // Layout description.
7356 static const int kValueOffset = JSObject::kHeaderSize;
7357 static const int kSize = kValueOffset + kPointerSize;
7360 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7366 // Representation for JS date objects.
7367 class JSDate: public JSObject {
7369 // If one component is NaN, all of them are, indicating a NaN time value.
7370 // [value]: the time value.
7371 DECL_ACCESSORS(value, Object)
7372 // [year]: caches year. Either undefined, smi, or NaN.
7373 DECL_ACCESSORS(year, Object)
7374 // [month]: caches month. Either undefined, smi, or NaN.
7375 DECL_ACCESSORS(month, Object)
7376 // [day]: caches day. Either undefined, smi, or NaN.
7377 DECL_ACCESSORS(day, Object)
7378 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7379 DECL_ACCESSORS(weekday, Object)
7380 // [hour]: caches hours. Either undefined, smi, or NaN.
7381 DECL_ACCESSORS(hour, Object)
7382 // [min]: caches minutes. Either undefined, smi, or NaN.
7383 DECL_ACCESSORS(min, Object)
7384 // [sec]: caches seconds. Either undefined, smi, or NaN.
7385 DECL_ACCESSORS(sec, Object)
7386 // [cache stamp]: sample of the date cache stamp at the
7387 // moment when chached fields were cached.
7388 DECL_ACCESSORS(cache_stamp, Object)
7390 DECLARE_CAST(JSDate)
7392 // Returns the date field with the specified index.
7393 // See FieldIndex for the list of date fields.
7394 static Object* GetField(Object* date, Smi* index);
7396 void SetValue(Object* value, bool is_value_nan);
7398 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7399 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7400 Handle<JSReceiver> receiver, Handle<Object> hint);
7402 // Dispatched behavior.
7403 DECLARE_PRINTER(JSDate)
7404 DECLARE_VERIFIER(JSDate)
7406 // The order is important. It must be kept in sync with date macros
7417 kFirstUncachedField,
7418 kMillisecond = kFirstUncachedField,
7422 kYearUTC = kFirstUTCField,
7435 // Layout description.
7436 static const int kValueOffset = JSObject::kHeaderSize;
7437 static const int kYearOffset = kValueOffset + kPointerSize;
7438 static const int kMonthOffset = kYearOffset + kPointerSize;
7439 static const int kDayOffset = kMonthOffset + kPointerSize;
7440 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7441 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7442 static const int kMinOffset = kHourOffset + kPointerSize;
7443 static const int kSecOffset = kMinOffset + kPointerSize;
7444 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7445 static const int kSize = kCacheStampOffset + kPointerSize;
7448 inline Object* DoGetField(FieldIndex index);
7450 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7452 // Computes and caches the cacheable fields of the date.
7453 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7456 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7460 // Representation of message objects used for error reporting through
7461 // the API. The messages are formatted in JavaScript so this object is
7462 // a real JavaScript object. The information used for formatting the
7463 // error messages are not directly accessible from JavaScript to
7464 // prevent leaking information to user code called during error
7466 class JSMessageObject: public JSObject {
7468 // [type]: the type of error message.
7469 inline int type() const;
7470 inline void set_type(int value);
7472 // [arguments]: the arguments for formatting the error message.
7473 DECL_ACCESSORS(argument, Object)
7475 // [script]: the script from which the error message originated.
7476 DECL_ACCESSORS(script, Object)
7478 // [stack_frames]: an array of stack frames for this error object.
7479 DECL_ACCESSORS(stack_frames, Object)
7481 // [start_position]: the start position in the script for the error message.
7482 inline int start_position() const;
7483 inline void set_start_position(int value);
7485 // [end_position]: the end position in the script for the error message.
7486 inline int end_position() const;
7487 inline void set_end_position(int value);
7489 DECLARE_CAST(JSMessageObject)
7491 // Dispatched behavior.
7492 DECLARE_PRINTER(JSMessageObject)
7493 DECLARE_VERIFIER(JSMessageObject)
7495 // Layout description.
7496 static const int kTypeOffset = JSObject::kHeaderSize;
7497 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7498 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7499 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7500 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7501 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7502 static const int kSize = kEndPositionOffset + kPointerSize;
7504 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7505 kStackFramesOffset + kPointerSize,
7506 kSize> BodyDescriptor;
7510 // Regular expressions
7511 // The regular expression holds a single reference to a FixedArray in
7512 // the kDataOffset field.
7513 // The FixedArray contains the following data:
7514 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7515 // - reference to the original source string
7516 // - reference to the original flag string
7517 // If it is an atom regexp
7518 // - a reference to a literal string to search for
7519 // If it is an irregexp regexp:
7520 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7521 // used for tracking the last usage (used for code flushing).
7522 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7523 // used for tracking the last usage (used for code flushing)..
7524 // - max number of registers used by irregexp implementations.
7525 // - number of capture registers (output values) of the regexp.
7526 class JSRegExp: public JSObject {
7529 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7530 // ATOM: A simple string to match against using an indexOf operation.
7531 // IRREGEXP: Compiled with Irregexp.
7532 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7533 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7540 UNICODE_ESCAPES = 16
7545 explicit Flags(uint32_t value) : value_(value) { }
7546 bool is_global() { return (value_ & GLOBAL) != 0; }
7547 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7548 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7549 bool is_sticky() { return (value_ & STICKY) != 0; }
7550 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7551 uint32_t value() { return value_; }
7556 DECL_ACCESSORS(data, Object)
7558 inline Type TypeTag();
7559 inline int CaptureCount();
7560 inline Flags GetFlags();
7561 inline String* Pattern();
7562 inline Object* DataAt(int index);
7563 // Set implementation data after the object has been prepared.
7564 inline void SetDataAt(int index, Object* value);
7566 static int code_index(bool is_latin1) {
7568 return kIrregexpLatin1CodeIndex;
7570 return kIrregexpUC16CodeIndex;
7574 static int saved_code_index(bool is_latin1) {
7576 return kIrregexpLatin1CodeSavedIndex;
7578 return kIrregexpUC16CodeSavedIndex;
7582 DECLARE_CAST(JSRegExp)
7584 // Dispatched behavior.
7585 DECLARE_VERIFIER(JSRegExp)
7587 static const int kDataOffset = JSObject::kHeaderSize;
7588 static const int kSize = kDataOffset + kPointerSize;
7590 // Indices in the data array.
7591 static const int kTagIndex = 0;
7592 static const int kSourceIndex = kTagIndex + 1;
7593 static const int kFlagsIndex = kSourceIndex + 1;
7594 static const int kDataIndex = kFlagsIndex + 1;
7595 // The data fields are used in different ways depending on the
7596 // value of the tag.
7597 // Atom regexps (literal strings).
7598 static const int kAtomPatternIndex = kDataIndex;
7600 static const int kAtomDataSize = kAtomPatternIndex + 1;
7602 // Irregexp compiled code or bytecode for Latin1. If compilation
7603 // fails, this fields hold an exception object that should be
7604 // thrown if the regexp is used again.
7605 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7606 // Irregexp compiled code or bytecode for UC16. If compilation
7607 // fails, this fields hold an exception object that should be
7608 // thrown if the regexp is used again.
7609 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7611 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7612 // is a potential candidate for flushing.
7613 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7614 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7615 // a potential candidate for flushing.
7616 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7618 // Maximal number of registers used by either Latin1 or UC16.
7619 // Only used to check that there is enough stack space
7620 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7621 // Number of captures in the compiled regexp.
7622 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7624 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7626 // Offsets directly into the data fixed array.
7627 static const int kDataTagOffset =
7628 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7629 static const int kDataOneByteCodeOffset =
7630 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7631 static const int kDataUC16CodeOffset =
7632 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7633 static const int kIrregexpCaptureCountOffset =
7634 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7636 // In-object fields.
7637 static const int kSourceFieldIndex = 0;
7638 static const int kGlobalFieldIndex = 1;
7639 static const int kIgnoreCaseFieldIndex = 2;
7640 static const int kMultilineFieldIndex = 3;
7641 static const int kLastIndexFieldIndex = 4;
7642 static const int kInObjectFieldCount = 5;
7644 // The uninitialized value for a regexp code object.
7645 static const int kUninitializedValue = -1;
7647 // The compilation error value for the regexp code object. The real error
7648 // object is in the saved code field.
7649 static const int kCompilationErrorValue = -2;
7651 // When we store the sweep generation at which we moved the code from the
7652 // code index to the saved code index we mask it of to be in the [0:255]
7654 static const int kCodeAgeMask = 0xff;
7658 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7660 static inline bool IsMatch(HashTableKey* key, Object* value) {
7661 return key->IsMatch(value);
7664 static inline uint32_t Hash(HashTableKey* key) {
7668 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7669 return key->HashForObject(object);
7672 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7674 static const int kPrefixSize = 0;
7675 static const int kEntrySize = 2;
7679 // This cache is used in two different variants. For regexp caching, it simply
7680 // maps identifying info of the regexp to the cached regexp object. Scripts and
7681 // eval code only gets cached after a second probe for the code object. To do
7682 // so, on first "put" only a hash identifying the source is entered into the
7683 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7684 // such lifetimes get reduced, and removed once they reach zero. If a second put
7685 // is called while such a hash is live in the cache, the hash gets replaced by
7686 // an actual cache entry. Age also removes stale live entries from the cache.
7687 // Such entries are identified by SharedFunctionInfos pointing to either the
7688 // recompilation stub, or to "old" code. This avoids memory leaks due to
7689 // premature caching of scripts and eval strings that are never needed later.
7690 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7691 CompilationCacheShape,
7694 // Find cached value for a string key, otherwise return null.
7695 Handle<Object> Lookup(
7696 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7697 Handle<Object> LookupEval(
7698 Handle<String> src, Handle<SharedFunctionInfo> shared,
7699 LanguageMode language_mode, int scope_position);
7700 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7701 static Handle<CompilationCacheTable> Put(
7702 Handle<CompilationCacheTable> cache, Handle<String> src,
7703 Handle<Context> context, LanguageMode language_mode,
7704 Handle<Object> value);
7705 static Handle<CompilationCacheTable> PutEval(
7706 Handle<CompilationCacheTable> cache, Handle<String> src,
7707 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7708 int scope_position);
7709 static Handle<CompilationCacheTable> PutRegExp(
7710 Handle<CompilationCacheTable> cache, Handle<String> src,
7711 JSRegExp::Flags flags, Handle<FixedArray> value);
7712 void Remove(Object* value);
7714 static const int kHashGenerations = 10;
7716 DECLARE_CAST(CompilationCacheTable)
7719 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7723 class CodeCache: public Struct {
7725 DECL_ACCESSORS(default_cache, FixedArray)
7726 DECL_ACCESSORS(normal_type_cache, Object)
7728 // Add the code object to the cache.
7730 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7732 // Lookup code object in the cache. Returns code object if found and undefined
7734 Object* Lookup(Name* name, Code::Flags flags);
7736 // Get the internal index of a code object in the cache. Returns -1 if the
7737 // code object is not in that cache. This index can be used to later call
7738 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7740 int GetIndex(Object* name, Code* code);
7742 // Remove an object from the cache with the provided internal index.
7743 void RemoveByIndex(Object* name, Code* code, int index);
7745 DECLARE_CAST(CodeCache)
7747 // Dispatched behavior.
7748 DECLARE_PRINTER(CodeCache)
7749 DECLARE_VERIFIER(CodeCache)
7751 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7752 static const int kNormalTypeCacheOffset =
7753 kDefaultCacheOffset + kPointerSize;
7754 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7757 static void UpdateDefaultCache(
7758 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7759 static void UpdateNormalTypeCache(
7760 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7761 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7762 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7764 // Code cache layout of the default cache. Elements are alternating name and
7765 // code objects for non normal load/store/call IC's.
7766 static const int kCodeCacheEntrySize = 2;
7767 static const int kCodeCacheEntryNameOffset = 0;
7768 static const int kCodeCacheEntryCodeOffset = 1;
7770 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7774 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7776 static inline bool IsMatch(HashTableKey* key, Object* value) {
7777 return key->IsMatch(value);
7780 static inline uint32_t Hash(HashTableKey* key) {
7784 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7785 return key->HashForObject(object);
7788 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7790 static const int kPrefixSize = 0;
7791 static const int kEntrySize = 2;
7795 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7796 CodeCacheHashTableShape,
7799 Object* Lookup(Name* name, Code::Flags flags);
7800 static Handle<CodeCacheHashTable> Put(
7801 Handle<CodeCacheHashTable> table,
7805 int GetIndex(Name* name, Code::Flags flags);
7806 void RemoveByIndex(int index);
7808 DECLARE_CAST(CodeCacheHashTable)
7810 // Initial size of the fixed array backing the hash table.
7811 static const int kInitialSize = 64;
7814 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7818 class PolymorphicCodeCache: public Struct {
7820 DECL_ACCESSORS(cache, Object)
7822 static void Update(Handle<PolymorphicCodeCache> cache,
7823 MapHandleList* maps,
7828 // Returns an undefined value if the entry is not found.
7829 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7831 DECLARE_CAST(PolymorphicCodeCache)
7833 // Dispatched behavior.
7834 DECLARE_PRINTER(PolymorphicCodeCache)
7835 DECLARE_VERIFIER(PolymorphicCodeCache)
7837 static const int kCacheOffset = HeapObject::kHeaderSize;
7838 static const int kSize = kCacheOffset + kPointerSize;
7841 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7845 class PolymorphicCodeCacheHashTable
7846 : public HashTable<PolymorphicCodeCacheHashTable,
7847 CodeCacheHashTableShape,
7850 Object* Lookup(MapHandleList* maps, int code_kind);
7852 static Handle<PolymorphicCodeCacheHashTable> Put(
7853 Handle<PolymorphicCodeCacheHashTable> hash_table,
7854 MapHandleList* maps,
7858 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7860 static const int kInitialSize = 64;
7862 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7866 class TypeFeedbackInfo: public Struct {
7868 inline int ic_total_count();
7869 inline void set_ic_total_count(int count);
7871 inline int ic_with_type_info_count();
7872 inline void change_ic_with_type_info_count(int delta);
7874 inline int ic_generic_count();
7875 inline void change_ic_generic_count(int delta);
7877 inline void initialize_storage();
7879 inline void change_own_type_change_checksum();
7880 inline int own_type_change_checksum();
7882 inline void set_inlined_type_change_checksum(int checksum);
7883 inline bool matches_inlined_type_change_checksum(int checksum);
7885 DECLARE_CAST(TypeFeedbackInfo)
7887 // Dispatched behavior.
7888 DECLARE_PRINTER(TypeFeedbackInfo)
7889 DECLARE_VERIFIER(TypeFeedbackInfo)
7891 static const int kStorage1Offset = HeapObject::kHeaderSize;
7892 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7893 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7894 static const int kSize = kStorage3Offset + kPointerSize;
7897 static const int kTypeChangeChecksumBits = 7;
7899 class ICTotalCountField: public BitField<int, 0,
7900 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7901 class OwnTypeChangeChecksum: public BitField<int,
7902 kSmiValueSize - kTypeChangeChecksumBits,
7903 kTypeChangeChecksumBits> {}; // NOLINT
7904 class ICsWithTypeInfoCountField: public BitField<int, 0,
7905 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7906 class InlinedTypeChangeChecksum: public BitField<int,
7907 kSmiValueSize - kTypeChangeChecksumBits,
7908 kTypeChangeChecksumBits> {}; // NOLINT
7910 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7914 enum AllocationSiteMode {
7915 DONT_TRACK_ALLOCATION_SITE,
7916 TRACK_ALLOCATION_SITE,
7917 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7921 class AllocationSite: public Struct {
7923 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7924 static const double kPretenureRatio;
7925 static const int kPretenureMinimumCreated = 100;
7927 // Values for pretenure decision field.
7928 enum PretenureDecision {
7934 kLastPretenureDecisionValue = kZombie
7937 const char* PretenureDecisionName(PretenureDecision decision);
7939 DECL_ACCESSORS(transition_info, Object)
7940 // nested_site threads a list of sites that represent nested literals
7941 // walked in a particular order. So [[1, 2], 1, 2] will have one
7942 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7943 DECL_ACCESSORS(nested_site, Object)
7944 DECL_INT_ACCESSORS(pretenure_data)
7945 DECL_INT_ACCESSORS(pretenure_create_count)
7946 DECL_ACCESSORS(dependent_code, DependentCode)
7947 DECL_ACCESSORS(weak_next, Object)
7949 inline void Initialize();
7951 // This method is expensive, it should only be called for reporting.
7952 bool IsNestedSite();
7954 // transition_info bitfields, for constructed array transition info.
7955 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7956 class UnusedBits: public BitField<int, 15, 14> {};
7957 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7959 // Bitfields for pretenure_data
7960 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7961 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7962 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7963 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7965 // Increments the mementos found counter and returns true when the first
7966 // memento was found for a given allocation site.
7967 inline bool IncrementMementoFoundCount();
7969 inline void IncrementMementoCreateCount();
7971 PretenureFlag GetPretenureMode();
7973 void ResetPretenureDecision();
7975 inline PretenureDecision pretenure_decision();
7976 inline void set_pretenure_decision(PretenureDecision decision);
7978 inline bool deopt_dependent_code();
7979 inline void set_deopt_dependent_code(bool deopt);
7981 inline int memento_found_count();
7982 inline void set_memento_found_count(int count);
7984 inline int memento_create_count();
7985 inline void set_memento_create_count(int count);
7987 // The pretenuring decision is made during gc, and the zombie state allows
7988 // us to recognize when an allocation site is just being kept alive because
7989 // a later traversal of new space may discover AllocationMementos that point
7990 // to this AllocationSite.
7991 inline bool IsZombie();
7993 inline bool IsMaybeTenure();
7995 inline void MarkZombie();
7997 inline bool MakePretenureDecision(PretenureDecision current_decision,
7999 bool maximum_size_scavenge);
8001 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8003 inline ElementsKind GetElementsKind();
8004 inline void SetElementsKind(ElementsKind kind);
8006 inline bool CanInlineCall();
8007 inline void SetDoNotInlineCall();
8009 inline bool SitePointsToLiteral();
8011 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8012 ElementsKind to_kind);
8014 DECLARE_PRINTER(AllocationSite)
8015 DECLARE_VERIFIER(AllocationSite)
8017 DECLARE_CAST(AllocationSite)
8018 static inline AllocationSiteMode GetMode(
8019 ElementsKind boilerplate_elements_kind);
8020 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8021 static inline bool CanTrack(InstanceType type);
8023 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8024 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8025 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8026 static const int kPretenureCreateCountOffset =
8027 kPretenureDataOffset + kPointerSize;
8028 static const int kDependentCodeOffset =
8029 kPretenureCreateCountOffset + kPointerSize;
8030 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8031 static const int kSize = kWeakNextOffset + kPointerSize;
8033 // During mark compact we need to take special care for the dependent code
8035 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8036 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8038 // For other visitors, use the fixed body descriptor below.
8039 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8040 kDependentCodeOffset + kPointerSize,
8041 kSize> BodyDescriptor;
8044 inline bool PretenuringDecisionMade();
8046 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8050 class AllocationMemento: public Struct {
8052 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8053 static const int kSize = kAllocationSiteOffset + kPointerSize;
8055 DECL_ACCESSORS(allocation_site, Object)
8057 inline bool IsValid();
8058 inline AllocationSite* GetAllocationSite();
8060 DECLARE_PRINTER(AllocationMemento)
8061 DECLARE_VERIFIER(AllocationMemento)
8063 DECLARE_CAST(AllocationMemento)
8066 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8070 // Representation of a slow alias as part of a sloppy arguments objects.
8071 // For fast aliases (if HasSloppyArgumentsElements()):
8072 // - the parameter map contains an index into the context
8073 // - all attributes of the element have default values
8074 // For slow aliases (if HasDictionaryArgumentsElements()):
8075 // - the parameter map contains no fast alias mapping (i.e. the hole)
8076 // - this struct (in the slow backing store) contains an index into the context
8077 // - all attributes are available as part if the property details
8078 class AliasedArgumentsEntry: public Struct {
8080 inline int aliased_context_slot() const;
8081 inline void set_aliased_context_slot(int count);
8083 DECLARE_CAST(AliasedArgumentsEntry)
8085 // Dispatched behavior.
8086 DECLARE_PRINTER(AliasedArgumentsEntry)
8087 DECLARE_VERIFIER(AliasedArgumentsEntry)
8089 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8090 static const int kSize = kAliasedContextSlot + kPointerSize;
8093 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8097 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8098 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8101 class StringHasher {
8103 explicit inline StringHasher(int length, uint32_t seed);
8105 template <typename schar>
8106 static inline uint32_t HashSequentialString(const schar* chars,
8110 // Reads all the data, even for long strings and computes the utf16 length.
8111 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8113 int* utf16_length_out);
8115 // Calculated hash value for a string consisting of 1 to
8116 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8117 // value is represented decimal value.
8118 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8120 // No string is allowed to have a hash of zero. That value is reserved
8121 // for internal properties. If the hash calculation yields zero then we
8123 static const int kZeroHash = 27;
8125 // Reusable parts of the hashing algorithm.
8126 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8127 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8128 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8129 const uc16* chars, int length));
8130 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8135 // Returns the value to store in the hash field of a string with
8136 // the given length and contents.
8137 uint32_t GetHashField();
8138 // Returns true if the hash of this string can be computed without
8139 // looking at the contents.
8140 inline bool has_trivial_hash();
8141 // Adds a block of characters to the hash.
8142 template<typename Char>
8143 inline void AddCharacters(const Char* chars, int len);
8146 // Add a character to the hash.
8147 inline void AddCharacter(uint16_t c);
8148 // Update index. Returns true if string is still an index.
8149 inline bool UpdateIndex(uint16_t c);
8152 uint32_t raw_running_hash_;
8153 uint32_t array_index_;
8154 bool is_array_index_;
8155 bool is_first_char_;
8156 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8160 class IteratingStringHasher : public StringHasher {
8162 static inline uint32_t Hash(String* string, uint32_t seed);
8163 inline void VisitOneByteString(const uint8_t* chars, int length);
8164 inline void VisitTwoByteString(const uint16_t* chars, int length);
8167 inline IteratingStringHasher(int len, uint32_t seed);
8168 void VisitConsString(ConsString* cons_string);
8169 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8173 // The characteristics of a string are stored in its map. Retrieving these
8174 // few bits of information is moderately expensive, involving two memory
8175 // loads where the second is dependent on the first. To improve efficiency
8176 // the shape of the string is given its own class so that it can be retrieved
8177 // once and used for several string operations. A StringShape is small enough
8178 // to be passed by value and is immutable, but be aware that flattening a
8179 // string can potentially alter its shape. Also be aware that a GC caused by
8180 // something else can alter the shape of a string due to ConsString
8181 // shortcutting. Keeping these restrictions in mind has proven to be error-
8182 // prone and so we no longer put StringShapes in variables unless there is a
8183 // concrete performance benefit at that particular point in the code.
8184 class StringShape BASE_EMBEDDED {
8186 inline explicit StringShape(const String* s);
8187 inline explicit StringShape(Map* s);
8188 inline explicit StringShape(InstanceType t);
8189 inline bool IsSequential();
8190 inline bool IsExternal();
8191 inline bool IsCons();
8192 inline bool IsSliced();
8193 inline bool IsIndirect();
8194 inline bool IsExternalOneByte();
8195 inline bool IsExternalTwoByte();
8196 inline bool IsSequentialOneByte();
8197 inline bool IsSequentialTwoByte();
8198 inline bool IsInternalized();
8199 inline StringRepresentationTag representation_tag();
8200 inline uint32_t encoding_tag();
8201 inline uint32_t full_representation_tag();
8202 inline uint32_t size_tag();
8204 inline uint32_t type() { return type_; }
8205 inline void invalidate() { valid_ = false; }
8206 inline bool valid() { return valid_; }
8208 inline void invalidate() { }
8214 inline void set_valid() { valid_ = true; }
8217 inline void set_valid() { }
8222 // The Name abstract class captures anything that can be used as a property
8223 // name, i.e., strings and symbols. All names store a hash value.
8224 class Name: public HeapObject {
8226 // Get and set the hash field of the name.
8227 inline uint32_t hash_field();
8228 inline void set_hash_field(uint32_t value);
8230 // Tells whether the hash code has been computed.
8231 inline bool HasHashCode();
8233 // Returns a hash value used for the property table
8234 inline uint32_t Hash();
8236 // Equality operations.
8237 inline bool Equals(Name* other);
8238 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8241 inline bool AsArrayIndex(uint32_t* index);
8243 // If the name is private, it can only name own properties.
8244 inline bool IsPrivate();
8246 // If the name is a non-flat string, this method returns a flat version of the
8247 // string. Otherwise it'll just return the input.
8248 static inline Handle<Name> Flatten(Handle<Name> name,
8249 PretenureFlag pretenure = NOT_TENURED);
8251 // Return a string version of this name that is converted according to the
8252 // rules described in ES6 section 9.2.11.
8253 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8257 DECLARE_PRINTER(Name)
8259 void NameShortPrint();
8260 int NameShortPrint(Vector<char> str);
8263 // Layout description.
8264 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8265 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8266 static const int kHashFieldOffset = kHashFieldSlot;
8268 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8270 static const int kSize = kHashFieldSlot + kPointerSize;
8272 // Mask constant for checking if a name has a computed hash code
8273 // and if it is a string that is an array index. The least significant bit
8274 // indicates whether a hash code has been computed. If the hash code has
8275 // been computed the 2nd bit tells whether the string can be used as an
8277 static const int kHashNotComputedMask = 1;
8278 static const int kIsNotArrayIndexMask = 1 << 1;
8279 static const int kNofHashBitFields = 2;
8281 // Shift constant retrieving hash code from hash field.
8282 static const int kHashShift = kNofHashBitFields;
8284 // Only these bits are relevant in the hash, since the top two are shifted
8286 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8288 // Array index strings this short can keep their index in the hash field.
8289 static const int kMaxCachedArrayIndexLength = 7;
8291 // For strings which are array indexes the hash value has the string length
8292 // mixed into the hash, mainly to avoid a hash value of zero which would be
8293 // the case for the string '0'. 24 bits are used for the array index value.
8294 static const int kArrayIndexValueBits = 24;
8295 static const int kArrayIndexLengthBits =
8296 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8298 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8300 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8301 kArrayIndexValueBits> {}; // NOLINT
8302 class ArrayIndexLengthBits : public BitField<unsigned int,
8303 kNofHashBitFields + kArrayIndexValueBits,
8304 kArrayIndexLengthBits> {}; // NOLINT
8306 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8307 // could use a mask to test if the length of string is less than or equal to
8308 // kMaxCachedArrayIndexLength.
8309 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8311 static const unsigned int kContainsCachedArrayIndexMask =
8312 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8313 << ArrayIndexLengthBits::kShift) |
8314 kIsNotArrayIndexMask;
8316 // Value of empty hash field indicating that the hash is not computed.
8317 static const int kEmptyHashField =
8318 kIsNotArrayIndexMask | kHashNotComputedMask;
8321 static inline bool IsHashFieldComputed(uint32_t field);
8324 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8329 class Symbol: public Name {
8331 // [name]: The print name of a symbol, or undefined if none.
8332 DECL_ACCESSORS(name, Object)
8334 DECL_INT_ACCESSORS(flags)
8336 // [is_private]: Whether this is a private symbol. Private symbols can only
8337 // be used to designate own properties of objects.
8338 DECL_BOOLEAN_ACCESSORS(is_private)
8340 DECLARE_CAST(Symbol)
8342 // Dispatched behavior.
8343 DECLARE_PRINTER(Symbol)
8344 DECLARE_VERIFIER(Symbol)
8346 // Layout description.
8347 static const int kNameOffset = Name::kSize;
8348 static const int kFlagsOffset = kNameOffset + kPointerSize;
8349 static const int kSize = kFlagsOffset + kPointerSize;
8351 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8353 void SymbolShortPrint(std::ostream& os);
8356 static const int kPrivateBit = 0;
8358 const char* PrivateSymbolToName() const;
8361 friend class Name; // For PrivateSymbolToName.
8364 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8370 // The String abstract class captures JavaScript string values:
8373 // 4.3.16 String Value
8374 // A string value is a member of the type String and is a finite
8375 // ordered sequence of zero or more 16-bit unsigned integer values.
8377 // All string values have a length field.
8378 class String: public Name {
8380 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8382 // Array index strings this short can keep their index in the hash field.
8383 static const int kMaxCachedArrayIndexLength = 7;
8385 // For strings which are array indexes the hash value has the string length
8386 // mixed into the hash, mainly to avoid a hash value of zero which would be
8387 // the case for the string '0'. 24 bits are used for the array index value.
8388 static const int kArrayIndexValueBits = 24;
8389 static const int kArrayIndexLengthBits =
8390 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8392 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8394 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8395 kArrayIndexValueBits> {}; // NOLINT
8396 class ArrayIndexLengthBits : public BitField<unsigned int,
8397 kNofHashBitFields + kArrayIndexValueBits,
8398 kArrayIndexLengthBits> {}; // NOLINT
8400 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8401 // could use a mask to test if the length of string is less than or equal to
8402 // kMaxCachedArrayIndexLength.
8403 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8405 static const unsigned int kContainsCachedArrayIndexMask =
8406 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8407 << ArrayIndexLengthBits::kShift) |
8408 kIsNotArrayIndexMask;
8410 class SubStringRange {
8412 explicit inline SubStringRange(String* string, int first = 0,
8415 inline iterator begin();
8416 inline iterator end();
8424 // Representation of the flat content of a String.
8425 // A non-flat string doesn't have flat content.
8426 // A flat string has content that's encoded as a sequence of either
8427 // one-byte chars or two-byte UC16.
8428 // Returned by String::GetFlatContent().
8431 // Returns true if the string is flat and this structure contains content.
8432 bool IsFlat() { return state_ != NON_FLAT; }
8433 // Returns true if the structure contains one-byte content.
8434 bool IsOneByte() { return state_ == ONE_BYTE; }
8435 // Returns true if the structure contains two-byte content.
8436 bool IsTwoByte() { return state_ == TWO_BYTE; }
8438 // Return the one byte content of the string. Only use if IsOneByte()
8440 Vector<const uint8_t> ToOneByteVector() {
8441 DCHECK_EQ(ONE_BYTE, state_);
8442 return Vector<const uint8_t>(onebyte_start, length_);
8444 // Return the two-byte content of the string. Only use if IsTwoByte()
8446 Vector<const uc16> ToUC16Vector() {
8447 DCHECK_EQ(TWO_BYTE, state_);
8448 return Vector<const uc16>(twobyte_start, length_);
8452 DCHECK(i < length_);
8453 DCHECK(state_ != NON_FLAT);
8454 if (state_ == ONE_BYTE) return onebyte_start[i];
8455 return twobyte_start[i];
8458 bool UsesSameString(const FlatContent& other) const {
8459 return onebyte_start == other.onebyte_start;
8463 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8465 // Constructors only used by String::GetFlatContent().
8466 explicit FlatContent(const uint8_t* start, int length)
8467 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8468 explicit FlatContent(const uc16* start, int length)
8469 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8470 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8473 const uint8_t* onebyte_start;
8474 const uc16* twobyte_start;
8479 friend class String;
8480 friend class IterableSubString;
8483 template <typename Char>
8484 INLINE(Vector<const Char> GetCharVector());
8486 // Get and set the length of the string.
8487 inline int length() const;
8488 inline void set_length(int value);
8490 // Get and set the length of the string using acquire loads and release
8492 inline int synchronized_length() const;
8493 inline void synchronized_set_length(int value);
8495 // Returns whether this string has only one-byte chars, i.e. all of them can
8496 // be one-byte encoded. This might be the case even if the string is
8497 // two-byte. Such strings may appear when the embedder prefers
8498 // two-byte external representations even for one-byte data.
8499 inline bool IsOneByteRepresentation() const;
8500 inline bool IsTwoByteRepresentation() const;
8502 // Cons and slices have an encoding flag that may not represent the actual
8503 // encoding of the underlying string. This is taken into account here.
8504 // Requires: this->IsFlat()
8505 inline bool IsOneByteRepresentationUnderneath();
8506 inline bool IsTwoByteRepresentationUnderneath();
8508 // NOTE: this should be considered only a hint. False negatives are
8510 inline bool HasOnlyOneByteChars();
8512 // Get and set individual two byte chars in the string.
8513 inline void Set(int index, uint16_t value);
8514 // Get individual two byte char in the string. Repeated calls
8515 // to this method are not efficient unless the string is flat.
8516 INLINE(uint16_t Get(int index));
8518 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8519 static Handle<Object> ToNumber(Handle<String> subject);
8521 // Flattens the string. Checks first inline to see if it is
8522 // necessary. Does nothing if the string is not a cons string.
8523 // Flattening allocates a sequential string with the same data as
8524 // the given string and mutates the cons string to a degenerate
8525 // form, where the first component is the new sequential string and
8526 // the second component is the empty string. If allocation fails,
8527 // this function returns a failure. If flattening succeeds, this
8528 // function returns the sequential string that is now the first
8529 // component of the cons string.
8531 // Degenerate cons strings are handled specially by the garbage
8532 // collector (see IsShortcutCandidate).
8534 static inline Handle<String> Flatten(Handle<String> string,
8535 PretenureFlag pretenure = NOT_TENURED);
8537 // Tries to return the content of a flat string as a structure holding either
8538 // a flat vector of char or of uc16.
8539 // If the string isn't flat, and therefore doesn't have flat content, the
8540 // returned structure will report so, and can't provide a vector of either
8542 FlatContent GetFlatContent();
8544 // Returns the parent of a sliced string or first part of a flat cons string.
8545 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8546 inline String* GetUnderlying();
8548 // String relational comparison, implemented according to ES6 section 7.2.11
8549 // Abstract Relational Comparison (step 5): The comparison of Strings uses a
8550 // simple lexicographic ordering on sequences of code unit values. There is no
8551 // attempt to use the more complex, semantically oriented definitions of
8552 // character or string equality and collating order defined in the Unicode
8553 // specification. Therefore String values that are canonically equal according
8554 // to the Unicode standard could test as unequal. In effect this algorithm
8555 // assumes that both Strings are already in normalized form. Also, note that
8556 // for strings containing supplementary characters, lexicographic ordering on
8557 // sequences of UTF-16 code unit values differs from that on sequences of code
8559 MUST_USE_RESULT static ComparisonResult Compare(Handle<String> x,
8562 // String equality operations.
8563 inline bool Equals(String* other);
8564 inline static bool Equals(Handle<String> one, Handle<String> two);
8565 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8566 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8567 bool IsTwoByteEqualTo(Vector<const uc16> str);
8569 // Return a UTF8 representation of the string. The string is null
8570 // terminated but may optionally contain nulls. Length is returned
8571 // in length_output if length_output is not a null pointer The string
8572 // should be nearly flat, otherwise the performance of this method may
8573 // be very slow (quadratic in the length). Setting robustness_flag to
8574 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8575 // handles unexpected data without causing assert failures and it does not
8576 // do any heap allocations. This is useful when printing stack traces.
8577 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8578 RobustnessFlag robustness_flag,
8579 int offset, int length,
8580 int* length_output = 0);
8581 base::SmartArrayPointer<char> ToCString(
8582 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8583 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8584 int* length_output = 0);
8586 // Return a 16 bit Unicode representation of the string.
8587 // The string should be nearly flat, otherwise the performance of
8588 // of this method may be very bad. Setting robustness_flag to
8589 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8590 // handles unexpected data without causing assert failures and it does not
8591 // do any heap allocations. This is useful when printing stack traces.
8592 base::SmartArrayPointer<uc16> ToWideCString(
8593 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8595 bool ComputeArrayIndex(uint32_t* index);
8598 bool MakeExternal(v8::String::ExternalStringResource* resource);
8599 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8602 inline bool AsArrayIndex(uint32_t* index);
8604 DECLARE_CAST(String)
8606 void PrintOn(FILE* out);
8608 // For use during stack traces. Performs rudimentary sanity check.
8611 // Dispatched behavior.
8612 void StringShortPrint(StringStream* accumulator);
8613 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8614 #if defined(DEBUG) || defined(OBJECT_PRINT)
8615 char* ToAsciiArray();
8617 DECLARE_PRINTER(String)
8618 DECLARE_VERIFIER(String)
8620 inline bool IsFlat();
8622 // Layout description.
8623 static const int kLengthOffset = Name::kSize;
8624 static const int kSize = kLengthOffset + kPointerSize;
8626 // Maximum number of characters to consider when trying to convert a string
8627 // value into an array index.
8628 static const int kMaxArrayIndexSize = 10;
8629 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8632 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8633 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8634 static const int kMaxUtf16CodeUnit = 0xffff;
8635 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8637 // Value of hash field containing computed hash equal to zero.
8638 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8640 // Maximal string length.
8641 static const int kMaxLength = (1 << 28) - 16;
8643 // Max length for computing hash. For strings longer than this limit the
8644 // string length is used as the hash value.
8645 static const int kMaxHashCalcLength = 16383;
8647 // Limit for truncation in short printing.
8648 static const int kMaxShortPrintLength = 1024;
8650 // Support for regular expressions.
8651 const uc16* GetTwoByteData(unsigned start);
8653 // Helper function for flattening strings.
8654 template <typename sinkchar>
8655 static void WriteToFlat(String* source,
8660 // The return value may point to the first aligned word containing the first
8661 // non-one-byte character, rather than directly to the non-one-byte character.
8662 // If the return value is >= the passed length, the entire string was
8664 static inline int NonAsciiStart(const char* chars, int length) {
8665 const char* start = chars;
8666 const char* limit = chars + length;
8668 if (length >= kIntptrSize) {
8669 // Check unaligned bytes.
8670 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8671 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8672 return static_cast<int>(chars - start);
8676 // Check aligned words.
8677 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8678 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8679 while (chars + sizeof(uintptr_t) <= limit) {
8680 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8681 return static_cast<int>(chars - start);
8683 chars += sizeof(uintptr_t);
8686 // Check remaining unaligned bytes.
8687 while (chars < limit) {
8688 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8689 return static_cast<int>(chars - start);
8694 return static_cast<int>(chars - start);
8697 static inline bool IsAscii(const char* chars, int length) {
8698 return NonAsciiStart(chars, length) >= length;
8701 static inline bool IsAscii(const uint8_t* chars, int length) {
8703 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8706 static inline int NonOneByteStart(const uc16* chars, int length) {
8707 const uc16* limit = chars + length;
8708 const uc16* start = chars;
8709 while (chars < limit) {
8710 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8713 return static_cast<int>(chars - start);
8716 static inline bool IsOneByte(const uc16* chars, int length) {
8717 return NonOneByteStart(chars, length) >= length;
8720 template<class Visitor>
8721 static inline ConsString* VisitFlat(Visitor* visitor,
8725 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8726 bool include_ending_line);
8728 // Use the hash field to forward to the canonical internalized string
8729 // when deserializing an internalized string.
8730 inline void SetForwardedInternalizedString(String* string);
8731 inline String* GetForwardedInternalizedString();
8735 friend class StringTableInsertionKey;
8737 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8738 PretenureFlag tenure);
8740 // Slow case of String::Equals. This implementation works on any strings
8741 // but it is most efficient on strings that are almost flat.
8742 bool SlowEquals(String* other);
8744 static bool SlowEquals(Handle<String> one, Handle<String> two);
8746 // Slow case of AsArrayIndex.
8747 bool SlowAsArrayIndex(uint32_t* index);
8749 // Compute and set the hash code.
8750 uint32_t ComputeAndSetHash();
8752 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8756 // The SeqString abstract class captures sequential string values.
8757 class SeqString: public String {
8759 DECLARE_CAST(SeqString)
8761 // Layout description.
8762 static const int kHeaderSize = String::kSize;
8764 // Truncate the string in-place if possible and return the result.
8765 // In case of new_length == 0, the empty string is returned without
8766 // truncating the original string.
8767 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8770 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8774 // The OneByteString class captures sequential one-byte string objects.
8775 // Each character in the OneByteString is an one-byte character.
8776 class SeqOneByteString: public SeqString {
8778 static const bool kHasOneByteEncoding = true;
8780 // Dispatched behavior.
8781 inline uint16_t SeqOneByteStringGet(int index);
8782 inline void SeqOneByteStringSet(int index, uint16_t value);
8784 // Get the address of the characters in this string.
8785 inline Address GetCharsAddress();
8787 inline uint8_t* GetChars();
8789 DECLARE_CAST(SeqOneByteString)
8791 // Garbage collection support. This method is called by the
8792 // garbage collector to compute the actual size of an OneByteString
8794 inline int SeqOneByteStringSize(InstanceType instance_type);
8796 // Computes the size for an OneByteString instance of a given length.
8797 static int SizeFor(int length) {
8798 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8801 // Maximal memory usage for a single sequential one-byte string.
8802 static const int kMaxSize = 512 * MB - 1;
8803 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8806 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8810 // The TwoByteString class captures sequential unicode string objects.
8811 // Each character in the TwoByteString is a two-byte uint16_t.
8812 class SeqTwoByteString: public SeqString {
8814 static const bool kHasOneByteEncoding = false;
8816 // Dispatched behavior.
8817 inline uint16_t SeqTwoByteStringGet(int index);
8818 inline void SeqTwoByteStringSet(int index, uint16_t value);
8820 // Get the address of the characters in this string.
8821 inline Address GetCharsAddress();
8823 inline uc16* GetChars();
8826 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8828 DECLARE_CAST(SeqTwoByteString)
8830 // Garbage collection support. This method is called by the
8831 // garbage collector to compute the actual size of a TwoByteString
8833 inline int SeqTwoByteStringSize(InstanceType instance_type);
8835 // Computes the size for a TwoByteString instance of a given length.
8836 static int SizeFor(int length) {
8837 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8840 // Maximal memory usage for a single sequential two-byte string.
8841 static const int kMaxSize = 512 * MB - 1;
8842 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8843 String::kMaxLength);
8846 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8850 // The ConsString class describes string values built by using the
8851 // addition operator on strings. A ConsString is a pair where the
8852 // first and second components are pointers to other string values.
8853 // One or both components of a ConsString can be pointers to other
8854 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8855 // are non-ConsString string values. The string value represented by
8856 // a ConsString can be obtained by concatenating the leaf string
8857 // values in a left-to-right depth-first traversal of the tree.
8858 class ConsString: public String {
8860 // First string of the cons cell.
8861 inline String* first();
8862 // Doesn't check that the result is a string, even in debug mode. This is
8863 // useful during GC where the mark bits confuse the checks.
8864 inline Object* unchecked_first();
8865 inline void set_first(String* first,
8866 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8868 // Second string of the cons cell.
8869 inline String* second();
8870 // Doesn't check that the result is a string, even in debug mode. This is
8871 // useful during GC where the mark bits confuse the checks.
8872 inline Object* unchecked_second();
8873 inline void set_second(String* second,
8874 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8876 // Dispatched behavior.
8877 uint16_t ConsStringGet(int index);
8879 DECLARE_CAST(ConsString)
8881 // Layout description.
8882 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8883 static const int kSecondOffset = kFirstOffset + kPointerSize;
8884 static const int kSize = kSecondOffset + kPointerSize;
8886 // Minimum length for a cons string.
8887 static const int kMinLength = 13;
8889 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8892 DECLARE_VERIFIER(ConsString)
8895 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8899 // The Sliced String class describes strings that are substrings of another
8900 // sequential string. The motivation is to save time and memory when creating
8901 // a substring. A Sliced String is described as a pointer to the parent,
8902 // the offset from the start of the parent string and the length. Using
8903 // a Sliced String therefore requires unpacking of the parent string and
8904 // adding the offset to the start address. A substring of a Sliced String
8905 // are not nested since the double indirection is simplified when creating
8906 // such a substring.
8907 // Currently missing features are:
8908 // - handling externalized parent strings
8909 // - external strings as parent
8910 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8911 class SlicedString: public String {
8913 inline String* parent();
8914 inline void set_parent(String* parent,
8915 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8916 inline int offset() const;
8917 inline void set_offset(int offset);
8919 // Dispatched behavior.
8920 uint16_t SlicedStringGet(int index);
8922 DECLARE_CAST(SlicedString)
8924 // Layout description.
8925 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8926 static const int kOffsetOffset = kParentOffset + kPointerSize;
8927 static const int kSize = kOffsetOffset + kPointerSize;
8929 // Minimum length for a sliced string.
8930 static const int kMinLength = 13;
8932 typedef FixedBodyDescriptor<kParentOffset,
8933 kOffsetOffset + kPointerSize, kSize>
8936 DECLARE_VERIFIER(SlicedString)
8939 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8943 // The ExternalString class describes string values that are backed by
8944 // a string resource that lies outside the V8 heap. ExternalStrings
8945 // consist of the length field common to all strings, a pointer to the
8946 // external resource. It is important to ensure (externally) that the
8947 // resource is not deallocated while the ExternalString is live in the
8950 // The API expects that all ExternalStrings are created through the
8951 // API. Therefore, ExternalStrings should not be used internally.
8952 class ExternalString: public String {
8954 DECLARE_CAST(ExternalString)
8956 // Layout description.
8957 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8958 static const int kShortSize = kResourceOffset + kPointerSize;
8959 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8960 static const int kSize = kResourceDataOffset + kPointerSize;
8962 static const int kMaxShortLength =
8963 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8965 // Return whether external string is short (data pointer is not cached).
8966 inline bool is_short();
8968 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8971 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8975 // The ExternalOneByteString class is an external string backed by an
8977 class ExternalOneByteString : public ExternalString {
8979 static const bool kHasOneByteEncoding = true;
8981 typedef v8::String::ExternalOneByteStringResource Resource;
8983 // The underlying resource.
8984 inline const Resource* resource();
8985 inline void set_resource(const Resource* buffer);
8987 // Update the pointer cache to the external character array.
8988 // The cached pointer is always valid, as the external character array does =
8989 // not move during lifetime. Deserialization is the only exception, after
8990 // which the pointer cache has to be refreshed.
8991 inline void update_data_cache();
8993 inline const uint8_t* GetChars();
8995 // Dispatched behavior.
8996 inline uint16_t ExternalOneByteStringGet(int index);
8998 DECLARE_CAST(ExternalOneByteString)
9000 // Garbage collection support.
9001 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9003 template <typename StaticVisitor>
9004 inline void ExternalOneByteStringIterateBody();
9007 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9011 // The ExternalTwoByteString class is an external string backed by a UTF-16
9013 class ExternalTwoByteString: public ExternalString {
9015 static const bool kHasOneByteEncoding = false;
9017 typedef v8::String::ExternalStringResource Resource;
9019 // The underlying string resource.
9020 inline const Resource* resource();
9021 inline void set_resource(const Resource* buffer);
9023 // Update the pointer cache to the external character array.
9024 // The cached pointer is always valid, as the external character array does =
9025 // not move during lifetime. Deserialization is the only exception, after
9026 // which the pointer cache has to be refreshed.
9027 inline void update_data_cache();
9029 inline const uint16_t* GetChars();
9031 // Dispatched behavior.
9032 inline uint16_t ExternalTwoByteStringGet(int index);
9035 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9037 DECLARE_CAST(ExternalTwoByteString)
9039 // Garbage collection support.
9040 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9042 template<typename StaticVisitor>
9043 inline void ExternalTwoByteStringIterateBody();
9046 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9050 // Utility superclass for stack-allocated objects that must be updated
9051 // on gc. It provides two ways for the gc to update instances, either
9052 // iterating or updating after gc.
9053 class Relocatable BASE_EMBEDDED {
9055 explicit inline Relocatable(Isolate* isolate);
9056 inline virtual ~Relocatable();
9057 virtual void IterateInstance(ObjectVisitor* v) { }
9058 virtual void PostGarbageCollection() { }
9060 static void PostGarbageCollectionProcessing(Isolate* isolate);
9061 static int ArchiveSpacePerThread();
9062 static char* ArchiveState(Isolate* isolate, char* to);
9063 static char* RestoreState(Isolate* isolate, char* from);
9064 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9065 static void Iterate(ObjectVisitor* v, Relocatable* top);
9066 static char* Iterate(ObjectVisitor* v, char* t);
9074 // A flat string reader provides random access to the contents of a
9075 // string independent of the character width of the string. The handle
9076 // must be valid as long as the reader is being used.
9077 class FlatStringReader : public Relocatable {
9079 FlatStringReader(Isolate* isolate, Handle<String> str);
9080 FlatStringReader(Isolate* isolate, Vector<const char> input);
9081 void PostGarbageCollection();
9082 inline uc32 Get(int index);
9083 template <typename Char>
9084 inline Char Get(int index);
9085 int length() { return length_; }
9094 // This maintains an off-stack representation of the stack frames required
9095 // to traverse a ConsString, allowing an entirely iterative and restartable
9096 // traversal of the entire string
9097 class ConsStringIterator {
9099 inline ConsStringIterator() {}
9100 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9101 Reset(cons_string, offset);
9103 inline void Reset(ConsString* cons_string, int offset = 0) {
9105 // Next will always return NULL.
9106 if (cons_string == NULL) return;
9107 Initialize(cons_string, offset);
9109 // Returns NULL when complete.
9110 inline String* Next(int* offset_out) {
9112 if (depth_ == 0) return NULL;
9113 return Continue(offset_out);
9117 static const int kStackSize = 32;
9118 // Use a mask instead of doing modulo operations for stack wrapping.
9119 static const int kDepthMask = kStackSize-1;
9120 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9121 static inline int OffsetForDepth(int depth);
9123 inline void PushLeft(ConsString* string);
9124 inline void PushRight(ConsString* string);
9125 inline void AdjustMaximumDepth();
9127 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9128 void Initialize(ConsString* cons_string, int offset);
9129 String* Continue(int* offset_out);
9130 String* NextLeaf(bool* blew_stack);
9131 String* Search(int* offset_out);
9133 // Stack must always contain only frames for which right traversal
9134 // has not yet been performed.
9135 ConsString* frames_[kStackSize];
9140 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9144 class StringCharacterStream {
9146 inline StringCharacterStream(String* string,
9148 inline uint16_t GetNext();
9149 inline bool HasMore();
9150 inline void Reset(String* string, int offset = 0);
9151 inline void VisitOneByteString(const uint8_t* chars, int length);
9152 inline void VisitTwoByteString(const uint16_t* chars, int length);
9155 ConsStringIterator iter_;
9158 const uint8_t* buffer8_;
9159 const uint16_t* buffer16_;
9161 const uint8_t* end_;
9162 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9166 template <typename T>
9167 class VectorIterator {
9169 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9170 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9171 T GetNext() { return data_[index_++]; }
9172 bool has_more() { return index_ < data_.length(); }
9174 Vector<const T> data_;
9179 // The Oddball describes objects null, undefined, true, and false.
9180 class Oddball: public HeapObject {
9182 // [to_string]: Cached to_string computed at startup.
9183 DECL_ACCESSORS(to_string, String)
9185 // [to_number]: Cached to_number computed at startup.
9186 DECL_ACCESSORS(to_number, Object)
9188 // [typeof]: Cached type_of computed at startup.
9189 DECL_ACCESSORS(type_of, String)
9191 inline byte kind() const;
9192 inline void set_kind(byte kind);
9194 // ES6 section 7.1.3 ToNumber for Boolean, Null, Undefined.
9195 MUST_USE_RESULT static inline Handle<Object> ToNumber(Handle<Oddball> input);
9197 DECLARE_CAST(Oddball)
9199 // Dispatched behavior.
9200 DECLARE_VERIFIER(Oddball)
9202 // Initialize the fields.
9203 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9204 const char* to_string, Handle<Object> to_number,
9205 const char* type_of, byte kind);
9207 // Layout description.
9208 static const int kToStringOffset = HeapObject::kHeaderSize;
9209 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9210 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9211 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9212 static const int kSize = kKindOffset + kPointerSize;
9214 static const byte kFalse = 0;
9215 static const byte kTrue = 1;
9216 static const byte kNotBooleanMask = ~1;
9217 static const byte kTheHole = 2;
9218 static const byte kNull = 3;
9219 static const byte kArgumentMarker = 4;
9220 static const byte kUndefined = 5;
9221 static const byte kUninitialized = 6;
9222 static const byte kOther = 7;
9223 static const byte kException = 8;
9225 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9226 kSize> BodyDescriptor;
9228 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9229 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9230 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9233 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9237 class Cell: public HeapObject {
9239 // [value]: value of the cell.
9240 DECL_ACCESSORS(value, Object)
9244 static inline Cell* FromValueAddress(Address value) {
9245 Object* result = FromAddress(value - kValueOffset);
9246 return static_cast<Cell*>(result);
9249 inline Address ValueAddress() {
9250 return address() + kValueOffset;
9253 // Dispatched behavior.
9254 DECLARE_PRINTER(Cell)
9255 DECLARE_VERIFIER(Cell)
9257 // Layout description.
9258 static const int kValueOffset = HeapObject::kHeaderSize;
9259 static const int kSize = kValueOffset + kPointerSize;
9261 typedef FixedBodyDescriptor<kValueOffset,
9262 kValueOffset + kPointerSize,
9263 kSize> BodyDescriptor;
9266 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9270 class PropertyCell : public HeapObject {
9272 // [property_details]: details of the global property.
9273 DECL_ACCESSORS(property_details_raw, Object)
9274 // [value]: value of the global property.
9275 DECL_ACCESSORS(value, Object)
9276 // [dependent_code]: dependent code that depends on the type of the global
9278 DECL_ACCESSORS(dependent_code, DependentCode)
9280 inline PropertyDetails property_details();
9281 inline void set_property_details(PropertyDetails details);
9283 PropertyCellConstantType GetConstantType();
9285 // Computes the new type of the cell's contents for the given value, but
9286 // without actually modifying the details.
9287 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9288 Handle<Object> value,
9289 PropertyDetails details);
9290 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9291 Handle<Object> value, PropertyDetails details);
9293 static Handle<PropertyCell> InvalidateEntry(
9294 Handle<GlobalDictionary> dictionary, int entry);
9296 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9297 Handle<Object> new_value);
9299 DECLARE_CAST(PropertyCell)
9301 // Dispatched behavior.
9302 DECLARE_PRINTER(PropertyCell)
9303 DECLARE_VERIFIER(PropertyCell)
9305 // Layout description.
9306 static const int kDetailsOffset = HeapObject::kHeaderSize;
9307 static const int kValueOffset = kDetailsOffset + kPointerSize;
9308 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9309 static const int kSize = kDependentCodeOffset + kPointerSize;
9311 static const int kPointerFieldsBeginOffset = kValueOffset;
9312 static const int kPointerFieldsEndOffset = kSize;
9314 typedef FixedBodyDescriptor<kValueOffset,
9316 kSize> BodyDescriptor;
9319 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9323 class WeakCell : public HeapObject {
9325 inline Object* value() const;
9327 // This should not be called by anyone except GC.
9328 inline void clear();
9330 // This should not be called by anyone except allocator.
9331 inline void initialize(HeapObject* value);
9333 inline bool cleared() const;
9335 DECL_ACCESSORS(next, Object)
9337 inline void clear_next(Heap* heap);
9339 inline bool next_cleared();
9341 DECLARE_CAST(WeakCell)
9343 DECLARE_PRINTER(WeakCell)
9344 DECLARE_VERIFIER(WeakCell)
9346 // Layout description.
9347 static const int kValueOffset = HeapObject::kHeaderSize;
9348 static const int kNextOffset = kValueOffset + kPointerSize;
9349 static const int kSize = kNextOffset + kPointerSize;
9351 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9354 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9358 // The JSProxy describes EcmaScript Harmony proxies
9359 class JSProxy: public JSReceiver {
9361 // [handler]: The handler property.
9362 DECL_ACCESSORS(handler, Object)
9364 // [hash]: The hash code property (undefined if not initialized yet).
9365 DECL_ACCESSORS(hash, Object)
9367 DECLARE_CAST(JSProxy)
9369 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9370 Handle<JSProxy> proxy,
9371 Handle<Object> receiver,
9374 // If the handler defines an accessor property with a setter, invoke it.
9375 // If it defines an accessor property without a setter, or a data property
9376 // that is read-only, throw. In all these cases set '*done' to true,
9377 // otherwise set it to false.
9379 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9380 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9381 Handle<Object> value, LanguageMode language_mode, bool* done);
9383 MUST_USE_RESULT static Maybe<PropertyAttributes>
9384 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9385 Handle<Object> receiver,
9387 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9388 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9389 Handle<Object> value, LanguageMode language_mode);
9391 // Turn the proxy into an (empty) JSObject.
9392 static void Fix(Handle<JSProxy> proxy);
9394 // Initializes the body after the handler slot.
9395 inline void InitializeBody(int object_size, Object* value);
9397 // Invoke a trap by name. If the trap does not exist on this's handler,
9398 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9399 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9400 Handle<JSProxy> proxy,
9402 Handle<Object> derived_trap,
9404 Handle<Object> args[]);
9406 // Dispatched behavior.
9407 DECLARE_PRINTER(JSProxy)
9408 DECLARE_VERIFIER(JSProxy)
9410 // Layout description. We add padding so that a proxy has the same
9411 // size as a virgin JSObject. This is essential for becoming a JSObject
9413 static const int kHandlerOffset = HeapObject::kHeaderSize;
9414 static const int kHashOffset = kHandlerOffset + kPointerSize;
9415 static const int kPaddingOffset = kHashOffset + kPointerSize;
9416 static const int kSize = JSObject::kHeaderSize;
9417 static const int kHeaderSize = kPaddingOffset;
9418 static const int kPaddingSize = kSize - kPaddingOffset;
9420 STATIC_ASSERT(kPaddingSize >= 0);
9422 typedef FixedBodyDescriptor<kHandlerOffset,
9424 kSize> BodyDescriptor;
9427 friend class JSReceiver;
9429 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9430 Handle<JSProxy> proxy, Handle<Name> name);
9432 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9433 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9435 MUST_USE_RESULT Object* GetIdentityHash();
9437 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9439 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9443 class JSFunctionProxy: public JSProxy {
9445 // [call_trap]: The call trap.
9446 DECL_ACCESSORS(call_trap, JSReceiver)
9448 // [construct_trap]: The construct trap.
9449 DECL_ACCESSORS(construct_trap, Object)
9451 DECLARE_CAST(JSFunctionProxy)
9453 // Dispatched behavior.
9454 DECLARE_PRINTER(JSFunctionProxy)
9455 DECLARE_VERIFIER(JSFunctionProxy)
9457 // Layout description.
9458 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9459 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9460 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9461 static const int kSize = JSFunction::kSize;
9462 static const int kPaddingSize = kSize - kPaddingOffset;
9464 STATIC_ASSERT(kPaddingSize >= 0);
9466 typedef FixedBodyDescriptor<kHandlerOffset,
9467 kConstructTrapOffset + kPointerSize,
9468 kSize> BodyDescriptor;
9471 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9475 class JSCollection : public JSObject {
9477 // [table]: the backing hash table
9478 DECL_ACCESSORS(table, Object)
9480 static const int kTableOffset = JSObject::kHeaderSize;
9481 static const int kSize = kTableOffset + kPointerSize;
9484 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9488 // The JSSet describes EcmaScript Harmony sets
9489 class JSSet : public JSCollection {
9493 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9494 static void Clear(Handle<JSSet> set);
9496 // Dispatched behavior.
9497 DECLARE_PRINTER(JSSet)
9498 DECLARE_VERIFIER(JSSet)
9501 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9505 // The JSMap describes EcmaScript Harmony maps
9506 class JSMap : public JSCollection {
9510 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9511 static void Clear(Handle<JSMap> map);
9513 // Dispatched behavior.
9514 DECLARE_PRINTER(JSMap)
9515 DECLARE_VERIFIER(JSMap)
9518 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9522 // OrderedHashTableIterator is an iterator that iterates over the keys and
9523 // values of an OrderedHashTable.
9525 // The iterator has a reference to the underlying OrderedHashTable data,
9526 // [table], as well as the current [index] the iterator is at.
9528 // When the OrderedHashTable is rehashed it adds a reference from the old table
9529 // to the new table as well as storing enough data about the changes so that the
9530 // iterator [index] can be adjusted accordingly.
9532 // When the [Next] result from the iterator is requested, the iterator checks if
9533 // there is a newer table that it needs to transition to.
9534 template<class Derived, class TableType>
9535 class OrderedHashTableIterator: public JSObject {
9537 // [table]: the backing hash table mapping keys to values.
9538 DECL_ACCESSORS(table, Object)
9540 // [index]: The index into the data table.
9541 DECL_ACCESSORS(index, Object)
9543 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9544 DECL_ACCESSORS(kind, Object)
9547 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9550 static const int kTableOffset = JSObject::kHeaderSize;
9551 static const int kIndexOffset = kTableOffset + kPointerSize;
9552 static const int kKindOffset = kIndexOffset + kPointerSize;
9553 static const int kSize = kKindOffset + kPointerSize;
9561 // Whether the iterator has more elements. This needs to be called before
9562 // calling |CurrentKey| and/or |CurrentValue|.
9565 // Move the index forward one.
9567 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9570 // Populates the array with the next key and value and then moves the iterator
9572 // This returns the |kind| or 0 if the iterator is already at the end.
9573 Smi* Next(JSArray* value_array);
9575 // Returns the current key of the iterator. This should only be called when
9576 // |HasMore| returns true.
9577 inline Object* CurrentKey();
9580 // Transitions the iterator to the non obsolete backing store. This is a NOP
9581 // if the [table] is not obsolete.
9584 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9588 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9591 // Dispatched behavior.
9592 DECLARE_PRINTER(JSSetIterator)
9593 DECLARE_VERIFIER(JSSetIterator)
9595 DECLARE_CAST(JSSetIterator)
9597 // Called by |Next| to populate the array. This allows the subclasses to
9598 // populate the array differently.
9599 inline void PopulateValueArray(FixedArray* array);
9602 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9606 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9609 // Dispatched behavior.
9610 DECLARE_PRINTER(JSMapIterator)
9611 DECLARE_VERIFIER(JSMapIterator)
9613 DECLARE_CAST(JSMapIterator)
9615 // Called by |Next| to populate the array. This allows the subclasses to
9616 // populate the array differently.
9617 inline void PopulateValueArray(FixedArray* array);
9620 // Returns the current value of the iterator. This should only be called when
9621 // |HasMore| returns true.
9622 inline Object* CurrentValue();
9624 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9628 // ES6 section 25.1.1.3 The IteratorResult Interface
9629 class JSIteratorResult final : public JSObject {
9631 // [done]: This is the result status of an iterator next method call. If the
9632 // end of the iterator was reached done is true. If the end was not reached
9633 // done is false and a [value] is available.
9634 DECL_ACCESSORS(done, Object)
9636 // [value]: If [done] is false, this is the current iteration element value.
9637 // If [done] is true, this is the return value of the iterator, if it supplied
9638 // one. If the iterator does not have a return value, value is undefined.
9639 // In that case, the value property may be absent from the conforming object
9640 // if it does not inherit an explicit value property.
9641 DECL_ACCESSORS(value, Object)
9643 // Dispatched behavior.
9644 DECLARE_PRINTER(JSIteratorResult)
9645 DECLARE_VERIFIER(JSIteratorResult)
9647 DECLARE_CAST(JSIteratorResult)
9649 static const int kValueOffset = JSObject::kHeaderSize;
9650 static const int kDoneOffset = kValueOffset + kPointerSize;
9651 static const int kSize = kDoneOffset + kPointerSize;
9653 // Indices of in-object properties.
9654 static const int kValueIndex = 0;
9655 static const int kDoneIndex = 1;
9658 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9662 // Base class for both JSWeakMap and JSWeakSet
9663 class JSWeakCollection: public JSObject {
9665 // [table]: the backing hash table mapping keys to values.
9666 DECL_ACCESSORS(table, Object)
9668 // [next]: linked list of encountered weak maps during GC.
9669 DECL_ACCESSORS(next, Object)
9671 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9672 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9673 Handle<Object> value, int32_t hash);
9674 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9677 static const int kTableOffset = JSObject::kHeaderSize;
9678 static const int kNextOffset = kTableOffset + kPointerSize;
9679 static const int kSize = kNextOffset + kPointerSize;
9682 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9686 // The JSWeakMap describes EcmaScript Harmony weak maps
9687 class JSWeakMap: public JSWeakCollection {
9689 DECLARE_CAST(JSWeakMap)
9691 // Dispatched behavior.
9692 DECLARE_PRINTER(JSWeakMap)
9693 DECLARE_VERIFIER(JSWeakMap)
9696 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9700 // The JSWeakSet describes EcmaScript Harmony weak sets
9701 class JSWeakSet: public JSWeakCollection {
9703 DECLARE_CAST(JSWeakSet)
9705 // Dispatched behavior.
9706 DECLARE_PRINTER(JSWeakSet)
9707 DECLARE_VERIFIER(JSWeakSet)
9710 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9714 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9715 enum class SharedFlag { kNotShared, kShared };
9718 class JSArrayBuffer: public JSObject {
9720 // [backing_store]: backing memory for this array
9721 DECL_ACCESSORS(backing_store, void)
9723 // [byte_length]: length in bytes
9724 DECL_ACCESSORS(byte_length, Object)
9726 inline uint32_t bit_field() const;
9727 inline void set_bit_field(uint32_t bits);
9729 inline bool is_external();
9730 inline void set_is_external(bool value);
9732 inline bool is_neuterable();
9733 inline void set_is_neuterable(bool value);
9735 inline bool was_neutered();
9736 inline void set_was_neutered(bool value);
9738 inline bool is_shared();
9739 inline void set_is_shared(bool value);
9741 DECLARE_CAST(JSArrayBuffer)
9745 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9746 bool is_external, void* data, size_t allocated_length,
9747 SharedFlag shared = SharedFlag::kNotShared);
9749 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9750 Isolate* isolate, size_t allocated_length,
9751 bool initialize = true,
9752 SharedFlag shared = SharedFlag::kNotShared);
9754 // Dispatched behavior.
9755 DECLARE_PRINTER(JSArrayBuffer)
9756 DECLARE_VERIFIER(JSArrayBuffer)
9758 static const int kByteLengthOffset = JSObject::kHeaderSize;
9760 // NOTE: GC will visit objects fields:
9761 // 1. From JSObject::BodyDescriptor::kStartOffset to kByteLengthOffset +
9763 // 2. From start of the internal fields and up to the end of them
9764 static const int kBackingStoreOffset = kByteLengthOffset + kPointerSize;
9765 static const int kBitFieldSlot = kBackingStoreOffset + kPointerSize;
9766 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9767 static const int kBitFieldOffset = kBitFieldSlot;
9769 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9771 static const int kSize = kBitFieldSlot + kPointerSize;
9773 static const int kSizeWithInternalFields =
9774 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9776 template <typename StaticVisitor>
9777 static inline void JSArrayBufferIterateBody(Heap* heap, HeapObject* obj);
9779 static inline void JSArrayBufferIterateBody(HeapObject* obj,
9782 class IsExternal : public BitField<bool, 1, 1> {};
9783 class IsNeuterable : public BitField<bool, 2, 1> {};
9784 class WasNeutered : public BitField<bool, 3, 1> {};
9785 class IsShared : public BitField<bool, 4, 1> {};
9788 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9792 class JSArrayBufferView: public JSObject {
9794 // [buffer]: ArrayBuffer that this typed array views.
9795 DECL_ACCESSORS(buffer, Object)
9797 // [byte_offset]: offset of typed array in bytes.
9798 DECL_ACCESSORS(byte_offset, Object)
9800 // [byte_length]: length of typed array in bytes.
9801 DECL_ACCESSORS(byte_length, Object)
9803 DECLARE_CAST(JSArrayBufferView)
9805 DECLARE_VERIFIER(JSArrayBufferView)
9807 inline bool WasNeutered() const;
9809 static const int kBufferOffset = JSObject::kHeaderSize;
9810 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9811 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9812 static const int kViewSize = kByteLengthOffset + kPointerSize;
9816 DECL_ACCESSORS(raw_byte_offset, Object)
9817 DECL_ACCESSORS(raw_byte_length, Object)
9820 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9824 class JSTypedArray: public JSArrayBufferView {
9826 // [length]: length of typed array in elements.
9827 DECL_ACCESSORS(length, Object)
9828 inline uint32_t length_value() const;
9830 DECLARE_CAST(JSTypedArray)
9832 ExternalArrayType type();
9833 size_t element_size();
9835 Handle<JSArrayBuffer> GetBuffer();
9837 // Dispatched behavior.
9838 DECLARE_PRINTER(JSTypedArray)
9839 DECLARE_VERIFIER(JSTypedArray)
9841 static const int kLengthOffset = kViewSize + kPointerSize;
9842 static const int kSize = kLengthOffset + kPointerSize;
9844 static const int kSizeWithInternalFields =
9845 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9848 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9849 Handle<JSTypedArray> typed_array);
9851 DECL_ACCESSORS(raw_length, Object)
9854 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9858 class JSDataView: public JSArrayBufferView {
9860 DECLARE_CAST(JSDataView)
9862 // Dispatched behavior.
9863 DECLARE_PRINTER(JSDataView)
9864 DECLARE_VERIFIER(JSDataView)
9866 static const int kSize = kViewSize;
9868 static const int kSizeWithInternalFields =
9869 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9872 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9876 // Foreign describes objects pointing from JavaScript to C structures.
9877 class Foreign: public HeapObject {
9879 // [address]: field containing the address.
9880 inline Address foreign_address();
9881 inline void set_foreign_address(Address value);
9883 DECLARE_CAST(Foreign)
9885 // Dispatched behavior.
9886 inline void ForeignIterateBody(ObjectVisitor* v);
9888 template<typename StaticVisitor>
9889 inline void ForeignIterateBody();
9891 // Dispatched behavior.
9892 DECLARE_PRINTER(Foreign)
9893 DECLARE_VERIFIER(Foreign)
9895 // Layout description.
9897 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9898 static const int kSize = kForeignAddressOffset + kPointerSize;
9900 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9903 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9907 // The JSArray describes JavaScript Arrays
9908 // Such an array can be in one of two modes:
9909 // - fast, backing storage is a FixedArray and length <= elements.length();
9910 // Please note: push and pop can be used to grow and shrink the array.
9911 // - slow, backing storage is a HashTable with numbers as keys.
9912 class JSArray: public JSObject {
9914 // [length]: The length property.
9915 DECL_ACCESSORS(length, Object)
9917 // Overload the length setter to skip write barrier when the length
9918 // is set to a smi. This matches the set function on FixedArray.
9919 inline void set_length(Smi* length);
9921 static bool HasReadOnlyLength(Handle<JSArray> array);
9922 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9923 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9925 // Initialize the array with the given capacity. The function may
9926 // fail due to out-of-memory situations, but only if the requested
9927 // capacity is non-zero.
9928 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9930 // If the JSArray has fast elements, and new_length would result in
9931 // normalization, returns true.
9932 bool SetLengthWouldNormalize(uint32_t new_length);
9933 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9935 // Initializes the array to a certain length.
9936 inline bool AllowsSetLength();
9938 static void SetLength(Handle<JSArray> array, uint32_t length);
9939 // Same as above but will also queue splice records if |array| is observed.
9940 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9943 // Set the content of the array to the content of storage.
9944 static inline void SetContent(Handle<JSArray> array,
9945 Handle<FixedArrayBase> storage);
9947 DECLARE_CAST(JSArray)
9949 // Dispatched behavior.
9950 DECLARE_PRINTER(JSArray)
9951 DECLARE_VERIFIER(JSArray)
9953 // Number of element slots to pre-allocate for an empty array.
9954 static const int kPreallocatedArrayElements = 4;
9956 // Layout description.
9957 static const int kLengthOffset = JSObject::kHeaderSize;
9958 static const int kSize = kLengthOffset + kPointerSize;
9961 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9965 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9966 Handle<Map> initial_map);
9969 // JSRegExpResult is just a JSArray with a specific initial map.
9970 // This initial map adds in-object properties for "index" and "input"
9971 // properties, as assigned by RegExp.prototype.exec, which allows
9972 // faster creation of RegExp exec results.
9973 // This class just holds constants used when creating the result.
9974 // After creation the result must be treated as a JSArray in all regards.
9975 class JSRegExpResult: public JSArray {
9977 // Offsets of object fields.
9978 static const int kIndexOffset = JSArray::kSize;
9979 static const int kInputOffset = kIndexOffset + kPointerSize;
9980 static const int kSize = kInputOffset + kPointerSize;
9981 // Indices of in-object properties.
9982 static const int kIndexIndex = 0;
9983 static const int kInputIndex = 1;
9985 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9989 class AccessorInfo: public Struct {
9991 DECL_ACCESSORS(name, Object)
9992 DECL_INT_ACCESSORS(flag)
9993 DECL_ACCESSORS(expected_receiver_type, Object)
9995 inline bool all_can_read();
9996 inline void set_all_can_read(bool value);
9998 inline bool all_can_write();
9999 inline void set_all_can_write(bool value);
10001 inline bool is_special_data_property();
10002 inline void set_is_special_data_property(bool value);
10004 inline PropertyAttributes property_attributes();
10005 inline void set_property_attributes(PropertyAttributes attributes);
10007 // Checks whether the given receiver is compatible with this accessor.
10008 static bool IsCompatibleReceiverMap(Isolate* isolate,
10009 Handle<AccessorInfo> info,
10011 inline bool IsCompatibleReceiver(Object* receiver);
10013 DECLARE_CAST(AccessorInfo)
10015 // Dispatched behavior.
10016 DECLARE_VERIFIER(AccessorInfo)
10018 // Append all descriptors to the array that are not already there.
10019 // Return number added.
10020 static int AppendUnique(Handle<Object> descriptors,
10021 Handle<FixedArray> array,
10022 int valid_descriptors);
10024 static const int kNameOffset = HeapObject::kHeaderSize;
10025 static const int kFlagOffset = kNameOffset + kPointerSize;
10026 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10027 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10030 inline bool HasExpectedReceiverType();
10032 // Bit positions in flag.
10033 static const int kAllCanReadBit = 0;
10034 static const int kAllCanWriteBit = 1;
10035 static const int kSpecialDataProperty = 2;
10036 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10038 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10042 // An accessor must have a getter, but can have no setter.
10044 // When setting a property, V8 searches accessors in prototypes.
10045 // If an accessor was found and it does not have a setter,
10046 // the request is ignored.
10048 // If the accessor in the prototype has the READ_ONLY property attribute, then
10049 // a new value is added to the derived object when the property is set.
10050 // This shadows the accessor in the prototype.
10051 class ExecutableAccessorInfo: public AccessorInfo {
10053 DECL_ACCESSORS(getter, Object)
10054 DECL_ACCESSORS(setter, Object)
10055 DECL_ACCESSORS(data, Object)
10057 DECLARE_CAST(ExecutableAccessorInfo)
10059 // Dispatched behavior.
10060 DECLARE_PRINTER(ExecutableAccessorInfo)
10061 DECLARE_VERIFIER(ExecutableAccessorInfo)
10063 static const int kGetterOffset = AccessorInfo::kSize;
10064 static const int kSetterOffset = kGetterOffset + kPointerSize;
10065 static const int kDataOffset = kSetterOffset + kPointerSize;
10066 static const int kSize = kDataOffset + kPointerSize;
10068 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10071 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10075 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10076 // accessor can either be
10077 // * a pointer to a JavaScript function or proxy: a real accessor
10078 // * undefined: considered an accessor by the spec, too, strangely enough
10079 // * the hole: an accessor which has not been set
10080 // * a pointer to a map: a transition used to ensure map sharing
10081 class AccessorPair: public Struct {
10083 DECL_ACCESSORS(getter, Object)
10084 DECL_ACCESSORS(setter, Object)
10086 DECLARE_CAST(AccessorPair)
10088 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10090 inline Object* get(AccessorComponent component);
10091 inline void set(AccessorComponent component, Object* value);
10093 // Note: Returns undefined instead in case of a hole.
10094 Object* GetComponent(AccessorComponent component);
10096 // Set both components, skipping arguments which are a JavaScript null.
10097 inline void SetComponents(Object* getter, Object* setter);
10099 inline bool Equals(AccessorPair* pair);
10100 inline bool Equals(Object* getter_value, Object* setter_value);
10102 inline bool ContainsAccessor();
10104 // Dispatched behavior.
10105 DECLARE_PRINTER(AccessorPair)
10106 DECLARE_VERIFIER(AccessorPair)
10108 static const int kGetterOffset = HeapObject::kHeaderSize;
10109 static const int kSetterOffset = kGetterOffset + kPointerSize;
10110 static const int kSize = kSetterOffset + kPointerSize;
10113 // Strangely enough, in addition to functions and harmony proxies, the spec
10114 // requires us to consider undefined as a kind of accessor, too:
10116 // Object.defineProperty(obj, "foo", {get: undefined});
10117 // assertTrue("foo" in obj);
10118 inline bool IsJSAccessor(Object* obj);
10120 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10124 class AccessCheckInfo: public Struct {
10126 DECL_ACCESSORS(named_callback, Object)
10127 DECL_ACCESSORS(indexed_callback, Object)
10128 DECL_ACCESSORS(data, Object)
10130 DECLARE_CAST(AccessCheckInfo)
10132 // Dispatched behavior.
10133 DECLARE_PRINTER(AccessCheckInfo)
10134 DECLARE_VERIFIER(AccessCheckInfo)
10136 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10137 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10138 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10139 static const int kSize = kDataOffset + kPointerSize;
10142 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10146 class InterceptorInfo: public Struct {
10148 DECL_ACCESSORS(getter, Object)
10149 DECL_ACCESSORS(setter, Object)
10150 DECL_ACCESSORS(query, Object)
10151 DECL_ACCESSORS(deleter, Object)
10152 DECL_ACCESSORS(enumerator, Object)
10153 DECL_ACCESSORS(data, Object)
10154 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10155 DECL_BOOLEAN_ACCESSORS(all_can_read)
10156 DECL_BOOLEAN_ACCESSORS(non_masking)
10158 inline int flags() const;
10159 inline void set_flags(int flags);
10161 DECLARE_CAST(InterceptorInfo)
10163 // Dispatched behavior.
10164 DECLARE_PRINTER(InterceptorInfo)
10165 DECLARE_VERIFIER(InterceptorInfo)
10167 static const int kGetterOffset = HeapObject::kHeaderSize;
10168 static const int kSetterOffset = kGetterOffset + kPointerSize;
10169 static const int kQueryOffset = kSetterOffset + kPointerSize;
10170 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10171 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10172 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10173 static const int kFlagsOffset = kDataOffset + kPointerSize;
10174 static const int kSize = kFlagsOffset + kPointerSize;
10176 static const int kCanInterceptSymbolsBit = 0;
10177 static const int kAllCanReadBit = 1;
10178 static const int kNonMasking = 2;
10181 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10185 class CallHandlerInfo: public Struct {
10187 DECL_ACCESSORS(callback, Object)
10188 DECL_ACCESSORS(data, Object)
10190 DECLARE_CAST(CallHandlerInfo)
10192 // Dispatched behavior.
10193 DECLARE_PRINTER(CallHandlerInfo)
10194 DECLARE_VERIFIER(CallHandlerInfo)
10196 static const int kCallbackOffset = HeapObject::kHeaderSize;
10197 static const int kDataOffset = kCallbackOffset + kPointerSize;
10198 static const int kSize = kDataOffset + kPointerSize;
10201 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10205 class TemplateInfo: public Struct {
10207 DECL_ACCESSORS(tag, Object)
10208 inline int number_of_properties() const;
10209 inline void set_number_of_properties(int value);
10210 DECL_ACCESSORS(property_list, Object)
10211 DECL_ACCESSORS(property_accessors, Object)
10213 DECLARE_VERIFIER(TemplateInfo)
10215 static const int kTagOffset = HeapObject::kHeaderSize;
10216 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10217 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10218 static const int kPropertyAccessorsOffset =
10219 kPropertyListOffset + kPointerSize;
10220 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10223 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10227 class FunctionTemplateInfo: public TemplateInfo {
10229 DECL_ACCESSORS(serial_number, Object)
10230 DECL_ACCESSORS(call_code, Object)
10231 DECL_ACCESSORS(prototype_template, Object)
10232 DECL_ACCESSORS(parent_template, Object)
10233 DECL_ACCESSORS(named_property_handler, Object)
10234 DECL_ACCESSORS(indexed_property_handler, Object)
10235 DECL_ACCESSORS(instance_template, Object)
10236 DECL_ACCESSORS(class_name, Object)
10237 DECL_ACCESSORS(signature, Object)
10238 DECL_ACCESSORS(instance_call_handler, Object)
10239 DECL_ACCESSORS(access_check_info, Object)
10240 DECL_INT_ACCESSORS(flag)
10242 inline int length() const;
10243 inline void set_length(int value);
10245 // Following properties use flag bits.
10246 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10247 DECL_BOOLEAN_ACCESSORS(undetectable)
10248 // If the bit is set, object instances created by this function
10249 // requires access check.
10250 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10251 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10252 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10253 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10254 DECL_BOOLEAN_ACCESSORS(instantiated)
10255 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10257 DECLARE_CAST(FunctionTemplateInfo)
10259 // Dispatched behavior.
10260 DECLARE_PRINTER(FunctionTemplateInfo)
10261 DECLARE_VERIFIER(FunctionTemplateInfo)
10263 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10264 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10265 static const int kPrototypeTemplateOffset =
10266 kCallCodeOffset + kPointerSize;
10267 static const int kParentTemplateOffset =
10268 kPrototypeTemplateOffset + kPointerSize;
10269 static const int kNamedPropertyHandlerOffset =
10270 kParentTemplateOffset + kPointerSize;
10271 static const int kIndexedPropertyHandlerOffset =
10272 kNamedPropertyHandlerOffset + kPointerSize;
10273 static const int kInstanceTemplateOffset =
10274 kIndexedPropertyHandlerOffset + kPointerSize;
10275 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10276 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10277 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10278 static const int kAccessCheckInfoOffset =
10279 kInstanceCallHandlerOffset + kPointerSize;
10280 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10281 static const int kLengthOffset = kFlagOffset + kPointerSize;
10282 static const int kSize = kLengthOffset + kPointerSize;
10284 // Returns true if |object| is an instance of this function template.
10285 bool IsTemplateFor(Object* object);
10286 bool IsTemplateFor(Map* map);
10288 // Returns the holder JSObject if the function can legally be called with this
10289 // receiver. Returns Heap::null_value() if the call is illegal.
10290 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10293 // Bit position in the flag, from least significant bit position.
10294 static const int kHiddenPrototypeBit = 0;
10295 static const int kUndetectableBit = 1;
10296 static const int kNeedsAccessCheckBit = 2;
10297 static const int kReadOnlyPrototypeBit = 3;
10298 static const int kRemovePrototypeBit = 4;
10299 static const int kDoNotCacheBit = 5;
10300 static const int kInstantiatedBit = 6;
10301 static const int kAcceptAnyReceiver = 7;
10303 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10307 class ObjectTemplateInfo: public TemplateInfo {
10309 DECL_ACCESSORS(constructor, Object)
10310 DECL_ACCESSORS(internal_field_count, Object)
10312 DECLARE_CAST(ObjectTemplateInfo)
10314 // Dispatched behavior.
10315 DECLARE_PRINTER(ObjectTemplateInfo)
10316 DECLARE_VERIFIER(ObjectTemplateInfo)
10318 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10319 static const int kInternalFieldCountOffset =
10320 kConstructorOffset + kPointerSize;
10321 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10325 class TypeSwitchInfo: public Struct {
10327 DECL_ACCESSORS(types, Object)
10329 DECLARE_CAST(TypeSwitchInfo)
10331 // Dispatched behavior.
10332 DECLARE_PRINTER(TypeSwitchInfo)
10333 DECLARE_VERIFIER(TypeSwitchInfo)
10335 static const int kTypesOffset = Struct::kHeaderSize;
10336 static const int kSize = kTypesOffset + kPointerSize;
10340 // The DebugInfo class holds additional information for a function being
10342 class DebugInfo: public Struct {
10344 // The shared function info for the source being debugged.
10345 DECL_ACCESSORS(shared, SharedFunctionInfo)
10346 // Code object for the patched code. This code object is the code object
10347 // currently active for the function.
10348 DECL_ACCESSORS(code, Code)
10349 // Fixed array holding status information for each active break point.
10350 DECL_ACCESSORS(break_points, FixedArray)
10352 // Check if there is a break point at a code position.
10353 bool HasBreakPoint(int code_position);
10354 // Get the break point info object for a code position.
10355 Object* GetBreakPointInfo(int code_position);
10356 // Clear a break point.
10357 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10359 Handle<Object> break_point_object);
10360 // Set a break point.
10361 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10362 int source_position, int statement_position,
10363 Handle<Object> break_point_object);
10364 // Get the break point objects for a code position.
10365 Handle<Object> GetBreakPointObjects(int code_position);
10366 // Find the break point info holding this break point object.
10367 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10368 Handle<Object> break_point_object);
10369 // Get the number of break points for this function.
10370 int GetBreakPointCount();
10372 DECLARE_CAST(DebugInfo)
10374 // Dispatched behavior.
10375 DECLARE_PRINTER(DebugInfo)
10376 DECLARE_VERIFIER(DebugInfo)
10378 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10379 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10380 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10381 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10383 static const int kEstimatedNofBreakPointsInFunction = 16;
10386 static const int kNoBreakPointInfo = -1;
10388 // Lookup the index in the break_points array for a code position.
10389 int GetBreakPointInfoIndex(int code_position);
10391 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10395 // The BreakPointInfo class holds information for break points set in a
10396 // function. The DebugInfo object holds a BreakPointInfo object for each code
10397 // position with one or more break points.
10398 class BreakPointInfo: public Struct {
10400 // The position in the code for the break point.
10401 DECL_INT_ACCESSORS(code_position)
10402 // The position in the source for the break position.
10403 DECL_INT_ACCESSORS(source_position)
10404 // The position in the source for the last statement before this break
10406 DECL_INT_ACCESSORS(statement_position)
10407 // List of related JavaScript break points.
10408 DECL_ACCESSORS(break_point_objects, Object)
10410 // Removes a break point.
10411 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10412 Handle<Object> break_point_object);
10413 // Set a break point.
10414 static void SetBreakPoint(Handle<BreakPointInfo> info,
10415 Handle<Object> break_point_object);
10416 // Check if break point info has this break point object.
10417 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10418 Handle<Object> break_point_object);
10419 // Get the number of break points for this code position.
10420 int GetBreakPointCount();
10422 DECLARE_CAST(BreakPointInfo)
10424 // Dispatched behavior.
10425 DECLARE_PRINTER(BreakPointInfo)
10426 DECLARE_VERIFIER(BreakPointInfo)
10428 static const int kCodePositionIndex = Struct::kHeaderSize;
10429 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10430 static const int kStatementPositionIndex =
10431 kSourcePositionIndex + kPointerSize;
10432 static const int kBreakPointObjectsIndex =
10433 kStatementPositionIndex + kPointerSize;
10434 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10437 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10441 #undef DECL_BOOLEAN_ACCESSORS
10442 #undef DECL_ACCESSORS
10443 #undef DECLARE_CAST
10444 #undef DECLARE_VERIFIER
10446 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10447 V(kStringTable, "string_table", "(Internalized strings)") \
10448 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10449 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10450 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10451 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10452 V(kTop, "top", "(Isolate)") \
10453 V(kRelocatable, "relocatable", "(Relocatable)") \
10454 V(kDebug, "debug", "(Debugger)") \
10455 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10456 V(kHandleScope, "handlescope", "(Handle scope)") \
10457 V(kBuiltins, "builtins", "(Builtins)") \
10458 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10459 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10460 V(kThreadManager, "threadmanager", "(Thread manager)") \
10461 V(kStrongRoots, "strong roots", "(Strong roots)") \
10462 V(kExtensions, "Extensions", "(Extensions)")
10464 class VisitorSynchronization : public AllStatic {
10466 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10468 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10471 #undef DECLARE_ENUM
10473 static const char* const kTags[kNumberOfSyncTags];
10474 static const char* const kTagNames[kNumberOfSyncTags];
10477 // Abstract base class for visiting, and optionally modifying, the
10478 // pointers contained in Objects. Used in GC and serialization/deserialization.
10479 class ObjectVisitor BASE_EMBEDDED {
10481 virtual ~ObjectVisitor() {}
10483 // Visits a contiguous arrays of pointers in the half-open range
10484 // [start, end). Any or all of the values may be modified on return.
10485 virtual void VisitPointers(Object** start, Object** end) = 0;
10487 // Handy shorthand for visiting a single pointer.
10488 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10490 // Visit weak next_code_link in Code object.
10491 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10493 // To allow lazy clearing of inline caches the visitor has
10494 // a rich interface for iterating over Code objects..
10496 // Visits a code target in the instruction stream.
10497 virtual void VisitCodeTarget(RelocInfo* rinfo);
10499 // Visits a code entry in a JS function.
10500 virtual void VisitCodeEntry(Address entry_address);
10502 // Visits a global property cell reference in the instruction stream.
10503 virtual void VisitCell(RelocInfo* rinfo);
10505 // Visits a runtime entry in the instruction stream.
10506 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10508 // Visits the resource of an one-byte or two-byte string.
10509 virtual void VisitExternalOneByteString(
10510 v8::String::ExternalOneByteStringResource** resource) {}
10511 virtual void VisitExternalTwoByteString(
10512 v8::String::ExternalStringResource** resource) {}
10514 // Visits a debug call target in the instruction stream.
10515 virtual void VisitDebugTarget(RelocInfo* rinfo);
10517 // Visits the byte sequence in a function's prologue that contains information
10518 // about the code's age.
10519 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10521 // Visit pointer embedded into a code object.
10522 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10524 // Visits an external reference embedded into a code object.
10525 virtual void VisitExternalReference(RelocInfo* rinfo);
10527 // Visits an external reference.
10528 virtual void VisitExternalReference(Address* p) {}
10530 // Visits an (encoded) internal reference.
10531 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10533 // Visits a handle that has an embedder-assigned class ID.
10534 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10536 // Intended for serialization/deserialization checking: insert, or
10537 // check for the presence of, a tag at this position in the stream.
10538 // Also used for marking up GC roots in heap snapshots.
10539 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10543 class StructBodyDescriptor : public
10544 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10546 static inline int SizeOf(Map* map, HeapObject* object);
10550 // BooleanBit is a helper class for setting and getting a bit in an integer.
10551 class BooleanBit : public AllStatic {
10553 static inline bool get(int value, int bit_position) {
10554 return (value & (1 << bit_position)) != 0;
10557 static inline int set(int value, int bit_position, bool v) {
10559 value |= (1 << bit_position);
10561 value &= ~(1 << bit_position);
10568 class KeyAccumulator final BASE_EMBEDDED {
10570 explicit KeyAccumulator(Isolate* isolate) : isolate_(isolate), length_(0) {}
10572 void AddKey(Handle<Object> key, int check_limit);
10573 void AddKeys(Handle<FixedArray> array, FixedArray::KeyFilter filter);
10574 void AddKeys(Handle<JSObject> array, FixedArray::KeyFilter filter);
10575 void PrepareForComparisons(int count);
10576 Handle<FixedArray> GetKeys();
10578 int GetLength() { return length_; }
10581 void EnsureCapacity(int capacity);
10585 Handle<FixedArray> keys_;
10586 Handle<OrderedHashSet> set_;
10588 DISALLOW_COPY_AND_ASSIGN(KeyAccumulator);
10590 } } // namespace v8::internal
10592 #endif // V8_OBJECTS_H_