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
812 #define DECL_BOOLEAN_ACCESSORS(name) \
813 inline bool name() const; \
814 inline void set_##name(bool value); \
817 #define DECL_ACCESSORS(name, type) \
818 inline type* name() const; \
819 inline void set_##name(type* value, \
820 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
823 #define DECLARE_CAST(type) \
824 INLINE(static type* cast(Object* object)); \
825 INLINE(static const type* cast(const Object* object));
829 class AllocationSite;
830 class AllocationSiteCreationContext;
831 class AllocationSiteUsageContext;
834 class ElementsAccessor;
835 class FixedArrayBase;
836 class FunctionLiteral;
838 class JSBuiltinsObject;
839 class LayoutDescriptor;
840 class LookupIterator;
841 class ObjectHashTable;
844 class SafepointEntry;
845 class SharedFunctionInfo;
847 class TypeFeedbackInfo;
848 class TypeFeedbackVector;
851 // We cannot just say "class HeapType;" if it is created from a template... =8-?
852 template<class> class TypeImpl;
853 struct HeapTypeConfig;
854 typedef TypeImpl<HeapTypeConfig> HeapType;
857 // A template-ized version of the IsXXX functions.
858 template <class C> inline bool Is(Object* obj);
861 #define DECLARE_VERIFIER(Name) void Name##Verify();
863 #define DECLARE_VERIFIER(Name)
867 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
869 #define DECLARE_PRINTER(Name)
873 #define OBJECT_TYPE_LIST(V) \
878 #define HEAP_OBJECT_TYPE_LIST(V) \
880 V(MutableHeapNumber) \
899 V(ExternalTwoByteString) \
900 V(ExternalOneByteString) \
901 V(SeqTwoByteString) \
902 V(SeqOneByteString) \
903 V(InternalizedString) \
906 V(FixedTypedArrayBase) \
909 V(FixedUint16Array) \
911 V(FixedUint32Array) \
913 V(FixedFloat32Array) \
914 V(FixedFloat64Array) \
915 V(FixedUint8ClampedArray) \
921 V(JSContextExtensionObject) \
922 V(JSGeneratorObject) \
924 V(LayoutDescriptor) \
928 V(TypeFeedbackVector) \
929 V(DeoptimizationInputData) \
930 V(DeoptimizationOutputData) \
934 V(FixedDoubleArray) \
938 V(ScriptContextTable) \
944 V(SharedFunctionInfo) \
953 V(JSArrayBufferView) \
962 V(JSIteratorResult) \
963 V(JSWeakCollection) \
970 V(NormalizedMapCache) \
971 V(CompilationCacheTable) \
972 V(CodeCacheHashTable) \
973 V(PolymorphicCodeCacheHashTable) \
978 V(JSBuiltinsObject) \
980 V(UndetectableObject) \
981 V(AccessCheckNeeded) \
989 // Object is the abstract superclass for all classes in the
991 // Object does not use any virtual functions to avoid the
992 // allocation of the C++ vtable.
993 // Since both Smi and HeapObject are subclasses of Object no
994 // data members can be present in Object.
998 bool IsObject() const { return true; }
1000 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1001 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1002 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1003 #undef IS_TYPE_FUNCTION_DECL
1005 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1006 // a keyed store is of the form a[expression] = foo.
1007 enum StoreFromKeyed {
1008 MAY_BE_STORE_FROM_KEYED,
1009 CERTAINLY_NOT_STORE_FROM_KEYED
1012 INLINE(bool IsFixedArrayBase() const);
1013 INLINE(bool IsExternal() const);
1014 INLINE(bool IsAccessorInfo() const);
1016 INLINE(bool IsStruct() const);
1017 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1018 INLINE(bool Is##Name() const);
1019 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1020 #undef DECLARE_STRUCT_PREDICATE
1022 // ES6, section 7.2.3 IsCallable.
1023 INLINE(bool IsCallable() const);
1025 INLINE(bool IsSpecObject()) const;
1026 // TODO(rossberg): IsSpecFunction should be removed in favor of IsCallable.
1027 INLINE(bool IsSpecFunction()) const;
1028 INLINE(bool IsTemplateInfo()) const;
1029 INLINE(bool IsNameDictionary() const);
1030 INLINE(bool IsGlobalDictionary() const);
1031 INLINE(bool IsSeededNumberDictionary() const);
1032 INLINE(bool IsUnseededNumberDictionary() const);
1033 INLINE(bool IsOrderedHashSet() const);
1034 INLINE(bool IsOrderedHashMap() const);
1035 static bool IsPromise(Handle<Object> object);
1038 INLINE(bool IsUndefined() const);
1039 INLINE(bool IsNull() const);
1040 INLINE(bool IsTheHole() const);
1041 INLINE(bool IsException() const);
1042 INLINE(bool IsUninitialized() const);
1043 INLINE(bool IsTrue() const);
1044 INLINE(bool IsFalse() const);
1045 INLINE(bool IsArgumentsMarker() const);
1047 // Filler objects (fillers and free space objects).
1048 INLINE(bool IsFiller() const);
1050 // Extract the number.
1051 inline double Number() const;
1052 INLINE(bool IsNaN() const);
1053 INLINE(bool IsMinusZero() const);
1054 bool ToInt32(int32_t* value);
1055 bool ToUint32(uint32_t* value);
1057 inline Representation OptimalRepresentation();
1059 inline ElementsKind OptimalElementsKind();
1061 inline bool FitsRepresentation(Representation representation);
1063 // Checks whether two valid primitive encodings of a property name resolve to
1064 // the same logical property. E.g., the smi 1, the string "1" and the double
1065 // 1 all refer to the same property, so this helper will return true.
1066 inline bool KeyEquals(Object* other);
1068 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1070 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1071 Handle<Object> object,
1072 Representation representation);
1074 inline static Handle<Object> WrapForRead(Isolate* isolate,
1075 Handle<Object> object,
1076 Representation representation);
1078 // Returns true if the object is of the correct type to be used as a
1079 // implementation of a JSObject's elements.
1080 inline bool HasValidElements();
1082 inline bool HasSpecificClassOf(String* name);
1084 bool BooleanValue(); // ECMA-262 9.2.
1086 // ES6 section 7.2.12 Abstract Equality Comparison
1087 MUST_USE_RESULT static Maybe<bool> Equals(Handle<Object> x, Handle<Object> y);
1089 // ES6 section 7.2.13 Strict Equality Comparison
1090 bool StrictEquals(Object* that);
1092 // Convert to a JSObject if needed.
1093 // native_context is used when creating wrapper object.
1094 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1095 Handle<Object> object);
1096 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1097 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1099 // ES6 section 7.1.14 ToPropertyKey
1100 MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1101 Handle<Object> input);
1103 // ES6 section 7.1.1 ToPrimitive
1104 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1105 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1107 // ES6 section 7.1.3 ToNumber
1108 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Handle<Object> input);
1110 // ES6 section 7.1.12 ToString
1111 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1112 Handle<Object> input);
1114 // ES6 section 7.3.9 GetMethod
1115 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1116 Handle<JSReceiver> receiver, Handle<Name> name);
1118 // ES6 section 12.5.6 The typeof Operator
1119 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1121 // ES6 section 12.6 Multiplicative Operators
1122 MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1123 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1124 Strength strength = Strength::WEAK);
1125 MUST_USE_RESULT static MaybeHandle<Object> Divide(
1126 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1127 Strength strength = Strength::WEAK);
1128 MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1129 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1130 Strength strength = Strength::WEAK);
1132 // ES6 section 12.7 Additive Operators
1133 MUST_USE_RESULT static MaybeHandle<Object> Add(
1134 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1135 Strength strength = Strength::WEAK);
1136 MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1137 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1138 Strength strength = Strength::WEAK);
1140 // ES6 section 12.8 Bitwise Shift Operators
1141 MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1142 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1143 Strength strength = Strength::WEAK);
1144 MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1145 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1146 Strength strength = Strength::WEAK);
1147 MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1148 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1149 Strength strength = Strength::WEAK);
1151 // ES6 section 12.11 Binary Bitwise Operators
1152 MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1153 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1154 Strength strength = Strength::WEAK);
1155 MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1156 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1157 Strength strength = Strength::WEAK);
1158 MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1159 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1160 Strength strength = Strength::WEAK);
1162 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1163 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1165 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1166 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1167 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1168 LanguageMode language_mode,
1169 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1171 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1172 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1173 StoreFromKeyed store_mode);
1175 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1176 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1177 StoreFromKeyed store_mode);
1179 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1180 LookupIterator* it, LanguageMode language_mode);
1181 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1182 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1183 LanguageMode language_mode);
1184 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1185 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1186 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1187 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1188 Handle<Object> value, LanguageMode language_mode);
1189 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1190 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1191 LanguageMode language_mode);
1192 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1193 LookupIterator* it, Handle<Object> value);
1194 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1195 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1196 LanguageMode language_mode, StoreFromKeyed store_mode);
1197 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1198 Handle<Object> object, Handle<Name> name,
1199 LanguageMode language_mode = SLOPPY);
1200 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1201 Isolate* isolate, Handle<Object> object, const char* key,
1202 LanguageMode language_mode = SLOPPY);
1203 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1204 Handle<Object> object, Handle<Name> name,
1205 LanguageMode language_mode = SLOPPY);
1207 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1208 LookupIterator* it, LanguageMode language_mode);
1209 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1210 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1212 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1213 Handle<Object> receiver,
1214 Handle<JSReceiver> getter);
1215 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1216 Handle<Object> receiver,
1217 Handle<JSReceiver> setter,
1218 Handle<Object> value);
1220 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1221 Isolate* isolate, Handle<Object> object, uint32_t index,
1222 LanguageMode language_mode = SLOPPY);
1224 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1225 Isolate* isolate, Handle<Object> object, uint32_t index,
1226 Handle<Object> value, LanguageMode language_mode);
1228 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1229 Isolate* isolate, Handle<Object> receiver);
1231 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1233 // Returns the permanent hash code associated with this object. May return
1234 // undefined if not yet created.
1237 // Returns undefined for JSObjects, but returns the hash code for simple
1238 // objects. This avoids a double lookup in the cases where we know we will
1239 // add the hash to the JSObject if it does not already exist.
1240 Object* GetSimpleHash();
1242 // Returns the permanent hash code associated with this object depending on
1243 // the actual object type. May create and store a hash code if needed and none
1245 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1247 // Checks whether this object has the same value as the given one. This
1248 // function is implemented according to ES5, section 9.12 and can be used
1249 // to implement the Harmony "egal" function.
1250 bool SameValue(Object* other);
1252 // Checks whether this object has the same value as the given one.
1253 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1254 // This function is implemented according to ES6, section 7.2.4 and is used
1255 // by ES6 Map and Set.
1256 bool SameValueZero(Object* other);
1258 // Tries to convert an object to an array length. Returns true and sets the
1259 // output parameter if it succeeds.
1260 inline bool ToArrayLength(uint32_t* index);
1262 // Tries to convert an object to an array index. Returns true and sets the
1263 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1264 // allow kMaxUInt32.
1265 inline bool ToArrayIndex(uint32_t* index);
1267 // Returns true if this is a JSValue containing a string and the index is
1268 // < the length of the string. Used to implement [] on strings.
1269 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1271 DECLARE_VERIFIER(Object)
1273 // Verify a pointer is a valid object pointer.
1274 static void VerifyPointer(Object* p);
1277 inline void VerifyApiCallResultType();
1279 // Prints this object without details.
1280 void ShortPrint(FILE* out = stdout);
1282 // Prints this object without details to a message accumulator.
1283 void ShortPrint(StringStream* accumulator);
1285 void ShortPrint(std::ostream& os); // NOLINT
1287 DECLARE_CAST(Object)
1289 // Layout description.
1290 static const int kHeaderSize = 0; // Object does not take up any space.
1293 // For our gdb macros, we should perhaps change these in the future.
1296 // Prints this object with details.
1297 void Print(std::ostream& os); // NOLINT
1299 void Print() { ShortPrint(); }
1300 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1304 friend class LookupIterator;
1305 friend class PrototypeIterator;
1307 // Return the map of the root of object's prototype chain.
1308 Map* GetRootMap(Isolate* isolate);
1310 // Helper for SetProperty and SetSuperProperty.
1311 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1312 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1313 StoreFromKeyed store_mode, bool* found);
1315 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1319 // In objects.h to be usable without objects-inl.h inclusion.
1320 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1321 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1325 explicit Brief(const Object* const v) : value(v) {}
1326 const Object* value;
1330 std::ostream& operator<<(std::ostream& os, const Brief& v);
1333 // Smi represents integer Numbers that can be stored in 31 bits.
1334 // Smis are immediate which means they are NOT allocated in the heap.
1335 // The this pointer has the following format: [31 bit signed int] 0
1336 // For long smis it has the following format:
1337 // [32 bit signed int] [31 bits zero padding] 0
1338 // Smi stands for small integer.
1339 class Smi: public Object {
1341 // Returns the integer value.
1342 inline int value() const { return Internals::SmiValue(this); }
1344 // Convert a value to a Smi object.
1345 static inline Smi* FromInt(int value) {
1346 DCHECK(Smi::IsValid(value));
1347 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1350 static inline Smi* FromIntptr(intptr_t value) {
1351 DCHECK(Smi::IsValid(value));
1352 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1353 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1356 // Returns whether value can be represented in a Smi.
1357 static inline bool IsValid(intptr_t value) {
1358 bool result = Internals::IsValidSmi(value);
1359 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1365 // Dispatched behavior.
1366 void SmiPrint(std::ostream& os) const; // NOLINT
1367 DECLARE_VERIFIER(Smi)
1369 static const int kMinValue =
1370 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1371 static const int kMaxValue = -(kMinValue + 1);
1374 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1378 // Heap objects typically have a map pointer in their first word. However,
1379 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1380 // encoded in the first word. The class MapWord is an abstraction of the
1381 // value in a heap object's first word.
1382 class MapWord BASE_EMBEDDED {
1384 // Normal state: the map word contains a map pointer.
1386 // Create a map word from a map pointer.
1387 static inline MapWord FromMap(const Map* map);
1389 // View this map word as a map pointer.
1390 inline Map* ToMap();
1393 // Scavenge collection: the map word of live objects in the from space
1394 // contains a forwarding address (a heap object pointer in the to space).
1396 // True if this map word is a forwarding address for a scavenge
1397 // collection. Only valid during a scavenge collection (specifically,
1398 // when all map words are heap object pointers, i.e. not during a full GC).
1399 inline bool IsForwardingAddress();
1401 // Create a map word from a forwarding address.
1402 static inline MapWord FromForwardingAddress(HeapObject* object);
1404 // View this map word as a forwarding address.
1405 inline HeapObject* ToForwardingAddress();
1407 static inline MapWord FromRawValue(uintptr_t value) {
1408 return MapWord(value);
1411 inline uintptr_t ToRawValue() {
1416 // HeapObject calls the private constructor and directly reads the value.
1417 friend class HeapObject;
1419 explicit MapWord(uintptr_t value) : value_(value) {}
1425 // The content of an heap object (except for the map pointer). kTaggedValues
1426 // objects can contain both heap pointers and Smis, kMixedValues can contain
1427 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1428 // objects can contain raw values and Smis.
1429 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1432 // HeapObject is the superclass for all classes describing heap allocated
1434 class HeapObject: public Object {
1436 // [map]: Contains a map which contains the object's reflective
1438 inline Map* map() const;
1439 inline void set_map(Map* value);
1440 // The no-write-barrier version. This is OK if the object is white and in
1441 // new space, or if the value is an immortal immutable object, like the maps
1442 // of primitive (non-JS) objects like strings, heap numbers etc.
1443 inline void set_map_no_write_barrier(Map* value);
1445 // Get the map using acquire load.
1446 inline Map* synchronized_map();
1447 inline MapWord synchronized_map_word() const;
1449 // Set the map using release store
1450 inline void synchronized_set_map(Map* value);
1451 inline void synchronized_set_map_no_write_barrier(Map* value);
1452 inline void synchronized_set_map_word(MapWord map_word);
1454 // During garbage collection, the map word of a heap object does not
1455 // necessarily contain a map pointer.
1456 inline MapWord map_word() const;
1457 inline void set_map_word(MapWord map_word);
1459 // The Heap the object was allocated in. Used also to access Isolate.
1460 inline Heap* GetHeap() const;
1462 // Convenience method to get current isolate.
1463 inline Isolate* GetIsolate() const;
1465 // Converts an address to a HeapObject pointer.
1466 static inline HeapObject* FromAddress(Address address) {
1467 DCHECK_TAG_ALIGNED(address);
1468 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1471 // Returns the address of this HeapObject.
1472 inline Address address() {
1473 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1476 // Iterates over pointers contained in the object (including the Map)
1477 void Iterate(ObjectVisitor* v);
1479 // Iterates over all pointers contained in the object except the
1480 // first map pointer. The object type is given in the first
1481 // parameter. This function does not access the map pointer in the
1482 // object, and so is safe to call while the map pointer is modified.
1483 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1485 // Returns the heap object's size in bytes
1488 // Indicates what type of values this heap object may contain.
1489 inline HeapObjectContents ContentType();
1491 // Given a heap object's map pointer, returns the heap size in bytes
1492 // Useful when the map pointer field is used for other purposes.
1494 inline int SizeFromMap(Map* map);
1496 // Returns the field at offset in obj, as a read/write Object* reference.
1497 // Does no checking, and is safe to use during GC, while maps are invalid.
1498 // Does not invoke write barrier, so should only be assigned to
1499 // during marking GC.
1500 static inline Object** RawField(HeapObject* obj, int offset);
1502 // Adds the |code| object related to |name| to the code cache of this map. If
1503 // this map is a dictionary map that is shared, the map copied and installed
1505 static void UpdateMapCodeCache(Handle<HeapObject> object,
1509 DECLARE_CAST(HeapObject)
1511 // Return the write barrier mode for this. Callers of this function
1512 // must be able to present a reference to an DisallowHeapAllocation
1513 // object as a sign that they are not going to use this function
1514 // from code that allocates and thus invalidates the returned write
1516 inline WriteBarrierMode GetWriteBarrierMode(
1517 const DisallowHeapAllocation& promise);
1519 // Dispatched behavior.
1520 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1522 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1524 DECLARE_PRINTER(HeapObject)
1525 DECLARE_VERIFIER(HeapObject)
1527 inline void VerifyObjectField(int offset);
1528 inline void VerifySmiField(int offset);
1530 // Verify a pointer is a valid HeapObject pointer that points to object
1531 // areas in the heap.
1532 static void VerifyHeapPointer(Object* p);
1535 inline AllocationAlignment RequiredAlignment();
1537 // Layout description.
1538 // First field in a heap object is map.
1539 static const int kMapOffset = Object::kHeaderSize;
1540 static const int kHeaderSize = kMapOffset + kPointerSize;
1542 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1545 // helpers for calling an ObjectVisitor to iterate over pointers in the
1546 // half-open range [start, end) specified as integer offsets
1547 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1548 // as above, for the single element at "offset"
1549 inline void IteratePointer(ObjectVisitor* v, int offset);
1550 // as above, for the next code link of a code object.
1551 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1554 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1558 // This class describes a body of an object of a fixed size
1559 // in which all pointer fields are located in the [start_offset, end_offset)
1561 template<int start_offset, int end_offset, int size>
1562 class FixedBodyDescriptor {
1564 static const int kStartOffset = start_offset;
1565 static const int kEndOffset = end_offset;
1566 static const int kSize = size;
1568 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1570 template<typename StaticVisitor>
1571 static inline void IterateBody(HeapObject* obj) {
1572 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1573 HeapObject::RawField(obj, end_offset));
1578 // This class describes a body of an object of a variable size
1579 // in which all pointer fields are located in the [start_offset, object_size)
1581 template<int start_offset>
1582 class FlexibleBodyDescriptor {
1584 static const int kStartOffset = start_offset;
1586 static inline void IterateBody(HeapObject* obj,
1590 template<typename StaticVisitor>
1591 static inline void IterateBody(HeapObject* obj, int object_size) {
1592 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1593 HeapObject::RawField(obj, object_size));
1598 // The HeapNumber class describes heap allocated numbers that cannot be
1599 // represented in a Smi (small integer)
1600 class HeapNumber: public HeapObject {
1602 // [value]: number value.
1603 inline double value() const;
1604 inline void set_value(double value);
1606 DECLARE_CAST(HeapNumber)
1608 // Dispatched behavior.
1609 bool HeapNumberBooleanValue();
1611 void HeapNumberPrint(std::ostream& os); // NOLINT
1612 DECLARE_VERIFIER(HeapNumber)
1614 inline int get_exponent();
1615 inline int get_sign();
1617 // Layout description.
1618 static const int kValueOffset = HeapObject::kHeaderSize;
1619 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1620 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1621 // words within double numbers are endian dependent and they are set
1623 #if defined(V8_TARGET_LITTLE_ENDIAN)
1624 static const int kMantissaOffset = kValueOffset;
1625 static const int kExponentOffset = kValueOffset + 4;
1626 #elif defined(V8_TARGET_BIG_ENDIAN)
1627 static const int kMantissaOffset = kValueOffset + 4;
1628 static const int kExponentOffset = kValueOffset;
1630 #error Unknown byte ordering
1633 static const int kSize = kValueOffset + kDoubleSize;
1634 static const uint32_t kSignMask = 0x80000000u;
1635 static const uint32_t kExponentMask = 0x7ff00000u;
1636 static const uint32_t kMantissaMask = 0xfffffu;
1637 static const int kMantissaBits = 52;
1638 static const int kExponentBits = 11;
1639 static const int kExponentBias = 1023;
1640 static const int kExponentShift = 20;
1641 static const int kInfinityOrNanExponent =
1642 (kExponentMask >> kExponentShift) - kExponentBias;
1643 static const int kMantissaBitsInTopWord = 20;
1644 static const int kNonMantissaBitsInTopWord = 12;
1647 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1651 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1652 class Simd128Value : public HeapObject {
1654 DECLARE_CAST(Simd128Value)
1656 DECLARE_PRINTER(Simd128Value)
1657 DECLARE_VERIFIER(Simd128Value)
1659 static Handle<String> ToString(Handle<Simd128Value> input);
1661 // Equality operations.
1662 inline bool Equals(Simd128Value* that);
1663 static inline bool Equals(Handle<Simd128Value> one, Handle<Simd128Value> two);
1665 // Checks that another instance is bit-wise equal.
1666 bool BitwiseEquals(const Simd128Value* other) const;
1667 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1668 uint32_t Hash() const;
1669 // Copies the 16 bytes of SIMD data to the destination address.
1670 void CopyBits(void* destination) const;
1672 // Layout description.
1673 static const int kValueOffset = HeapObject::kHeaderSize;
1674 static const int kSize = kValueOffset + kSimd128Size;
1677 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1681 // V has parameters (TYPE, Type, type, lane count, lane type)
1682 #define SIMD128_TYPES(V) \
1683 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1684 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1685 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1686 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1687 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1688 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1689 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1690 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1691 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1692 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1694 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1695 class Type final : public Simd128Value { \
1697 inline lane_type get_lane(int lane) const; \
1698 inline void set_lane(int lane, lane_type value); \
1700 DECLARE_CAST(Type) \
1702 DECLARE_PRINTER(Type) \
1704 static Handle<String> ToString(Handle<Type> input); \
1706 inline bool Equals(Type* that); \
1709 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1711 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1712 #undef SIMD128_VALUE_CLASS
1715 enum EnsureElementsMode {
1716 DONT_ALLOW_DOUBLE_ELEMENTS,
1717 ALLOW_COPIED_DOUBLE_ELEMENTS,
1718 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1722 // Indicator for one component of an AccessorPair.
1723 enum AccessorComponent {
1729 // JSReceiver includes types on which properties can be defined, i.e.,
1730 // JSObject and JSProxy.
1731 class JSReceiver: public HeapObject {
1733 DECLARE_CAST(JSReceiver)
1735 // ES6 section 7.1.1 ToPrimitive
1736 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1737 Handle<JSReceiver> receiver,
1738 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1739 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1740 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1742 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1743 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1744 Handle<JSReceiver> object, Handle<Name> name);
1745 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1747 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1748 Handle<JSReceiver> object, uint32_t index);
1749 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1750 Handle<JSReceiver> object, uint32_t index);
1752 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1753 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1754 Handle<JSReceiver> object, Handle<Name> name,
1755 LanguageMode language_mode = SLOPPY);
1756 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1757 Handle<JSReceiver> object, Handle<Name> name,
1758 LanguageMode language_mode = SLOPPY);
1759 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1760 LookupIterator* it, LanguageMode language_mode);
1761 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1762 Handle<JSReceiver> object, uint32_t index,
1763 LanguageMode language_mode = SLOPPY);
1765 // Tests for the fast common case for property enumeration.
1766 bool IsSimpleEnum();
1768 // Returns the class name ([[Class]] property in the specification).
1769 String* class_name();
1771 // Returns the constructor name (the name (possibly, inferred name) of the
1772 // function that was used to instantiate the object).
1773 String* constructor_name();
1775 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1776 Handle<JSReceiver> object, Handle<Name> name);
1777 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1778 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1780 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1781 Handle<JSReceiver> object, uint32_t index);
1782 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1783 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1785 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1786 LookupIterator* it);
1789 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1791 static Handle<Object> GetDataProperty(LookupIterator* it);
1794 // Retrieves a permanent object identity hash code. The undefined value might
1795 // be returned in case no hash was created yet.
1796 inline Object* GetIdentityHash();
1798 // Retrieves a permanent object identity hash code. May create and store a
1799 // hash code if needed and none exists.
1800 inline static Handle<Smi> GetOrCreateIdentityHash(
1801 Handle<JSReceiver> object);
1803 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1805 // Computes the enumerable keys for a JSObject. Used for implementing
1806 // "for (n in object) { }".
1807 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1808 Handle<JSReceiver> object,
1809 KeyCollectionType type);
1812 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1816 // The JSObject describes real heap allocated JavaScript objects with
1818 // Note that the map of JSObject changes during execution to enable inline
1820 class JSObject: public JSReceiver {
1822 // [properties]: Backing storage for properties.
1823 // properties is a FixedArray in the fast case and a Dictionary in the
1825 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1826 inline void initialize_properties();
1827 inline bool HasFastProperties();
1828 // Gets slow properties for non-global objects.
1829 inline NameDictionary* property_dictionary();
1830 // Gets global object properties.
1831 inline GlobalDictionary* global_dictionary();
1833 // [elements]: The elements (properties with names that are integers).
1835 // Elements can be in two general modes: fast and slow. Each mode
1836 // corrensponds to a set of object representations of elements that
1837 // have something in common.
1839 // In the fast mode elements is a FixedArray and so each element can
1840 // be quickly accessed. This fact is used in the generated code. The
1841 // elements array can have one of three maps in this mode:
1842 // fixed_array_map, sloppy_arguments_elements_map or
1843 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1844 // the elements array may be shared by a few objects and so before
1845 // writing to any element the array must be copied. Use
1846 // EnsureWritableFastElements in this case.
1848 // In the slow mode the elements is either a NumberDictionary, a
1849 // FixedArray parameter map for a (sloppy) arguments object.
1850 DECL_ACCESSORS(elements, FixedArrayBase)
1851 inline void initialize_elements();
1852 static void ResetElements(Handle<JSObject> object);
1853 static inline void SetMapAndElements(Handle<JSObject> object,
1855 Handle<FixedArrayBase> elements);
1856 inline ElementsKind GetElementsKind();
1857 ElementsAccessor* GetElementsAccessor();
1858 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1859 inline bool HasFastSmiElements();
1860 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1861 inline bool HasFastObjectElements();
1862 // Returns true if an object has elements of FAST_ELEMENTS or
1863 // FAST_SMI_ONLY_ELEMENTS.
1864 inline bool HasFastSmiOrObjectElements();
1865 // Returns true if an object has any of the fast elements kinds.
1866 inline bool HasFastElements();
1867 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1869 inline bool HasFastDoubleElements();
1870 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1872 inline bool HasFastHoleyElements();
1873 inline bool HasSloppyArgumentsElements();
1874 inline bool HasDictionaryElements();
1876 inline bool HasFixedTypedArrayElements();
1878 inline bool HasFixedUint8ClampedElements();
1879 inline bool HasFixedArrayElements();
1880 inline bool HasFixedInt8Elements();
1881 inline bool HasFixedUint8Elements();
1882 inline bool HasFixedInt16Elements();
1883 inline bool HasFixedUint16Elements();
1884 inline bool HasFixedInt32Elements();
1885 inline bool HasFixedUint32Elements();
1886 inline bool HasFixedFloat32Elements();
1887 inline bool HasFixedFloat64Elements();
1889 inline bool HasFastArgumentsElements();
1890 inline bool HasSlowArgumentsElements();
1891 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1893 // Requires: HasFastElements().
1894 static Handle<FixedArray> EnsureWritableFastElements(
1895 Handle<JSObject> object);
1897 // Collects elements starting at index 0.
1898 // Undefined values are placed after non-undefined values.
1899 // Returns the number of non-undefined values.
1900 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1902 // As PrepareElementsForSort, but only on objects where elements is
1903 // a dictionary, and it will stay a dictionary. Collates undefined and
1904 // unexisting elements below limit from position zero of the elements.
1905 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1908 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1909 LookupIterator* it, Handle<Object> value);
1911 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1912 // grant an exemption to ExecutableAccessor callbacks in some cases.
1913 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1915 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1916 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1917 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1919 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1920 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1921 PropertyAttributes attributes,
1922 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1924 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1925 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1926 PropertyAttributes attributes,
1927 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1929 // Equivalent to one of the above depending on whether |name| can be converted
1930 // to an array index.
1931 MUST_USE_RESULT static MaybeHandle<Object>
1932 DefinePropertyOrElementIgnoreAttributes(
1933 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1934 PropertyAttributes attributes = NONE,
1935 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1937 // Adds or reconfigures a property to attributes NONE. It will fail when it
1939 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1940 Handle<Object> value);
1942 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1943 Handle<Object> value, PropertyAttributes attributes);
1945 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1946 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1947 PropertyAttributes attributes);
1949 // Extend the receiver with a single fast property appeared first in the
1950 // passed map. This also extends the property backing store if necessary.
1951 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1953 // Migrates the given object to a map whose field representations are the
1954 // lowest upper bound of all known representations for that field.
1955 static void MigrateInstance(Handle<JSObject> instance);
1957 // Migrates the given object only if the target map is already available,
1958 // or returns false if such a map is not yet available.
1959 static bool TryMigrateInstance(Handle<JSObject> instance);
1961 // Sets the property value in a normalized object given (key, value, details).
1962 // Handles the special representation of JS global objects.
1963 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1964 Handle<Object> value,
1965 PropertyDetails details);
1966 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1967 Handle<Object> value,
1968 PropertyAttributes attributes);
1969 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1971 Handle<Object> value,
1972 PropertyAttributes attributes);
1974 static void OptimizeAsPrototype(Handle<JSObject> object,
1975 PrototypeOptimizationMode mode);
1976 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1977 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1978 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1979 static void InvalidatePrototypeChains(Map* map);
1981 // Alternative implementation of WeakFixedArray::NullCallback.
1982 class PrototypeRegistryCompactionCallback {
1984 static void Callback(Object* value, int old_index, int new_index);
1987 // Retrieve interceptors.
1988 InterceptorInfo* GetNamedInterceptor();
1989 InterceptorInfo* GetIndexedInterceptor();
1991 // Used from JSReceiver.
1992 MUST_USE_RESULT static Maybe<PropertyAttributes>
1993 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1994 MUST_USE_RESULT static Maybe<PropertyAttributes>
1995 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1997 // Retrieves an AccessorPair property from the given object. Might return
1998 // undefined if the property doesn't exist or is of a different kind.
1999 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
2000 Handle<JSObject> object,
2002 AccessorComponent component);
2004 // Defines an AccessorPair property on the given object.
2005 // TODO(mstarzinger): Rename to SetAccessor().
2006 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2008 Handle<Object> getter,
2009 Handle<Object> setter,
2010 PropertyAttributes attributes);
2012 // Defines an AccessorInfo property on the given object.
2013 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2014 Handle<JSObject> object,
2015 Handle<AccessorInfo> info);
2017 // The result must be checked first for exceptions. If there's no exception,
2018 // the output parameter |done| indicates whether the interceptor has a result
2020 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2021 LookupIterator* it, bool* done);
2023 // Accessors for hidden properties object.
2025 // Hidden properties are not own properties of the object itself.
2026 // Instead they are stored in an auxiliary structure kept as an own
2027 // property with a special name Heap::hidden_string(). But if the
2028 // receiver is a JSGlobalProxy then the auxiliary object is a property
2029 // of its prototype, and if it's a detached proxy, then you can't have
2030 // hidden properties.
2032 // Sets a hidden property on this object. Returns this object if successful,
2033 // undefined if called on a detached proxy.
2034 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2036 Handle<Object> value);
2037 // Gets the value of a hidden property with the given key. Returns the hole
2038 // if the property doesn't exist (or if called on a detached proxy),
2039 // otherwise returns the value set for the key.
2040 Object* GetHiddenProperty(Handle<Name> key);
2041 // Deletes a hidden property. Deleting a non-existing property is
2042 // considered successful.
2043 static void DeleteHiddenProperty(Handle<JSObject> object,
2045 // Returns true if the object has a property with the hidden string as name.
2046 static bool HasHiddenProperties(Handle<JSObject> object);
2048 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2050 static void ValidateElements(Handle<JSObject> object);
2052 // Makes sure that this object can contain HeapObject as elements.
2053 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2055 // Makes sure that this object can contain the specified elements.
2056 static inline void EnsureCanContainElements(
2057 Handle<JSObject> object,
2060 EnsureElementsMode mode);
2061 static inline void EnsureCanContainElements(
2062 Handle<JSObject> object,
2063 Handle<FixedArrayBase> elements,
2065 EnsureElementsMode mode);
2066 static void EnsureCanContainElements(
2067 Handle<JSObject> object,
2068 Arguments* arguments,
2071 EnsureElementsMode mode);
2073 // Would we convert a fast elements array to dictionary mode given
2074 // an access at key?
2075 bool WouldConvertToSlowElements(uint32_t index);
2077 // Computes the new capacity when expanding the elements of a JSObject.
2078 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2079 // (old_capacity + 50%) + 16
2080 return old_capacity + (old_capacity >> 1) + 16;
2083 // These methods do not perform access checks!
2084 static void UpdateAllocationSite(Handle<JSObject> object,
2085 ElementsKind to_kind);
2087 // Lookup interceptors are used for handling properties controlled by host
2089 inline bool HasNamedInterceptor();
2090 inline bool HasIndexedInterceptor();
2092 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2093 // by JSReceiver::GetKeys.
2094 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2095 Handle<JSObject> object,
2096 Handle<JSReceiver> receiver);
2097 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2098 Handle<JSObject> object,
2099 Handle<JSReceiver> receiver);
2101 // Support functions for v8 api (needed for correct interceptor behavior).
2102 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2103 Handle<JSObject> object, Handle<Name> name);
2104 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2105 Handle<JSObject> object, uint32_t index);
2106 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2107 Handle<JSObject> object, Handle<Name> name);
2109 // Get the header size for a JSObject. Used to compute the index of
2110 // internal fields as well as the number of internal fields.
2111 inline int GetHeaderSize();
2113 inline int GetInternalFieldCount();
2114 inline int GetInternalFieldOffset(int index);
2115 inline Object* GetInternalField(int index);
2116 inline void SetInternalField(int index, Object* value);
2117 inline void SetInternalField(int index, Smi* value);
2119 // Returns the number of properties on this object filtering out properties
2120 // with the specified attributes (ignoring interceptors).
2121 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2122 // Fill in details for properties into storage starting at the specified
2123 // index. Returns the number of properties added.
2124 int GetOwnPropertyNames(FixedArray* storage, int index,
2125 PropertyAttributes filter = NONE);
2127 // Returns the number of properties on this object filtering out properties
2128 // with the specified attributes (ignoring interceptors).
2129 int NumberOfOwnElements(PropertyAttributes filter);
2130 // Returns the number of enumerable elements (ignoring interceptors).
2131 int NumberOfEnumElements();
2132 // Returns the number of elements on this object filtering out elements
2133 // with the specified attributes (ignoring interceptors).
2134 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2135 // Count and fill in the enumerable elements into storage.
2136 // (storage->length() == NumberOfEnumElements()).
2137 // If storage is NULL, will count the elements without adding
2138 // them to any storage.
2139 // Returns the number of enumerable elements.
2140 int GetEnumElementKeys(FixedArray* storage);
2142 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2145 // Returns a new map with all transitions dropped from the object's current
2146 // map and the ElementsKind set.
2147 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2148 ElementsKind to_kind);
2149 static void TransitionElementsKind(Handle<JSObject> object,
2150 ElementsKind to_kind);
2152 // Always use this to migrate an object to a new map.
2153 // |expected_additional_properties| is only used for fast-to-slow transitions
2154 // and ignored otherwise.
2155 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2156 int expected_additional_properties = 0);
2158 // Convert the object to use the canonical dictionary
2159 // representation. If the object is expected to have additional properties
2160 // added this number can be indicated to have the backing store allocated to
2161 // an initial capacity for holding these properties.
2162 static void NormalizeProperties(Handle<JSObject> object,
2163 PropertyNormalizationMode mode,
2164 int expected_additional_properties,
2165 const char* reason);
2167 // Convert and update the elements backing store to be a
2168 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2169 static Handle<SeededNumberDictionary> NormalizeElements(
2170 Handle<JSObject> object);
2172 void RequireSlowElements(SeededNumberDictionary* dictionary);
2174 // Transform slow named properties to fast variants.
2175 static void MigrateSlowToFast(Handle<JSObject> object,
2176 int unused_property_fields, const char* reason);
2178 inline bool IsUnboxedDoubleField(FieldIndex index);
2180 // Access fast-case object properties at index.
2181 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2182 Representation representation,
2184 inline Object* RawFastPropertyAt(FieldIndex index);
2185 inline double RawFastDoublePropertyAt(FieldIndex index);
2187 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2188 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2189 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2190 inline void WriteToField(int descriptor, Object* value);
2192 // Access to in object properties.
2193 inline int GetInObjectPropertyOffset(int index);
2194 inline Object* InObjectPropertyAt(int index);
2195 inline Object* InObjectPropertyAtPut(int index,
2197 WriteBarrierMode mode
2198 = UPDATE_WRITE_BARRIER);
2200 // Set the object's prototype (only JSReceiver and null are allowed values).
2201 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2202 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2204 // Initializes the body after properties slot, properties slot is
2205 // initialized by set_properties. Fill the pre-allocated fields with
2206 // pre_allocated_value and the rest with filler_value.
2207 // Note: this call does not update write barrier, the caller is responsible
2208 // to ensure that |filler_value| can be collected without WB here.
2209 inline void InitializeBody(Map* map,
2210 Object* pre_allocated_value,
2211 Object* filler_value);
2213 // Check whether this object references another object
2214 bool ReferencesObject(Object* obj);
2216 // Disalow further properties to be added to the oject.
2217 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2218 Handle<JSObject> object);
2220 bool IsExtensible();
2223 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2225 // ES5 Object.freeze
2226 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2228 // Called the first time an object is observed with ES7 Object.observe.
2229 static void SetObserved(Handle<JSObject> object);
2232 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2234 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2235 Handle<JSObject> object,
2236 AllocationSiteUsageContext* site_context,
2237 DeepCopyHints hints = kNoHints);
2238 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2239 Handle<JSObject> object,
2240 AllocationSiteCreationContext* site_context);
2242 DECLARE_CAST(JSObject)
2244 // Dispatched behavior.
2245 void JSObjectShortPrint(StringStream* accumulator);
2246 DECLARE_PRINTER(JSObject)
2247 DECLARE_VERIFIER(JSObject)
2249 void PrintProperties(std::ostream& os); // NOLINT
2250 void PrintElements(std::ostream& os); // NOLINT
2252 #if defined(DEBUG) || defined(OBJECT_PRINT)
2253 void PrintTransitions(std::ostream& os); // NOLINT
2256 static void PrintElementsTransition(
2257 FILE* file, Handle<JSObject> object,
2258 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2259 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2261 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2264 // Structure for collecting spill information about JSObjects.
2265 class SpillInformation {
2269 int number_of_objects_;
2270 int number_of_objects_with_fast_properties_;
2271 int number_of_objects_with_fast_elements_;
2272 int number_of_fast_used_fields_;
2273 int number_of_fast_unused_fields_;
2274 int number_of_slow_used_properties_;
2275 int number_of_slow_unused_properties_;
2276 int number_of_fast_used_elements_;
2277 int number_of_fast_unused_elements_;
2278 int number_of_slow_used_elements_;
2279 int number_of_slow_unused_elements_;
2282 void IncrementSpillStatistics(SpillInformation* info);
2286 // If a GC was caused while constructing this object, the elements pointer
2287 // may point to a one pointer filler map. The object won't be rooted, but
2288 // our heap verification code could stumble across it.
2289 bool ElementsAreSafeToExamine();
2292 Object* SlowReverseLookup(Object* value);
2294 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2295 // Also maximal value of JSArray's length property.
2296 static const uint32_t kMaxElementCount = 0xffffffffu;
2298 // Constants for heuristics controlling conversion of fast elements
2299 // to slow elements.
2301 // Maximal gap that can be introduced by adding an element beyond
2302 // the current elements length.
2303 static const uint32_t kMaxGap = 1024;
2305 // Maximal length of fast elements array that won't be checked for
2306 // being dense enough on expansion.
2307 static const int kMaxUncheckedFastElementsLength = 5000;
2309 // Same as above but for old arrays. This limit is more strict. We
2310 // don't want to be wasteful with long lived objects.
2311 static const int kMaxUncheckedOldFastElementsLength = 500;
2313 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2314 // permissible values (see the DCHECK in heap.cc).
2315 static const int kInitialMaxFastElementArray = 100000;
2317 // This constant applies only to the initial map of "global.Object" and
2318 // not to arbitrary other JSObject maps.
2319 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2321 static const int kMaxInstanceSize = 255 * kPointerSize;
2322 // When extending the backing storage for property values, we increase
2323 // its size by more than the 1 entry necessary, so sequentially adding fields
2324 // to the same object requires fewer allocations and copies.
2325 static const int kFieldsAdded = 3;
2327 // Layout description.
2328 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2329 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2330 static const int kHeaderSize = kElementsOffset + kPointerSize;
2332 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2334 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2336 static inline int SizeOf(Map* map, HeapObject* object);
2339 Context* GetCreationContext();
2341 // Enqueue change record for Object.observe. May cause GC.
2342 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2343 Handle<JSObject> object, const char* type, Handle<Name> name,
2344 Handle<Object> old_value);
2346 // Gets the number of currently used elements.
2347 int GetFastElementsUsage();
2349 // Deletes an existing named property in a normalized object.
2350 static void DeleteNormalizedProperty(Handle<JSObject> object,
2351 Handle<Name> name, int entry);
2353 static bool AllCanRead(LookupIterator* it);
2354 static bool AllCanWrite(LookupIterator* it);
2357 friend class JSReceiver;
2358 friend class Object;
2360 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2361 static void MigrateFastToSlow(Handle<JSObject> object,
2362 Handle<Map> new_map,
2363 int expected_additional_properties);
2365 // Used from Object::GetProperty().
2366 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2367 LookupIterator* it);
2369 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2370 LookupIterator* it, Handle<Object> value);
2372 // Add a property to a slow-case object.
2373 static void AddSlowProperty(Handle<JSObject> object,
2375 Handle<Object> value,
2376 PropertyAttributes attributes);
2378 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2379 LookupIterator* it);
2381 bool ReferencesObjectFromElements(FixedArray* elements,
2385 // Return the hash table backing store or the inline stored identity hash,
2386 // whatever is found.
2387 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2389 // Return the hash table backing store for hidden properties. If there is no
2390 // backing store, allocate one.
2391 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2392 Handle<JSObject> object);
2394 // Set the hidden property backing store to either a hash table or
2395 // the inline-stored identity hash.
2396 static Handle<Object> SetHiddenPropertiesHashTable(
2397 Handle<JSObject> object,
2398 Handle<Object> value);
2400 MUST_USE_RESULT Object* GetIdentityHash();
2402 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2404 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2405 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2407 // Helper for fast versions of preventExtensions, seal, and freeze.
2408 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2409 template <PropertyAttributes attrs>
2410 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2411 Handle<JSObject> object);
2413 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2417 // Common superclass for FixedArrays that allow implementations to share
2418 // common accessors and some code paths.
2419 class FixedArrayBase: public HeapObject {
2421 // [length]: length of the array.
2422 inline int length() const;
2423 inline void set_length(int value);
2425 // Get and set the length using acquire loads and release stores.
2426 inline int synchronized_length() const;
2427 inline void synchronized_set_length(int value);
2429 DECLARE_CAST(FixedArrayBase)
2431 // Layout description.
2432 // Length is smi tagged when it is stored.
2433 static const int kLengthOffset = HeapObject::kHeaderSize;
2434 static const int kHeaderSize = kLengthOffset + kPointerSize;
2438 class FixedDoubleArray;
2439 class IncrementalMarking;
2442 // FixedArray describes fixed-sized arrays with element type Object*.
2443 class FixedArray: public FixedArrayBase {
2445 // Setter and getter for elements.
2446 inline Object* get(int index) const;
2447 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2448 // Setter that uses write barrier.
2449 inline void set(int index, Object* value);
2450 inline bool is_the_hole(int index);
2452 // Setter that doesn't need write barrier.
2453 inline void set(int index, Smi* value);
2454 // Setter with explicit barrier mode.
2455 inline void set(int index, Object* value, WriteBarrierMode mode);
2457 // Setters for frequently used oddballs located in old space.
2458 inline void set_undefined(int index);
2459 inline void set_null(int index);
2460 inline void set_the_hole(int index);
2462 inline Object** GetFirstElementAddress();
2463 inline bool ContainsOnlySmisOrHoles();
2465 // Gives access to raw memory which stores the array's data.
2466 inline Object** data_start();
2468 inline void FillWithHoles(int from, int to);
2470 // Shrink length and insert filler objects.
2471 void Shrink(int length);
2473 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2475 // Add the elements of a JSArray to this FixedArray.
2476 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2477 Handle<FixedArray> content, Handle<JSObject> array,
2478 KeyFilter filter = ALL_KEYS);
2480 // Computes the union of keys and return the result.
2481 // Used for implementing "for (n in object) { }"
2482 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2483 Handle<FixedArray> first,
2484 Handle<FixedArray> second);
2486 // Copy a sub array from the receiver to dest.
2487 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2489 // Garbage collection support.
2490 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2492 // Code Generation support.
2493 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2495 // Garbage collection support.
2496 inline Object** RawFieldOfElementAt(int index);
2498 DECLARE_CAST(FixedArray)
2500 // Maximal allowed size, in bytes, of a single FixedArray.
2501 // Prevents overflowing size computations, as well as extreme memory
2503 static const int kMaxSize = 128 * MB * kPointerSize;
2504 // Maximally allowed length of a FixedArray.
2505 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2507 // Dispatched behavior.
2508 DECLARE_PRINTER(FixedArray)
2509 DECLARE_VERIFIER(FixedArray)
2511 // Checks if two FixedArrays have identical contents.
2512 bool IsEqualTo(FixedArray* other);
2515 // Swap two elements in a pair of arrays. If this array and the
2516 // numbers array are the same object, the elements are only swapped
2518 void SwapPairs(FixedArray* numbers, int i, int j);
2520 // Sort prefix of this array and the numbers array as pairs wrt. the
2521 // numbers. If the numbers array and the this array are the same
2522 // object, the prefix of this array is sorted.
2523 void SortPairs(FixedArray* numbers, uint32_t len);
2525 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2527 static inline int SizeOf(Map* map, HeapObject* object);
2531 // Set operation on FixedArray without using write barriers. Can
2532 // only be used for storing old space objects or smis.
2533 static inline void NoWriteBarrierSet(FixedArray* array,
2537 // Set operation on FixedArray without incremental write barrier. Can
2538 // only be used if the object is guaranteed to be white (whiteness witness
2540 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2545 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2547 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2551 // FixedDoubleArray describes fixed-sized arrays with element type double.
2552 class FixedDoubleArray: public FixedArrayBase {
2554 // Setter and getter for elements.
2555 inline double get_scalar(int index);
2556 inline uint64_t get_representation(int index);
2557 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2558 inline void set(int index, double value);
2559 inline void set_the_hole(int index);
2561 // Checking for the hole.
2562 inline bool is_the_hole(int index);
2564 // Garbage collection support.
2565 inline static int SizeFor(int length) {
2566 return kHeaderSize + length * kDoubleSize;
2569 // Gives access to raw memory which stores the array's data.
2570 inline double* data_start();
2572 inline void FillWithHoles(int from, int to);
2574 // Code Generation support.
2575 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2577 DECLARE_CAST(FixedDoubleArray)
2579 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2580 // Prevents overflowing size computations, as well as extreme memory
2582 static const int kMaxSize = 512 * MB;
2583 // Maximally allowed length of a FixedArray.
2584 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2586 // Dispatched behavior.
2587 DECLARE_PRINTER(FixedDoubleArray)
2588 DECLARE_VERIFIER(FixedDoubleArray)
2591 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2595 class WeakFixedArray : public FixedArray {
2597 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2598 // This function does not check if the value exists already, callers must
2599 // ensure this themselves if necessary.
2600 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2601 Handle<HeapObject> value,
2602 int* assigned_index = NULL);
2604 // Returns true if an entry was found and removed.
2605 bool Remove(Handle<HeapObject> value);
2607 class NullCallback {
2609 static void Callback(Object* value, int old_index, int new_index) {}
2612 template <class CompactionCallback>
2615 inline Object* Get(int index) const;
2616 inline void Clear(int index);
2617 inline int Length() const;
2619 inline bool IsEmptySlot(int index) const;
2620 static Object* Empty() { return Smi::FromInt(0); }
2624 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2625 void Reset(Object* maybe_array);
2632 WeakFixedArray* list_;
2634 int last_used_index_;
2635 DisallowHeapAllocation no_gc_;
2637 DISALLOW_COPY_AND_ASSIGN(Iterator);
2640 DECLARE_CAST(WeakFixedArray)
2643 static const int kLastUsedIndexIndex = 0;
2644 static const int kFirstIndex = 1;
2646 static Handle<WeakFixedArray> Allocate(
2647 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2649 static void Set(Handle<WeakFixedArray> array, int index,
2650 Handle<HeapObject> value);
2651 inline void clear(int index);
2653 inline int last_used_index() const;
2654 inline void set_last_used_index(int index);
2656 // Disallow inherited setters.
2657 void set(int index, Smi* value);
2658 void set(int index, Object* value);
2659 void set(int index, Object* value, WriteBarrierMode mode);
2660 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2664 // Generic array grows dynamically with O(1) amortized insertion.
2665 class ArrayList : public FixedArray {
2669 // Use this if GC can delete elements from the array.
2670 kReloadLengthAfterAllocation,
2672 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2673 AddMode mode = kNone);
2674 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2675 Handle<Object> obj2, AddMode = kNone);
2676 inline int Length();
2677 inline void SetLength(int length);
2678 inline Object* Get(int index);
2679 inline Object** Slot(int index);
2680 inline void Set(int index, Object* obj);
2681 inline void Clear(int index, Object* undefined);
2682 DECLARE_CAST(ArrayList)
2685 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2686 static const int kLengthIndex = 0;
2687 static const int kFirstIndex = 1;
2688 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2692 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2693 // The format of the these objects is:
2694 // [0]: Number of descriptors
2695 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2696 // [0]: pointer to fixed array with enum cache
2697 // [1]: either Smi(0) or pointer to fixed array with indices
2699 // [2 + number of descriptors * kDescriptorSize]: start of slack
2700 class DescriptorArray: public FixedArray {
2702 // Returns true for both shared empty_descriptor_array and for smis, which the
2703 // map uses to encode additional bit fields when the descriptor array is not
2705 inline bool IsEmpty();
2707 // Returns the number of descriptors in the array.
2708 inline int number_of_descriptors();
2710 inline int number_of_descriptors_storage();
2712 inline int NumberOfSlackDescriptors();
2714 inline void SetNumberOfDescriptors(int number_of_descriptors);
2715 inline int number_of_entries();
2717 inline bool HasEnumCache();
2719 inline void CopyEnumCacheFrom(DescriptorArray* array);
2721 inline FixedArray* GetEnumCache();
2723 inline bool HasEnumIndicesCache();
2725 inline FixedArray* GetEnumIndicesCache();
2727 inline Object** GetEnumCacheSlot();
2729 void ClearEnumCache();
2731 // Initialize or change the enum cache,
2732 // using the supplied storage for the small "bridge".
2733 void SetEnumCache(FixedArray* bridge_storage,
2734 FixedArray* new_cache,
2735 Object* new_index_cache);
2737 bool CanHoldValue(int descriptor, Object* value);
2739 // Accessors for fetching instance descriptor at descriptor number.
2740 inline Name* GetKey(int descriptor_number);
2741 inline Object** GetKeySlot(int descriptor_number);
2742 inline Object* GetValue(int descriptor_number);
2743 inline void SetValue(int descriptor_number, Object* value);
2744 inline Object** GetValueSlot(int descriptor_number);
2745 static inline int GetValueOffset(int descriptor_number);
2746 inline Object** GetDescriptorStartSlot(int descriptor_number);
2747 inline Object** GetDescriptorEndSlot(int descriptor_number);
2748 inline PropertyDetails GetDetails(int descriptor_number);
2749 inline PropertyType GetType(int descriptor_number);
2750 inline int GetFieldIndex(int descriptor_number);
2751 inline HeapType* GetFieldType(int descriptor_number);
2752 inline Object* GetConstant(int descriptor_number);
2753 inline Object* GetCallbacksObject(int descriptor_number);
2754 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2756 inline Name* GetSortedKey(int descriptor_number);
2757 inline int GetSortedKeyIndex(int descriptor_number);
2758 inline void SetSortedKey(int pointer, int descriptor_number);
2759 inline void SetRepresentation(int descriptor_number,
2760 Representation representation);
2762 // Accessor for complete descriptor.
2763 inline void Get(int descriptor_number, Descriptor* desc);
2764 inline void Set(int descriptor_number, Descriptor* desc);
2765 void Replace(int descriptor_number, Descriptor* descriptor);
2767 // Append automatically sets the enumeration index. This should only be used
2768 // to add descriptors in bulk at the end, followed by sorting the descriptor
2770 inline void Append(Descriptor* desc);
2772 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2773 int enumeration_index,
2776 static Handle<DescriptorArray> CopyUpToAddAttributes(
2777 Handle<DescriptorArray> desc,
2778 int enumeration_index,
2779 PropertyAttributes attributes,
2782 // Sort the instance descriptors by the hash codes of their keys.
2785 // Search the instance descriptors for given name.
2786 INLINE(int Search(Name* name, int number_of_own_descriptors));
2788 // As the above, but uses DescriptorLookupCache and updates it when
2790 INLINE(int SearchWithCache(Name* name, Map* map));
2792 // Allocates a DescriptorArray, but returns the singleton
2793 // empty descriptor array object if number_of_descriptors is 0.
2794 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2795 int number_of_descriptors,
2798 DECLARE_CAST(DescriptorArray)
2800 // Constant for denoting key was not found.
2801 static const int kNotFound = -1;
2803 static const int kDescriptorLengthIndex = 0;
2804 static const int kEnumCacheIndex = 1;
2805 static const int kFirstIndex = 2;
2807 // The length of the "bridge" to the enum cache.
2808 static const int kEnumCacheBridgeLength = 2;
2809 static const int kEnumCacheBridgeCacheIndex = 0;
2810 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2812 // Layout description.
2813 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2814 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2815 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2817 // Layout description for the bridge array.
2818 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2820 // Layout of descriptor.
2821 static const int kDescriptorKey = 0;
2822 static const int kDescriptorDetails = 1;
2823 static const int kDescriptorValue = 2;
2824 static const int kDescriptorSize = 3;
2826 #if defined(DEBUG) || defined(OBJECT_PRINT)
2827 // For our gdb macros, we should perhaps change these in the future.
2830 // Print all the descriptors.
2831 void PrintDescriptors(std::ostream& os); // NOLINT
2835 // Is the descriptor array sorted and without duplicates?
2836 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2838 // Is the descriptor array consistent with the back pointers in targets?
2839 bool IsConsistentWithBackPointers(Map* current_map);
2841 // Are two DescriptorArrays equal?
2842 bool IsEqualTo(DescriptorArray* other);
2845 // Returns the fixed array length required to hold number_of_descriptors
2847 static int LengthFor(int number_of_descriptors) {
2848 return ToKeyIndex(number_of_descriptors);
2852 // WhitenessWitness is used to prove that a descriptor array is white
2853 // (unmarked), so incremental write barriers can be skipped because the
2854 // marking invariant cannot be broken and slots pointing into evacuation
2855 // candidates will be discovered when the object is scanned. A witness is
2856 // always stack-allocated right after creating an array. By allocating a
2857 // witness, incremental marking is globally disabled. The witness is then
2858 // passed along wherever needed to statically prove that the array is known to
2860 class WhitenessWitness {
2862 inline explicit WhitenessWitness(DescriptorArray* array);
2863 inline ~WhitenessWitness();
2866 IncrementalMarking* marking_;
2869 // An entry in a DescriptorArray, represented as an (array, index) pair.
2872 inline explicit Entry(DescriptorArray* descs, int index) :
2873 descs_(descs), index_(index) { }
2875 inline PropertyType type();
2876 inline Object* GetCallbackObject();
2879 DescriptorArray* descs_;
2883 // Conversion from descriptor number to array indices.
2884 static int ToKeyIndex(int descriptor_number) {
2885 return kFirstIndex +
2886 (descriptor_number * kDescriptorSize) +
2890 static int ToDetailsIndex(int descriptor_number) {
2891 return kFirstIndex +
2892 (descriptor_number * kDescriptorSize) +
2896 static int ToValueIndex(int descriptor_number) {
2897 return kFirstIndex +
2898 (descriptor_number * kDescriptorSize) +
2902 // Transfer a complete descriptor from the src descriptor array to this
2903 // descriptor array.
2904 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2906 inline void Set(int descriptor_number,
2908 const WhitenessWitness&);
2910 // Swap first and second descriptor.
2911 inline void SwapSortedKeys(int first, int second);
2913 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2917 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2919 template <SearchMode search_mode, typename T>
2920 inline int Search(T* array, Name* name, int valid_entries = 0,
2921 int* out_insertion_index = NULL);
2924 // HashTable is a subclass of FixedArray that implements a hash table
2925 // that uses open addressing and quadratic probing.
2927 // In order for the quadratic probing to work, elements that have not
2928 // yet been used and elements that have been deleted are
2929 // distinguished. Probing continues when deleted elements are
2930 // encountered and stops when unused elements are encountered.
2932 // - Elements with key == undefined have not been used yet.
2933 // - Elements with key == the_hole have been deleted.
2935 // The hash table class is parameterized with a Shape and a Key.
2936 // Shape must be a class with the following interface:
2937 // class ExampleShape {
2939 // // Tells whether key matches other.
2940 // static bool IsMatch(Key key, Object* other);
2941 // // Returns the hash value for key.
2942 // static uint32_t Hash(Key key);
2943 // // Returns the hash value for object.
2944 // static uint32_t HashForObject(Key key, Object* object);
2945 // // Convert key to an object.
2946 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2947 // // The prefix size indicates number of elements in the beginning
2948 // // of the backing storage.
2949 // static const int kPrefixSize = ..;
2950 // // The Element size indicates number of elements per entry.
2951 // static const int kEntrySize = ..;
2953 // The prefix size indicates an amount of memory in the
2954 // beginning of the backing storage that can be used for non-element
2955 // information by subclasses.
2957 template<typename Key>
2960 static const bool UsesSeed = false;
2961 static uint32_t Hash(Key key) { return 0; }
2962 static uint32_t SeededHash(Key key, uint32_t seed) {
2966 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2967 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2969 return HashForObject(key, object);
2974 class HashTableBase : public FixedArray {
2976 // Returns the number of elements in the hash table.
2977 inline int NumberOfElements();
2979 // Returns the number of deleted elements in the hash table.
2980 inline int NumberOfDeletedElements();
2982 // Returns the capacity of the hash table.
2983 inline int Capacity();
2985 // ElementAdded should be called whenever an element is added to a
2987 inline void ElementAdded();
2989 // ElementRemoved should be called whenever an element is removed from
2991 inline void ElementRemoved();
2992 inline void ElementsRemoved(int n);
2994 // Computes the required capacity for a table holding the given
2995 // number of elements. May be more than HashTable::kMaxCapacity.
2996 static inline int ComputeCapacity(int at_least_space_for);
2998 // Tells whether k is a real key. The hole and undefined are not allowed
2999 // as keys and can be used to indicate missing or deleted elements.
3000 inline bool IsKey(Object* k);
3002 // Compute the probe offset (quadratic probing).
3003 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3004 return (n + n * n) >> 1;
3007 static const int kNumberOfElementsIndex = 0;
3008 static const int kNumberOfDeletedElementsIndex = 1;
3009 static const int kCapacityIndex = 2;
3010 static const int kPrefixStartIndex = 3;
3012 // Constant used for denoting a absent entry.
3013 static const int kNotFound = -1;
3016 // Update the number of elements in the hash table.
3017 inline void SetNumberOfElements(int nof);
3019 // Update the number of deleted elements in the hash table.
3020 inline void SetNumberOfDeletedElements(int nod);
3022 // Returns probe entry.
3023 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3024 DCHECK(base::bits::IsPowerOfTwo32(size));
3025 return (hash + GetProbeOffset(number)) & (size - 1);
3028 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3029 return hash & (size - 1);
3032 inline static uint32_t NextProbe(
3033 uint32_t last, uint32_t number, uint32_t size) {
3034 return (last + number) & (size - 1);
3039 template <typename Derived, typename Shape, typename Key>
3040 class HashTable : public HashTableBase {
3043 inline uint32_t Hash(Key key) {
3044 if (Shape::UsesSeed) {
3045 return Shape::SeededHash(key, GetHeap()->HashSeed());
3047 return Shape::Hash(key);
3051 inline uint32_t HashForObject(Key key, Object* object) {
3052 if (Shape::UsesSeed) {
3053 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3055 return Shape::HashForObject(key, object);
3059 // Returns a new HashTable object.
3060 MUST_USE_RESULT static Handle<Derived> New(
3061 Isolate* isolate, int at_least_space_for,
3062 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3063 PretenureFlag pretenure = NOT_TENURED);
3065 DECLARE_CAST(HashTable)
3067 // Garbage collection support.
3068 void IteratePrefix(ObjectVisitor* visitor);
3069 void IterateElements(ObjectVisitor* visitor);
3071 // Find entry for key otherwise return kNotFound.
3072 inline int FindEntry(Key key);
3073 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3074 int FindEntry(Isolate* isolate, Key key);
3076 // Rehashes the table in-place.
3077 void Rehash(Key key);
3079 // Returns the key at entry.
3080 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3082 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3083 static const int kEntrySize = Shape::kEntrySize;
3084 static const int kElementsStartOffset =
3085 kHeaderSize + kElementsStartIndex * kPointerSize;
3086 static const int kCapacityOffset =
3087 kHeaderSize + kCapacityIndex * kPointerSize;
3089 // Returns the index for an entry (of the key)
3090 static inline int EntryToIndex(int entry) {
3091 return (entry * kEntrySize) + kElementsStartIndex;
3095 friend class ObjectHashTable;
3097 // Find the entry at which to insert element with the given key that
3098 // has the given hash value.
3099 uint32_t FindInsertionEntry(uint32_t hash);
3101 // Attempt to shrink hash table after removal of key.
3102 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3104 // Ensure enough space for n additional elements.
3105 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3106 Handle<Derived> table,
3109 PretenureFlag pretenure = NOT_TENURED);
3111 // Sets the capacity of the hash table.
3112 void SetCapacity(int capacity) {
3113 // To scale a computed hash code to fit within the hash table, we
3114 // use bit-wise AND with a mask, so the capacity must be positive
3116 DCHECK(capacity > 0);
3117 DCHECK(capacity <= kMaxCapacity);
3118 set(kCapacityIndex, Smi::FromInt(capacity));
3121 // Maximal capacity of HashTable. Based on maximal length of underlying
3122 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3124 static const int kMaxCapacity =
3125 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3128 // Returns _expected_ if one of entries given by the first _probe_ probes is
3129 // equal to _expected_. Otherwise, returns the entry given by the probe
3131 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3133 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3135 // Rehashes this hash-table into the new table.
3136 void Rehash(Handle<Derived> new_table, Key key);
3140 // HashTableKey is an abstract superclass for virtual key behavior.
3141 class HashTableKey {
3143 // Returns whether the other object matches this key.
3144 virtual bool IsMatch(Object* other) = 0;
3145 // Returns the hash value for this key.
3146 virtual uint32_t Hash() = 0;
3147 // Returns the hash value for object.
3148 virtual uint32_t HashForObject(Object* key) = 0;
3149 // Returns the key object for storing into the hash table.
3150 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3152 virtual ~HashTableKey() {}
3156 class StringTableShape : public BaseShape<HashTableKey*> {
3158 static inline bool IsMatch(HashTableKey* key, Object* value) {
3159 return key->IsMatch(value);
3162 static inline uint32_t Hash(HashTableKey* key) {
3166 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3167 return key->HashForObject(object);
3170 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3172 static const int kPrefixSize = 0;
3173 static const int kEntrySize = 1;
3176 class SeqOneByteString;
3180 // No special elements in the prefix and the element size is 1
3181 // because only the string itself (the key) needs to be stored.
3182 class StringTable: public HashTable<StringTable,
3186 // Find string in the string table. If it is not there yet, it is
3187 // added. The return value is the string found.
3188 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3189 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3190 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3192 // Tries to internalize given string and returns string handle on success
3193 // or an empty handle otherwise.
3194 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3196 Handle<String> string);
3198 // Looks up a string that is equal to the given string and returns
3199 // string handle if it is found, or an empty handle otherwise.
3200 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3202 Handle<String> str);
3203 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3208 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3210 DECLARE_CAST(StringTable)
3213 template <bool seq_one_byte>
3214 friend class JsonParser;
3216 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3220 template <typename Derived, typename Shape, typename Key>
3221 class Dictionary: public HashTable<Derived, Shape, Key> {
3222 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3225 // Returns the value at entry.
3226 Object* ValueAt(int entry) {
3227 return this->get(Derived::EntryToIndex(entry) + 1);
3230 // Set the value for entry.
3231 void ValueAtPut(int entry, Object* value) {
3232 this->set(Derived::EntryToIndex(entry) + 1, value);
3235 // Returns the property details for the property at entry.
3236 PropertyDetails DetailsAt(int entry) {
3237 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3240 // Set the details for entry.
3241 void DetailsAtPut(int entry, PropertyDetails value) {
3242 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3245 // Returns true if property at given entry is deleted.
3246 bool IsDeleted(int entry) {
3247 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3250 // Delete a property from the dictionary.
3251 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3253 // Attempt to shrink the dictionary after deletion of key.
3254 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3255 Handle<Derived> dictionary,
3257 return DerivedHashTable::Shrink(dictionary, key);
3261 // TODO(dcarney): templatize or move to SeededNumberDictionary
3262 void CopyValuesTo(FixedArray* elements);
3264 // Returns the number of elements in the dictionary filtering out properties
3265 // with the specified attributes.
3266 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3268 // Returns the number of enumerable elements in the dictionary.
3269 int NumberOfEnumElements() {
3270 return NumberOfElementsFilterAttributes(
3271 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3274 // Returns true if the dictionary contains any elements that are non-writable,
3275 // non-configurable, non-enumerable, or have getters/setters.
3276 bool HasComplexElements();
3278 enum SortMode { UNSORTED, SORTED };
3280 // Fill in details for properties into storage.
3281 // Returns the number of properties added.
3282 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3283 SortMode sort_mode);
3285 // Copies enumerable keys to preallocated fixed array.
3286 void CopyEnumKeysTo(FixedArray* storage);
3288 // Accessors for next enumeration index.
3289 void SetNextEnumerationIndex(int index) {
3291 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3294 int NextEnumerationIndex() {
3295 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3298 // Creates a new dictionary.
3299 MUST_USE_RESULT static Handle<Derived> New(
3301 int at_least_space_for,
3302 PretenureFlag pretenure = NOT_TENURED);
3304 // Ensure enough space for n additional elements.
3305 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3308 void Print(std::ostream& os); // NOLINT
3310 // Returns the key (slow).
3311 Object* SlowReverseLookup(Object* value);
3313 // Sets the entry to (key, value) pair.
3314 inline void SetEntry(int entry,
3316 Handle<Object> value);
3317 inline void SetEntry(int entry,
3319 Handle<Object> value,
3320 PropertyDetails details);
3322 MUST_USE_RESULT static Handle<Derived> Add(
3323 Handle<Derived> dictionary,
3325 Handle<Object> value,
3326 PropertyDetails details);
3328 // Returns iteration indices array for the |dictionary|.
3329 // Values are direct indices in the |HashTable| array.
3330 static Handle<FixedArray> BuildIterationIndicesArray(
3331 Handle<Derived> dictionary);
3334 // Generic at put operation.
3335 MUST_USE_RESULT static Handle<Derived> AtPut(
3336 Handle<Derived> dictionary,
3338 Handle<Object> value);
3340 // Add entry to dictionary.
3341 static void AddEntry(
3342 Handle<Derived> dictionary,
3344 Handle<Object> value,
3345 PropertyDetails details,
3348 // Generate new enumeration indices to avoid enumeration index overflow.
3349 // Returns iteration indices array for the |dictionary|.
3350 static Handle<FixedArray> GenerateNewEnumerationIndices(
3351 Handle<Derived> dictionary);
3352 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3353 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3357 template <typename Derived, typename Shape>
3358 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3359 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3362 // Find entry for key, otherwise return kNotFound. Optimized version of
3363 // HashTable::FindEntry.
3364 int FindEntry(Handle<Name> key);
3368 template <typename Key>
3369 class BaseDictionaryShape : public BaseShape<Key> {
3371 template <typename Dictionary>
3372 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3373 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3374 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3375 return PropertyDetails(
3376 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3379 template <typename Dictionary>
3380 static inline void DetailsAtPut(Dictionary* dict, int entry,
3381 PropertyDetails value) {
3382 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3383 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3386 template <typename Dictionary>
3387 static bool IsDeleted(Dictionary* dict, int entry) {
3391 template <typename Dictionary>
3392 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3393 Handle<Object> value, PropertyDetails details);
3397 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3399 static inline bool IsMatch(Handle<Name> key, Object* other);
3400 static inline uint32_t Hash(Handle<Name> key);
3401 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3402 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3403 static const int kPrefixSize = 2;
3404 static const int kEntrySize = 3;
3405 static const bool kIsEnumerable = true;
3409 class NameDictionary
3410 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3411 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3415 DECLARE_CAST(NameDictionary)
3417 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3418 Handle<NameDictionary> dictionary);
3422 class GlobalDictionaryShape : public NameDictionaryShape {
3424 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3426 template <typename Dictionary>
3427 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3429 template <typename Dictionary>
3430 static inline void DetailsAtPut(Dictionary* dict, int entry,
3431 PropertyDetails value);
3433 template <typename Dictionary>
3434 static bool IsDeleted(Dictionary* dict, int entry);
3436 template <typename Dictionary>
3437 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3438 Handle<Object> value, PropertyDetails details);
3442 class GlobalDictionary
3443 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3445 DECLARE_CAST(GlobalDictionary)
3449 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3451 static inline bool IsMatch(uint32_t key, Object* other);
3452 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3453 static const int kEntrySize = 3;
3454 static const bool kIsEnumerable = false;
3458 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3460 static const bool UsesSeed = true;
3461 static const int kPrefixSize = 2;
3463 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3464 static inline uint32_t SeededHashForObject(uint32_t key,
3470 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3472 static const int kPrefixSize = 0;
3474 static inline uint32_t Hash(uint32_t key);
3475 static inline uint32_t HashForObject(uint32_t key, Object* object);
3479 class SeededNumberDictionary
3480 : public Dictionary<SeededNumberDictionary,
3481 SeededNumberDictionaryShape,
3484 DECLARE_CAST(SeededNumberDictionary)
3486 // Type specific at put (default NONE attributes is used when adding).
3487 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3488 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3489 Handle<Object> value, bool used_as_prototype);
3490 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3491 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3492 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3494 // Set an existing entry or add a new one if needed.
3495 // Return the updated dictionary.
3496 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3497 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3498 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3500 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3502 // If slow elements are required we will never go back to fast-case
3503 // for the elements kept in this dictionary. We require slow
3504 // elements if an element has been added at an index larger than
3505 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3506 // when defining a getter or setter with a number key.
3507 inline bool requires_slow_elements();
3508 inline void set_requires_slow_elements();
3510 // Get the value of the max number key that has been added to this
3511 // dictionary. max_number_key can only be called if
3512 // requires_slow_elements returns false.
3513 inline uint32_t max_number_key();
3516 static const int kRequiresSlowElementsMask = 1;
3517 static const int kRequiresSlowElementsTagSize = 1;
3518 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3522 class UnseededNumberDictionary
3523 : public Dictionary<UnseededNumberDictionary,
3524 UnseededNumberDictionaryShape,
3527 DECLARE_CAST(UnseededNumberDictionary)
3529 // Type specific at put (default NONE attributes is used when adding).
3530 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3531 Handle<UnseededNumberDictionary> dictionary,
3533 Handle<Object> value);
3534 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3535 Handle<UnseededNumberDictionary> dictionary,
3537 Handle<Object> value);
3539 // Set an existing entry or add a new one if needed.
3540 // Return the updated dictionary.
3541 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3542 Handle<UnseededNumberDictionary> dictionary,
3544 Handle<Object> value);
3548 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3550 static inline bool IsMatch(Handle<Object> key, Object* other);
3551 static inline uint32_t Hash(Handle<Object> key);
3552 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3553 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3554 static const int kPrefixSize = 0;
3555 static const int kEntrySize = 2;
3559 // ObjectHashTable maps keys that are arbitrary objects to object values by
3560 // using the identity hash of the key for hashing purposes.
3561 class ObjectHashTable: public HashTable<ObjectHashTable,
3562 ObjectHashTableShape,
3565 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3567 DECLARE_CAST(ObjectHashTable)
3569 // Attempt to shrink hash table after removal of key.
3570 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3571 Handle<ObjectHashTable> table,
3572 Handle<Object> key);
3574 // Looks up the value associated with the given key. The hole value is
3575 // returned in case the key is not present.
3576 Object* Lookup(Handle<Object> key);
3577 Object* Lookup(Handle<Object> key, int32_t hash);
3578 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3580 // Adds (or overwrites) the value associated with the given key.
3581 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3583 Handle<Object> value);
3584 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3585 Handle<Object> key, Handle<Object> value,
3588 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3589 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3592 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3593 Handle<Object> key, bool* was_present,
3597 friend class MarkCompactCollector;
3599 void AddEntry(int entry, Object* key, Object* value);
3600 void RemoveEntry(int entry);
3602 // Returns the index to the value of an entry.
3603 static inline int EntryToValueIndex(int entry) {
3604 return EntryToIndex(entry) + 1;
3609 // OrderedHashTable is a HashTable with Object keys that preserves
3610 // insertion order. There are Map and Set interfaces (OrderedHashMap
3611 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3613 // Only Object* keys are supported, with Object::SameValueZero() used as the
3614 // equality operator and Object::GetHash() for the hash function.
3616 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3617 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3618 // Originally attributed to Tyler Close.
3621 // [0]: bucket count
3622 // [1]: element count
3623 // [2]: deleted element count
3624 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3625 // offset into the data table (see below) where the
3626 // first item in this bucket is stored.
3627 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3628 // Capacity() * kEntrySize, where the first entrysize
3629 // items are handled by the derived class and the
3630 // item at kChainOffset is another entry into the
3631 // data table indicating the next entry in this hash
3634 // When we transition the table to a new version we obsolete it and reuse parts
3635 // of the memory to store information how to transition an iterator to the new
3638 // Memory layout for obsolete table:
3639 // [0]: bucket count
3640 // [1]: Next newer table
3641 // [2]: Number of removed holes or -1 when the table was cleared.
3642 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3643 // [3 + NumberOfRemovedHoles()..length]: Not used
3645 template<class Derived, class Iterator, int entrysize>
3646 class OrderedHashTable: public FixedArray {
3648 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3649 static Handle<Derived> Allocate(
3650 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3652 // Returns an OrderedHashTable (possibly |table|) with enough space
3653 // to add at least one new element.
3654 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3656 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3658 static Handle<Derived> Shrink(Handle<Derived> table);
3660 // Returns a new empty OrderedHashTable and records the clearing so that
3661 // exisiting iterators can be updated.
3662 static Handle<Derived> Clear(Handle<Derived> table);
3664 int NumberOfElements() {
3665 return Smi::cast(get(kNumberOfElementsIndex))->value();
3668 int NumberOfDeletedElements() {
3669 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3672 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3674 int NumberOfBuckets() {
3675 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3678 // Returns an index into |this| for the given entry.
3679 int EntryToIndex(int entry) {
3680 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3683 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3686 return !get(kNextTableIndex)->IsSmi();
3689 // The next newer table. This is only valid if the table is obsolete.
3690 Derived* NextTable() {
3691 return Derived::cast(get(kNextTableIndex));
3694 // When the table is obsolete we store the indexes of the removed holes.
3695 int RemovedIndexAt(int index) {
3696 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3699 static const int kNotFound = -1;
3700 static const int kMinCapacity = 4;
3702 static const int kNumberOfBucketsIndex = 0;
3703 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3704 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3705 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3706 static const int kNextTableIndex = kNumberOfElementsIndex;
3708 static const int kNumberOfBucketsOffset =
3709 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3710 static const int kNumberOfElementsOffset =
3711 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3712 static const int kNumberOfDeletedElementsOffset =
3713 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3714 static const int kHashTableStartOffset =
3715 kHeaderSize + kHashTableStartIndex * kPointerSize;
3716 static const int kNextTableOffset =
3717 kHeaderSize + kNextTableIndex * kPointerSize;
3719 static const int kEntrySize = entrysize + 1;
3720 static const int kChainOffset = entrysize;
3722 static const int kLoadFactor = 2;
3724 // NumberOfDeletedElements is set to kClearedTableSentinel when
3725 // the table is cleared, which allows iterator transitions to
3726 // optimize that case.
3727 static const int kClearedTableSentinel = -1;
3730 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3732 void SetNumberOfBuckets(int num) {
3733 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3736 void SetNumberOfElements(int num) {
3737 set(kNumberOfElementsIndex, Smi::FromInt(num));
3740 void SetNumberOfDeletedElements(int num) {
3741 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3745 return NumberOfBuckets() * kLoadFactor;
3748 void SetNextTable(Derived* next_table) {
3749 set(kNextTableIndex, next_table);
3752 void SetRemovedIndexAt(int index, int removed_index) {
3753 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3756 static const int kRemovedHolesIndex = kHashTableStartIndex;
3758 static const int kMaxCapacity =
3759 (FixedArray::kMaxLength - kHashTableStartIndex)
3760 / (1 + (kEntrySize * kLoadFactor));
3764 class JSSetIterator;
3767 class OrderedHashSet: public OrderedHashTable<
3768 OrderedHashSet, JSSetIterator, 1> {
3770 DECLARE_CAST(OrderedHashSet)
3774 class JSMapIterator;
3777 class OrderedHashMap
3778 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3780 DECLARE_CAST(OrderedHashMap)
3782 inline Object* ValueAt(int entry);
3784 static const int kValueOffset = 1;
3788 template <int entrysize>
3789 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3791 static inline bool IsMatch(Handle<Object> key, Object* other);
3792 static inline uint32_t Hash(Handle<Object> key);
3793 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3794 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3795 static const int kPrefixSize = 0;
3796 static const int kEntrySize = entrysize;
3800 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3801 // values. The table wraps the keys in weak cells and store values directly.
3802 // Thus it references keys weakly and values strongly.
3803 class WeakHashTable: public HashTable<WeakHashTable,
3804 WeakHashTableShape<2>,
3807 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3809 DECLARE_CAST(WeakHashTable)
3811 // Looks up the value associated with the given key. The hole value is
3812 // returned in case the key is not present.
3813 Object* Lookup(Handle<HeapObject> key);
3815 // Adds (or overwrites) the value associated with the given key. Mapping a
3816 // key to the hole value causes removal of the whole entry.
3817 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3818 Handle<HeapObject> key,
3819 Handle<HeapObject> value);
3821 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3824 friend class MarkCompactCollector;
3826 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3828 // Returns the index to the value of an entry.
3829 static inline int EntryToValueIndex(int entry) {
3830 return EntryToIndex(entry) + 1;
3835 // ScopeInfo represents information about different scopes of a source
3836 // program and the allocation of the scope's variables. Scope information
3837 // is stored in a compressed form in ScopeInfo objects and is used
3838 // at runtime (stack dumps, deoptimization, etc.).
3840 // This object provides quick access to scope info details for runtime
3842 class ScopeInfo : public FixedArray {
3844 DECLARE_CAST(ScopeInfo)
3846 // Return the type of this scope.
3847 ScopeType scope_type();
3849 // Does this scope call eval?
3852 // Return the language mode of this scope.
3853 LanguageMode language_mode();
3855 // True if this scope is a (var) declaration scope.
3856 bool is_declaration_scope();
3858 // Does this scope make a sloppy eval call?
3859 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3861 // Return the total number of locals allocated on the stack and in the
3862 // context. This includes the parameters that are allocated in the context.
3865 // Return the number of stack slots for code. This number consists of two
3867 // 1. One stack slot per stack allocated local.
3868 // 2. One stack slot for the function name if it is stack allocated.
3869 int StackSlotCount();
3871 // Return the number of context slots for code if a context is allocated. This
3872 // number consists of three parts:
3873 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3874 // 2. One context slot per context allocated local.
3875 // 3. One context slot for the function name if it is context allocated.
3876 // Parameters allocated in the context count as context allocated locals. If
3877 // no contexts are allocated for this scope ContextLength returns 0.
3878 int ContextLength();
3880 // Does this scope declare a "this" binding?
3883 // Does this scope declare a "this" binding, and the "this" binding is stack-
3884 // or context-allocated?
3885 bool HasAllocatedReceiver();
3887 // Is this scope the scope of a named function expression?
3888 bool HasFunctionName();
3890 // Return if this has context allocated locals.
3891 bool HasHeapAllocatedLocals();
3893 // Return if contexts are allocated for this scope.
3896 // Return if this is a function scope with "use asm".
3897 inline bool IsAsmModule();
3899 // Return if this is a nested function within an asm module scope.
3900 inline bool IsAsmFunction();
3902 inline bool HasSimpleParameters();
3904 // Return the function_name if present.
3905 String* FunctionName();
3907 // Return the name of the given parameter.
3908 String* ParameterName(int var);
3910 // Return the name of the given local.
3911 String* LocalName(int var);
3913 // Return the name of the given stack local.
3914 String* StackLocalName(int var);
3916 // Return the name of the given stack local.
3917 int StackLocalIndex(int var);
3919 // Return the name of the given context local.
3920 String* ContextLocalName(int var);
3922 // Return the mode of the given context local.
3923 VariableMode ContextLocalMode(int var);
3925 // Return the initialization flag of the given context local.
3926 InitializationFlag ContextLocalInitFlag(int var);
3928 // Return the initialization flag of the given context local.
3929 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3931 // Return true if this local was introduced by the compiler, and should not be
3932 // exposed to the user in a debugger.
3933 bool LocalIsSynthetic(int var);
3935 String* StrongModeFreeVariableName(int var);
3936 int StrongModeFreeVariableStartPosition(int var);
3937 int StrongModeFreeVariableEndPosition(int var);
3939 // Lookup support for serialized scope info. Returns the
3940 // the stack slot index for a given slot name if the slot is
3941 // present; otherwise returns a value < 0. The name must be an internalized
3943 int StackSlotIndex(String* name);
3945 // Lookup support for serialized scope info. Returns the local context slot
3946 // index for a given slot name if the slot is present; otherwise
3947 // returns a value < 0. The name must be an internalized string.
3948 // If the slot is present and mode != NULL, sets *mode to the corresponding
3949 // mode for that variable.
3950 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3951 VariableMode* mode, InitializationFlag* init_flag,
3952 MaybeAssignedFlag* maybe_assigned_flag);
3954 // Similar to ContextSlotIndex() but this method searches only among
3955 // global slots of the serialized scope info. Returns the context slot index
3956 // for a given slot name if the slot is present; otherwise returns a
3957 // value < 0. The name must be an internalized string. If the slot is present
3958 // and mode != NULL, sets *mode to the corresponding mode for that variable.
3959 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
3960 Handle<String> name, VariableMode* mode,
3961 InitializationFlag* init_flag,
3962 MaybeAssignedFlag* maybe_assigned_flag);
3964 // Lookup the name of a certain context slot by its index.
3965 String* ContextSlotName(int slot_index);
3967 // Lookup support for serialized scope info. Returns the
3968 // parameter index for a given parameter name if the parameter is present;
3969 // otherwise returns a value < 0. The name must be an internalized string.
3970 int ParameterIndex(String* name);
3972 // Lookup support for serialized scope info. Returns the function context
3973 // slot index if the function name is present and context-allocated (named
3974 // function expressions, only), otherwise returns a value < 0. The name
3975 // must be an internalized string.
3976 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3978 // Lookup support for serialized scope info. Returns the receiver context
3979 // slot index if scope has a "this" binding, and the binding is
3980 // context-allocated. Otherwise returns a value < 0.
3981 int ReceiverContextSlotIndex();
3983 FunctionKind function_kind();
3985 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3986 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3988 // Serializes empty scope info.
3989 static ScopeInfo* Empty(Isolate* isolate);
3995 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3996 // numeric and occupies one array slot.
3997 // 1. A set of properties of the scope
3998 // 2. The number of parameters. This only applies to function scopes. For
3999 // non-function scopes this is 0.
4000 // 3. The number of non-parameter variables allocated on the stack.
4001 // 4. The number of non-parameter and parameter variables allocated in the
4003 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4006 V(StackLocalCount) \
4007 V(ContextLocalCount) \
4008 V(ContextGlobalCount) \
4009 V(StrongModeFreeVariableCount)
4011 #define FIELD_ACCESSORS(name) \
4012 inline void Set##name(int value); \
4014 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4015 #undef FIELD_ACCESSORS
4019 #define DECL_INDEX(name) k##name,
4020 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4025 // The layout of the variable part of a ScopeInfo is as follows:
4026 // 1. ParameterEntries:
4027 // This part stores the names of the parameters for function scopes. One
4028 // slot is used per parameter, so in total this part occupies
4029 // ParameterCount() slots in the array. For other scopes than function
4030 // scopes ParameterCount() is 0.
4031 // 2. StackLocalFirstSlot:
4032 // Index of a first stack slot for stack local. Stack locals belonging to
4033 // this scope are located on a stack at slots starting from this index.
4034 // 3. StackLocalEntries:
4035 // Contains the names of local variables that are allocated on the stack,
4036 // in increasing order of the stack slot index. First local variable has
4037 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4038 // One slot is used per stack local, so in total this part occupies
4039 // StackLocalCount() slots in the array.
4040 // 4. ContextLocalNameEntries:
4041 // Contains the names of local variables and parameters that are allocated
4042 // in the context. They are stored in increasing order of the context slot
4043 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4044 // context local, so in total this part occupies ContextLocalCount() slots
4046 // 5. ContextLocalInfoEntries:
4047 // Contains the variable modes and initialization flags corresponding to
4048 // the context locals in ContextLocalNameEntries. One slot is used per
4049 // context local, so in total this part occupies ContextLocalCount()
4050 // slots in the array.
4051 // 6. StrongModeFreeVariableNameEntries:
4052 // Stores the names of strong mode free variables.
4053 // 7. StrongModeFreeVariablePositionEntries:
4054 // Stores the locations (start and end position) of strong mode free
4056 // 8. RecieverEntryIndex:
4057 // If the scope binds a "this" value, one slot is reserved to hold the
4058 // context or stack slot index for the variable.
4059 // 9. FunctionNameEntryIndex:
4060 // If the scope belongs to a named function expression this part contains
4061 // information about the function variable. It always occupies two array
4062 // slots: a. The name of the function variable.
4063 // b. The context or stack slot index for the variable.
4064 int ParameterEntriesIndex();
4065 int StackLocalFirstSlotIndex();
4066 int StackLocalEntriesIndex();
4067 int ContextLocalNameEntriesIndex();
4068 int ContextGlobalNameEntriesIndex();
4069 int ContextLocalInfoEntriesIndex();
4070 int ContextGlobalInfoEntriesIndex();
4071 int StrongModeFreeVariableNameEntriesIndex();
4072 int StrongModeFreeVariablePositionEntriesIndex();
4073 int ReceiverEntryIndex();
4074 int FunctionNameEntryIndex();
4076 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4077 VariableLocation* location, InitializationFlag* init_flag,
4078 MaybeAssignedFlag* maybe_assigned_flag);
4080 // Used for the function name variable for named function expressions, and for
4082 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4084 // Properties of scopes.
4085 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4086 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4087 STATIC_ASSERT(LANGUAGE_END == 3);
4088 class LanguageModeField
4089 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4090 class DeclarationScopeField
4091 : public BitField<bool, LanguageModeField::kNext, 1> {};
4092 class ReceiverVariableField
4093 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4095 class FunctionVariableField
4096 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4098 class FunctionVariableMode
4099 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4100 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4102 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4103 class HasSimpleParametersField
4104 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4105 class FunctionKindField
4106 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4108 // BitFields representing the encoded information for context locals in the
4109 // ContextLocalInfoEntries part.
4110 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4111 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4112 class ContextLocalMaybeAssignedFlag
4113 : public BitField<MaybeAssignedFlag, 4, 1> {};
4115 friend class ScopeIterator;
4119 // The cache for maps used by normalized (dictionary mode) objects.
4120 // Such maps do not have property descriptors, so a typical program
4121 // needs very limited number of distinct normalized maps.
4122 class NormalizedMapCache: public FixedArray {
4124 static Handle<NormalizedMapCache> New(Isolate* isolate);
4126 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4127 PropertyNormalizationMode mode);
4128 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4132 DECLARE_CAST(NormalizedMapCache)
4134 static inline bool IsNormalizedMapCache(const Object* obj);
4136 DECLARE_VERIFIER(NormalizedMapCache)
4138 static const int kEntries = 64;
4140 static inline int GetIndex(Handle<Map> map);
4142 // The following declarations hide base class methods.
4143 Object* get(int index);
4144 void set(int index, Object* value);
4148 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4149 // that is attached to code objects.
4150 class ByteArray: public FixedArrayBase {
4154 // Setter and getter.
4155 inline byte get(int index);
4156 inline void set(int index, byte value);
4158 // Treat contents as an int array.
4159 inline int get_int(int index);
4161 static int SizeFor(int length) {
4162 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4164 // We use byte arrays for free blocks in the heap. Given a desired size in
4165 // bytes that is a multiple of the word size and big enough to hold a byte
4166 // array, this function returns the number of elements a byte array should
4168 static int LengthFor(int size_in_bytes) {
4169 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4170 DCHECK(size_in_bytes >= kHeaderSize);
4171 return size_in_bytes - kHeaderSize;
4174 // Returns data start address.
4175 inline Address GetDataStartAddress();
4177 // Returns a pointer to the ByteArray object for a given data start address.
4178 static inline ByteArray* FromDataStartAddress(Address address);
4180 DECLARE_CAST(ByteArray)
4182 // Dispatched behavior.
4183 inline int ByteArraySize();
4184 DECLARE_PRINTER(ByteArray)
4185 DECLARE_VERIFIER(ByteArray)
4187 // Layout description.
4188 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4190 // Maximal memory consumption for a single ByteArray.
4191 static const int kMaxSize = 512 * MB;
4192 // Maximal length of a single ByteArray.
4193 static const int kMaxLength = kMaxSize - kHeaderSize;
4196 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4200 // BytecodeArray represents a sequence of interpreter bytecodes.
4201 class BytecodeArray : public FixedArrayBase {
4203 static int SizeFor(int length) {
4204 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4207 // Setter and getter
4208 inline byte get(int index);
4209 inline void set(int index, byte value);
4211 // Returns data start address.
4212 inline Address GetFirstBytecodeAddress();
4214 // Accessors for frame size.
4215 inline int frame_size() const;
4216 inline void set_frame_size(int frame_size);
4218 // Accessor for register count (derived from frame_size).
4219 inline int register_count() const;
4221 // Accessors for parameter count (including implicit 'this' receiver).
4222 inline int parameter_count() const;
4223 inline void set_parameter_count(int number_of_parameters);
4225 // Accessors for the constant pool.
4226 DECL_ACCESSORS(constant_pool, FixedArray)
4228 DECLARE_CAST(BytecodeArray)
4230 // Dispatched behavior.
4231 inline int BytecodeArraySize();
4232 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4234 DECLARE_PRINTER(BytecodeArray)
4235 DECLARE_VERIFIER(BytecodeArray)
4237 void Disassemble(std::ostream& os);
4239 // Layout description.
4240 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4241 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4242 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4243 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4245 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4247 // Maximal memory consumption for a single BytecodeArray.
4248 static const int kMaxSize = 512 * MB;
4249 // Maximal length of a single BytecodeArray.
4250 static const int kMaxLength = kMaxSize - kHeaderSize;
4253 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4257 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4258 // They look like heap objects (are heap object tagged and have a map) so that
4259 // the heap remains iterable. They have a size and a next pointer.
4260 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4261 // in the free list.
4262 class FreeSpace: public HeapObject {
4264 // [size]: size of the free space including the header.
4265 inline int size() const;
4266 inline void set_size(int value);
4268 inline int nobarrier_size() const;
4269 inline void nobarrier_set_size(int value);
4273 // Accessors for the next field.
4274 inline FreeSpace* next();
4275 inline FreeSpace** next_address();
4276 inline void set_next(FreeSpace* next);
4278 inline static FreeSpace* cast(HeapObject* obj);
4280 // Dispatched behavior.
4281 DECLARE_PRINTER(FreeSpace)
4282 DECLARE_VERIFIER(FreeSpace)
4284 // Layout description.
4285 // Size is smi tagged when it is stored.
4286 static const int kSizeOffset = HeapObject::kHeaderSize;
4287 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4290 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4294 // V has parameters (Type, type, TYPE, C type, element_size)
4295 #define TYPED_ARRAYS(V) \
4296 V(Uint8, uint8, UINT8, uint8_t, 1) \
4297 V(Int8, int8, INT8, int8_t, 1) \
4298 V(Uint16, uint16, UINT16, uint16_t, 2) \
4299 V(Int16, int16, INT16, int16_t, 2) \
4300 V(Uint32, uint32, UINT32, uint32_t, 4) \
4301 V(Int32, int32, INT32, int32_t, 4) \
4302 V(Float32, float32, FLOAT32, float, 4) \
4303 V(Float64, float64, FLOAT64, double, 8) \
4304 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4307 class FixedTypedArrayBase: public FixedArrayBase {
4309 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4310 DECL_ACCESSORS(base_pointer, Object)
4312 // [external_pointer]: Contains the offset between base_pointer and the start
4313 // of the data. If the base_pointer is a nullptr, the external_pointer
4314 // therefore points to the actual backing store.
4315 DECL_ACCESSORS(external_pointer, void)
4317 // Dispatched behavior.
4318 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4320 template <typename StaticVisitor>
4321 inline void FixedTypedArrayBaseIterateBody();
4323 DECLARE_CAST(FixedTypedArrayBase)
4325 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4326 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4327 static const int kHeaderSize =
4328 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4330 static const int kDataOffset = kHeaderSize;
4334 static inline int TypedArraySize(InstanceType type, int length);
4335 inline int TypedArraySize(InstanceType type);
4337 // Use with care: returns raw pointer into heap.
4338 inline void* DataPtr();
4340 inline int DataSize();
4343 static inline int ElementSize(InstanceType type);
4345 inline int DataSize(InstanceType type);
4347 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4351 template <class Traits>
4352 class FixedTypedArray: public FixedTypedArrayBase {
4354 typedef typename Traits::ElementType ElementType;
4355 static const InstanceType kInstanceType = Traits::kInstanceType;
4357 DECLARE_CAST(FixedTypedArray<Traits>)
4359 inline ElementType get_scalar(int index);
4360 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4361 inline void set(int index, ElementType value);
4363 static inline ElementType from_int(int value);
4364 static inline ElementType from_double(double value);
4366 // This accessor applies the correct conversion from Smi, HeapNumber
4368 inline void SetValue(uint32_t index, Object* value);
4370 DECLARE_PRINTER(FixedTypedArray)
4371 DECLARE_VERIFIER(FixedTypedArray)
4374 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4377 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4378 class Type##ArrayTraits { \
4379 public: /* NOLINT */ \
4380 typedef elementType ElementType; \
4381 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4382 static const char* Designator() { return #type " array"; } \
4383 static inline Handle<Object> ToHandle(Isolate* isolate, \
4384 elementType scalar); \
4385 static inline elementType defaultValue(); \
4388 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4390 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4392 #undef FIXED_TYPED_ARRAY_TRAITS
4395 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4396 // data for code generated by the Hydrogen/Lithium compiler. It also
4397 // contains information about functions that were inlined. If N different
4398 // functions were inlined then first N elements of the literal array will
4399 // contain these functions.
4402 class DeoptimizationInputData: public FixedArray {
4404 // Layout description. Indices in the array.
4405 static const int kTranslationByteArrayIndex = 0;
4406 static const int kInlinedFunctionCountIndex = 1;
4407 static const int kLiteralArrayIndex = 2;
4408 static const int kOsrAstIdIndex = 3;
4409 static const int kOsrPcOffsetIndex = 4;
4410 static const int kOptimizationIdIndex = 5;
4411 static const int kSharedFunctionInfoIndex = 6;
4412 static const int kWeakCellCacheIndex = 7;
4413 static const int kFirstDeoptEntryIndex = 8;
4415 // Offsets of deopt entry elements relative to the start of the entry.
4416 static const int kAstIdRawOffset = 0;
4417 static const int kTranslationIndexOffset = 1;
4418 static const int kArgumentsStackHeightOffset = 2;
4419 static const int kPcOffset = 3;
4420 static const int kDeoptEntrySize = 4;
4422 // Simple element accessors.
4423 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4424 inline type* name(); \
4425 inline void Set##name(type* value);
4427 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4428 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4429 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4430 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4431 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4432 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4433 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4434 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4436 #undef DECLARE_ELEMENT_ACCESSORS
4438 // Accessors for elements of the ith deoptimization entry.
4439 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4440 inline type* name(int i); \
4441 inline void Set##name(int i, type* value);
4443 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4444 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4445 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4446 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4448 #undef DECLARE_ENTRY_ACCESSORS
4450 inline BailoutId AstId(int i);
4452 inline void SetAstId(int i, BailoutId value);
4454 inline int DeoptCount();
4456 // Allocates a DeoptimizationInputData.
4457 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4458 int deopt_entry_count,
4459 PretenureFlag pretenure);
4461 DECLARE_CAST(DeoptimizationInputData)
4463 #ifdef ENABLE_DISASSEMBLER
4464 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4468 static int IndexForEntry(int i) {
4469 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4473 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4477 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4478 // data for code generated by the full compiler.
4479 // The format of the these objects is
4480 // [i * 2]: Ast ID for ith deoptimization.
4481 // [i * 2 + 1]: PC and state of ith deoptimization
4482 class DeoptimizationOutputData: public FixedArray {
4484 inline int DeoptPoints();
4486 inline BailoutId AstId(int index);
4488 inline void SetAstId(int index, BailoutId id);
4490 inline Smi* PcAndState(int index);
4491 inline void SetPcAndState(int index, Smi* offset);
4493 static int LengthOfFixedArray(int deopt_points) {
4494 return deopt_points * 2;
4497 // Allocates a DeoptimizationOutputData.
4498 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4499 int number_of_deopt_points,
4500 PretenureFlag pretenure);
4502 DECLARE_CAST(DeoptimizationOutputData)
4504 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4505 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4510 // HandlerTable is a fixed array containing entries for exception handlers in
4511 // the code object it is associated with. The tables comes in two flavors:
4512 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4513 // exception handler and a range representing the try-block covered by that
4514 // handler. Layout looks as follows:
4515 // [ range-start , range-end , handler-offset , stack-depth ]
4516 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4517 // per call-site that could throw an exception. Layout looks as follows:
4518 // [ return-address-offset , handler-offset ]
4519 class HandlerTable : public FixedArray {
4521 // Conservative prediction whether a given handler will locally catch an
4522 // exception or cause a re-throw to outside the code boundary. Since this is
4523 // undecidable it is merely an approximation (e.g. useful for debugger).
4524 enum CatchPrediction { UNCAUGHT, CAUGHT };
4526 // Accessors for handler table based on ranges.
4527 inline void SetRangeStart(int index, int value);
4528 inline void SetRangeEnd(int index, int value);
4529 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4530 inline void SetRangeDepth(int index, int value);
4532 // Accessors for handler table based on return addresses.
4533 inline void SetReturnOffset(int index, int value);
4534 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4536 // Lookup handler in a table based on ranges.
4537 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4539 // Lookup handler in a table based on return addresses.
4540 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4542 // Returns the required length of the underlying fixed array.
4543 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4544 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4546 DECLARE_CAST(HandlerTable)
4548 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4549 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4550 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4554 // Layout description for handler table based on ranges.
4555 static const int kRangeStartIndex = 0;
4556 static const int kRangeEndIndex = 1;
4557 static const int kRangeHandlerIndex = 2;
4558 static const int kRangeDepthIndex = 3;
4559 static const int kRangeEntrySize = 4;
4561 // Layout description for handler table based on return addresses.
4562 static const int kReturnOffsetIndex = 0;
4563 static const int kReturnHandlerIndex = 1;
4564 static const int kReturnEntrySize = 2;
4566 // Encoding of the {handler} field.
4567 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4568 class HandlerOffsetField : public BitField<int, 1, 30> {};
4572 // Code describes objects with on-the-fly generated machine code.
4573 class Code: public HeapObject {
4575 // Opaque data type for encapsulating code flags like kind, inline
4576 // cache state, and arguments count.
4577 typedef uint32_t Flags;
4579 #define NON_IC_KIND_LIST(V) \
4581 V(OPTIMIZED_FUNCTION) \
4588 #define IC_KIND_LIST(V) \
4599 #define CODE_KIND_LIST(V) \
4600 NON_IC_KIND_LIST(V) \
4604 #define DEFINE_CODE_KIND_ENUM(name) name,
4605 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4606 #undef DEFINE_CODE_KIND_ENUM
4610 // No more than 16 kinds. The value is currently encoded in four bits in
4612 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4614 static const char* Kind2String(Kind kind);
4622 static const int kPrologueOffsetNotSet = -1;
4624 #ifdef ENABLE_DISASSEMBLER
4626 static const char* ICState2String(InlineCacheState state);
4627 static const char* StubType2String(StubType type);
4628 static void PrintExtraICState(std::ostream& os, // NOLINT
4629 Kind kind, ExtraICState extra);
4630 void Disassemble(const char* name, std::ostream& os); // NOLINT
4631 #endif // ENABLE_DISASSEMBLER
4633 // [instruction_size]: Size of the native instructions
4634 inline int instruction_size() const;
4635 inline void set_instruction_size(int value);
4637 // [relocation_info]: Code relocation information
4638 DECL_ACCESSORS(relocation_info, ByteArray)
4639 void InvalidateRelocation();
4640 void InvalidateEmbeddedObjects();
4642 // [handler_table]: Fixed array containing offsets of exception handlers.
4643 DECL_ACCESSORS(handler_table, FixedArray)
4645 // [deoptimization_data]: Array containing data for deopt.
4646 DECL_ACCESSORS(deoptimization_data, FixedArray)
4648 // [raw_type_feedback_info]: This field stores various things, depending on
4649 // the kind of the code object.
4650 // FUNCTION => type feedback information.
4651 // STUB and ICs => major/minor key as Smi.
4652 DECL_ACCESSORS(raw_type_feedback_info, Object)
4653 inline Object* type_feedback_info();
4654 inline void set_type_feedback_info(
4655 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4656 inline uint32_t stub_key();
4657 inline void set_stub_key(uint32_t key);
4659 // [next_code_link]: Link for lists of optimized or deoptimized code.
4660 // Note that storage for this field is overlapped with typefeedback_info.
4661 DECL_ACCESSORS(next_code_link, Object)
4663 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4664 // field does not have to be traced during garbage collection since
4665 // it is only used by the garbage collector itself.
4666 DECL_ACCESSORS(gc_metadata, Object)
4668 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4669 // at the moment when this object was created.
4670 inline void set_ic_age(int count);
4671 inline int ic_age() const;
4673 // [prologue_offset]: Offset of the function prologue, used for aging
4674 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4675 inline int prologue_offset() const;
4676 inline void set_prologue_offset(int offset);
4678 // [constant_pool offset]: Offset of the constant pool.
4679 // Valid for FLAG_enable_embedded_constant_pool only
4680 inline int constant_pool_offset() const;
4681 inline void set_constant_pool_offset(int offset);
4683 // Unchecked accessors to be used during GC.
4684 inline ByteArray* unchecked_relocation_info();
4686 inline int relocation_size();
4688 // [flags]: Various code flags.
4689 inline Flags flags();
4690 inline void set_flags(Flags flags);
4692 // [flags]: Access to specific code flags.
4694 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4695 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4697 inline StubType type(); // Only valid for monomorphic IC stubs.
4699 // Testers for IC stub kinds.
4700 inline bool is_inline_cache_stub();
4701 inline bool is_debug_stub();
4702 inline bool is_handler();
4703 inline bool is_load_stub();
4704 inline bool is_keyed_load_stub();
4705 inline bool is_store_stub();
4706 inline bool is_keyed_store_stub();
4707 inline bool is_call_stub();
4708 inline bool is_binary_op_stub();
4709 inline bool is_compare_ic_stub();
4710 inline bool is_compare_nil_ic_stub();
4711 inline bool is_to_boolean_ic_stub();
4712 inline bool is_keyed_stub();
4713 inline bool is_optimized_code();
4714 inline bool embeds_maps_weakly();
4716 inline bool IsCodeStubOrIC();
4717 inline bool IsJavaScriptCode();
4719 inline void set_raw_kind_specific_flags1(int value);
4720 inline void set_raw_kind_specific_flags2(int value);
4722 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4723 // object was generated by either the hydrogen or the TurboFan optimizing
4724 // compiler (but it may not be an optimized function).
4725 inline bool is_crankshafted();
4726 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4727 inline void set_is_crankshafted(bool value);
4729 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4730 // code object was generated by the TurboFan optimizing compiler.
4731 inline bool is_turbofanned();
4732 inline void set_is_turbofanned(bool value);
4734 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4735 // embedded objects in code should be treated weakly.
4736 inline bool can_have_weak_objects();
4737 inline void set_can_have_weak_objects(bool value);
4739 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4740 // deoptimization support.
4741 inline bool has_deoptimization_support();
4742 inline void set_has_deoptimization_support(bool value);
4744 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4745 // been compiled with debug break slots.
4746 inline bool has_debug_break_slots();
4747 inline void set_has_debug_break_slots(bool value);
4749 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4750 // reloc info includes runtime and external references to support
4751 // serialization/deserialization.
4752 inline bool has_reloc_info_for_serialization();
4753 inline void set_has_reloc_info_for_serialization(bool value);
4755 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4756 // how long the function has been marked for OSR and therefore which
4757 // level of loop nesting we are willing to do on-stack replacement
4759 inline void set_allow_osr_at_loop_nesting_level(int level);
4760 inline int allow_osr_at_loop_nesting_level();
4762 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4763 // the code object was seen on the stack with no IC patching going on.
4764 inline int profiler_ticks();
4765 inline void set_profiler_ticks(int ticks);
4767 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4768 // For builtins, tells which builtin index it has.
4769 // Note that builtins can have a code kind other than BUILTIN, which means
4770 // that for arbitrary code objects, this index value may be random garbage.
4771 // To verify in that case, compare the code object to the indexed builtin.
4772 inline int builtin_index();
4773 inline void set_builtin_index(int id);
4775 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4776 // reserved in the code prologue.
4777 inline unsigned stack_slots();
4778 inline void set_stack_slots(unsigned slots);
4780 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4781 // the instruction stream where the safepoint table starts.
4782 inline unsigned safepoint_table_offset();
4783 inline void set_safepoint_table_offset(unsigned offset);
4785 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4786 // instruction stream where the back edge table starts.
4787 inline unsigned back_edge_table_offset();
4788 inline void set_back_edge_table_offset(unsigned offset);
4790 inline bool back_edges_patched_for_osr();
4792 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4793 inline uint16_t to_boolean_state();
4795 // [has_function_cache]: For kind STUB tells whether there is a function
4796 // cache is passed to the stub.
4797 inline bool has_function_cache();
4798 inline void set_has_function_cache(bool flag);
4801 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4802 // the code is going to be deoptimized because of dead embedded maps.
4803 inline bool marked_for_deoptimization();
4804 inline void set_marked_for_deoptimization(bool flag);
4806 // [constant_pool]: The constant pool for this function.
4807 inline Address constant_pool();
4809 // Get the safepoint entry for the given pc.
4810 SafepointEntry GetSafepointEntry(Address pc);
4812 // Find an object in a stub with a specified map
4813 Object* FindNthObject(int n, Map* match_map);
4815 // Find the first allocation site in an IC stub.
4816 AllocationSite* FindFirstAllocationSite();
4818 // Find the first map in an IC stub.
4819 Map* FindFirstMap();
4820 void FindAllMaps(MapHandleList* maps);
4822 // Find the first handler in an IC stub.
4823 Code* FindFirstHandler();
4825 // Find |length| handlers and put them into |code_list|. Returns false if not
4826 // enough handlers can be found.
4827 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4829 // Find the handler for |map|.
4830 MaybeHandle<Code> FindHandlerForMap(Map* map);
4832 // Find the first name in an IC stub.
4833 Name* FindFirstName();
4835 class FindAndReplacePattern;
4836 // For each (map-to-find, object-to-replace) pair in the pattern, this
4837 // function replaces the corresponding placeholder in the code with the
4838 // object-to-replace. The function assumes that pairs in the pattern come in
4839 // the same order as the placeholders in the code.
4840 // If the placeholder is a weak cell, then the value of weak cell is matched
4841 // against the map-to-find.
4842 void FindAndReplace(const FindAndReplacePattern& pattern);
4844 // The entire code object including its header is copied verbatim to the
4845 // snapshot so that it can be written in one, fast, memcpy during
4846 // deserialization. The deserializer will overwrite some pointers, rather
4847 // like a runtime linker, but the random allocation addresses used in the
4848 // mksnapshot process would still be present in the unlinked snapshot data,
4849 // which would make snapshot production non-reproducible. This method wipes
4850 // out the to-be-overwritten header data for reproducible snapshots.
4851 inline void WipeOutHeader();
4853 // Flags operations.
4854 static inline Flags ComputeFlags(
4855 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4856 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4857 CacheHolderFlag holder = kCacheOnReceiver);
4859 static inline Flags ComputeMonomorphicFlags(
4860 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4861 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4863 static inline Flags ComputeHandlerFlags(
4864 Kind handler_kind, StubType type = NORMAL,
4865 CacheHolderFlag holder = kCacheOnReceiver);
4867 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4868 static inline StubType ExtractTypeFromFlags(Flags flags);
4869 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4870 static inline Kind ExtractKindFromFlags(Flags flags);
4871 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4873 static inline Flags RemoveTypeFromFlags(Flags flags);
4874 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4876 // Convert a target address into a code object.
4877 static inline Code* GetCodeFromTargetAddress(Address address);
4879 // Convert an entry address into an object.
4880 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4882 // Returns the address of the first instruction.
4883 inline byte* instruction_start();
4885 // Returns the address right after the last instruction.
4886 inline byte* instruction_end();
4888 // Returns the size of the instructions, padding, and relocation information.
4889 inline int body_size();
4891 // Returns the address of the first relocation info (read backwards!).
4892 inline byte* relocation_start();
4894 // Code entry point.
4895 inline byte* entry();
4897 // Returns true if pc is inside this object's instructions.
4898 inline bool contains(byte* pc);
4900 // Relocate the code by delta bytes. Called to signal that this code
4901 // object has been moved by delta bytes.
4902 void Relocate(intptr_t delta);
4904 // Migrate code described by desc.
4905 void CopyFrom(const CodeDesc& desc);
4907 // Returns the object size for a given body (used for allocation).
4908 static int SizeFor(int body_size) {
4909 DCHECK_SIZE_TAG_ALIGNED(body_size);
4910 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4913 // Calculate the size of the code object to report for log events. This takes
4914 // the layout of the code object into account.
4915 inline int ExecutableSize();
4917 // Locating source position.
4918 int SourcePosition(Address pc);
4919 int SourceStatementPosition(Address pc);
4923 // Dispatched behavior.
4924 inline int CodeSize();
4925 inline void CodeIterateBody(ObjectVisitor* v);
4927 template<typename StaticVisitor>
4928 inline void CodeIterateBody(Heap* heap);
4930 DECLARE_PRINTER(Code)
4931 DECLARE_VERIFIER(Code)
4933 void ClearInlineCaches();
4934 void ClearInlineCaches(Kind kind);
4936 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4937 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4939 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4941 kToBeExecutedOnceCodeAge = -3,
4942 kNotExecutedCodeAge = -2,
4943 kExecutedOnceCodeAge = -1,
4945 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4947 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4948 kLastCodeAge = kAfterLastCodeAge - 1,
4949 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4950 kIsOldCodeAge = kSexagenarianCodeAge,
4951 kPreAgedCodeAge = kIsOldCodeAge - 1
4953 #undef DECLARE_CODE_AGE_ENUM
4955 // Code aging. Indicates how many full GCs this code has survived without
4956 // being entered through the prologue. Used to determine when it is
4957 // relatively safe to flush this code object and replace it with the lazy
4958 // compilation stub.
4959 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4960 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4961 void MakeYoung(Isolate* isolate);
4962 void MarkToBeExecutedOnce(Isolate* isolate);
4963 void MakeOlder(MarkingParity);
4964 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4967 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4968 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4971 void PrintDeoptLocation(FILE* out, Address pc);
4972 bool CanDeoptAt(Address pc);
4975 void VerifyEmbeddedObjectsDependency();
4979 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4980 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4981 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4984 inline bool CanContainWeakObjects();
4986 inline bool IsWeakObject(Object* object);
4988 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4990 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4991 WeakCell* CachedWeakCell();
4993 // Max loop nesting marker used to postpose OSR. We don't take loop
4994 // nesting that is deeper than 5 levels into account.
4995 static const int kMaxLoopNestingMarker = 6;
4997 static const int kConstantPoolSize =
4998 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5000 // Layout description.
5001 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5002 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5003 static const int kDeoptimizationDataOffset =
5004 kHandlerTableOffset + kPointerSize;
5005 // For FUNCTION kind, we store the type feedback info here.
5006 static const int kTypeFeedbackInfoOffset =
5007 kDeoptimizationDataOffset + kPointerSize;
5008 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5009 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5010 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5011 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5012 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5013 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5014 static const int kKindSpecificFlags2Offset =
5015 kKindSpecificFlags1Offset + kIntSize;
5016 // Note: We might be able to squeeze this into the flags above.
5017 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5018 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5019 static const int kHeaderPaddingStart =
5020 kConstantPoolOffset + kConstantPoolSize;
5022 // Add padding to align the instruction start following right after
5023 // the Code object header.
5024 static const int kHeaderSize =
5025 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5027 // Byte offsets within kKindSpecificFlags1Offset.
5028 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5029 class FullCodeFlagsHasDeoptimizationSupportField:
5030 public BitField<bool, 0, 1> {}; // NOLINT
5031 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5032 class FullCodeFlagsHasRelocInfoForSerialization
5033 : public BitField<bool, 2, 1> {};
5034 // Bit 3 in this bitfield is unused.
5035 class ProfilerTicksField : public BitField<int, 4, 28> {};
5037 // Flags layout. BitField<type, shift, size>.
5038 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5039 class TypeField : public BitField<StubType, 4, 1> {};
5040 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5041 class KindField : public BitField<Kind, 7, 4> {};
5042 class ExtraICStateField: public BitField<ExtraICState, 11,
5043 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5045 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5046 static const int kStackSlotsFirstBit = 0;
5047 static const int kStackSlotsBitCount = 24;
5048 static const int kHasFunctionCacheBit =
5049 kStackSlotsFirstBit + kStackSlotsBitCount;
5050 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5051 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5052 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5054 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5055 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5057 class StackSlotsField: public BitField<int,
5058 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5059 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5061 class MarkedForDeoptimizationField
5062 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5063 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5065 class CanHaveWeakObjectsField
5066 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5068 // KindSpecificFlags2 layout (ALL)
5069 static const int kIsCrankshaftedBit = 0;
5070 class IsCrankshaftedField: public BitField<bool,
5071 kIsCrankshaftedBit, 1> {}; // NOLINT
5073 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5074 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5075 static const int kSafepointTableOffsetBitCount = 30;
5077 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5078 kSafepointTableOffsetBitCount <= 32);
5079 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5081 class SafepointTableOffsetField: public BitField<int,
5082 kSafepointTableOffsetFirstBit,
5083 kSafepointTableOffsetBitCount> {}; // NOLINT
5085 // KindSpecificFlags2 layout (FUNCTION)
5086 class BackEdgeTableOffsetField: public BitField<int,
5087 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5088 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5089 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5090 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5092 static const int kArgumentsBits = 16;
5093 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5095 // This constant should be encodable in an ARM instruction.
5096 static const int kFlagsNotUsedInLookup =
5097 TypeField::kMask | CacheHolderField::kMask;
5100 friend class RelocIterator;
5101 friend class Deoptimizer; // For FindCodeAgeSequence.
5103 void ClearInlineCaches(Kind* kind);
5106 byte* FindCodeAgeSequence();
5107 static void GetCodeAgeAndParity(Code* code, Age* age,
5108 MarkingParity* parity);
5109 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5110 MarkingParity* parity);
5111 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5113 // Code aging -- platform-specific
5114 static void PatchPlatformCodeAge(Isolate* isolate,
5115 byte* sequence, Age age,
5116 MarkingParity parity);
5118 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5122 // This class describes the layout of dependent codes array of a map. The
5123 // array is partitioned into several groups of dependent codes. Each group
5124 // contains codes with the same dependency on the map. The array has the
5125 // following layout for n dependency groups:
5127 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5128 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5129 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5131 // The first n elements are Smis, each of them specifies the number of codes
5132 // in the corresponding group. The subsequent elements contain grouped code
5133 // objects in weak cells. The suffix of the array can be filled with the
5134 // undefined value if the number of codes is less than the length of the
5135 // array. The order of the code objects within a group is not preserved.
5137 // All code indexes used in the class are counted starting from the first
5138 // code object of the first group. In other words, code index 0 corresponds
5139 // to array index n = kCodesStartIndex.
5141 class DependentCode: public FixedArray {
5143 enum DependencyGroup {
5144 // Group of code that weakly embed this map and depend on being
5145 // deoptimized when the map is garbage collected.
5147 // Group of code that embed a transition to this map, and depend on being
5148 // deoptimized when the transition is replaced by a new version.
5150 // Group of code that omit run-time prototype checks for prototypes
5151 // described by this map. The group is deoptimized whenever an object
5152 // described by this map changes shape (and transitions to a new map),
5153 // possibly invalidating the assumptions embedded in the code.
5154 kPrototypeCheckGroup,
5155 // Group of code that depends on global property values in property cells
5156 // not being changed.
5157 kPropertyCellChangedGroup,
5158 // Group of code that omit run-time type checks for the field(s) introduced
5161 // Group of code that omit run-time type checks for initial maps of
5163 kInitialMapChangedGroup,
5164 // Group of code that depends on tenuring information in AllocationSites
5165 // not being changed.
5166 kAllocationSiteTenuringChangedGroup,
5167 // Group of code that depends on element transition information in
5168 // AllocationSites not being changed.
5169 kAllocationSiteTransitionChangedGroup
5172 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5174 // Array for holding the index of the first code object of each group.
5175 // The last element stores the total number of code objects.
5176 class GroupStartIndexes {
5178 explicit GroupStartIndexes(DependentCode* entries);
5179 void Recompute(DependentCode* entries);
5180 int at(int i) { return start_indexes_[i]; }
5181 int number_of_entries() { return start_indexes_[kGroupCount]; }
5183 int start_indexes_[kGroupCount + 1];
5186 bool Contains(DependencyGroup group, WeakCell* code_cell);
5188 static Handle<DependentCode> InsertCompilationDependencies(
5189 Handle<DependentCode> entries, DependencyGroup group,
5190 Handle<Foreign> info);
5192 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5193 DependencyGroup group,
5194 Handle<WeakCell> code_cell);
5196 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5197 WeakCell* code_cell);
5199 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5202 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5203 DependentCode::DependencyGroup group);
5205 bool MarkCodeForDeoptimization(Isolate* isolate,
5206 DependentCode::DependencyGroup group);
5208 // The following low-level accessors should only be used by this class
5209 // and the mark compact collector.
5210 inline int number_of_entries(DependencyGroup group);
5211 inline void set_number_of_entries(DependencyGroup group, int value);
5212 inline Object* object_at(int i);
5213 inline void set_object_at(int i, Object* object);
5214 inline void clear_at(int i);
5215 inline void copy(int from, int to);
5216 DECLARE_CAST(DependentCode)
5218 static const char* DependencyGroupName(DependencyGroup group);
5219 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5222 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5223 DependencyGroup group,
5224 Handle<Object> object);
5225 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5226 // Make a room at the end of the given group by moving out the first
5227 // code objects of the subsequent groups.
5228 inline void ExtendGroup(DependencyGroup group);
5229 // Compact by removing cleared weak cells and return true if there was
5230 // any cleared weak cell.
5232 static int Grow(int number_of_entries) {
5233 if (number_of_entries < 5) return number_of_entries + 1;
5234 return number_of_entries * 5 / 4;
5236 static const int kCodesStartIndex = kGroupCount;
5240 class PrototypeInfo;
5243 // All heap objects have a Map that describes their structure.
5244 // A Map contains information about:
5245 // - Size information about the object
5246 // - How to iterate over an object (for garbage collection)
5247 class Map: public HeapObject {
5250 // Size in bytes or kVariableSizeSentinel if instances do not have
5252 inline int instance_size();
5253 inline void set_instance_size(int value);
5255 // Only to clear an unused byte, remove once byte is used.
5256 inline void clear_unused();
5258 // [inobject_properties_or_constructor_function_index]: Provides access
5259 // to the inobject properties in case of JSObject maps, or the constructor
5260 // function index in case of primitive maps.
5261 inline int inobject_properties_or_constructor_function_index();
5262 inline void set_inobject_properties_or_constructor_function_index(int value);
5263 // Count of properties allocated in the object (JSObject only).
5264 inline int GetInObjectProperties();
5265 inline void SetInObjectProperties(int value);
5266 // Index of the constructor function in the native context (primitives only),
5267 // or the special sentinel value to indicate that there is no object wrapper
5268 // for the primitive (i.e. in case of null or undefined).
5269 static const int kNoConstructorFunctionIndex = 0;
5270 inline int GetConstructorFunctionIndex();
5271 inline void SetConstructorFunctionIndex(int value);
5274 inline InstanceType instance_type();
5275 inline void set_instance_type(InstanceType value);
5277 // Tells how many unused property fields are available in the
5278 // instance (only used for JSObject in fast mode).
5279 inline int unused_property_fields();
5280 inline void set_unused_property_fields(int value);
5283 inline byte bit_field() const;
5284 inline void set_bit_field(byte value);
5287 inline byte bit_field2() const;
5288 inline void set_bit_field2(byte value);
5291 inline uint32_t bit_field3() const;
5292 inline void set_bit_field3(uint32_t bits);
5294 class EnumLengthBits: public BitField<int,
5295 0, kDescriptorIndexBitCount> {}; // NOLINT
5296 class NumberOfOwnDescriptorsBits: public BitField<int,
5297 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5298 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5299 class DictionaryMap : public BitField<bool, 20, 1> {};
5300 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5301 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5302 class Deprecated : public BitField<bool, 23, 1> {};
5303 class IsUnstable : public BitField<bool, 24, 1> {};
5304 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5305 class IsStrong : public BitField<bool, 26, 1> {};
5308 // Keep this bit field at the very end for better code in
5309 // Builtins::kJSConstructStubGeneric stub.
5310 // This counter is used for in-object slack tracking and for map aging.
5311 // The in-object slack tracking is considered enabled when the counter is
5312 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5313 class Counter : public BitField<int, 28, 4> {};
5314 static const int kSlackTrackingCounterStart = 14;
5315 static const int kSlackTrackingCounterEnd = 8;
5316 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5317 static const int kRetainingCounterEnd = 0;
5319 // Tells whether the object in the prototype property will be used
5320 // for instances created from this function. If the prototype
5321 // property is set to a value that is not a JSObject, the prototype
5322 // property will not be used to create instances of the function.
5323 // See ECMA-262, 13.2.2.
5324 inline void set_non_instance_prototype(bool value);
5325 inline bool has_non_instance_prototype();
5327 // Tells whether function has special prototype property. If not, prototype
5328 // property will not be created when accessed (will return undefined),
5329 // and construction from this function will not be allowed.
5330 inline void set_function_with_prototype(bool value);
5331 inline bool function_with_prototype();
5333 // Tells whether the instance with this map should be ignored by the
5334 // Object.getPrototypeOf() function and the __proto__ accessor.
5335 inline void set_is_hidden_prototype();
5336 inline bool is_hidden_prototype() const;
5338 // Records and queries whether the instance has a named interceptor.
5339 inline void set_has_named_interceptor();
5340 inline bool has_named_interceptor();
5342 // Records and queries whether the instance has an indexed interceptor.
5343 inline void set_has_indexed_interceptor();
5344 inline bool has_indexed_interceptor();
5346 // Tells whether the instance is undetectable.
5347 // An undetectable object is a special class of JSObject: 'typeof' operator
5348 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5349 // a normal JS object. It is useful for implementing undetectable
5350 // document.all in Firefox & Safari.
5351 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5352 inline void set_is_undetectable();
5353 inline bool is_undetectable();
5355 // Tells whether the instance has a call-as-function handler.
5356 inline void set_is_observed();
5357 inline bool is_observed();
5359 // Tells whether the instance has a [[Call]] internal field.
5360 // This property is implemented according to ES6, section 7.2.3.
5361 inline void set_is_callable();
5362 inline bool is_callable() const;
5364 inline void set_is_strong();
5365 inline bool is_strong();
5366 inline void set_is_extensible(bool value);
5367 inline bool is_extensible();
5368 inline void set_is_prototype_map(bool value);
5369 inline bool is_prototype_map() const;
5371 inline void set_elements_kind(ElementsKind elements_kind);
5372 inline ElementsKind elements_kind();
5374 // Tells whether the instance has fast elements that are only Smis.
5375 inline bool has_fast_smi_elements();
5377 // Tells whether the instance has fast elements.
5378 inline bool has_fast_object_elements();
5379 inline bool has_fast_smi_or_object_elements();
5380 inline bool has_fast_double_elements();
5381 inline bool has_fast_elements();
5382 inline bool has_sloppy_arguments_elements();
5383 inline bool has_fixed_typed_array_elements();
5384 inline bool has_dictionary_elements();
5386 static bool IsValidElementsTransition(ElementsKind from_kind,
5387 ElementsKind to_kind);
5389 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5390 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5391 bool DictionaryElementsInPrototypeChainOnly();
5393 inline Map* ElementsTransitionMap();
5395 inline FixedArrayBase* GetInitialElements();
5397 // [raw_transitions]: Provides access to the transitions storage field.
5398 // Don't call set_raw_transitions() directly to overwrite transitions, use
5399 // the TransitionArray::ReplaceTransitions() wrapper instead!
5400 DECL_ACCESSORS(raw_transitions, Object)
5401 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5402 // (which prototype maps don't have).
5403 DECL_ACCESSORS(prototype_info, Object)
5404 // PrototypeInfo is created lazily using this helper (which installs it on
5405 // the given prototype's map).
5406 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5407 Handle<JSObject> prototype, Isolate* isolate);
5408 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5409 Handle<Map> prototype_map, Isolate* isolate);
5411 // [prototype chain validity cell]: Associated with a prototype object,
5412 // stored in that object's map's PrototypeInfo, indicates that prototype
5413 // chains through this object are currently valid. The cell will be
5414 // invalidated and replaced when the prototype chain changes.
5415 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5417 static const int kPrototypeChainValid = 0;
5418 static const int kPrototypeChainInvalid = 1;
5421 Map* FindFieldOwner(int descriptor);
5423 inline int GetInObjectPropertyOffset(int index);
5425 int NumberOfFields();
5427 // TODO(ishell): candidate with JSObject::MigrateToMap().
5428 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5429 int target_inobject, int target_unused,
5430 int* old_number_of_fields);
5431 // TODO(ishell): moveit!
5432 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5433 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5434 Handle<HeapType> type1,
5435 Handle<HeapType> type2,
5437 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5438 Representation new_representation,
5439 Handle<HeapType> new_field_type);
5440 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5441 PropertyKind new_kind,
5442 PropertyAttributes new_attributes,
5443 Representation new_representation,
5444 Handle<HeapType> new_field_type,
5445 StoreMode store_mode);
5446 static Handle<Map> CopyGeneralizeAllRepresentations(
5447 Handle<Map> map, int modify_index, StoreMode store_mode,
5448 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5450 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5451 int descriptor_number,
5452 Handle<Object> value);
5454 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5455 const char* reason);
5457 // Returns the constructor name (the name (possibly, inferred name) of the
5458 // function that was used to instantiate the object).
5459 String* constructor_name();
5461 // Tells whether the map is used for JSObjects in dictionary mode (ie
5462 // normalized objects, ie objects for which HasFastProperties returns false).
5463 // A map can never be used for both dictionary mode and fast mode JSObjects.
5464 // False by default and for HeapObjects that are not JSObjects.
5465 inline void set_dictionary_map(bool value);
5466 inline bool is_dictionary_map();
5468 // Tells whether the instance needs security checks when accessing its
5470 inline void set_is_access_check_needed(bool access_check_needed);
5471 inline bool is_access_check_needed();
5473 // Returns true if map has a non-empty stub code cache.
5474 inline bool has_code_cache();
5476 // [prototype]: implicit prototype object.
5477 DECL_ACCESSORS(prototype, Object)
5478 // TODO(jkummerow): make set_prototype private.
5479 static void SetPrototype(
5480 Handle<Map> map, Handle<Object> prototype,
5481 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5483 // [constructor]: points back to the function responsible for this map.
5484 // The field overlaps with the back pointer. All maps in a transition tree
5485 // have the same constructor, so maps with back pointers can walk the
5486 // back pointer chain until they find the map holding their constructor.
5487 DECL_ACCESSORS(constructor_or_backpointer, Object)
5488 inline Object* GetConstructor() const;
5489 inline void SetConstructor(Object* constructor,
5490 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5491 // [back pointer]: points back to the parent map from which a transition
5492 // leads to this map. The field overlaps with the constructor (see above).
5493 inline Object* GetBackPointer();
5494 inline void SetBackPointer(Object* value,
5495 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5497 // [instance descriptors]: describes the object.
5498 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5500 // [layout descriptor]: describes the object layout.
5501 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5502 // |layout descriptor| accessor which can be used from GC.
5503 inline LayoutDescriptor* layout_descriptor_gc_safe();
5504 inline bool HasFastPointerLayout() const;
5506 // |layout descriptor| accessor that is safe to call even when
5507 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5508 // |layout_descriptor| field at all).
5509 inline LayoutDescriptor* GetLayoutDescriptor();
5511 inline void UpdateDescriptors(DescriptorArray* descriptors,
5512 LayoutDescriptor* layout_descriptor);
5513 inline void InitializeDescriptors(DescriptorArray* descriptors,
5514 LayoutDescriptor* layout_descriptor);
5516 // [stub cache]: contains stubs compiled for this map.
5517 DECL_ACCESSORS(code_cache, Object)
5519 // [dependent code]: list of optimized codes that weakly embed this map.
5520 DECL_ACCESSORS(dependent_code, DependentCode)
5522 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5523 DECL_ACCESSORS(weak_cell_cache, Object)
5525 inline PropertyDetails GetLastDescriptorDetails();
5527 inline int LastAdded();
5529 inline int NumberOfOwnDescriptors();
5530 inline void SetNumberOfOwnDescriptors(int number);
5532 inline Cell* RetrieveDescriptorsPointer();
5534 inline int EnumLength();
5535 inline void SetEnumLength(int length);
5537 inline bool owns_descriptors();
5538 inline void set_owns_descriptors(bool owns_descriptors);
5539 inline void mark_unstable();
5540 inline bool is_stable();
5541 inline void set_migration_target(bool value);
5542 inline bool is_migration_target();
5543 inline void set_counter(int value);
5544 inline int counter();
5545 inline void deprecate();
5546 inline bool is_deprecated();
5547 inline bool CanBeDeprecated();
5548 // Returns a non-deprecated version of the input. If the input was not
5549 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5550 // is found by re-transitioning from the root of the transition tree using the
5551 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5553 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5555 // Returns a non-deprecated version of the input. This method may deprecate
5556 // existing maps along the way if encodings conflict. Not for use while
5557 // gathering type feedback. Use TryUpdate in those cases instead.
5558 static Handle<Map> Update(Handle<Map> map);
5560 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5561 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5562 Descriptor* descriptor,
5563 TransitionFlag flag);
5565 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5568 Handle<HeapType> type,
5569 PropertyAttributes attributes,
5570 Representation representation,
5571 TransitionFlag flag);
5573 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5576 Handle<Object> constant,
5577 PropertyAttributes attributes,
5578 TransitionFlag flag);
5580 // Returns a new map with all transitions dropped from the given map and
5581 // the ElementsKind set.
5582 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5583 ElementsKind to_kind);
5585 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5587 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5589 TransitionFlag flag);
5591 static Handle<Map> CopyForObserved(Handle<Map> map);
5593 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5594 PropertyAttributes attrs_to_add,
5595 Handle<Symbol> transition_marker,
5596 const char* reason);
5598 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5601 // Maximal number of fast properties. Used to restrict the number of map
5602 // transitions to avoid an explosion in the number of maps for objects used as
5604 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5605 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5607 Handle<Object> value,
5608 PropertyAttributes attributes,
5609 StoreFromKeyed store_mode);
5610 static Handle<Map> TransitionToAccessorProperty(
5611 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5612 Handle<Object> accessor, PropertyAttributes attributes);
5613 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5616 PropertyAttributes attributes);
5618 inline void AppendDescriptor(Descriptor* desc);
5620 // Returns a copy of the map, prepared for inserting into the transition
5621 // tree (if the |map| owns descriptors then the new one will share
5622 // descriptors with |map|).
5623 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5625 // Returns a copy of the map, with all transitions dropped from the
5626 // instance descriptors.
5627 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5628 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5630 // Returns the next free property index (only valid for FAST MODE).
5631 int NextFreePropertyIndex();
5633 // Returns the number of properties described in instance_descriptors
5634 // filtering out properties with the specified attributes.
5635 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5636 PropertyAttributes filter = NONE);
5640 // Code cache operations.
5642 // Clears the code cache.
5643 inline void ClearCodeCache(Heap* heap);
5645 // Update code cache.
5646 static void UpdateCodeCache(Handle<Map> map,
5650 // Extend the descriptor array of the map with the list of descriptors.
5651 // In case of duplicates, the latest descriptor is used.
5652 static void AppendCallbackDescriptors(Handle<Map> map,
5653 Handle<Object> descriptors);
5655 static inline int SlackForArraySize(int old_size, int size_limit);
5657 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5659 // Returns the found code or undefined if absent.
5660 Object* FindInCodeCache(Name* name, Code::Flags flags);
5662 // Returns the non-negative index of the code object if it is in the
5663 // cache and -1 otherwise.
5664 int IndexInCodeCache(Object* name, Code* code);
5666 // Removes a code object from the code cache at the given index.
5667 void RemoveFromCodeCache(Name* name, Code* code, int index);
5669 // Computes a hash value for this map, to be used in HashTables and such.
5672 // Returns the map that this map transitions to if its elements_kind
5673 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5674 // |safe_to_add_transitions| is set to false if adding transitions is not
5676 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5678 // Returns the transitioned map for this map with the most generic
5679 // elements_kind that's found in |candidates|, or null handle if no match is
5681 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5682 MapHandleList* candidates);
5684 inline bool CanTransition();
5686 inline bool IsPrimitiveMap();
5687 inline bool IsJSObjectMap();
5688 inline bool IsJSArrayMap();
5689 inline bool IsStringMap();
5690 inline bool IsJSProxyMap();
5691 inline bool IsJSGlobalProxyMap();
5692 inline bool IsJSGlobalObjectMap();
5693 inline bool IsGlobalObjectMap();
5695 inline bool CanOmitMapChecks();
5697 static void AddDependentCode(Handle<Map> map,
5698 DependentCode::DependencyGroup group,
5701 bool IsMapInArrayPrototypeChain();
5703 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5705 // Dispatched behavior.
5706 DECLARE_PRINTER(Map)
5707 DECLARE_VERIFIER(Map)
5710 void DictionaryMapVerify();
5711 void VerifyOmittedMapChecks();
5714 inline int visitor_id();
5715 inline void set_visitor_id(int visitor_id);
5717 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5718 Handle<Object> prototype,
5719 PrototypeOptimizationMode mode);
5721 static const int kMaxPreAllocatedPropertyFields = 255;
5723 // Layout description.
5724 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5725 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5726 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5727 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5728 static const int kConstructorOrBackPointerOffset =
5729 kPrototypeOffset + kPointerSize;
5730 // When there is only one transition, it is stored directly in this field;
5731 // otherwise a transition array is used.
5732 // For prototype maps, this slot is used to store this map's PrototypeInfo
5734 static const int kTransitionsOrPrototypeInfoOffset =
5735 kConstructorOrBackPointerOffset + kPointerSize;
5736 static const int kDescriptorsOffset =
5737 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5738 #if V8_DOUBLE_FIELDS_UNBOXING
5739 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5740 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5742 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5743 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5745 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5746 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5747 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5749 // Layout of pointer fields. Heap iteration code relies on them
5750 // being continuously allocated.
5751 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5752 static const int kPointerFieldsEndOffset = kSize;
5754 // Byte offsets within kInstanceSizesOffset.
5755 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5756 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5757 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5758 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5759 // Note there is one byte available for use here.
5760 static const int kUnusedByte = 2;
5761 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5762 static const int kVisitorIdByte = 3;
5763 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5765 // Byte offsets within kInstanceAttributesOffset attributes.
5766 #if V8_TARGET_LITTLE_ENDIAN
5767 // Order instance type and bit field together such that they can be loaded
5768 // together as a 16-bit word with instance type in the lower 8 bits regardless
5769 // of endianess. Also provide endian-independent offset to that 16-bit word.
5770 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5771 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5773 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5774 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5776 static const int kInstanceTypeAndBitFieldOffset =
5777 kInstanceAttributesOffset + 0;
5778 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5779 static const int kUnusedPropertyFieldsByte = 3;
5780 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5782 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5783 Internals::kMapInstanceTypeAndBitFieldOffset);
5785 // Bit positions for bit field.
5786 static const int kHasNonInstancePrototype = 0;
5787 static const int kIsCallable = 1;
5788 static const int kHasNamedInterceptor = 2;
5789 static const int kHasIndexedInterceptor = 3;
5790 static const int kIsUndetectable = 4;
5791 static const int kIsObserved = 5;
5792 static const int kIsAccessCheckNeeded = 6;
5793 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5795 // Bit positions for bit field 2
5796 static const int kIsExtensible = 0;
5798 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5799 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5801 // Derived values from bit field 2
5802 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5803 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5804 static const int8_t kMaximumBitField2FastSmiElementValue =
5805 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5806 Map::ElementsKindBits::kShift) - 1;
5807 static const int8_t kMaximumBitField2FastHoleyElementValue =
5808 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5809 Map::ElementsKindBits::kShift) - 1;
5810 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5811 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5812 Map::ElementsKindBits::kShift) - 1;
5814 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5815 kPointerFieldsEndOffset,
5816 kSize> BodyDescriptor;
5818 // Compares this map to another to see if they describe equivalent objects.
5819 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5820 // it had exactly zero inobject properties.
5821 // The "shared" flags of both this map and |other| are ignored.
5822 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5824 // Returns true if given field is unboxed double.
5825 inline bool IsUnboxedDoubleField(FieldIndex index);
5828 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5829 static void TraceAllTransitions(Map* map);
5832 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5833 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5834 Handle<LayoutDescriptor> layout_descriptor);
5837 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5838 Handle<Name> name, SimpleTransitionFlag flag);
5840 bool EquivalentToForTransition(Map* other);
5841 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5842 static Handle<Map> ShareDescriptor(Handle<Map> map,
5843 Handle<DescriptorArray> descriptors,
5844 Descriptor* descriptor);
5845 static Handle<Map> CopyInstallDescriptors(
5846 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5847 Handle<LayoutDescriptor> layout_descriptor);
5848 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5849 Descriptor* descriptor,
5850 TransitionFlag flag);
5851 static Handle<Map> CopyReplaceDescriptors(
5852 Handle<Map> map, Handle<DescriptorArray> descriptors,
5853 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5854 MaybeHandle<Name> maybe_name, const char* reason,
5855 SimpleTransitionFlag simple_flag);
5857 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5858 Handle<DescriptorArray> descriptors,
5859 Descriptor* descriptor,
5861 TransitionFlag flag);
5862 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5863 Handle<Map> map, int descriptor, PropertyKind kind,
5864 PropertyAttributes attributes, const char** reason);
5866 static Handle<Map> CopyNormalized(Handle<Map> map,
5867 PropertyNormalizationMode mode);
5869 // Fires when the layout of an object with a leaf map changes.
5870 // This includes adding transitions to the leaf map or changing
5871 // the descriptor array.
5872 inline void NotifyLeafMapLayoutChange();
5874 void DeprecateTransitionTree();
5875 bool DeprecateTarget(PropertyKind kind, Name* key,
5876 PropertyAttributes attributes,
5877 DescriptorArray* new_descriptors,
5878 LayoutDescriptor* new_layout_descriptor);
5880 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5882 // Update field type of the given descriptor to new representation and new
5883 // type. The type must be prepared for storing in descriptor array:
5884 // it must be either a simple type or a map wrapped in a weak cell.
5885 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5886 Representation new_representation,
5887 Handle<Object> new_wrapped_type);
5889 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5890 PropertyAttributes attributes);
5891 void PrintGeneralization(FILE* file,
5896 bool constant_to_field,
5897 Representation old_representation,
5898 Representation new_representation,
5899 HeapType* old_field_type,
5900 HeapType* new_field_type);
5902 static const int kFastPropertiesSoftLimit = 12;
5903 static const int kMaxFastProperties = 128;
5905 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5909 // An abstract superclass, a marker class really, for simple structure classes.
5910 // It doesn't carry much functionality but allows struct classes to be
5911 // identified in the type system.
5912 class Struct: public HeapObject {
5914 inline void InitializeBody(int object_size);
5915 DECLARE_CAST(Struct)
5919 // A simple one-element struct, useful where smis need to be boxed.
5920 class Box : public Struct {
5922 // [value]: the boxed contents.
5923 DECL_ACCESSORS(value, Object)
5927 // Dispatched behavior.
5928 DECLARE_PRINTER(Box)
5929 DECLARE_VERIFIER(Box)
5931 static const int kValueOffset = HeapObject::kHeaderSize;
5932 static const int kSize = kValueOffset + kPointerSize;
5935 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5939 // Container for metadata stored on each prototype map.
5940 class PrototypeInfo : public Struct {
5942 static const int UNREGISTERED = -1;
5944 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5945 // or Smi(0) if uninitialized.
5946 DECL_ACCESSORS(prototype_users, Object)
5947 // [registry_slot]: Slot in prototype's user registry where this user
5948 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5949 inline int registry_slot() const;
5950 inline void set_registry_slot(int slot);
5951 // [validity_cell]: Cell containing the validity bit for prototype chains
5952 // going through this object, or Smi(0) if uninitialized.
5953 DECL_ACCESSORS(validity_cell, Object)
5954 // [constructor_name]: User-friendly name of the original constructor.
5955 DECL_ACCESSORS(constructor_name, Object)
5957 DECLARE_CAST(PrototypeInfo)
5959 // Dispatched behavior.
5960 DECLARE_PRINTER(PrototypeInfo)
5961 DECLARE_VERIFIER(PrototypeInfo)
5963 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5964 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5965 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5966 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5967 static const int kSize = kConstructorNameOffset + kPointerSize;
5970 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5974 // Pair used to store both a ScopeInfo and an extension object in the extension
5975 // slot of a block context. Needed in the rare case where a declaration block
5976 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5977 // a sloppy direct eval. (In no other case both are needed at the same time.)
5978 class SloppyBlockWithEvalContextExtension : public Struct {
5980 // [scope_info]: Scope info.
5981 DECL_ACCESSORS(scope_info, ScopeInfo)
5982 // [extension]: Extension object.
5983 DECL_ACCESSORS(extension, JSObject)
5985 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5987 // Dispatched behavior.
5988 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5989 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5991 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5992 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5993 static const int kSize = kExtensionOffset + kPointerSize;
5996 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
6000 // Script describes a script which has been added to the VM.
6001 class Script: public Struct {
6010 // Script compilation types.
6011 enum CompilationType {
6012 COMPILATION_TYPE_HOST = 0,
6013 COMPILATION_TYPE_EVAL = 1
6016 // Script compilation state.
6017 enum CompilationState {
6018 COMPILATION_STATE_INITIAL = 0,
6019 COMPILATION_STATE_COMPILED = 1
6022 // [source]: the script source.
6023 DECL_ACCESSORS(source, Object)
6025 // [name]: the script name.
6026 DECL_ACCESSORS(name, Object)
6028 // [id]: the script id.
6029 DECL_ACCESSORS(id, Smi)
6031 // [line_offset]: script line offset in resource from where it was extracted.
6032 DECL_ACCESSORS(line_offset, Smi)
6034 // [column_offset]: script column offset in resource from where it was
6036 DECL_ACCESSORS(column_offset, Smi)
6038 // [context_data]: context data for the context this script was compiled in.
6039 DECL_ACCESSORS(context_data, Object)
6041 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6042 DECL_ACCESSORS(wrapper, HeapObject)
6044 // [type]: the script type.
6045 DECL_ACCESSORS(type, Smi)
6047 // [line_ends]: FixedArray of line ends positions.
6048 DECL_ACCESSORS(line_ends, Object)
6050 // [eval_from_shared]: for eval scripts the shared funcion info for the
6051 // function from which eval was called.
6052 DECL_ACCESSORS(eval_from_shared, Object)
6054 // [eval_from_instructions_offset]: the instruction offset in the code for the
6055 // function from which eval was called where eval was called.
6056 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6058 // [shared_function_infos]: weak fixed array containing all shared
6059 // function infos created from this script.
6060 DECL_ACCESSORS(shared_function_infos, Object)
6062 // [flags]: Holds an exciting bitfield.
6063 DECL_ACCESSORS(flags, Smi)
6065 // [source_url]: sourceURL from magic comment
6066 DECL_ACCESSORS(source_url, Object)
6068 // [source_url]: sourceMappingURL magic comment
6069 DECL_ACCESSORS(source_mapping_url, Object)
6071 // [compilation_type]: how the the script was compiled. Encoded in the
6073 inline CompilationType compilation_type();
6074 inline void set_compilation_type(CompilationType type);
6076 // [compilation_state]: determines whether the script has already been
6077 // compiled. Encoded in the 'flags' field.
6078 inline CompilationState compilation_state();
6079 inline void set_compilation_state(CompilationState state);
6081 // [hide_source]: determines whether the script source can be exposed as
6082 // function source. Encoded in the 'flags' field.
6083 inline bool hide_source();
6084 inline void set_hide_source(bool value);
6086 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6087 // and used by the embedder to make decisions about the script. V8 just passes
6088 // this through. Encoded in the 'flags' field.
6089 inline v8::ScriptOriginOptions origin_options();
6090 inline void set_origin_options(ScriptOriginOptions origin_options);
6092 DECLARE_CAST(Script)
6094 // If script source is an external string, check that the underlying
6095 // resource is accessible. Otherwise, always return true.
6096 inline bool HasValidSource();
6098 // Convert code position into column number.
6099 static int GetColumnNumber(Handle<Script> script, int code_pos);
6101 // Convert code position into (zero-based) line number.
6102 // The non-handlified version does not allocate, but may be much slower.
6103 static int GetLineNumber(Handle<Script> script, int code_pos);
6104 int GetLineNumber(int code_pos);
6106 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6108 // Init line_ends array with code positions of line ends inside script source.
6109 static void InitLineEnds(Handle<Script> script);
6111 // Get the JS object wrapping the given script; create it if none exists.
6112 static Handle<JSObject> GetWrapper(Handle<Script> script);
6114 // Look through the list of existing shared function infos to find one
6115 // that matches the function literal. Return empty handle if not found.
6116 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6118 // Iterate over all script objects on the heap.
6121 explicit Iterator(Isolate* isolate);
6125 WeakFixedArray::Iterator iterator_;
6126 DISALLOW_COPY_AND_ASSIGN(Iterator);
6129 // Dispatched behavior.
6130 DECLARE_PRINTER(Script)
6131 DECLARE_VERIFIER(Script)
6133 static const int kSourceOffset = HeapObject::kHeaderSize;
6134 static const int kNameOffset = kSourceOffset + kPointerSize;
6135 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6136 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6137 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6138 static const int kWrapperOffset = kContextOffset + kPointerSize;
6139 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6140 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6141 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6142 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6143 static const int kEvalFrominstructionsOffsetOffset =
6144 kEvalFromSharedOffset + kPointerSize;
6145 static const int kSharedFunctionInfosOffset =
6146 kEvalFrominstructionsOffsetOffset + kPointerSize;
6147 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6148 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6149 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6150 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6153 int GetLineNumberWithArray(int code_pos);
6155 // Bit positions in the flags field.
6156 static const int kCompilationTypeBit = 0;
6157 static const int kCompilationStateBit = 1;
6158 static const int kHideSourceBit = 2;
6159 static const int kOriginOptionsShift = 3;
6160 static const int kOriginOptionsSize = 3;
6161 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6162 << kOriginOptionsShift;
6164 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6168 // List of builtin functions we want to identify to improve code
6171 // Each entry has a name of a global object property holding an object
6172 // optionally followed by ".prototype", a name of a builtin function
6173 // on the object (the one the id is set for), and a label.
6175 // Installation of ids for the selected builtin functions is handled
6176 // by the bootstrapper.
6177 #define FUNCTIONS_WITH_ID_LIST(V) \
6178 V(Array.prototype, indexOf, ArrayIndexOf) \
6179 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6180 V(Array.prototype, push, ArrayPush) \
6181 V(Array.prototype, pop, ArrayPop) \
6182 V(Array.prototype, shift, ArrayShift) \
6183 V(Function.prototype, apply, FunctionApply) \
6184 V(Function.prototype, call, FunctionCall) \
6185 V(String.prototype, charCodeAt, StringCharCodeAt) \
6186 V(String.prototype, charAt, StringCharAt) \
6187 V(String, fromCharCode, StringFromCharCode) \
6188 V(Math, random, MathRandom) \
6189 V(Math, floor, MathFloor) \
6190 V(Math, round, MathRound) \
6191 V(Math, ceil, MathCeil) \
6192 V(Math, abs, MathAbs) \
6193 V(Math, log, MathLog) \
6194 V(Math, exp, MathExp) \
6195 V(Math, sqrt, MathSqrt) \
6196 V(Math, pow, MathPow) \
6197 V(Math, max, MathMax) \
6198 V(Math, min, MathMin) \
6199 V(Math, cos, MathCos) \
6200 V(Math, sin, MathSin) \
6201 V(Math, tan, MathTan) \
6202 V(Math, acos, MathAcos) \
6203 V(Math, asin, MathAsin) \
6204 V(Math, atan, MathAtan) \
6205 V(Math, atan2, MathAtan2) \
6206 V(Math, imul, MathImul) \
6207 V(Math, clz32, MathClz32) \
6208 V(Math, fround, MathFround)
6210 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6211 V(Atomics, load, AtomicsLoad) \
6212 V(Atomics, store, AtomicsStore)
6214 enum BuiltinFunctionId {
6216 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6218 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6219 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6220 #undef DECLARE_FUNCTION_ID
6221 // Fake id for a special case of Math.pow. Note, it continues the
6222 // list of math functions.
6227 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6228 // that both {code} and {literals} can be NULL to pass search result status.
6229 struct CodeAndLiterals {
6230 Code* code; // Cached optimized code.
6231 FixedArray* literals; // Cached literals array.
6235 // SharedFunctionInfo describes the JSFunction information that can be
6236 // shared by multiple instances of the function.
6237 class SharedFunctionInfo: public HeapObject {
6239 // [name]: Function name.
6240 DECL_ACCESSORS(name, Object)
6242 // [code]: Function code.
6243 DECL_ACCESSORS(code, Code)
6244 inline void ReplaceCode(Code* code);
6246 // [optimized_code_map]: Map from native context to optimized code
6247 // and a shared literals array or Smi(0) if none.
6248 DECL_ACCESSORS(optimized_code_map, Object)
6250 // Returns entry from optimized code map for specified context and OSR entry.
6251 // Note that {code == nullptr} indicates no matching entry has been found,
6252 // whereas {literals == nullptr} indicates the code is context-independent.
6253 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6254 BailoutId osr_ast_id);
6256 // Clear optimized code map.
6257 void ClearOptimizedCodeMap();
6259 // Removed a specific optimized code object from the optimized code map.
6260 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6262 // Trims the optimized code map after entries have been removed.
6263 void TrimOptimizedCodeMap(int shrink_by);
6265 // Add a new entry to the optimized code map for context-independent code.
6266 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6269 // Add a new entry to the optimized code map for context-dependent code.
6270 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6271 Handle<Context> native_context,
6273 Handle<FixedArray> literals,
6274 BailoutId osr_ast_id);
6276 // Set up the link between shared function info and the script. The shared
6277 // function info is added to the list on the script.
6278 static void SetScript(Handle<SharedFunctionInfo> shared,
6279 Handle<Object> script_object);
6281 // Layout description of the optimized code map.
6282 static const int kNextMapIndex = 0;
6283 static const int kSharedCodeIndex = 1;
6284 static const int kEntriesStart = 2;
6285 static const int kContextOffset = 0;
6286 static const int kCachedCodeOffset = 1;
6287 static const int kLiteralsOffset = 2;
6288 static const int kOsrAstIdOffset = 3;
6289 static const int kEntryLength = 4;
6290 static const int kInitialLength = kEntriesStart + kEntryLength;
6292 // [scope_info]: Scope info.
6293 DECL_ACCESSORS(scope_info, ScopeInfo)
6295 // [construct stub]: Code stub for constructing instances of this function.
6296 DECL_ACCESSORS(construct_stub, Code)
6298 // Returns if this function has been compiled to native code yet.
6299 inline bool is_compiled();
6301 // [length]: The function length - usually the number of declared parameters.
6302 // Use up to 2^30 parameters.
6303 inline int length() const;
6304 inline void set_length(int value);
6306 // [internal formal parameter count]: The declared number of parameters.
6307 // For subclass constructors, also includes new.target.
6308 // The size of function's frame is internal_formal_parameter_count + 1.
6309 inline int internal_formal_parameter_count() const;
6310 inline void set_internal_formal_parameter_count(int value);
6312 // Set the formal parameter count so the function code will be
6313 // called without using argument adaptor frames.
6314 inline void DontAdaptArguments();
6316 // [expected_nof_properties]: Expected number of properties for the function.
6317 inline int expected_nof_properties() const;
6318 inline void set_expected_nof_properties(int value);
6320 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6321 // (increasingly) from crankshafted code where sufficient feedback isn't
6323 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6325 // Unconditionally clear the type feedback vector (including vector ICs).
6326 void ClearTypeFeedbackInfo();
6328 // Clear the type feedback vector with a more subtle policy at GC time.
6329 void ClearTypeFeedbackInfoAtGCTime();
6332 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6333 // even if the GC moves this SharedFunctionInfo.
6334 inline int unique_id() const;
6335 inline void set_unique_id(int value);
6338 // [instance class name]: class name for instances.
6339 DECL_ACCESSORS(instance_class_name, Object)
6341 // [function data]: This field holds some additional data for function.
6342 // Currently it has one of:
6343 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6344 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6345 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6346 // In the long run we don't want all functions to have this field but
6347 // we can fix that when we have a better model for storing hidden data
6349 DECL_ACCESSORS(function_data, Object)
6351 inline bool IsApiFunction();
6352 inline FunctionTemplateInfo* get_api_func_data();
6353 inline bool HasBuiltinFunctionId();
6354 inline BuiltinFunctionId builtin_function_id();
6355 inline bool HasBytecodeArray();
6356 inline BytecodeArray* bytecode_array();
6358 // [script info]: Script from which the function originates.
6359 DECL_ACCESSORS(script, Object)
6361 // [num_literals]: Number of literals used by this function.
6362 inline int num_literals() const;
6363 inline void set_num_literals(int value);
6365 // [start_position_and_type]: Field used to store both the source code
6366 // position, whether or not the function is a function expression,
6367 // and whether or not the function is a toplevel function. The two
6368 // least significants bit indicates whether the function is an
6369 // expression and the rest contains the source code position.
6370 inline int start_position_and_type() const;
6371 inline void set_start_position_and_type(int value);
6373 // The function is subject to debugging if a debug info is attached.
6374 inline bool HasDebugInfo();
6375 inline DebugInfo* GetDebugInfo();
6377 // A function has debug code if the compiled code has debug break slots.
6378 inline bool HasDebugCode();
6380 // [debug info]: Debug information.
6381 DECL_ACCESSORS(debug_info, Object)
6383 // [inferred name]: Name inferred from variable or property
6384 // assignment of this function. Used to facilitate debugging and
6385 // profiling of JavaScript code written in OO style, where almost
6386 // all functions are anonymous but are assigned to object
6388 DECL_ACCESSORS(inferred_name, String)
6390 // The function's name if it is non-empty, otherwise the inferred name.
6391 String* DebugName();
6393 // Position of the 'function' token in the script source.
6394 inline int function_token_position() const;
6395 inline void set_function_token_position(int function_token_position);
6397 // Position of this function in the script source.
6398 inline int start_position() const;
6399 inline void set_start_position(int start_position);
6401 // End position of this function in the script source.
6402 inline int end_position() const;
6403 inline void set_end_position(int end_position);
6405 // Is this function a function expression in the source code.
6406 DECL_BOOLEAN_ACCESSORS(is_expression)
6408 // Is this function a top-level function (scripts, evals).
6409 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6411 // Bit field containing various information collected by the compiler to
6412 // drive optimization.
6413 inline int compiler_hints() const;
6414 inline void set_compiler_hints(int value);
6416 inline int ast_node_count() const;
6417 inline void set_ast_node_count(int count);
6419 inline int profiler_ticks() const;
6420 inline void set_profiler_ticks(int ticks);
6422 // Inline cache age is used to infer whether the function survived a context
6423 // disposal or not. In the former case we reset the opt_count.
6424 inline int ic_age();
6425 inline void set_ic_age(int age);
6427 // Indicates if this function can be lazy compiled.
6428 // This is used to determine if we can safely flush code from a function
6429 // when doing GC if we expect that the function will no longer be used.
6430 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6432 // Indicates if this function can be lazy compiled without a context.
6433 // This is used to determine if we can force compilation without reaching
6434 // the function through program execution but through other means (e.g. heap
6435 // iteration by the debugger).
6436 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6438 // Indicates whether optimizations have been disabled for this
6439 // shared function info. If a function is repeatedly optimized or if
6440 // we cannot optimize the function we disable optimization to avoid
6441 // spending time attempting to optimize it again.
6442 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6444 // Indicates the language mode.
6445 inline LanguageMode language_mode();
6446 inline void set_language_mode(LanguageMode language_mode);
6448 // False if the function definitely does not allocate an arguments object.
6449 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6451 // Indicates that this function uses a super property (or an eval that may
6452 // use a super property).
6453 // This is needed to set up the [[HomeObject]] on the function instance.
6454 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6456 // True if the function has any duplicated parameter names.
6457 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6459 // Indicates whether the function is a native function.
6460 // These needs special treatment in .call and .apply since
6461 // null passed as the receiver should not be translated to the
6463 DECL_BOOLEAN_ACCESSORS(native)
6465 // Indicate that this function should always be inlined in optimized code.
6466 DECL_BOOLEAN_ACCESSORS(force_inline)
6468 // Indicates that the function was created by the Function function.
6469 // Though it's anonymous, toString should treat it as if it had the name
6470 // "anonymous". We don't set the name itself so that the system does not
6471 // see a binding for it.
6472 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6474 // Indicates whether the function is a bound function created using
6475 // the bind function.
6476 DECL_BOOLEAN_ACCESSORS(bound)
6478 // Indicates that the function is anonymous (the name field can be set
6479 // through the API, which does not change this flag).
6480 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6482 // Is this a function or top-level/eval code.
6483 DECL_BOOLEAN_ACCESSORS(is_function)
6485 // Indicates that code for this function cannot be compiled with Crankshaft.
6486 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6488 // Indicates that code for this function cannot be flushed.
6489 DECL_BOOLEAN_ACCESSORS(dont_flush)
6491 // Indicates that this function is a generator.
6492 DECL_BOOLEAN_ACCESSORS(is_generator)
6494 // Indicates that this function is an arrow function.
6495 DECL_BOOLEAN_ACCESSORS(is_arrow)
6497 // Indicates that this function is a concise method.
6498 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6500 // Indicates that this function is an accessor (getter or setter).
6501 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6503 // Indicates that this function is a default constructor.
6504 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6506 // Indicates that this function is an asm function.
6507 DECL_BOOLEAN_ACCESSORS(asm_function)
6509 // Indicates that the the shared function info is deserialized from cache.
6510 DECL_BOOLEAN_ACCESSORS(deserialized)
6512 // Indicates that the the shared function info has never been compiled before.
6513 DECL_BOOLEAN_ACCESSORS(never_compiled)
6515 inline FunctionKind kind();
6516 inline void set_kind(FunctionKind kind);
6518 // Indicates whether or not the code in the shared function support
6520 inline bool has_deoptimization_support();
6522 // Enable deoptimization support through recompiled code.
6523 void EnableDeoptimizationSupport(Code* recompiled);
6525 // Disable (further) attempted optimization of all functions sharing this
6526 // shared function info.
6527 void DisableOptimization(BailoutReason reason);
6529 inline BailoutReason disable_optimization_reason();
6531 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6532 // code, returns whether it asserted (i.e., always true if assertions are
6534 bool VerifyBailoutId(BailoutId id);
6536 // [source code]: Source code for the function.
6537 bool HasSourceCode() const;
6538 Handle<Object> GetSourceCode();
6540 // Number of times the function was optimized.
6541 inline int opt_count();
6542 inline void set_opt_count(int opt_count);
6544 // Number of times the function was deoptimized.
6545 inline void set_deopt_count(int value);
6546 inline int deopt_count();
6547 inline void increment_deopt_count();
6549 // Number of time we tried to re-enable optimization after it
6550 // was disabled due to high number of deoptimizations.
6551 inline void set_opt_reenable_tries(int value);
6552 inline int opt_reenable_tries();
6554 inline void TryReenableOptimization();
6556 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6557 inline void set_counters(int value);
6558 inline int counters() const;
6560 // Stores opt_count and bailout_reason as bit-fields.
6561 inline void set_opt_count_and_bailout_reason(int value);
6562 inline int opt_count_and_bailout_reason() const;
6564 inline void set_disable_optimization_reason(BailoutReason reason);
6566 // Tells whether this function should be subject to debugging.
6567 inline bool IsSubjectToDebugging();
6569 // Whether this function is defined in native code or extensions.
6570 inline bool IsBuiltin();
6572 // Check whether or not this function is inlineable.
6573 bool IsInlineable();
6575 // Source size of this function.
6578 // Calculate the instance size.
6579 int CalculateInstanceSize();
6581 // Calculate the number of in-object properties.
6582 int CalculateInObjectProperties();
6584 inline bool has_simple_parameters();
6586 // Initialize a SharedFunctionInfo from a parsed function literal.
6587 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6588 FunctionLiteral* lit);
6590 // Dispatched behavior.
6591 DECLARE_PRINTER(SharedFunctionInfo)
6592 DECLARE_VERIFIER(SharedFunctionInfo)
6594 void ResetForNewContext(int new_ic_age);
6596 // Iterate over all shared function infos that are created from a script.
6597 // That excludes shared function infos created for API functions and C++
6601 explicit Iterator(Isolate* isolate);
6602 SharedFunctionInfo* Next();
6607 Script::Iterator script_iterator_;
6608 WeakFixedArray::Iterator sfi_iterator_;
6609 DisallowHeapAllocation no_gc_;
6610 DISALLOW_COPY_AND_ASSIGN(Iterator);
6613 DECLARE_CAST(SharedFunctionInfo)
6616 static const int kDontAdaptArgumentsSentinel = -1;
6618 // Layout description.
6620 static const int kNameOffset = HeapObject::kHeaderSize;
6621 static const int kCodeOffset = kNameOffset + kPointerSize;
6622 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6623 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6624 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6625 static const int kInstanceClassNameOffset =
6626 kConstructStubOffset + kPointerSize;
6627 static const int kFunctionDataOffset =
6628 kInstanceClassNameOffset + kPointerSize;
6629 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6630 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6631 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6632 static const int kFeedbackVectorOffset =
6633 kInferredNameOffset + kPointerSize;
6635 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6636 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6638 // Just to not break the postmortrem support with conditional offsets
6639 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6640 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6643 #if V8_HOST_ARCH_32_BIT
6645 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6646 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6647 static const int kExpectedNofPropertiesOffset =
6648 kFormalParameterCountOffset + kPointerSize;
6649 static const int kNumLiteralsOffset =
6650 kExpectedNofPropertiesOffset + kPointerSize;
6651 static const int kStartPositionAndTypeOffset =
6652 kNumLiteralsOffset + kPointerSize;
6653 static const int kEndPositionOffset =
6654 kStartPositionAndTypeOffset + kPointerSize;
6655 static const int kFunctionTokenPositionOffset =
6656 kEndPositionOffset + kPointerSize;
6657 static const int kCompilerHintsOffset =
6658 kFunctionTokenPositionOffset + kPointerSize;
6659 static const int kOptCountAndBailoutReasonOffset =
6660 kCompilerHintsOffset + kPointerSize;
6661 static const int kCountersOffset =
6662 kOptCountAndBailoutReasonOffset + kPointerSize;
6663 static const int kAstNodeCountOffset =
6664 kCountersOffset + kPointerSize;
6665 static const int kProfilerTicksOffset =
6666 kAstNodeCountOffset + kPointerSize;
6669 static const int kSize = kProfilerTicksOffset + kPointerSize;
6671 // The only reason to use smi fields instead of int fields
6672 // is to allow iteration without maps decoding during
6673 // garbage collections.
6674 // To avoid wasting space on 64-bit architectures we use
6675 // the following trick: we group integer fields into pairs
6676 // The least significant integer in each pair is shifted left by 1.
6677 // By doing this we guarantee that LSB of each kPointerSize aligned
6678 // word is not set and thus this word cannot be treated as pointer
6679 // to HeapObject during old space traversal.
6680 #if V8_TARGET_LITTLE_ENDIAN
6681 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6682 static const int kFormalParameterCountOffset =
6683 kLengthOffset + kIntSize;
6685 static const int kExpectedNofPropertiesOffset =
6686 kFormalParameterCountOffset + kIntSize;
6687 static const int kNumLiteralsOffset =
6688 kExpectedNofPropertiesOffset + kIntSize;
6690 static const int kEndPositionOffset =
6691 kNumLiteralsOffset + kIntSize;
6692 static const int kStartPositionAndTypeOffset =
6693 kEndPositionOffset + kIntSize;
6695 static const int kFunctionTokenPositionOffset =
6696 kStartPositionAndTypeOffset + kIntSize;
6697 static const int kCompilerHintsOffset =
6698 kFunctionTokenPositionOffset + kIntSize;
6700 static const int kOptCountAndBailoutReasonOffset =
6701 kCompilerHintsOffset + kIntSize;
6702 static const int kCountersOffset =
6703 kOptCountAndBailoutReasonOffset + kIntSize;
6705 static const int kAstNodeCountOffset =
6706 kCountersOffset + kIntSize;
6707 static const int kProfilerTicksOffset =
6708 kAstNodeCountOffset + kIntSize;
6711 static const int kSize = kProfilerTicksOffset + kIntSize;
6713 #elif V8_TARGET_BIG_ENDIAN
6714 static const int kFormalParameterCountOffset =
6715 kLastPointerFieldOffset + kPointerSize;
6716 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6718 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6719 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6721 static const int kStartPositionAndTypeOffset =
6722 kExpectedNofPropertiesOffset + kIntSize;
6723 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6725 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6726 static const int kFunctionTokenPositionOffset =
6727 kCompilerHintsOffset + kIntSize;
6729 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6730 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6732 static const int kProfilerTicksOffset =
6733 kOptCountAndBailoutReasonOffset + kIntSize;
6734 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6737 static const int kSize = kAstNodeCountOffset + kIntSize;
6740 #error Unknown byte ordering
6741 #endif // Big endian
6745 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6747 typedef FixedBodyDescriptor<kNameOffset,
6748 kLastPointerFieldOffset + kPointerSize,
6749 kSize> BodyDescriptor;
6751 // Bit positions in start_position_and_type.
6752 // The source code start position is in the 30 most significant bits of
6753 // the start_position_and_type field.
6754 static const int kIsExpressionBit = 0;
6755 static const int kIsTopLevelBit = 1;
6756 static const int kStartPositionShift = 2;
6757 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6759 // Bit positions in compiler_hints.
6760 enum CompilerHints {
6761 kAllowLazyCompilation,
6762 kAllowLazyCompilationWithoutContext,
6763 kOptimizationDisabled,
6765 kStrictModeFunction,
6766 kStrongModeFunction,
6769 kHasDuplicateParameters,
6773 kNameShouldPrintAsAnonymous,
6780 kIsAccessorFunction,
6781 kIsDefaultConstructor,
6782 kIsSubclassConstructor,
6788 kCompilerHintsCount // Pseudo entry
6790 // Add hints for other modes when they're added.
6791 STATIC_ASSERT(LANGUAGE_END == 3);
6793 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6795 class DeoptCountBits : public BitField<int, 0, 4> {};
6796 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6797 class ICAgeBits : public BitField<int, 22, 8> {};
6799 class OptCountBits : public BitField<int, 0, 22> {};
6800 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6803 #if V8_HOST_ARCH_32_BIT
6804 // On 32 bit platforms, compiler hints is a smi.
6805 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6806 static const int kCompilerHintsSize = kPointerSize;
6808 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6809 static const int kCompilerHintsSmiTagSize = 0;
6810 static const int kCompilerHintsSize = kIntSize;
6813 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6814 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6817 // Constants for optimizing codegen for strict mode function and
6819 // Allows to use byte-width instructions.
6820 static const int kStrictModeBitWithinByte =
6821 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6822 static const int kStrongModeBitWithinByte =
6823 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6825 static const int kNativeBitWithinByte =
6826 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6828 static const int kBoundBitWithinByte =
6829 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6831 #if defined(V8_TARGET_LITTLE_ENDIAN)
6832 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6833 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6834 static const int kStrongModeByteOffset =
6835 kCompilerHintsOffset +
6836 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6837 static const int kNativeByteOffset = kCompilerHintsOffset +
6838 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6839 static const int kBoundByteOffset =
6840 kCompilerHintsOffset +
6841 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6842 #elif defined(V8_TARGET_BIG_ENDIAN)
6843 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6844 (kCompilerHintsSize - 1) -
6845 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6846 static const int kStrongModeByteOffset =
6847 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6848 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6849 static const int kNativeByteOffset = kCompilerHintsOffset +
6850 (kCompilerHintsSize - 1) -
6851 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6852 static const int kBoundByteOffset =
6853 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6854 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6856 #error Unknown byte ordering
6860 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6864 // Printing support.
6865 struct SourceCodeOf {
6866 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6867 : value(v), max_length(max) {}
6868 const SharedFunctionInfo* value;
6873 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6876 class JSGeneratorObject: public JSObject {
6878 // [function]: The function corresponding to this generator object.
6879 DECL_ACCESSORS(function, JSFunction)
6881 // [context]: The context of the suspended computation.
6882 DECL_ACCESSORS(context, Context)
6884 // [receiver]: The receiver of the suspended computation.
6885 DECL_ACCESSORS(receiver, Object)
6887 // [continuation]: Offset into code of continuation.
6889 // A positive offset indicates a suspended generator. The special
6890 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6891 // cannot be resumed.
6892 inline int continuation() const;
6893 inline void set_continuation(int continuation);
6894 inline bool is_closed();
6895 inline bool is_executing();
6896 inline bool is_suspended();
6898 // [operand_stack]: Saved operand stack.
6899 DECL_ACCESSORS(operand_stack, FixedArray)
6901 DECLARE_CAST(JSGeneratorObject)
6903 // Dispatched behavior.
6904 DECLARE_PRINTER(JSGeneratorObject)
6905 DECLARE_VERIFIER(JSGeneratorObject)
6907 // Magic sentinel values for the continuation.
6908 static const int kGeneratorExecuting = -1;
6909 static const int kGeneratorClosed = 0;
6911 // Layout description.
6912 static const int kFunctionOffset = JSObject::kHeaderSize;
6913 static const int kContextOffset = kFunctionOffset + kPointerSize;
6914 static const int kReceiverOffset = kContextOffset + kPointerSize;
6915 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6916 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6917 static const int kSize = kOperandStackOffset + kPointerSize;
6919 // Resume mode, for use by runtime functions.
6920 enum ResumeMode { NEXT, THROW };
6923 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6927 // Representation for module instance objects.
6928 class JSModule: public JSObject {
6930 // [context]: the context holding the module's locals, or undefined if none.
6931 DECL_ACCESSORS(context, Object)
6933 // [scope_info]: Scope info.
6934 DECL_ACCESSORS(scope_info, ScopeInfo)
6936 DECLARE_CAST(JSModule)
6938 // Dispatched behavior.
6939 DECLARE_PRINTER(JSModule)
6940 DECLARE_VERIFIER(JSModule)
6942 // Layout description.
6943 static const int kContextOffset = JSObject::kHeaderSize;
6944 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6945 static const int kSize = kScopeInfoOffset + kPointerSize;
6948 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6952 // JSFunction describes JavaScript functions.
6953 class JSFunction: public JSObject {
6955 // [prototype_or_initial_map]:
6956 DECL_ACCESSORS(prototype_or_initial_map, Object)
6958 // [shared]: The information about the function that
6959 // can be shared by instances.
6960 DECL_ACCESSORS(shared, SharedFunctionInfo)
6962 // [context]: The context for this function.
6963 inline Context* context();
6964 inline void set_context(Object* context);
6965 inline JSObject* global_proxy();
6967 // [code]: The generated code object for this function. Executed
6968 // when the function is invoked, e.g. foo() or new foo(). See
6969 // [[Call]] and [[Construct]] description in ECMA-262, section
6971 inline Code* code();
6972 inline void set_code(Code* code);
6973 inline void set_code_no_write_barrier(Code* code);
6974 inline void ReplaceCode(Code* code);
6976 // Tells whether this function is builtin.
6977 inline bool IsBuiltin();
6979 // Tells whether this function inlines the given shared function info.
6980 bool Inlines(SharedFunctionInfo* candidate);
6982 // Tells whether this function should be subject to debugging.
6983 inline bool IsSubjectToDebugging();
6985 // Tells whether or not the function needs arguments adaption.
6986 inline bool NeedsArgumentsAdaption();
6988 // Tells whether or not this function has been optimized.
6989 inline bool IsOptimized();
6991 // Mark this function for lazy recompilation. The function will be
6992 // recompiled the next time it is executed.
6993 void MarkForOptimization();
6994 void AttemptConcurrentOptimization();
6996 // Tells whether or not the function is already marked for lazy
6998 inline bool IsMarkedForOptimization();
6999 inline bool IsMarkedForConcurrentOptimization();
7001 // Tells whether or not the function is on the concurrent recompilation queue.
7002 inline bool IsInOptimizationQueue();
7004 // Inobject slack tracking is the way to reclaim unused inobject space.
7006 // The instance size is initially determined by adding some slack to
7007 // expected_nof_properties (to allow for a few extra properties added
7008 // after the constructor). There is no guarantee that the extra space
7009 // will not be wasted.
7011 // Here is the algorithm to reclaim the unused inobject space:
7012 // - Detect the first constructor call for this JSFunction.
7013 // When it happens enter the "in progress" state: initialize construction
7014 // counter in the initial_map.
7015 // - While the tracking is in progress create objects filled with
7016 // one_pointer_filler_map instead of undefined_value. This way they can be
7017 // resized quickly and safely.
7018 // - Once enough objects have been created compute the 'slack'
7019 // (traverse the map transition tree starting from the
7020 // initial_map and find the lowest value of unused_property_fields).
7021 // - Traverse the transition tree again and decrease the instance size
7022 // of every map. Existing objects will resize automatically (they are
7023 // filled with one_pointer_filler_map). All further allocations will
7024 // use the adjusted instance size.
7025 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7026 // allocations made using different closures could actually create different
7027 // kind of objects (see prototype inheritance pattern).
7029 // Important: inobject slack tracking is not attempted during the snapshot
7032 // True if the initial_map is set and the object constructions countdown
7033 // counter is not zero.
7034 static const int kGenerousAllocationCount =
7035 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7036 inline bool IsInobjectSlackTrackingInProgress();
7038 // Starts the tracking.
7039 // Initializes object constructions countdown counter in the initial map.
7040 void StartInobjectSlackTracking();
7042 // Completes the tracking.
7043 void CompleteInobjectSlackTracking();
7045 // [literals_or_bindings]: Fixed array holding either
7046 // the materialized literals or the bindings of a bound function.
7048 // If the function contains object, regexp or array literals, the
7049 // literals array prefix contains the object, regexp, and array
7050 // function to be used when creating these literals. This is
7051 // necessary so that we do not dynamically lookup the object, regexp
7052 // or array functions. Performing a dynamic lookup, we might end up
7053 // using the functions from a new context that we should not have
7056 // On bound functions, the array is a (copy-on-write) fixed-array containing
7057 // the function that was bound, bound this-value and any bound
7058 // arguments. Bound functions never contain literals.
7059 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7061 inline FixedArray* literals();
7062 inline void set_literals(FixedArray* literals);
7064 inline FixedArray* function_bindings();
7065 inline void set_function_bindings(FixedArray* bindings);
7067 // The initial map for an object created by this constructor.
7068 inline Map* initial_map();
7069 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7070 Handle<Object> prototype);
7071 inline bool has_initial_map();
7072 static void EnsureHasInitialMap(Handle<JSFunction> function);
7074 // Get and set the prototype property on a JSFunction. If the
7075 // function has an initial map the prototype is set on the initial
7076 // map. Otherwise, the prototype is put in the initial map field
7077 // until an initial map is needed.
7078 inline bool has_prototype();
7079 inline bool has_instance_prototype();
7080 inline Object* prototype();
7081 inline Object* instance_prototype();
7082 static void SetPrototype(Handle<JSFunction> function,
7083 Handle<Object> value);
7084 static void SetInstancePrototype(Handle<JSFunction> function,
7085 Handle<Object> value);
7087 // Creates a new closure for the fucntion with the same bindings,
7088 // bound values, and prototype. An equivalent of spec operations
7089 // ``CloneMethod`` and ``CloneBoundFunction``.
7090 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7092 // After prototype is removed, it will not be created when accessed, and
7093 // [[Construct]] from this function will not be allowed.
7094 bool RemovePrototype();
7095 inline bool should_have_prototype();
7097 // Accessor for this function's initial map's [[class]]
7098 // property. This is primarily used by ECMA native functions. This
7099 // method sets the class_name field of this function's initial map
7100 // to a given value. It creates an initial map if this function does
7101 // not have one. Note that this method does not copy the initial map
7102 // if it has one already, but simply replaces it with the new value.
7103 // Instances created afterwards will have a map whose [[class]] is
7104 // set to 'value', but there is no guarantees on instances created
7106 void SetInstanceClassName(String* name);
7108 // Returns if this function has been compiled to native code yet.
7109 inline bool is_compiled();
7111 // Returns `false` if formal parameters include rest parameters, optional
7112 // parameters, or destructuring parameters.
7113 // TODO(caitp): make this a flag set during parsing
7114 inline bool has_simple_parameters();
7116 // [next_function_link]: Links functions into various lists, e.g. the list
7117 // of optimized functions hanging off the native_context. The CodeFlusher
7118 // uses this link to chain together flushing candidates. Treated weakly
7119 // by the garbage collector.
7120 DECL_ACCESSORS(next_function_link, Object)
7122 // Prints the name of the function using PrintF.
7123 void PrintName(FILE* out = stdout);
7125 DECLARE_CAST(JSFunction)
7127 // Iterates the objects, including code objects indirectly referenced
7128 // through pointers to the first instruction in the code object.
7129 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7131 // Dispatched behavior.
7132 DECLARE_PRINTER(JSFunction)
7133 DECLARE_VERIFIER(JSFunction)
7135 // Returns the number of allocated literals.
7136 inline int NumberOfLiterals();
7138 // Used for flags such as --hydrogen-filter.
7139 bool PassesFilter(const char* raw_filter);
7141 // The function's name if it is configured, otherwise shared function info
7143 static Handle<String> GetDebugName(Handle<JSFunction> function);
7145 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7146 // kSize) is weak and has special handling during garbage collection.
7147 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7148 static const int kPrototypeOrInitialMapOffset =
7149 kCodeEntryOffset + kPointerSize;
7150 static const int kSharedFunctionInfoOffset =
7151 kPrototypeOrInitialMapOffset + kPointerSize;
7152 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7153 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7154 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7155 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7156 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7158 // Layout of the bound-function binding array.
7159 static const int kBoundFunctionIndex = 0;
7160 static const int kBoundThisIndex = 1;
7161 static const int kBoundArgumentsStartIndex = 2;
7164 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7168 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7169 // and the prototype is hidden. JSGlobalProxy always delegates
7170 // property accesses to its prototype if the prototype is not null.
7172 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7174 // Accessing a JSGlobalProxy requires security check.
7176 class JSGlobalProxy : public JSObject {
7178 // [native_context]: the owner native context of this global proxy object.
7179 // It is null value if this object is not used by any context.
7180 DECL_ACCESSORS(native_context, Object)
7182 // [hash]: The hash code property (undefined if not initialized yet).
7183 DECL_ACCESSORS(hash, Object)
7185 DECLARE_CAST(JSGlobalProxy)
7187 inline bool IsDetachedFrom(GlobalObject* global) const;
7189 // Dispatched behavior.
7190 DECLARE_PRINTER(JSGlobalProxy)
7191 DECLARE_VERIFIER(JSGlobalProxy)
7193 // Layout description.
7194 static const int kNativeContextOffset = JSObject::kHeaderSize;
7195 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7196 static const int kSize = kHashOffset + kPointerSize;
7199 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7203 // Common super class for JavaScript global objects and the special
7204 // builtins global objects.
7205 class GlobalObject: public JSObject {
7207 // [builtins]: the object holding the runtime routines written in JS.
7208 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7210 // [native context]: the natives corresponding to this global object.
7211 DECL_ACCESSORS(native_context, Context)
7213 // [global proxy]: the global proxy object of the context
7214 DECL_ACCESSORS(global_proxy, JSObject)
7216 DECLARE_CAST(GlobalObject)
7218 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7220 // Ensure that the global object has a cell for the given property name.
7221 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7224 // Layout description.
7225 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7226 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7227 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7228 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7231 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7235 // JavaScript global object.
7236 class JSGlobalObject: public GlobalObject {
7238 DECLARE_CAST(JSGlobalObject)
7240 inline bool IsDetached();
7242 // Dispatched behavior.
7243 DECLARE_PRINTER(JSGlobalObject)
7244 DECLARE_VERIFIER(JSGlobalObject)
7246 // Layout description.
7247 static const int kSize = GlobalObject::kHeaderSize;
7250 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7254 // Builtins global object which holds the runtime routines written in
7256 class JSBuiltinsObject: public GlobalObject {
7258 DECLARE_CAST(JSBuiltinsObject)
7260 // Dispatched behavior.
7261 DECLARE_PRINTER(JSBuiltinsObject)
7262 DECLARE_VERIFIER(JSBuiltinsObject)
7264 // Layout description.
7265 static const int kSize = GlobalObject::kHeaderSize;
7268 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7272 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7273 class JSValue: public JSObject {
7275 // [value]: the object being wrapped.
7276 DECL_ACCESSORS(value, Object)
7278 DECLARE_CAST(JSValue)
7280 // Dispatched behavior.
7281 DECLARE_PRINTER(JSValue)
7282 DECLARE_VERIFIER(JSValue)
7284 // Layout description.
7285 static const int kValueOffset = JSObject::kHeaderSize;
7286 static const int kSize = kValueOffset + kPointerSize;
7289 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7295 // Representation for JS date objects.
7296 class JSDate: public JSObject {
7298 // If one component is NaN, all of them are, indicating a NaN time value.
7299 // [value]: the time value.
7300 DECL_ACCESSORS(value, Object)
7301 // [year]: caches year. Either undefined, smi, or NaN.
7302 DECL_ACCESSORS(year, Object)
7303 // [month]: caches month. Either undefined, smi, or NaN.
7304 DECL_ACCESSORS(month, Object)
7305 // [day]: caches day. Either undefined, smi, or NaN.
7306 DECL_ACCESSORS(day, Object)
7307 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7308 DECL_ACCESSORS(weekday, Object)
7309 // [hour]: caches hours. Either undefined, smi, or NaN.
7310 DECL_ACCESSORS(hour, Object)
7311 // [min]: caches minutes. Either undefined, smi, or NaN.
7312 DECL_ACCESSORS(min, Object)
7313 // [sec]: caches seconds. Either undefined, smi, or NaN.
7314 DECL_ACCESSORS(sec, Object)
7315 // [cache stamp]: sample of the date cache stamp at the
7316 // moment when chached fields were cached.
7317 DECL_ACCESSORS(cache_stamp, Object)
7319 DECLARE_CAST(JSDate)
7321 // Returns the date field with the specified index.
7322 // See FieldIndex for the list of date fields.
7323 static Object* GetField(Object* date, Smi* index);
7325 void SetValue(Object* value, bool is_value_nan);
7327 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7328 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7329 Handle<JSReceiver> receiver, Handle<Object> hint);
7331 // Dispatched behavior.
7332 DECLARE_PRINTER(JSDate)
7333 DECLARE_VERIFIER(JSDate)
7335 // The order is important. It must be kept in sync with date macros
7346 kFirstUncachedField,
7347 kMillisecond = kFirstUncachedField,
7351 kYearUTC = kFirstUTCField,
7364 // Layout description.
7365 static const int kValueOffset = JSObject::kHeaderSize;
7366 static const int kYearOffset = kValueOffset + kPointerSize;
7367 static const int kMonthOffset = kYearOffset + kPointerSize;
7368 static const int kDayOffset = kMonthOffset + kPointerSize;
7369 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7370 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7371 static const int kMinOffset = kHourOffset + kPointerSize;
7372 static const int kSecOffset = kMinOffset + kPointerSize;
7373 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7374 static const int kSize = kCacheStampOffset + kPointerSize;
7377 inline Object* DoGetField(FieldIndex index);
7379 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7381 // Computes and caches the cacheable fields of the date.
7382 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7385 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7389 // Representation of message objects used for error reporting through
7390 // the API. The messages are formatted in JavaScript so this object is
7391 // a real JavaScript object. The information used for formatting the
7392 // error messages are not directly accessible from JavaScript to
7393 // prevent leaking information to user code called during error
7395 class JSMessageObject: public JSObject {
7397 // [type]: the type of error message.
7398 inline int type() const;
7399 inline void set_type(int value);
7401 // [arguments]: the arguments for formatting the error message.
7402 DECL_ACCESSORS(argument, Object)
7404 // [script]: the script from which the error message originated.
7405 DECL_ACCESSORS(script, Object)
7407 // [stack_frames]: an array of stack frames for this error object.
7408 DECL_ACCESSORS(stack_frames, Object)
7410 // [start_position]: the start position in the script for the error message.
7411 inline int start_position() const;
7412 inline void set_start_position(int value);
7414 // [end_position]: the end position in the script for the error message.
7415 inline int end_position() const;
7416 inline void set_end_position(int value);
7418 DECLARE_CAST(JSMessageObject)
7420 // Dispatched behavior.
7421 DECLARE_PRINTER(JSMessageObject)
7422 DECLARE_VERIFIER(JSMessageObject)
7424 // Layout description.
7425 static const int kTypeOffset = JSObject::kHeaderSize;
7426 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7427 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7428 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7429 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7430 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7431 static const int kSize = kEndPositionOffset + kPointerSize;
7433 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7434 kStackFramesOffset + kPointerSize,
7435 kSize> BodyDescriptor;
7439 // Regular expressions
7440 // The regular expression holds a single reference to a FixedArray in
7441 // the kDataOffset field.
7442 // The FixedArray contains the following data:
7443 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7444 // - reference to the original source string
7445 // - reference to the original flag string
7446 // If it is an atom regexp
7447 // - a reference to a literal string to search for
7448 // If it is an irregexp regexp:
7449 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7450 // used for tracking the last usage (used for code flushing).
7451 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7452 // used for tracking the last usage (used for code flushing)..
7453 // - max number of registers used by irregexp implementations.
7454 // - number of capture registers (output values) of the regexp.
7455 class JSRegExp: public JSObject {
7458 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7459 // ATOM: A simple string to match against using an indexOf operation.
7460 // IRREGEXP: Compiled with Irregexp.
7461 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7462 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7469 UNICODE_ESCAPES = 16
7474 explicit Flags(uint32_t value) : value_(value) { }
7475 bool is_global() { return (value_ & GLOBAL) != 0; }
7476 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7477 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7478 bool is_sticky() { return (value_ & STICKY) != 0; }
7479 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7480 uint32_t value() { return value_; }
7485 DECL_ACCESSORS(data, Object)
7487 inline Type TypeTag();
7488 inline int CaptureCount();
7489 inline Flags GetFlags();
7490 inline String* Pattern();
7491 inline Object* DataAt(int index);
7492 // Set implementation data after the object has been prepared.
7493 inline void SetDataAt(int index, Object* value);
7495 static int code_index(bool is_latin1) {
7497 return kIrregexpLatin1CodeIndex;
7499 return kIrregexpUC16CodeIndex;
7503 static int saved_code_index(bool is_latin1) {
7505 return kIrregexpLatin1CodeSavedIndex;
7507 return kIrregexpUC16CodeSavedIndex;
7511 DECLARE_CAST(JSRegExp)
7513 // Dispatched behavior.
7514 DECLARE_VERIFIER(JSRegExp)
7516 static const int kDataOffset = JSObject::kHeaderSize;
7517 static const int kSize = kDataOffset + kPointerSize;
7519 // Indices in the data array.
7520 static const int kTagIndex = 0;
7521 static const int kSourceIndex = kTagIndex + 1;
7522 static const int kFlagsIndex = kSourceIndex + 1;
7523 static const int kDataIndex = kFlagsIndex + 1;
7524 // The data fields are used in different ways depending on the
7525 // value of the tag.
7526 // Atom regexps (literal strings).
7527 static const int kAtomPatternIndex = kDataIndex;
7529 static const int kAtomDataSize = kAtomPatternIndex + 1;
7531 // Irregexp compiled code or bytecode for Latin1. If compilation
7532 // fails, this fields hold an exception object that should be
7533 // thrown if the regexp is used again.
7534 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7535 // Irregexp compiled code or bytecode for UC16. If compilation
7536 // fails, this fields hold an exception object that should be
7537 // thrown if the regexp is used again.
7538 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7540 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7541 // is a potential candidate for flushing.
7542 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7543 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7544 // a potential candidate for flushing.
7545 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7547 // Maximal number of registers used by either Latin1 or UC16.
7548 // Only used to check that there is enough stack space
7549 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7550 // Number of captures in the compiled regexp.
7551 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7553 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7555 // Offsets directly into the data fixed array.
7556 static const int kDataTagOffset =
7557 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7558 static const int kDataOneByteCodeOffset =
7559 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7560 static const int kDataUC16CodeOffset =
7561 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7562 static const int kIrregexpCaptureCountOffset =
7563 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7565 // In-object fields.
7566 static const int kSourceFieldIndex = 0;
7567 static const int kGlobalFieldIndex = 1;
7568 static const int kIgnoreCaseFieldIndex = 2;
7569 static const int kMultilineFieldIndex = 3;
7570 static const int kLastIndexFieldIndex = 4;
7571 static const int kInObjectFieldCount = 5;
7573 // The uninitialized value for a regexp code object.
7574 static const int kUninitializedValue = -1;
7576 // The compilation error value for the regexp code object. The real error
7577 // object is in the saved code field.
7578 static const int kCompilationErrorValue = -2;
7580 // When we store the sweep generation at which we moved the code from the
7581 // code index to the saved code index we mask it of to be in the [0:255]
7583 static const int kCodeAgeMask = 0xff;
7587 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7589 static inline bool IsMatch(HashTableKey* key, Object* value) {
7590 return key->IsMatch(value);
7593 static inline uint32_t Hash(HashTableKey* key) {
7597 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7598 return key->HashForObject(object);
7601 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7603 static const int kPrefixSize = 0;
7604 static const int kEntrySize = 2;
7608 // This cache is used in two different variants. For regexp caching, it simply
7609 // maps identifying info of the regexp to the cached regexp object. Scripts and
7610 // eval code only gets cached after a second probe for the code object. To do
7611 // so, on first "put" only a hash identifying the source is entered into the
7612 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7613 // such lifetimes get reduced, and removed once they reach zero. If a second put
7614 // is called while such a hash is live in the cache, the hash gets replaced by
7615 // an actual cache entry. Age also removes stale live entries from the cache.
7616 // Such entries are identified by SharedFunctionInfos pointing to either the
7617 // recompilation stub, or to "old" code. This avoids memory leaks due to
7618 // premature caching of scripts and eval strings that are never needed later.
7619 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7620 CompilationCacheShape,
7623 // Find cached value for a string key, otherwise return null.
7624 Handle<Object> Lookup(
7625 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7626 Handle<Object> LookupEval(
7627 Handle<String> src, Handle<SharedFunctionInfo> shared,
7628 LanguageMode language_mode, int scope_position);
7629 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7630 static Handle<CompilationCacheTable> Put(
7631 Handle<CompilationCacheTable> cache, Handle<String> src,
7632 Handle<Context> context, LanguageMode language_mode,
7633 Handle<Object> value);
7634 static Handle<CompilationCacheTable> PutEval(
7635 Handle<CompilationCacheTable> cache, Handle<String> src,
7636 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7637 int scope_position);
7638 static Handle<CompilationCacheTable> PutRegExp(
7639 Handle<CompilationCacheTable> cache, Handle<String> src,
7640 JSRegExp::Flags flags, Handle<FixedArray> value);
7641 void Remove(Object* value);
7643 static const int kHashGenerations = 10;
7645 DECLARE_CAST(CompilationCacheTable)
7648 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7652 class CodeCache: public Struct {
7654 DECL_ACCESSORS(default_cache, FixedArray)
7655 DECL_ACCESSORS(normal_type_cache, Object)
7657 // Add the code object to the cache.
7659 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7661 // Lookup code object in the cache. Returns code object if found and undefined
7663 Object* Lookup(Name* name, Code::Flags flags);
7665 // Get the internal index of a code object in the cache. Returns -1 if the
7666 // code object is not in that cache. This index can be used to later call
7667 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7669 int GetIndex(Object* name, Code* code);
7671 // Remove an object from the cache with the provided internal index.
7672 void RemoveByIndex(Object* name, Code* code, int index);
7674 DECLARE_CAST(CodeCache)
7676 // Dispatched behavior.
7677 DECLARE_PRINTER(CodeCache)
7678 DECLARE_VERIFIER(CodeCache)
7680 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7681 static const int kNormalTypeCacheOffset =
7682 kDefaultCacheOffset + kPointerSize;
7683 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7686 static void UpdateDefaultCache(
7687 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7688 static void UpdateNormalTypeCache(
7689 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7690 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7691 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7693 // Code cache layout of the default cache. Elements are alternating name and
7694 // code objects for non normal load/store/call IC's.
7695 static const int kCodeCacheEntrySize = 2;
7696 static const int kCodeCacheEntryNameOffset = 0;
7697 static const int kCodeCacheEntryCodeOffset = 1;
7699 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7703 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7705 static inline bool IsMatch(HashTableKey* key, Object* value) {
7706 return key->IsMatch(value);
7709 static inline uint32_t Hash(HashTableKey* key) {
7713 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7714 return key->HashForObject(object);
7717 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7719 static const int kPrefixSize = 0;
7720 static const int kEntrySize = 2;
7724 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7725 CodeCacheHashTableShape,
7728 Object* Lookup(Name* name, Code::Flags flags);
7729 static Handle<CodeCacheHashTable> Put(
7730 Handle<CodeCacheHashTable> table,
7734 int GetIndex(Name* name, Code::Flags flags);
7735 void RemoveByIndex(int index);
7737 DECLARE_CAST(CodeCacheHashTable)
7739 // Initial size of the fixed array backing the hash table.
7740 static const int kInitialSize = 64;
7743 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7747 class PolymorphicCodeCache: public Struct {
7749 DECL_ACCESSORS(cache, Object)
7751 static void Update(Handle<PolymorphicCodeCache> cache,
7752 MapHandleList* maps,
7757 // Returns an undefined value if the entry is not found.
7758 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7760 DECLARE_CAST(PolymorphicCodeCache)
7762 // Dispatched behavior.
7763 DECLARE_PRINTER(PolymorphicCodeCache)
7764 DECLARE_VERIFIER(PolymorphicCodeCache)
7766 static const int kCacheOffset = HeapObject::kHeaderSize;
7767 static const int kSize = kCacheOffset + kPointerSize;
7770 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7774 class PolymorphicCodeCacheHashTable
7775 : public HashTable<PolymorphicCodeCacheHashTable,
7776 CodeCacheHashTableShape,
7779 Object* Lookup(MapHandleList* maps, int code_kind);
7781 static Handle<PolymorphicCodeCacheHashTable> Put(
7782 Handle<PolymorphicCodeCacheHashTable> hash_table,
7783 MapHandleList* maps,
7787 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7789 static const int kInitialSize = 64;
7791 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7795 class TypeFeedbackInfo: public Struct {
7797 inline int ic_total_count();
7798 inline void set_ic_total_count(int count);
7800 inline int ic_with_type_info_count();
7801 inline void change_ic_with_type_info_count(int delta);
7803 inline int ic_generic_count();
7804 inline void change_ic_generic_count(int delta);
7806 inline void initialize_storage();
7808 inline void change_own_type_change_checksum();
7809 inline int own_type_change_checksum();
7811 inline void set_inlined_type_change_checksum(int checksum);
7812 inline bool matches_inlined_type_change_checksum(int checksum);
7814 DECLARE_CAST(TypeFeedbackInfo)
7816 // Dispatched behavior.
7817 DECLARE_PRINTER(TypeFeedbackInfo)
7818 DECLARE_VERIFIER(TypeFeedbackInfo)
7820 static const int kStorage1Offset = HeapObject::kHeaderSize;
7821 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7822 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7823 static const int kSize = kStorage3Offset + kPointerSize;
7826 static const int kTypeChangeChecksumBits = 7;
7828 class ICTotalCountField: public BitField<int, 0,
7829 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7830 class OwnTypeChangeChecksum: public BitField<int,
7831 kSmiValueSize - kTypeChangeChecksumBits,
7832 kTypeChangeChecksumBits> {}; // NOLINT
7833 class ICsWithTypeInfoCountField: public BitField<int, 0,
7834 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7835 class InlinedTypeChangeChecksum: public BitField<int,
7836 kSmiValueSize - kTypeChangeChecksumBits,
7837 kTypeChangeChecksumBits> {}; // NOLINT
7839 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7843 enum AllocationSiteMode {
7844 DONT_TRACK_ALLOCATION_SITE,
7845 TRACK_ALLOCATION_SITE,
7846 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7850 class AllocationSite: public Struct {
7852 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7853 static const double kPretenureRatio;
7854 static const int kPretenureMinimumCreated = 100;
7856 // Values for pretenure decision field.
7857 enum PretenureDecision {
7863 kLastPretenureDecisionValue = kZombie
7866 const char* PretenureDecisionName(PretenureDecision decision);
7868 DECL_ACCESSORS(transition_info, Object)
7869 // nested_site threads a list of sites that represent nested literals
7870 // walked in a particular order. So [[1, 2], 1, 2] will have one
7871 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7872 DECL_ACCESSORS(nested_site, Object)
7873 DECL_ACCESSORS(pretenure_data, Smi)
7874 DECL_ACCESSORS(pretenure_create_count, Smi)
7875 DECL_ACCESSORS(dependent_code, DependentCode)
7876 DECL_ACCESSORS(weak_next, Object)
7878 inline void Initialize();
7880 // This method is expensive, it should only be called for reporting.
7881 bool IsNestedSite();
7883 // transition_info bitfields, for constructed array transition info.
7884 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7885 class UnusedBits: public BitField<int, 15, 14> {};
7886 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7888 // Bitfields for pretenure_data
7889 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7890 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7891 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7892 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7894 // Increments the mementos found counter and returns true when the first
7895 // memento was found for a given allocation site.
7896 inline bool IncrementMementoFoundCount();
7898 inline void IncrementMementoCreateCount();
7900 PretenureFlag GetPretenureMode();
7902 void ResetPretenureDecision();
7904 inline PretenureDecision pretenure_decision();
7905 inline void set_pretenure_decision(PretenureDecision decision);
7907 inline bool deopt_dependent_code();
7908 inline void set_deopt_dependent_code(bool deopt);
7910 inline int memento_found_count();
7911 inline void set_memento_found_count(int count);
7913 inline int memento_create_count();
7914 inline void set_memento_create_count(int count);
7916 // The pretenuring decision is made during gc, and the zombie state allows
7917 // us to recognize when an allocation site is just being kept alive because
7918 // a later traversal of new space may discover AllocationMementos that point
7919 // to this AllocationSite.
7920 inline bool IsZombie();
7922 inline bool IsMaybeTenure();
7924 inline void MarkZombie();
7926 inline bool MakePretenureDecision(PretenureDecision current_decision,
7928 bool maximum_size_scavenge);
7930 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7932 inline ElementsKind GetElementsKind();
7933 inline void SetElementsKind(ElementsKind kind);
7935 inline bool CanInlineCall();
7936 inline void SetDoNotInlineCall();
7938 inline bool SitePointsToLiteral();
7940 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7941 ElementsKind to_kind);
7943 DECLARE_PRINTER(AllocationSite)
7944 DECLARE_VERIFIER(AllocationSite)
7946 DECLARE_CAST(AllocationSite)
7947 static inline AllocationSiteMode GetMode(
7948 ElementsKind boilerplate_elements_kind);
7949 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7950 static inline bool CanTrack(InstanceType type);
7952 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7953 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7954 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7955 static const int kPretenureCreateCountOffset =
7956 kPretenureDataOffset + kPointerSize;
7957 static const int kDependentCodeOffset =
7958 kPretenureCreateCountOffset + kPointerSize;
7959 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7960 static const int kSize = kWeakNextOffset + kPointerSize;
7962 // During mark compact we need to take special care for the dependent code
7964 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7965 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7967 // For other visitors, use the fixed body descriptor below.
7968 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7969 kDependentCodeOffset + kPointerSize,
7970 kSize> BodyDescriptor;
7973 inline bool PretenuringDecisionMade();
7975 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7979 class AllocationMemento: public Struct {
7981 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7982 static const int kSize = kAllocationSiteOffset + kPointerSize;
7984 DECL_ACCESSORS(allocation_site, Object)
7986 inline bool IsValid();
7987 inline AllocationSite* GetAllocationSite();
7989 DECLARE_PRINTER(AllocationMemento)
7990 DECLARE_VERIFIER(AllocationMemento)
7992 DECLARE_CAST(AllocationMemento)
7995 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7999 // Representation of a slow alias as part of a sloppy arguments objects.
8000 // For fast aliases (if HasSloppyArgumentsElements()):
8001 // - the parameter map contains an index into the context
8002 // - all attributes of the element have default values
8003 // For slow aliases (if HasDictionaryArgumentsElements()):
8004 // - the parameter map contains no fast alias mapping (i.e. the hole)
8005 // - this struct (in the slow backing store) contains an index into the context
8006 // - all attributes are available as part if the property details
8007 class AliasedArgumentsEntry: public Struct {
8009 inline int aliased_context_slot() const;
8010 inline void set_aliased_context_slot(int count);
8012 DECLARE_CAST(AliasedArgumentsEntry)
8014 // Dispatched behavior.
8015 DECLARE_PRINTER(AliasedArgumentsEntry)
8016 DECLARE_VERIFIER(AliasedArgumentsEntry)
8018 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8019 static const int kSize = kAliasedContextSlot + kPointerSize;
8022 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8026 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8027 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8030 class StringHasher {
8032 explicit inline StringHasher(int length, uint32_t seed);
8034 template <typename schar>
8035 static inline uint32_t HashSequentialString(const schar* chars,
8039 // Reads all the data, even for long strings and computes the utf16 length.
8040 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8042 int* utf16_length_out);
8044 // Calculated hash value for a string consisting of 1 to
8045 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8046 // value is represented decimal value.
8047 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8049 // No string is allowed to have a hash of zero. That value is reserved
8050 // for internal properties. If the hash calculation yields zero then we
8052 static const int kZeroHash = 27;
8054 // Reusable parts of the hashing algorithm.
8055 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8056 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8057 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8058 const uc16* chars, int length));
8059 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8064 // Returns the value to store in the hash field of a string with
8065 // the given length and contents.
8066 uint32_t GetHashField();
8067 // Returns true if the hash of this string can be computed without
8068 // looking at the contents.
8069 inline bool has_trivial_hash();
8070 // Adds a block of characters to the hash.
8071 template<typename Char>
8072 inline void AddCharacters(const Char* chars, int len);
8075 // Add a character to the hash.
8076 inline void AddCharacter(uint16_t c);
8077 // Update index. Returns true if string is still an index.
8078 inline bool UpdateIndex(uint16_t c);
8081 uint32_t raw_running_hash_;
8082 uint32_t array_index_;
8083 bool is_array_index_;
8084 bool is_first_char_;
8085 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8089 class IteratingStringHasher : public StringHasher {
8091 static inline uint32_t Hash(String* string, uint32_t seed);
8092 inline void VisitOneByteString(const uint8_t* chars, int length);
8093 inline void VisitTwoByteString(const uint16_t* chars, int length);
8096 inline IteratingStringHasher(int len, uint32_t seed);
8097 void VisitConsString(ConsString* cons_string);
8098 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8102 // The characteristics of a string are stored in its map. Retrieving these
8103 // few bits of information is moderately expensive, involving two memory
8104 // loads where the second is dependent on the first. To improve efficiency
8105 // the shape of the string is given its own class so that it can be retrieved
8106 // once and used for several string operations. A StringShape is small enough
8107 // to be passed by value and is immutable, but be aware that flattening a
8108 // string can potentially alter its shape. Also be aware that a GC caused by
8109 // something else can alter the shape of a string due to ConsString
8110 // shortcutting. Keeping these restrictions in mind has proven to be error-
8111 // prone and so we no longer put StringShapes in variables unless there is a
8112 // concrete performance benefit at that particular point in the code.
8113 class StringShape BASE_EMBEDDED {
8115 inline explicit StringShape(const String* s);
8116 inline explicit StringShape(Map* s);
8117 inline explicit StringShape(InstanceType t);
8118 inline bool IsSequential();
8119 inline bool IsExternal();
8120 inline bool IsCons();
8121 inline bool IsSliced();
8122 inline bool IsIndirect();
8123 inline bool IsExternalOneByte();
8124 inline bool IsExternalTwoByte();
8125 inline bool IsSequentialOneByte();
8126 inline bool IsSequentialTwoByte();
8127 inline bool IsInternalized();
8128 inline StringRepresentationTag representation_tag();
8129 inline uint32_t encoding_tag();
8130 inline uint32_t full_representation_tag();
8131 inline uint32_t size_tag();
8133 inline uint32_t type() { return type_; }
8134 inline void invalidate() { valid_ = false; }
8135 inline bool valid() { return valid_; }
8137 inline void invalidate() { }
8143 inline void set_valid() { valid_ = true; }
8146 inline void set_valid() { }
8151 // The Name abstract class captures anything that can be used as a property
8152 // name, i.e., strings and symbols. All names store a hash value.
8153 class Name: public HeapObject {
8155 // Get and set the hash field of the name.
8156 inline uint32_t hash_field();
8157 inline void set_hash_field(uint32_t value);
8159 // Tells whether the hash code has been computed.
8160 inline bool HasHashCode();
8162 // Returns a hash value used for the property table
8163 inline uint32_t Hash();
8165 // Equality operations.
8166 inline bool Equals(Name* other);
8167 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8170 inline bool AsArrayIndex(uint32_t* index);
8172 // If the name is private, it can only name own properties.
8173 inline bool IsPrivate();
8175 // If the name is a non-flat string, this method returns a flat version of the
8176 // string. Otherwise it'll just return the input.
8177 static inline Handle<Name> Flatten(Handle<Name> name,
8178 PretenureFlag pretenure = NOT_TENURED);
8180 // Return a string version of this name that is converted according to the
8181 // rules described in ES6 section 9.2.11.
8182 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8186 DECLARE_PRINTER(Name)
8188 void NameShortPrint();
8189 int NameShortPrint(Vector<char> str);
8192 // Layout description.
8193 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8194 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8195 static const int kHashFieldOffset = kHashFieldSlot;
8197 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8199 static const int kSize = kHashFieldSlot + kPointerSize;
8201 // Mask constant for checking if a name has a computed hash code
8202 // and if it is a string that is an array index. The least significant bit
8203 // indicates whether a hash code has been computed. If the hash code has
8204 // been computed the 2nd bit tells whether the string can be used as an
8206 static const int kHashNotComputedMask = 1;
8207 static const int kIsNotArrayIndexMask = 1 << 1;
8208 static const int kNofHashBitFields = 2;
8210 // Shift constant retrieving hash code from hash field.
8211 static const int kHashShift = kNofHashBitFields;
8213 // Only these bits are relevant in the hash, since the top two are shifted
8215 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8217 // Array index strings this short can keep their index in the hash field.
8218 static const int kMaxCachedArrayIndexLength = 7;
8220 // For strings which are array indexes the hash value has the string length
8221 // mixed into the hash, mainly to avoid a hash value of zero which would be
8222 // the case for the string '0'. 24 bits are used for the array index value.
8223 static const int kArrayIndexValueBits = 24;
8224 static const int kArrayIndexLengthBits =
8225 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8227 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8229 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8230 kArrayIndexValueBits> {}; // NOLINT
8231 class ArrayIndexLengthBits : public BitField<unsigned int,
8232 kNofHashBitFields + kArrayIndexValueBits,
8233 kArrayIndexLengthBits> {}; // NOLINT
8235 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8236 // could use a mask to test if the length of string is less than or equal to
8237 // kMaxCachedArrayIndexLength.
8238 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8240 static const unsigned int kContainsCachedArrayIndexMask =
8241 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8242 << ArrayIndexLengthBits::kShift) |
8243 kIsNotArrayIndexMask;
8245 // Value of empty hash field indicating that the hash is not computed.
8246 static const int kEmptyHashField =
8247 kIsNotArrayIndexMask | kHashNotComputedMask;
8250 static inline bool IsHashFieldComputed(uint32_t field);
8253 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8258 class Symbol: public Name {
8260 // [name]: The print name of a symbol, or undefined if none.
8261 DECL_ACCESSORS(name, Object)
8263 DECL_ACCESSORS(flags, Smi)
8265 // [is_private]: Whether this is a private symbol. Private symbols can only
8266 // be used to designate own properties of objects.
8267 DECL_BOOLEAN_ACCESSORS(is_private)
8269 DECLARE_CAST(Symbol)
8271 // Dispatched behavior.
8272 DECLARE_PRINTER(Symbol)
8273 DECLARE_VERIFIER(Symbol)
8275 // Layout description.
8276 static const int kNameOffset = Name::kSize;
8277 static const int kFlagsOffset = kNameOffset + kPointerSize;
8278 static const int kSize = kFlagsOffset + kPointerSize;
8280 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8282 void SymbolShortPrint(std::ostream& os);
8285 static const int kPrivateBit = 0;
8287 const char* PrivateSymbolToName() const;
8290 friend class Name; // For PrivateSymbolToName.
8293 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8299 // The String abstract class captures JavaScript string values:
8302 // 4.3.16 String Value
8303 // A string value is a member of the type String and is a finite
8304 // ordered sequence of zero or more 16-bit unsigned integer values.
8306 // All string values have a length field.
8307 class String: public Name {
8309 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8311 // Array index strings this short can keep their index in the hash field.
8312 static const int kMaxCachedArrayIndexLength = 7;
8314 // For strings which are array indexes the hash value has the string length
8315 // mixed into the hash, mainly to avoid a hash value of zero which would be
8316 // the case for the string '0'. 24 bits are used for the array index value.
8317 static const int kArrayIndexValueBits = 24;
8318 static const int kArrayIndexLengthBits =
8319 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8321 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8323 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8324 kArrayIndexValueBits> {}; // NOLINT
8325 class ArrayIndexLengthBits : public BitField<unsigned int,
8326 kNofHashBitFields + kArrayIndexValueBits,
8327 kArrayIndexLengthBits> {}; // NOLINT
8329 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8330 // could use a mask to test if the length of string is less than or equal to
8331 // kMaxCachedArrayIndexLength.
8332 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8334 static const unsigned int kContainsCachedArrayIndexMask =
8335 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8336 << ArrayIndexLengthBits::kShift) |
8337 kIsNotArrayIndexMask;
8339 class SubStringRange {
8341 explicit inline SubStringRange(String* string, int first = 0,
8344 inline iterator begin();
8345 inline iterator end();
8353 // Representation of the flat content of a String.
8354 // A non-flat string doesn't have flat content.
8355 // A flat string has content that's encoded as a sequence of either
8356 // one-byte chars or two-byte UC16.
8357 // Returned by String::GetFlatContent().
8360 // Returns true if the string is flat and this structure contains content.
8361 bool IsFlat() { return state_ != NON_FLAT; }
8362 // Returns true if the structure contains one-byte content.
8363 bool IsOneByte() { return state_ == ONE_BYTE; }
8364 // Returns true if the structure contains two-byte content.
8365 bool IsTwoByte() { return state_ == TWO_BYTE; }
8367 // Return the one byte content of the string. Only use if IsOneByte()
8369 Vector<const uint8_t> ToOneByteVector() {
8370 DCHECK_EQ(ONE_BYTE, state_);
8371 return Vector<const uint8_t>(onebyte_start, length_);
8373 // Return the two-byte content of the string. Only use if IsTwoByte()
8375 Vector<const uc16> ToUC16Vector() {
8376 DCHECK_EQ(TWO_BYTE, state_);
8377 return Vector<const uc16>(twobyte_start, length_);
8381 DCHECK(i < length_);
8382 DCHECK(state_ != NON_FLAT);
8383 if (state_ == ONE_BYTE) return onebyte_start[i];
8384 return twobyte_start[i];
8387 bool UsesSameString(const FlatContent& other) const {
8388 return onebyte_start == other.onebyte_start;
8392 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8394 // Constructors only used by String::GetFlatContent().
8395 explicit FlatContent(const uint8_t* start, int length)
8396 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8397 explicit FlatContent(const uc16* start, int length)
8398 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8399 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8402 const uint8_t* onebyte_start;
8403 const uc16* twobyte_start;
8408 friend class String;
8409 friend class IterableSubString;
8412 template <typename Char>
8413 INLINE(Vector<const Char> GetCharVector());
8415 // Get and set the length of the string.
8416 inline int length() const;
8417 inline void set_length(int value);
8419 // Get and set the length of the string using acquire loads and release
8421 inline int synchronized_length() const;
8422 inline void synchronized_set_length(int value);
8424 // Returns whether this string has only one-byte chars, i.e. all of them can
8425 // be one-byte encoded. This might be the case even if the string is
8426 // two-byte. Such strings may appear when the embedder prefers
8427 // two-byte external representations even for one-byte data.
8428 inline bool IsOneByteRepresentation() const;
8429 inline bool IsTwoByteRepresentation() const;
8431 // Cons and slices have an encoding flag that may not represent the actual
8432 // encoding of the underlying string. This is taken into account here.
8433 // Requires: this->IsFlat()
8434 inline bool IsOneByteRepresentationUnderneath();
8435 inline bool IsTwoByteRepresentationUnderneath();
8437 // NOTE: this should be considered only a hint. False negatives are
8439 inline bool HasOnlyOneByteChars();
8441 // Get and set individual two byte chars in the string.
8442 inline void Set(int index, uint16_t value);
8443 // Get individual two byte char in the string. Repeated calls
8444 // to this method are not efficient unless the string is flat.
8445 INLINE(uint16_t Get(int index));
8447 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8448 static Handle<Object> ToNumber(Handle<String> subject);
8450 // Flattens the string. Checks first inline to see if it is
8451 // necessary. Does nothing if the string is not a cons string.
8452 // Flattening allocates a sequential string with the same data as
8453 // the given string and mutates the cons string to a degenerate
8454 // form, where the first component is the new sequential string and
8455 // the second component is the empty string. If allocation fails,
8456 // this function returns a failure. If flattening succeeds, this
8457 // function returns the sequential string that is now the first
8458 // component of the cons string.
8460 // Degenerate cons strings are handled specially by the garbage
8461 // collector (see IsShortcutCandidate).
8463 static inline Handle<String> Flatten(Handle<String> string,
8464 PretenureFlag pretenure = NOT_TENURED);
8466 // Tries to return the content of a flat string as a structure holding either
8467 // a flat vector of char or of uc16.
8468 // If the string isn't flat, and therefore doesn't have flat content, the
8469 // returned structure will report so, and can't provide a vector of either
8471 FlatContent GetFlatContent();
8473 // Returns the parent of a sliced string or first part of a flat cons string.
8474 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8475 inline String* GetUnderlying();
8477 // String equality operations.
8478 inline bool Equals(String* other);
8479 inline static bool Equals(Handle<String> one, Handle<String> two);
8480 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8481 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8482 bool IsTwoByteEqualTo(Vector<const uc16> str);
8484 // Return a UTF8 representation of the string. The string is null
8485 // terminated but may optionally contain nulls. Length is returned
8486 // in length_output if length_output is not a null pointer The string
8487 // should be nearly flat, otherwise the performance of this method may
8488 // be very slow (quadratic in the length). Setting robustness_flag to
8489 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8490 // handles unexpected data without causing assert failures and it does not
8491 // do any heap allocations. This is useful when printing stack traces.
8492 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8493 RobustnessFlag robustness_flag,
8494 int offset, int length,
8495 int* length_output = 0);
8496 base::SmartArrayPointer<char> ToCString(
8497 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8498 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8499 int* length_output = 0);
8501 // Return a 16 bit Unicode representation of the string.
8502 // The string should be nearly flat, otherwise the performance of
8503 // of this method may be very bad. Setting robustness_flag to
8504 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8505 // handles unexpected data without causing assert failures and it does not
8506 // do any heap allocations. This is useful when printing stack traces.
8507 base::SmartArrayPointer<uc16> ToWideCString(
8508 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8510 bool ComputeArrayIndex(uint32_t* index);
8513 bool MakeExternal(v8::String::ExternalStringResource* resource);
8514 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8517 inline bool AsArrayIndex(uint32_t* index);
8519 DECLARE_CAST(String)
8521 void PrintOn(FILE* out);
8523 // For use during stack traces. Performs rudimentary sanity check.
8526 // Dispatched behavior.
8527 void StringShortPrint(StringStream* accumulator);
8528 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8529 #if defined(DEBUG) || defined(OBJECT_PRINT)
8530 char* ToAsciiArray();
8532 DECLARE_PRINTER(String)
8533 DECLARE_VERIFIER(String)
8535 inline bool IsFlat();
8537 // Layout description.
8538 static const int kLengthOffset = Name::kSize;
8539 static const int kSize = kLengthOffset + kPointerSize;
8541 // Maximum number of characters to consider when trying to convert a string
8542 // value into an array index.
8543 static const int kMaxArrayIndexSize = 10;
8544 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8547 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8548 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8549 static const int kMaxUtf16CodeUnit = 0xffff;
8550 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8552 // Value of hash field containing computed hash equal to zero.
8553 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8555 // Maximal string length.
8556 static const int kMaxLength = (1 << 28) - 16;
8558 // Max length for computing hash. For strings longer than this limit the
8559 // string length is used as the hash value.
8560 static const int kMaxHashCalcLength = 16383;
8562 // Limit for truncation in short printing.
8563 static const int kMaxShortPrintLength = 1024;
8565 // Support for regular expressions.
8566 const uc16* GetTwoByteData(unsigned start);
8568 // Helper function for flattening strings.
8569 template <typename sinkchar>
8570 static void WriteToFlat(String* source,
8575 // The return value may point to the first aligned word containing the first
8576 // non-one-byte character, rather than directly to the non-one-byte character.
8577 // If the return value is >= the passed length, the entire string was
8579 static inline int NonAsciiStart(const char* chars, int length) {
8580 const char* start = chars;
8581 const char* limit = chars + length;
8583 if (length >= kIntptrSize) {
8584 // Check unaligned bytes.
8585 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8586 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8587 return static_cast<int>(chars - start);
8591 // Check aligned words.
8592 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8593 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8594 while (chars + sizeof(uintptr_t) <= limit) {
8595 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8596 return static_cast<int>(chars - start);
8598 chars += sizeof(uintptr_t);
8601 // Check remaining unaligned bytes.
8602 while (chars < limit) {
8603 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8604 return static_cast<int>(chars - start);
8609 return static_cast<int>(chars - start);
8612 static inline bool IsAscii(const char* chars, int length) {
8613 return NonAsciiStart(chars, length) >= length;
8616 static inline bool IsAscii(const uint8_t* chars, int length) {
8618 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8621 static inline int NonOneByteStart(const uc16* chars, int length) {
8622 const uc16* limit = chars + length;
8623 const uc16* start = chars;
8624 while (chars < limit) {
8625 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8628 return static_cast<int>(chars - start);
8631 static inline bool IsOneByte(const uc16* chars, int length) {
8632 return NonOneByteStart(chars, length) >= length;
8635 template<class Visitor>
8636 static inline ConsString* VisitFlat(Visitor* visitor,
8640 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8641 bool include_ending_line);
8643 // Use the hash field to forward to the canonical internalized string
8644 // when deserializing an internalized string.
8645 inline void SetForwardedInternalizedString(String* string);
8646 inline String* GetForwardedInternalizedString();
8650 friend class StringTableInsertionKey;
8652 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8653 PretenureFlag tenure);
8655 // Slow case of String::Equals. This implementation works on any strings
8656 // but it is most efficient on strings that are almost flat.
8657 bool SlowEquals(String* other);
8659 static bool SlowEquals(Handle<String> one, Handle<String> two);
8661 // Slow case of AsArrayIndex.
8662 bool SlowAsArrayIndex(uint32_t* index);
8664 // Compute and set the hash code.
8665 uint32_t ComputeAndSetHash();
8667 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8671 // The SeqString abstract class captures sequential string values.
8672 class SeqString: public String {
8674 DECLARE_CAST(SeqString)
8676 // Layout description.
8677 static const int kHeaderSize = String::kSize;
8679 // Truncate the string in-place if possible and return the result.
8680 // In case of new_length == 0, the empty string is returned without
8681 // truncating the original string.
8682 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8685 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8689 // The OneByteString class captures sequential one-byte string objects.
8690 // Each character in the OneByteString is an one-byte character.
8691 class SeqOneByteString: public SeqString {
8693 static const bool kHasOneByteEncoding = true;
8695 // Dispatched behavior.
8696 inline uint16_t SeqOneByteStringGet(int index);
8697 inline void SeqOneByteStringSet(int index, uint16_t value);
8699 // Get the address of the characters in this string.
8700 inline Address GetCharsAddress();
8702 inline uint8_t* GetChars();
8704 DECLARE_CAST(SeqOneByteString)
8706 // Garbage collection support. This method is called by the
8707 // garbage collector to compute the actual size of an OneByteString
8709 inline int SeqOneByteStringSize(InstanceType instance_type);
8711 // Computes the size for an OneByteString instance of a given length.
8712 static int SizeFor(int length) {
8713 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8716 // Maximal memory usage for a single sequential one-byte string.
8717 static const int kMaxSize = 512 * MB - 1;
8718 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8721 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8725 // The TwoByteString class captures sequential unicode string objects.
8726 // Each character in the TwoByteString is a two-byte uint16_t.
8727 class SeqTwoByteString: public SeqString {
8729 static const bool kHasOneByteEncoding = false;
8731 // Dispatched behavior.
8732 inline uint16_t SeqTwoByteStringGet(int index);
8733 inline void SeqTwoByteStringSet(int index, uint16_t value);
8735 // Get the address of the characters in this string.
8736 inline Address GetCharsAddress();
8738 inline uc16* GetChars();
8741 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8743 DECLARE_CAST(SeqTwoByteString)
8745 // Garbage collection support. This method is called by the
8746 // garbage collector to compute the actual size of a TwoByteString
8748 inline int SeqTwoByteStringSize(InstanceType instance_type);
8750 // Computes the size for a TwoByteString instance of a given length.
8751 static int SizeFor(int length) {
8752 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8755 // Maximal memory usage for a single sequential two-byte string.
8756 static const int kMaxSize = 512 * MB - 1;
8757 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8758 String::kMaxLength);
8761 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8765 // The ConsString class describes string values built by using the
8766 // addition operator on strings. A ConsString is a pair where the
8767 // first and second components are pointers to other string values.
8768 // One or both components of a ConsString can be pointers to other
8769 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8770 // are non-ConsString string values. The string value represented by
8771 // a ConsString can be obtained by concatenating the leaf string
8772 // values in a left-to-right depth-first traversal of the tree.
8773 class ConsString: public String {
8775 // First string of the cons cell.
8776 inline String* first();
8777 // Doesn't check that the result is a string, even in debug mode. This is
8778 // useful during GC where the mark bits confuse the checks.
8779 inline Object* unchecked_first();
8780 inline void set_first(String* first,
8781 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8783 // Second string of the cons cell.
8784 inline String* second();
8785 // Doesn't check that the result is a string, even in debug mode. This is
8786 // useful during GC where the mark bits confuse the checks.
8787 inline Object* unchecked_second();
8788 inline void set_second(String* second,
8789 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8791 // Dispatched behavior.
8792 uint16_t ConsStringGet(int index);
8794 DECLARE_CAST(ConsString)
8796 // Layout description.
8797 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8798 static const int kSecondOffset = kFirstOffset + kPointerSize;
8799 static const int kSize = kSecondOffset + kPointerSize;
8801 // Minimum length for a cons string.
8802 static const int kMinLength = 13;
8804 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8807 DECLARE_VERIFIER(ConsString)
8810 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8814 // The Sliced String class describes strings that are substrings of another
8815 // sequential string. The motivation is to save time and memory when creating
8816 // a substring. A Sliced String is described as a pointer to the parent,
8817 // the offset from the start of the parent string and the length. Using
8818 // a Sliced String therefore requires unpacking of the parent string and
8819 // adding the offset to the start address. A substring of a Sliced String
8820 // are not nested since the double indirection is simplified when creating
8821 // such a substring.
8822 // Currently missing features are:
8823 // - handling externalized parent strings
8824 // - external strings as parent
8825 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8826 class SlicedString: public String {
8828 inline String* parent();
8829 inline void set_parent(String* parent,
8830 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8831 inline int offset() const;
8832 inline void set_offset(int offset);
8834 // Dispatched behavior.
8835 uint16_t SlicedStringGet(int index);
8837 DECLARE_CAST(SlicedString)
8839 // Layout description.
8840 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8841 static const int kOffsetOffset = kParentOffset + kPointerSize;
8842 static const int kSize = kOffsetOffset + kPointerSize;
8844 // Minimum length for a sliced string.
8845 static const int kMinLength = 13;
8847 typedef FixedBodyDescriptor<kParentOffset,
8848 kOffsetOffset + kPointerSize, kSize>
8851 DECLARE_VERIFIER(SlicedString)
8854 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8858 // The ExternalString class describes string values that are backed by
8859 // a string resource that lies outside the V8 heap. ExternalStrings
8860 // consist of the length field common to all strings, a pointer to the
8861 // external resource. It is important to ensure (externally) that the
8862 // resource is not deallocated while the ExternalString is live in the
8865 // The API expects that all ExternalStrings are created through the
8866 // API. Therefore, ExternalStrings should not be used internally.
8867 class ExternalString: public String {
8869 DECLARE_CAST(ExternalString)
8871 // Layout description.
8872 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8873 static const int kShortSize = kResourceOffset + kPointerSize;
8874 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8875 static const int kSize = kResourceDataOffset + kPointerSize;
8877 static const int kMaxShortLength =
8878 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8880 // Return whether external string is short (data pointer is not cached).
8881 inline bool is_short();
8883 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8886 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8890 // The ExternalOneByteString class is an external string backed by an
8892 class ExternalOneByteString : public ExternalString {
8894 static const bool kHasOneByteEncoding = true;
8896 typedef v8::String::ExternalOneByteStringResource Resource;
8898 // The underlying resource.
8899 inline const Resource* resource();
8900 inline void set_resource(const Resource* buffer);
8902 // Update the pointer cache to the external character array.
8903 // The cached pointer is always valid, as the external character array does =
8904 // not move during lifetime. Deserialization is the only exception, after
8905 // which the pointer cache has to be refreshed.
8906 inline void update_data_cache();
8908 inline const uint8_t* GetChars();
8910 // Dispatched behavior.
8911 inline uint16_t ExternalOneByteStringGet(int index);
8913 DECLARE_CAST(ExternalOneByteString)
8915 // Garbage collection support.
8916 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8918 template <typename StaticVisitor>
8919 inline void ExternalOneByteStringIterateBody();
8922 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8926 // The ExternalTwoByteString class is an external string backed by a UTF-16
8928 class ExternalTwoByteString: public ExternalString {
8930 static const bool kHasOneByteEncoding = false;
8932 typedef v8::String::ExternalStringResource Resource;
8934 // The underlying string resource.
8935 inline const Resource* resource();
8936 inline void set_resource(const Resource* buffer);
8938 // Update the pointer cache to the external character array.
8939 // The cached pointer is always valid, as the external character array does =
8940 // not move during lifetime. Deserialization is the only exception, after
8941 // which the pointer cache has to be refreshed.
8942 inline void update_data_cache();
8944 inline const uint16_t* GetChars();
8946 // Dispatched behavior.
8947 inline uint16_t ExternalTwoByteStringGet(int index);
8950 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8952 DECLARE_CAST(ExternalTwoByteString)
8954 // Garbage collection support.
8955 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8957 template<typename StaticVisitor>
8958 inline void ExternalTwoByteStringIterateBody();
8961 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8965 // Utility superclass for stack-allocated objects that must be updated
8966 // on gc. It provides two ways for the gc to update instances, either
8967 // iterating or updating after gc.
8968 class Relocatable BASE_EMBEDDED {
8970 explicit inline Relocatable(Isolate* isolate);
8971 inline virtual ~Relocatable();
8972 virtual void IterateInstance(ObjectVisitor* v) { }
8973 virtual void PostGarbageCollection() { }
8975 static void PostGarbageCollectionProcessing(Isolate* isolate);
8976 static int ArchiveSpacePerThread();
8977 static char* ArchiveState(Isolate* isolate, char* to);
8978 static char* RestoreState(Isolate* isolate, char* from);
8979 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8980 static void Iterate(ObjectVisitor* v, Relocatable* top);
8981 static char* Iterate(ObjectVisitor* v, char* t);
8989 // A flat string reader provides random access to the contents of a
8990 // string independent of the character width of the string. The handle
8991 // must be valid as long as the reader is being used.
8992 class FlatStringReader : public Relocatable {
8994 FlatStringReader(Isolate* isolate, Handle<String> str);
8995 FlatStringReader(Isolate* isolate, Vector<const char> input);
8996 void PostGarbageCollection();
8997 inline uc32 Get(int index);
8998 template <typename Char>
8999 inline Char Get(int index);
9000 int length() { return length_; }
9009 // This maintains an off-stack representation of the stack frames required
9010 // to traverse a ConsString, allowing an entirely iterative and restartable
9011 // traversal of the entire string
9012 class ConsStringIterator {
9014 inline ConsStringIterator() {}
9015 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9016 Reset(cons_string, offset);
9018 inline void Reset(ConsString* cons_string, int offset = 0) {
9020 // Next will always return NULL.
9021 if (cons_string == NULL) return;
9022 Initialize(cons_string, offset);
9024 // Returns NULL when complete.
9025 inline String* Next(int* offset_out) {
9027 if (depth_ == 0) return NULL;
9028 return Continue(offset_out);
9032 static const int kStackSize = 32;
9033 // Use a mask instead of doing modulo operations for stack wrapping.
9034 static const int kDepthMask = kStackSize-1;
9035 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9036 static inline int OffsetForDepth(int depth);
9038 inline void PushLeft(ConsString* string);
9039 inline void PushRight(ConsString* string);
9040 inline void AdjustMaximumDepth();
9042 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9043 void Initialize(ConsString* cons_string, int offset);
9044 String* Continue(int* offset_out);
9045 String* NextLeaf(bool* blew_stack);
9046 String* Search(int* offset_out);
9048 // Stack must always contain only frames for which right traversal
9049 // has not yet been performed.
9050 ConsString* frames_[kStackSize];
9055 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9059 class StringCharacterStream {
9061 inline StringCharacterStream(String* string,
9063 inline uint16_t GetNext();
9064 inline bool HasMore();
9065 inline void Reset(String* string, int offset = 0);
9066 inline void VisitOneByteString(const uint8_t* chars, int length);
9067 inline void VisitTwoByteString(const uint16_t* chars, int length);
9070 ConsStringIterator iter_;
9073 const uint8_t* buffer8_;
9074 const uint16_t* buffer16_;
9076 const uint8_t* end_;
9077 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9081 template <typename T>
9082 class VectorIterator {
9084 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9085 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9086 T GetNext() { return data_[index_++]; }
9087 bool has_more() { return index_ < data_.length(); }
9089 Vector<const T> data_;
9094 // The Oddball describes objects null, undefined, true, and false.
9095 class Oddball: public HeapObject {
9097 // [to_string]: Cached to_string computed at startup.
9098 DECL_ACCESSORS(to_string, String)
9100 // [to_number]: Cached to_number computed at startup.
9101 DECL_ACCESSORS(to_number, Object)
9103 // [typeof]: Cached type_of computed at startup.
9104 DECL_ACCESSORS(type_of, String)
9106 inline byte kind() const;
9107 inline void set_kind(byte kind);
9109 // ES6 section 7.1.3 ToNumber for Boolean, Null, Undefined.
9110 MUST_USE_RESULT static inline Handle<Object> ToNumber(Handle<Oddball> input);
9112 DECLARE_CAST(Oddball)
9114 // Dispatched behavior.
9115 DECLARE_VERIFIER(Oddball)
9117 // Initialize the fields.
9118 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9119 const char* to_string, Handle<Object> to_number,
9120 const char* type_of, byte kind);
9122 // Layout description.
9123 static const int kToStringOffset = HeapObject::kHeaderSize;
9124 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9125 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9126 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9127 static const int kSize = kKindOffset + kPointerSize;
9129 static const byte kFalse = 0;
9130 static const byte kTrue = 1;
9131 static const byte kNotBooleanMask = ~1;
9132 static const byte kTheHole = 2;
9133 static const byte kNull = 3;
9134 static const byte kArgumentMarker = 4;
9135 static const byte kUndefined = 5;
9136 static const byte kUninitialized = 6;
9137 static const byte kOther = 7;
9138 static const byte kException = 8;
9140 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9141 kSize> BodyDescriptor;
9143 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9144 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9145 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9148 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9152 class Cell: public HeapObject {
9154 // [value]: value of the cell.
9155 DECL_ACCESSORS(value, Object)
9159 static inline Cell* FromValueAddress(Address value) {
9160 Object* result = FromAddress(value - kValueOffset);
9161 return static_cast<Cell*>(result);
9164 inline Address ValueAddress() {
9165 return address() + kValueOffset;
9168 // Dispatched behavior.
9169 DECLARE_PRINTER(Cell)
9170 DECLARE_VERIFIER(Cell)
9172 // Layout description.
9173 static const int kValueOffset = HeapObject::kHeaderSize;
9174 static const int kSize = kValueOffset + kPointerSize;
9176 typedef FixedBodyDescriptor<kValueOffset,
9177 kValueOffset + kPointerSize,
9178 kSize> BodyDescriptor;
9181 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9185 class PropertyCell : public HeapObject {
9187 // [property_details]: details of the global property.
9188 DECL_ACCESSORS(property_details_raw, Object)
9189 // [value]: value of the global property.
9190 DECL_ACCESSORS(value, Object)
9191 // [dependent_code]: dependent code that depends on the type of the global
9193 DECL_ACCESSORS(dependent_code, DependentCode)
9195 inline PropertyDetails property_details();
9196 inline void set_property_details(PropertyDetails details);
9198 PropertyCellConstantType GetConstantType();
9200 // Computes the new type of the cell's contents for the given value, but
9201 // without actually modifying the details.
9202 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9203 Handle<Object> value,
9204 PropertyDetails details);
9205 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9206 Handle<Object> value, PropertyDetails details);
9208 static Handle<PropertyCell> InvalidateEntry(
9209 Handle<GlobalDictionary> dictionary, int entry);
9211 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9212 Handle<Object> new_value);
9214 DECLARE_CAST(PropertyCell)
9216 // Dispatched behavior.
9217 DECLARE_PRINTER(PropertyCell)
9218 DECLARE_VERIFIER(PropertyCell)
9220 // Layout description.
9221 static const int kDetailsOffset = HeapObject::kHeaderSize;
9222 static const int kValueOffset = kDetailsOffset + kPointerSize;
9223 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9224 static const int kSize = kDependentCodeOffset + kPointerSize;
9226 static const int kPointerFieldsBeginOffset = kValueOffset;
9227 static const int kPointerFieldsEndOffset = kSize;
9229 typedef FixedBodyDescriptor<kValueOffset,
9231 kSize> BodyDescriptor;
9234 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9238 class WeakCell : public HeapObject {
9240 inline Object* value() const;
9242 // This should not be called by anyone except GC.
9243 inline void clear();
9245 // This should not be called by anyone except allocator.
9246 inline void initialize(HeapObject* value);
9248 inline bool cleared() const;
9250 DECL_ACCESSORS(next, Object)
9252 inline void clear_next(Heap* heap);
9254 inline bool next_cleared();
9256 DECLARE_CAST(WeakCell)
9258 DECLARE_PRINTER(WeakCell)
9259 DECLARE_VERIFIER(WeakCell)
9261 // Layout description.
9262 static const int kValueOffset = HeapObject::kHeaderSize;
9263 static const int kNextOffset = kValueOffset + kPointerSize;
9264 static const int kSize = kNextOffset + kPointerSize;
9266 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9269 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9273 // The JSProxy describes EcmaScript Harmony proxies
9274 class JSProxy: public JSReceiver {
9276 // [handler]: The handler property.
9277 DECL_ACCESSORS(handler, Object)
9279 // [hash]: The hash code property (undefined if not initialized yet).
9280 DECL_ACCESSORS(hash, Object)
9282 DECLARE_CAST(JSProxy)
9284 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9285 Handle<JSProxy> proxy,
9286 Handle<Object> receiver,
9289 // If the handler defines an accessor property with a setter, invoke it.
9290 // If it defines an accessor property without a setter, or a data property
9291 // that is read-only, throw. In all these cases set '*done' to true,
9292 // otherwise set it to false.
9294 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9295 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9296 Handle<Object> value, LanguageMode language_mode, bool* done);
9298 MUST_USE_RESULT static Maybe<PropertyAttributes>
9299 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9300 Handle<Object> receiver,
9302 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9303 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9304 Handle<Object> value, LanguageMode language_mode);
9306 // Turn the proxy into an (empty) JSObject.
9307 static void Fix(Handle<JSProxy> proxy);
9309 // Initializes the body after the handler slot.
9310 inline void InitializeBody(int object_size, Object* value);
9312 // Invoke a trap by name. If the trap does not exist on this's handler,
9313 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9314 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9315 Handle<JSProxy> proxy,
9317 Handle<Object> derived_trap,
9319 Handle<Object> args[]);
9321 // Dispatched behavior.
9322 DECLARE_PRINTER(JSProxy)
9323 DECLARE_VERIFIER(JSProxy)
9325 // Layout description. We add padding so that a proxy has the same
9326 // size as a virgin JSObject. This is essential for becoming a JSObject
9328 static const int kHandlerOffset = HeapObject::kHeaderSize;
9329 static const int kHashOffset = kHandlerOffset + kPointerSize;
9330 static const int kPaddingOffset = kHashOffset + kPointerSize;
9331 static const int kSize = JSObject::kHeaderSize;
9332 static const int kHeaderSize = kPaddingOffset;
9333 static const int kPaddingSize = kSize - kPaddingOffset;
9335 STATIC_ASSERT(kPaddingSize >= 0);
9337 typedef FixedBodyDescriptor<kHandlerOffset,
9339 kSize> BodyDescriptor;
9342 friend class JSReceiver;
9344 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9345 Handle<JSProxy> proxy, Handle<Name> name);
9347 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9348 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9350 MUST_USE_RESULT Object* GetIdentityHash();
9352 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9354 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9358 class JSFunctionProxy: public JSProxy {
9360 // [call_trap]: The call trap.
9361 DECL_ACCESSORS(call_trap, JSReceiver)
9363 // [construct_trap]: The construct trap.
9364 DECL_ACCESSORS(construct_trap, Object)
9366 DECLARE_CAST(JSFunctionProxy)
9368 // Dispatched behavior.
9369 DECLARE_PRINTER(JSFunctionProxy)
9370 DECLARE_VERIFIER(JSFunctionProxy)
9372 // Layout description.
9373 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9374 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9375 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9376 static const int kSize = JSFunction::kSize;
9377 static const int kPaddingSize = kSize - kPaddingOffset;
9379 STATIC_ASSERT(kPaddingSize >= 0);
9381 typedef FixedBodyDescriptor<kHandlerOffset,
9382 kConstructTrapOffset + kPointerSize,
9383 kSize> BodyDescriptor;
9386 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9390 class JSCollection : public JSObject {
9392 // [table]: the backing hash table
9393 DECL_ACCESSORS(table, Object)
9395 static const int kTableOffset = JSObject::kHeaderSize;
9396 static const int kSize = kTableOffset + kPointerSize;
9399 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9403 // The JSSet describes EcmaScript Harmony sets
9404 class JSSet : public JSCollection {
9408 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9409 static void Clear(Handle<JSSet> set);
9411 // Dispatched behavior.
9412 DECLARE_PRINTER(JSSet)
9413 DECLARE_VERIFIER(JSSet)
9416 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9420 // The JSMap describes EcmaScript Harmony maps
9421 class JSMap : public JSCollection {
9425 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9426 static void Clear(Handle<JSMap> map);
9428 // Dispatched behavior.
9429 DECLARE_PRINTER(JSMap)
9430 DECLARE_VERIFIER(JSMap)
9433 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9437 // OrderedHashTableIterator is an iterator that iterates over the keys and
9438 // values of an OrderedHashTable.
9440 // The iterator has a reference to the underlying OrderedHashTable data,
9441 // [table], as well as the current [index] the iterator is at.
9443 // When the OrderedHashTable is rehashed it adds a reference from the old table
9444 // to the new table as well as storing enough data about the changes so that the
9445 // iterator [index] can be adjusted accordingly.
9447 // When the [Next] result from the iterator is requested, the iterator checks if
9448 // there is a newer table that it needs to transition to.
9449 template<class Derived, class TableType>
9450 class OrderedHashTableIterator: public JSObject {
9452 // [table]: the backing hash table mapping keys to values.
9453 DECL_ACCESSORS(table, Object)
9455 // [index]: The index into the data table.
9456 DECL_ACCESSORS(index, Object)
9458 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9459 DECL_ACCESSORS(kind, Object)
9462 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9465 static const int kTableOffset = JSObject::kHeaderSize;
9466 static const int kIndexOffset = kTableOffset + kPointerSize;
9467 static const int kKindOffset = kIndexOffset + kPointerSize;
9468 static const int kSize = kKindOffset + kPointerSize;
9476 // Whether the iterator has more elements. This needs to be called before
9477 // calling |CurrentKey| and/or |CurrentValue|.
9480 // Move the index forward one.
9482 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9485 // Populates the array with the next key and value and then moves the iterator
9487 // This returns the |kind| or 0 if the iterator is already at the end.
9488 Smi* Next(JSArray* value_array);
9490 // Returns the current key of the iterator. This should only be called when
9491 // |HasMore| returns true.
9492 inline Object* CurrentKey();
9495 // Transitions the iterator to the non obsolete backing store. This is a NOP
9496 // if the [table] is not obsolete.
9499 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9503 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9506 // Dispatched behavior.
9507 DECLARE_PRINTER(JSSetIterator)
9508 DECLARE_VERIFIER(JSSetIterator)
9510 DECLARE_CAST(JSSetIterator)
9512 // Called by |Next| to populate the array. This allows the subclasses to
9513 // populate the array differently.
9514 inline void PopulateValueArray(FixedArray* array);
9517 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9521 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9524 // Dispatched behavior.
9525 DECLARE_PRINTER(JSMapIterator)
9526 DECLARE_VERIFIER(JSMapIterator)
9528 DECLARE_CAST(JSMapIterator)
9530 // Called by |Next| to populate the array. This allows the subclasses to
9531 // populate the array differently.
9532 inline void PopulateValueArray(FixedArray* array);
9535 // Returns the current value of the iterator. This should only be called when
9536 // |HasMore| returns true.
9537 inline Object* CurrentValue();
9539 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9543 // ES6 section 25.1.1.3 The IteratorResult Interface
9544 class JSIteratorResult final : public JSObject {
9546 // [done]: This is the result status of an iterator next method call. If the
9547 // end of the iterator was reached done is true. If the end was not reached
9548 // done is false and a [value] is available.
9549 DECL_ACCESSORS(done, Object)
9551 // [value]: If [done] is false, this is the current iteration element value.
9552 // If [done] is true, this is the return value of the iterator, if it supplied
9553 // one. If the iterator does not have a return value, value is undefined.
9554 // In that case, the value property may be absent from the conforming object
9555 // if it does not inherit an explicit value property.
9556 DECL_ACCESSORS(value, Object)
9558 // Dispatched behavior.
9559 DECLARE_PRINTER(JSIteratorResult)
9560 DECLARE_VERIFIER(JSIteratorResult)
9562 DECLARE_CAST(JSIteratorResult)
9564 static const int kValueOffset = JSObject::kHeaderSize;
9565 static const int kDoneOffset = kValueOffset + kPointerSize;
9566 static const int kSize = kDoneOffset + kPointerSize;
9568 // Indices of in-object properties.
9569 static const int kValueIndex = 0;
9570 static const int kDoneIndex = 1;
9573 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9577 // Base class for both JSWeakMap and JSWeakSet
9578 class JSWeakCollection: public JSObject {
9580 // [table]: the backing hash table mapping keys to values.
9581 DECL_ACCESSORS(table, Object)
9583 // [next]: linked list of encountered weak maps during GC.
9584 DECL_ACCESSORS(next, Object)
9586 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9587 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9588 Handle<Object> value, int32_t hash);
9589 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9592 static const int kTableOffset = JSObject::kHeaderSize;
9593 static const int kNextOffset = kTableOffset + kPointerSize;
9594 static const int kSize = kNextOffset + kPointerSize;
9597 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9601 // The JSWeakMap describes EcmaScript Harmony weak maps
9602 class JSWeakMap: public JSWeakCollection {
9604 DECLARE_CAST(JSWeakMap)
9606 // Dispatched behavior.
9607 DECLARE_PRINTER(JSWeakMap)
9608 DECLARE_VERIFIER(JSWeakMap)
9611 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9615 // The JSWeakSet describes EcmaScript Harmony weak sets
9616 class JSWeakSet: public JSWeakCollection {
9618 DECLARE_CAST(JSWeakSet)
9620 // Dispatched behavior.
9621 DECLARE_PRINTER(JSWeakSet)
9622 DECLARE_VERIFIER(JSWeakSet)
9625 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9629 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9630 enum class SharedFlag { kNotShared, kShared };
9633 class JSArrayBuffer: public JSObject {
9635 // [backing_store]: backing memory for this array
9636 DECL_ACCESSORS(backing_store, void)
9638 // [byte_length]: length in bytes
9639 DECL_ACCESSORS(byte_length, Object)
9641 inline uint32_t bit_field() const;
9642 inline void set_bit_field(uint32_t bits);
9644 inline bool is_external();
9645 inline void set_is_external(bool value);
9647 inline bool is_neuterable();
9648 inline void set_is_neuterable(bool value);
9650 inline bool was_neutered();
9651 inline void set_was_neutered(bool value);
9653 inline bool is_shared();
9654 inline void set_is_shared(bool value);
9656 DECLARE_CAST(JSArrayBuffer)
9660 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9661 bool is_external, void* data, size_t allocated_length,
9662 SharedFlag shared = SharedFlag::kNotShared);
9664 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9665 Isolate* isolate, size_t allocated_length,
9666 bool initialize = true,
9667 SharedFlag shared = SharedFlag::kNotShared);
9669 // Dispatched behavior.
9670 DECLARE_PRINTER(JSArrayBuffer)
9671 DECLARE_VERIFIER(JSArrayBuffer)
9673 static const int kByteLengthOffset = JSObject::kHeaderSize;
9675 // NOTE: GC will visit objects fields:
9676 // 1. From JSObject::BodyDescriptor::kStartOffset to kByteLengthOffset +
9678 // 2. From start of the internal fields and up to the end of them
9679 static const int kBackingStoreOffset = kByteLengthOffset + kPointerSize;
9680 static const int kBitFieldSlot = kBackingStoreOffset + kPointerSize;
9681 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9682 static const int kBitFieldOffset = kBitFieldSlot;
9684 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9686 static const int kSize = kBitFieldSlot + kPointerSize;
9688 static const int kSizeWithInternalFields =
9689 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9691 template <typename StaticVisitor>
9692 static inline void JSArrayBufferIterateBody(Heap* heap, HeapObject* obj);
9694 static inline void JSArrayBufferIterateBody(HeapObject* obj,
9697 class IsExternal : public BitField<bool, 1, 1> {};
9698 class IsNeuterable : public BitField<bool, 2, 1> {};
9699 class WasNeutered : public BitField<bool, 3, 1> {};
9700 class IsShared : public BitField<bool, 4, 1> {};
9703 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9707 class JSArrayBufferView: public JSObject {
9709 // [buffer]: ArrayBuffer that this typed array views.
9710 DECL_ACCESSORS(buffer, Object)
9712 // [byte_offset]: offset of typed array in bytes.
9713 DECL_ACCESSORS(byte_offset, Object)
9715 // [byte_length]: length of typed array in bytes.
9716 DECL_ACCESSORS(byte_length, Object)
9718 DECLARE_CAST(JSArrayBufferView)
9720 DECLARE_VERIFIER(JSArrayBufferView)
9722 inline bool WasNeutered() const;
9724 static const int kBufferOffset = JSObject::kHeaderSize;
9725 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9726 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9727 static const int kViewSize = kByteLengthOffset + kPointerSize;
9731 DECL_ACCESSORS(raw_byte_offset, Object)
9732 DECL_ACCESSORS(raw_byte_length, Object)
9735 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9739 class JSTypedArray: public JSArrayBufferView {
9741 // [length]: length of typed array in elements.
9742 DECL_ACCESSORS(length, Object)
9743 inline uint32_t length_value() const;
9745 DECLARE_CAST(JSTypedArray)
9747 ExternalArrayType type();
9748 size_t element_size();
9750 Handle<JSArrayBuffer> GetBuffer();
9752 // Dispatched behavior.
9753 DECLARE_PRINTER(JSTypedArray)
9754 DECLARE_VERIFIER(JSTypedArray)
9756 static const int kLengthOffset = kViewSize + kPointerSize;
9757 static const int kSize = kLengthOffset + kPointerSize;
9759 static const int kSizeWithInternalFields =
9760 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9763 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9764 Handle<JSTypedArray> typed_array);
9766 DECL_ACCESSORS(raw_length, Object)
9769 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9773 class JSDataView: public JSArrayBufferView {
9775 DECLARE_CAST(JSDataView)
9777 // Dispatched behavior.
9778 DECLARE_PRINTER(JSDataView)
9779 DECLARE_VERIFIER(JSDataView)
9781 static const int kSize = kViewSize;
9783 static const int kSizeWithInternalFields =
9784 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9787 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9791 // Foreign describes objects pointing from JavaScript to C structures.
9792 class Foreign: public HeapObject {
9794 // [address]: field containing the address.
9795 inline Address foreign_address();
9796 inline void set_foreign_address(Address value);
9798 DECLARE_CAST(Foreign)
9800 // Dispatched behavior.
9801 inline void ForeignIterateBody(ObjectVisitor* v);
9803 template<typename StaticVisitor>
9804 inline void ForeignIterateBody();
9806 // Dispatched behavior.
9807 DECLARE_PRINTER(Foreign)
9808 DECLARE_VERIFIER(Foreign)
9810 // Layout description.
9812 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9813 static const int kSize = kForeignAddressOffset + kPointerSize;
9815 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9818 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9822 // The JSArray describes JavaScript Arrays
9823 // Such an array can be in one of two modes:
9824 // - fast, backing storage is a FixedArray and length <= elements.length();
9825 // Please note: push and pop can be used to grow and shrink the array.
9826 // - slow, backing storage is a HashTable with numbers as keys.
9827 class JSArray: public JSObject {
9829 // [length]: The length property.
9830 DECL_ACCESSORS(length, Object)
9832 // Overload the length setter to skip write barrier when the length
9833 // is set to a smi. This matches the set function on FixedArray.
9834 inline void set_length(Smi* length);
9836 static bool HasReadOnlyLength(Handle<JSArray> array);
9837 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9838 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9840 // Initialize the array with the given capacity. The function may
9841 // fail due to out-of-memory situations, but only if the requested
9842 // capacity is non-zero.
9843 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9845 // If the JSArray has fast elements, and new_length would result in
9846 // normalization, returns true.
9847 bool SetLengthWouldNormalize(uint32_t new_length);
9848 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9850 // Initializes the array to a certain length.
9851 inline bool AllowsSetLength();
9853 static void SetLength(Handle<JSArray> array, uint32_t length);
9854 // Same as above but will also queue splice records if |array| is observed.
9855 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9858 // Set the content of the array to the content of storage.
9859 static inline void SetContent(Handle<JSArray> array,
9860 Handle<FixedArrayBase> storage);
9862 DECLARE_CAST(JSArray)
9864 // Dispatched behavior.
9865 DECLARE_PRINTER(JSArray)
9866 DECLARE_VERIFIER(JSArray)
9868 // Number of element slots to pre-allocate for an empty array.
9869 static const int kPreallocatedArrayElements = 4;
9871 // Layout description.
9872 static const int kLengthOffset = JSObject::kHeaderSize;
9873 static const int kSize = kLengthOffset + kPointerSize;
9876 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9880 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9881 Handle<Map> initial_map);
9884 // JSRegExpResult is just a JSArray with a specific initial map.
9885 // This initial map adds in-object properties for "index" and "input"
9886 // properties, as assigned by RegExp.prototype.exec, which allows
9887 // faster creation of RegExp exec results.
9888 // This class just holds constants used when creating the result.
9889 // After creation the result must be treated as a JSArray in all regards.
9890 class JSRegExpResult: public JSArray {
9892 // Offsets of object fields.
9893 static const int kIndexOffset = JSArray::kSize;
9894 static const int kInputOffset = kIndexOffset + kPointerSize;
9895 static const int kSize = kInputOffset + kPointerSize;
9896 // Indices of in-object properties.
9897 static const int kIndexIndex = 0;
9898 static const int kInputIndex = 1;
9900 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9904 class AccessorInfo: public Struct {
9906 DECL_ACCESSORS(name, Object)
9907 DECL_ACCESSORS(flag, Smi)
9908 DECL_ACCESSORS(expected_receiver_type, Object)
9910 inline bool all_can_read();
9911 inline void set_all_can_read(bool value);
9913 inline bool all_can_write();
9914 inline void set_all_can_write(bool value);
9916 inline bool is_special_data_property();
9917 inline void set_is_special_data_property(bool value);
9919 inline PropertyAttributes property_attributes();
9920 inline void set_property_attributes(PropertyAttributes attributes);
9922 // Checks whether the given receiver is compatible with this accessor.
9923 static bool IsCompatibleReceiverMap(Isolate* isolate,
9924 Handle<AccessorInfo> info,
9926 inline bool IsCompatibleReceiver(Object* receiver);
9928 DECLARE_CAST(AccessorInfo)
9930 // Dispatched behavior.
9931 DECLARE_VERIFIER(AccessorInfo)
9933 // Append all descriptors to the array that are not already there.
9934 // Return number added.
9935 static int AppendUnique(Handle<Object> descriptors,
9936 Handle<FixedArray> array,
9937 int valid_descriptors);
9939 static const int kNameOffset = HeapObject::kHeaderSize;
9940 static const int kFlagOffset = kNameOffset + kPointerSize;
9941 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9942 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9945 inline bool HasExpectedReceiverType();
9947 // Bit positions in flag.
9948 static const int kAllCanReadBit = 0;
9949 static const int kAllCanWriteBit = 1;
9950 static const int kSpecialDataProperty = 2;
9951 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9953 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9957 // An accessor must have a getter, but can have no setter.
9959 // When setting a property, V8 searches accessors in prototypes.
9960 // If an accessor was found and it does not have a setter,
9961 // the request is ignored.
9963 // If the accessor in the prototype has the READ_ONLY property attribute, then
9964 // a new value is added to the derived object when the property is set.
9965 // This shadows the accessor in the prototype.
9966 class ExecutableAccessorInfo: public AccessorInfo {
9968 DECL_ACCESSORS(getter, Object)
9969 DECL_ACCESSORS(setter, Object)
9970 DECL_ACCESSORS(data, Object)
9972 DECLARE_CAST(ExecutableAccessorInfo)
9974 // Dispatched behavior.
9975 DECLARE_PRINTER(ExecutableAccessorInfo)
9976 DECLARE_VERIFIER(ExecutableAccessorInfo)
9978 static const int kGetterOffset = AccessorInfo::kSize;
9979 static const int kSetterOffset = kGetterOffset + kPointerSize;
9980 static const int kDataOffset = kSetterOffset + kPointerSize;
9981 static const int kSize = kDataOffset + kPointerSize;
9983 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9986 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9990 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9991 // accessor can either be
9992 // * a pointer to a JavaScript function or proxy: a real accessor
9993 // * undefined: considered an accessor by the spec, too, strangely enough
9994 // * the hole: an accessor which has not been set
9995 // * a pointer to a map: a transition used to ensure map sharing
9996 class AccessorPair: public Struct {
9998 DECL_ACCESSORS(getter, Object)
9999 DECL_ACCESSORS(setter, Object)
10001 DECLARE_CAST(AccessorPair)
10003 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10005 inline Object* get(AccessorComponent component);
10006 inline void set(AccessorComponent component, Object* value);
10008 // Note: Returns undefined instead in case of a hole.
10009 Object* GetComponent(AccessorComponent component);
10011 // Set both components, skipping arguments which are a JavaScript null.
10012 inline void SetComponents(Object* getter, Object* setter);
10014 inline bool Equals(AccessorPair* pair);
10015 inline bool Equals(Object* getter_value, Object* setter_value);
10017 inline bool ContainsAccessor();
10019 // Dispatched behavior.
10020 DECLARE_PRINTER(AccessorPair)
10021 DECLARE_VERIFIER(AccessorPair)
10023 static const int kGetterOffset = HeapObject::kHeaderSize;
10024 static const int kSetterOffset = kGetterOffset + kPointerSize;
10025 static const int kSize = kSetterOffset + kPointerSize;
10028 // Strangely enough, in addition to functions and harmony proxies, the spec
10029 // requires us to consider undefined as a kind of accessor, too:
10031 // Object.defineProperty(obj, "foo", {get: undefined});
10032 // assertTrue("foo" in obj);
10033 inline bool IsJSAccessor(Object* obj);
10035 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10039 class AccessCheckInfo: public Struct {
10041 DECL_ACCESSORS(named_callback, Object)
10042 DECL_ACCESSORS(indexed_callback, Object)
10043 DECL_ACCESSORS(data, Object)
10045 DECLARE_CAST(AccessCheckInfo)
10047 // Dispatched behavior.
10048 DECLARE_PRINTER(AccessCheckInfo)
10049 DECLARE_VERIFIER(AccessCheckInfo)
10051 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10052 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10053 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10054 static const int kSize = kDataOffset + kPointerSize;
10057 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10061 class InterceptorInfo: public Struct {
10063 DECL_ACCESSORS(getter, Object)
10064 DECL_ACCESSORS(setter, Object)
10065 DECL_ACCESSORS(query, Object)
10066 DECL_ACCESSORS(deleter, Object)
10067 DECL_ACCESSORS(enumerator, Object)
10068 DECL_ACCESSORS(data, Object)
10069 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10070 DECL_BOOLEAN_ACCESSORS(all_can_read)
10071 DECL_BOOLEAN_ACCESSORS(non_masking)
10073 inline int flags() const;
10074 inline void set_flags(int flags);
10076 DECLARE_CAST(InterceptorInfo)
10078 // Dispatched behavior.
10079 DECLARE_PRINTER(InterceptorInfo)
10080 DECLARE_VERIFIER(InterceptorInfo)
10082 static const int kGetterOffset = HeapObject::kHeaderSize;
10083 static const int kSetterOffset = kGetterOffset + kPointerSize;
10084 static const int kQueryOffset = kSetterOffset + kPointerSize;
10085 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10086 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10087 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10088 static const int kFlagsOffset = kDataOffset + kPointerSize;
10089 static const int kSize = kFlagsOffset + kPointerSize;
10091 static const int kCanInterceptSymbolsBit = 0;
10092 static const int kAllCanReadBit = 1;
10093 static const int kNonMasking = 2;
10096 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10100 class CallHandlerInfo: public Struct {
10102 DECL_ACCESSORS(callback, Object)
10103 DECL_ACCESSORS(data, Object)
10105 DECLARE_CAST(CallHandlerInfo)
10107 // Dispatched behavior.
10108 DECLARE_PRINTER(CallHandlerInfo)
10109 DECLARE_VERIFIER(CallHandlerInfo)
10111 static const int kCallbackOffset = HeapObject::kHeaderSize;
10112 static const int kDataOffset = kCallbackOffset + kPointerSize;
10113 static const int kSize = kDataOffset + kPointerSize;
10116 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10120 class TemplateInfo: public Struct {
10122 DECL_ACCESSORS(tag, Object)
10123 inline int number_of_properties() const;
10124 inline void set_number_of_properties(int value);
10125 DECL_ACCESSORS(property_list, Object)
10126 DECL_ACCESSORS(property_accessors, Object)
10128 DECLARE_VERIFIER(TemplateInfo)
10130 static const int kTagOffset = HeapObject::kHeaderSize;
10131 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10132 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10133 static const int kPropertyAccessorsOffset =
10134 kPropertyListOffset + kPointerSize;
10135 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10138 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10142 class FunctionTemplateInfo: public TemplateInfo {
10144 DECL_ACCESSORS(serial_number, Object)
10145 DECL_ACCESSORS(call_code, Object)
10146 DECL_ACCESSORS(prototype_template, Object)
10147 DECL_ACCESSORS(parent_template, Object)
10148 DECL_ACCESSORS(named_property_handler, Object)
10149 DECL_ACCESSORS(indexed_property_handler, Object)
10150 DECL_ACCESSORS(instance_template, Object)
10151 DECL_ACCESSORS(class_name, Object)
10152 DECL_ACCESSORS(signature, Object)
10153 DECL_ACCESSORS(instance_call_handler, Object)
10154 DECL_ACCESSORS(access_check_info, Object)
10155 DECL_ACCESSORS(flag, Smi)
10157 inline int length() const;
10158 inline void set_length(int value);
10160 // Following properties use flag bits.
10161 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10162 DECL_BOOLEAN_ACCESSORS(undetectable)
10163 // If the bit is set, object instances created by this function
10164 // requires access check.
10165 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10166 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10167 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10168 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10169 DECL_BOOLEAN_ACCESSORS(instantiated)
10170 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10172 DECLARE_CAST(FunctionTemplateInfo)
10174 // Dispatched behavior.
10175 DECLARE_PRINTER(FunctionTemplateInfo)
10176 DECLARE_VERIFIER(FunctionTemplateInfo)
10178 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10179 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10180 static const int kPrototypeTemplateOffset =
10181 kCallCodeOffset + kPointerSize;
10182 static const int kParentTemplateOffset =
10183 kPrototypeTemplateOffset + kPointerSize;
10184 static const int kNamedPropertyHandlerOffset =
10185 kParentTemplateOffset + kPointerSize;
10186 static const int kIndexedPropertyHandlerOffset =
10187 kNamedPropertyHandlerOffset + kPointerSize;
10188 static const int kInstanceTemplateOffset =
10189 kIndexedPropertyHandlerOffset + kPointerSize;
10190 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10191 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10192 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10193 static const int kAccessCheckInfoOffset =
10194 kInstanceCallHandlerOffset + kPointerSize;
10195 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10196 static const int kLengthOffset = kFlagOffset + kPointerSize;
10197 static const int kSize = kLengthOffset + kPointerSize;
10199 // Returns true if |object| is an instance of this function template.
10200 bool IsTemplateFor(Object* object);
10201 bool IsTemplateFor(Map* map);
10203 // Returns the holder JSObject if the function can legally be called with this
10204 // receiver. Returns Heap::null_value() if the call is illegal.
10205 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10208 // Bit position in the flag, from least significant bit position.
10209 static const int kHiddenPrototypeBit = 0;
10210 static const int kUndetectableBit = 1;
10211 static const int kNeedsAccessCheckBit = 2;
10212 static const int kReadOnlyPrototypeBit = 3;
10213 static const int kRemovePrototypeBit = 4;
10214 static const int kDoNotCacheBit = 5;
10215 static const int kInstantiatedBit = 6;
10216 static const int kAcceptAnyReceiver = 7;
10218 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10222 class ObjectTemplateInfo: public TemplateInfo {
10224 DECL_ACCESSORS(constructor, Object)
10225 DECL_ACCESSORS(internal_field_count, Object)
10227 DECLARE_CAST(ObjectTemplateInfo)
10229 // Dispatched behavior.
10230 DECLARE_PRINTER(ObjectTemplateInfo)
10231 DECLARE_VERIFIER(ObjectTemplateInfo)
10233 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10234 static const int kInternalFieldCountOffset =
10235 kConstructorOffset + kPointerSize;
10236 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10240 class TypeSwitchInfo: public Struct {
10242 DECL_ACCESSORS(types, Object)
10244 DECLARE_CAST(TypeSwitchInfo)
10246 // Dispatched behavior.
10247 DECLARE_PRINTER(TypeSwitchInfo)
10248 DECLARE_VERIFIER(TypeSwitchInfo)
10250 static const int kTypesOffset = Struct::kHeaderSize;
10251 static const int kSize = kTypesOffset + kPointerSize;
10255 // The DebugInfo class holds additional information for a function being
10257 class DebugInfo: public Struct {
10259 // The shared function info for the source being debugged.
10260 DECL_ACCESSORS(shared, SharedFunctionInfo)
10261 // Code object for the patched code. This code object is the code object
10262 // currently active for the function.
10263 DECL_ACCESSORS(code, Code)
10264 // Fixed array holding status information for each active break point.
10265 DECL_ACCESSORS(break_points, FixedArray)
10267 // Check if there is a break point at a code position.
10268 bool HasBreakPoint(int code_position);
10269 // Get the break point info object for a code position.
10270 Object* GetBreakPointInfo(int code_position);
10271 // Clear a break point.
10272 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10274 Handle<Object> break_point_object);
10275 // Set a break point.
10276 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10277 int source_position, int statement_position,
10278 Handle<Object> break_point_object);
10279 // Get the break point objects for a code position.
10280 Handle<Object> GetBreakPointObjects(int code_position);
10281 // Find the break point info holding this break point object.
10282 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10283 Handle<Object> break_point_object);
10284 // Get the number of break points for this function.
10285 int GetBreakPointCount();
10287 DECLARE_CAST(DebugInfo)
10289 // Dispatched behavior.
10290 DECLARE_PRINTER(DebugInfo)
10291 DECLARE_VERIFIER(DebugInfo)
10293 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10294 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10295 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10296 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10298 static const int kEstimatedNofBreakPointsInFunction = 16;
10301 static const int kNoBreakPointInfo = -1;
10303 // Lookup the index in the break_points array for a code position.
10304 int GetBreakPointInfoIndex(int code_position);
10306 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10310 // The BreakPointInfo class holds information for break points set in a
10311 // function. The DebugInfo object holds a BreakPointInfo object for each code
10312 // position with one or more break points.
10313 class BreakPointInfo: public Struct {
10315 // The position in the code for the break point.
10316 DECL_ACCESSORS(code_position, Smi)
10317 // The position in the source for the break position.
10318 DECL_ACCESSORS(source_position, Smi)
10319 // The position in the source for the last statement before this break
10321 DECL_ACCESSORS(statement_position, Smi)
10322 // List of related JavaScript break points.
10323 DECL_ACCESSORS(break_point_objects, Object)
10325 // Removes a break point.
10326 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10327 Handle<Object> break_point_object);
10328 // Set a break point.
10329 static void SetBreakPoint(Handle<BreakPointInfo> info,
10330 Handle<Object> break_point_object);
10331 // Check if break point info has this break point object.
10332 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10333 Handle<Object> break_point_object);
10334 // Get the number of break points for this code position.
10335 int GetBreakPointCount();
10337 DECLARE_CAST(BreakPointInfo)
10339 // Dispatched behavior.
10340 DECLARE_PRINTER(BreakPointInfo)
10341 DECLARE_VERIFIER(BreakPointInfo)
10343 static const int kCodePositionIndex = Struct::kHeaderSize;
10344 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10345 static const int kStatementPositionIndex =
10346 kSourcePositionIndex + kPointerSize;
10347 static const int kBreakPointObjectsIndex =
10348 kStatementPositionIndex + kPointerSize;
10349 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10352 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10356 #undef DECL_BOOLEAN_ACCESSORS
10357 #undef DECL_ACCESSORS
10358 #undef DECLARE_CAST
10359 #undef DECLARE_VERIFIER
10361 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10362 V(kStringTable, "string_table", "(Internalized strings)") \
10363 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10364 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10365 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10366 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10367 V(kTop, "top", "(Isolate)") \
10368 V(kRelocatable, "relocatable", "(Relocatable)") \
10369 V(kDebug, "debug", "(Debugger)") \
10370 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10371 V(kHandleScope, "handlescope", "(Handle scope)") \
10372 V(kBuiltins, "builtins", "(Builtins)") \
10373 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10374 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10375 V(kThreadManager, "threadmanager", "(Thread manager)") \
10376 V(kStrongRoots, "strong roots", "(Strong roots)") \
10377 V(kExtensions, "Extensions", "(Extensions)")
10379 class VisitorSynchronization : public AllStatic {
10381 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10383 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10386 #undef DECLARE_ENUM
10388 static const char* const kTags[kNumberOfSyncTags];
10389 static const char* const kTagNames[kNumberOfSyncTags];
10392 // Abstract base class for visiting, and optionally modifying, the
10393 // pointers contained in Objects. Used in GC and serialization/deserialization.
10394 class ObjectVisitor BASE_EMBEDDED {
10396 virtual ~ObjectVisitor() {}
10398 // Visits a contiguous arrays of pointers in the half-open range
10399 // [start, end). Any or all of the values may be modified on return.
10400 virtual void VisitPointers(Object** start, Object** end) = 0;
10402 // Handy shorthand for visiting a single pointer.
10403 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10405 // Visit weak next_code_link in Code object.
10406 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10408 // To allow lazy clearing of inline caches the visitor has
10409 // a rich interface for iterating over Code objects..
10411 // Visits a code target in the instruction stream.
10412 virtual void VisitCodeTarget(RelocInfo* rinfo);
10414 // Visits a code entry in a JS function.
10415 virtual void VisitCodeEntry(Address entry_address);
10417 // Visits a global property cell reference in the instruction stream.
10418 virtual void VisitCell(RelocInfo* rinfo);
10420 // Visits a runtime entry in the instruction stream.
10421 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10423 // Visits the resource of an one-byte or two-byte string.
10424 virtual void VisitExternalOneByteString(
10425 v8::String::ExternalOneByteStringResource** resource) {}
10426 virtual void VisitExternalTwoByteString(
10427 v8::String::ExternalStringResource** resource) {}
10429 // Visits a debug call target in the instruction stream.
10430 virtual void VisitDebugTarget(RelocInfo* rinfo);
10432 // Visits the byte sequence in a function's prologue that contains information
10433 // about the code's age.
10434 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10436 // Visit pointer embedded into a code object.
10437 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10439 // Visits an external reference embedded into a code object.
10440 virtual void VisitExternalReference(RelocInfo* rinfo);
10442 // Visits an external reference.
10443 virtual void VisitExternalReference(Address* p) {}
10445 // Visits an (encoded) internal reference.
10446 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10448 // Visits a handle that has an embedder-assigned class ID.
10449 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10451 // Intended for serialization/deserialization checking: insert, or
10452 // check for the presence of, a tag at this position in the stream.
10453 // Also used for marking up GC roots in heap snapshots.
10454 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10458 class StructBodyDescriptor : public
10459 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10461 static inline int SizeOf(Map* map, HeapObject* object);
10465 // BooleanBit is a helper class for setting and getting a bit in an
10467 class BooleanBit : public AllStatic {
10469 static inline bool get(Smi* smi, int bit_position) {
10470 return get(smi->value(), bit_position);
10473 static inline bool get(int value, int bit_position) {
10474 return (value & (1 << bit_position)) != 0;
10477 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10478 return Smi::FromInt(set(smi->value(), bit_position, v));
10481 static inline int set(int value, int bit_position, bool v) {
10483 value |= (1 << bit_position);
10485 value &= ~(1 << bit_position);
10491 } } // namespace v8::internal
10493 #endif // V8_OBJECTS_H_