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 > x
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.12 ToString
1131 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1132 Handle<Object> input);
1134 // ES6 section 7.3.9 GetMethod
1135 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1136 Handle<JSReceiver> receiver, Handle<Name> name);
1138 // ES6 section 12.5.6 The typeof Operator
1139 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1141 // ES6 section 12.6 Multiplicative Operators
1142 MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1143 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1144 Strength strength = Strength::WEAK);
1145 MUST_USE_RESULT static MaybeHandle<Object> Divide(
1146 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1147 Strength strength = Strength::WEAK);
1148 MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1149 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1150 Strength strength = Strength::WEAK);
1152 // ES6 section 12.7 Additive Operators
1153 MUST_USE_RESULT static MaybeHandle<Object> Add(
1154 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1155 Strength strength = Strength::WEAK);
1156 MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1157 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1158 Strength strength = Strength::WEAK);
1160 // ES6 section 12.8 Bitwise Shift Operators
1161 MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1162 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1163 Strength strength = Strength::WEAK);
1164 MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1165 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1166 Strength strength = Strength::WEAK);
1167 MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1168 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1169 Strength strength = Strength::WEAK);
1171 // ES6 section 12.9 Relational Operators
1172 MUST_USE_RESULT static inline Maybe<bool> GreaterThan(
1173 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1174 MUST_USE_RESULT static inline Maybe<bool> GreaterThanOrEqual(
1175 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1176 MUST_USE_RESULT static inline Maybe<bool> LessThan(
1177 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1178 MUST_USE_RESULT static inline Maybe<bool> LessThanOrEqual(
1179 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1181 // ES6 section 12.11 Binary Bitwise Operators
1182 MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1183 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1184 Strength strength = Strength::WEAK);
1185 MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1186 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1187 Strength strength = Strength::WEAK);
1188 MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1189 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1190 Strength strength = Strength::WEAK);
1192 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1193 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1195 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1196 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1197 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1198 LanguageMode language_mode,
1199 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1201 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1202 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1203 StoreFromKeyed store_mode);
1205 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1206 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1207 StoreFromKeyed store_mode);
1209 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1210 LookupIterator* it, LanguageMode language_mode);
1211 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1212 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1213 LanguageMode language_mode);
1214 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1215 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1216 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1217 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1218 Handle<Object> value, LanguageMode language_mode);
1219 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1220 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1221 LanguageMode language_mode);
1222 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1223 LookupIterator* it, Handle<Object> value);
1224 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1225 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1226 LanguageMode language_mode, StoreFromKeyed store_mode);
1227 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1228 Handle<Object> object, Handle<Name> name,
1229 LanguageMode language_mode = SLOPPY);
1230 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1231 Isolate* isolate, Handle<Object> object, const char* key,
1232 LanguageMode language_mode = SLOPPY);
1233 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1234 Handle<Object> object, Handle<Name> name,
1235 LanguageMode language_mode = SLOPPY);
1237 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1238 LookupIterator* it, LanguageMode language_mode);
1239 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1240 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1242 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1243 Handle<Object> receiver,
1244 Handle<JSReceiver> getter);
1245 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1246 Handle<Object> receiver,
1247 Handle<JSReceiver> setter,
1248 Handle<Object> value);
1250 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1251 Isolate* isolate, Handle<Object> object, uint32_t index,
1252 LanguageMode language_mode = SLOPPY);
1254 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1255 Isolate* isolate, Handle<Object> object, uint32_t index,
1256 Handle<Object> value, LanguageMode language_mode);
1258 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1259 Isolate* isolate, Handle<Object> receiver);
1261 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1263 // Returns the permanent hash code associated with this object. May return
1264 // undefined if not yet created.
1267 // Returns undefined for JSObjects, but returns the hash code for simple
1268 // objects. This avoids a double lookup in the cases where we know we will
1269 // add the hash to the JSObject if it does not already exist.
1270 Object* GetSimpleHash();
1272 // Returns the permanent hash code associated with this object depending on
1273 // the actual object type. May create and store a hash code if needed and none
1275 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1277 // Checks whether this object has the same value as the given one. This
1278 // function is implemented according to ES5, section 9.12 and can be used
1279 // to implement the Harmony "egal" function.
1280 bool SameValue(Object* other);
1282 // Checks whether this object has the same value as the given one.
1283 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1284 // This function is implemented according to ES6, section 7.2.4 and is used
1285 // by ES6 Map and Set.
1286 bool SameValueZero(Object* other);
1288 // Tries to convert an object to an array length. Returns true and sets the
1289 // output parameter if it succeeds.
1290 inline bool ToArrayLength(uint32_t* index);
1292 // Tries to convert an object to an array index. Returns true and sets the
1293 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1294 // allow kMaxUInt32.
1295 inline bool ToArrayIndex(uint32_t* index);
1297 // Returns true if this is a JSValue containing a string and the index is
1298 // < the length of the string. Used to implement [] on strings.
1299 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1301 DECLARE_VERIFIER(Object)
1303 // Verify a pointer is a valid object pointer.
1304 static void VerifyPointer(Object* p);
1307 inline void VerifyApiCallResultType();
1309 // Prints this object without details.
1310 void ShortPrint(FILE* out = stdout);
1312 // Prints this object without details to a message accumulator.
1313 void ShortPrint(StringStream* accumulator);
1315 void ShortPrint(std::ostream& os); // NOLINT
1317 DECLARE_CAST(Object)
1319 // Layout description.
1320 static const int kHeaderSize = 0; // Object does not take up any space.
1323 // For our gdb macros, we should perhaps change these in the future.
1326 // Prints this object with details.
1327 void Print(std::ostream& os); // NOLINT
1329 void Print() { ShortPrint(); }
1330 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1334 friend class LookupIterator;
1335 friend class PrototypeIterator;
1337 // Return the map of the root of object's prototype chain.
1338 Map* GetRootMap(Isolate* isolate);
1340 // Helper for SetProperty and SetSuperProperty.
1341 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1342 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1343 StoreFromKeyed store_mode, bool* found);
1345 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1349 // In objects.h to be usable without objects-inl.h inclusion.
1350 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1351 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1355 explicit Brief(const Object* const v) : value(v) {}
1356 const Object* value;
1360 std::ostream& operator<<(std::ostream& os, const Brief& v);
1363 // Smi represents integer Numbers that can be stored in 31 bits.
1364 // Smis are immediate which means they are NOT allocated in the heap.
1365 // The this pointer has the following format: [31 bit signed int] 0
1366 // For long smis it has the following format:
1367 // [32 bit signed int] [31 bits zero padding] 0
1368 // Smi stands for small integer.
1369 class Smi: public Object {
1371 // Returns the integer value.
1372 inline int value() const { return Internals::SmiValue(this); }
1374 // Convert a value to a Smi object.
1375 static inline Smi* FromInt(int value) {
1376 DCHECK(Smi::IsValid(value));
1377 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1380 static inline Smi* FromIntptr(intptr_t value) {
1381 DCHECK(Smi::IsValid(value));
1382 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1383 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1386 // Returns whether value can be represented in a Smi.
1387 static inline bool IsValid(intptr_t value) {
1388 bool result = Internals::IsValidSmi(value);
1389 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1395 // Dispatched behavior.
1396 void SmiPrint(std::ostream& os) const; // NOLINT
1397 DECLARE_VERIFIER(Smi)
1399 static const int kMinValue =
1400 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1401 static const int kMaxValue = -(kMinValue + 1);
1404 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1408 // Heap objects typically have a map pointer in their first word. However,
1409 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1410 // encoded in the first word. The class MapWord is an abstraction of the
1411 // value in a heap object's first word.
1412 class MapWord BASE_EMBEDDED {
1414 // Normal state: the map word contains a map pointer.
1416 // Create a map word from a map pointer.
1417 static inline MapWord FromMap(const Map* map);
1419 // View this map word as a map pointer.
1420 inline Map* ToMap();
1423 // Scavenge collection: the map word of live objects in the from space
1424 // contains a forwarding address (a heap object pointer in the to space).
1426 // True if this map word is a forwarding address for a scavenge
1427 // collection. Only valid during a scavenge collection (specifically,
1428 // when all map words are heap object pointers, i.e. not during a full GC).
1429 inline bool IsForwardingAddress();
1431 // Create a map word from a forwarding address.
1432 static inline MapWord FromForwardingAddress(HeapObject* object);
1434 // View this map word as a forwarding address.
1435 inline HeapObject* ToForwardingAddress();
1437 static inline MapWord FromRawValue(uintptr_t value) {
1438 return MapWord(value);
1441 inline uintptr_t ToRawValue() {
1446 // HeapObject calls the private constructor and directly reads the value.
1447 friend class HeapObject;
1449 explicit MapWord(uintptr_t value) : value_(value) {}
1455 // The content of an heap object (except for the map pointer). kTaggedValues
1456 // objects can contain both heap pointers and Smis, kMixedValues can contain
1457 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1458 // objects can contain raw values and Smis.
1459 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1462 // HeapObject is the superclass for all classes describing heap allocated
1464 class HeapObject: public Object {
1466 // [map]: Contains a map which contains the object's reflective
1468 inline Map* map() const;
1469 inline void set_map(Map* value);
1470 // The no-write-barrier version. This is OK if the object is white and in
1471 // new space, or if the value is an immortal immutable object, like the maps
1472 // of primitive (non-JS) objects like strings, heap numbers etc.
1473 inline void set_map_no_write_barrier(Map* value);
1475 // Get the map using acquire load.
1476 inline Map* synchronized_map();
1477 inline MapWord synchronized_map_word() const;
1479 // Set the map using release store
1480 inline void synchronized_set_map(Map* value);
1481 inline void synchronized_set_map_no_write_barrier(Map* value);
1482 inline void synchronized_set_map_word(MapWord map_word);
1484 // During garbage collection, the map word of a heap object does not
1485 // necessarily contain a map pointer.
1486 inline MapWord map_word() const;
1487 inline void set_map_word(MapWord map_word);
1489 // The Heap the object was allocated in. Used also to access Isolate.
1490 inline Heap* GetHeap() const;
1492 // Convenience method to get current isolate.
1493 inline Isolate* GetIsolate() const;
1495 // Converts an address to a HeapObject pointer.
1496 static inline HeapObject* FromAddress(Address address) {
1497 DCHECK_TAG_ALIGNED(address);
1498 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1501 // Returns the address of this HeapObject.
1502 inline Address address() {
1503 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1506 // Iterates over pointers contained in the object (including the Map)
1507 void Iterate(ObjectVisitor* v);
1509 // Iterates over all pointers contained in the object except the
1510 // first map pointer. The object type is given in the first
1511 // parameter. This function does not access the map pointer in the
1512 // object, and so is safe to call while the map pointer is modified.
1513 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1515 // Returns the heap object's size in bytes
1518 // Indicates what type of values this heap object may contain.
1519 inline HeapObjectContents ContentType();
1521 // Given a heap object's map pointer, returns the heap size in bytes
1522 // Useful when the map pointer field is used for other purposes.
1524 inline int SizeFromMap(Map* map);
1526 // Returns the field at offset in obj, as a read/write Object* reference.
1527 // Does no checking, and is safe to use during GC, while maps are invalid.
1528 // Does not invoke write barrier, so should only be assigned to
1529 // during marking GC.
1530 static inline Object** RawField(HeapObject* obj, int offset);
1532 // Adds the |code| object related to |name| to the code cache of this map. If
1533 // this map is a dictionary map that is shared, the map copied and installed
1535 static void UpdateMapCodeCache(Handle<HeapObject> object,
1539 DECLARE_CAST(HeapObject)
1541 // Return the write barrier mode for this. Callers of this function
1542 // must be able to present a reference to an DisallowHeapAllocation
1543 // object as a sign that they are not going to use this function
1544 // from code that allocates and thus invalidates the returned write
1546 inline WriteBarrierMode GetWriteBarrierMode(
1547 const DisallowHeapAllocation& promise);
1549 // Dispatched behavior.
1550 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1552 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1554 DECLARE_PRINTER(HeapObject)
1555 DECLARE_VERIFIER(HeapObject)
1557 inline void VerifyObjectField(int offset);
1558 inline void VerifySmiField(int offset);
1560 // Verify a pointer is a valid HeapObject pointer that points to object
1561 // areas in the heap.
1562 static void VerifyHeapPointer(Object* p);
1565 inline AllocationAlignment RequiredAlignment();
1567 // Layout description.
1568 // First field in a heap object is map.
1569 static const int kMapOffset = Object::kHeaderSize;
1570 static const int kHeaderSize = kMapOffset + kPointerSize;
1572 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1575 // helpers for calling an ObjectVisitor to iterate over pointers in the
1576 // half-open range [start, end) specified as integer offsets
1577 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1578 // as above, for the single element at "offset"
1579 inline void IteratePointer(ObjectVisitor* v, int offset);
1580 // as above, for the next code link of a code object.
1581 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1584 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1588 // This class describes a body of an object of a fixed size
1589 // in which all pointer fields are located in the [start_offset, end_offset)
1591 template<int start_offset, int end_offset, int size>
1592 class FixedBodyDescriptor {
1594 static const int kStartOffset = start_offset;
1595 static const int kEndOffset = end_offset;
1596 static const int kSize = size;
1598 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1600 template<typename StaticVisitor>
1601 static inline void IterateBody(HeapObject* obj) {
1602 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1603 HeapObject::RawField(obj, end_offset));
1608 // This class describes a body of an object of a variable size
1609 // in which all pointer fields are located in the [start_offset, object_size)
1611 template<int start_offset>
1612 class FlexibleBodyDescriptor {
1614 static const int kStartOffset = start_offset;
1616 static inline void IterateBody(HeapObject* obj,
1620 template<typename StaticVisitor>
1621 static inline void IterateBody(HeapObject* obj, int object_size) {
1622 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1623 HeapObject::RawField(obj, object_size));
1628 // The HeapNumber class describes heap allocated numbers that cannot be
1629 // represented in a Smi (small integer)
1630 class HeapNumber: public HeapObject {
1632 // [value]: number value.
1633 inline double value() const;
1634 inline void set_value(double value);
1636 DECLARE_CAST(HeapNumber)
1638 // Dispatched behavior.
1639 bool HeapNumberBooleanValue();
1641 void HeapNumberPrint(std::ostream& os); // NOLINT
1642 DECLARE_VERIFIER(HeapNumber)
1644 inline int get_exponent();
1645 inline int get_sign();
1647 // Layout description.
1648 static const int kValueOffset = HeapObject::kHeaderSize;
1649 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1650 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1651 // words within double numbers are endian dependent and they are set
1653 #if defined(V8_TARGET_LITTLE_ENDIAN)
1654 static const int kMantissaOffset = kValueOffset;
1655 static const int kExponentOffset = kValueOffset + 4;
1656 #elif defined(V8_TARGET_BIG_ENDIAN)
1657 static const int kMantissaOffset = kValueOffset + 4;
1658 static const int kExponentOffset = kValueOffset;
1660 #error Unknown byte ordering
1663 static const int kSize = kValueOffset + kDoubleSize;
1664 static const uint32_t kSignMask = 0x80000000u;
1665 static const uint32_t kExponentMask = 0x7ff00000u;
1666 static const uint32_t kMantissaMask = 0xfffffu;
1667 static const int kMantissaBits = 52;
1668 static const int kExponentBits = 11;
1669 static const int kExponentBias = 1023;
1670 static const int kExponentShift = 20;
1671 static const int kInfinityOrNanExponent =
1672 (kExponentMask >> kExponentShift) - kExponentBias;
1673 static const int kMantissaBitsInTopWord = 20;
1674 static const int kNonMantissaBitsInTopWord = 12;
1677 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1681 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1682 class Simd128Value : public HeapObject {
1684 DECLARE_CAST(Simd128Value)
1686 DECLARE_PRINTER(Simd128Value)
1687 DECLARE_VERIFIER(Simd128Value)
1689 static Handle<String> ToString(Handle<Simd128Value> input);
1691 // Equality operations.
1692 inline bool Equals(Simd128Value* that);
1693 static inline bool Equals(Handle<Simd128Value> one, Handle<Simd128Value> two);
1695 // Checks that another instance is bit-wise equal.
1696 bool BitwiseEquals(const Simd128Value* other) const;
1697 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1698 uint32_t Hash() const;
1699 // Copies the 16 bytes of SIMD data to the destination address.
1700 void CopyBits(void* destination) const;
1702 // Layout description.
1703 static const int kValueOffset = HeapObject::kHeaderSize;
1704 static const int kSize = kValueOffset + kSimd128Size;
1707 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1711 // V has parameters (TYPE, Type, type, lane count, lane type)
1712 #define SIMD128_TYPES(V) \
1713 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1714 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1715 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1716 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1717 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1718 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1719 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1720 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1721 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1722 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1724 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1725 class Type final : public Simd128Value { \
1727 inline lane_type get_lane(int lane) const; \
1728 inline void set_lane(int lane, lane_type value); \
1730 DECLARE_CAST(Type) \
1732 DECLARE_PRINTER(Type) \
1734 static Handle<String> ToString(Handle<Type> input); \
1736 inline bool Equals(Type* that); \
1739 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1741 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1742 #undef SIMD128_VALUE_CLASS
1745 enum EnsureElementsMode {
1746 DONT_ALLOW_DOUBLE_ELEMENTS,
1747 ALLOW_COPIED_DOUBLE_ELEMENTS,
1748 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1752 // Indicator for one component of an AccessorPair.
1753 enum AccessorComponent {
1759 // JSReceiver includes types on which properties can be defined, i.e.,
1760 // JSObject and JSProxy.
1761 class JSReceiver: public HeapObject {
1763 DECLARE_CAST(JSReceiver)
1765 // ES6 section 7.1.1 ToPrimitive
1766 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1767 Handle<JSReceiver> receiver,
1768 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1769 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1770 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1772 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1773 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1774 Handle<JSReceiver> object, Handle<Name> name);
1775 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1777 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1778 Handle<JSReceiver> object, uint32_t index);
1779 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1780 Handle<JSReceiver> object, uint32_t index);
1782 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1783 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1784 Handle<JSReceiver> object, Handle<Name> name,
1785 LanguageMode language_mode = SLOPPY);
1786 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1787 Handle<JSReceiver> object, Handle<Name> name,
1788 LanguageMode language_mode = SLOPPY);
1789 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1790 LookupIterator* it, LanguageMode language_mode);
1791 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1792 Handle<JSReceiver> object, uint32_t index,
1793 LanguageMode language_mode = SLOPPY);
1795 // Tests for the fast common case for property enumeration.
1796 bool IsSimpleEnum();
1798 // Returns the class name ([[Class]] property in the specification).
1799 String* class_name();
1801 // Returns the constructor name (the name (possibly, inferred name) of the
1802 // function that was used to instantiate the object).
1803 String* constructor_name();
1805 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1806 Handle<JSReceiver> object, Handle<Name> name);
1807 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1808 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1810 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1811 Handle<JSReceiver> object, uint32_t index);
1812 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1813 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1815 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1816 LookupIterator* it);
1819 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1821 static Handle<Object> GetDataProperty(LookupIterator* it);
1824 // Retrieves a permanent object identity hash code. The undefined value might
1825 // be returned in case no hash was created yet.
1826 inline Object* GetIdentityHash();
1828 // Retrieves a permanent object identity hash code. May create and store a
1829 // hash code if needed and none exists.
1830 inline static Handle<Smi> GetOrCreateIdentityHash(
1831 Handle<JSReceiver> object);
1833 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1835 // Computes the enumerable keys for a JSObject. Used for implementing
1836 // "for (n in object) { }".
1837 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1838 Handle<JSReceiver> object,
1839 KeyCollectionType type);
1842 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1846 // The JSObject describes real heap allocated JavaScript objects with
1848 // Note that the map of JSObject changes during execution to enable inline
1850 class JSObject: public JSReceiver {
1852 // [properties]: Backing storage for properties.
1853 // properties is a FixedArray in the fast case and a Dictionary in the
1855 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1856 inline void initialize_properties();
1857 inline bool HasFastProperties();
1858 // Gets slow properties for non-global objects.
1859 inline NameDictionary* property_dictionary();
1860 // Gets global object properties.
1861 inline GlobalDictionary* global_dictionary();
1863 // [elements]: The elements (properties with names that are integers).
1865 // Elements can be in two general modes: fast and slow. Each mode
1866 // corrensponds to a set of object representations of elements that
1867 // have something in common.
1869 // In the fast mode elements is a FixedArray and so each element can
1870 // be quickly accessed. This fact is used in the generated code. The
1871 // elements array can have one of three maps in this mode:
1872 // fixed_array_map, sloppy_arguments_elements_map or
1873 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1874 // the elements array may be shared by a few objects and so before
1875 // writing to any element the array must be copied. Use
1876 // EnsureWritableFastElements in this case.
1878 // In the slow mode the elements is either a NumberDictionary, a
1879 // FixedArray parameter map for a (sloppy) arguments object.
1880 DECL_ACCESSORS(elements, FixedArrayBase)
1881 inline void initialize_elements();
1882 static void ResetElements(Handle<JSObject> object);
1883 static inline void SetMapAndElements(Handle<JSObject> object,
1885 Handle<FixedArrayBase> elements);
1886 inline ElementsKind GetElementsKind();
1887 ElementsAccessor* GetElementsAccessor();
1888 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1889 inline bool HasFastSmiElements();
1890 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1891 inline bool HasFastObjectElements();
1892 // Returns true if an object has elements of FAST_ELEMENTS or
1893 // FAST_SMI_ONLY_ELEMENTS.
1894 inline bool HasFastSmiOrObjectElements();
1895 // Returns true if an object has any of the fast elements kinds.
1896 inline bool HasFastElements();
1897 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1899 inline bool HasFastDoubleElements();
1900 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1902 inline bool HasFastHoleyElements();
1903 inline bool HasSloppyArgumentsElements();
1904 inline bool HasDictionaryElements();
1906 inline bool HasFixedTypedArrayElements();
1908 inline bool HasFixedUint8ClampedElements();
1909 inline bool HasFixedArrayElements();
1910 inline bool HasFixedInt8Elements();
1911 inline bool HasFixedUint8Elements();
1912 inline bool HasFixedInt16Elements();
1913 inline bool HasFixedUint16Elements();
1914 inline bool HasFixedInt32Elements();
1915 inline bool HasFixedUint32Elements();
1916 inline bool HasFixedFloat32Elements();
1917 inline bool HasFixedFloat64Elements();
1919 inline bool HasFastArgumentsElements();
1920 inline bool HasSlowArgumentsElements();
1921 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1923 // Requires: HasFastElements().
1924 static Handle<FixedArray> EnsureWritableFastElements(
1925 Handle<JSObject> object);
1927 // Collects elements starting at index 0.
1928 // Undefined values are placed after non-undefined values.
1929 // Returns the number of non-undefined values.
1930 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1932 // As PrepareElementsForSort, but only on objects where elements is
1933 // a dictionary, and it will stay a dictionary. Collates undefined and
1934 // unexisting elements below limit from position zero of the elements.
1935 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1938 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1939 LookupIterator* it, Handle<Object> value);
1941 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1942 // grant an exemption to ExecutableAccessor callbacks in some cases.
1943 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1945 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1946 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1947 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1949 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1950 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1951 PropertyAttributes attributes,
1952 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1954 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1955 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1956 PropertyAttributes attributes,
1957 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1959 // Equivalent to one of the above depending on whether |name| can be converted
1960 // to an array index.
1961 MUST_USE_RESULT static MaybeHandle<Object>
1962 DefinePropertyOrElementIgnoreAttributes(
1963 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1964 PropertyAttributes attributes = NONE,
1965 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1967 // Adds or reconfigures a property to attributes NONE. It will fail when it
1969 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1970 Handle<Object> value);
1972 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1973 Handle<Object> value, PropertyAttributes attributes);
1975 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1976 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1977 PropertyAttributes attributes);
1979 // Extend the receiver with a single fast property appeared first in the
1980 // passed map. This also extends the property backing store if necessary.
1981 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1983 // Migrates the given object to a map whose field representations are the
1984 // lowest upper bound of all known representations for that field.
1985 static void MigrateInstance(Handle<JSObject> instance);
1987 // Migrates the given object only if the target map is already available,
1988 // or returns false if such a map is not yet available.
1989 static bool TryMigrateInstance(Handle<JSObject> instance);
1991 // Sets the property value in a normalized object given (key, value, details).
1992 // Handles the special representation of JS global objects.
1993 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1994 Handle<Object> value,
1995 PropertyDetails details);
1996 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1997 Handle<Object> value,
1998 PropertyAttributes attributes);
1999 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
2001 Handle<Object> value,
2002 PropertyAttributes attributes);
2004 static void OptimizeAsPrototype(Handle<JSObject> object,
2005 PrototypeOptimizationMode mode);
2006 static void ReoptimizeIfPrototype(Handle<JSObject> object);
2007 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2008 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2009 static void InvalidatePrototypeChains(Map* map);
2011 // Alternative implementation of WeakFixedArray::NullCallback.
2012 class PrototypeRegistryCompactionCallback {
2014 static void Callback(Object* value, int old_index, int new_index);
2017 // Retrieve interceptors.
2018 InterceptorInfo* GetNamedInterceptor();
2019 InterceptorInfo* GetIndexedInterceptor();
2021 // Used from JSReceiver.
2022 MUST_USE_RESULT static Maybe<PropertyAttributes>
2023 GetPropertyAttributesWithInterceptor(LookupIterator* it);
2024 MUST_USE_RESULT static Maybe<PropertyAttributes>
2025 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
2027 // Retrieves an AccessorPair property from the given object. Might return
2028 // undefined if the property doesn't exist or is of a different kind.
2029 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
2030 Handle<JSObject> object,
2032 AccessorComponent component);
2034 // Defines an AccessorPair property on the given object.
2035 // TODO(mstarzinger): Rename to SetAccessor().
2036 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2038 Handle<Object> getter,
2039 Handle<Object> setter,
2040 PropertyAttributes attributes);
2042 // Defines an AccessorInfo property on the given object.
2043 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2044 Handle<JSObject> object,
2045 Handle<AccessorInfo> info);
2047 // The result must be checked first for exceptions. If there's no exception,
2048 // the output parameter |done| indicates whether the interceptor has a result
2050 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2051 LookupIterator* it, bool* done);
2053 // Accessors for hidden properties object.
2055 // Hidden properties are not own properties of the object itself.
2056 // Instead they are stored in an auxiliary structure kept as an own
2057 // property with a special name Heap::hidden_string(). But if the
2058 // receiver is a JSGlobalProxy then the auxiliary object is a property
2059 // of its prototype, and if it's a detached proxy, then you can't have
2060 // hidden properties.
2062 // Sets a hidden property on this object. Returns this object if successful,
2063 // undefined if called on a detached proxy.
2064 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2066 Handle<Object> value);
2067 // Gets the value of a hidden property with the given key. Returns the hole
2068 // if the property doesn't exist (or if called on a detached proxy),
2069 // otherwise returns the value set for the key.
2070 Object* GetHiddenProperty(Handle<Name> key);
2071 // Deletes a hidden property. Deleting a non-existing property is
2072 // considered successful.
2073 static void DeleteHiddenProperty(Handle<JSObject> object,
2075 // Returns true if the object has a property with the hidden string as name.
2076 static bool HasHiddenProperties(Handle<JSObject> object);
2078 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2080 static void ValidateElements(Handle<JSObject> object);
2082 // Makes sure that this object can contain HeapObject as elements.
2083 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2085 // Makes sure that this object can contain the specified elements.
2086 static inline void EnsureCanContainElements(
2087 Handle<JSObject> object,
2090 EnsureElementsMode mode);
2091 static inline void EnsureCanContainElements(
2092 Handle<JSObject> object,
2093 Handle<FixedArrayBase> elements,
2095 EnsureElementsMode mode);
2096 static void EnsureCanContainElements(
2097 Handle<JSObject> object,
2098 Arguments* arguments,
2101 EnsureElementsMode mode);
2103 // Would we convert a fast elements array to dictionary mode given
2104 // an access at key?
2105 bool WouldConvertToSlowElements(uint32_t index);
2107 // Computes the new capacity when expanding the elements of a JSObject.
2108 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2109 // (old_capacity + 50%) + 16
2110 return old_capacity + (old_capacity >> 1) + 16;
2113 // These methods do not perform access checks!
2114 static void UpdateAllocationSite(Handle<JSObject> object,
2115 ElementsKind to_kind);
2117 // Lookup interceptors are used for handling properties controlled by host
2119 inline bool HasNamedInterceptor();
2120 inline bool HasIndexedInterceptor();
2122 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2123 // by JSReceiver::GetKeys.
2124 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2125 Handle<JSObject> object,
2126 Handle<JSReceiver> receiver);
2127 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2128 Handle<JSObject> object,
2129 Handle<JSReceiver> receiver);
2131 // Support functions for v8 api (needed for correct interceptor behavior).
2132 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2133 Handle<JSObject> object, Handle<Name> name);
2134 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2135 Handle<JSObject> object, uint32_t index);
2136 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2137 Handle<JSObject> object, Handle<Name> name);
2139 // Get the header size for a JSObject. Used to compute the index of
2140 // internal fields as well as the number of internal fields.
2141 inline int GetHeaderSize();
2143 inline int GetInternalFieldCount();
2144 inline int GetInternalFieldOffset(int index);
2145 inline Object* GetInternalField(int index);
2146 inline void SetInternalField(int index, Object* value);
2147 inline void SetInternalField(int index, Smi* value);
2149 // Returns the number of properties on this object filtering out properties
2150 // with the specified attributes (ignoring interceptors).
2151 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2152 // Fill in details for properties into storage starting at the specified
2153 // index. Returns the number of properties added.
2154 int GetOwnPropertyNames(FixedArray* storage, int index,
2155 PropertyAttributes filter = NONE);
2157 // Returns the number of properties on this object filtering out properties
2158 // with the specified attributes (ignoring interceptors).
2159 int NumberOfOwnElements(PropertyAttributes filter);
2160 // Returns the number of enumerable elements (ignoring interceptors).
2161 int NumberOfEnumElements();
2162 // Returns the number of elements on this object filtering out elements
2163 // with the specified attributes (ignoring interceptors).
2164 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2165 // Count and fill in the enumerable elements into storage.
2166 // (storage->length() == NumberOfEnumElements()).
2167 // If storage is NULL, will count the elements without adding
2168 // them to any storage.
2169 // Returns the number of enumerable elements.
2170 int GetEnumElementKeys(FixedArray* storage);
2172 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2175 // Returns a new map with all transitions dropped from the object's current
2176 // map and the ElementsKind set.
2177 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2178 ElementsKind to_kind);
2179 static void TransitionElementsKind(Handle<JSObject> object,
2180 ElementsKind to_kind);
2182 // Always use this to migrate an object to a new map.
2183 // |expected_additional_properties| is only used for fast-to-slow transitions
2184 // and ignored otherwise.
2185 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2186 int expected_additional_properties = 0);
2188 // Convert the object to use the canonical dictionary
2189 // representation. If the object is expected to have additional properties
2190 // added this number can be indicated to have the backing store allocated to
2191 // an initial capacity for holding these properties.
2192 static void NormalizeProperties(Handle<JSObject> object,
2193 PropertyNormalizationMode mode,
2194 int expected_additional_properties,
2195 const char* reason);
2197 // Convert and update the elements backing store to be a
2198 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2199 static Handle<SeededNumberDictionary> NormalizeElements(
2200 Handle<JSObject> object);
2202 void RequireSlowElements(SeededNumberDictionary* dictionary);
2204 // Transform slow named properties to fast variants.
2205 static void MigrateSlowToFast(Handle<JSObject> object,
2206 int unused_property_fields, const char* reason);
2208 inline bool IsUnboxedDoubleField(FieldIndex index);
2210 // Access fast-case object properties at index.
2211 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2212 Representation representation,
2214 inline Object* RawFastPropertyAt(FieldIndex index);
2215 inline double RawFastDoublePropertyAt(FieldIndex index);
2217 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2218 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2219 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2220 inline void WriteToField(int descriptor, Object* value);
2222 // Access to in object properties.
2223 inline int GetInObjectPropertyOffset(int index);
2224 inline Object* InObjectPropertyAt(int index);
2225 inline Object* InObjectPropertyAtPut(int index,
2227 WriteBarrierMode mode
2228 = UPDATE_WRITE_BARRIER);
2230 // Set the object's prototype (only JSReceiver and null are allowed values).
2231 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2232 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2234 // Initializes the body after properties slot, properties slot is
2235 // initialized by set_properties. Fill the pre-allocated fields with
2236 // pre_allocated_value and the rest with filler_value.
2237 // Note: this call does not update write barrier, the caller is responsible
2238 // to ensure that |filler_value| can be collected without WB here.
2239 inline void InitializeBody(Map* map,
2240 Object* pre_allocated_value,
2241 Object* filler_value);
2243 // Check whether this object references another object
2244 bool ReferencesObject(Object* obj);
2246 // Disalow further properties to be added to the oject.
2247 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2248 Handle<JSObject> object);
2250 bool IsExtensible();
2253 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2255 // ES5 Object.freeze
2256 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2258 // Called the first time an object is observed with ES7 Object.observe.
2259 static void SetObserved(Handle<JSObject> object);
2262 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2264 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2265 Handle<JSObject> object,
2266 AllocationSiteUsageContext* site_context,
2267 DeepCopyHints hints = kNoHints);
2268 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2269 Handle<JSObject> object,
2270 AllocationSiteCreationContext* site_context);
2272 DECLARE_CAST(JSObject)
2274 // Dispatched behavior.
2275 void JSObjectShortPrint(StringStream* accumulator);
2276 DECLARE_PRINTER(JSObject)
2277 DECLARE_VERIFIER(JSObject)
2279 void PrintProperties(std::ostream& os); // NOLINT
2280 void PrintElements(std::ostream& os); // NOLINT
2282 #if defined(DEBUG) || defined(OBJECT_PRINT)
2283 void PrintTransitions(std::ostream& os); // NOLINT
2286 static void PrintElementsTransition(
2287 FILE* file, Handle<JSObject> object,
2288 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2289 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2291 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2294 // Structure for collecting spill information about JSObjects.
2295 class SpillInformation {
2299 int number_of_objects_;
2300 int number_of_objects_with_fast_properties_;
2301 int number_of_objects_with_fast_elements_;
2302 int number_of_fast_used_fields_;
2303 int number_of_fast_unused_fields_;
2304 int number_of_slow_used_properties_;
2305 int number_of_slow_unused_properties_;
2306 int number_of_fast_used_elements_;
2307 int number_of_fast_unused_elements_;
2308 int number_of_slow_used_elements_;
2309 int number_of_slow_unused_elements_;
2312 void IncrementSpillStatistics(SpillInformation* info);
2316 // If a GC was caused while constructing this object, the elements pointer
2317 // may point to a one pointer filler map. The object won't be rooted, but
2318 // our heap verification code could stumble across it.
2319 bool ElementsAreSafeToExamine();
2322 Object* SlowReverseLookup(Object* value);
2324 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2325 // Also maximal value of JSArray's length property.
2326 static const uint32_t kMaxElementCount = 0xffffffffu;
2328 // Constants for heuristics controlling conversion of fast elements
2329 // to slow elements.
2331 // Maximal gap that can be introduced by adding an element beyond
2332 // the current elements length.
2333 static const uint32_t kMaxGap = 1024;
2335 // Maximal length of fast elements array that won't be checked for
2336 // being dense enough on expansion.
2337 static const int kMaxUncheckedFastElementsLength = 5000;
2339 // Same as above but for old arrays. This limit is more strict. We
2340 // don't want to be wasteful with long lived objects.
2341 static const int kMaxUncheckedOldFastElementsLength = 500;
2343 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2344 // permissible values (see the DCHECK in heap.cc).
2345 static const int kInitialMaxFastElementArray = 100000;
2347 // This constant applies only to the initial map of "global.Object" and
2348 // not to arbitrary other JSObject maps.
2349 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2351 static const int kMaxInstanceSize = 255 * kPointerSize;
2352 // When extending the backing storage for property values, we increase
2353 // its size by more than the 1 entry necessary, so sequentially adding fields
2354 // to the same object requires fewer allocations and copies.
2355 static const int kFieldsAdded = 3;
2357 // Layout description.
2358 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2359 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2360 static const int kHeaderSize = kElementsOffset + kPointerSize;
2362 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2364 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2366 static inline int SizeOf(Map* map, HeapObject* object);
2369 Context* GetCreationContext();
2371 // Enqueue change record for Object.observe. May cause GC.
2372 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2373 Handle<JSObject> object, const char* type, Handle<Name> name,
2374 Handle<Object> old_value);
2376 // Gets the number of currently used elements.
2377 int GetFastElementsUsage();
2379 // Deletes an existing named property in a normalized object.
2380 static void DeleteNormalizedProperty(Handle<JSObject> object,
2381 Handle<Name> name, int entry);
2383 static bool AllCanRead(LookupIterator* it);
2384 static bool AllCanWrite(LookupIterator* it);
2387 friend class JSReceiver;
2388 friend class Object;
2390 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2391 static void MigrateFastToSlow(Handle<JSObject> object,
2392 Handle<Map> new_map,
2393 int expected_additional_properties);
2395 // Used from Object::GetProperty().
2396 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2397 LookupIterator* it);
2399 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2400 LookupIterator* it, Handle<Object> value);
2402 // Add a property to a slow-case object.
2403 static void AddSlowProperty(Handle<JSObject> object,
2405 Handle<Object> value,
2406 PropertyAttributes attributes);
2408 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2409 LookupIterator* it);
2411 bool ReferencesObjectFromElements(FixedArray* elements,
2415 // Return the hash table backing store or the inline stored identity hash,
2416 // whatever is found.
2417 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2419 // Return the hash table backing store for hidden properties. If there is no
2420 // backing store, allocate one.
2421 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2422 Handle<JSObject> object);
2424 // Set the hidden property backing store to either a hash table or
2425 // the inline-stored identity hash.
2426 static Handle<Object> SetHiddenPropertiesHashTable(
2427 Handle<JSObject> object,
2428 Handle<Object> value);
2430 MUST_USE_RESULT Object* GetIdentityHash();
2432 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2434 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2435 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2437 // Helper for fast versions of preventExtensions, seal, and freeze.
2438 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2439 template <PropertyAttributes attrs>
2440 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2441 Handle<JSObject> object);
2443 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2447 // Common superclass for FixedArrays that allow implementations to share
2448 // common accessors and some code paths.
2449 class FixedArrayBase: public HeapObject {
2451 // [length]: length of the array.
2452 inline int length() const;
2453 inline void set_length(int value);
2455 // Get and set the length using acquire loads and release stores.
2456 inline int synchronized_length() const;
2457 inline void synchronized_set_length(int value);
2459 DECLARE_CAST(FixedArrayBase)
2461 // Layout description.
2462 // Length is smi tagged when it is stored.
2463 static const int kLengthOffset = HeapObject::kHeaderSize;
2464 static const int kHeaderSize = kLengthOffset + kPointerSize;
2468 class FixedDoubleArray;
2469 class IncrementalMarking;
2472 // FixedArray describes fixed-sized arrays with element type Object*.
2473 class FixedArray: public FixedArrayBase {
2475 // Setter and getter for elements.
2476 inline Object* get(int index) const;
2477 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2478 // Setter that uses write barrier.
2479 inline void set(int index, Object* value);
2480 inline bool is_the_hole(int index);
2482 // Setter that doesn't need write barrier.
2483 inline void set(int index, Smi* value);
2484 // Setter with explicit barrier mode.
2485 inline void set(int index, Object* value, WriteBarrierMode mode);
2487 // Setters for frequently used oddballs located in old space.
2488 inline void set_undefined(int index);
2489 inline void set_null(int index);
2490 inline void set_the_hole(int index);
2492 inline Object** GetFirstElementAddress();
2493 inline bool ContainsOnlySmisOrHoles();
2495 // Gives access to raw memory which stores the array's data.
2496 inline Object** data_start();
2498 inline void FillWithHoles(int from, int to);
2500 // Shrink length and insert filler objects.
2501 void Shrink(int length);
2503 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2505 // Copy a sub array from the receiver to dest.
2506 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2508 // Garbage collection support.
2509 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2511 // Code Generation support.
2512 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2514 // Garbage collection support.
2515 inline Object** RawFieldOfElementAt(int index);
2517 DECLARE_CAST(FixedArray)
2519 // Maximal allowed size, in bytes, of a single FixedArray.
2520 // Prevents overflowing size computations, as well as extreme memory
2522 static const int kMaxSize = 128 * MB * kPointerSize;
2523 // Maximally allowed length of a FixedArray.
2524 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2526 // Dispatched behavior.
2527 DECLARE_PRINTER(FixedArray)
2528 DECLARE_VERIFIER(FixedArray)
2530 // Checks if two FixedArrays have identical contents.
2531 bool IsEqualTo(FixedArray* other);
2534 // Swap two elements in a pair of arrays. If this array and the
2535 // numbers array are the same object, the elements are only swapped
2537 void SwapPairs(FixedArray* numbers, int i, int j);
2539 // Sort prefix of this array and the numbers array as pairs wrt. the
2540 // numbers. If the numbers array and the this array are the same
2541 // object, the prefix of this array is sorted.
2542 void SortPairs(FixedArray* numbers, uint32_t len);
2544 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2546 static inline int SizeOf(Map* map, HeapObject* object);
2550 // Set operation on FixedArray without using write barriers. Can
2551 // only be used for storing old space objects or smis.
2552 static inline void NoWriteBarrierSet(FixedArray* array,
2556 // Set operation on FixedArray without incremental write barrier. Can
2557 // only be used if the object is guaranteed to be white (whiteness witness
2559 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2564 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2566 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2570 // FixedDoubleArray describes fixed-sized arrays with element type double.
2571 class FixedDoubleArray: public FixedArrayBase {
2573 // Setter and getter for elements.
2574 inline double get_scalar(int index);
2575 inline uint64_t get_representation(int index);
2576 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2577 inline void set(int index, double value);
2578 inline void set_the_hole(int index);
2580 // Checking for the hole.
2581 inline bool is_the_hole(int index);
2583 // Garbage collection support.
2584 inline static int SizeFor(int length) {
2585 return kHeaderSize + length * kDoubleSize;
2588 // Gives access to raw memory which stores the array's data.
2589 inline double* data_start();
2591 inline void FillWithHoles(int from, int to);
2593 // Code Generation support.
2594 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2596 DECLARE_CAST(FixedDoubleArray)
2598 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2599 // Prevents overflowing size computations, as well as extreme memory
2601 static const int kMaxSize = 512 * MB;
2602 // Maximally allowed length of a FixedArray.
2603 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2605 // Dispatched behavior.
2606 DECLARE_PRINTER(FixedDoubleArray)
2607 DECLARE_VERIFIER(FixedDoubleArray)
2610 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2614 class WeakFixedArray : public FixedArray {
2616 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2617 // This function does not check if the value exists already, callers must
2618 // ensure this themselves if necessary.
2619 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2620 Handle<HeapObject> value,
2621 int* assigned_index = NULL);
2623 // Returns true if an entry was found and removed.
2624 bool Remove(Handle<HeapObject> value);
2626 class NullCallback {
2628 static void Callback(Object* value, int old_index, int new_index) {}
2631 template <class CompactionCallback>
2634 inline Object* Get(int index) const;
2635 inline void Clear(int index);
2636 inline int Length() const;
2638 inline bool IsEmptySlot(int index) const;
2639 static Object* Empty() { return Smi::FromInt(0); }
2643 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2644 void Reset(Object* maybe_array);
2651 WeakFixedArray* list_;
2653 int last_used_index_;
2654 DisallowHeapAllocation no_gc_;
2656 DISALLOW_COPY_AND_ASSIGN(Iterator);
2659 DECLARE_CAST(WeakFixedArray)
2662 static const int kLastUsedIndexIndex = 0;
2663 static const int kFirstIndex = 1;
2665 static Handle<WeakFixedArray> Allocate(
2666 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2668 static void Set(Handle<WeakFixedArray> array, int index,
2669 Handle<HeapObject> value);
2670 inline void clear(int index);
2672 inline int last_used_index() const;
2673 inline void set_last_used_index(int index);
2675 // Disallow inherited setters.
2676 void set(int index, Smi* value);
2677 void set(int index, Object* value);
2678 void set(int index, Object* value, WriteBarrierMode mode);
2679 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2683 // Generic array grows dynamically with O(1) amortized insertion.
2684 class ArrayList : public FixedArray {
2688 // Use this if GC can delete elements from the array.
2689 kReloadLengthAfterAllocation,
2691 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2692 AddMode mode = kNone);
2693 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2694 Handle<Object> obj2, AddMode = kNone);
2695 inline int Length();
2696 inline void SetLength(int length);
2697 inline Object* Get(int index);
2698 inline Object** Slot(int index);
2699 inline void Set(int index, Object* obj);
2700 inline void Clear(int index, Object* undefined);
2701 DECLARE_CAST(ArrayList)
2704 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2705 static const int kLengthIndex = 0;
2706 static const int kFirstIndex = 1;
2707 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2711 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2712 // The format of the these objects is:
2713 // [0]: Number of descriptors
2714 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2715 // [0]: pointer to fixed array with enum cache
2716 // [1]: either Smi(0) or pointer to fixed array with indices
2718 // [2 + number of descriptors * kDescriptorSize]: start of slack
2719 class DescriptorArray: public FixedArray {
2721 // Returns true for both shared empty_descriptor_array and for smis, which the
2722 // map uses to encode additional bit fields when the descriptor array is not
2724 inline bool IsEmpty();
2726 // Returns the number of descriptors in the array.
2727 inline int number_of_descriptors();
2729 inline int number_of_descriptors_storage();
2731 inline int NumberOfSlackDescriptors();
2733 inline void SetNumberOfDescriptors(int number_of_descriptors);
2734 inline int number_of_entries();
2736 inline bool HasEnumCache();
2738 inline void CopyEnumCacheFrom(DescriptorArray* array);
2740 inline FixedArray* GetEnumCache();
2742 inline bool HasEnumIndicesCache();
2744 inline FixedArray* GetEnumIndicesCache();
2746 inline Object** GetEnumCacheSlot();
2748 void ClearEnumCache();
2750 // Initialize or change the enum cache,
2751 // using the supplied storage for the small "bridge".
2752 void SetEnumCache(FixedArray* bridge_storage,
2753 FixedArray* new_cache,
2754 Object* new_index_cache);
2756 bool CanHoldValue(int descriptor, Object* value);
2758 // Accessors for fetching instance descriptor at descriptor number.
2759 inline Name* GetKey(int descriptor_number);
2760 inline Object** GetKeySlot(int descriptor_number);
2761 inline Object* GetValue(int descriptor_number);
2762 inline void SetValue(int descriptor_number, Object* value);
2763 inline Object** GetValueSlot(int descriptor_number);
2764 static inline int GetValueOffset(int descriptor_number);
2765 inline Object** GetDescriptorStartSlot(int descriptor_number);
2766 inline Object** GetDescriptorEndSlot(int descriptor_number);
2767 inline PropertyDetails GetDetails(int descriptor_number);
2768 inline PropertyType GetType(int descriptor_number);
2769 inline int GetFieldIndex(int descriptor_number);
2770 inline HeapType* GetFieldType(int descriptor_number);
2771 inline Object* GetConstant(int descriptor_number);
2772 inline Object* GetCallbacksObject(int descriptor_number);
2773 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2775 inline Name* GetSortedKey(int descriptor_number);
2776 inline int GetSortedKeyIndex(int descriptor_number);
2777 inline void SetSortedKey(int pointer, int descriptor_number);
2778 inline void SetRepresentation(int descriptor_number,
2779 Representation representation);
2781 // Accessor for complete descriptor.
2782 inline void Get(int descriptor_number, Descriptor* desc);
2783 inline void Set(int descriptor_number, Descriptor* desc);
2784 void Replace(int descriptor_number, Descriptor* descriptor);
2786 // Append automatically sets the enumeration index. This should only be used
2787 // to add descriptors in bulk at the end, followed by sorting the descriptor
2789 inline void Append(Descriptor* desc);
2791 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2792 int enumeration_index,
2795 static Handle<DescriptorArray> CopyUpToAddAttributes(
2796 Handle<DescriptorArray> desc,
2797 int enumeration_index,
2798 PropertyAttributes attributes,
2801 // Sort the instance descriptors by the hash codes of their keys.
2804 // Search the instance descriptors for given name.
2805 INLINE(int Search(Name* name, int number_of_own_descriptors));
2807 // As the above, but uses DescriptorLookupCache and updates it when
2809 INLINE(int SearchWithCache(Name* name, Map* map));
2811 // Allocates a DescriptorArray, but returns the singleton
2812 // empty descriptor array object if number_of_descriptors is 0.
2813 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2814 int number_of_descriptors,
2817 DECLARE_CAST(DescriptorArray)
2819 // Constant for denoting key was not found.
2820 static const int kNotFound = -1;
2822 static const int kDescriptorLengthIndex = 0;
2823 static const int kEnumCacheIndex = 1;
2824 static const int kFirstIndex = 2;
2826 // The length of the "bridge" to the enum cache.
2827 static const int kEnumCacheBridgeLength = 2;
2828 static const int kEnumCacheBridgeCacheIndex = 0;
2829 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2831 // Layout description.
2832 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2833 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2834 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2836 // Layout description for the bridge array.
2837 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2839 // Layout of descriptor.
2840 static const int kDescriptorKey = 0;
2841 static const int kDescriptorDetails = 1;
2842 static const int kDescriptorValue = 2;
2843 static const int kDescriptorSize = 3;
2845 #if defined(DEBUG) || defined(OBJECT_PRINT)
2846 // For our gdb macros, we should perhaps change these in the future.
2849 // Print all the descriptors.
2850 void PrintDescriptors(std::ostream& os); // NOLINT
2854 // Is the descriptor array sorted and without duplicates?
2855 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2857 // Is the descriptor array consistent with the back pointers in targets?
2858 bool IsConsistentWithBackPointers(Map* current_map);
2860 // Are two DescriptorArrays equal?
2861 bool IsEqualTo(DescriptorArray* other);
2864 // Returns the fixed array length required to hold number_of_descriptors
2866 static int LengthFor(int number_of_descriptors) {
2867 return ToKeyIndex(number_of_descriptors);
2871 // WhitenessWitness is used to prove that a descriptor array is white
2872 // (unmarked), so incremental write barriers can be skipped because the
2873 // marking invariant cannot be broken and slots pointing into evacuation
2874 // candidates will be discovered when the object is scanned. A witness is
2875 // always stack-allocated right after creating an array. By allocating a
2876 // witness, incremental marking is globally disabled. The witness is then
2877 // passed along wherever needed to statically prove that the array is known to
2879 class WhitenessWitness {
2881 inline explicit WhitenessWitness(DescriptorArray* array);
2882 inline ~WhitenessWitness();
2885 IncrementalMarking* marking_;
2888 // An entry in a DescriptorArray, represented as an (array, index) pair.
2891 inline explicit Entry(DescriptorArray* descs, int index) :
2892 descs_(descs), index_(index) { }
2894 inline PropertyType type();
2895 inline Object* GetCallbackObject();
2898 DescriptorArray* descs_;
2902 // Conversion from descriptor number to array indices.
2903 static int ToKeyIndex(int descriptor_number) {
2904 return kFirstIndex +
2905 (descriptor_number * kDescriptorSize) +
2909 static int ToDetailsIndex(int descriptor_number) {
2910 return kFirstIndex +
2911 (descriptor_number * kDescriptorSize) +
2915 static int ToValueIndex(int descriptor_number) {
2916 return kFirstIndex +
2917 (descriptor_number * kDescriptorSize) +
2921 // Transfer a complete descriptor from the src descriptor array to this
2922 // descriptor array.
2923 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2925 inline void Set(int descriptor_number,
2927 const WhitenessWitness&);
2929 // Swap first and second descriptor.
2930 inline void SwapSortedKeys(int first, int second);
2932 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2936 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2938 template <SearchMode search_mode, typename T>
2939 inline int Search(T* array, Name* name, int valid_entries = 0,
2940 int* out_insertion_index = NULL);
2943 // HashTable is a subclass of FixedArray that implements a hash table
2944 // that uses open addressing and quadratic probing.
2946 // In order for the quadratic probing to work, elements that have not
2947 // yet been used and elements that have been deleted are
2948 // distinguished. Probing continues when deleted elements are
2949 // encountered and stops when unused elements are encountered.
2951 // - Elements with key == undefined have not been used yet.
2952 // - Elements with key == the_hole have been deleted.
2954 // The hash table class is parameterized with a Shape and a Key.
2955 // Shape must be a class with the following interface:
2956 // class ExampleShape {
2958 // // Tells whether key matches other.
2959 // static bool IsMatch(Key key, Object* other);
2960 // // Returns the hash value for key.
2961 // static uint32_t Hash(Key key);
2962 // // Returns the hash value for object.
2963 // static uint32_t HashForObject(Key key, Object* object);
2964 // // Convert key to an object.
2965 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2966 // // The prefix size indicates number of elements in the beginning
2967 // // of the backing storage.
2968 // static const int kPrefixSize = ..;
2969 // // The Element size indicates number of elements per entry.
2970 // static const int kEntrySize = ..;
2972 // The prefix size indicates an amount of memory in the
2973 // beginning of the backing storage that can be used for non-element
2974 // information by subclasses.
2976 template<typename Key>
2979 static const bool UsesSeed = false;
2980 static uint32_t Hash(Key key) { return 0; }
2981 static uint32_t SeededHash(Key key, uint32_t seed) {
2985 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2986 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2988 return HashForObject(key, object);
2993 class HashTableBase : public FixedArray {
2995 // Returns the number of elements in the hash table.
2996 inline int NumberOfElements();
2998 // Returns the number of deleted elements in the hash table.
2999 inline int NumberOfDeletedElements();
3001 // Returns the capacity of the hash table.
3002 inline int Capacity();
3004 // ElementAdded should be called whenever an element is added to a
3006 inline void ElementAdded();
3008 // ElementRemoved should be called whenever an element is removed from
3010 inline void ElementRemoved();
3011 inline void ElementsRemoved(int n);
3013 // Computes the required capacity for a table holding the given
3014 // number of elements. May be more than HashTable::kMaxCapacity.
3015 static inline int ComputeCapacity(int at_least_space_for);
3017 // Tells whether k is a real key. The hole and undefined are not allowed
3018 // as keys and can be used to indicate missing or deleted elements.
3019 inline bool IsKey(Object* k);
3021 // Compute the probe offset (quadratic probing).
3022 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3023 return (n + n * n) >> 1;
3026 static const int kNumberOfElementsIndex = 0;
3027 static const int kNumberOfDeletedElementsIndex = 1;
3028 static const int kCapacityIndex = 2;
3029 static const int kPrefixStartIndex = 3;
3031 // Constant used for denoting a absent entry.
3032 static const int kNotFound = -1;
3035 // Update the number of elements in the hash table.
3036 inline void SetNumberOfElements(int nof);
3038 // Update the number of deleted elements in the hash table.
3039 inline void SetNumberOfDeletedElements(int nod);
3041 // Returns probe entry.
3042 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3043 DCHECK(base::bits::IsPowerOfTwo32(size));
3044 return (hash + GetProbeOffset(number)) & (size - 1);
3047 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3048 return hash & (size - 1);
3051 inline static uint32_t NextProbe(
3052 uint32_t last, uint32_t number, uint32_t size) {
3053 return (last + number) & (size - 1);
3058 template <typename Derived, typename Shape, typename Key>
3059 class HashTable : public HashTableBase {
3062 inline uint32_t Hash(Key key) {
3063 if (Shape::UsesSeed) {
3064 return Shape::SeededHash(key, GetHeap()->HashSeed());
3066 return Shape::Hash(key);
3070 inline uint32_t HashForObject(Key key, Object* object) {
3071 if (Shape::UsesSeed) {
3072 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3074 return Shape::HashForObject(key, object);
3078 // Returns a new HashTable object.
3079 MUST_USE_RESULT static Handle<Derived> New(
3080 Isolate* isolate, int at_least_space_for,
3081 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3082 PretenureFlag pretenure = NOT_TENURED);
3084 DECLARE_CAST(HashTable)
3086 // Garbage collection support.
3087 void IteratePrefix(ObjectVisitor* visitor);
3088 void IterateElements(ObjectVisitor* visitor);
3090 // Find entry for key otherwise return kNotFound.
3091 inline int FindEntry(Key key);
3092 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3093 int FindEntry(Isolate* isolate, Key key);
3095 // Rehashes the table in-place.
3096 void Rehash(Key key);
3098 // Returns the key at entry.
3099 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3101 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3102 static const int kEntrySize = Shape::kEntrySize;
3103 static const int kElementsStartOffset =
3104 kHeaderSize + kElementsStartIndex * kPointerSize;
3105 static const int kCapacityOffset =
3106 kHeaderSize + kCapacityIndex * kPointerSize;
3108 // Returns the index for an entry (of the key)
3109 static inline int EntryToIndex(int entry) {
3110 return (entry * kEntrySize) + kElementsStartIndex;
3114 friend class ObjectHashTable;
3116 // Find the entry at which to insert element with the given key that
3117 // has the given hash value.
3118 uint32_t FindInsertionEntry(uint32_t hash);
3120 // Attempt to shrink hash table after removal of key.
3121 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3123 // Ensure enough space for n additional elements.
3124 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3125 Handle<Derived> table,
3128 PretenureFlag pretenure = NOT_TENURED);
3130 // Sets the capacity of the hash table.
3131 void SetCapacity(int capacity) {
3132 // To scale a computed hash code to fit within the hash table, we
3133 // use bit-wise AND with a mask, so the capacity must be positive
3135 DCHECK(capacity > 0);
3136 DCHECK(capacity <= kMaxCapacity);
3137 set(kCapacityIndex, Smi::FromInt(capacity));
3140 // Maximal capacity of HashTable. Based on maximal length of underlying
3141 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3143 static const int kMaxCapacity =
3144 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3147 // Returns _expected_ if one of entries given by the first _probe_ probes is
3148 // equal to _expected_. Otherwise, returns the entry given by the probe
3150 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3152 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3154 // Rehashes this hash-table into the new table.
3155 void Rehash(Handle<Derived> new_table, Key key);
3159 // HashTableKey is an abstract superclass for virtual key behavior.
3160 class HashTableKey {
3162 // Returns whether the other object matches this key.
3163 virtual bool IsMatch(Object* other) = 0;
3164 // Returns the hash value for this key.
3165 virtual uint32_t Hash() = 0;
3166 // Returns the hash value for object.
3167 virtual uint32_t HashForObject(Object* key) = 0;
3168 // Returns the key object for storing into the hash table.
3169 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3171 virtual ~HashTableKey() {}
3175 class StringTableShape : public BaseShape<HashTableKey*> {
3177 static inline bool IsMatch(HashTableKey* key, Object* value) {
3178 return key->IsMatch(value);
3181 static inline uint32_t Hash(HashTableKey* key) {
3185 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3186 return key->HashForObject(object);
3189 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3191 static const int kPrefixSize = 0;
3192 static const int kEntrySize = 1;
3195 class SeqOneByteString;
3199 // No special elements in the prefix and the element size is 1
3200 // because only the string itself (the key) needs to be stored.
3201 class StringTable: public HashTable<StringTable,
3205 // Find string in the string table. If it is not there yet, it is
3206 // added. The return value is the string found.
3207 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3208 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3209 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3211 // Tries to internalize given string and returns string handle on success
3212 // or an empty handle otherwise.
3213 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3215 Handle<String> string);
3217 // Looks up a string that is equal to the given string and returns
3218 // string handle if it is found, or an empty handle otherwise.
3219 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3221 Handle<String> str);
3222 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3227 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3229 DECLARE_CAST(StringTable)
3232 template <bool seq_one_byte>
3233 friend class JsonParser;
3235 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3239 template <typename Derived, typename Shape, typename Key>
3240 class Dictionary: public HashTable<Derived, Shape, Key> {
3241 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3244 // Returns the value at entry.
3245 Object* ValueAt(int entry) {
3246 return this->get(Derived::EntryToIndex(entry) + 1);
3249 // Set the value for entry.
3250 void ValueAtPut(int entry, Object* value) {
3251 this->set(Derived::EntryToIndex(entry) + 1, value);
3254 // Returns the property details for the property at entry.
3255 PropertyDetails DetailsAt(int entry) {
3256 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3259 // Set the details for entry.
3260 void DetailsAtPut(int entry, PropertyDetails value) {
3261 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3264 // Returns true if property at given entry is deleted.
3265 bool IsDeleted(int entry) {
3266 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3269 // Delete a property from the dictionary.
3270 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3272 // Attempt to shrink the dictionary after deletion of key.
3273 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3274 Handle<Derived> dictionary,
3276 return DerivedHashTable::Shrink(dictionary, key);
3280 // TODO(dcarney): templatize or move to SeededNumberDictionary
3281 void CopyValuesTo(FixedArray* elements);
3283 // Returns the number of elements in the dictionary filtering out properties
3284 // with the specified attributes.
3285 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3287 // Returns the number of enumerable elements in the dictionary.
3288 int NumberOfEnumElements() {
3289 return NumberOfElementsFilterAttributes(
3290 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3293 // Returns true if the dictionary contains any elements that are non-writable,
3294 // non-configurable, non-enumerable, or have getters/setters.
3295 bool HasComplexElements();
3297 enum SortMode { UNSORTED, SORTED };
3299 // Fill in details for properties into storage.
3300 // Returns the number of properties added.
3301 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3302 SortMode sort_mode);
3304 // Copies enumerable keys to preallocated fixed array.
3305 void CopyEnumKeysTo(FixedArray* storage);
3307 // Accessors for next enumeration index.
3308 void SetNextEnumerationIndex(int index) {
3310 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3313 int NextEnumerationIndex() {
3314 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3317 // Creates a new dictionary.
3318 MUST_USE_RESULT static Handle<Derived> New(
3320 int at_least_space_for,
3321 PretenureFlag pretenure = NOT_TENURED);
3323 // Ensure enough space for n additional elements.
3324 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3327 void Print(std::ostream& os); // NOLINT
3329 // Returns the key (slow).
3330 Object* SlowReverseLookup(Object* value);
3332 // Sets the entry to (key, value) pair.
3333 inline void SetEntry(int entry,
3335 Handle<Object> value);
3336 inline void SetEntry(int entry,
3338 Handle<Object> value,
3339 PropertyDetails details);
3341 MUST_USE_RESULT static Handle<Derived> Add(
3342 Handle<Derived> dictionary,
3344 Handle<Object> value,
3345 PropertyDetails details);
3347 // Returns iteration indices array for the |dictionary|.
3348 // Values are direct indices in the |HashTable| array.
3349 static Handle<FixedArray> BuildIterationIndicesArray(
3350 Handle<Derived> dictionary);
3353 // Generic at put operation.
3354 MUST_USE_RESULT static Handle<Derived> AtPut(
3355 Handle<Derived> dictionary,
3357 Handle<Object> value);
3359 // Add entry to dictionary.
3360 static void AddEntry(
3361 Handle<Derived> dictionary,
3363 Handle<Object> value,
3364 PropertyDetails details,
3367 // Generate new enumeration indices to avoid enumeration index overflow.
3368 // Returns iteration indices array for the |dictionary|.
3369 static Handle<FixedArray> GenerateNewEnumerationIndices(
3370 Handle<Derived> dictionary);
3371 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3372 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3376 template <typename Derived, typename Shape>
3377 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3378 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3381 // Find entry for key, otherwise return kNotFound. Optimized version of
3382 // HashTable::FindEntry.
3383 int FindEntry(Handle<Name> key);
3387 template <typename Key>
3388 class BaseDictionaryShape : public BaseShape<Key> {
3390 template <typename Dictionary>
3391 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3392 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3393 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3394 return PropertyDetails(
3395 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3398 template <typename Dictionary>
3399 static inline void DetailsAtPut(Dictionary* dict, int entry,
3400 PropertyDetails value) {
3401 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3402 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3405 template <typename Dictionary>
3406 static bool IsDeleted(Dictionary* dict, int entry) {
3410 template <typename Dictionary>
3411 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3412 Handle<Object> value, PropertyDetails details);
3416 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3418 static inline bool IsMatch(Handle<Name> key, Object* other);
3419 static inline uint32_t Hash(Handle<Name> key);
3420 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3421 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3422 static const int kPrefixSize = 2;
3423 static const int kEntrySize = 3;
3424 static const bool kIsEnumerable = true;
3428 class NameDictionary
3429 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3430 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3434 DECLARE_CAST(NameDictionary)
3436 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3437 Handle<NameDictionary> dictionary);
3441 class GlobalDictionaryShape : public NameDictionaryShape {
3443 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3445 template <typename Dictionary>
3446 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3448 template <typename Dictionary>
3449 static inline void DetailsAtPut(Dictionary* dict, int entry,
3450 PropertyDetails value);
3452 template <typename Dictionary>
3453 static bool IsDeleted(Dictionary* dict, int entry);
3455 template <typename Dictionary>
3456 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3457 Handle<Object> value, PropertyDetails details);
3461 class GlobalDictionary
3462 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3464 DECLARE_CAST(GlobalDictionary)
3468 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3470 static inline bool IsMatch(uint32_t key, Object* other);
3471 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3472 static const int kEntrySize = 3;
3473 static const bool kIsEnumerable = false;
3477 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3479 static const bool UsesSeed = true;
3480 static const int kPrefixSize = 2;
3482 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3483 static inline uint32_t SeededHashForObject(uint32_t key,
3489 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3491 static const int kPrefixSize = 0;
3493 static inline uint32_t Hash(uint32_t key);
3494 static inline uint32_t HashForObject(uint32_t key, Object* object);
3498 class SeededNumberDictionary
3499 : public Dictionary<SeededNumberDictionary,
3500 SeededNumberDictionaryShape,
3503 DECLARE_CAST(SeededNumberDictionary)
3505 // Type specific at put (default NONE attributes is used when adding).
3506 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3507 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3508 Handle<Object> value, bool used_as_prototype);
3509 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3510 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3511 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3513 // Set an existing entry or add a new one if needed.
3514 // Return the updated dictionary.
3515 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3516 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3517 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3519 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3521 // If slow elements are required we will never go back to fast-case
3522 // for the elements kept in this dictionary. We require slow
3523 // elements if an element has been added at an index larger than
3524 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3525 // when defining a getter or setter with a number key.
3526 inline bool requires_slow_elements();
3527 inline void set_requires_slow_elements();
3529 // Get the value of the max number key that has been added to this
3530 // dictionary. max_number_key can only be called if
3531 // requires_slow_elements returns false.
3532 inline uint32_t max_number_key();
3535 static const int kRequiresSlowElementsMask = 1;
3536 static const int kRequiresSlowElementsTagSize = 1;
3537 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3541 class UnseededNumberDictionary
3542 : public Dictionary<UnseededNumberDictionary,
3543 UnseededNumberDictionaryShape,
3546 DECLARE_CAST(UnseededNumberDictionary)
3548 // Type specific at put (default NONE attributes is used when adding).
3549 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3550 Handle<UnseededNumberDictionary> dictionary,
3552 Handle<Object> value);
3553 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3554 Handle<UnseededNumberDictionary> dictionary,
3556 Handle<Object> value);
3558 // Set an existing entry or add a new one if needed.
3559 // Return the updated dictionary.
3560 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3561 Handle<UnseededNumberDictionary> dictionary,
3563 Handle<Object> value);
3567 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3569 static inline bool IsMatch(Handle<Object> key, Object* other);
3570 static inline uint32_t Hash(Handle<Object> key);
3571 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3572 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3573 static const int kPrefixSize = 0;
3574 static const int kEntrySize = 2;
3578 // ObjectHashTable maps keys that are arbitrary objects to object values by
3579 // using the identity hash of the key for hashing purposes.
3580 class ObjectHashTable: public HashTable<ObjectHashTable,
3581 ObjectHashTableShape,
3584 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3586 DECLARE_CAST(ObjectHashTable)
3588 // Attempt to shrink hash table after removal of key.
3589 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3590 Handle<ObjectHashTable> table,
3591 Handle<Object> key);
3593 // Looks up the value associated with the given key. The hole value is
3594 // returned in case the key is not present.
3595 Object* Lookup(Handle<Object> key);
3596 Object* Lookup(Handle<Object> key, int32_t hash);
3597 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3599 // Adds (or overwrites) the value associated with the given key.
3600 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3602 Handle<Object> value);
3603 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3604 Handle<Object> key, Handle<Object> value,
3607 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3608 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3611 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3612 Handle<Object> key, bool* was_present,
3616 friend class MarkCompactCollector;
3618 void AddEntry(int entry, Object* key, Object* value);
3619 void RemoveEntry(int entry);
3621 // Returns the index to the value of an entry.
3622 static inline int EntryToValueIndex(int entry) {
3623 return EntryToIndex(entry) + 1;
3628 // OrderedHashTable is a HashTable with Object keys that preserves
3629 // insertion order. There are Map and Set interfaces (OrderedHashMap
3630 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3632 // Only Object* keys are supported, with Object::SameValueZero() used as the
3633 // equality operator and Object::GetHash() for the hash function.
3635 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3636 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3637 // Originally attributed to Tyler Close.
3640 // [0]: bucket count
3641 // [1]: element count
3642 // [2]: deleted element count
3643 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3644 // offset into the data table (see below) where the
3645 // first item in this bucket is stored.
3646 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3647 // Capacity() * kEntrySize, where the first entrysize
3648 // items are handled by the derived class and the
3649 // item at kChainOffset is another entry into the
3650 // data table indicating the next entry in this hash
3653 // When we transition the table to a new version we obsolete it and reuse parts
3654 // of the memory to store information how to transition an iterator to the new
3657 // Memory layout for obsolete table:
3658 // [0]: bucket count
3659 // [1]: Next newer table
3660 // [2]: Number of removed holes or -1 when the table was cleared.
3661 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3662 // [3 + NumberOfRemovedHoles()..length]: Not used
3664 template<class Derived, class Iterator, int entrysize>
3665 class OrderedHashTable: public FixedArray {
3667 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3668 static Handle<Derived> Allocate(
3669 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3671 // Returns an OrderedHashTable (possibly |table|) with enough space
3672 // to add at least one new element.
3673 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3675 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3677 static Handle<Derived> Shrink(Handle<Derived> table);
3679 // Returns a new empty OrderedHashTable and records the clearing so that
3680 // exisiting iterators can be updated.
3681 static Handle<Derived> Clear(Handle<Derived> table);
3683 // Returns a true if the OrderedHashTable contains the key
3684 static bool HasKey(Handle<Derived> table, Handle<Object> key);
3686 int NumberOfElements() {
3687 return Smi::cast(get(kNumberOfElementsIndex))->value();
3690 int NumberOfDeletedElements() {
3691 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3694 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3696 int NumberOfBuckets() {
3697 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3700 // Returns an index into |this| for the given entry.
3701 int EntryToIndex(int entry) {
3702 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3705 int HashToBucket(int hash) { return hash & (NumberOfBuckets() - 1); }
3707 int HashToEntry(int hash) {
3708 int bucket = HashToBucket(hash);
3709 Object* entry = this->get(kHashTableStartIndex + bucket);
3710 return Smi::cast(entry)->value();
3713 int KeyToFirstEntry(Object* key) {
3714 Object* hash = key->GetHash();
3715 // If the object does not have an identity hash, it was never used as a key
3716 if (hash->IsUndefined()) return kNotFound;
3717 return HashToEntry(Smi::cast(hash)->value());
3720 int NextChainEntry(int entry) {
3721 Object* next_entry = get(EntryToIndex(entry) + kChainOffset);
3722 return Smi::cast(next_entry)->value();
3725 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3728 return !get(kNextTableIndex)->IsSmi();
3731 // The next newer table. This is only valid if the table is obsolete.
3732 Derived* NextTable() {
3733 return Derived::cast(get(kNextTableIndex));
3736 // When the table is obsolete we store the indexes of the removed holes.
3737 int RemovedIndexAt(int index) {
3738 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3741 static const int kNotFound = -1;
3742 static const int kMinCapacity = 4;
3744 static const int kNumberOfBucketsIndex = 0;
3745 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3746 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3747 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3748 static const int kNextTableIndex = kNumberOfElementsIndex;
3750 static const int kNumberOfBucketsOffset =
3751 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3752 static const int kNumberOfElementsOffset =
3753 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3754 static const int kNumberOfDeletedElementsOffset =
3755 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3756 static const int kHashTableStartOffset =
3757 kHeaderSize + kHashTableStartIndex * kPointerSize;
3758 static const int kNextTableOffset =
3759 kHeaderSize + kNextTableIndex * kPointerSize;
3761 static const int kEntrySize = entrysize + 1;
3762 static const int kChainOffset = entrysize;
3764 static const int kLoadFactor = 2;
3766 // NumberOfDeletedElements is set to kClearedTableSentinel when
3767 // the table is cleared, which allows iterator transitions to
3768 // optimize that case.
3769 static const int kClearedTableSentinel = -1;
3772 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3774 void SetNumberOfBuckets(int num) {
3775 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3778 void SetNumberOfElements(int num) {
3779 set(kNumberOfElementsIndex, Smi::FromInt(num));
3782 void SetNumberOfDeletedElements(int num) {
3783 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3787 return NumberOfBuckets() * kLoadFactor;
3790 void SetNextTable(Derived* next_table) {
3791 set(kNextTableIndex, next_table);
3794 void SetRemovedIndexAt(int index, int removed_index) {
3795 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3798 static const int kRemovedHolesIndex = kHashTableStartIndex;
3800 static const int kMaxCapacity =
3801 (FixedArray::kMaxLength - kHashTableStartIndex)
3802 / (1 + (kEntrySize * kLoadFactor));
3806 class JSSetIterator;
3809 class OrderedHashSet: public OrderedHashTable<
3810 OrderedHashSet, JSSetIterator, 1> {
3812 DECLARE_CAST(OrderedHashSet)
3814 static Handle<OrderedHashSet> Add(Handle<OrderedHashSet> table,
3815 Handle<Object> value);
3819 class JSMapIterator;
3822 class OrderedHashMap
3823 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3825 DECLARE_CAST(OrderedHashMap)
3827 inline Object* ValueAt(int entry);
3829 static const int kValueOffset = 1;
3833 template <int entrysize>
3834 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3836 static inline bool IsMatch(Handle<Object> key, Object* other);
3837 static inline uint32_t Hash(Handle<Object> key);
3838 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3839 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3840 static const int kPrefixSize = 0;
3841 static const int kEntrySize = entrysize;
3845 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3846 // values. The table wraps the keys in weak cells and store values directly.
3847 // Thus it references keys weakly and values strongly.
3848 class WeakHashTable: public HashTable<WeakHashTable,
3849 WeakHashTableShape<2>,
3852 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3854 DECLARE_CAST(WeakHashTable)
3856 // Looks up the value associated with the given key. The hole value is
3857 // returned in case the key is not present.
3858 Object* Lookup(Handle<HeapObject> key);
3860 // Adds (or overwrites) the value associated with the given key. Mapping a
3861 // key to the hole value causes removal of the whole entry.
3862 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3863 Handle<HeapObject> key,
3864 Handle<HeapObject> value);
3866 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3869 friend class MarkCompactCollector;
3871 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3873 // Returns the index to the value of an entry.
3874 static inline int EntryToValueIndex(int entry) {
3875 return EntryToIndex(entry) + 1;
3880 // ScopeInfo represents information about different scopes of a source
3881 // program and the allocation of the scope's variables. Scope information
3882 // is stored in a compressed form in ScopeInfo objects and is used
3883 // at runtime (stack dumps, deoptimization, etc.).
3885 // This object provides quick access to scope info details for runtime
3887 class ScopeInfo : public FixedArray {
3889 DECLARE_CAST(ScopeInfo)
3891 // Return the type of this scope.
3892 ScopeType scope_type();
3894 // Does this scope call eval?
3897 // Return the language mode of this scope.
3898 LanguageMode language_mode();
3900 // True if this scope is a (var) declaration scope.
3901 bool is_declaration_scope();
3903 // Does this scope make a sloppy eval call?
3904 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3906 // Return the total number of locals allocated on the stack and in the
3907 // context. This includes the parameters that are allocated in the context.
3910 // Return the number of stack slots for code. This number consists of two
3912 // 1. One stack slot per stack allocated local.
3913 // 2. One stack slot for the function name if it is stack allocated.
3914 int StackSlotCount();
3916 // Return the number of context slots for code if a context is allocated. This
3917 // number consists of three parts:
3918 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3919 // 2. One context slot per context allocated local.
3920 // 3. One context slot for the function name if it is context allocated.
3921 // Parameters allocated in the context count as context allocated locals. If
3922 // no contexts are allocated for this scope ContextLength returns 0.
3923 int ContextLength();
3925 // Does this scope declare a "this" binding?
3928 // Does this scope declare a "this" binding, and the "this" binding is stack-
3929 // or context-allocated?
3930 bool HasAllocatedReceiver();
3932 // Is this scope the scope of a named function expression?
3933 bool HasFunctionName();
3935 // Return if this has context allocated locals.
3936 bool HasHeapAllocatedLocals();
3938 // Return if contexts are allocated for this scope.
3941 // Return if this is a function scope with "use asm".
3942 inline bool IsAsmModule();
3944 // Return if this is a nested function within an asm module scope.
3945 inline bool IsAsmFunction();
3947 inline bool HasSimpleParameters();
3949 // Return the function_name if present.
3950 String* FunctionName();
3952 // Return the name of the given parameter.
3953 String* ParameterName(int var);
3955 // Return the name of the given local.
3956 String* LocalName(int var);
3958 // Return the name of the given stack local.
3959 String* StackLocalName(int var);
3961 // Return the name of the given stack local.
3962 int StackLocalIndex(int var);
3964 // Return the name of the given context local.
3965 String* ContextLocalName(int var);
3967 // Return the mode of the given context local.
3968 VariableMode ContextLocalMode(int var);
3970 // Return the initialization flag of the given context local.
3971 InitializationFlag ContextLocalInitFlag(int var);
3973 // Return the initialization flag of the given context local.
3974 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3976 // Return true if this local was introduced by the compiler, and should not be
3977 // exposed to the user in a debugger.
3978 bool LocalIsSynthetic(int var);
3980 String* StrongModeFreeVariableName(int var);
3981 int StrongModeFreeVariableStartPosition(int var);
3982 int StrongModeFreeVariableEndPosition(int var);
3984 // Lookup support for serialized scope info. Returns the
3985 // the stack slot index for a given slot name if the slot is
3986 // present; otherwise returns a value < 0. The name must be an internalized
3988 int StackSlotIndex(String* name);
3990 // Lookup support for serialized scope info. Returns the local context slot
3991 // index for a given slot name if the slot is present; otherwise
3992 // returns a value < 0. The name must be an internalized string.
3993 // If the slot is present and mode != NULL, sets *mode to the corresponding
3994 // mode for that variable.
3995 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3996 VariableMode* mode, InitializationFlag* init_flag,
3997 MaybeAssignedFlag* maybe_assigned_flag);
3999 // Similar to ContextSlotIndex() but this method searches only among
4000 // global slots of the serialized scope info. Returns the context slot index
4001 // for a given slot name if the slot is present; otherwise returns a
4002 // value < 0. The name must be an internalized string. If the slot is present
4003 // and mode != NULL, sets *mode to the corresponding mode for that variable.
4004 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
4005 Handle<String> name, VariableMode* mode,
4006 InitializationFlag* init_flag,
4007 MaybeAssignedFlag* maybe_assigned_flag);
4009 // Lookup the name of a certain context slot by its index.
4010 String* ContextSlotName(int slot_index);
4012 // Lookup support for serialized scope info. Returns the
4013 // parameter index for a given parameter name if the parameter is present;
4014 // otherwise returns a value < 0. The name must be an internalized string.
4015 int ParameterIndex(String* name);
4017 // Lookup support for serialized scope info. Returns the function context
4018 // slot index if the function name is present and context-allocated (named
4019 // function expressions, only), otherwise returns a value < 0. The name
4020 // must be an internalized string.
4021 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4023 // Lookup support for serialized scope info. Returns the receiver context
4024 // slot index if scope has a "this" binding, and the binding is
4025 // context-allocated. Otherwise returns a value < 0.
4026 int ReceiverContextSlotIndex();
4028 FunctionKind function_kind();
4030 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4031 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4033 // Serializes empty scope info.
4034 static ScopeInfo* Empty(Isolate* isolate);
4040 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4041 // numeric and occupies one array slot.
4042 // 1. A set of properties of the scope
4043 // 2. The number of parameters. This only applies to function scopes. For
4044 // non-function scopes this is 0.
4045 // 3. The number of non-parameter variables allocated on the stack.
4046 // 4. The number of non-parameter and parameter variables allocated in the
4048 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4051 V(StackLocalCount) \
4052 V(ContextLocalCount) \
4053 V(ContextGlobalCount) \
4054 V(StrongModeFreeVariableCount)
4056 #define FIELD_ACCESSORS(name) \
4057 inline void Set##name(int value); \
4059 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4060 #undef FIELD_ACCESSORS
4063 #define DECL_INDEX(name) k##name,
4064 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4070 // The layout of the variable part of a ScopeInfo is as follows:
4071 // 1. ParameterEntries:
4072 // This part stores the names of the parameters for function scopes. One
4073 // slot is used per parameter, so in total this part occupies
4074 // ParameterCount() slots in the array. For other scopes than function
4075 // scopes ParameterCount() is 0.
4076 // 2. StackLocalFirstSlot:
4077 // Index of a first stack slot for stack local. Stack locals belonging to
4078 // this scope are located on a stack at slots starting from this index.
4079 // 3. StackLocalEntries:
4080 // Contains the names of local variables that are allocated on the stack,
4081 // in increasing order of the stack slot index. First local variable has
4082 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4083 // One slot is used per stack local, so in total this part occupies
4084 // StackLocalCount() slots in the array.
4085 // 4. ContextLocalNameEntries:
4086 // Contains the names of local variables and parameters that are allocated
4087 // in the context. They are stored in increasing order of the context slot
4088 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4089 // context local, so in total this part occupies ContextLocalCount() slots
4091 // 5. ContextLocalInfoEntries:
4092 // Contains the variable modes and initialization flags corresponding to
4093 // the context locals in ContextLocalNameEntries. One slot is used per
4094 // context local, so in total this part occupies ContextLocalCount()
4095 // slots in the array.
4096 // 6. StrongModeFreeVariableNameEntries:
4097 // Stores the names of strong mode free variables.
4098 // 7. StrongModeFreeVariablePositionEntries:
4099 // Stores the locations (start and end position) of strong mode free
4101 // 8. RecieverEntryIndex:
4102 // If the scope binds a "this" value, one slot is reserved to hold the
4103 // context or stack slot index for the variable.
4104 // 9. FunctionNameEntryIndex:
4105 // If the scope belongs to a named function expression this part contains
4106 // information about the function variable. It always occupies two array
4107 // slots: a. The name of the function variable.
4108 // b. The context or stack slot index for the variable.
4109 int ParameterEntriesIndex();
4110 int StackLocalFirstSlotIndex();
4111 int StackLocalEntriesIndex();
4112 int ContextLocalNameEntriesIndex();
4113 int ContextGlobalNameEntriesIndex();
4114 int ContextLocalInfoEntriesIndex();
4115 int ContextGlobalInfoEntriesIndex();
4116 int StrongModeFreeVariableNameEntriesIndex();
4117 int StrongModeFreeVariablePositionEntriesIndex();
4118 int ReceiverEntryIndex();
4119 int FunctionNameEntryIndex();
4121 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4122 VariableLocation* location, InitializationFlag* init_flag,
4123 MaybeAssignedFlag* maybe_assigned_flag);
4125 // Used for the function name variable for named function expressions, and for
4127 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4129 // Properties of scopes.
4130 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4131 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4132 STATIC_ASSERT(LANGUAGE_END == 3);
4133 class LanguageModeField
4134 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4135 class DeclarationScopeField
4136 : public BitField<bool, LanguageModeField::kNext, 1> {};
4137 class ReceiverVariableField
4138 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4140 class FunctionVariableField
4141 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4143 class FunctionVariableMode
4144 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4145 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4147 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4148 class HasSimpleParametersField
4149 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4150 class FunctionKindField
4151 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4153 // BitFields representing the encoded information for context locals in the
4154 // ContextLocalInfoEntries part.
4155 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4156 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4157 class ContextLocalMaybeAssignedFlag
4158 : public BitField<MaybeAssignedFlag, 4, 1> {};
4160 friend class ScopeIterator;
4164 // The cache for maps used by normalized (dictionary mode) objects.
4165 // Such maps do not have property descriptors, so a typical program
4166 // needs very limited number of distinct normalized maps.
4167 class NormalizedMapCache: public FixedArray {
4169 static Handle<NormalizedMapCache> New(Isolate* isolate);
4171 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4172 PropertyNormalizationMode mode);
4173 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4177 DECLARE_CAST(NormalizedMapCache)
4179 static inline bool IsNormalizedMapCache(const Object* obj);
4181 DECLARE_VERIFIER(NormalizedMapCache)
4183 static const int kEntries = 64;
4185 static inline int GetIndex(Handle<Map> map);
4187 // The following declarations hide base class methods.
4188 Object* get(int index);
4189 void set(int index, Object* value);
4193 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4194 // that is attached to code objects.
4195 class ByteArray: public FixedArrayBase {
4199 // Setter and getter.
4200 inline byte get(int index);
4201 inline void set(int index, byte value);
4203 // Treat contents as an int array.
4204 inline int get_int(int index);
4206 static int SizeFor(int length) {
4207 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4209 // We use byte arrays for free blocks in the heap. Given a desired size in
4210 // bytes that is a multiple of the word size and big enough to hold a byte
4211 // array, this function returns the number of elements a byte array should
4213 static int LengthFor(int size_in_bytes) {
4214 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4215 DCHECK(size_in_bytes >= kHeaderSize);
4216 return size_in_bytes - kHeaderSize;
4219 // Returns data start address.
4220 inline Address GetDataStartAddress();
4222 // Returns a pointer to the ByteArray object for a given data start address.
4223 static inline ByteArray* FromDataStartAddress(Address address);
4225 DECLARE_CAST(ByteArray)
4227 // Dispatched behavior.
4228 inline int ByteArraySize();
4229 DECLARE_PRINTER(ByteArray)
4230 DECLARE_VERIFIER(ByteArray)
4232 // Layout description.
4233 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4235 // Maximal memory consumption for a single ByteArray.
4236 static const int kMaxSize = 512 * MB;
4237 // Maximal length of a single ByteArray.
4238 static const int kMaxLength = kMaxSize - kHeaderSize;
4241 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4245 // BytecodeArray represents a sequence of interpreter bytecodes.
4246 class BytecodeArray : public FixedArrayBase {
4248 static int SizeFor(int length) {
4249 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4252 // Setter and getter
4253 inline byte get(int index);
4254 inline void set(int index, byte value);
4256 // Returns data start address.
4257 inline Address GetFirstBytecodeAddress();
4259 // Accessors for frame size.
4260 inline int frame_size() const;
4261 inline void set_frame_size(int frame_size);
4263 // Accessor for register count (derived from frame_size).
4264 inline int register_count() const;
4266 // Accessors for parameter count (including implicit 'this' receiver).
4267 inline int parameter_count() const;
4268 inline void set_parameter_count(int number_of_parameters);
4270 // Accessors for the constant pool.
4271 DECL_ACCESSORS(constant_pool, FixedArray)
4273 DECLARE_CAST(BytecodeArray)
4275 // Dispatched behavior.
4276 inline int BytecodeArraySize();
4277 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4279 DECLARE_PRINTER(BytecodeArray)
4280 DECLARE_VERIFIER(BytecodeArray)
4282 void Disassemble(std::ostream& os);
4284 // Layout description.
4285 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4286 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4287 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4288 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4290 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4292 // Maximal memory consumption for a single BytecodeArray.
4293 static const int kMaxSize = 512 * MB;
4294 // Maximal length of a single BytecodeArray.
4295 static const int kMaxLength = kMaxSize - kHeaderSize;
4298 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4302 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4303 // They look like heap objects (are heap object tagged and have a map) so that
4304 // the heap remains iterable. They have a size and a next pointer.
4305 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4306 // in the free list.
4307 class FreeSpace: public HeapObject {
4309 // [size]: size of the free space including the header.
4310 inline int size() const;
4311 inline void set_size(int value);
4313 inline int nobarrier_size() const;
4314 inline void nobarrier_set_size(int value);
4318 // Accessors for the next field.
4319 inline FreeSpace* next();
4320 inline FreeSpace** next_address();
4321 inline void set_next(FreeSpace* next);
4323 inline static FreeSpace* cast(HeapObject* obj);
4325 // Dispatched behavior.
4326 DECLARE_PRINTER(FreeSpace)
4327 DECLARE_VERIFIER(FreeSpace)
4329 // Layout description.
4330 // Size is smi tagged when it is stored.
4331 static const int kSizeOffset = HeapObject::kHeaderSize;
4332 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4335 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4339 // V has parameters (Type, type, TYPE, C type, element_size)
4340 #define TYPED_ARRAYS(V) \
4341 V(Uint8, uint8, UINT8, uint8_t, 1) \
4342 V(Int8, int8, INT8, int8_t, 1) \
4343 V(Uint16, uint16, UINT16, uint16_t, 2) \
4344 V(Int16, int16, INT16, int16_t, 2) \
4345 V(Uint32, uint32, UINT32, uint32_t, 4) \
4346 V(Int32, int32, INT32, int32_t, 4) \
4347 V(Float32, float32, FLOAT32, float, 4) \
4348 V(Float64, float64, FLOAT64, double, 8) \
4349 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4352 class FixedTypedArrayBase: public FixedArrayBase {
4354 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4355 DECL_ACCESSORS(base_pointer, Object)
4357 // [external_pointer]: Contains the offset between base_pointer and the start
4358 // of the data. If the base_pointer is a nullptr, the external_pointer
4359 // therefore points to the actual backing store.
4360 DECL_ACCESSORS(external_pointer, void)
4362 // Dispatched behavior.
4363 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4365 template <typename StaticVisitor>
4366 inline void FixedTypedArrayBaseIterateBody();
4368 DECLARE_CAST(FixedTypedArrayBase)
4370 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4371 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4372 static const int kHeaderSize =
4373 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4375 static const int kDataOffset = kHeaderSize;
4379 static inline int TypedArraySize(InstanceType type, int length);
4380 inline int TypedArraySize(InstanceType type);
4382 // Use with care: returns raw pointer into heap.
4383 inline void* DataPtr();
4385 inline int DataSize();
4388 static inline int ElementSize(InstanceType type);
4390 inline int DataSize(InstanceType type);
4392 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4396 template <class Traits>
4397 class FixedTypedArray: public FixedTypedArrayBase {
4399 typedef typename Traits::ElementType ElementType;
4400 static const InstanceType kInstanceType = Traits::kInstanceType;
4402 DECLARE_CAST(FixedTypedArray<Traits>)
4404 inline ElementType get_scalar(int index);
4405 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4406 inline void set(int index, ElementType value);
4408 static inline ElementType from_int(int value);
4409 static inline ElementType from_double(double value);
4411 // This accessor applies the correct conversion from Smi, HeapNumber
4413 inline void SetValue(uint32_t index, Object* value);
4415 DECLARE_PRINTER(FixedTypedArray)
4416 DECLARE_VERIFIER(FixedTypedArray)
4419 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4422 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4423 class Type##ArrayTraits { \
4424 public: /* NOLINT */ \
4425 typedef elementType ElementType; \
4426 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4427 static const char* Designator() { return #type " array"; } \
4428 static inline Handle<Object> ToHandle(Isolate* isolate, \
4429 elementType scalar); \
4430 static inline elementType defaultValue(); \
4433 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4435 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4437 #undef FIXED_TYPED_ARRAY_TRAITS
4440 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4441 // data for code generated by the Hydrogen/Lithium compiler. It also
4442 // contains information about functions that were inlined. If N different
4443 // functions were inlined then first N elements of the literal array will
4444 // contain these functions.
4447 class DeoptimizationInputData: public FixedArray {
4449 // Layout description. Indices in the array.
4450 static const int kTranslationByteArrayIndex = 0;
4451 static const int kInlinedFunctionCountIndex = 1;
4452 static const int kLiteralArrayIndex = 2;
4453 static const int kOsrAstIdIndex = 3;
4454 static const int kOsrPcOffsetIndex = 4;
4455 static const int kOptimizationIdIndex = 5;
4456 static const int kSharedFunctionInfoIndex = 6;
4457 static const int kWeakCellCacheIndex = 7;
4458 static const int kFirstDeoptEntryIndex = 8;
4460 // Offsets of deopt entry elements relative to the start of the entry.
4461 static const int kAstIdRawOffset = 0;
4462 static const int kTranslationIndexOffset = 1;
4463 static const int kArgumentsStackHeightOffset = 2;
4464 static const int kPcOffset = 3;
4465 static const int kDeoptEntrySize = 4;
4467 // Simple element accessors.
4468 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4469 inline type* name(); \
4470 inline void Set##name(type* value);
4472 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4473 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4474 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4475 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4476 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4477 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4478 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4479 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4481 #undef DECLARE_ELEMENT_ACCESSORS
4483 // Accessors for elements of the ith deoptimization entry.
4484 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4485 inline type* name(int i); \
4486 inline void Set##name(int i, type* value);
4488 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4489 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4490 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4491 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4493 #undef DECLARE_ENTRY_ACCESSORS
4495 inline BailoutId AstId(int i);
4497 inline void SetAstId(int i, BailoutId value);
4499 inline int DeoptCount();
4501 // Allocates a DeoptimizationInputData.
4502 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4503 int deopt_entry_count,
4504 PretenureFlag pretenure);
4506 DECLARE_CAST(DeoptimizationInputData)
4508 #ifdef ENABLE_DISASSEMBLER
4509 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4513 static int IndexForEntry(int i) {
4514 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4518 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4522 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4523 // data for code generated by the full compiler.
4524 // The format of the these objects is
4525 // [i * 2]: Ast ID for ith deoptimization.
4526 // [i * 2 + 1]: PC and state of ith deoptimization
4527 class DeoptimizationOutputData: public FixedArray {
4529 inline int DeoptPoints();
4531 inline BailoutId AstId(int index);
4533 inline void SetAstId(int index, BailoutId id);
4535 inline Smi* PcAndState(int index);
4536 inline void SetPcAndState(int index, Smi* offset);
4538 static int LengthOfFixedArray(int deopt_points) {
4539 return deopt_points * 2;
4542 // Allocates a DeoptimizationOutputData.
4543 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4544 int number_of_deopt_points,
4545 PretenureFlag pretenure);
4547 DECLARE_CAST(DeoptimizationOutputData)
4549 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4550 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4555 // HandlerTable is a fixed array containing entries for exception handlers in
4556 // the code object it is associated with. The tables comes in two flavors:
4557 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4558 // exception handler and a range representing the try-block covered by that
4559 // handler. Layout looks as follows:
4560 // [ range-start , range-end , handler-offset , stack-depth ]
4561 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4562 // per call-site that could throw an exception. Layout looks as follows:
4563 // [ return-address-offset , handler-offset ]
4564 class HandlerTable : public FixedArray {
4566 // Conservative prediction whether a given handler will locally catch an
4567 // exception or cause a re-throw to outside the code boundary. Since this is
4568 // undecidable it is merely an approximation (e.g. useful for debugger).
4569 enum CatchPrediction { UNCAUGHT, CAUGHT };
4571 // Accessors for handler table based on ranges.
4572 inline void SetRangeStart(int index, int value);
4573 inline void SetRangeEnd(int index, int value);
4574 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4575 inline void SetRangeDepth(int index, int value);
4577 // Accessors for handler table based on return addresses.
4578 inline void SetReturnOffset(int index, int value);
4579 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4581 // Lookup handler in a table based on ranges.
4582 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4584 // Lookup handler in a table based on return addresses.
4585 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4587 // Returns the required length of the underlying fixed array.
4588 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4589 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4591 DECLARE_CAST(HandlerTable)
4593 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4594 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4595 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4599 // Layout description for handler table based on ranges.
4600 static const int kRangeStartIndex = 0;
4601 static const int kRangeEndIndex = 1;
4602 static const int kRangeHandlerIndex = 2;
4603 static const int kRangeDepthIndex = 3;
4604 static const int kRangeEntrySize = 4;
4606 // Layout description for handler table based on return addresses.
4607 static const int kReturnOffsetIndex = 0;
4608 static const int kReturnHandlerIndex = 1;
4609 static const int kReturnEntrySize = 2;
4611 // Encoding of the {handler} field.
4612 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4613 class HandlerOffsetField : public BitField<int, 1, 30> {};
4617 // Code describes objects with on-the-fly generated machine code.
4618 class Code: public HeapObject {
4620 // Opaque data type for encapsulating code flags like kind, inline
4621 // cache state, and arguments count.
4622 typedef uint32_t Flags;
4624 #define NON_IC_KIND_LIST(V) \
4626 V(OPTIMIZED_FUNCTION) \
4633 #define IC_KIND_LIST(V) \
4644 #define CODE_KIND_LIST(V) \
4645 NON_IC_KIND_LIST(V) \
4649 #define DEFINE_CODE_KIND_ENUM(name) name,
4650 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4651 #undef DEFINE_CODE_KIND_ENUM
4655 // No more than 16 kinds. The value is currently encoded in four bits in
4657 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4659 static const char* Kind2String(Kind kind);
4667 static const int kPrologueOffsetNotSet = -1;
4669 #ifdef ENABLE_DISASSEMBLER
4671 static const char* ICState2String(InlineCacheState state);
4672 static const char* StubType2String(StubType type);
4673 static void PrintExtraICState(std::ostream& os, // NOLINT
4674 Kind kind, ExtraICState extra);
4675 void Disassemble(const char* name, std::ostream& os); // NOLINT
4676 #endif // ENABLE_DISASSEMBLER
4678 // [instruction_size]: Size of the native instructions
4679 inline int instruction_size() const;
4680 inline void set_instruction_size(int value);
4682 // [relocation_info]: Code relocation information
4683 DECL_ACCESSORS(relocation_info, ByteArray)
4684 void InvalidateRelocation();
4685 void InvalidateEmbeddedObjects();
4687 // [handler_table]: Fixed array containing offsets of exception handlers.
4688 DECL_ACCESSORS(handler_table, FixedArray)
4690 // [deoptimization_data]: Array containing data for deopt.
4691 DECL_ACCESSORS(deoptimization_data, FixedArray)
4693 // [raw_type_feedback_info]: This field stores various things, depending on
4694 // the kind of the code object.
4695 // FUNCTION => type feedback information.
4696 // STUB and ICs => major/minor key as Smi.
4697 DECL_ACCESSORS(raw_type_feedback_info, Object)
4698 inline Object* type_feedback_info();
4699 inline void set_type_feedback_info(
4700 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4701 inline uint32_t stub_key();
4702 inline void set_stub_key(uint32_t key);
4704 // [next_code_link]: Link for lists of optimized or deoptimized code.
4705 // Note that storage for this field is overlapped with typefeedback_info.
4706 DECL_ACCESSORS(next_code_link, Object)
4708 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4709 // field does not have to be traced during garbage collection since
4710 // it is only used by the garbage collector itself.
4711 DECL_ACCESSORS(gc_metadata, Object)
4713 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4714 // at the moment when this object was created.
4715 inline void set_ic_age(int count);
4716 inline int ic_age() const;
4718 // [prologue_offset]: Offset of the function prologue, used for aging
4719 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4720 inline int prologue_offset() const;
4721 inline void set_prologue_offset(int offset);
4723 // [constant_pool offset]: Offset of the constant pool.
4724 // Valid for FLAG_enable_embedded_constant_pool only
4725 inline int constant_pool_offset() const;
4726 inline void set_constant_pool_offset(int offset);
4728 // Unchecked accessors to be used during GC.
4729 inline ByteArray* unchecked_relocation_info();
4731 inline int relocation_size();
4733 // [flags]: Various code flags.
4734 inline Flags flags();
4735 inline void set_flags(Flags flags);
4737 // [flags]: Access to specific code flags.
4739 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4740 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4742 inline StubType type(); // Only valid for monomorphic IC stubs.
4744 // Testers for IC stub kinds.
4745 inline bool is_inline_cache_stub();
4746 inline bool is_debug_stub();
4747 inline bool is_handler();
4748 inline bool is_load_stub();
4749 inline bool is_keyed_load_stub();
4750 inline bool is_store_stub();
4751 inline bool is_keyed_store_stub();
4752 inline bool is_call_stub();
4753 inline bool is_binary_op_stub();
4754 inline bool is_compare_ic_stub();
4755 inline bool is_compare_nil_ic_stub();
4756 inline bool is_to_boolean_ic_stub();
4757 inline bool is_keyed_stub();
4758 inline bool is_optimized_code();
4759 inline bool embeds_maps_weakly();
4761 inline bool IsCodeStubOrIC();
4762 inline bool IsJavaScriptCode();
4764 inline void set_raw_kind_specific_flags1(int value);
4765 inline void set_raw_kind_specific_flags2(int value);
4767 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4768 // object was generated by either the hydrogen or the TurboFan optimizing
4769 // compiler (but it may not be an optimized function).
4770 inline bool is_crankshafted();
4771 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4772 inline void set_is_crankshafted(bool value);
4774 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4775 // code object was generated by the TurboFan optimizing compiler.
4776 inline bool is_turbofanned();
4777 inline void set_is_turbofanned(bool value);
4779 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4780 // embedded objects in code should be treated weakly.
4781 inline bool can_have_weak_objects();
4782 inline void set_can_have_weak_objects(bool value);
4784 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4785 // deoptimization support.
4786 inline bool has_deoptimization_support();
4787 inline void set_has_deoptimization_support(bool value);
4789 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4790 // been compiled with debug break slots.
4791 inline bool has_debug_break_slots();
4792 inline void set_has_debug_break_slots(bool value);
4794 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4795 // reloc info includes runtime and external references to support
4796 // serialization/deserialization.
4797 inline bool has_reloc_info_for_serialization();
4798 inline void set_has_reloc_info_for_serialization(bool value);
4800 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4801 // how long the function has been marked for OSR and therefore which
4802 // level of loop nesting we are willing to do on-stack replacement
4804 inline void set_allow_osr_at_loop_nesting_level(int level);
4805 inline int allow_osr_at_loop_nesting_level();
4807 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4808 // the code object was seen on the stack with no IC patching going on.
4809 inline int profiler_ticks();
4810 inline void set_profiler_ticks(int ticks);
4812 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4813 // For builtins, tells which builtin index it has.
4814 // Note that builtins can have a code kind other than BUILTIN, which means
4815 // that for arbitrary code objects, this index value may be random garbage.
4816 // To verify in that case, compare the code object to the indexed builtin.
4817 inline int builtin_index();
4818 inline void set_builtin_index(int id);
4820 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4821 // reserved in the code prologue.
4822 inline unsigned stack_slots();
4823 inline void set_stack_slots(unsigned slots);
4825 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4826 // the instruction stream where the safepoint table starts.
4827 inline unsigned safepoint_table_offset();
4828 inline void set_safepoint_table_offset(unsigned offset);
4830 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4831 // instruction stream where the back edge table starts.
4832 inline unsigned back_edge_table_offset();
4833 inline void set_back_edge_table_offset(unsigned offset);
4835 inline bool back_edges_patched_for_osr();
4837 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4838 inline uint16_t to_boolean_state();
4840 // [has_function_cache]: For kind STUB tells whether there is a function
4841 // cache is passed to the stub.
4842 inline bool has_function_cache();
4843 inline void set_has_function_cache(bool flag);
4846 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4847 // the code is going to be deoptimized because of dead embedded maps.
4848 inline bool marked_for_deoptimization();
4849 inline void set_marked_for_deoptimization(bool flag);
4851 // [constant_pool]: The constant pool for this function.
4852 inline Address constant_pool();
4854 // Get the safepoint entry for the given pc.
4855 SafepointEntry GetSafepointEntry(Address pc);
4857 // Find an object in a stub with a specified map
4858 Object* FindNthObject(int n, Map* match_map);
4860 // Find the first allocation site in an IC stub.
4861 AllocationSite* FindFirstAllocationSite();
4863 // Find the first map in an IC stub.
4864 Map* FindFirstMap();
4865 void FindAllMaps(MapHandleList* maps);
4867 // Find the first handler in an IC stub.
4868 Code* FindFirstHandler();
4870 // Find |length| handlers and put them into |code_list|. Returns false if not
4871 // enough handlers can be found.
4872 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4874 // Find the handler for |map|.
4875 MaybeHandle<Code> FindHandlerForMap(Map* map);
4877 // Find the first name in an IC stub.
4878 Name* FindFirstName();
4880 class FindAndReplacePattern;
4881 // For each (map-to-find, object-to-replace) pair in the pattern, this
4882 // function replaces the corresponding placeholder in the code with the
4883 // object-to-replace. The function assumes that pairs in the pattern come in
4884 // the same order as the placeholders in the code.
4885 // If the placeholder is a weak cell, then the value of weak cell is matched
4886 // against the map-to-find.
4887 void FindAndReplace(const FindAndReplacePattern& pattern);
4889 // The entire code object including its header is copied verbatim to the
4890 // snapshot so that it can be written in one, fast, memcpy during
4891 // deserialization. The deserializer will overwrite some pointers, rather
4892 // like a runtime linker, but the random allocation addresses used in the
4893 // mksnapshot process would still be present in the unlinked snapshot data,
4894 // which would make snapshot production non-reproducible. This method wipes
4895 // out the to-be-overwritten header data for reproducible snapshots.
4896 inline void WipeOutHeader();
4898 // Flags operations.
4899 static inline Flags ComputeFlags(
4900 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4901 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4902 CacheHolderFlag holder = kCacheOnReceiver);
4904 static inline Flags ComputeMonomorphicFlags(
4905 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4906 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4908 static inline Flags ComputeHandlerFlags(
4909 Kind handler_kind, StubType type = NORMAL,
4910 CacheHolderFlag holder = kCacheOnReceiver);
4912 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4913 static inline StubType ExtractTypeFromFlags(Flags flags);
4914 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4915 static inline Kind ExtractKindFromFlags(Flags flags);
4916 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4918 static inline Flags RemoveTypeFromFlags(Flags flags);
4919 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4921 // Convert a target address into a code object.
4922 static inline Code* GetCodeFromTargetAddress(Address address);
4924 // Convert an entry address into an object.
4925 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4927 // Returns the address of the first instruction.
4928 inline byte* instruction_start();
4930 // Returns the address right after the last instruction.
4931 inline byte* instruction_end();
4933 // Returns the size of the instructions, padding, and relocation information.
4934 inline int body_size();
4936 // Returns the address of the first relocation info (read backwards!).
4937 inline byte* relocation_start();
4939 // Code entry point.
4940 inline byte* entry();
4942 // Returns true if pc is inside this object's instructions.
4943 inline bool contains(byte* pc);
4945 // Relocate the code by delta bytes. Called to signal that this code
4946 // object has been moved by delta bytes.
4947 void Relocate(intptr_t delta);
4949 // Migrate code described by desc.
4950 void CopyFrom(const CodeDesc& desc);
4952 // Returns the object size for a given body (used for allocation).
4953 static int SizeFor(int body_size) {
4954 DCHECK_SIZE_TAG_ALIGNED(body_size);
4955 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4958 // Calculate the size of the code object to report for log events. This takes
4959 // the layout of the code object into account.
4960 inline int ExecutableSize();
4962 // Locating source position.
4963 int SourcePosition(Address pc);
4964 int SourceStatementPosition(Address pc);
4968 // Dispatched behavior.
4969 inline int CodeSize();
4970 inline void CodeIterateBody(ObjectVisitor* v);
4972 template<typename StaticVisitor>
4973 inline void CodeIterateBody(Heap* heap);
4975 DECLARE_PRINTER(Code)
4976 DECLARE_VERIFIER(Code)
4978 void ClearInlineCaches();
4979 void ClearInlineCaches(Kind kind);
4981 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4982 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4984 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4986 kToBeExecutedOnceCodeAge = -3,
4987 kNotExecutedCodeAge = -2,
4988 kExecutedOnceCodeAge = -1,
4990 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4992 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4993 kLastCodeAge = kAfterLastCodeAge - 1,
4994 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4995 kIsOldCodeAge = kSexagenarianCodeAge,
4996 kPreAgedCodeAge = kIsOldCodeAge - 1
4998 #undef DECLARE_CODE_AGE_ENUM
5000 // Code aging. Indicates how many full GCs this code has survived without
5001 // being entered through the prologue. Used to determine when it is
5002 // relatively safe to flush this code object and replace it with the lazy
5003 // compilation stub.
5004 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5005 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5006 void MakeYoung(Isolate* isolate);
5007 void MarkToBeExecutedOnce(Isolate* isolate);
5008 void MakeOlder(MarkingParity);
5009 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5012 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5013 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5016 void PrintDeoptLocation(FILE* out, Address pc);
5017 bool CanDeoptAt(Address pc);
5020 void VerifyEmbeddedObjectsDependency();
5024 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5025 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5026 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
5029 inline bool CanContainWeakObjects();
5031 inline bool IsWeakObject(Object* object);
5033 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5035 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5036 WeakCell* CachedWeakCell();
5038 // Max loop nesting marker used to postpose OSR. We don't take loop
5039 // nesting that is deeper than 5 levels into account.
5040 static const int kMaxLoopNestingMarker = 6;
5042 static const int kConstantPoolSize =
5043 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5045 // Layout description.
5046 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5047 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5048 static const int kDeoptimizationDataOffset =
5049 kHandlerTableOffset + kPointerSize;
5050 // For FUNCTION kind, we store the type feedback info here.
5051 static const int kTypeFeedbackInfoOffset =
5052 kDeoptimizationDataOffset + kPointerSize;
5053 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5054 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5055 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5056 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5057 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5058 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5059 static const int kKindSpecificFlags2Offset =
5060 kKindSpecificFlags1Offset + kIntSize;
5061 // Note: We might be able to squeeze this into the flags above.
5062 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5063 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5064 static const int kHeaderPaddingStart =
5065 kConstantPoolOffset + kConstantPoolSize;
5067 // Add padding to align the instruction start following right after
5068 // the Code object header.
5069 static const int kHeaderSize =
5070 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5072 // Byte offsets within kKindSpecificFlags1Offset.
5073 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5074 class FullCodeFlagsHasDeoptimizationSupportField:
5075 public BitField<bool, 0, 1> {}; // NOLINT
5076 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5077 class FullCodeFlagsHasRelocInfoForSerialization
5078 : public BitField<bool, 2, 1> {};
5079 // Bit 3 in this bitfield is unused.
5080 class ProfilerTicksField : public BitField<int, 4, 28> {};
5082 // Flags layout. BitField<type, shift, size>.
5083 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5084 class TypeField : public BitField<StubType, 4, 1> {};
5085 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5086 class KindField : public BitField<Kind, 7, 4> {};
5087 class ExtraICStateField: public BitField<ExtraICState, 11,
5088 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5090 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5091 static const int kStackSlotsFirstBit = 0;
5092 static const int kStackSlotsBitCount = 24;
5093 static const int kHasFunctionCacheBit =
5094 kStackSlotsFirstBit + kStackSlotsBitCount;
5095 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5096 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5097 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5099 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5100 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5102 class StackSlotsField: public BitField<int,
5103 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5104 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5106 class MarkedForDeoptimizationField
5107 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5108 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5110 class CanHaveWeakObjectsField
5111 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5113 // KindSpecificFlags2 layout (ALL)
5114 static const int kIsCrankshaftedBit = 0;
5115 class IsCrankshaftedField: public BitField<bool,
5116 kIsCrankshaftedBit, 1> {}; // NOLINT
5118 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5119 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5120 static const int kSafepointTableOffsetBitCount = 30;
5122 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5123 kSafepointTableOffsetBitCount <= 32);
5124 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5126 class SafepointTableOffsetField: public BitField<int,
5127 kSafepointTableOffsetFirstBit,
5128 kSafepointTableOffsetBitCount> {}; // NOLINT
5130 // KindSpecificFlags2 layout (FUNCTION)
5131 class BackEdgeTableOffsetField: public BitField<int,
5132 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5133 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5134 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5135 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5137 static const int kArgumentsBits = 16;
5138 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5140 // This constant should be encodable in an ARM instruction.
5141 static const int kFlagsNotUsedInLookup =
5142 TypeField::kMask | CacheHolderField::kMask;
5145 friend class RelocIterator;
5146 friend class Deoptimizer; // For FindCodeAgeSequence.
5148 void ClearInlineCaches(Kind* kind);
5151 byte* FindCodeAgeSequence();
5152 static void GetCodeAgeAndParity(Code* code, Age* age,
5153 MarkingParity* parity);
5154 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5155 MarkingParity* parity);
5156 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5158 // Code aging -- platform-specific
5159 static void PatchPlatformCodeAge(Isolate* isolate,
5160 byte* sequence, Age age,
5161 MarkingParity parity);
5163 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5167 // This class describes the layout of dependent codes array of a map. The
5168 // array is partitioned into several groups of dependent codes. Each group
5169 // contains codes with the same dependency on the map. The array has the
5170 // following layout for n dependency groups:
5172 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5173 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5174 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5176 // The first n elements are Smis, each of them specifies the number of codes
5177 // in the corresponding group. The subsequent elements contain grouped code
5178 // objects in weak cells. The suffix of the array can be filled with the
5179 // undefined value if the number of codes is less than the length of the
5180 // array. The order of the code objects within a group is not preserved.
5182 // All code indexes used in the class are counted starting from the first
5183 // code object of the first group. In other words, code index 0 corresponds
5184 // to array index n = kCodesStartIndex.
5186 class DependentCode: public FixedArray {
5188 enum DependencyGroup {
5189 // Group of code that weakly embed this map and depend on being
5190 // deoptimized when the map is garbage collected.
5192 // Group of code that embed a transition to this map, and depend on being
5193 // deoptimized when the transition is replaced by a new version.
5195 // Group of code that omit run-time prototype checks for prototypes
5196 // described by this map. The group is deoptimized whenever an object
5197 // described by this map changes shape (and transitions to a new map),
5198 // possibly invalidating the assumptions embedded in the code.
5199 kPrototypeCheckGroup,
5200 // Group of code that depends on global property values in property cells
5201 // not being changed.
5202 kPropertyCellChangedGroup,
5203 // Group of code that omit run-time type checks for the field(s) introduced
5206 // Group of code that omit run-time type checks for initial maps of
5208 kInitialMapChangedGroup,
5209 // Group of code that depends on tenuring information in AllocationSites
5210 // not being changed.
5211 kAllocationSiteTenuringChangedGroup,
5212 // Group of code that depends on element transition information in
5213 // AllocationSites not being changed.
5214 kAllocationSiteTransitionChangedGroup
5217 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5219 // Array for holding the index of the first code object of each group.
5220 // The last element stores the total number of code objects.
5221 class GroupStartIndexes {
5223 explicit GroupStartIndexes(DependentCode* entries);
5224 void Recompute(DependentCode* entries);
5225 int at(int i) { return start_indexes_[i]; }
5226 int number_of_entries() { return start_indexes_[kGroupCount]; }
5228 int start_indexes_[kGroupCount + 1];
5231 bool Contains(DependencyGroup group, WeakCell* code_cell);
5233 static Handle<DependentCode> InsertCompilationDependencies(
5234 Handle<DependentCode> entries, DependencyGroup group,
5235 Handle<Foreign> info);
5237 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5238 DependencyGroup group,
5239 Handle<WeakCell> code_cell);
5241 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5242 WeakCell* code_cell);
5244 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5247 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5248 DependentCode::DependencyGroup group);
5250 bool MarkCodeForDeoptimization(Isolate* isolate,
5251 DependentCode::DependencyGroup group);
5253 // The following low-level accessors should only be used by this class
5254 // and the mark compact collector.
5255 inline int number_of_entries(DependencyGroup group);
5256 inline void set_number_of_entries(DependencyGroup group, int value);
5257 inline Object* object_at(int i);
5258 inline void set_object_at(int i, Object* object);
5259 inline void clear_at(int i);
5260 inline void copy(int from, int to);
5261 DECLARE_CAST(DependentCode)
5263 static const char* DependencyGroupName(DependencyGroup group);
5264 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5267 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5268 DependencyGroup group,
5269 Handle<Object> object);
5270 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5271 // Make a room at the end of the given group by moving out the first
5272 // code objects of the subsequent groups.
5273 inline void ExtendGroup(DependencyGroup group);
5274 // Compact by removing cleared weak cells and return true if there was
5275 // any cleared weak cell.
5277 static int Grow(int number_of_entries) {
5278 if (number_of_entries < 5) return number_of_entries + 1;
5279 return number_of_entries * 5 / 4;
5281 static const int kCodesStartIndex = kGroupCount;
5285 class PrototypeInfo;
5288 // All heap objects have a Map that describes their structure.
5289 // A Map contains information about:
5290 // - Size information about the object
5291 // - How to iterate over an object (for garbage collection)
5292 class Map: public HeapObject {
5295 // Size in bytes or kVariableSizeSentinel if instances do not have
5297 inline int instance_size();
5298 inline void set_instance_size(int value);
5300 // Only to clear an unused byte, remove once byte is used.
5301 inline void clear_unused();
5303 // [inobject_properties_or_constructor_function_index]: Provides access
5304 // to the inobject properties in case of JSObject maps, or the constructor
5305 // function index in case of primitive maps.
5306 inline int inobject_properties_or_constructor_function_index();
5307 inline void set_inobject_properties_or_constructor_function_index(int value);
5308 // Count of properties allocated in the object (JSObject only).
5309 inline int GetInObjectProperties();
5310 inline void SetInObjectProperties(int value);
5311 // Index of the constructor function in the native context (primitives only),
5312 // or the special sentinel value to indicate that there is no object wrapper
5313 // for the primitive (i.e. in case of null or undefined).
5314 static const int kNoConstructorFunctionIndex = 0;
5315 inline int GetConstructorFunctionIndex();
5316 inline void SetConstructorFunctionIndex(int value);
5319 inline InstanceType instance_type();
5320 inline void set_instance_type(InstanceType value);
5322 // Tells how many unused property fields are available in the
5323 // instance (only used for JSObject in fast mode).
5324 inline int unused_property_fields();
5325 inline void set_unused_property_fields(int value);
5328 inline byte bit_field() const;
5329 inline void set_bit_field(byte value);
5332 inline byte bit_field2() const;
5333 inline void set_bit_field2(byte value);
5336 inline uint32_t bit_field3() const;
5337 inline void set_bit_field3(uint32_t bits);
5339 class EnumLengthBits: public BitField<int,
5340 0, kDescriptorIndexBitCount> {}; // NOLINT
5341 class NumberOfOwnDescriptorsBits: public BitField<int,
5342 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5343 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5344 class DictionaryMap : public BitField<bool, 20, 1> {};
5345 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5346 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5347 class Deprecated : public BitField<bool, 23, 1> {};
5348 class IsUnstable : public BitField<bool, 24, 1> {};
5349 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5350 class IsStrong : public BitField<bool, 26, 1> {};
5353 // Keep this bit field at the very end for better code in
5354 // Builtins::kJSConstructStubGeneric stub.
5355 // This counter is used for in-object slack tracking and for map aging.
5356 // The in-object slack tracking is considered enabled when the counter is
5357 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5358 class Counter : public BitField<int, 28, 4> {};
5359 static const int kSlackTrackingCounterStart = 14;
5360 static const int kSlackTrackingCounterEnd = 8;
5361 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5362 static const int kRetainingCounterEnd = 0;
5364 // Tells whether the object in the prototype property will be used
5365 // for instances created from this function. If the prototype
5366 // property is set to a value that is not a JSObject, the prototype
5367 // property will not be used to create instances of the function.
5368 // See ECMA-262, 13.2.2.
5369 inline void set_non_instance_prototype(bool value);
5370 inline bool has_non_instance_prototype();
5372 // Tells whether the instance has a [[Construct]] internal method.
5373 // This property is implemented according to ES6, section 7.2.4.
5374 inline void set_is_constructor(bool value);
5375 inline bool is_constructor() const;
5377 // Tells whether the instance with this map should be ignored by the
5378 // Object.getPrototypeOf() function and the __proto__ accessor.
5379 inline void set_is_hidden_prototype();
5380 inline bool is_hidden_prototype() const;
5382 // Records and queries whether the instance has a named interceptor.
5383 inline void set_has_named_interceptor();
5384 inline bool has_named_interceptor();
5386 // Records and queries whether the instance has an indexed interceptor.
5387 inline void set_has_indexed_interceptor();
5388 inline bool has_indexed_interceptor();
5390 // Tells whether the instance is undetectable.
5391 // An undetectable object is a special class of JSObject: 'typeof' operator
5392 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5393 // a normal JS object. It is useful for implementing undetectable
5394 // document.all in Firefox & Safari.
5395 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5396 inline void set_is_undetectable();
5397 inline bool is_undetectable();
5399 // Tells whether the instance has a call-as-function handler.
5400 inline void set_is_observed();
5401 inline bool is_observed();
5403 // Tells whether the instance has a [[Call]] internal method.
5404 // This property is implemented according to ES6, section 7.2.3.
5405 inline void set_is_callable();
5406 inline bool is_callable() const;
5408 inline void set_is_strong();
5409 inline bool is_strong();
5410 inline void set_is_extensible(bool value);
5411 inline bool is_extensible();
5412 inline void set_is_prototype_map(bool value);
5413 inline bool is_prototype_map() const;
5415 inline void set_elements_kind(ElementsKind elements_kind);
5416 inline ElementsKind elements_kind();
5418 // Tells whether the instance has fast elements that are only Smis.
5419 inline bool has_fast_smi_elements();
5421 // Tells whether the instance has fast elements.
5422 inline bool has_fast_object_elements();
5423 inline bool has_fast_smi_or_object_elements();
5424 inline bool has_fast_double_elements();
5425 inline bool has_fast_elements();
5426 inline bool has_sloppy_arguments_elements();
5427 inline bool has_fixed_typed_array_elements();
5428 inline bool has_dictionary_elements();
5430 static bool IsValidElementsTransition(ElementsKind from_kind,
5431 ElementsKind to_kind);
5433 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5434 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5435 bool DictionaryElementsInPrototypeChainOnly();
5437 inline Map* ElementsTransitionMap();
5439 inline FixedArrayBase* GetInitialElements();
5441 // [raw_transitions]: Provides access to the transitions storage field.
5442 // Don't call set_raw_transitions() directly to overwrite transitions, use
5443 // the TransitionArray::ReplaceTransitions() wrapper instead!
5444 DECL_ACCESSORS(raw_transitions, Object)
5445 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5446 // (which prototype maps don't have).
5447 DECL_ACCESSORS(prototype_info, Object)
5448 // PrototypeInfo is created lazily using this helper (which installs it on
5449 // the given prototype's map).
5450 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5451 Handle<JSObject> prototype, Isolate* isolate);
5452 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5453 Handle<Map> prototype_map, Isolate* isolate);
5455 // [prototype chain validity cell]: Associated with a prototype object,
5456 // stored in that object's map's PrototypeInfo, indicates that prototype
5457 // chains through this object are currently valid. The cell will be
5458 // invalidated and replaced when the prototype chain changes.
5459 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5461 static const int kPrototypeChainValid = 0;
5462 static const int kPrototypeChainInvalid = 1;
5465 Map* FindFieldOwner(int descriptor);
5467 inline int GetInObjectPropertyOffset(int index);
5469 int NumberOfFields();
5471 // TODO(ishell): candidate with JSObject::MigrateToMap().
5472 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5473 int target_inobject, int target_unused,
5474 int* old_number_of_fields);
5475 // TODO(ishell): moveit!
5476 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5477 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5478 Representation rep1, Handle<HeapType> type1, Representation rep2,
5479 Handle<HeapType> type2, Isolate* isolate);
5480 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5481 Representation new_representation,
5482 Handle<HeapType> new_field_type);
5483 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5484 PropertyKind new_kind,
5485 PropertyAttributes new_attributes,
5486 Representation new_representation,
5487 Handle<HeapType> new_field_type,
5488 StoreMode store_mode);
5489 static Handle<Map> CopyGeneralizeAllRepresentations(
5490 Handle<Map> map, int modify_index, StoreMode store_mode,
5491 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5493 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5494 int descriptor_number,
5495 Handle<Object> value);
5497 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5498 const char* reason);
5500 // Returns the constructor name (the name (possibly, inferred name) of the
5501 // function that was used to instantiate the object).
5502 String* constructor_name();
5504 // Tells whether the map is used for JSObjects in dictionary mode (ie
5505 // normalized objects, ie objects for which HasFastProperties returns false).
5506 // A map can never be used for both dictionary mode and fast mode JSObjects.
5507 // False by default and for HeapObjects that are not JSObjects.
5508 inline void set_dictionary_map(bool value);
5509 inline bool is_dictionary_map();
5511 // Tells whether the instance needs security checks when accessing its
5513 inline void set_is_access_check_needed(bool access_check_needed);
5514 inline bool is_access_check_needed();
5516 // Returns true if map has a non-empty stub code cache.
5517 inline bool has_code_cache();
5519 // [prototype]: implicit prototype object.
5520 DECL_ACCESSORS(prototype, Object)
5521 // TODO(jkummerow): make set_prototype private.
5522 static void SetPrototype(
5523 Handle<Map> map, Handle<Object> prototype,
5524 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5526 // [constructor]: points back to the function responsible for this map.
5527 // The field overlaps with the back pointer. All maps in a transition tree
5528 // have the same constructor, so maps with back pointers can walk the
5529 // back pointer chain until they find the map holding their constructor.
5530 DECL_ACCESSORS(constructor_or_backpointer, Object)
5531 inline Object* GetConstructor() const;
5532 inline void SetConstructor(Object* constructor,
5533 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5534 // [back pointer]: points back to the parent map from which a transition
5535 // leads to this map. The field overlaps with the constructor (see above).
5536 inline Object* GetBackPointer();
5537 inline void SetBackPointer(Object* value,
5538 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5540 // [instance descriptors]: describes the object.
5541 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5543 // [layout descriptor]: describes the object layout.
5544 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5545 // |layout descriptor| accessor which can be used from GC.
5546 inline LayoutDescriptor* layout_descriptor_gc_safe();
5547 inline bool HasFastPointerLayout() const;
5549 // |layout descriptor| accessor that is safe to call even when
5550 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5551 // |layout_descriptor| field at all).
5552 inline LayoutDescriptor* GetLayoutDescriptor();
5554 inline void UpdateDescriptors(DescriptorArray* descriptors,
5555 LayoutDescriptor* layout_descriptor);
5556 inline void InitializeDescriptors(DescriptorArray* descriptors,
5557 LayoutDescriptor* layout_descriptor);
5559 // [stub cache]: contains stubs compiled for this map.
5560 DECL_ACCESSORS(code_cache, Object)
5562 // [dependent code]: list of optimized codes that weakly embed this map.
5563 DECL_ACCESSORS(dependent_code, DependentCode)
5565 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5566 DECL_ACCESSORS(weak_cell_cache, Object)
5568 inline PropertyDetails GetLastDescriptorDetails();
5570 inline int LastAdded();
5572 inline int NumberOfOwnDescriptors();
5573 inline void SetNumberOfOwnDescriptors(int number);
5575 inline Cell* RetrieveDescriptorsPointer();
5577 inline int EnumLength();
5578 inline void SetEnumLength(int length);
5580 inline bool owns_descriptors();
5581 inline void set_owns_descriptors(bool owns_descriptors);
5582 inline void mark_unstable();
5583 inline bool is_stable();
5584 inline void set_migration_target(bool value);
5585 inline bool is_migration_target();
5586 inline void set_counter(int value);
5587 inline int counter();
5588 inline void deprecate();
5589 inline bool is_deprecated();
5590 inline bool CanBeDeprecated();
5591 // Returns a non-deprecated version of the input. If the input was not
5592 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5593 // is found by re-transitioning from the root of the transition tree using the
5594 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5596 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5598 // Returns a non-deprecated version of the input. This method may deprecate
5599 // existing maps along the way if encodings conflict. Not for use while
5600 // gathering type feedback. Use TryUpdate in those cases instead.
5601 static Handle<Map> Update(Handle<Map> map);
5603 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5604 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5605 Descriptor* descriptor,
5606 TransitionFlag flag);
5608 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5611 Handle<HeapType> type,
5612 PropertyAttributes attributes,
5613 Representation representation,
5614 TransitionFlag flag);
5616 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5619 Handle<Object> constant,
5620 PropertyAttributes attributes,
5621 TransitionFlag flag);
5623 // Returns a new map with all transitions dropped from the given map and
5624 // the ElementsKind set.
5625 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5626 ElementsKind to_kind);
5628 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5630 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5632 TransitionFlag flag);
5634 static Handle<Map> CopyForObserved(Handle<Map> map);
5636 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5637 PropertyAttributes attrs_to_add,
5638 Handle<Symbol> transition_marker,
5639 const char* reason);
5641 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5644 // Maximal number of fast properties. Used to restrict the number of map
5645 // transitions to avoid an explosion in the number of maps for objects used as
5647 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5648 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5650 Handle<Object> value,
5651 PropertyAttributes attributes,
5652 StoreFromKeyed store_mode);
5653 static Handle<Map> TransitionToAccessorProperty(
5654 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5655 Handle<Object> accessor, PropertyAttributes attributes);
5656 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5659 PropertyAttributes attributes);
5661 inline void AppendDescriptor(Descriptor* desc);
5663 // Returns a copy of the map, prepared for inserting into the transition
5664 // tree (if the |map| owns descriptors then the new one will share
5665 // descriptors with |map|).
5666 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5668 // Returns a copy of the map, with all transitions dropped from the
5669 // instance descriptors.
5670 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5671 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5673 // Returns the next free property index (only valid for FAST MODE).
5674 int NextFreePropertyIndex();
5676 // Returns the number of properties described in instance_descriptors
5677 // filtering out properties with the specified attributes.
5678 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5679 PropertyAttributes filter = NONE);
5683 // Code cache operations.
5685 // Clears the code cache.
5686 inline void ClearCodeCache(Heap* heap);
5688 // Update code cache.
5689 static void UpdateCodeCache(Handle<Map> map,
5693 // Extend the descriptor array of the map with the list of descriptors.
5694 // In case of duplicates, the latest descriptor is used.
5695 static void AppendCallbackDescriptors(Handle<Map> map,
5696 Handle<Object> descriptors);
5698 static inline int SlackForArraySize(int old_size, int size_limit);
5700 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5702 // Returns the found code or undefined if absent.
5703 Object* FindInCodeCache(Name* name, Code::Flags flags);
5705 // Returns the non-negative index of the code object if it is in the
5706 // cache and -1 otherwise.
5707 int IndexInCodeCache(Object* name, Code* code);
5709 // Removes a code object from the code cache at the given index.
5710 void RemoveFromCodeCache(Name* name, Code* code, int index);
5712 // Computes a hash value for this map, to be used in HashTables and such.
5715 // Returns the map that this map transitions to if its elements_kind
5716 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5717 // |safe_to_add_transitions| is set to false if adding transitions is not
5719 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5721 // Returns the transitioned map for this map with the most generic
5722 // elements_kind that's found in |candidates|, or null handle if no match is
5724 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5725 MapHandleList* candidates);
5727 inline bool CanTransition();
5729 inline bool IsPrimitiveMap();
5730 inline bool IsJSObjectMap();
5731 inline bool IsJSArrayMap();
5732 inline bool IsJSFunctionMap();
5733 inline bool IsStringMap();
5734 inline bool IsJSProxyMap();
5735 inline bool IsJSGlobalProxyMap();
5736 inline bool IsJSGlobalObjectMap();
5737 inline bool IsGlobalObjectMap();
5739 inline bool CanOmitMapChecks();
5741 static void AddDependentCode(Handle<Map> map,
5742 DependentCode::DependencyGroup group,
5745 bool IsMapInArrayPrototypeChain();
5747 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5749 // Dispatched behavior.
5750 DECLARE_PRINTER(Map)
5751 DECLARE_VERIFIER(Map)
5754 void DictionaryMapVerify();
5755 void VerifyOmittedMapChecks();
5758 inline int visitor_id();
5759 inline void set_visitor_id(int visitor_id);
5761 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5762 Handle<Object> prototype,
5763 PrototypeOptimizationMode mode);
5765 static const int kMaxPreAllocatedPropertyFields = 255;
5767 // Layout description.
5768 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5769 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5770 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5771 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5772 static const int kConstructorOrBackPointerOffset =
5773 kPrototypeOffset + kPointerSize;
5774 // When there is only one transition, it is stored directly in this field;
5775 // otherwise a transition array is used.
5776 // For prototype maps, this slot is used to store this map's PrototypeInfo
5778 static const int kTransitionsOrPrototypeInfoOffset =
5779 kConstructorOrBackPointerOffset + kPointerSize;
5780 static const int kDescriptorsOffset =
5781 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5782 #if V8_DOUBLE_FIELDS_UNBOXING
5783 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5784 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5786 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5787 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5789 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5790 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5791 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5793 // Layout of pointer fields. Heap iteration code relies on them
5794 // being continuously allocated.
5795 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5796 static const int kPointerFieldsEndOffset = kSize;
5798 // Byte offsets within kInstanceSizesOffset.
5799 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5800 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5801 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5802 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5803 // Note there is one byte available for use here.
5804 static const int kUnusedByte = 2;
5805 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5806 static const int kVisitorIdByte = 3;
5807 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5809 // Byte offsets within kInstanceAttributesOffset attributes.
5810 #if V8_TARGET_LITTLE_ENDIAN
5811 // Order instance type and bit field together such that they can be loaded
5812 // together as a 16-bit word with instance type in the lower 8 bits regardless
5813 // of endianess. Also provide endian-independent offset to that 16-bit word.
5814 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5815 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5817 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5818 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5820 static const int kInstanceTypeAndBitFieldOffset =
5821 kInstanceAttributesOffset + 0;
5822 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5823 static const int kUnusedPropertyFieldsByte = 3;
5824 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5826 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5827 Internals::kMapInstanceTypeAndBitFieldOffset);
5829 // Bit positions for bit field.
5830 static const int kHasNonInstancePrototype = 0;
5831 static const int kIsCallable = 1;
5832 static const int kHasNamedInterceptor = 2;
5833 static const int kHasIndexedInterceptor = 3;
5834 static const int kIsUndetectable = 4;
5835 static const int kIsObserved = 5;
5836 static const int kIsAccessCheckNeeded = 6;
5837 static const int kIsConstructor = 7;
5839 // Bit positions for bit field 2
5840 static const int kIsExtensible = 0;
5842 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5843 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5845 // Derived values from bit field 2
5846 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5847 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5848 static const int8_t kMaximumBitField2FastSmiElementValue =
5849 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5850 Map::ElementsKindBits::kShift) - 1;
5851 static const int8_t kMaximumBitField2FastHoleyElementValue =
5852 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5853 Map::ElementsKindBits::kShift) - 1;
5854 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5855 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5856 Map::ElementsKindBits::kShift) - 1;
5858 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5859 kPointerFieldsEndOffset,
5860 kSize> BodyDescriptor;
5862 // Compares this map to another to see if they describe equivalent objects.
5863 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5864 // it had exactly zero inobject properties.
5865 // The "shared" flags of both this map and |other| are ignored.
5866 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5868 // Returns true if given field is unboxed double.
5869 inline bool IsUnboxedDoubleField(FieldIndex index);
5872 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5873 static void TraceAllTransitions(Map* map);
5876 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5877 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5878 Handle<LayoutDescriptor> layout_descriptor);
5881 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5882 Handle<Name> name, SimpleTransitionFlag flag);
5884 bool EquivalentToForTransition(Map* other);
5885 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5886 static Handle<Map> ShareDescriptor(Handle<Map> map,
5887 Handle<DescriptorArray> descriptors,
5888 Descriptor* descriptor);
5889 static Handle<Map> CopyInstallDescriptors(
5890 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5891 Handle<LayoutDescriptor> layout_descriptor);
5892 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5893 Descriptor* descriptor,
5894 TransitionFlag flag);
5895 static Handle<Map> CopyReplaceDescriptors(
5896 Handle<Map> map, Handle<DescriptorArray> descriptors,
5897 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5898 MaybeHandle<Name> maybe_name, const char* reason,
5899 SimpleTransitionFlag simple_flag);
5901 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5902 Handle<DescriptorArray> descriptors,
5903 Descriptor* descriptor,
5905 TransitionFlag flag);
5906 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5907 Handle<Map> map, int descriptor, PropertyKind kind,
5908 PropertyAttributes attributes, const char** reason);
5910 static Handle<Map> CopyNormalized(Handle<Map> map,
5911 PropertyNormalizationMode mode);
5913 // Fires when the layout of an object with a leaf map changes.
5914 // This includes adding transitions to the leaf map or changing
5915 // the descriptor array.
5916 inline void NotifyLeafMapLayoutChange();
5918 void DeprecateTransitionTree();
5919 bool DeprecateTarget(PropertyKind kind, Name* key,
5920 PropertyAttributes attributes,
5921 DescriptorArray* new_descriptors,
5922 LayoutDescriptor* new_layout_descriptor);
5924 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5926 // Update field type of the given descriptor to new representation and new
5927 // type. The type must be prepared for storing in descriptor array:
5928 // it must be either a simple type or a map wrapped in a weak cell.
5929 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5930 Representation new_representation,
5931 Handle<Object> new_wrapped_type);
5933 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5934 PropertyAttributes attributes);
5935 void PrintGeneralization(FILE* file,
5940 bool constant_to_field,
5941 Representation old_representation,
5942 Representation new_representation,
5943 HeapType* old_field_type,
5944 HeapType* new_field_type);
5946 static const int kFastPropertiesSoftLimit = 12;
5947 static const int kMaxFastProperties = 128;
5949 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5953 // An abstract superclass, a marker class really, for simple structure classes.
5954 // It doesn't carry much functionality but allows struct classes to be
5955 // identified in the type system.
5956 class Struct: public HeapObject {
5958 inline void InitializeBody(int object_size);
5959 DECLARE_CAST(Struct)
5963 // A simple one-element struct, useful where smis need to be boxed.
5964 class Box : public Struct {
5966 // [value]: the boxed contents.
5967 DECL_ACCESSORS(value, Object)
5971 // Dispatched behavior.
5972 DECLARE_PRINTER(Box)
5973 DECLARE_VERIFIER(Box)
5975 static const int kValueOffset = HeapObject::kHeaderSize;
5976 static const int kSize = kValueOffset + kPointerSize;
5979 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5983 // Container for metadata stored on each prototype map.
5984 class PrototypeInfo : public Struct {
5986 static const int UNREGISTERED = -1;
5988 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5989 // or Smi(0) if uninitialized.
5990 DECL_ACCESSORS(prototype_users, Object)
5991 // [registry_slot]: Slot in prototype's user registry where this user
5992 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5993 inline int registry_slot() const;
5994 inline void set_registry_slot(int slot);
5995 // [validity_cell]: Cell containing the validity bit for prototype chains
5996 // going through this object, or Smi(0) if uninitialized.
5997 // When a prototype object changes its map, then both its own validity cell
5998 // and those of all "downstream" prototypes are invalidated; handlers for a
5999 // given receiver embed the currently valid cell for that receiver's prototype
6000 // during their compilation and check it on execution.
6001 DECL_ACCESSORS(validity_cell, Object)
6002 // [constructor_name]: User-friendly name of the original constructor.
6003 DECL_ACCESSORS(constructor_name, Object)
6005 DECLARE_CAST(PrototypeInfo)
6007 // Dispatched behavior.
6008 DECLARE_PRINTER(PrototypeInfo)
6009 DECLARE_VERIFIER(PrototypeInfo)
6011 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6012 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
6013 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
6014 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6015 static const int kSize = kConstructorNameOffset + kPointerSize;
6018 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6022 // Pair used to store both a ScopeInfo and an extension object in the extension
6023 // slot of a block context. Needed in the rare case where a declaration block
6024 // scope (a "varblock" as used to desugar parameter destructuring) also contains
6025 // a sloppy direct eval. (In no other case both are needed at the same time.)
6026 class SloppyBlockWithEvalContextExtension : public Struct {
6028 // [scope_info]: Scope info.
6029 DECL_ACCESSORS(scope_info, ScopeInfo)
6030 // [extension]: Extension object.
6031 DECL_ACCESSORS(extension, JSObject)
6033 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
6035 // Dispatched behavior.
6036 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
6037 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
6039 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
6040 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
6041 static const int kSize = kExtensionOffset + kPointerSize;
6044 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
6048 // Script describes a script which has been added to the VM.
6049 class Script: public Struct {
6058 // Script compilation types.
6059 enum CompilationType {
6060 COMPILATION_TYPE_HOST = 0,
6061 COMPILATION_TYPE_EVAL = 1
6064 // Script compilation state.
6065 enum CompilationState {
6066 COMPILATION_STATE_INITIAL = 0,
6067 COMPILATION_STATE_COMPILED = 1
6070 // [source]: the script source.
6071 DECL_ACCESSORS(source, Object)
6073 // [name]: the script name.
6074 DECL_ACCESSORS(name, Object)
6076 // [id]: the script id.
6077 DECL_INT_ACCESSORS(id)
6079 // [line_offset]: script line offset in resource from where it was extracted.
6080 DECL_INT_ACCESSORS(line_offset)
6082 // [column_offset]: script column offset in resource from where it was
6084 DECL_INT_ACCESSORS(column_offset)
6086 // [context_data]: context data for the context this script was compiled in.
6087 DECL_ACCESSORS(context_data, Object)
6089 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6090 DECL_ACCESSORS(wrapper, HeapObject)
6092 // [type]: the script type.
6093 DECL_INT_ACCESSORS(type)
6095 // [line_ends]: FixedArray of line ends positions.
6096 DECL_ACCESSORS(line_ends, Object)
6098 // [eval_from_shared]: for eval scripts the shared funcion info for the
6099 // function from which eval was called.
6100 DECL_ACCESSORS(eval_from_shared, Object)
6102 // [eval_from_instructions_offset]: the instruction offset in the code for the
6103 // function from which eval was called where eval was called.
6104 DECL_INT_ACCESSORS(eval_from_instructions_offset)
6106 // [shared_function_infos]: weak fixed array containing all shared
6107 // function infos created from this script.
6108 DECL_ACCESSORS(shared_function_infos, Object)
6110 // [flags]: Holds an exciting bitfield.
6111 DECL_INT_ACCESSORS(flags)
6113 // [source_url]: sourceURL from magic comment
6114 DECL_ACCESSORS(source_url, Object)
6116 // [source_url]: sourceMappingURL magic comment
6117 DECL_ACCESSORS(source_mapping_url, Object)
6119 // [compilation_type]: how the the script was compiled. Encoded in the
6121 inline CompilationType compilation_type();
6122 inline void set_compilation_type(CompilationType type);
6124 // [compilation_state]: determines whether the script has already been
6125 // compiled. Encoded in the 'flags' field.
6126 inline CompilationState compilation_state();
6127 inline void set_compilation_state(CompilationState state);
6129 // [hide_source]: determines whether the script source can be exposed as
6130 // function source. Encoded in the 'flags' field.
6131 inline bool hide_source();
6132 inline void set_hide_source(bool value);
6134 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6135 // and used by the embedder to make decisions about the script. V8 just passes
6136 // this through. Encoded in the 'flags' field.
6137 inline v8::ScriptOriginOptions origin_options();
6138 inline void set_origin_options(ScriptOriginOptions origin_options);
6140 DECLARE_CAST(Script)
6142 // If script source is an external string, check that the underlying
6143 // resource is accessible. Otherwise, always return true.
6144 inline bool HasValidSource();
6146 // Convert code position into column number.
6147 static int GetColumnNumber(Handle<Script> script, int code_pos);
6149 // Convert code position into (zero-based) line number.
6150 // The non-handlified version does not allocate, but may be much slower.
6151 static int GetLineNumber(Handle<Script> script, int code_pos);
6152 int GetLineNumber(int code_pos);
6154 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6156 // Init line_ends array with code positions of line ends inside script source.
6157 static void InitLineEnds(Handle<Script> script);
6159 // Get the JS object wrapping the given script; create it if none exists.
6160 static Handle<JSObject> GetWrapper(Handle<Script> script);
6162 // Look through the list of existing shared function infos to find one
6163 // that matches the function literal. Return empty handle if not found.
6164 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6166 // Iterate over all script objects on the heap.
6169 explicit Iterator(Isolate* isolate);
6173 WeakFixedArray::Iterator iterator_;
6174 DISALLOW_COPY_AND_ASSIGN(Iterator);
6177 // Dispatched behavior.
6178 DECLARE_PRINTER(Script)
6179 DECLARE_VERIFIER(Script)
6181 static const int kSourceOffset = HeapObject::kHeaderSize;
6182 static const int kNameOffset = kSourceOffset + kPointerSize;
6183 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6184 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6185 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6186 static const int kWrapperOffset = kContextOffset + kPointerSize;
6187 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6188 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6189 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6190 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6191 static const int kEvalFrominstructionsOffsetOffset =
6192 kEvalFromSharedOffset + kPointerSize;
6193 static const int kSharedFunctionInfosOffset =
6194 kEvalFrominstructionsOffsetOffset + kPointerSize;
6195 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6196 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6197 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6198 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6201 int GetLineNumberWithArray(int code_pos);
6203 // Bit positions in the flags field.
6204 static const int kCompilationTypeBit = 0;
6205 static const int kCompilationStateBit = 1;
6206 static const int kHideSourceBit = 2;
6207 static const int kOriginOptionsShift = 3;
6208 static const int kOriginOptionsSize = 3;
6209 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6210 << kOriginOptionsShift;
6212 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6216 // List of builtin functions we want to identify to improve code
6219 // Each entry has a name of a global object property holding an object
6220 // optionally followed by ".prototype", a name of a builtin function
6221 // on the object (the one the id is set for), and a label.
6223 // Installation of ids for the selected builtin functions is handled
6224 // by the bootstrapper.
6225 #define FUNCTIONS_WITH_ID_LIST(V) \
6226 V(Array.prototype, indexOf, ArrayIndexOf) \
6227 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6228 V(Array.prototype, push, ArrayPush) \
6229 V(Array.prototype, pop, ArrayPop) \
6230 V(Array.prototype, shift, ArrayShift) \
6231 V(Function.prototype, apply, FunctionApply) \
6232 V(Function.prototype, call, FunctionCall) \
6233 V(String.prototype, charCodeAt, StringCharCodeAt) \
6234 V(String.prototype, charAt, StringCharAt) \
6235 V(String, fromCharCode, StringFromCharCode) \
6236 V(Math, random, MathRandom) \
6237 V(Math, floor, MathFloor) \
6238 V(Math, round, MathRound) \
6239 V(Math, ceil, MathCeil) \
6240 V(Math, abs, MathAbs) \
6241 V(Math, log, MathLog) \
6242 V(Math, exp, MathExp) \
6243 V(Math, sqrt, MathSqrt) \
6244 V(Math, pow, MathPow) \
6245 V(Math, max, MathMax) \
6246 V(Math, min, MathMin) \
6247 V(Math, cos, MathCos) \
6248 V(Math, sin, MathSin) \
6249 V(Math, tan, MathTan) \
6250 V(Math, acos, MathAcos) \
6251 V(Math, asin, MathAsin) \
6252 V(Math, atan, MathAtan) \
6253 V(Math, atan2, MathAtan2) \
6254 V(Math, imul, MathImul) \
6255 V(Math, clz32, MathClz32) \
6256 V(Math, fround, MathFround)
6258 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6259 V(Atomics, load, AtomicsLoad) \
6260 V(Atomics, store, AtomicsStore)
6262 enum BuiltinFunctionId {
6264 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6266 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6267 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6268 #undef DECLARE_FUNCTION_ID
6269 // Fake id for a special case of Math.pow. Note, it continues the
6270 // list of math functions.
6275 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6276 // that both {code} and {literals} can be NULL to pass search result status.
6277 struct CodeAndLiterals {
6278 Code* code; // Cached optimized code.
6279 FixedArray* literals; // Cached literals array.
6283 // SharedFunctionInfo describes the JSFunction information that can be
6284 // shared by multiple instances of the function.
6285 class SharedFunctionInfo: public HeapObject {
6287 // [name]: Function name.
6288 DECL_ACCESSORS(name, Object)
6290 // [code]: Function code.
6291 DECL_ACCESSORS(code, Code)
6292 inline void ReplaceCode(Code* code);
6294 // [optimized_code_map]: Map from native context to optimized code
6295 // and a shared literals array or Smi(0) if none.
6296 DECL_ACCESSORS(optimized_code_map, Object)
6298 // Returns entry from optimized code map for specified context and OSR entry.
6299 // Note that {code == nullptr, literals == nullptr} indicates no matching
6300 // entry has been found, whereas {code, literals == nullptr} indicates that
6301 // code is context-independent.
6302 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6303 BailoutId osr_ast_id);
6305 // Clear optimized code map.
6306 void ClearOptimizedCodeMap();
6308 // Removes a specific optimized code object from the optimized code map.
6309 // In case of non-OSR the code reference is cleared from the cache entry but
6310 // the entry itself is left in the map in order to proceed sharing literals.
6311 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6313 // Trims the optimized code map after entries have been removed.
6314 void TrimOptimizedCodeMap(int shrink_by);
6316 // Add a new entry to the optimized code map for context-independent code.
6317 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6320 // Add a new entry to the optimized code map for context-dependent code.
6321 // |code| is either a code object or an undefined value. In the latter case
6322 // the entry just maps |native_context, osr_ast_id| pair to |literals| array.
6323 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6324 Handle<Context> native_context,
6325 Handle<HeapObject> code,
6326 Handle<FixedArray> literals,
6327 BailoutId osr_ast_id);
6329 // Set up the link between shared function info and the script. The shared
6330 // function info is added to the list on the script.
6331 static void SetScript(Handle<SharedFunctionInfo> shared,
6332 Handle<Object> script_object);
6334 // Layout description of the optimized code map.
6335 static const int kNextMapIndex = 0;
6336 static const int kSharedCodeIndex = 1;
6337 static const int kEntriesStart = 2;
6338 static const int kContextOffset = 0;
6339 static const int kCachedCodeOffset = 1;
6340 static const int kLiteralsOffset = 2;
6341 static const int kOsrAstIdOffset = 3;
6342 static const int kEntryLength = 4;
6343 static const int kInitialLength = kEntriesStart + kEntryLength;
6345 static const int kNotFound = -1;
6347 // [scope_info]: Scope info.
6348 DECL_ACCESSORS(scope_info, ScopeInfo)
6350 // [construct stub]: Code stub for constructing instances of this function.
6351 DECL_ACCESSORS(construct_stub, Code)
6353 // Returns if this function has been compiled to native code yet.
6354 inline bool is_compiled();
6356 // [length]: The function length - usually the number of declared parameters.
6357 // Use up to 2^30 parameters.
6358 inline int length() const;
6359 inline void set_length(int value);
6361 // [internal formal parameter count]: The declared number of parameters.
6362 // For subclass constructors, also includes new.target.
6363 // The size of function's frame is internal_formal_parameter_count + 1.
6364 inline int internal_formal_parameter_count() const;
6365 inline void set_internal_formal_parameter_count(int value);
6367 // Set the formal parameter count so the function code will be
6368 // called without using argument adaptor frames.
6369 inline void DontAdaptArguments();
6371 // [expected_nof_properties]: Expected number of properties for the function.
6372 inline int expected_nof_properties() const;
6373 inline void set_expected_nof_properties(int value);
6375 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6376 // (increasingly) from crankshafted code where sufficient feedback isn't
6378 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6380 // Unconditionally clear the type feedback vector (including vector ICs).
6381 void ClearTypeFeedbackInfo();
6383 // Clear the type feedback vector with a more subtle policy at GC time.
6384 void ClearTypeFeedbackInfoAtGCTime();
6387 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6388 // even if the GC moves this SharedFunctionInfo.
6389 inline int unique_id() const;
6390 inline void set_unique_id(int value);
6393 // [instance class name]: class name for instances.
6394 DECL_ACCESSORS(instance_class_name, Object)
6396 // [function data]: This field holds some additional data for function.
6397 // Currently it has one of:
6398 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6399 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6400 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6401 // In the long run we don't want all functions to have this field but
6402 // we can fix that when we have a better model for storing hidden data
6404 DECL_ACCESSORS(function_data, Object)
6406 inline bool IsApiFunction();
6407 inline FunctionTemplateInfo* get_api_func_data();
6408 inline bool HasBuiltinFunctionId();
6409 inline BuiltinFunctionId builtin_function_id();
6410 inline bool HasBytecodeArray();
6411 inline BytecodeArray* bytecode_array();
6413 // [script info]: Script from which the function originates.
6414 DECL_ACCESSORS(script, Object)
6416 // [num_literals]: Number of literals used by this function.
6417 inline int num_literals() const;
6418 inline void set_num_literals(int value);
6420 // [start_position_and_type]: Field used to store both the source code
6421 // position, whether or not the function is a function expression,
6422 // and whether or not the function is a toplevel function. The two
6423 // least significants bit indicates whether the function is an
6424 // expression and the rest contains the source code position.
6425 inline int start_position_and_type() const;
6426 inline void set_start_position_and_type(int value);
6428 // The function is subject to debugging if a debug info is attached.
6429 inline bool HasDebugInfo();
6430 inline DebugInfo* GetDebugInfo();
6432 // A function has debug code if the compiled code has debug break slots.
6433 inline bool HasDebugCode();
6435 // [debug info]: Debug information.
6436 DECL_ACCESSORS(debug_info, Object)
6438 // [inferred name]: Name inferred from variable or property
6439 // assignment of this function. Used to facilitate debugging and
6440 // profiling of JavaScript code written in OO style, where almost
6441 // all functions are anonymous but are assigned to object
6443 DECL_ACCESSORS(inferred_name, String)
6445 // The function's name if it is non-empty, otherwise the inferred name.
6446 String* DebugName();
6448 // Position of the 'function' token in the script source.
6449 inline int function_token_position() const;
6450 inline void set_function_token_position(int function_token_position);
6452 // Position of this function in the script source.
6453 inline int start_position() const;
6454 inline void set_start_position(int start_position);
6456 // End position of this function in the script source.
6457 inline int end_position() const;
6458 inline void set_end_position(int end_position);
6460 // Is this function a function expression in the source code.
6461 DECL_BOOLEAN_ACCESSORS(is_expression)
6463 // Is this function a top-level function (scripts, evals).
6464 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6466 // Bit field containing various information collected by the compiler to
6467 // drive optimization.
6468 inline int compiler_hints() const;
6469 inline void set_compiler_hints(int value);
6471 inline int ast_node_count() const;
6472 inline void set_ast_node_count(int count);
6474 inline int profiler_ticks() const;
6475 inline void set_profiler_ticks(int ticks);
6477 // Inline cache age is used to infer whether the function survived a context
6478 // disposal or not. In the former case we reset the opt_count.
6479 inline int ic_age();
6480 inline void set_ic_age(int age);
6482 // Indicates if this function can be lazy compiled.
6483 // This is used to determine if we can safely flush code from a function
6484 // when doing GC if we expect that the function will no longer be used.
6485 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6487 // Indicates if this function can be lazy compiled without a context.
6488 // This is used to determine if we can force compilation without reaching
6489 // the function through program execution but through other means (e.g. heap
6490 // iteration by the debugger).
6491 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6493 // Indicates whether optimizations have been disabled for this
6494 // shared function info. If a function is repeatedly optimized or if
6495 // we cannot optimize the function we disable optimization to avoid
6496 // spending time attempting to optimize it again.
6497 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6499 // Indicates the language mode.
6500 inline LanguageMode language_mode();
6501 inline void set_language_mode(LanguageMode language_mode);
6503 // False if the function definitely does not allocate an arguments object.
6504 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6506 // Indicates that this function uses a super property (or an eval that may
6507 // use a super property).
6508 // This is needed to set up the [[HomeObject]] on the function instance.
6509 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6511 // True if the function has any duplicated parameter names.
6512 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6514 // Indicates whether the function is a native function.
6515 // These needs special treatment in .call and .apply since
6516 // null passed as the receiver should not be translated to the
6518 DECL_BOOLEAN_ACCESSORS(native)
6520 // Indicate that this function should always be inlined in optimized code.
6521 DECL_BOOLEAN_ACCESSORS(force_inline)
6523 // Indicates that the function was created by the Function function.
6524 // Though it's anonymous, toString should treat it as if it had the name
6525 // "anonymous". We don't set the name itself so that the system does not
6526 // see a binding for it.
6527 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6529 // Indicates whether the function is a bound function created using
6530 // the bind function.
6531 DECL_BOOLEAN_ACCESSORS(bound)
6533 // Indicates that the function is anonymous (the name field can be set
6534 // through the API, which does not change this flag).
6535 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6537 // Is this a function or top-level/eval code.
6538 DECL_BOOLEAN_ACCESSORS(is_function)
6540 // Indicates that code for this function cannot be compiled with Crankshaft.
6541 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6543 // Indicates that code for this function cannot be flushed.
6544 DECL_BOOLEAN_ACCESSORS(dont_flush)
6546 // Indicates that this function is a generator.
6547 DECL_BOOLEAN_ACCESSORS(is_generator)
6549 // Indicates that this function is an arrow function.
6550 DECL_BOOLEAN_ACCESSORS(is_arrow)
6552 // Indicates that this function is a concise method.
6553 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6555 // Indicates that this function is an accessor (getter or setter).
6556 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6558 // Indicates that this function is a default constructor.
6559 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6561 // Indicates that this function is an asm function.
6562 DECL_BOOLEAN_ACCESSORS(asm_function)
6564 // Indicates that the the shared function info is deserialized from cache.
6565 DECL_BOOLEAN_ACCESSORS(deserialized)
6567 // Indicates that the the shared function info has never been compiled before.
6568 DECL_BOOLEAN_ACCESSORS(never_compiled)
6570 inline FunctionKind kind();
6571 inline void set_kind(FunctionKind kind);
6573 // Indicates whether or not the code in the shared function support
6575 inline bool has_deoptimization_support();
6577 // Enable deoptimization support through recompiled code.
6578 void EnableDeoptimizationSupport(Code* recompiled);
6580 // Disable (further) attempted optimization of all functions sharing this
6581 // shared function info.
6582 void DisableOptimization(BailoutReason reason);
6584 inline BailoutReason disable_optimization_reason();
6586 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6587 // code, returns whether it asserted (i.e., always true if assertions are
6589 bool VerifyBailoutId(BailoutId id);
6591 // [source code]: Source code for the function.
6592 bool HasSourceCode() const;
6593 Handle<Object> GetSourceCode();
6595 // Number of times the function was optimized.
6596 inline int opt_count();
6597 inline void set_opt_count(int opt_count);
6599 // Number of times the function was deoptimized.
6600 inline void set_deopt_count(int value);
6601 inline int deopt_count();
6602 inline void increment_deopt_count();
6604 // Number of time we tried to re-enable optimization after it
6605 // was disabled due to high number of deoptimizations.
6606 inline void set_opt_reenable_tries(int value);
6607 inline int opt_reenable_tries();
6609 inline void TryReenableOptimization();
6611 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6612 inline void set_counters(int value);
6613 inline int counters() const;
6615 // Stores opt_count and bailout_reason as bit-fields.
6616 inline void set_opt_count_and_bailout_reason(int value);
6617 inline int opt_count_and_bailout_reason() const;
6619 inline void set_disable_optimization_reason(BailoutReason reason);
6621 // Tells whether this function should be subject to debugging.
6622 inline bool IsSubjectToDebugging();
6624 // Whether this function is defined in native code or extensions.
6625 inline bool IsBuiltin();
6627 // Check whether or not this function is inlineable.
6628 bool IsInlineable();
6630 // Source size of this function.
6633 // Calculate the instance size.
6634 int CalculateInstanceSize();
6636 // Calculate the number of in-object properties.
6637 int CalculateInObjectProperties();
6639 inline bool has_simple_parameters();
6641 // Initialize a SharedFunctionInfo from a parsed function literal.
6642 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6643 FunctionLiteral* lit);
6645 // Dispatched behavior.
6646 DECLARE_PRINTER(SharedFunctionInfo)
6647 DECLARE_VERIFIER(SharedFunctionInfo)
6649 void ResetForNewContext(int new_ic_age);
6651 // Iterate over all shared function infos that are created from a script.
6652 // That excludes shared function infos created for API functions and C++
6656 explicit Iterator(Isolate* isolate);
6657 SharedFunctionInfo* Next();
6662 Script::Iterator script_iterator_;
6663 WeakFixedArray::Iterator sfi_iterator_;
6664 DisallowHeapAllocation no_gc_;
6665 DISALLOW_COPY_AND_ASSIGN(Iterator);
6668 DECLARE_CAST(SharedFunctionInfo)
6671 static const int kDontAdaptArgumentsSentinel = -1;
6673 // Layout description.
6675 static const int kNameOffset = HeapObject::kHeaderSize;
6676 static const int kCodeOffset = kNameOffset + kPointerSize;
6677 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6678 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6679 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6680 static const int kInstanceClassNameOffset =
6681 kConstructStubOffset + kPointerSize;
6682 static const int kFunctionDataOffset =
6683 kInstanceClassNameOffset + kPointerSize;
6684 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6685 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6686 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6687 static const int kFeedbackVectorOffset =
6688 kInferredNameOffset + kPointerSize;
6690 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6691 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6693 // Just to not break the postmortrem support with conditional offsets
6694 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6695 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6698 #if V8_HOST_ARCH_32_BIT
6700 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6701 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6702 static const int kExpectedNofPropertiesOffset =
6703 kFormalParameterCountOffset + kPointerSize;
6704 static const int kNumLiteralsOffset =
6705 kExpectedNofPropertiesOffset + kPointerSize;
6706 static const int kStartPositionAndTypeOffset =
6707 kNumLiteralsOffset + kPointerSize;
6708 static const int kEndPositionOffset =
6709 kStartPositionAndTypeOffset + kPointerSize;
6710 static const int kFunctionTokenPositionOffset =
6711 kEndPositionOffset + kPointerSize;
6712 static const int kCompilerHintsOffset =
6713 kFunctionTokenPositionOffset + kPointerSize;
6714 static const int kOptCountAndBailoutReasonOffset =
6715 kCompilerHintsOffset + kPointerSize;
6716 static const int kCountersOffset =
6717 kOptCountAndBailoutReasonOffset + kPointerSize;
6718 static const int kAstNodeCountOffset =
6719 kCountersOffset + kPointerSize;
6720 static const int kProfilerTicksOffset =
6721 kAstNodeCountOffset + kPointerSize;
6724 static const int kSize = kProfilerTicksOffset + kPointerSize;
6726 // The only reason to use smi fields instead of int fields
6727 // is to allow iteration without maps decoding during
6728 // garbage collections.
6729 // To avoid wasting space on 64-bit architectures we use
6730 // the following trick: we group integer fields into pairs
6731 // The least significant integer in each pair is shifted left by 1.
6732 // By doing this we guarantee that LSB of each kPointerSize aligned
6733 // word is not set and thus this word cannot be treated as pointer
6734 // to HeapObject during old space traversal.
6735 #if V8_TARGET_LITTLE_ENDIAN
6736 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6737 static const int kFormalParameterCountOffset =
6738 kLengthOffset + kIntSize;
6740 static const int kExpectedNofPropertiesOffset =
6741 kFormalParameterCountOffset + kIntSize;
6742 static const int kNumLiteralsOffset =
6743 kExpectedNofPropertiesOffset + kIntSize;
6745 static const int kEndPositionOffset =
6746 kNumLiteralsOffset + kIntSize;
6747 static const int kStartPositionAndTypeOffset =
6748 kEndPositionOffset + kIntSize;
6750 static const int kFunctionTokenPositionOffset =
6751 kStartPositionAndTypeOffset + kIntSize;
6752 static const int kCompilerHintsOffset =
6753 kFunctionTokenPositionOffset + kIntSize;
6755 static const int kOptCountAndBailoutReasonOffset =
6756 kCompilerHintsOffset + kIntSize;
6757 static const int kCountersOffset =
6758 kOptCountAndBailoutReasonOffset + kIntSize;
6760 static const int kAstNodeCountOffset =
6761 kCountersOffset + kIntSize;
6762 static const int kProfilerTicksOffset =
6763 kAstNodeCountOffset + kIntSize;
6766 static const int kSize = kProfilerTicksOffset + kIntSize;
6768 #elif V8_TARGET_BIG_ENDIAN
6769 static const int kFormalParameterCountOffset =
6770 kLastPointerFieldOffset + kPointerSize;
6771 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6773 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6774 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6776 static const int kStartPositionAndTypeOffset =
6777 kExpectedNofPropertiesOffset + kIntSize;
6778 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6780 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6781 static const int kFunctionTokenPositionOffset =
6782 kCompilerHintsOffset + kIntSize;
6784 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6785 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6787 static const int kProfilerTicksOffset =
6788 kOptCountAndBailoutReasonOffset + kIntSize;
6789 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6792 static const int kSize = kAstNodeCountOffset + kIntSize;
6795 #error Unknown byte ordering
6796 #endif // Big endian
6800 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6802 typedef FixedBodyDescriptor<kNameOffset,
6803 kLastPointerFieldOffset + kPointerSize,
6804 kSize> BodyDescriptor;
6806 // Bit positions in start_position_and_type.
6807 // The source code start position is in the 30 most significant bits of
6808 // the start_position_and_type field.
6809 static const int kIsExpressionBit = 0;
6810 static const int kIsTopLevelBit = 1;
6811 static const int kStartPositionShift = 2;
6812 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6814 // Bit positions in compiler_hints.
6815 enum CompilerHints {
6816 kAllowLazyCompilation,
6817 kAllowLazyCompilationWithoutContext,
6818 kOptimizationDisabled,
6820 kStrictModeFunction,
6821 kStrongModeFunction,
6824 kHasDuplicateParameters,
6828 kNameShouldPrintAsAnonymous,
6835 kIsAccessorFunction,
6836 kIsDefaultConstructor,
6837 kIsSubclassConstructor,
6843 kCompilerHintsCount // Pseudo entry
6845 // Add hints for other modes when they're added.
6846 STATIC_ASSERT(LANGUAGE_END == 3);
6848 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6850 class DeoptCountBits : public BitField<int, 0, 4> {};
6851 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6852 class ICAgeBits : public BitField<int, 22, 8> {};
6854 class OptCountBits : public BitField<int, 0, 22> {};
6855 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6858 #if V8_HOST_ARCH_32_BIT
6859 // On 32 bit platforms, compiler hints is a smi.
6860 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6861 static const int kCompilerHintsSize = kPointerSize;
6863 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6864 static const int kCompilerHintsSmiTagSize = 0;
6865 static const int kCompilerHintsSize = kIntSize;
6868 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6869 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6872 // Constants for optimizing codegen for strict mode function and
6874 // Allows to use byte-width instructions.
6875 static const int kStrictModeBitWithinByte =
6876 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6877 static const int kStrongModeBitWithinByte =
6878 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6880 static const int kNativeBitWithinByte =
6881 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6883 static const int kBoundBitWithinByte =
6884 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6886 #if defined(V8_TARGET_LITTLE_ENDIAN)
6887 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6888 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6889 static const int kStrongModeByteOffset =
6890 kCompilerHintsOffset +
6891 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6892 static const int kNativeByteOffset = kCompilerHintsOffset +
6893 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6894 static const int kBoundByteOffset =
6895 kCompilerHintsOffset +
6896 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6897 #elif defined(V8_TARGET_BIG_ENDIAN)
6898 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6899 (kCompilerHintsSize - 1) -
6900 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6901 static const int kStrongModeByteOffset =
6902 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6903 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6904 static const int kNativeByteOffset = kCompilerHintsOffset +
6905 (kCompilerHintsSize - 1) -
6906 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6907 static const int kBoundByteOffset =
6908 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6909 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6911 #error Unknown byte ordering
6915 // Returns entry from optimized code map for specified context and OSR entry.
6916 // The result is either kNotFound, kSharedCodeIndex for context-independent
6917 // entry or a start index of the context-dependent entry.
6918 int SearchOptimizedCodeMapEntry(Context* native_context,
6919 BailoutId osr_ast_id);
6921 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6925 // Printing support.
6926 struct SourceCodeOf {
6927 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6928 : value(v), max_length(max) {}
6929 const SharedFunctionInfo* value;
6934 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6937 class JSGeneratorObject: public JSObject {
6939 // [function]: The function corresponding to this generator object.
6940 DECL_ACCESSORS(function, JSFunction)
6942 // [context]: The context of the suspended computation.
6943 DECL_ACCESSORS(context, Context)
6945 // [receiver]: The receiver of the suspended computation.
6946 DECL_ACCESSORS(receiver, Object)
6948 // [continuation]: Offset into code of continuation.
6950 // A positive offset indicates a suspended generator. The special
6951 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6952 // cannot be resumed.
6953 inline int continuation() const;
6954 inline void set_continuation(int continuation);
6955 inline bool is_closed();
6956 inline bool is_executing();
6957 inline bool is_suspended();
6959 // [operand_stack]: Saved operand stack.
6960 DECL_ACCESSORS(operand_stack, FixedArray)
6962 DECLARE_CAST(JSGeneratorObject)
6964 // Dispatched behavior.
6965 DECLARE_PRINTER(JSGeneratorObject)
6966 DECLARE_VERIFIER(JSGeneratorObject)
6968 // Magic sentinel values for the continuation.
6969 static const int kGeneratorExecuting = -1;
6970 static const int kGeneratorClosed = 0;
6972 // Layout description.
6973 static const int kFunctionOffset = JSObject::kHeaderSize;
6974 static const int kContextOffset = kFunctionOffset + kPointerSize;
6975 static const int kReceiverOffset = kContextOffset + kPointerSize;
6976 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6977 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6978 static const int kSize = kOperandStackOffset + kPointerSize;
6980 // Resume mode, for use by runtime functions.
6981 enum ResumeMode { NEXT, THROW };
6984 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6988 // Representation for module instance objects.
6989 class JSModule: public JSObject {
6991 // [context]: the context holding the module's locals, or undefined if none.
6992 DECL_ACCESSORS(context, Object)
6994 // [scope_info]: Scope info.
6995 DECL_ACCESSORS(scope_info, ScopeInfo)
6997 DECLARE_CAST(JSModule)
6999 // Dispatched behavior.
7000 DECLARE_PRINTER(JSModule)
7001 DECLARE_VERIFIER(JSModule)
7003 // Layout description.
7004 static const int kContextOffset = JSObject::kHeaderSize;
7005 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7006 static const int kSize = kScopeInfoOffset + kPointerSize;
7009 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7013 // JSFunction describes JavaScript functions.
7014 class JSFunction: public JSObject {
7016 // [prototype_or_initial_map]:
7017 DECL_ACCESSORS(prototype_or_initial_map, Object)
7019 // [shared]: The information about the function that
7020 // can be shared by instances.
7021 DECL_ACCESSORS(shared, SharedFunctionInfo)
7023 // [context]: The context for this function.
7024 inline Context* context();
7025 inline void set_context(Object* context);
7026 inline JSObject* global_proxy();
7028 // [code]: The generated code object for this function. Executed
7029 // when the function is invoked, e.g. foo() or new foo(). See
7030 // [[Call]] and [[Construct]] description in ECMA-262, section
7032 inline Code* code();
7033 inline void set_code(Code* code);
7034 inline void set_code_no_write_barrier(Code* code);
7035 inline void ReplaceCode(Code* code);
7037 // Tells whether this function is builtin.
7038 inline bool IsBuiltin();
7040 // Tells whether this function inlines the given shared function info.
7041 bool Inlines(SharedFunctionInfo* candidate);
7043 // Tells whether this function should be subject to debugging.
7044 inline bool IsSubjectToDebugging();
7046 // Tells whether or not the function needs arguments adaption.
7047 inline bool NeedsArgumentsAdaption();
7049 // Tells whether or not this function has been optimized.
7050 inline bool IsOptimized();
7052 // Mark this function for lazy recompilation. The function will be
7053 // recompiled the next time it is executed.
7054 void MarkForOptimization();
7055 void AttemptConcurrentOptimization();
7057 // Tells whether or not the function is already marked for lazy
7059 inline bool IsMarkedForOptimization();
7060 inline bool IsMarkedForConcurrentOptimization();
7062 // Tells whether or not the function is on the concurrent recompilation queue.
7063 inline bool IsInOptimizationQueue();
7065 // Inobject slack tracking is the way to reclaim unused inobject space.
7067 // The instance size is initially determined by adding some slack to
7068 // expected_nof_properties (to allow for a few extra properties added
7069 // after the constructor). There is no guarantee that the extra space
7070 // will not be wasted.
7072 // Here is the algorithm to reclaim the unused inobject space:
7073 // - Detect the first constructor call for this JSFunction.
7074 // When it happens enter the "in progress" state: initialize construction
7075 // counter in the initial_map.
7076 // - While the tracking is in progress create objects filled with
7077 // one_pointer_filler_map instead of undefined_value. This way they can be
7078 // resized quickly and safely.
7079 // - Once enough objects have been created compute the 'slack'
7080 // (traverse the map transition tree starting from the
7081 // initial_map and find the lowest value of unused_property_fields).
7082 // - Traverse the transition tree again and decrease the instance size
7083 // of every map. Existing objects will resize automatically (they are
7084 // filled with one_pointer_filler_map). All further allocations will
7085 // use the adjusted instance size.
7086 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7087 // allocations made using different closures could actually create different
7088 // kind of objects (see prototype inheritance pattern).
7090 // Important: inobject slack tracking is not attempted during the snapshot
7093 // True if the initial_map is set and the object constructions countdown
7094 // counter is not zero.
7095 static const int kGenerousAllocationCount =
7096 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7097 inline bool IsInobjectSlackTrackingInProgress();
7099 // Starts the tracking.
7100 // Initializes object constructions countdown counter in the initial map.
7101 void StartInobjectSlackTracking();
7103 // Completes the tracking.
7104 void CompleteInobjectSlackTracking();
7106 // [literals_or_bindings]: Fixed array holding either
7107 // the materialized literals or the bindings of a bound function.
7109 // If the function contains object, regexp or array literals, the
7110 // literals array prefix contains the object, regexp, and array
7111 // function to be used when creating these literals. This is
7112 // necessary so that we do not dynamically lookup the object, regexp
7113 // or array functions. Performing a dynamic lookup, we might end up
7114 // using the functions from a new context that we should not have
7117 // On bound functions, the array is a (copy-on-write) fixed-array containing
7118 // the function that was bound, bound this-value and any bound
7119 // arguments. Bound functions never contain literals.
7120 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7122 inline FixedArray* literals();
7123 inline void set_literals(FixedArray* literals);
7125 inline FixedArray* function_bindings();
7126 inline void set_function_bindings(FixedArray* bindings);
7128 // The initial map for an object created by this constructor.
7129 inline Map* initial_map();
7130 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7131 Handle<Object> prototype);
7132 inline bool has_initial_map();
7133 static void EnsureHasInitialMap(Handle<JSFunction> function);
7135 // Get and set the prototype property on a JSFunction. If the
7136 // function has an initial map the prototype is set on the initial
7137 // map. Otherwise, the prototype is put in the initial map field
7138 // until an initial map is needed.
7139 inline bool has_prototype();
7140 inline bool has_instance_prototype();
7141 inline Object* prototype();
7142 inline Object* instance_prototype();
7143 static void SetPrototype(Handle<JSFunction> function,
7144 Handle<Object> value);
7145 static void SetInstancePrototype(Handle<JSFunction> function,
7146 Handle<Object> value);
7148 // After prototype is removed, it will not be created when accessed, and
7149 // [[Construct]] from this function will not be allowed.
7150 bool RemovePrototype();
7152 // Accessor for this function's initial map's [[class]]
7153 // property. This is primarily used by ECMA native functions. This
7154 // method sets the class_name field of this function's initial map
7155 // to a given value. It creates an initial map if this function does
7156 // not have one. Note that this method does not copy the initial map
7157 // if it has one already, but simply replaces it with the new value.
7158 // Instances created afterwards will have a map whose [[class]] is
7159 // set to 'value', but there is no guarantees on instances created
7161 void SetInstanceClassName(String* name);
7163 // Returns if this function has been compiled to native code yet.
7164 inline bool is_compiled();
7166 // Returns `false` if formal parameters include rest parameters, optional
7167 // parameters, or destructuring parameters.
7168 // TODO(caitp): make this a flag set during parsing
7169 inline bool has_simple_parameters();
7171 // [next_function_link]: Links functions into various lists, e.g. the list
7172 // of optimized functions hanging off the native_context. The CodeFlusher
7173 // uses this link to chain together flushing candidates. Treated weakly
7174 // by the garbage collector.
7175 DECL_ACCESSORS(next_function_link, Object)
7177 // Prints the name of the function using PrintF.
7178 void PrintName(FILE* out = stdout);
7180 DECLARE_CAST(JSFunction)
7182 // Iterates the objects, including code objects indirectly referenced
7183 // through pointers to the first instruction in the code object.
7184 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7186 // Dispatched behavior.
7187 DECLARE_PRINTER(JSFunction)
7188 DECLARE_VERIFIER(JSFunction)
7190 // Returns the number of allocated literals.
7191 inline int NumberOfLiterals();
7193 // Used for flags such as --hydrogen-filter.
7194 bool PassesFilter(const char* raw_filter);
7196 // The function's name if it is configured, otherwise shared function info
7198 static Handle<String> GetDebugName(Handle<JSFunction> function);
7200 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7201 // kSize) is weak and has special handling during garbage collection.
7202 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7203 static const int kPrototypeOrInitialMapOffset =
7204 kCodeEntryOffset + kPointerSize;
7205 static const int kSharedFunctionInfoOffset =
7206 kPrototypeOrInitialMapOffset + kPointerSize;
7207 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7208 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7209 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7210 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7211 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7213 // Layout of the bound-function binding array.
7214 static const int kBoundFunctionIndex = 0;
7215 static const int kBoundThisIndex = 1;
7216 static const int kBoundArgumentsStartIndex = 2;
7219 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7223 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7224 // and the prototype is hidden. JSGlobalProxy always delegates
7225 // property accesses to its prototype if the prototype is not null.
7227 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7229 // Accessing a JSGlobalProxy requires security check.
7231 class JSGlobalProxy : public JSObject {
7233 // [native_context]: the owner native context of this global proxy object.
7234 // It is null value if this object is not used by any context.
7235 DECL_ACCESSORS(native_context, Object)
7237 // [hash]: The hash code property (undefined if not initialized yet).
7238 DECL_ACCESSORS(hash, Object)
7240 DECLARE_CAST(JSGlobalProxy)
7242 inline bool IsDetachedFrom(GlobalObject* global) const;
7244 // Dispatched behavior.
7245 DECLARE_PRINTER(JSGlobalProxy)
7246 DECLARE_VERIFIER(JSGlobalProxy)
7248 // Layout description.
7249 static const int kNativeContextOffset = JSObject::kHeaderSize;
7250 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7251 static const int kSize = kHashOffset + kPointerSize;
7254 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7258 // Common super class for JavaScript global objects and the special
7259 // builtins global objects.
7260 class GlobalObject: public JSObject {
7262 // [builtins]: the object holding the runtime routines written in JS.
7263 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7265 // [native context]: the natives corresponding to this global object.
7266 DECL_ACCESSORS(native_context, Context)
7268 // [global proxy]: the global proxy object of the context
7269 DECL_ACCESSORS(global_proxy, JSObject)
7271 DECLARE_CAST(GlobalObject)
7273 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7275 // Ensure that the global object has a cell for the given property name.
7276 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7279 // Layout description.
7280 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7281 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7282 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7283 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7286 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7290 // JavaScript global object.
7291 class JSGlobalObject: public GlobalObject {
7293 DECLARE_CAST(JSGlobalObject)
7295 inline bool IsDetached();
7297 // Dispatched behavior.
7298 DECLARE_PRINTER(JSGlobalObject)
7299 DECLARE_VERIFIER(JSGlobalObject)
7301 // Layout description.
7302 static const int kSize = GlobalObject::kHeaderSize;
7305 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7309 // Builtins global object which holds the runtime routines written in
7311 class JSBuiltinsObject: public GlobalObject {
7313 DECLARE_CAST(JSBuiltinsObject)
7315 // Dispatched behavior.
7316 DECLARE_PRINTER(JSBuiltinsObject)
7317 DECLARE_VERIFIER(JSBuiltinsObject)
7319 // Layout description.
7320 static const int kSize = GlobalObject::kHeaderSize;
7323 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7327 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7328 class JSValue: public JSObject {
7330 // [value]: the object being wrapped.
7331 DECL_ACCESSORS(value, Object)
7333 DECLARE_CAST(JSValue)
7335 // Dispatched behavior.
7336 DECLARE_PRINTER(JSValue)
7337 DECLARE_VERIFIER(JSValue)
7339 // Layout description.
7340 static const int kValueOffset = JSObject::kHeaderSize;
7341 static const int kSize = kValueOffset + kPointerSize;
7344 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7350 // Representation for JS date objects.
7351 class JSDate: public JSObject {
7353 // If one component is NaN, all of them are, indicating a NaN time value.
7354 // [value]: the time value.
7355 DECL_ACCESSORS(value, Object)
7356 // [year]: caches year. Either undefined, smi, or NaN.
7357 DECL_ACCESSORS(year, Object)
7358 // [month]: caches month. Either undefined, smi, or NaN.
7359 DECL_ACCESSORS(month, Object)
7360 // [day]: caches day. Either undefined, smi, or NaN.
7361 DECL_ACCESSORS(day, Object)
7362 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7363 DECL_ACCESSORS(weekday, Object)
7364 // [hour]: caches hours. Either undefined, smi, or NaN.
7365 DECL_ACCESSORS(hour, Object)
7366 // [min]: caches minutes. Either undefined, smi, or NaN.
7367 DECL_ACCESSORS(min, Object)
7368 // [sec]: caches seconds. Either undefined, smi, or NaN.
7369 DECL_ACCESSORS(sec, Object)
7370 // [cache stamp]: sample of the date cache stamp at the
7371 // moment when chached fields were cached.
7372 DECL_ACCESSORS(cache_stamp, Object)
7374 DECLARE_CAST(JSDate)
7376 // Returns the date field with the specified index.
7377 // See FieldIndex for the list of date fields.
7378 static Object* GetField(Object* date, Smi* index);
7380 void SetValue(Object* value, bool is_value_nan);
7382 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7383 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7384 Handle<JSReceiver> receiver, Handle<Object> hint);
7386 // Dispatched behavior.
7387 DECLARE_PRINTER(JSDate)
7388 DECLARE_VERIFIER(JSDate)
7390 // The order is important. It must be kept in sync with date macros
7401 kFirstUncachedField,
7402 kMillisecond = kFirstUncachedField,
7406 kYearUTC = kFirstUTCField,
7419 // Layout description.
7420 static const int kValueOffset = JSObject::kHeaderSize;
7421 static const int kYearOffset = kValueOffset + kPointerSize;
7422 static const int kMonthOffset = kYearOffset + kPointerSize;
7423 static const int kDayOffset = kMonthOffset + kPointerSize;
7424 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7425 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7426 static const int kMinOffset = kHourOffset + kPointerSize;
7427 static const int kSecOffset = kMinOffset + kPointerSize;
7428 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7429 static const int kSize = kCacheStampOffset + kPointerSize;
7432 inline Object* DoGetField(FieldIndex index);
7434 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7436 // Computes and caches the cacheable fields of the date.
7437 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7440 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7444 // Representation of message objects used for error reporting through
7445 // the API. The messages are formatted in JavaScript so this object is
7446 // a real JavaScript object. The information used for formatting the
7447 // error messages are not directly accessible from JavaScript to
7448 // prevent leaking information to user code called during error
7450 class JSMessageObject: public JSObject {
7452 // [type]: the type of error message.
7453 inline int type() const;
7454 inline void set_type(int value);
7456 // [arguments]: the arguments for formatting the error message.
7457 DECL_ACCESSORS(argument, Object)
7459 // [script]: the script from which the error message originated.
7460 DECL_ACCESSORS(script, Object)
7462 // [stack_frames]: an array of stack frames for this error object.
7463 DECL_ACCESSORS(stack_frames, Object)
7465 // [start_position]: the start position in the script for the error message.
7466 inline int start_position() const;
7467 inline void set_start_position(int value);
7469 // [end_position]: the end position in the script for the error message.
7470 inline int end_position() const;
7471 inline void set_end_position(int value);
7473 DECLARE_CAST(JSMessageObject)
7475 // Dispatched behavior.
7476 DECLARE_PRINTER(JSMessageObject)
7477 DECLARE_VERIFIER(JSMessageObject)
7479 // Layout description.
7480 static const int kTypeOffset = JSObject::kHeaderSize;
7481 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7482 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7483 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7484 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7485 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7486 static const int kSize = kEndPositionOffset + kPointerSize;
7488 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7489 kStackFramesOffset + kPointerSize,
7490 kSize> BodyDescriptor;
7494 // Regular expressions
7495 // The regular expression holds a single reference to a FixedArray in
7496 // the kDataOffset field.
7497 // The FixedArray contains the following data:
7498 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7499 // - reference to the original source string
7500 // - reference to the original flag string
7501 // If it is an atom regexp
7502 // - a reference to a literal string to search for
7503 // If it is an irregexp regexp:
7504 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7505 // used for tracking the last usage (used for code flushing).
7506 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7507 // used for tracking the last usage (used for code flushing)..
7508 // - max number of registers used by irregexp implementations.
7509 // - number of capture registers (output values) of the regexp.
7510 class JSRegExp: public JSObject {
7513 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7514 // ATOM: A simple string to match against using an indexOf operation.
7515 // IRREGEXP: Compiled with Irregexp.
7516 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7517 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7524 UNICODE_ESCAPES = 16
7529 explicit Flags(uint32_t value) : value_(value) { }
7530 bool is_global() { return (value_ & GLOBAL) != 0; }
7531 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7532 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7533 bool is_sticky() { return (value_ & STICKY) != 0; }
7534 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7535 uint32_t value() { return value_; }
7540 DECL_ACCESSORS(data, Object)
7542 inline Type TypeTag();
7543 inline int CaptureCount();
7544 inline Flags GetFlags();
7545 inline String* Pattern();
7546 inline Object* DataAt(int index);
7547 // Set implementation data after the object has been prepared.
7548 inline void SetDataAt(int index, Object* value);
7550 static int code_index(bool is_latin1) {
7552 return kIrregexpLatin1CodeIndex;
7554 return kIrregexpUC16CodeIndex;
7558 static int saved_code_index(bool is_latin1) {
7560 return kIrregexpLatin1CodeSavedIndex;
7562 return kIrregexpUC16CodeSavedIndex;
7566 DECLARE_CAST(JSRegExp)
7568 // Dispatched behavior.
7569 DECLARE_VERIFIER(JSRegExp)
7571 static const int kDataOffset = JSObject::kHeaderSize;
7572 static const int kSize = kDataOffset + kPointerSize;
7574 // Indices in the data array.
7575 static const int kTagIndex = 0;
7576 static const int kSourceIndex = kTagIndex + 1;
7577 static const int kFlagsIndex = kSourceIndex + 1;
7578 static const int kDataIndex = kFlagsIndex + 1;
7579 // The data fields are used in different ways depending on the
7580 // value of the tag.
7581 // Atom regexps (literal strings).
7582 static const int kAtomPatternIndex = kDataIndex;
7584 static const int kAtomDataSize = kAtomPatternIndex + 1;
7586 // Irregexp compiled code or bytecode for Latin1. If compilation
7587 // fails, this fields hold an exception object that should be
7588 // thrown if the regexp is used again.
7589 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7590 // Irregexp compiled code or bytecode for UC16. If compilation
7591 // fails, this fields hold an exception object that should be
7592 // thrown if the regexp is used again.
7593 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7595 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7596 // is a potential candidate for flushing.
7597 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7598 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7599 // a potential candidate for flushing.
7600 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7602 // Maximal number of registers used by either Latin1 or UC16.
7603 // Only used to check that there is enough stack space
7604 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7605 // Number of captures in the compiled regexp.
7606 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7608 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7610 // Offsets directly into the data fixed array.
7611 static const int kDataTagOffset =
7612 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7613 static const int kDataOneByteCodeOffset =
7614 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7615 static const int kDataUC16CodeOffset =
7616 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7617 static const int kIrregexpCaptureCountOffset =
7618 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7620 // In-object fields.
7621 static const int kSourceFieldIndex = 0;
7622 static const int kGlobalFieldIndex = 1;
7623 static const int kIgnoreCaseFieldIndex = 2;
7624 static const int kMultilineFieldIndex = 3;
7625 static const int kLastIndexFieldIndex = 4;
7626 static const int kInObjectFieldCount = 5;
7628 // The uninitialized value for a regexp code object.
7629 static const int kUninitializedValue = -1;
7631 // The compilation error value for the regexp code object. The real error
7632 // object is in the saved code field.
7633 static const int kCompilationErrorValue = -2;
7635 // When we store the sweep generation at which we moved the code from the
7636 // code index to the saved code index we mask it of to be in the [0:255]
7638 static const int kCodeAgeMask = 0xff;
7642 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7644 static inline bool IsMatch(HashTableKey* key, Object* value) {
7645 return key->IsMatch(value);
7648 static inline uint32_t Hash(HashTableKey* key) {
7652 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7653 return key->HashForObject(object);
7656 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7658 static const int kPrefixSize = 0;
7659 static const int kEntrySize = 2;
7663 // This cache is used in two different variants. For regexp caching, it simply
7664 // maps identifying info of the regexp to the cached regexp object. Scripts and
7665 // eval code only gets cached after a second probe for the code object. To do
7666 // so, on first "put" only a hash identifying the source is entered into the
7667 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7668 // such lifetimes get reduced, and removed once they reach zero. If a second put
7669 // is called while such a hash is live in the cache, the hash gets replaced by
7670 // an actual cache entry. Age also removes stale live entries from the cache.
7671 // Such entries are identified by SharedFunctionInfos pointing to either the
7672 // recompilation stub, or to "old" code. This avoids memory leaks due to
7673 // premature caching of scripts and eval strings that are never needed later.
7674 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7675 CompilationCacheShape,
7678 // Find cached value for a string key, otherwise return null.
7679 Handle<Object> Lookup(
7680 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7681 Handle<Object> LookupEval(
7682 Handle<String> src, Handle<SharedFunctionInfo> shared,
7683 LanguageMode language_mode, int scope_position);
7684 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7685 static Handle<CompilationCacheTable> Put(
7686 Handle<CompilationCacheTable> cache, Handle<String> src,
7687 Handle<Context> context, LanguageMode language_mode,
7688 Handle<Object> value);
7689 static Handle<CompilationCacheTable> PutEval(
7690 Handle<CompilationCacheTable> cache, Handle<String> src,
7691 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7692 int scope_position);
7693 static Handle<CompilationCacheTable> PutRegExp(
7694 Handle<CompilationCacheTable> cache, Handle<String> src,
7695 JSRegExp::Flags flags, Handle<FixedArray> value);
7696 void Remove(Object* value);
7698 static const int kHashGenerations = 10;
7700 DECLARE_CAST(CompilationCacheTable)
7703 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7707 class CodeCache: public Struct {
7709 DECL_ACCESSORS(default_cache, FixedArray)
7710 DECL_ACCESSORS(normal_type_cache, Object)
7712 // Add the code object to the cache.
7714 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7716 // Lookup code object in the cache. Returns code object if found and undefined
7718 Object* Lookup(Name* name, Code::Flags flags);
7720 // Get the internal index of a code object in the cache. Returns -1 if the
7721 // code object is not in that cache. This index can be used to later call
7722 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7724 int GetIndex(Object* name, Code* code);
7726 // Remove an object from the cache with the provided internal index.
7727 void RemoveByIndex(Object* name, Code* code, int index);
7729 DECLARE_CAST(CodeCache)
7731 // Dispatched behavior.
7732 DECLARE_PRINTER(CodeCache)
7733 DECLARE_VERIFIER(CodeCache)
7735 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7736 static const int kNormalTypeCacheOffset =
7737 kDefaultCacheOffset + kPointerSize;
7738 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7741 static void UpdateDefaultCache(
7742 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7743 static void UpdateNormalTypeCache(
7744 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7745 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7746 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7748 // Code cache layout of the default cache. Elements are alternating name and
7749 // code objects for non normal load/store/call IC's.
7750 static const int kCodeCacheEntrySize = 2;
7751 static const int kCodeCacheEntryNameOffset = 0;
7752 static const int kCodeCacheEntryCodeOffset = 1;
7754 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7758 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7760 static inline bool IsMatch(HashTableKey* key, Object* value) {
7761 return key->IsMatch(value);
7764 static inline uint32_t Hash(HashTableKey* key) {
7768 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7769 return key->HashForObject(object);
7772 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7774 static const int kPrefixSize = 0;
7775 static const int kEntrySize = 2;
7779 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7780 CodeCacheHashTableShape,
7783 Object* Lookup(Name* name, Code::Flags flags);
7784 static Handle<CodeCacheHashTable> Put(
7785 Handle<CodeCacheHashTable> table,
7789 int GetIndex(Name* name, Code::Flags flags);
7790 void RemoveByIndex(int index);
7792 DECLARE_CAST(CodeCacheHashTable)
7794 // Initial size of the fixed array backing the hash table.
7795 static const int kInitialSize = 64;
7798 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7802 class PolymorphicCodeCache: public Struct {
7804 DECL_ACCESSORS(cache, Object)
7806 static void Update(Handle<PolymorphicCodeCache> cache,
7807 MapHandleList* maps,
7812 // Returns an undefined value if the entry is not found.
7813 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7815 DECLARE_CAST(PolymorphicCodeCache)
7817 // Dispatched behavior.
7818 DECLARE_PRINTER(PolymorphicCodeCache)
7819 DECLARE_VERIFIER(PolymorphicCodeCache)
7821 static const int kCacheOffset = HeapObject::kHeaderSize;
7822 static const int kSize = kCacheOffset + kPointerSize;
7825 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7829 class PolymorphicCodeCacheHashTable
7830 : public HashTable<PolymorphicCodeCacheHashTable,
7831 CodeCacheHashTableShape,
7834 Object* Lookup(MapHandleList* maps, int code_kind);
7836 static Handle<PolymorphicCodeCacheHashTable> Put(
7837 Handle<PolymorphicCodeCacheHashTable> hash_table,
7838 MapHandleList* maps,
7842 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7844 static const int kInitialSize = 64;
7846 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7850 class TypeFeedbackInfo: public Struct {
7852 inline int ic_total_count();
7853 inline void set_ic_total_count(int count);
7855 inline int ic_with_type_info_count();
7856 inline void change_ic_with_type_info_count(int delta);
7858 inline int ic_generic_count();
7859 inline void change_ic_generic_count(int delta);
7861 inline void initialize_storage();
7863 inline void change_own_type_change_checksum();
7864 inline int own_type_change_checksum();
7866 inline void set_inlined_type_change_checksum(int checksum);
7867 inline bool matches_inlined_type_change_checksum(int checksum);
7869 DECLARE_CAST(TypeFeedbackInfo)
7871 // Dispatched behavior.
7872 DECLARE_PRINTER(TypeFeedbackInfo)
7873 DECLARE_VERIFIER(TypeFeedbackInfo)
7875 static const int kStorage1Offset = HeapObject::kHeaderSize;
7876 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7877 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7878 static const int kSize = kStorage3Offset + kPointerSize;
7881 static const int kTypeChangeChecksumBits = 7;
7883 class ICTotalCountField: public BitField<int, 0,
7884 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7885 class OwnTypeChangeChecksum: public BitField<int,
7886 kSmiValueSize - kTypeChangeChecksumBits,
7887 kTypeChangeChecksumBits> {}; // NOLINT
7888 class ICsWithTypeInfoCountField: public BitField<int, 0,
7889 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7890 class InlinedTypeChangeChecksum: public BitField<int,
7891 kSmiValueSize - kTypeChangeChecksumBits,
7892 kTypeChangeChecksumBits> {}; // NOLINT
7894 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7898 enum AllocationSiteMode {
7899 DONT_TRACK_ALLOCATION_SITE,
7900 TRACK_ALLOCATION_SITE,
7901 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7905 class AllocationSite: public Struct {
7907 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7908 static const double kPretenureRatio;
7909 static const int kPretenureMinimumCreated = 100;
7911 // Values for pretenure decision field.
7912 enum PretenureDecision {
7918 kLastPretenureDecisionValue = kZombie
7921 const char* PretenureDecisionName(PretenureDecision decision);
7923 DECL_ACCESSORS(transition_info, Object)
7924 // nested_site threads a list of sites that represent nested literals
7925 // walked in a particular order. So [[1, 2], 1, 2] will have one
7926 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7927 DECL_ACCESSORS(nested_site, Object)
7928 DECL_INT_ACCESSORS(pretenure_data)
7929 DECL_INT_ACCESSORS(pretenure_create_count)
7930 DECL_ACCESSORS(dependent_code, DependentCode)
7931 DECL_ACCESSORS(weak_next, Object)
7933 inline void Initialize();
7935 // This method is expensive, it should only be called for reporting.
7936 bool IsNestedSite();
7938 // transition_info bitfields, for constructed array transition info.
7939 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7940 class UnusedBits: public BitField<int, 15, 14> {};
7941 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7943 // Bitfields for pretenure_data
7944 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7945 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7946 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7947 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7949 // Increments the mementos found counter and returns true when the first
7950 // memento was found for a given allocation site.
7951 inline bool IncrementMementoFoundCount();
7953 inline void IncrementMementoCreateCount();
7955 PretenureFlag GetPretenureMode();
7957 void ResetPretenureDecision();
7959 inline PretenureDecision pretenure_decision();
7960 inline void set_pretenure_decision(PretenureDecision decision);
7962 inline bool deopt_dependent_code();
7963 inline void set_deopt_dependent_code(bool deopt);
7965 inline int memento_found_count();
7966 inline void set_memento_found_count(int count);
7968 inline int memento_create_count();
7969 inline void set_memento_create_count(int count);
7971 // The pretenuring decision is made during gc, and the zombie state allows
7972 // us to recognize when an allocation site is just being kept alive because
7973 // a later traversal of new space may discover AllocationMementos that point
7974 // to this AllocationSite.
7975 inline bool IsZombie();
7977 inline bool IsMaybeTenure();
7979 inline void MarkZombie();
7981 inline bool MakePretenureDecision(PretenureDecision current_decision,
7983 bool maximum_size_scavenge);
7985 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7987 inline ElementsKind GetElementsKind();
7988 inline void SetElementsKind(ElementsKind kind);
7990 inline bool CanInlineCall();
7991 inline void SetDoNotInlineCall();
7993 inline bool SitePointsToLiteral();
7995 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7996 ElementsKind to_kind);
7998 DECLARE_PRINTER(AllocationSite)
7999 DECLARE_VERIFIER(AllocationSite)
8001 DECLARE_CAST(AllocationSite)
8002 static inline AllocationSiteMode GetMode(
8003 ElementsKind boilerplate_elements_kind);
8004 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8005 static inline bool CanTrack(InstanceType type);
8007 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8008 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8009 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8010 static const int kPretenureCreateCountOffset =
8011 kPretenureDataOffset + kPointerSize;
8012 static const int kDependentCodeOffset =
8013 kPretenureCreateCountOffset + kPointerSize;
8014 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8015 static const int kSize = kWeakNextOffset + kPointerSize;
8017 // During mark compact we need to take special care for the dependent code
8019 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8020 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8022 // For other visitors, use the fixed body descriptor below.
8023 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8024 kDependentCodeOffset + kPointerSize,
8025 kSize> BodyDescriptor;
8028 inline bool PretenuringDecisionMade();
8030 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8034 class AllocationMemento: public Struct {
8036 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8037 static const int kSize = kAllocationSiteOffset + kPointerSize;
8039 DECL_ACCESSORS(allocation_site, Object)
8041 inline bool IsValid();
8042 inline AllocationSite* GetAllocationSite();
8044 DECLARE_PRINTER(AllocationMemento)
8045 DECLARE_VERIFIER(AllocationMemento)
8047 DECLARE_CAST(AllocationMemento)
8050 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8054 // Representation of a slow alias as part of a sloppy arguments objects.
8055 // For fast aliases (if HasSloppyArgumentsElements()):
8056 // - the parameter map contains an index into the context
8057 // - all attributes of the element have default values
8058 // For slow aliases (if HasDictionaryArgumentsElements()):
8059 // - the parameter map contains no fast alias mapping (i.e. the hole)
8060 // - this struct (in the slow backing store) contains an index into the context
8061 // - all attributes are available as part if the property details
8062 class AliasedArgumentsEntry: public Struct {
8064 inline int aliased_context_slot() const;
8065 inline void set_aliased_context_slot(int count);
8067 DECLARE_CAST(AliasedArgumentsEntry)
8069 // Dispatched behavior.
8070 DECLARE_PRINTER(AliasedArgumentsEntry)
8071 DECLARE_VERIFIER(AliasedArgumentsEntry)
8073 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8074 static const int kSize = kAliasedContextSlot + kPointerSize;
8077 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8081 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8082 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8085 class StringHasher {
8087 explicit inline StringHasher(int length, uint32_t seed);
8089 template <typename schar>
8090 static inline uint32_t HashSequentialString(const schar* chars,
8094 // Reads all the data, even for long strings and computes the utf16 length.
8095 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8097 int* utf16_length_out);
8099 // Calculated hash value for a string consisting of 1 to
8100 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8101 // value is represented decimal value.
8102 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8104 // No string is allowed to have a hash of zero. That value is reserved
8105 // for internal properties. If the hash calculation yields zero then we
8107 static const int kZeroHash = 27;
8109 // Reusable parts of the hashing algorithm.
8110 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8111 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8112 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8113 const uc16* chars, int length));
8114 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8119 // Returns the value to store in the hash field of a string with
8120 // the given length and contents.
8121 uint32_t GetHashField();
8122 // Returns true if the hash of this string can be computed without
8123 // looking at the contents.
8124 inline bool has_trivial_hash();
8125 // Adds a block of characters to the hash.
8126 template<typename Char>
8127 inline void AddCharacters(const Char* chars, int len);
8130 // Add a character to the hash.
8131 inline void AddCharacter(uint16_t c);
8132 // Update index. Returns true if string is still an index.
8133 inline bool UpdateIndex(uint16_t c);
8136 uint32_t raw_running_hash_;
8137 uint32_t array_index_;
8138 bool is_array_index_;
8139 bool is_first_char_;
8140 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8144 class IteratingStringHasher : public StringHasher {
8146 static inline uint32_t Hash(String* string, uint32_t seed);
8147 inline void VisitOneByteString(const uint8_t* chars, int length);
8148 inline void VisitTwoByteString(const uint16_t* chars, int length);
8151 inline IteratingStringHasher(int len, uint32_t seed);
8152 void VisitConsString(ConsString* cons_string);
8153 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8157 // The characteristics of a string are stored in its map. Retrieving these
8158 // few bits of information is moderately expensive, involving two memory
8159 // loads where the second is dependent on the first. To improve efficiency
8160 // the shape of the string is given its own class so that it can be retrieved
8161 // once and used for several string operations. A StringShape is small enough
8162 // to be passed by value and is immutable, but be aware that flattening a
8163 // string can potentially alter its shape. Also be aware that a GC caused by
8164 // something else can alter the shape of a string due to ConsString
8165 // shortcutting. Keeping these restrictions in mind has proven to be error-
8166 // prone and so we no longer put StringShapes in variables unless there is a
8167 // concrete performance benefit at that particular point in the code.
8168 class StringShape BASE_EMBEDDED {
8170 inline explicit StringShape(const String* s);
8171 inline explicit StringShape(Map* s);
8172 inline explicit StringShape(InstanceType t);
8173 inline bool IsSequential();
8174 inline bool IsExternal();
8175 inline bool IsCons();
8176 inline bool IsSliced();
8177 inline bool IsIndirect();
8178 inline bool IsExternalOneByte();
8179 inline bool IsExternalTwoByte();
8180 inline bool IsSequentialOneByte();
8181 inline bool IsSequentialTwoByte();
8182 inline bool IsInternalized();
8183 inline StringRepresentationTag representation_tag();
8184 inline uint32_t encoding_tag();
8185 inline uint32_t full_representation_tag();
8186 inline uint32_t size_tag();
8188 inline uint32_t type() { return type_; }
8189 inline void invalidate() { valid_ = false; }
8190 inline bool valid() { return valid_; }
8192 inline void invalidate() { }
8198 inline void set_valid() { valid_ = true; }
8201 inline void set_valid() { }
8206 // The Name abstract class captures anything that can be used as a property
8207 // name, i.e., strings and symbols. All names store a hash value.
8208 class Name: public HeapObject {
8210 // Get and set the hash field of the name.
8211 inline uint32_t hash_field();
8212 inline void set_hash_field(uint32_t value);
8214 // Tells whether the hash code has been computed.
8215 inline bool HasHashCode();
8217 // Returns a hash value used for the property table
8218 inline uint32_t Hash();
8220 // Equality operations.
8221 inline bool Equals(Name* other);
8222 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8225 inline bool AsArrayIndex(uint32_t* index);
8227 // If the name is private, it can only name own properties.
8228 inline bool IsPrivate();
8230 // If the name is a non-flat string, this method returns a flat version of the
8231 // string. Otherwise it'll just return the input.
8232 static inline Handle<Name> Flatten(Handle<Name> name,
8233 PretenureFlag pretenure = NOT_TENURED);
8235 // Return a string version of this name that is converted according to the
8236 // rules described in ES6 section 9.2.11.
8237 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8241 DECLARE_PRINTER(Name)
8243 void NameShortPrint();
8244 int NameShortPrint(Vector<char> str);
8247 // Layout description.
8248 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8249 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8250 static const int kHashFieldOffset = kHashFieldSlot;
8252 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8254 static const int kSize = kHashFieldSlot + kPointerSize;
8256 // Mask constant for checking if a name has a computed hash code
8257 // and if it is a string that is an array index. The least significant bit
8258 // indicates whether a hash code has been computed. If the hash code has
8259 // been computed the 2nd bit tells whether the string can be used as an
8261 static const int kHashNotComputedMask = 1;
8262 static const int kIsNotArrayIndexMask = 1 << 1;
8263 static const int kNofHashBitFields = 2;
8265 // Shift constant retrieving hash code from hash field.
8266 static const int kHashShift = kNofHashBitFields;
8268 // Only these bits are relevant in the hash, since the top two are shifted
8270 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8272 // Array index strings this short can keep their index in the hash field.
8273 static const int kMaxCachedArrayIndexLength = 7;
8275 // For strings which are array indexes the hash value has the string length
8276 // mixed into the hash, mainly to avoid a hash value of zero which would be
8277 // the case for the string '0'. 24 bits are used for the array index value.
8278 static const int kArrayIndexValueBits = 24;
8279 static const int kArrayIndexLengthBits =
8280 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8282 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8284 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8285 kArrayIndexValueBits> {}; // NOLINT
8286 class ArrayIndexLengthBits : public BitField<unsigned int,
8287 kNofHashBitFields + kArrayIndexValueBits,
8288 kArrayIndexLengthBits> {}; // NOLINT
8290 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8291 // could use a mask to test if the length of string is less than or equal to
8292 // kMaxCachedArrayIndexLength.
8293 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8295 static const unsigned int kContainsCachedArrayIndexMask =
8296 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8297 << ArrayIndexLengthBits::kShift) |
8298 kIsNotArrayIndexMask;
8300 // Value of empty hash field indicating that the hash is not computed.
8301 static const int kEmptyHashField =
8302 kIsNotArrayIndexMask | kHashNotComputedMask;
8305 static inline bool IsHashFieldComputed(uint32_t field);
8308 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8313 class Symbol: public Name {
8315 // [name]: The print name of a symbol, or undefined if none.
8316 DECL_ACCESSORS(name, Object)
8318 DECL_INT_ACCESSORS(flags)
8320 // [is_private]: Whether this is a private symbol. Private symbols can only
8321 // be used to designate own properties of objects.
8322 DECL_BOOLEAN_ACCESSORS(is_private)
8324 DECLARE_CAST(Symbol)
8326 // Dispatched behavior.
8327 DECLARE_PRINTER(Symbol)
8328 DECLARE_VERIFIER(Symbol)
8330 // Layout description.
8331 static const int kNameOffset = Name::kSize;
8332 static const int kFlagsOffset = kNameOffset + kPointerSize;
8333 static const int kSize = kFlagsOffset + kPointerSize;
8335 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8337 void SymbolShortPrint(std::ostream& os);
8340 static const int kPrivateBit = 0;
8342 const char* PrivateSymbolToName() const;
8345 friend class Name; // For PrivateSymbolToName.
8348 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8354 // The String abstract class captures JavaScript string values:
8357 // 4.3.16 String Value
8358 // A string value is a member of the type String and is a finite
8359 // ordered sequence of zero or more 16-bit unsigned integer values.
8361 // All string values have a length field.
8362 class String: public Name {
8364 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8366 // Array index strings this short can keep their index in the hash field.
8367 static const int kMaxCachedArrayIndexLength = 7;
8369 // For strings which are array indexes the hash value has the string length
8370 // mixed into the hash, mainly to avoid a hash value of zero which would be
8371 // the case for the string '0'. 24 bits are used for the array index value.
8372 static const int kArrayIndexValueBits = 24;
8373 static const int kArrayIndexLengthBits =
8374 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8376 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8378 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8379 kArrayIndexValueBits> {}; // NOLINT
8380 class ArrayIndexLengthBits : public BitField<unsigned int,
8381 kNofHashBitFields + kArrayIndexValueBits,
8382 kArrayIndexLengthBits> {}; // NOLINT
8384 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8385 // could use a mask to test if the length of string is less than or equal to
8386 // kMaxCachedArrayIndexLength.
8387 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8389 static const unsigned int kContainsCachedArrayIndexMask =
8390 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8391 << ArrayIndexLengthBits::kShift) |
8392 kIsNotArrayIndexMask;
8394 class SubStringRange {
8396 explicit inline SubStringRange(String* string, int first = 0,
8399 inline iterator begin();
8400 inline iterator end();
8408 // Representation of the flat content of a String.
8409 // A non-flat string doesn't have flat content.
8410 // A flat string has content that's encoded as a sequence of either
8411 // one-byte chars or two-byte UC16.
8412 // Returned by String::GetFlatContent().
8415 // Returns true if the string is flat and this structure contains content.
8416 bool IsFlat() { return state_ != NON_FLAT; }
8417 // Returns true if the structure contains one-byte content.
8418 bool IsOneByte() { return state_ == ONE_BYTE; }
8419 // Returns true if the structure contains two-byte content.
8420 bool IsTwoByte() { return state_ == TWO_BYTE; }
8422 // Return the one byte content of the string. Only use if IsOneByte()
8424 Vector<const uint8_t> ToOneByteVector() {
8425 DCHECK_EQ(ONE_BYTE, state_);
8426 return Vector<const uint8_t>(onebyte_start, length_);
8428 // Return the two-byte content of the string. Only use if IsTwoByte()
8430 Vector<const uc16> ToUC16Vector() {
8431 DCHECK_EQ(TWO_BYTE, state_);
8432 return Vector<const uc16>(twobyte_start, length_);
8436 DCHECK(i < length_);
8437 DCHECK(state_ != NON_FLAT);
8438 if (state_ == ONE_BYTE) return onebyte_start[i];
8439 return twobyte_start[i];
8442 bool UsesSameString(const FlatContent& other) const {
8443 return onebyte_start == other.onebyte_start;
8447 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8449 // Constructors only used by String::GetFlatContent().
8450 explicit FlatContent(const uint8_t* start, int length)
8451 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8452 explicit FlatContent(const uc16* start, int length)
8453 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8454 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8457 const uint8_t* onebyte_start;
8458 const uc16* twobyte_start;
8463 friend class String;
8464 friend class IterableSubString;
8467 template <typename Char>
8468 INLINE(Vector<const Char> GetCharVector());
8470 // Get and set the length of the string.
8471 inline int length() const;
8472 inline void set_length(int value);
8474 // Get and set the length of the string using acquire loads and release
8476 inline int synchronized_length() const;
8477 inline void synchronized_set_length(int value);
8479 // Returns whether this string has only one-byte chars, i.e. all of them can
8480 // be one-byte encoded. This might be the case even if the string is
8481 // two-byte. Such strings may appear when the embedder prefers
8482 // two-byte external representations even for one-byte data.
8483 inline bool IsOneByteRepresentation() const;
8484 inline bool IsTwoByteRepresentation() const;
8486 // Cons and slices have an encoding flag that may not represent the actual
8487 // encoding of the underlying string. This is taken into account here.
8488 // Requires: this->IsFlat()
8489 inline bool IsOneByteRepresentationUnderneath();
8490 inline bool IsTwoByteRepresentationUnderneath();
8492 // NOTE: this should be considered only a hint. False negatives are
8494 inline bool HasOnlyOneByteChars();
8496 // Get and set individual two byte chars in the string.
8497 inline void Set(int index, uint16_t value);
8498 // Get individual two byte char in the string. Repeated calls
8499 // to this method are not efficient unless the string is flat.
8500 INLINE(uint16_t Get(int index));
8502 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8503 static Handle<Object> ToNumber(Handle<String> subject);
8505 // Flattens the string. Checks first inline to see if it is
8506 // necessary. Does nothing if the string is not a cons string.
8507 // Flattening allocates a sequential string with the same data as
8508 // the given string and mutates the cons string to a degenerate
8509 // form, where the first component is the new sequential string and
8510 // the second component is the empty string. If allocation fails,
8511 // this function returns a failure. If flattening succeeds, this
8512 // function returns the sequential string that is now the first
8513 // component of the cons string.
8515 // Degenerate cons strings are handled specially by the garbage
8516 // collector (see IsShortcutCandidate).
8518 static inline Handle<String> Flatten(Handle<String> string,
8519 PretenureFlag pretenure = NOT_TENURED);
8521 // Tries to return the content of a flat string as a structure holding either
8522 // a flat vector of char or of uc16.
8523 // If the string isn't flat, and therefore doesn't have flat content, the
8524 // returned structure will report so, and can't provide a vector of either
8526 FlatContent GetFlatContent();
8528 // Returns the parent of a sliced string or first part of a flat cons string.
8529 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8530 inline String* GetUnderlying();
8532 // String relational comparison, implemented according to ES6 section 7.2.11
8533 // Abstract Relational Comparison (step 5): The comparison of Strings uses a
8534 // simple lexicographic ordering on sequences of code unit values. There is no
8535 // attempt to use the more complex, semantically oriented definitions of
8536 // character or string equality and collating order defined in the Unicode
8537 // specification. Therefore String values that are canonically equal according
8538 // to the Unicode standard could test as unequal. In effect this algorithm
8539 // assumes that both Strings are already in normalized form. Also, note that
8540 // for strings containing supplementary characters, lexicographic ordering on
8541 // sequences of UTF-16 code unit values differs from that on sequences of code
8543 MUST_USE_RESULT static ComparisonResult Compare(Handle<String> x,
8546 // String equality operations.
8547 inline bool Equals(String* other);
8548 inline static bool Equals(Handle<String> one, Handle<String> two);
8549 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8550 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8551 bool IsTwoByteEqualTo(Vector<const uc16> str);
8553 // Return a UTF8 representation of the string. The string is null
8554 // terminated but may optionally contain nulls. Length is returned
8555 // in length_output if length_output is not a null pointer The string
8556 // should be nearly flat, otherwise the performance of this method may
8557 // be very slow (quadratic in the length). Setting robustness_flag to
8558 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8559 // handles unexpected data without causing assert failures and it does not
8560 // do any heap allocations. This is useful when printing stack traces.
8561 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8562 RobustnessFlag robustness_flag,
8563 int offset, int length,
8564 int* length_output = 0);
8565 base::SmartArrayPointer<char> ToCString(
8566 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8567 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8568 int* length_output = 0);
8570 // Return a 16 bit Unicode representation of the string.
8571 // The string should be nearly flat, otherwise the performance of
8572 // of this method may be very bad. Setting robustness_flag to
8573 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8574 // handles unexpected data without causing assert failures and it does not
8575 // do any heap allocations. This is useful when printing stack traces.
8576 base::SmartArrayPointer<uc16> ToWideCString(
8577 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8579 bool ComputeArrayIndex(uint32_t* index);
8582 bool MakeExternal(v8::String::ExternalStringResource* resource);
8583 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8586 inline bool AsArrayIndex(uint32_t* index);
8588 DECLARE_CAST(String)
8590 void PrintOn(FILE* out);
8592 // For use during stack traces. Performs rudimentary sanity check.
8595 // Dispatched behavior.
8596 void StringShortPrint(StringStream* accumulator);
8597 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8598 #if defined(DEBUG) || defined(OBJECT_PRINT)
8599 char* ToAsciiArray();
8601 DECLARE_PRINTER(String)
8602 DECLARE_VERIFIER(String)
8604 inline bool IsFlat();
8606 // Layout description.
8607 static const int kLengthOffset = Name::kSize;
8608 static const int kSize = kLengthOffset + kPointerSize;
8610 // Maximum number of characters to consider when trying to convert a string
8611 // value into an array index.
8612 static const int kMaxArrayIndexSize = 10;
8613 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8616 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8617 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8618 static const int kMaxUtf16CodeUnit = 0xffff;
8619 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8621 // Value of hash field containing computed hash equal to zero.
8622 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8624 // Maximal string length.
8625 static const int kMaxLength = (1 << 28) - 16;
8627 // Max length for computing hash. For strings longer than this limit the
8628 // string length is used as the hash value.
8629 static const int kMaxHashCalcLength = 16383;
8631 // Limit for truncation in short printing.
8632 static const int kMaxShortPrintLength = 1024;
8634 // Support for regular expressions.
8635 const uc16* GetTwoByteData(unsigned start);
8637 // Helper function for flattening strings.
8638 template <typename sinkchar>
8639 static void WriteToFlat(String* source,
8644 // The return value may point to the first aligned word containing the first
8645 // non-one-byte character, rather than directly to the non-one-byte character.
8646 // If the return value is >= the passed length, the entire string was
8648 static inline int NonAsciiStart(const char* chars, int length) {
8649 const char* start = chars;
8650 const char* limit = chars + length;
8652 if (length >= kIntptrSize) {
8653 // Check unaligned bytes.
8654 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8655 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8656 return static_cast<int>(chars - start);
8660 // Check aligned words.
8661 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8662 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8663 while (chars + sizeof(uintptr_t) <= limit) {
8664 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8665 return static_cast<int>(chars - start);
8667 chars += sizeof(uintptr_t);
8670 // Check remaining unaligned bytes.
8671 while (chars < limit) {
8672 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8673 return static_cast<int>(chars - start);
8678 return static_cast<int>(chars - start);
8681 static inline bool IsAscii(const char* chars, int length) {
8682 return NonAsciiStart(chars, length) >= length;
8685 static inline bool IsAscii(const uint8_t* chars, int length) {
8687 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8690 static inline int NonOneByteStart(const uc16* chars, int length) {
8691 const uc16* limit = chars + length;
8692 const uc16* start = chars;
8693 while (chars < limit) {
8694 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8697 return static_cast<int>(chars - start);
8700 static inline bool IsOneByte(const uc16* chars, int length) {
8701 return NonOneByteStart(chars, length) >= length;
8704 template<class Visitor>
8705 static inline ConsString* VisitFlat(Visitor* visitor,
8709 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8710 bool include_ending_line);
8712 // Use the hash field to forward to the canonical internalized string
8713 // when deserializing an internalized string.
8714 inline void SetForwardedInternalizedString(String* string);
8715 inline String* GetForwardedInternalizedString();
8719 friend class StringTableInsertionKey;
8721 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8722 PretenureFlag tenure);
8724 // Slow case of String::Equals. This implementation works on any strings
8725 // but it is most efficient on strings that are almost flat.
8726 bool SlowEquals(String* other);
8728 static bool SlowEquals(Handle<String> one, Handle<String> two);
8730 // Slow case of AsArrayIndex.
8731 bool SlowAsArrayIndex(uint32_t* index);
8733 // Compute and set the hash code.
8734 uint32_t ComputeAndSetHash();
8736 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8740 // The SeqString abstract class captures sequential string values.
8741 class SeqString: public String {
8743 DECLARE_CAST(SeqString)
8745 // Layout description.
8746 static const int kHeaderSize = String::kSize;
8748 // Truncate the string in-place if possible and return the result.
8749 // In case of new_length == 0, the empty string is returned without
8750 // truncating the original string.
8751 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8754 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8758 // The OneByteString class captures sequential one-byte string objects.
8759 // Each character in the OneByteString is an one-byte character.
8760 class SeqOneByteString: public SeqString {
8762 static const bool kHasOneByteEncoding = true;
8764 // Dispatched behavior.
8765 inline uint16_t SeqOneByteStringGet(int index);
8766 inline void SeqOneByteStringSet(int index, uint16_t value);
8768 // Get the address of the characters in this string.
8769 inline Address GetCharsAddress();
8771 inline uint8_t* GetChars();
8773 DECLARE_CAST(SeqOneByteString)
8775 // Garbage collection support. This method is called by the
8776 // garbage collector to compute the actual size of an OneByteString
8778 inline int SeqOneByteStringSize(InstanceType instance_type);
8780 // Computes the size for an OneByteString instance of a given length.
8781 static int SizeFor(int length) {
8782 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8785 // Maximal memory usage for a single sequential one-byte string.
8786 static const int kMaxSize = 512 * MB - 1;
8787 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8790 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8794 // The TwoByteString class captures sequential unicode string objects.
8795 // Each character in the TwoByteString is a two-byte uint16_t.
8796 class SeqTwoByteString: public SeqString {
8798 static const bool kHasOneByteEncoding = false;
8800 // Dispatched behavior.
8801 inline uint16_t SeqTwoByteStringGet(int index);
8802 inline void SeqTwoByteStringSet(int index, uint16_t value);
8804 // Get the address of the characters in this string.
8805 inline Address GetCharsAddress();
8807 inline uc16* GetChars();
8810 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8812 DECLARE_CAST(SeqTwoByteString)
8814 // Garbage collection support. This method is called by the
8815 // garbage collector to compute the actual size of a TwoByteString
8817 inline int SeqTwoByteStringSize(InstanceType instance_type);
8819 // Computes the size for a TwoByteString instance of a given length.
8820 static int SizeFor(int length) {
8821 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8824 // Maximal memory usage for a single sequential two-byte string.
8825 static const int kMaxSize = 512 * MB - 1;
8826 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8827 String::kMaxLength);
8830 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8834 // The ConsString class describes string values built by using the
8835 // addition operator on strings. A ConsString is a pair where the
8836 // first and second components are pointers to other string values.
8837 // One or both components of a ConsString can be pointers to other
8838 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8839 // are non-ConsString string values. The string value represented by
8840 // a ConsString can be obtained by concatenating the leaf string
8841 // values in a left-to-right depth-first traversal of the tree.
8842 class ConsString: public String {
8844 // First string of the cons cell.
8845 inline String* first();
8846 // Doesn't check that the result is a string, even in debug mode. This is
8847 // useful during GC where the mark bits confuse the checks.
8848 inline Object* unchecked_first();
8849 inline void set_first(String* first,
8850 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8852 // Second string of the cons cell.
8853 inline String* second();
8854 // Doesn't check that the result is a string, even in debug mode. This is
8855 // useful during GC where the mark bits confuse the checks.
8856 inline Object* unchecked_second();
8857 inline void set_second(String* second,
8858 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8860 // Dispatched behavior.
8861 uint16_t ConsStringGet(int index);
8863 DECLARE_CAST(ConsString)
8865 // Layout description.
8866 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8867 static const int kSecondOffset = kFirstOffset + kPointerSize;
8868 static const int kSize = kSecondOffset + kPointerSize;
8870 // Minimum length for a cons string.
8871 static const int kMinLength = 13;
8873 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8876 DECLARE_VERIFIER(ConsString)
8879 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8883 // The Sliced String class describes strings that are substrings of another
8884 // sequential string. The motivation is to save time and memory when creating
8885 // a substring. A Sliced String is described as a pointer to the parent,
8886 // the offset from the start of the parent string and the length. Using
8887 // a Sliced String therefore requires unpacking of the parent string and
8888 // adding the offset to the start address. A substring of a Sliced String
8889 // are not nested since the double indirection is simplified when creating
8890 // such a substring.
8891 // Currently missing features are:
8892 // - handling externalized parent strings
8893 // - external strings as parent
8894 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8895 class SlicedString: public String {
8897 inline String* parent();
8898 inline void set_parent(String* parent,
8899 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8900 inline int offset() const;
8901 inline void set_offset(int offset);
8903 // Dispatched behavior.
8904 uint16_t SlicedStringGet(int index);
8906 DECLARE_CAST(SlicedString)
8908 // Layout description.
8909 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8910 static const int kOffsetOffset = kParentOffset + kPointerSize;
8911 static const int kSize = kOffsetOffset + kPointerSize;
8913 // Minimum length for a sliced string.
8914 static const int kMinLength = 13;
8916 typedef FixedBodyDescriptor<kParentOffset,
8917 kOffsetOffset + kPointerSize, kSize>
8920 DECLARE_VERIFIER(SlicedString)
8923 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8927 // The ExternalString class describes string values that are backed by
8928 // a string resource that lies outside the V8 heap. ExternalStrings
8929 // consist of the length field common to all strings, a pointer to the
8930 // external resource. It is important to ensure (externally) that the
8931 // resource is not deallocated while the ExternalString is live in the
8934 // The API expects that all ExternalStrings are created through the
8935 // API. Therefore, ExternalStrings should not be used internally.
8936 class ExternalString: public String {
8938 DECLARE_CAST(ExternalString)
8940 // Layout description.
8941 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8942 static const int kShortSize = kResourceOffset + kPointerSize;
8943 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8944 static const int kSize = kResourceDataOffset + kPointerSize;
8946 static const int kMaxShortLength =
8947 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8949 // Return whether external string is short (data pointer is not cached).
8950 inline bool is_short();
8952 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8955 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8959 // The ExternalOneByteString class is an external string backed by an
8961 class ExternalOneByteString : public ExternalString {
8963 static const bool kHasOneByteEncoding = true;
8965 typedef v8::String::ExternalOneByteStringResource Resource;
8967 // The underlying resource.
8968 inline const Resource* resource();
8969 inline void set_resource(const Resource* buffer);
8971 // Update the pointer cache to the external character array.
8972 // The cached pointer is always valid, as the external character array does =
8973 // not move during lifetime. Deserialization is the only exception, after
8974 // which the pointer cache has to be refreshed.
8975 inline void update_data_cache();
8977 inline const uint8_t* GetChars();
8979 // Dispatched behavior.
8980 inline uint16_t ExternalOneByteStringGet(int index);
8982 DECLARE_CAST(ExternalOneByteString)
8984 // Garbage collection support.
8985 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8987 template <typename StaticVisitor>
8988 inline void ExternalOneByteStringIterateBody();
8991 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8995 // The ExternalTwoByteString class is an external string backed by a UTF-16
8997 class ExternalTwoByteString: public ExternalString {
8999 static const bool kHasOneByteEncoding = false;
9001 typedef v8::String::ExternalStringResource Resource;
9003 // The underlying string resource.
9004 inline const Resource* resource();
9005 inline void set_resource(const Resource* buffer);
9007 // Update the pointer cache to the external character array.
9008 // The cached pointer is always valid, as the external character array does =
9009 // not move during lifetime. Deserialization is the only exception, after
9010 // which the pointer cache has to be refreshed.
9011 inline void update_data_cache();
9013 inline const uint16_t* GetChars();
9015 // Dispatched behavior.
9016 inline uint16_t ExternalTwoByteStringGet(int index);
9019 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9021 DECLARE_CAST(ExternalTwoByteString)
9023 // Garbage collection support.
9024 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9026 template<typename StaticVisitor>
9027 inline void ExternalTwoByteStringIterateBody();
9030 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9034 // Utility superclass for stack-allocated objects that must be updated
9035 // on gc. It provides two ways for the gc to update instances, either
9036 // iterating or updating after gc.
9037 class Relocatable BASE_EMBEDDED {
9039 explicit inline Relocatable(Isolate* isolate);
9040 inline virtual ~Relocatable();
9041 virtual void IterateInstance(ObjectVisitor* v) { }
9042 virtual void PostGarbageCollection() { }
9044 static void PostGarbageCollectionProcessing(Isolate* isolate);
9045 static int ArchiveSpacePerThread();
9046 static char* ArchiveState(Isolate* isolate, char* to);
9047 static char* RestoreState(Isolate* isolate, char* from);
9048 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9049 static void Iterate(ObjectVisitor* v, Relocatable* top);
9050 static char* Iterate(ObjectVisitor* v, char* t);
9058 // A flat string reader provides random access to the contents of a
9059 // string independent of the character width of the string. The handle
9060 // must be valid as long as the reader is being used.
9061 class FlatStringReader : public Relocatable {
9063 FlatStringReader(Isolate* isolate, Handle<String> str);
9064 FlatStringReader(Isolate* isolate, Vector<const char> input);
9065 void PostGarbageCollection();
9066 inline uc32 Get(int index);
9067 template <typename Char>
9068 inline Char Get(int index);
9069 int length() { return length_; }
9078 // This maintains an off-stack representation of the stack frames required
9079 // to traverse a ConsString, allowing an entirely iterative and restartable
9080 // traversal of the entire string
9081 class ConsStringIterator {
9083 inline ConsStringIterator() {}
9084 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9085 Reset(cons_string, offset);
9087 inline void Reset(ConsString* cons_string, int offset = 0) {
9089 // Next will always return NULL.
9090 if (cons_string == NULL) return;
9091 Initialize(cons_string, offset);
9093 // Returns NULL when complete.
9094 inline String* Next(int* offset_out) {
9096 if (depth_ == 0) return NULL;
9097 return Continue(offset_out);
9101 static const int kStackSize = 32;
9102 // Use a mask instead of doing modulo operations for stack wrapping.
9103 static const int kDepthMask = kStackSize-1;
9104 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9105 static inline int OffsetForDepth(int depth);
9107 inline void PushLeft(ConsString* string);
9108 inline void PushRight(ConsString* string);
9109 inline void AdjustMaximumDepth();
9111 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9112 void Initialize(ConsString* cons_string, int offset);
9113 String* Continue(int* offset_out);
9114 String* NextLeaf(bool* blew_stack);
9115 String* Search(int* offset_out);
9117 // Stack must always contain only frames for which right traversal
9118 // has not yet been performed.
9119 ConsString* frames_[kStackSize];
9124 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9128 class StringCharacterStream {
9130 inline StringCharacterStream(String* string,
9132 inline uint16_t GetNext();
9133 inline bool HasMore();
9134 inline void Reset(String* string, int offset = 0);
9135 inline void VisitOneByteString(const uint8_t* chars, int length);
9136 inline void VisitTwoByteString(const uint16_t* chars, int length);
9139 ConsStringIterator iter_;
9142 const uint8_t* buffer8_;
9143 const uint16_t* buffer16_;
9145 const uint8_t* end_;
9146 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9150 template <typename T>
9151 class VectorIterator {
9153 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9154 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9155 T GetNext() { return data_[index_++]; }
9156 bool has_more() { return index_ < data_.length(); }
9158 Vector<const T> data_;
9163 // The Oddball describes objects null, undefined, true, and false.
9164 class Oddball: public HeapObject {
9166 // [to_string]: Cached to_string computed at startup.
9167 DECL_ACCESSORS(to_string, String)
9169 // [to_number]: Cached to_number computed at startup.
9170 DECL_ACCESSORS(to_number, Object)
9172 // [typeof]: Cached type_of computed at startup.
9173 DECL_ACCESSORS(type_of, String)
9175 inline byte kind() const;
9176 inline void set_kind(byte kind);
9178 // ES6 section 7.1.3 ToNumber for Boolean, Null, Undefined.
9179 MUST_USE_RESULT static inline Handle<Object> ToNumber(Handle<Oddball> input);
9181 DECLARE_CAST(Oddball)
9183 // Dispatched behavior.
9184 DECLARE_VERIFIER(Oddball)
9186 // Initialize the fields.
9187 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9188 const char* to_string, Handle<Object> to_number,
9189 const char* type_of, byte kind);
9191 // Layout description.
9192 static const int kToStringOffset = HeapObject::kHeaderSize;
9193 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9194 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9195 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9196 static const int kSize = kKindOffset + kPointerSize;
9198 static const byte kFalse = 0;
9199 static const byte kTrue = 1;
9200 static const byte kNotBooleanMask = ~1;
9201 static const byte kTheHole = 2;
9202 static const byte kNull = 3;
9203 static const byte kArgumentMarker = 4;
9204 static const byte kUndefined = 5;
9205 static const byte kUninitialized = 6;
9206 static const byte kOther = 7;
9207 static const byte kException = 8;
9209 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9210 kSize> BodyDescriptor;
9212 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9213 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9214 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9217 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9221 class Cell: public HeapObject {
9223 // [value]: value of the cell.
9224 DECL_ACCESSORS(value, Object)
9228 static inline Cell* FromValueAddress(Address value) {
9229 Object* result = FromAddress(value - kValueOffset);
9230 return static_cast<Cell*>(result);
9233 inline Address ValueAddress() {
9234 return address() + kValueOffset;
9237 // Dispatched behavior.
9238 DECLARE_PRINTER(Cell)
9239 DECLARE_VERIFIER(Cell)
9241 // Layout description.
9242 static const int kValueOffset = HeapObject::kHeaderSize;
9243 static const int kSize = kValueOffset + kPointerSize;
9245 typedef FixedBodyDescriptor<kValueOffset,
9246 kValueOffset + kPointerSize,
9247 kSize> BodyDescriptor;
9250 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9254 class PropertyCell : public HeapObject {
9256 // [property_details]: details of the global property.
9257 DECL_ACCESSORS(property_details_raw, Object)
9258 // [value]: value of the global property.
9259 DECL_ACCESSORS(value, Object)
9260 // [dependent_code]: dependent code that depends on the type of the global
9262 DECL_ACCESSORS(dependent_code, DependentCode)
9264 inline PropertyDetails property_details();
9265 inline void set_property_details(PropertyDetails details);
9267 PropertyCellConstantType GetConstantType();
9269 // Computes the new type of the cell's contents for the given value, but
9270 // without actually modifying the details.
9271 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9272 Handle<Object> value,
9273 PropertyDetails details);
9274 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9275 Handle<Object> value, PropertyDetails details);
9277 static Handle<PropertyCell> InvalidateEntry(
9278 Handle<GlobalDictionary> dictionary, int entry);
9280 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9281 Handle<Object> new_value);
9283 DECLARE_CAST(PropertyCell)
9285 // Dispatched behavior.
9286 DECLARE_PRINTER(PropertyCell)
9287 DECLARE_VERIFIER(PropertyCell)
9289 // Layout description.
9290 static const int kDetailsOffset = HeapObject::kHeaderSize;
9291 static const int kValueOffset = kDetailsOffset + kPointerSize;
9292 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9293 static const int kSize = kDependentCodeOffset + kPointerSize;
9295 static const int kPointerFieldsBeginOffset = kValueOffset;
9296 static const int kPointerFieldsEndOffset = kSize;
9298 typedef FixedBodyDescriptor<kValueOffset,
9300 kSize> BodyDescriptor;
9303 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9307 class WeakCell : public HeapObject {
9309 inline Object* value() const;
9311 // This should not be called by anyone except GC.
9312 inline void clear();
9314 // This should not be called by anyone except allocator.
9315 inline void initialize(HeapObject* value);
9317 inline bool cleared() const;
9319 DECL_ACCESSORS(next, Object)
9321 inline void clear_next(Heap* heap);
9323 inline bool next_cleared();
9325 DECLARE_CAST(WeakCell)
9327 DECLARE_PRINTER(WeakCell)
9328 DECLARE_VERIFIER(WeakCell)
9330 // Layout description.
9331 static const int kValueOffset = HeapObject::kHeaderSize;
9332 static const int kNextOffset = kValueOffset + kPointerSize;
9333 static const int kSize = kNextOffset + kPointerSize;
9335 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9338 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9342 // The JSProxy describes EcmaScript Harmony proxies
9343 class JSProxy: public JSReceiver {
9345 // [handler]: The handler property.
9346 DECL_ACCESSORS(handler, Object)
9348 // [hash]: The hash code property (undefined if not initialized yet).
9349 DECL_ACCESSORS(hash, Object)
9351 DECLARE_CAST(JSProxy)
9353 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9354 Handle<JSProxy> proxy,
9355 Handle<Object> receiver,
9358 // If the handler defines an accessor property with a setter, invoke it.
9359 // If it defines an accessor property without a setter, or a data property
9360 // that is read-only, throw. In all these cases set '*done' to true,
9361 // otherwise set it to false.
9363 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9364 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9365 Handle<Object> value, LanguageMode language_mode, bool* done);
9367 MUST_USE_RESULT static Maybe<PropertyAttributes>
9368 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9369 Handle<Object> receiver,
9371 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9372 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9373 Handle<Object> value, LanguageMode language_mode);
9375 // Turn the proxy into an (empty) JSObject.
9376 static void Fix(Handle<JSProxy> proxy);
9378 // Initializes the body after the handler slot.
9379 inline void InitializeBody(int object_size, Object* value);
9381 // Invoke a trap by name. If the trap does not exist on this's handler,
9382 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9383 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9384 Handle<JSProxy> proxy,
9386 Handle<Object> derived_trap,
9388 Handle<Object> args[]);
9390 // Dispatched behavior.
9391 DECLARE_PRINTER(JSProxy)
9392 DECLARE_VERIFIER(JSProxy)
9394 // Layout description. We add padding so that a proxy has the same
9395 // size as a virgin JSObject. This is essential for becoming a JSObject
9397 static const int kHandlerOffset = HeapObject::kHeaderSize;
9398 static const int kHashOffset = kHandlerOffset + kPointerSize;
9399 static const int kPaddingOffset = kHashOffset + kPointerSize;
9400 static const int kSize = JSObject::kHeaderSize;
9401 static const int kHeaderSize = kPaddingOffset;
9402 static const int kPaddingSize = kSize - kPaddingOffset;
9404 STATIC_ASSERT(kPaddingSize >= 0);
9406 typedef FixedBodyDescriptor<kHandlerOffset,
9408 kSize> BodyDescriptor;
9411 friend class JSReceiver;
9413 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9414 Handle<JSProxy> proxy, Handle<Name> name);
9416 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9417 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9419 MUST_USE_RESULT Object* GetIdentityHash();
9421 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9423 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9427 class JSFunctionProxy: public JSProxy {
9429 // [call_trap]: The call trap.
9430 DECL_ACCESSORS(call_trap, JSReceiver)
9432 // [construct_trap]: The construct trap.
9433 DECL_ACCESSORS(construct_trap, Object)
9435 DECLARE_CAST(JSFunctionProxy)
9437 // Dispatched behavior.
9438 DECLARE_PRINTER(JSFunctionProxy)
9439 DECLARE_VERIFIER(JSFunctionProxy)
9441 // Layout description.
9442 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9443 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9444 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9445 static const int kSize = JSFunction::kSize;
9446 static const int kPaddingSize = kSize - kPaddingOffset;
9448 STATIC_ASSERT(kPaddingSize >= 0);
9450 typedef FixedBodyDescriptor<kHandlerOffset,
9451 kConstructTrapOffset + kPointerSize,
9452 kSize> BodyDescriptor;
9455 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9459 class JSCollection : public JSObject {
9461 // [table]: the backing hash table
9462 DECL_ACCESSORS(table, Object)
9464 static const int kTableOffset = JSObject::kHeaderSize;
9465 static const int kSize = kTableOffset + kPointerSize;
9468 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9472 // The JSSet describes EcmaScript Harmony sets
9473 class JSSet : public JSCollection {
9477 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9478 static void Clear(Handle<JSSet> set);
9480 // Dispatched behavior.
9481 DECLARE_PRINTER(JSSet)
9482 DECLARE_VERIFIER(JSSet)
9485 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9489 // The JSMap describes EcmaScript Harmony maps
9490 class JSMap : public JSCollection {
9494 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9495 static void Clear(Handle<JSMap> map);
9497 // Dispatched behavior.
9498 DECLARE_PRINTER(JSMap)
9499 DECLARE_VERIFIER(JSMap)
9502 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9506 // OrderedHashTableIterator is an iterator that iterates over the keys and
9507 // values of an OrderedHashTable.
9509 // The iterator has a reference to the underlying OrderedHashTable data,
9510 // [table], as well as the current [index] the iterator is at.
9512 // When the OrderedHashTable is rehashed it adds a reference from the old table
9513 // to the new table as well as storing enough data about the changes so that the
9514 // iterator [index] can be adjusted accordingly.
9516 // When the [Next] result from the iterator is requested, the iterator checks if
9517 // there is a newer table that it needs to transition to.
9518 template<class Derived, class TableType>
9519 class OrderedHashTableIterator: public JSObject {
9521 // [table]: the backing hash table mapping keys to values.
9522 DECL_ACCESSORS(table, Object)
9524 // [index]: The index into the data table.
9525 DECL_ACCESSORS(index, Object)
9527 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9528 DECL_ACCESSORS(kind, Object)
9531 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9534 static const int kTableOffset = JSObject::kHeaderSize;
9535 static const int kIndexOffset = kTableOffset + kPointerSize;
9536 static const int kKindOffset = kIndexOffset + kPointerSize;
9537 static const int kSize = kKindOffset + kPointerSize;
9545 // Whether the iterator has more elements. This needs to be called before
9546 // calling |CurrentKey| and/or |CurrentValue|.
9549 // Move the index forward one.
9551 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9554 // Populates the array with the next key and value and then moves the iterator
9556 // This returns the |kind| or 0 if the iterator is already at the end.
9557 Smi* Next(JSArray* value_array);
9559 // Returns the current key of the iterator. This should only be called when
9560 // |HasMore| returns true.
9561 inline Object* CurrentKey();
9564 // Transitions the iterator to the non obsolete backing store. This is a NOP
9565 // if the [table] is not obsolete.
9568 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9572 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9575 // Dispatched behavior.
9576 DECLARE_PRINTER(JSSetIterator)
9577 DECLARE_VERIFIER(JSSetIterator)
9579 DECLARE_CAST(JSSetIterator)
9581 // Called by |Next| to populate the array. This allows the subclasses to
9582 // populate the array differently.
9583 inline void PopulateValueArray(FixedArray* array);
9586 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9590 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9593 // Dispatched behavior.
9594 DECLARE_PRINTER(JSMapIterator)
9595 DECLARE_VERIFIER(JSMapIterator)
9597 DECLARE_CAST(JSMapIterator)
9599 // Called by |Next| to populate the array. This allows the subclasses to
9600 // populate the array differently.
9601 inline void PopulateValueArray(FixedArray* array);
9604 // Returns the current value of the iterator. This should only be called when
9605 // |HasMore| returns true.
9606 inline Object* CurrentValue();
9608 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9612 // ES6 section 25.1.1.3 The IteratorResult Interface
9613 class JSIteratorResult final : public JSObject {
9615 // [done]: This is the result status of an iterator next method call. If the
9616 // end of the iterator was reached done is true. If the end was not reached
9617 // done is false and a [value] is available.
9618 DECL_ACCESSORS(done, Object)
9620 // [value]: If [done] is false, this is the current iteration element value.
9621 // If [done] is true, this is the return value of the iterator, if it supplied
9622 // one. If the iterator does not have a return value, value is undefined.
9623 // In that case, the value property may be absent from the conforming object
9624 // if it does not inherit an explicit value property.
9625 DECL_ACCESSORS(value, Object)
9627 // Dispatched behavior.
9628 DECLARE_PRINTER(JSIteratorResult)
9629 DECLARE_VERIFIER(JSIteratorResult)
9631 DECLARE_CAST(JSIteratorResult)
9633 static const int kValueOffset = JSObject::kHeaderSize;
9634 static const int kDoneOffset = kValueOffset + kPointerSize;
9635 static const int kSize = kDoneOffset + kPointerSize;
9637 // Indices of in-object properties.
9638 static const int kValueIndex = 0;
9639 static const int kDoneIndex = 1;
9642 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9646 // Base class for both JSWeakMap and JSWeakSet
9647 class JSWeakCollection: public JSObject {
9649 // [table]: the backing hash table mapping keys to values.
9650 DECL_ACCESSORS(table, Object)
9652 // [next]: linked list of encountered weak maps during GC.
9653 DECL_ACCESSORS(next, Object)
9655 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9656 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9657 Handle<Object> value, int32_t hash);
9658 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9661 static const int kTableOffset = JSObject::kHeaderSize;
9662 static const int kNextOffset = kTableOffset + kPointerSize;
9663 static const int kSize = kNextOffset + kPointerSize;
9666 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9670 // The JSWeakMap describes EcmaScript Harmony weak maps
9671 class JSWeakMap: public JSWeakCollection {
9673 DECLARE_CAST(JSWeakMap)
9675 // Dispatched behavior.
9676 DECLARE_PRINTER(JSWeakMap)
9677 DECLARE_VERIFIER(JSWeakMap)
9680 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9684 // The JSWeakSet describes EcmaScript Harmony weak sets
9685 class JSWeakSet: public JSWeakCollection {
9687 DECLARE_CAST(JSWeakSet)
9689 // Dispatched behavior.
9690 DECLARE_PRINTER(JSWeakSet)
9691 DECLARE_VERIFIER(JSWeakSet)
9694 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9698 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9699 enum class SharedFlag { kNotShared, kShared };
9702 class JSArrayBuffer: public JSObject {
9704 // [backing_store]: backing memory for this array
9705 DECL_ACCESSORS(backing_store, void)
9707 // [byte_length]: length in bytes
9708 DECL_ACCESSORS(byte_length, Object)
9710 inline uint32_t bit_field() const;
9711 inline void set_bit_field(uint32_t bits);
9713 inline bool is_external();
9714 inline void set_is_external(bool value);
9716 inline bool is_neuterable();
9717 inline void set_is_neuterable(bool value);
9719 inline bool was_neutered();
9720 inline void set_was_neutered(bool value);
9722 inline bool is_shared();
9723 inline void set_is_shared(bool value);
9725 DECLARE_CAST(JSArrayBuffer)
9729 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9730 bool is_external, void* data, size_t allocated_length,
9731 SharedFlag shared = SharedFlag::kNotShared);
9733 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9734 Isolate* isolate, size_t allocated_length,
9735 bool initialize = true,
9736 SharedFlag shared = SharedFlag::kNotShared);
9738 // Dispatched behavior.
9739 DECLARE_PRINTER(JSArrayBuffer)
9740 DECLARE_VERIFIER(JSArrayBuffer)
9742 static const int kByteLengthOffset = JSObject::kHeaderSize;
9744 // NOTE: GC will visit objects fields:
9745 // 1. From JSObject::BodyDescriptor::kStartOffset to kByteLengthOffset +
9747 // 2. From start of the internal fields and up to the end of them
9748 static const int kBackingStoreOffset = kByteLengthOffset + kPointerSize;
9749 static const int kBitFieldSlot = kBackingStoreOffset + kPointerSize;
9750 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9751 static const int kBitFieldOffset = kBitFieldSlot;
9753 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9755 static const int kSize = kBitFieldSlot + kPointerSize;
9757 static const int kSizeWithInternalFields =
9758 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9760 template <typename StaticVisitor>
9761 static inline void JSArrayBufferIterateBody(Heap* heap, HeapObject* obj);
9763 static inline void JSArrayBufferIterateBody(HeapObject* obj,
9766 class IsExternal : public BitField<bool, 1, 1> {};
9767 class IsNeuterable : public BitField<bool, 2, 1> {};
9768 class WasNeutered : public BitField<bool, 3, 1> {};
9769 class IsShared : public BitField<bool, 4, 1> {};
9772 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9776 class JSArrayBufferView: public JSObject {
9778 // [buffer]: ArrayBuffer that this typed array views.
9779 DECL_ACCESSORS(buffer, Object)
9781 // [byte_offset]: offset of typed array in bytes.
9782 DECL_ACCESSORS(byte_offset, Object)
9784 // [byte_length]: length of typed array in bytes.
9785 DECL_ACCESSORS(byte_length, Object)
9787 DECLARE_CAST(JSArrayBufferView)
9789 DECLARE_VERIFIER(JSArrayBufferView)
9791 inline bool WasNeutered() const;
9793 static const int kBufferOffset = JSObject::kHeaderSize;
9794 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9795 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9796 static const int kViewSize = kByteLengthOffset + kPointerSize;
9800 DECL_ACCESSORS(raw_byte_offset, Object)
9801 DECL_ACCESSORS(raw_byte_length, Object)
9804 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9808 class JSTypedArray: public JSArrayBufferView {
9810 // [length]: length of typed array in elements.
9811 DECL_ACCESSORS(length, Object)
9812 inline uint32_t length_value() const;
9814 DECLARE_CAST(JSTypedArray)
9816 ExternalArrayType type();
9817 size_t element_size();
9819 Handle<JSArrayBuffer> GetBuffer();
9821 // Dispatched behavior.
9822 DECLARE_PRINTER(JSTypedArray)
9823 DECLARE_VERIFIER(JSTypedArray)
9825 static const int kLengthOffset = kViewSize + kPointerSize;
9826 static const int kSize = kLengthOffset + kPointerSize;
9828 static const int kSizeWithInternalFields =
9829 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9832 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9833 Handle<JSTypedArray> typed_array);
9835 DECL_ACCESSORS(raw_length, Object)
9838 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9842 class JSDataView: public JSArrayBufferView {
9844 DECLARE_CAST(JSDataView)
9846 // Dispatched behavior.
9847 DECLARE_PRINTER(JSDataView)
9848 DECLARE_VERIFIER(JSDataView)
9850 static const int kSize = kViewSize;
9852 static const int kSizeWithInternalFields =
9853 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9856 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9860 // Foreign describes objects pointing from JavaScript to C structures.
9861 class Foreign: public HeapObject {
9863 // [address]: field containing the address.
9864 inline Address foreign_address();
9865 inline void set_foreign_address(Address value);
9867 DECLARE_CAST(Foreign)
9869 // Dispatched behavior.
9870 inline void ForeignIterateBody(ObjectVisitor* v);
9872 template<typename StaticVisitor>
9873 inline void ForeignIterateBody();
9875 // Dispatched behavior.
9876 DECLARE_PRINTER(Foreign)
9877 DECLARE_VERIFIER(Foreign)
9879 // Layout description.
9881 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9882 static const int kSize = kForeignAddressOffset + kPointerSize;
9884 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9887 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9891 // The JSArray describes JavaScript Arrays
9892 // Such an array can be in one of two modes:
9893 // - fast, backing storage is a FixedArray and length <= elements.length();
9894 // Please note: push and pop can be used to grow and shrink the array.
9895 // - slow, backing storage is a HashTable with numbers as keys.
9896 class JSArray: public JSObject {
9898 // [length]: The length property.
9899 DECL_ACCESSORS(length, Object)
9901 // Overload the length setter to skip write barrier when the length
9902 // is set to a smi. This matches the set function on FixedArray.
9903 inline void set_length(Smi* length);
9905 static bool HasReadOnlyLength(Handle<JSArray> array);
9906 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9907 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9909 // Initialize the array with the given capacity. The function may
9910 // fail due to out-of-memory situations, but only if the requested
9911 // capacity is non-zero.
9912 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9914 // If the JSArray has fast elements, and new_length would result in
9915 // normalization, returns true.
9916 bool SetLengthWouldNormalize(uint32_t new_length);
9917 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9919 // Initializes the array to a certain length.
9920 inline bool AllowsSetLength();
9922 static void SetLength(Handle<JSArray> array, uint32_t length);
9923 // Same as above but will also queue splice records if |array| is observed.
9924 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9927 // Set the content of the array to the content of storage.
9928 static inline void SetContent(Handle<JSArray> array,
9929 Handle<FixedArrayBase> storage);
9931 DECLARE_CAST(JSArray)
9933 // Dispatched behavior.
9934 DECLARE_PRINTER(JSArray)
9935 DECLARE_VERIFIER(JSArray)
9937 // Number of element slots to pre-allocate for an empty array.
9938 static const int kPreallocatedArrayElements = 4;
9940 // Layout description.
9941 static const int kLengthOffset = JSObject::kHeaderSize;
9942 static const int kSize = kLengthOffset + kPointerSize;
9945 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9949 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9950 Handle<Map> initial_map);
9953 // JSRegExpResult is just a JSArray with a specific initial map.
9954 // This initial map adds in-object properties for "index" and "input"
9955 // properties, as assigned by RegExp.prototype.exec, which allows
9956 // faster creation of RegExp exec results.
9957 // This class just holds constants used when creating the result.
9958 // After creation the result must be treated as a JSArray in all regards.
9959 class JSRegExpResult: public JSArray {
9961 // Offsets of object fields.
9962 static const int kIndexOffset = JSArray::kSize;
9963 static const int kInputOffset = kIndexOffset + kPointerSize;
9964 static const int kSize = kInputOffset + kPointerSize;
9965 // Indices of in-object properties.
9966 static const int kIndexIndex = 0;
9967 static const int kInputIndex = 1;
9969 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9973 class AccessorInfo: public Struct {
9975 DECL_ACCESSORS(name, Object)
9976 DECL_INT_ACCESSORS(flag)
9977 DECL_ACCESSORS(expected_receiver_type, Object)
9979 inline bool all_can_read();
9980 inline void set_all_can_read(bool value);
9982 inline bool all_can_write();
9983 inline void set_all_can_write(bool value);
9985 inline bool is_special_data_property();
9986 inline void set_is_special_data_property(bool value);
9988 inline PropertyAttributes property_attributes();
9989 inline void set_property_attributes(PropertyAttributes attributes);
9991 // Checks whether the given receiver is compatible with this accessor.
9992 static bool IsCompatibleReceiverMap(Isolate* isolate,
9993 Handle<AccessorInfo> info,
9995 inline bool IsCompatibleReceiver(Object* receiver);
9997 DECLARE_CAST(AccessorInfo)
9999 // Dispatched behavior.
10000 DECLARE_VERIFIER(AccessorInfo)
10002 // Append all descriptors to the array that are not already there.
10003 // Return number added.
10004 static int AppendUnique(Handle<Object> descriptors,
10005 Handle<FixedArray> array,
10006 int valid_descriptors);
10008 static const int kNameOffset = HeapObject::kHeaderSize;
10009 static const int kFlagOffset = kNameOffset + kPointerSize;
10010 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10011 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10014 inline bool HasExpectedReceiverType();
10016 // Bit positions in flag.
10017 static const int kAllCanReadBit = 0;
10018 static const int kAllCanWriteBit = 1;
10019 static const int kSpecialDataProperty = 2;
10020 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10022 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10026 // An accessor must have a getter, but can have no setter.
10028 // When setting a property, V8 searches accessors in prototypes.
10029 // If an accessor was found and it does not have a setter,
10030 // the request is ignored.
10032 // If the accessor in the prototype has the READ_ONLY property attribute, then
10033 // a new value is added to the derived object when the property is set.
10034 // This shadows the accessor in the prototype.
10035 class ExecutableAccessorInfo: public AccessorInfo {
10037 DECL_ACCESSORS(getter, Object)
10038 DECL_ACCESSORS(setter, Object)
10039 DECL_ACCESSORS(data, Object)
10041 DECLARE_CAST(ExecutableAccessorInfo)
10043 // Dispatched behavior.
10044 DECLARE_PRINTER(ExecutableAccessorInfo)
10045 DECLARE_VERIFIER(ExecutableAccessorInfo)
10047 static const int kGetterOffset = AccessorInfo::kSize;
10048 static const int kSetterOffset = kGetterOffset + kPointerSize;
10049 static const int kDataOffset = kSetterOffset + kPointerSize;
10050 static const int kSize = kDataOffset + kPointerSize;
10052 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10055 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10059 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10060 // accessor can either be
10061 // * a pointer to a JavaScript function or proxy: a real accessor
10062 // * undefined: considered an accessor by the spec, too, strangely enough
10063 // * the hole: an accessor which has not been set
10064 // * a pointer to a map: a transition used to ensure map sharing
10065 class AccessorPair: public Struct {
10067 DECL_ACCESSORS(getter, Object)
10068 DECL_ACCESSORS(setter, Object)
10070 DECLARE_CAST(AccessorPair)
10072 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10074 inline Object* get(AccessorComponent component);
10075 inline void set(AccessorComponent component, Object* value);
10077 // Note: Returns undefined instead in case of a hole.
10078 Object* GetComponent(AccessorComponent component);
10080 // Set both components, skipping arguments which are a JavaScript null.
10081 inline void SetComponents(Object* getter, Object* setter);
10083 inline bool Equals(AccessorPair* pair);
10084 inline bool Equals(Object* getter_value, Object* setter_value);
10086 inline bool ContainsAccessor();
10088 // Dispatched behavior.
10089 DECLARE_PRINTER(AccessorPair)
10090 DECLARE_VERIFIER(AccessorPair)
10092 static const int kGetterOffset = HeapObject::kHeaderSize;
10093 static const int kSetterOffset = kGetterOffset + kPointerSize;
10094 static const int kSize = kSetterOffset + kPointerSize;
10097 // Strangely enough, in addition to functions and harmony proxies, the spec
10098 // requires us to consider undefined as a kind of accessor, too:
10100 // Object.defineProperty(obj, "foo", {get: undefined});
10101 // assertTrue("foo" in obj);
10102 inline bool IsJSAccessor(Object* obj);
10104 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10108 class AccessCheckInfo: public Struct {
10110 DECL_ACCESSORS(named_callback, Object)
10111 DECL_ACCESSORS(indexed_callback, Object)
10112 DECL_ACCESSORS(data, Object)
10114 DECLARE_CAST(AccessCheckInfo)
10116 // Dispatched behavior.
10117 DECLARE_PRINTER(AccessCheckInfo)
10118 DECLARE_VERIFIER(AccessCheckInfo)
10120 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10121 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10122 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10123 static const int kSize = kDataOffset + kPointerSize;
10126 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10130 class InterceptorInfo: public Struct {
10132 DECL_ACCESSORS(getter, Object)
10133 DECL_ACCESSORS(setter, Object)
10134 DECL_ACCESSORS(query, Object)
10135 DECL_ACCESSORS(deleter, Object)
10136 DECL_ACCESSORS(enumerator, Object)
10137 DECL_ACCESSORS(data, Object)
10138 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10139 DECL_BOOLEAN_ACCESSORS(all_can_read)
10140 DECL_BOOLEAN_ACCESSORS(non_masking)
10142 inline int flags() const;
10143 inline void set_flags(int flags);
10145 DECLARE_CAST(InterceptorInfo)
10147 // Dispatched behavior.
10148 DECLARE_PRINTER(InterceptorInfo)
10149 DECLARE_VERIFIER(InterceptorInfo)
10151 static const int kGetterOffset = HeapObject::kHeaderSize;
10152 static const int kSetterOffset = kGetterOffset + kPointerSize;
10153 static const int kQueryOffset = kSetterOffset + kPointerSize;
10154 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10155 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10156 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10157 static const int kFlagsOffset = kDataOffset + kPointerSize;
10158 static const int kSize = kFlagsOffset + kPointerSize;
10160 static const int kCanInterceptSymbolsBit = 0;
10161 static const int kAllCanReadBit = 1;
10162 static const int kNonMasking = 2;
10165 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10169 class CallHandlerInfo: public Struct {
10171 DECL_ACCESSORS(callback, Object)
10172 DECL_ACCESSORS(data, Object)
10174 DECLARE_CAST(CallHandlerInfo)
10176 // Dispatched behavior.
10177 DECLARE_PRINTER(CallHandlerInfo)
10178 DECLARE_VERIFIER(CallHandlerInfo)
10180 static const int kCallbackOffset = HeapObject::kHeaderSize;
10181 static const int kDataOffset = kCallbackOffset + kPointerSize;
10182 static const int kSize = kDataOffset + kPointerSize;
10185 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10189 class TemplateInfo: public Struct {
10191 DECL_ACCESSORS(tag, Object)
10192 inline int number_of_properties() const;
10193 inline void set_number_of_properties(int value);
10194 DECL_ACCESSORS(property_list, Object)
10195 DECL_ACCESSORS(property_accessors, Object)
10197 DECLARE_VERIFIER(TemplateInfo)
10199 static const int kTagOffset = HeapObject::kHeaderSize;
10200 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10201 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10202 static const int kPropertyAccessorsOffset =
10203 kPropertyListOffset + kPointerSize;
10204 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10207 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10211 class FunctionTemplateInfo: public TemplateInfo {
10213 DECL_ACCESSORS(serial_number, Object)
10214 DECL_ACCESSORS(call_code, Object)
10215 DECL_ACCESSORS(prototype_template, Object)
10216 DECL_ACCESSORS(parent_template, Object)
10217 DECL_ACCESSORS(named_property_handler, Object)
10218 DECL_ACCESSORS(indexed_property_handler, Object)
10219 DECL_ACCESSORS(instance_template, Object)
10220 DECL_ACCESSORS(class_name, Object)
10221 DECL_ACCESSORS(signature, Object)
10222 DECL_ACCESSORS(instance_call_handler, Object)
10223 DECL_ACCESSORS(access_check_info, Object)
10224 DECL_INT_ACCESSORS(flag)
10226 inline int length() const;
10227 inline void set_length(int value);
10229 // Following properties use flag bits.
10230 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10231 DECL_BOOLEAN_ACCESSORS(undetectable)
10232 // If the bit is set, object instances created by this function
10233 // requires access check.
10234 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10235 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10236 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10237 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10238 DECL_BOOLEAN_ACCESSORS(instantiated)
10239 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10241 DECLARE_CAST(FunctionTemplateInfo)
10243 // Dispatched behavior.
10244 DECLARE_PRINTER(FunctionTemplateInfo)
10245 DECLARE_VERIFIER(FunctionTemplateInfo)
10247 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10248 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10249 static const int kPrototypeTemplateOffset =
10250 kCallCodeOffset + kPointerSize;
10251 static const int kParentTemplateOffset =
10252 kPrototypeTemplateOffset + kPointerSize;
10253 static const int kNamedPropertyHandlerOffset =
10254 kParentTemplateOffset + kPointerSize;
10255 static const int kIndexedPropertyHandlerOffset =
10256 kNamedPropertyHandlerOffset + kPointerSize;
10257 static const int kInstanceTemplateOffset =
10258 kIndexedPropertyHandlerOffset + kPointerSize;
10259 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10260 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10261 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10262 static const int kAccessCheckInfoOffset =
10263 kInstanceCallHandlerOffset + kPointerSize;
10264 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10265 static const int kLengthOffset = kFlagOffset + kPointerSize;
10266 static const int kSize = kLengthOffset + kPointerSize;
10268 // Returns true if |object| is an instance of this function template.
10269 bool IsTemplateFor(Object* object);
10270 bool IsTemplateFor(Map* map);
10272 // Returns the holder JSObject if the function can legally be called with this
10273 // receiver. Returns Heap::null_value() if the call is illegal.
10274 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10277 // Bit position in the flag, from least significant bit position.
10278 static const int kHiddenPrototypeBit = 0;
10279 static const int kUndetectableBit = 1;
10280 static const int kNeedsAccessCheckBit = 2;
10281 static const int kReadOnlyPrototypeBit = 3;
10282 static const int kRemovePrototypeBit = 4;
10283 static const int kDoNotCacheBit = 5;
10284 static const int kInstantiatedBit = 6;
10285 static const int kAcceptAnyReceiver = 7;
10287 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10291 class ObjectTemplateInfo: public TemplateInfo {
10293 DECL_ACCESSORS(constructor, Object)
10294 DECL_ACCESSORS(internal_field_count, Object)
10296 DECLARE_CAST(ObjectTemplateInfo)
10298 // Dispatched behavior.
10299 DECLARE_PRINTER(ObjectTemplateInfo)
10300 DECLARE_VERIFIER(ObjectTemplateInfo)
10302 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10303 static const int kInternalFieldCountOffset =
10304 kConstructorOffset + kPointerSize;
10305 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10309 class TypeSwitchInfo: public Struct {
10311 DECL_ACCESSORS(types, Object)
10313 DECLARE_CAST(TypeSwitchInfo)
10315 // Dispatched behavior.
10316 DECLARE_PRINTER(TypeSwitchInfo)
10317 DECLARE_VERIFIER(TypeSwitchInfo)
10319 static const int kTypesOffset = Struct::kHeaderSize;
10320 static const int kSize = kTypesOffset + kPointerSize;
10324 // The DebugInfo class holds additional information for a function being
10326 class DebugInfo: public Struct {
10328 // The shared function info for the source being debugged.
10329 DECL_ACCESSORS(shared, SharedFunctionInfo)
10330 // Code object for the patched code. This code object is the code object
10331 // currently active for the function.
10332 DECL_ACCESSORS(code, Code)
10333 // Fixed array holding status information for each active break point.
10334 DECL_ACCESSORS(break_points, FixedArray)
10336 // Check if there is a break point at a code position.
10337 bool HasBreakPoint(int code_position);
10338 // Get the break point info object for a code position.
10339 Object* GetBreakPointInfo(int code_position);
10340 // Clear a break point.
10341 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10343 Handle<Object> break_point_object);
10344 // Set a break point.
10345 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10346 int source_position, int statement_position,
10347 Handle<Object> break_point_object);
10348 // Get the break point objects for a code position.
10349 Handle<Object> GetBreakPointObjects(int code_position);
10350 // Find the break point info holding this break point object.
10351 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10352 Handle<Object> break_point_object);
10353 // Get the number of break points for this function.
10354 int GetBreakPointCount();
10356 DECLARE_CAST(DebugInfo)
10358 // Dispatched behavior.
10359 DECLARE_PRINTER(DebugInfo)
10360 DECLARE_VERIFIER(DebugInfo)
10362 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10363 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10364 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10365 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10367 static const int kEstimatedNofBreakPointsInFunction = 16;
10370 static const int kNoBreakPointInfo = -1;
10372 // Lookup the index in the break_points array for a code position.
10373 int GetBreakPointInfoIndex(int code_position);
10375 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10379 // The BreakPointInfo class holds information for break points set in a
10380 // function. The DebugInfo object holds a BreakPointInfo object for each code
10381 // position with one or more break points.
10382 class BreakPointInfo: public Struct {
10384 // The position in the code for the break point.
10385 DECL_INT_ACCESSORS(code_position)
10386 // The position in the source for the break position.
10387 DECL_INT_ACCESSORS(source_position)
10388 // The position in the source for the last statement before this break
10390 DECL_INT_ACCESSORS(statement_position)
10391 // List of related JavaScript break points.
10392 DECL_ACCESSORS(break_point_objects, Object)
10394 // Removes a break point.
10395 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10396 Handle<Object> break_point_object);
10397 // Set a break point.
10398 static void SetBreakPoint(Handle<BreakPointInfo> info,
10399 Handle<Object> break_point_object);
10400 // Check if break point info has this break point object.
10401 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10402 Handle<Object> break_point_object);
10403 // Get the number of break points for this code position.
10404 int GetBreakPointCount();
10406 DECLARE_CAST(BreakPointInfo)
10408 // Dispatched behavior.
10409 DECLARE_PRINTER(BreakPointInfo)
10410 DECLARE_VERIFIER(BreakPointInfo)
10412 static const int kCodePositionIndex = Struct::kHeaderSize;
10413 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10414 static const int kStatementPositionIndex =
10415 kSourcePositionIndex + kPointerSize;
10416 static const int kBreakPointObjectsIndex =
10417 kStatementPositionIndex + kPointerSize;
10418 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10421 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10425 #undef DECL_BOOLEAN_ACCESSORS
10426 #undef DECL_ACCESSORS
10427 #undef DECLARE_CAST
10428 #undef DECLARE_VERIFIER
10430 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10431 V(kStringTable, "string_table", "(Internalized strings)") \
10432 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10433 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10434 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10435 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10436 V(kTop, "top", "(Isolate)") \
10437 V(kRelocatable, "relocatable", "(Relocatable)") \
10438 V(kDebug, "debug", "(Debugger)") \
10439 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10440 V(kHandleScope, "handlescope", "(Handle scope)") \
10441 V(kBuiltins, "builtins", "(Builtins)") \
10442 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10443 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10444 V(kThreadManager, "threadmanager", "(Thread manager)") \
10445 V(kStrongRoots, "strong roots", "(Strong roots)") \
10446 V(kExtensions, "Extensions", "(Extensions)")
10448 class VisitorSynchronization : public AllStatic {
10450 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10452 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10455 #undef DECLARE_ENUM
10457 static const char* const kTags[kNumberOfSyncTags];
10458 static const char* const kTagNames[kNumberOfSyncTags];
10461 // Abstract base class for visiting, and optionally modifying, the
10462 // pointers contained in Objects. Used in GC and serialization/deserialization.
10463 class ObjectVisitor BASE_EMBEDDED {
10465 virtual ~ObjectVisitor() {}
10467 // Visits a contiguous arrays of pointers in the half-open range
10468 // [start, end). Any or all of the values may be modified on return.
10469 virtual void VisitPointers(Object** start, Object** end) = 0;
10471 // Handy shorthand for visiting a single pointer.
10472 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10474 // Visit weak next_code_link in Code object.
10475 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10477 // To allow lazy clearing of inline caches the visitor has
10478 // a rich interface for iterating over Code objects..
10480 // Visits a code target in the instruction stream.
10481 virtual void VisitCodeTarget(RelocInfo* rinfo);
10483 // Visits a code entry in a JS function.
10484 virtual void VisitCodeEntry(Address entry_address);
10486 // Visits a global property cell reference in the instruction stream.
10487 virtual void VisitCell(RelocInfo* rinfo);
10489 // Visits a runtime entry in the instruction stream.
10490 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10492 // Visits the resource of an one-byte or two-byte string.
10493 virtual void VisitExternalOneByteString(
10494 v8::String::ExternalOneByteStringResource** resource) {}
10495 virtual void VisitExternalTwoByteString(
10496 v8::String::ExternalStringResource** resource) {}
10498 // Visits a debug call target in the instruction stream.
10499 virtual void VisitDebugTarget(RelocInfo* rinfo);
10501 // Visits the byte sequence in a function's prologue that contains information
10502 // about the code's age.
10503 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10505 // Visit pointer embedded into a code object.
10506 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10508 // Visits an external reference embedded into a code object.
10509 virtual void VisitExternalReference(RelocInfo* rinfo);
10511 // Visits an external reference.
10512 virtual void VisitExternalReference(Address* p) {}
10514 // Visits an (encoded) internal reference.
10515 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10517 // Visits a handle that has an embedder-assigned class ID.
10518 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10520 // Intended for serialization/deserialization checking: insert, or
10521 // check for the presence of, a tag at this position in the stream.
10522 // Also used for marking up GC roots in heap snapshots.
10523 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10527 class StructBodyDescriptor : public
10528 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10530 static inline int SizeOf(Map* map, HeapObject* object);
10534 // BooleanBit is a helper class for setting and getting a bit in an integer.
10535 class BooleanBit : public AllStatic {
10537 static inline bool get(int value, int bit_position) {
10538 return (value & (1 << bit_position)) != 0;
10541 static inline int set(int value, int bit_position, bool v) {
10543 value |= (1 << bit_position);
10545 value &= ~(1 << bit_position);
10552 class KeyAccumulator final BASE_EMBEDDED {
10554 explicit KeyAccumulator(Isolate* isolate) : isolate_(isolate), length_(0) {}
10556 void AddKey(Handle<Object> key, int check_limit);
10557 void AddKeys(Handle<FixedArray> array, FixedArray::KeyFilter filter);
10558 void AddKeys(Handle<JSObject> array, FixedArray::KeyFilter filter);
10559 void PrepareForComparisons(int count);
10560 Handle<FixedArray> GetKeys();
10562 int GetLength() { return length_; }
10565 void EnsureCapacity(int capacity);
10569 Handle<FixedArray> keys_;
10570 Handle<OrderedHashSet> set_;
10572 DISALLOW_COPY_AND_ASSIGN(KeyAccumulator);
10574 } } // namespace v8::internal
10576 #endif // V8_OBJECTS_H_