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();
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.13 Strict Equality Comparison
1087 bool StrictEquals(Object* that);
1089 // Convert to a JSObject if needed.
1090 // native_context is used when creating wrapper object.
1091 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1092 Handle<Object> object);
1093 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1094 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1096 // ES6 section 7.1.14 ToPropertyKey
1097 MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1098 Handle<Object> input);
1100 // ES6 section 7.1.1 ToPrimitive
1101 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1102 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1104 // ES6 section 7.1.3 ToNumber
1105 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Handle<Object> input);
1107 // ES6 section 7.1.12 ToString
1108 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1109 Handle<Object> input);
1111 // ES6 section 7.3.9 GetMethod
1112 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1113 Handle<JSReceiver> receiver, Handle<Name> name);
1115 // ES6 section 12.5.6 The typeof Operator
1116 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1118 // ES6 section 12.6 Multiplicative Operators
1119 MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1120 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1121 Strength strength = Strength::WEAK);
1122 MUST_USE_RESULT static MaybeHandle<Object> Divide(
1123 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1124 Strength strength = Strength::WEAK);
1125 MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1126 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1127 Strength strength = Strength::WEAK);
1129 // ES6 section 12.7 Additive Operators
1130 MUST_USE_RESULT static MaybeHandle<Object> Add(
1131 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1132 Strength strength = Strength::WEAK);
1133 MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1134 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1135 Strength strength = Strength::WEAK);
1137 // ES6 section 12.8 Bitwise Shift Operators
1138 MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1139 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1140 Strength strength = Strength::WEAK);
1141 MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1142 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1143 Strength strength = Strength::WEAK);
1144 MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1145 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1146 Strength strength = Strength::WEAK);
1148 // ES6 section 12.11 Binary Bitwise Operators
1149 MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1150 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1151 Strength strength = Strength::WEAK);
1152 MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1153 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1154 Strength strength = Strength::WEAK);
1155 MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1156 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1157 Strength strength = Strength::WEAK);
1159 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1160 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1162 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1163 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1164 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1165 LanguageMode language_mode,
1166 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1168 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1169 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1170 StoreFromKeyed store_mode);
1172 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1173 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1174 StoreFromKeyed store_mode);
1176 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1177 LookupIterator* it, LanguageMode language_mode);
1178 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1179 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1180 LanguageMode language_mode);
1181 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1182 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1183 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1184 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1185 Handle<Object> value, LanguageMode language_mode);
1186 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1187 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1188 LanguageMode language_mode);
1189 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1190 LookupIterator* it, Handle<Object> value);
1191 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1192 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1193 LanguageMode language_mode, StoreFromKeyed store_mode);
1194 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1195 Handle<Object> object, Handle<Name> name,
1196 LanguageMode language_mode = SLOPPY);
1197 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1198 Isolate* isolate, Handle<Object> object, const char* key,
1199 LanguageMode language_mode = SLOPPY);
1200 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1201 Handle<Object> object, Handle<Name> name,
1202 LanguageMode language_mode = SLOPPY);
1204 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1205 LookupIterator* it, LanguageMode language_mode);
1206 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1207 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1209 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1210 Handle<Object> receiver,
1211 Handle<JSReceiver> getter);
1212 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1213 Handle<Object> receiver,
1214 Handle<JSReceiver> setter,
1215 Handle<Object> value);
1217 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1218 Isolate* isolate, Handle<Object> object, uint32_t index,
1219 LanguageMode language_mode = SLOPPY);
1221 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1222 Isolate* isolate, Handle<Object> object, uint32_t index,
1223 Handle<Object> value, LanguageMode language_mode);
1225 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1226 Isolate* isolate, Handle<Object> receiver);
1228 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1230 // Returns the permanent hash code associated with this object. May return
1231 // undefined if not yet created.
1234 // Returns undefined for JSObjects, but returns the hash code for simple
1235 // objects. This avoids a double lookup in the cases where we know we will
1236 // add the hash to the JSObject if it does not already exist.
1237 Object* GetSimpleHash();
1239 // Returns the permanent hash code associated with this object depending on
1240 // the actual object type. May create and store a hash code if needed and none
1242 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1244 // Checks whether this object has the same value as the given one. This
1245 // function is implemented according to ES5, section 9.12 and can be used
1246 // to implement the Harmony "egal" function.
1247 bool SameValue(Object* other);
1249 // Checks whether this object has the same value as the given one.
1250 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1251 // This function is implemented according to ES6, section 7.2.4 and is used
1252 // by ES6 Map and Set.
1253 bool SameValueZero(Object* other);
1255 // Tries to convert an object to an array length. Returns true and sets the
1256 // output parameter if it succeeds.
1257 inline bool ToArrayLength(uint32_t* index);
1259 // Tries to convert an object to an array index. Returns true and sets the
1260 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1261 // allow kMaxUInt32.
1262 inline bool ToArrayIndex(uint32_t* index);
1264 // Returns true if this is a JSValue containing a string and the index is
1265 // < the length of the string. Used to implement [] on strings.
1266 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1268 DECLARE_VERIFIER(Object)
1270 // Verify a pointer is a valid object pointer.
1271 static void VerifyPointer(Object* p);
1274 inline void VerifyApiCallResultType();
1276 // Prints this object without details.
1277 void ShortPrint(FILE* out = stdout);
1279 // Prints this object without details to a message accumulator.
1280 void ShortPrint(StringStream* accumulator);
1282 void ShortPrint(std::ostream& os); // NOLINT
1284 DECLARE_CAST(Object)
1286 // Layout description.
1287 static const int kHeaderSize = 0; // Object does not take up any space.
1290 // For our gdb macros, we should perhaps change these in the future.
1293 // Prints this object with details.
1294 void Print(std::ostream& os); // NOLINT
1296 void Print() { ShortPrint(); }
1297 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1301 friend class LookupIterator;
1302 friend class PrototypeIterator;
1304 // Return the map of the root of object's prototype chain.
1305 Map* GetRootMap(Isolate* isolate);
1307 // Helper for SetProperty and SetSuperProperty.
1308 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1309 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1310 StoreFromKeyed store_mode, bool* found);
1312 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1316 // In objects.h to be usable without objects-inl.h inclusion.
1317 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1318 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1322 explicit Brief(const Object* const v) : value(v) {}
1323 const Object* value;
1327 std::ostream& operator<<(std::ostream& os, const Brief& v);
1330 // Smi represents integer Numbers that can be stored in 31 bits.
1331 // Smis are immediate which means they are NOT allocated in the heap.
1332 // The this pointer has the following format: [31 bit signed int] 0
1333 // For long smis it has the following format:
1334 // [32 bit signed int] [31 bits zero padding] 0
1335 // Smi stands for small integer.
1336 class Smi: public Object {
1338 // Returns the integer value.
1339 inline int value() const { return Internals::SmiValue(this); }
1341 // Convert a value to a Smi object.
1342 static inline Smi* FromInt(int value) {
1343 DCHECK(Smi::IsValid(value));
1344 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1347 static inline Smi* FromIntptr(intptr_t value) {
1348 DCHECK(Smi::IsValid(value));
1349 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1350 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1353 // Returns whether value can be represented in a Smi.
1354 static inline bool IsValid(intptr_t value) {
1355 bool result = Internals::IsValidSmi(value);
1356 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1362 // Dispatched behavior.
1363 void SmiPrint(std::ostream& os) const; // NOLINT
1364 DECLARE_VERIFIER(Smi)
1366 static const int kMinValue =
1367 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1368 static const int kMaxValue = -(kMinValue + 1);
1371 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1375 // Heap objects typically have a map pointer in their first word. However,
1376 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1377 // encoded in the first word. The class MapWord is an abstraction of the
1378 // value in a heap object's first word.
1379 class MapWord BASE_EMBEDDED {
1381 // Normal state: the map word contains a map pointer.
1383 // Create a map word from a map pointer.
1384 static inline MapWord FromMap(const Map* map);
1386 // View this map word as a map pointer.
1387 inline Map* ToMap();
1390 // Scavenge collection: the map word of live objects in the from space
1391 // contains a forwarding address (a heap object pointer in the to space).
1393 // True if this map word is a forwarding address for a scavenge
1394 // collection. Only valid during a scavenge collection (specifically,
1395 // when all map words are heap object pointers, i.e. not during a full GC).
1396 inline bool IsForwardingAddress();
1398 // Create a map word from a forwarding address.
1399 static inline MapWord FromForwardingAddress(HeapObject* object);
1401 // View this map word as a forwarding address.
1402 inline HeapObject* ToForwardingAddress();
1404 static inline MapWord FromRawValue(uintptr_t value) {
1405 return MapWord(value);
1408 inline uintptr_t ToRawValue() {
1413 // HeapObject calls the private constructor and directly reads the value.
1414 friend class HeapObject;
1416 explicit MapWord(uintptr_t value) : value_(value) {}
1422 // The content of an heap object (except for the map pointer). kTaggedValues
1423 // objects can contain both heap pointers and Smis, kMixedValues can contain
1424 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1425 // objects can contain raw values and Smis.
1426 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1429 // HeapObject is the superclass for all classes describing heap allocated
1431 class HeapObject: public Object {
1433 // [map]: Contains a map which contains the object's reflective
1435 inline Map* map() const;
1436 inline void set_map(Map* value);
1437 // The no-write-barrier version. This is OK if the object is white and in
1438 // new space, or if the value is an immortal immutable object, like the maps
1439 // of primitive (non-JS) objects like strings, heap numbers etc.
1440 inline void set_map_no_write_barrier(Map* value);
1442 // Get the map using acquire load.
1443 inline Map* synchronized_map();
1444 inline MapWord synchronized_map_word() const;
1446 // Set the map using release store
1447 inline void synchronized_set_map(Map* value);
1448 inline void synchronized_set_map_no_write_barrier(Map* value);
1449 inline void synchronized_set_map_word(MapWord map_word);
1451 // During garbage collection, the map word of a heap object does not
1452 // necessarily contain a map pointer.
1453 inline MapWord map_word() const;
1454 inline void set_map_word(MapWord map_word);
1456 // The Heap the object was allocated in. Used also to access Isolate.
1457 inline Heap* GetHeap() const;
1459 // Convenience method to get current isolate.
1460 inline Isolate* GetIsolate() const;
1462 // Converts an address to a HeapObject pointer.
1463 static inline HeapObject* FromAddress(Address address) {
1464 DCHECK_TAG_ALIGNED(address);
1465 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1468 // Returns the address of this HeapObject.
1469 inline Address address() {
1470 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1473 // Iterates over pointers contained in the object (including the Map)
1474 void Iterate(ObjectVisitor* v);
1476 // Iterates over all pointers contained in the object except the
1477 // first map pointer. The object type is given in the first
1478 // parameter. This function does not access the map pointer in the
1479 // object, and so is safe to call while the map pointer is modified.
1480 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1482 // Returns the heap object's size in bytes
1485 // Indicates what type of values this heap object may contain.
1486 inline HeapObjectContents ContentType();
1488 // Given a heap object's map pointer, returns the heap size in bytes
1489 // Useful when the map pointer field is used for other purposes.
1491 inline int SizeFromMap(Map* map);
1493 // Returns the field at offset in obj, as a read/write Object* reference.
1494 // Does no checking, and is safe to use during GC, while maps are invalid.
1495 // Does not invoke write barrier, so should only be assigned to
1496 // during marking GC.
1497 static inline Object** RawField(HeapObject* obj, int offset);
1499 // Adds the |code| object related to |name| to the code cache of this map. If
1500 // this map is a dictionary map that is shared, the map copied and installed
1502 static void UpdateMapCodeCache(Handle<HeapObject> object,
1506 DECLARE_CAST(HeapObject)
1508 // Return the write barrier mode for this. Callers of this function
1509 // must be able to present a reference to an DisallowHeapAllocation
1510 // object as a sign that they are not going to use this function
1511 // from code that allocates and thus invalidates the returned write
1513 inline WriteBarrierMode GetWriteBarrierMode(
1514 const DisallowHeapAllocation& promise);
1516 // Dispatched behavior.
1517 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1519 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1521 DECLARE_PRINTER(HeapObject)
1522 DECLARE_VERIFIER(HeapObject)
1524 inline void VerifyObjectField(int offset);
1525 inline void VerifySmiField(int offset);
1527 // Verify a pointer is a valid HeapObject pointer that points to object
1528 // areas in the heap.
1529 static void VerifyHeapPointer(Object* p);
1532 inline AllocationAlignment RequiredAlignment();
1534 // Layout description.
1535 // First field in a heap object is map.
1536 static const int kMapOffset = Object::kHeaderSize;
1537 static const int kHeaderSize = kMapOffset + kPointerSize;
1539 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1542 // helpers for calling an ObjectVisitor to iterate over pointers in the
1543 // half-open range [start, end) specified as integer offsets
1544 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1545 // as above, for the single element at "offset"
1546 inline void IteratePointer(ObjectVisitor* v, int offset);
1547 // as above, for the next code link of a code object.
1548 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1551 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1555 // This class describes a body of an object of a fixed size
1556 // in which all pointer fields are located in the [start_offset, end_offset)
1558 template<int start_offset, int end_offset, int size>
1559 class FixedBodyDescriptor {
1561 static const int kStartOffset = start_offset;
1562 static const int kEndOffset = end_offset;
1563 static const int kSize = size;
1565 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1567 template<typename StaticVisitor>
1568 static inline void IterateBody(HeapObject* obj) {
1569 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1570 HeapObject::RawField(obj, end_offset));
1575 // This class describes a body of an object of a variable size
1576 // in which all pointer fields are located in the [start_offset, object_size)
1578 template<int start_offset>
1579 class FlexibleBodyDescriptor {
1581 static const int kStartOffset = start_offset;
1583 static inline void IterateBody(HeapObject* obj,
1587 template<typename StaticVisitor>
1588 static inline void IterateBody(HeapObject* obj, int object_size) {
1589 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1590 HeapObject::RawField(obj, object_size));
1595 // The HeapNumber class describes heap allocated numbers that cannot be
1596 // represented in a Smi (small integer)
1597 class HeapNumber: public HeapObject {
1599 // [value]: number value.
1600 inline double value() const;
1601 inline void set_value(double value);
1603 DECLARE_CAST(HeapNumber)
1605 // Dispatched behavior.
1606 bool HeapNumberBooleanValue();
1608 void HeapNumberPrint(std::ostream& os); // NOLINT
1609 DECLARE_VERIFIER(HeapNumber)
1611 inline int get_exponent();
1612 inline int get_sign();
1614 // Layout description.
1615 static const int kValueOffset = HeapObject::kHeaderSize;
1616 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1617 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1618 // words within double numbers are endian dependent and they are set
1620 #if defined(V8_TARGET_LITTLE_ENDIAN)
1621 static const int kMantissaOffset = kValueOffset;
1622 static const int kExponentOffset = kValueOffset + 4;
1623 #elif defined(V8_TARGET_BIG_ENDIAN)
1624 static const int kMantissaOffset = kValueOffset + 4;
1625 static const int kExponentOffset = kValueOffset;
1627 #error Unknown byte ordering
1630 static const int kSize = kValueOffset + kDoubleSize;
1631 static const uint32_t kSignMask = 0x80000000u;
1632 static const uint32_t kExponentMask = 0x7ff00000u;
1633 static const uint32_t kMantissaMask = 0xfffffu;
1634 static const int kMantissaBits = 52;
1635 static const int kExponentBits = 11;
1636 static const int kExponentBias = 1023;
1637 static const int kExponentShift = 20;
1638 static const int kInfinityOrNanExponent =
1639 (kExponentMask >> kExponentShift) - kExponentBias;
1640 static const int kMantissaBitsInTopWord = 20;
1641 static const int kNonMantissaBitsInTopWord = 12;
1644 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1648 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1649 class Simd128Value : public HeapObject {
1651 DECLARE_CAST(Simd128Value)
1653 DECLARE_PRINTER(Simd128Value)
1654 DECLARE_VERIFIER(Simd128Value)
1656 static Handle<String> ToString(Handle<Simd128Value> input);
1658 // Equality operations.
1659 inline bool Equals(Simd128Value* that);
1661 // Checks that another instance is bit-wise equal.
1662 bool BitwiseEquals(const Simd128Value* other) const;
1663 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1664 uint32_t Hash() const;
1665 // Copies the 16 bytes of SIMD data to the destination address.
1666 void CopyBits(void* destination) const;
1668 // Layout description.
1669 static const int kValueOffset = HeapObject::kHeaderSize;
1670 static const int kSize = kValueOffset + kSimd128Size;
1673 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1677 // V has parameters (TYPE, Type, type, lane count, lane type)
1678 #define SIMD128_TYPES(V) \
1679 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1680 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1681 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1682 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1683 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1684 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1685 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1686 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1687 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1688 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1690 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1691 class Type final : public Simd128Value { \
1693 inline lane_type get_lane(int lane) const; \
1694 inline void set_lane(int lane, lane_type value); \
1696 DECLARE_CAST(Type) \
1698 DECLARE_PRINTER(Type) \
1700 static Handle<String> ToString(Handle<Type> input); \
1702 inline bool Equals(Type* that); \
1705 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1707 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1708 #undef SIMD128_VALUE_CLASS
1711 enum EnsureElementsMode {
1712 DONT_ALLOW_DOUBLE_ELEMENTS,
1713 ALLOW_COPIED_DOUBLE_ELEMENTS,
1714 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1718 // Indicator for one component of an AccessorPair.
1719 enum AccessorComponent {
1725 // JSReceiver includes types on which properties can be defined, i.e.,
1726 // JSObject and JSProxy.
1727 class JSReceiver: public HeapObject {
1729 DECLARE_CAST(JSReceiver)
1731 // ES6 section 7.1.1 ToPrimitive
1732 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1733 Handle<JSReceiver> receiver,
1734 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1735 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1736 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1738 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1739 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1740 Handle<JSReceiver> object, Handle<Name> name);
1741 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1743 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1744 Handle<JSReceiver> object, uint32_t index);
1745 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1746 Handle<JSReceiver> object, uint32_t index);
1748 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1749 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1750 Handle<JSReceiver> object, Handle<Name> name,
1751 LanguageMode language_mode = SLOPPY);
1752 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1753 Handle<JSReceiver> object, Handle<Name> name,
1754 LanguageMode language_mode = SLOPPY);
1755 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1756 LookupIterator* it, LanguageMode language_mode);
1757 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1758 Handle<JSReceiver> object, uint32_t index,
1759 LanguageMode language_mode = SLOPPY);
1761 // Tests for the fast common case for property enumeration.
1762 bool IsSimpleEnum();
1764 // Returns the class name ([[Class]] property in the specification).
1765 String* class_name();
1767 // Returns the constructor name (the name (possibly, inferred name) of the
1768 // function that was used to instantiate the object).
1769 String* constructor_name();
1771 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1772 Handle<JSReceiver> object, Handle<Name> name);
1773 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1774 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1776 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1777 Handle<JSReceiver> object, uint32_t index);
1778 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1779 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1781 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1782 LookupIterator* it);
1785 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1787 static Handle<Object> GetDataProperty(LookupIterator* it);
1790 // Retrieves a permanent object identity hash code. The undefined value might
1791 // be returned in case no hash was created yet.
1792 inline Object* GetIdentityHash();
1794 // Retrieves a permanent object identity hash code. May create and store a
1795 // hash code if needed and none exists.
1796 inline static Handle<Smi> GetOrCreateIdentityHash(
1797 Handle<JSReceiver> object);
1799 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1801 // Computes the enumerable keys for a JSObject. Used for implementing
1802 // "for (n in object) { }".
1803 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1804 Handle<JSReceiver> object,
1805 KeyCollectionType type);
1808 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1812 // The JSObject describes real heap allocated JavaScript objects with
1814 // Note that the map of JSObject changes during execution to enable inline
1816 class JSObject: public JSReceiver {
1818 // [properties]: Backing storage for properties.
1819 // properties is a FixedArray in the fast case and a Dictionary in the
1821 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1822 inline void initialize_properties();
1823 inline bool HasFastProperties();
1824 // Gets slow properties for non-global objects.
1825 inline NameDictionary* property_dictionary();
1826 // Gets global object properties.
1827 inline GlobalDictionary* global_dictionary();
1829 // [elements]: The elements (properties with names that are integers).
1831 // Elements can be in two general modes: fast and slow. Each mode
1832 // corrensponds to a set of object representations of elements that
1833 // have something in common.
1835 // In the fast mode elements is a FixedArray and so each element can
1836 // be quickly accessed. This fact is used in the generated code. The
1837 // elements array can have one of three maps in this mode:
1838 // fixed_array_map, sloppy_arguments_elements_map or
1839 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1840 // the elements array may be shared by a few objects and so before
1841 // writing to any element the array must be copied. Use
1842 // EnsureWritableFastElements in this case.
1844 // In the slow mode the elements is either a NumberDictionary, a
1845 // FixedArray parameter map for a (sloppy) arguments object.
1846 DECL_ACCESSORS(elements, FixedArrayBase)
1847 inline void initialize_elements();
1848 static void ResetElements(Handle<JSObject> object);
1849 static inline void SetMapAndElements(Handle<JSObject> object,
1851 Handle<FixedArrayBase> elements);
1852 inline ElementsKind GetElementsKind();
1853 ElementsAccessor* GetElementsAccessor();
1854 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1855 inline bool HasFastSmiElements();
1856 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1857 inline bool HasFastObjectElements();
1858 // Returns true if an object has elements of FAST_ELEMENTS or
1859 // FAST_SMI_ONLY_ELEMENTS.
1860 inline bool HasFastSmiOrObjectElements();
1861 // Returns true if an object has any of the fast elements kinds.
1862 inline bool HasFastElements();
1863 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1865 inline bool HasFastDoubleElements();
1866 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1868 inline bool HasFastHoleyElements();
1869 inline bool HasSloppyArgumentsElements();
1870 inline bool HasDictionaryElements();
1872 inline bool HasFixedTypedArrayElements();
1874 inline bool HasFixedUint8ClampedElements();
1875 inline bool HasFixedArrayElements();
1876 inline bool HasFixedInt8Elements();
1877 inline bool HasFixedUint8Elements();
1878 inline bool HasFixedInt16Elements();
1879 inline bool HasFixedUint16Elements();
1880 inline bool HasFixedInt32Elements();
1881 inline bool HasFixedUint32Elements();
1882 inline bool HasFixedFloat32Elements();
1883 inline bool HasFixedFloat64Elements();
1885 inline bool HasFastArgumentsElements();
1886 inline bool HasSlowArgumentsElements();
1887 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1889 // Requires: HasFastElements().
1890 static Handle<FixedArray> EnsureWritableFastElements(
1891 Handle<JSObject> object);
1893 // Collects elements starting at index 0.
1894 // Undefined values are placed after non-undefined values.
1895 // Returns the number of non-undefined values.
1896 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1898 // As PrepareElementsForSort, but only on objects where elements is
1899 // a dictionary, and it will stay a dictionary. Collates undefined and
1900 // unexisting elements below limit from position zero of the elements.
1901 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1904 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1905 LookupIterator* it, Handle<Object> value);
1907 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1908 // grant an exemption to ExecutableAccessor callbacks in some cases.
1909 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1911 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1912 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1913 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1915 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1916 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1917 PropertyAttributes attributes,
1918 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1920 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1921 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1922 PropertyAttributes attributes,
1923 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1925 // Equivalent to one of the above depending on whether |name| can be converted
1926 // to an array index.
1927 MUST_USE_RESULT static MaybeHandle<Object>
1928 DefinePropertyOrElementIgnoreAttributes(
1929 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1930 PropertyAttributes attributes = NONE,
1931 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1933 // Adds or reconfigures a property to attributes NONE. It will fail when it
1935 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1936 Handle<Object> value);
1938 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1939 Handle<Object> value, PropertyAttributes attributes);
1941 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1942 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1943 PropertyAttributes attributes);
1945 // Extend the receiver with a single fast property appeared first in the
1946 // passed map. This also extends the property backing store if necessary.
1947 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1949 // Migrates the given object to a map whose field representations are the
1950 // lowest upper bound of all known representations for that field.
1951 static void MigrateInstance(Handle<JSObject> instance);
1953 // Migrates the given object only if the target map is already available,
1954 // or returns false if such a map is not yet available.
1955 static bool TryMigrateInstance(Handle<JSObject> instance);
1957 // Sets the property value in a normalized object given (key, value, details).
1958 // Handles the special representation of JS global objects.
1959 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1960 Handle<Object> value,
1961 PropertyDetails details);
1962 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1963 Handle<Object> value,
1964 PropertyAttributes attributes);
1965 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1967 Handle<Object> value,
1968 PropertyAttributes attributes);
1970 static void OptimizeAsPrototype(Handle<JSObject> object,
1971 PrototypeOptimizationMode mode);
1972 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1973 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1974 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1975 static void InvalidatePrototypeChains(Map* map);
1977 // Alternative implementation of WeakFixedArray::NullCallback.
1978 class PrototypeRegistryCompactionCallback {
1980 static void Callback(Object* value, int old_index, int new_index);
1983 // Retrieve interceptors.
1984 InterceptorInfo* GetNamedInterceptor();
1985 InterceptorInfo* GetIndexedInterceptor();
1987 // Used from JSReceiver.
1988 MUST_USE_RESULT static Maybe<PropertyAttributes>
1989 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1990 MUST_USE_RESULT static Maybe<PropertyAttributes>
1991 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1993 // Retrieves an AccessorPair property from the given object. Might return
1994 // undefined if the property doesn't exist or is of a different kind.
1995 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1996 Handle<JSObject> object,
1998 AccessorComponent component);
2000 // Defines an AccessorPair property on the given object.
2001 // TODO(mstarzinger): Rename to SetAccessor().
2002 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2004 Handle<Object> getter,
2005 Handle<Object> setter,
2006 PropertyAttributes attributes);
2008 // Defines an AccessorInfo property on the given object.
2009 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2010 Handle<JSObject> object,
2011 Handle<AccessorInfo> info);
2013 // The result must be checked first for exceptions. If there's no exception,
2014 // the output parameter |done| indicates whether the interceptor has a result
2016 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2017 LookupIterator* it, bool* done);
2019 // Accessors for hidden properties object.
2021 // Hidden properties are not own properties of the object itself.
2022 // Instead they are stored in an auxiliary structure kept as an own
2023 // property with a special name Heap::hidden_string(). But if the
2024 // receiver is a JSGlobalProxy then the auxiliary object is a property
2025 // of its prototype, and if it's a detached proxy, then you can't have
2026 // hidden properties.
2028 // Sets a hidden property on this object. Returns this object if successful,
2029 // undefined if called on a detached proxy.
2030 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2032 Handle<Object> value);
2033 // Gets the value of a hidden property with the given key. Returns the hole
2034 // if the property doesn't exist (or if called on a detached proxy),
2035 // otherwise returns the value set for the key.
2036 Object* GetHiddenProperty(Handle<Name> key);
2037 // Deletes a hidden property. Deleting a non-existing property is
2038 // considered successful.
2039 static void DeleteHiddenProperty(Handle<JSObject> object,
2041 // Returns true if the object has a property with the hidden string as name.
2042 static bool HasHiddenProperties(Handle<JSObject> object);
2044 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2046 static void ValidateElements(Handle<JSObject> object);
2048 // Makes sure that this object can contain HeapObject as elements.
2049 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2051 // Makes sure that this object can contain the specified elements.
2052 static inline void EnsureCanContainElements(
2053 Handle<JSObject> object,
2056 EnsureElementsMode mode);
2057 static inline void EnsureCanContainElements(
2058 Handle<JSObject> object,
2059 Handle<FixedArrayBase> elements,
2061 EnsureElementsMode mode);
2062 static void EnsureCanContainElements(
2063 Handle<JSObject> object,
2064 Arguments* arguments,
2067 EnsureElementsMode mode);
2069 // Would we convert a fast elements array to dictionary mode given
2070 // an access at key?
2071 bool WouldConvertToSlowElements(uint32_t index);
2073 // Computes the new capacity when expanding the elements of a JSObject.
2074 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2075 // (old_capacity + 50%) + 16
2076 return old_capacity + (old_capacity >> 1) + 16;
2079 // These methods do not perform access checks!
2080 static void UpdateAllocationSite(Handle<JSObject> object,
2081 ElementsKind to_kind);
2083 // Lookup interceptors are used for handling properties controlled by host
2085 inline bool HasNamedInterceptor();
2086 inline bool HasIndexedInterceptor();
2088 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2089 // by JSReceiver::GetKeys.
2090 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2091 Handle<JSObject> object,
2092 Handle<JSReceiver> receiver);
2093 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2094 Handle<JSObject> object,
2095 Handle<JSReceiver> receiver);
2097 // Support functions for v8 api (needed for correct interceptor behavior).
2098 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2099 Handle<JSObject> object, Handle<Name> name);
2100 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2101 Handle<JSObject> object, uint32_t index);
2102 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2103 Handle<JSObject> object, Handle<Name> name);
2105 // Get the header size for a JSObject. Used to compute the index of
2106 // internal fields as well as the number of internal fields.
2107 inline int GetHeaderSize();
2109 inline int GetInternalFieldCount();
2110 inline int GetInternalFieldOffset(int index);
2111 inline Object* GetInternalField(int index);
2112 inline void SetInternalField(int index, Object* value);
2113 inline void SetInternalField(int index, Smi* value);
2115 // Returns the number of properties on this object filtering out properties
2116 // with the specified attributes (ignoring interceptors).
2117 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2118 // Fill in details for properties into storage starting at the specified
2119 // index. Returns the number of properties added.
2120 int GetOwnPropertyNames(FixedArray* storage, int index,
2121 PropertyAttributes filter = NONE);
2123 // Returns the number of properties on this object filtering out properties
2124 // with the specified attributes (ignoring interceptors).
2125 int NumberOfOwnElements(PropertyAttributes filter);
2126 // Returns the number of enumerable elements (ignoring interceptors).
2127 int NumberOfEnumElements();
2128 // Returns the number of elements on this object filtering out elements
2129 // with the specified attributes (ignoring interceptors).
2130 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2131 // Count and fill in the enumerable elements into storage.
2132 // (storage->length() == NumberOfEnumElements()).
2133 // If storage is NULL, will count the elements without adding
2134 // them to any storage.
2135 // Returns the number of enumerable elements.
2136 int GetEnumElementKeys(FixedArray* storage);
2138 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2141 // Returns a new map with all transitions dropped from the object's current
2142 // map and the ElementsKind set.
2143 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2144 ElementsKind to_kind);
2145 static void TransitionElementsKind(Handle<JSObject> object,
2146 ElementsKind to_kind);
2148 // Always use this to migrate an object to a new map.
2149 // |expected_additional_properties| is only used for fast-to-slow transitions
2150 // and ignored otherwise.
2151 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2152 int expected_additional_properties = 0);
2154 // Convert the object to use the canonical dictionary
2155 // representation. If the object is expected to have additional properties
2156 // added this number can be indicated to have the backing store allocated to
2157 // an initial capacity for holding these properties.
2158 static void NormalizeProperties(Handle<JSObject> object,
2159 PropertyNormalizationMode mode,
2160 int expected_additional_properties,
2161 const char* reason);
2163 // Convert and update the elements backing store to be a
2164 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2165 static Handle<SeededNumberDictionary> NormalizeElements(
2166 Handle<JSObject> object);
2168 void RequireSlowElements(SeededNumberDictionary* dictionary);
2170 // Transform slow named properties to fast variants.
2171 static void MigrateSlowToFast(Handle<JSObject> object,
2172 int unused_property_fields, const char* reason);
2174 inline bool IsUnboxedDoubleField(FieldIndex index);
2176 // Access fast-case object properties at index.
2177 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2178 Representation representation,
2180 inline Object* RawFastPropertyAt(FieldIndex index);
2181 inline double RawFastDoublePropertyAt(FieldIndex index);
2183 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2184 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2185 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2186 inline void WriteToField(int descriptor, Object* value);
2188 // Access to in object properties.
2189 inline int GetInObjectPropertyOffset(int index);
2190 inline Object* InObjectPropertyAt(int index);
2191 inline Object* InObjectPropertyAtPut(int index,
2193 WriteBarrierMode mode
2194 = UPDATE_WRITE_BARRIER);
2196 // Set the object's prototype (only JSReceiver and null are allowed values).
2197 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2198 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2200 // Initializes the body after properties slot, properties slot is
2201 // initialized by set_properties. Fill the pre-allocated fields with
2202 // pre_allocated_value and the rest with filler_value.
2203 // Note: this call does not update write barrier, the caller is responsible
2204 // to ensure that |filler_value| can be collected without WB here.
2205 inline void InitializeBody(Map* map,
2206 Object* pre_allocated_value,
2207 Object* filler_value);
2209 // Check whether this object references another object
2210 bool ReferencesObject(Object* obj);
2212 // Disalow further properties to be added to the oject.
2213 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2214 Handle<JSObject> object);
2216 bool IsExtensible();
2219 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2221 // ES5 Object.freeze
2222 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2224 // Called the first time an object is observed with ES7 Object.observe.
2225 static void SetObserved(Handle<JSObject> object);
2228 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2230 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2231 Handle<JSObject> object,
2232 AllocationSiteUsageContext* site_context,
2233 DeepCopyHints hints = kNoHints);
2234 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2235 Handle<JSObject> object,
2236 AllocationSiteCreationContext* site_context);
2238 DECLARE_CAST(JSObject)
2240 // Dispatched behavior.
2241 void JSObjectShortPrint(StringStream* accumulator);
2242 DECLARE_PRINTER(JSObject)
2243 DECLARE_VERIFIER(JSObject)
2245 void PrintProperties(std::ostream& os); // NOLINT
2246 void PrintElements(std::ostream& os); // NOLINT
2248 #if defined(DEBUG) || defined(OBJECT_PRINT)
2249 void PrintTransitions(std::ostream& os); // NOLINT
2252 static void PrintElementsTransition(
2253 FILE* file, Handle<JSObject> object,
2254 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2255 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2257 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2260 // Structure for collecting spill information about JSObjects.
2261 class SpillInformation {
2265 int number_of_objects_;
2266 int number_of_objects_with_fast_properties_;
2267 int number_of_objects_with_fast_elements_;
2268 int number_of_fast_used_fields_;
2269 int number_of_fast_unused_fields_;
2270 int number_of_slow_used_properties_;
2271 int number_of_slow_unused_properties_;
2272 int number_of_fast_used_elements_;
2273 int number_of_fast_unused_elements_;
2274 int number_of_slow_used_elements_;
2275 int number_of_slow_unused_elements_;
2278 void IncrementSpillStatistics(SpillInformation* info);
2282 // If a GC was caused while constructing this object, the elements pointer
2283 // may point to a one pointer filler map. The object won't be rooted, but
2284 // our heap verification code could stumble across it.
2285 bool ElementsAreSafeToExamine();
2288 Object* SlowReverseLookup(Object* value);
2290 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2291 // Also maximal value of JSArray's length property.
2292 static const uint32_t kMaxElementCount = 0xffffffffu;
2294 // Constants for heuristics controlling conversion of fast elements
2295 // to slow elements.
2297 // Maximal gap that can be introduced by adding an element beyond
2298 // the current elements length.
2299 static const uint32_t kMaxGap = 1024;
2301 // Maximal length of fast elements array that won't be checked for
2302 // being dense enough on expansion.
2303 static const int kMaxUncheckedFastElementsLength = 5000;
2305 // Same as above but for old arrays. This limit is more strict. We
2306 // don't want to be wasteful with long lived objects.
2307 static const int kMaxUncheckedOldFastElementsLength = 500;
2309 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2310 // permissible values (see the DCHECK in heap.cc).
2311 static const int kInitialMaxFastElementArray = 100000;
2313 // This constant applies only to the initial map of "global.Object" and
2314 // not to arbitrary other JSObject maps.
2315 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2317 static const int kMaxInstanceSize = 255 * kPointerSize;
2318 // When extending the backing storage for property values, we increase
2319 // its size by more than the 1 entry necessary, so sequentially adding fields
2320 // to the same object requires fewer allocations and copies.
2321 static const int kFieldsAdded = 3;
2323 // Layout description.
2324 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2325 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2326 static const int kHeaderSize = kElementsOffset + kPointerSize;
2328 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2330 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2332 static inline int SizeOf(Map* map, HeapObject* object);
2335 Context* GetCreationContext();
2337 // Enqueue change record for Object.observe. May cause GC.
2338 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2339 Handle<JSObject> object, const char* type, Handle<Name> name,
2340 Handle<Object> old_value);
2342 // Gets the number of currently used elements.
2343 int GetFastElementsUsage();
2345 // Deletes an existing named property in a normalized object.
2346 static void DeleteNormalizedProperty(Handle<JSObject> object,
2347 Handle<Name> name, int entry);
2349 static bool AllCanRead(LookupIterator* it);
2350 static bool AllCanWrite(LookupIterator* it);
2353 friend class JSReceiver;
2354 friend class Object;
2356 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2357 static void MigrateFastToSlow(Handle<JSObject> object,
2358 Handle<Map> new_map,
2359 int expected_additional_properties);
2361 // Used from Object::GetProperty().
2362 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2363 LookupIterator* it);
2365 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2366 LookupIterator* it, Handle<Object> value);
2368 // Add a property to a slow-case object.
2369 static void AddSlowProperty(Handle<JSObject> object,
2371 Handle<Object> value,
2372 PropertyAttributes attributes);
2374 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2375 LookupIterator* it);
2377 bool ReferencesObjectFromElements(FixedArray* elements,
2381 // Return the hash table backing store or the inline stored identity hash,
2382 // whatever is found.
2383 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2385 // Return the hash table backing store for hidden properties. If there is no
2386 // backing store, allocate one.
2387 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2388 Handle<JSObject> object);
2390 // Set the hidden property backing store to either a hash table or
2391 // the inline-stored identity hash.
2392 static Handle<Object> SetHiddenPropertiesHashTable(
2393 Handle<JSObject> object,
2394 Handle<Object> value);
2396 MUST_USE_RESULT Object* GetIdentityHash();
2398 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2400 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2401 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2403 // Helper for fast versions of preventExtensions, seal, and freeze.
2404 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2405 template <PropertyAttributes attrs>
2406 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2407 Handle<JSObject> object);
2409 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2413 // Common superclass for FixedArrays that allow implementations to share
2414 // common accessors and some code paths.
2415 class FixedArrayBase: public HeapObject {
2417 // [length]: length of the array.
2418 inline int length() const;
2419 inline void set_length(int value);
2421 // Get and set the length using acquire loads and release stores.
2422 inline int synchronized_length() const;
2423 inline void synchronized_set_length(int value);
2425 DECLARE_CAST(FixedArrayBase)
2427 // Layout description.
2428 // Length is smi tagged when it is stored.
2429 static const int kLengthOffset = HeapObject::kHeaderSize;
2430 static const int kHeaderSize = kLengthOffset + kPointerSize;
2434 class FixedDoubleArray;
2435 class IncrementalMarking;
2438 // FixedArray describes fixed-sized arrays with element type Object*.
2439 class FixedArray: public FixedArrayBase {
2441 // Setter and getter for elements.
2442 inline Object* get(int index) const;
2443 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2444 // Setter that uses write barrier.
2445 inline void set(int index, Object* value);
2446 inline bool is_the_hole(int index);
2448 // Setter that doesn't need write barrier.
2449 inline void set(int index, Smi* value);
2450 // Setter with explicit barrier mode.
2451 inline void set(int index, Object* value, WriteBarrierMode mode);
2453 // Setters for frequently used oddballs located in old space.
2454 inline void set_undefined(int index);
2455 inline void set_null(int index);
2456 inline void set_the_hole(int index);
2458 inline Object** GetFirstElementAddress();
2459 inline bool ContainsOnlySmisOrHoles();
2461 // Gives access to raw memory which stores the array's data.
2462 inline Object** data_start();
2464 inline void FillWithHoles(int from, int to);
2466 // Shrink length and insert filler objects.
2467 void Shrink(int length);
2469 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2471 // Add the elements of a JSArray to this FixedArray.
2472 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2473 Handle<FixedArray> content, Handle<JSObject> array,
2474 KeyFilter filter = ALL_KEYS);
2476 // Computes the union of keys and return the result.
2477 // Used for implementing "for (n in object) { }"
2478 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2479 Handle<FixedArray> first,
2480 Handle<FixedArray> second);
2482 // Copy a sub array from the receiver to dest.
2483 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2485 // Garbage collection support.
2486 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2488 // Code Generation support.
2489 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2491 // Garbage collection support.
2492 inline Object** RawFieldOfElementAt(int index);
2494 DECLARE_CAST(FixedArray)
2496 // Maximal allowed size, in bytes, of a single FixedArray.
2497 // Prevents overflowing size computations, as well as extreme memory
2499 static const int kMaxSize = 128 * MB * kPointerSize;
2500 // Maximally allowed length of a FixedArray.
2501 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2503 // Dispatched behavior.
2504 DECLARE_PRINTER(FixedArray)
2505 DECLARE_VERIFIER(FixedArray)
2507 // Checks if two FixedArrays have identical contents.
2508 bool IsEqualTo(FixedArray* other);
2511 // Swap two elements in a pair of arrays. If this array and the
2512 // numbers array are the same object, the elements are only swapped
2514 void SwapPairs(FixedArray* numbers, int i, int j);
2516 // Sort prefix of this array and the numbers array as pairs wrt. the
2517 // numbers. If the numbers array and the this array are the same
2518 // object, the prefix of this array is sorted.
2519 void SortPairs(FixedArray* numbers, uint32_t len);
2521 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2523 static inline int SizeOf(Map* map, HeapObject* object);
2527 // Set operation on FixedArray without using write barriers. Can
2528 // only be used for storing old space objects or smis.
2529 static inline void NoWriteBarrierSet(FixedArray* array,
2533 // Set operation on FixedArray without incremental write barrier. Can
2534 // only be used if the object is guaranteed to be white (whiteness witness
2536 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2541 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2543 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2547 // FixedDoubleArray describes fixed-sized arrays with element type double.
2548 class FixedDoubleArray: public FixedArrayBase {
2550 // Setter and getter for elements.
2551 inline double get_scalar(int index);
2552 inline uint64_t get_representation(int index);
2553 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2554 inline void set(int index, double value);
2555 inline void set_the_hole(int index);
2557 // Checking for the hole.
2558 inline bool is_the_hole(int index);
2560 // Garbage collection support.
2561 inline static int SizeFor(int length) {
2562 return kHeaderSize + length * kDoubleSize;
2565 // Gives access to raw memory which stores the array's data.
2566 inline double* data_start();
2568 inline void FillWithHoles(int from, int to);
2570 // Code Generation support.
2571 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2573 DECLARE_CAST(FixedDoubleArray)
2575 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2576 // Prevents overflowing size computations, as well as extreme memory
2578 static const int kMaxSize = 512 * MB;
2579 // Maximally allowed length of a FixedArray.
2580 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2582 // Dispatched behavior.
2583 DECLARE_PRINTER(FixedDoubleArray)
2584 DECLARE_VERIFIER(FixedDoubleArray)
2587 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2591 class WeakFixedArray : public FixedArray {
2593 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2594 // This function does not check if the value exists already, callers must
2595 // ensure this themselves if necessary.
2596 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2597 Handle<HeapObject> value,
2598 int* assigned_index = NULL);
2600 // Returns true if an entry was found and removed.
2601 bool Remove(Handle<HeapObject> value);
2603 class NullCallback {
2605 static void Callback(Object* value, int old_index, int new_index) {}
2608 template <class CompactionCallback>
2611 inline Object* Get(int index) const;
2612 inline void Clear(int index);
2613 inline int Length() const;
2615 inline bool IsEmptySlot(int index) const;
2616 static Object* Empty() { return Smi::FromInt(0); }
2620 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2621 void Reset(Object* maybe_array);
2628 WeakFixedArray* list_;
2630 int last_used_index_;
2631 DisallowHeapAllocation no_gc_;
2633 DISALLOW_COPY_AND_ASSIGN(Iterator);
2636 DECLARE_CAST(WeakFixedArray)
2639 static const int kLastUsedIndexIndex = 0;
2640 static const int kFirstIndex = 1;
2642 static Handle<WeakFixedArray> Allocate(
2643 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2645 static void Set(Handle<WeakFixedArray> array, int index,
2646 Handle<HeapObject> value);
2647 inline void clear(int index);
2649 inline int last_used_index() const;
2650 inline void set_last_used_index(int index);
2652 // Disallow inherited setters.
2653 void set(int index, Smi* value);
2654 void set(int index, Object* value);
2655 void set(int index, Object* value, WriteBarrierMode mode);
2656 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2660 // Generic array grows dynamically with O(1) amortized insertion.
2661 class ArrayList : public FixedArray {
2665 // Use this if GC can delete elements from the array.
2666 kReloadLengthAfterAllocation,
2668 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2669 AddMode mode = kNone);
2670 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2671 Handle<Object> obj2, AddMode = kNone);
2672 inline int Length();
2673 inline void SetLength(int length);
2674 inline Object* Get(int index);
2675 inline Object** Slot(int index);
2676 inline void Set(int index, Object* obj);
2677 inline void Clear(int index, Object* undefined);
2678 DECLARE_CAST(ArrayList)
2681 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2682 static const int kLengthIndex = 0;
2683 static const int kFirstIndex = 1;
2684 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2688 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2689 // The format of the these objects is:
2690 // [0]: Number of descriptors
2691 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2692 // [0]: pointer to fixed array with enum cache
2693 // [1]: either Smi(0) or pointer to fixed array with indices
2695 // [2 + number of descriptors * kDescriptorSize]: start of slack
2696 class DescriptorArray: public FixedArray {
2698 // Returns true for both shared empty_descriptor_array and for smis, which the
2699 // map uses to encode additional bit fields when the descriptor array is not
2701 inline bool IsEmpty();
2703 // Returns the number of descriptors in the array.
2704 inline int number_of_descriptors();
2706 inline int number_of_descriptors_storage();
2708 inline int NumberOfSlackDescriptors();
2710 inline void SetNumberOfDescriptors(int number_of_descriptors);
2711 inline int number_of_entries();
2713 inline bool HasEnumCache();
2715 inline void CopyEnumCacheFrom(DescriptorArray* array);
2717 inline FixedArray* GetEnumCache();
2719 inline bool HasEnumIndicesCache();
2721 inline FixedArray* GetEnumIndicesCache();
2723 inline Object** GetEnumCacheSlot();
2725 void ClearEnumCache();
2727 // Initialize or change the enum cache,
2728 // using the supplied storage for the small "bridge".
2729 void SetEnumCache(FixedArray* bridge_storage,
2730 FixedArray* new_cache,
2731 Object* new_index_cache);
2733 bool CanHoldValue(int descriptor, Object* value);
2735 // Accessors for fetching instance descriptor at descriptor number.
2736 inline Name* GetKey(int descriptor_number);
2737 inline Object** GetKeySlot(int descriptor_number);
2738 inline Object* GetValue(int descriptor_number);
2739 inline void SetValue(int descriptor_number, Object* value);
2740 inline Object** GetValueSlot(int descriptor_number);
2741 static inline int GetValueOffset(int descriptor_number);
2742 inline Object** GetDescriptorStartSlot(int descriptor_number);
2743 inline Object** GetDescriptorEndSlot(int descriptor_number);
2744 inline PropertyDetails GetDetails(int descriptor_number);
2745 inline PropertyType GetType(int descriptor_number);
2746 inline int GetFieldIndex(int descriptor_number);
2747 inline HeapType* GetFieldType(int descriptor_number);
2748 inline Object* GetConstant(int descriptor_number);
2749 inline Object* GetCallbacksObject(int descriptor_number);
2750 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2752 inline Name* GetSortedKey(int descriptor_number);
2753 inline int GetSortedKeyIndex(int descriptor_number);
2754 inline void SetSortedKey(int pointer, int descriptor_number);
2755 inline void SetRepresentation(int descriptor_number,
2756 Representation representation);
2758 // Accessor for complete descriptor.
2759 inline void Get(int descriptor_number, Descriptor* desc);
2760 inline void Set(int descriptor_number, Descriptor* desc);
2761 void Replace(int descriptor_number, Descriptor* descriptor);
2763 // Append automatically sets the enumeration index. This should only be used
2764 // to add descriptors in bulk at the end, followed by sorting the descriptor
2766 inline void Append(Descriptor* desc);
2768 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2769 int enumeration_index,
2772 static Handle<DescriptorArray> CopyUpToAddAttributes(
2773 Handle<DescriptorArray> desc,
2774 int enumeration_index,
2775 PropertyAttributes attributes,
2778 // Sort the instance descriptors by the hash codes of their keys.
2781 // Search the instance descriptors for given name.
2782 INLINE(int Search(Name* name, int number_of_own_descriptors));
2784 // As the above, but uses DescriptorLookupCache and updates it when
2786 INLINE(int SearchWithCache(Name* name, Map* map));
2788 // Allocates a DescriptorArray, but returns the singleton
2789 // empty descriptor array object if number_of_descriptors is 0.
2790 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2791 int number_of_descriptors,
2794 DECLARE_CAST(DescriptorArray)
2796 // Constant for denoting key was not found.
2797 static const int kNotFound = -1;
2799 static const int kDescriptorLengthIndex = 0;
2800 static const int kEnumCacheIndex = 1;
2801 static const int kFirstIndex = 2;
2803 // The length of the "bridge" to the enum cache.
2804 static const int kEnumCacheBridgeLength = 2;
2805 static const int kEnumCacheBridgeCacheIndex = 0;
2806 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2808 // Layout description.
2809 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2810 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2811 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2813 // Layout description for the bridge array.
2814 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2816 // Layout of descriptor.
2817 static const int kDescriptorKey = 0;
2818 static const int kDescriptorDetails = 1;
2819 static const int kDescriptorValue = 2;
2820 static const int kDescriptorSize = 3;
2822 #if defined(DEBUG) || defined(OBJECT_PRINT)
2823 // For our gdb macros, we should perhaps change these in the future.
2826 // Print all the descriptors.
2827 void PrintDescriptors(std::ostream& os); // NOLINT
2831 // Is the descriptor array sorted and without duplicates?
2832 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2834 // Is the descriptor array consistent with the back pointers in targets?
2835 bool IsConsistentWithBackPointers(Map* current_map);
2837 // Are two DescriptorArrays equal?
2838 bool IsEqualTo(DescriptorArray* other);
2841 // Returns the fixed array length required to hold number_of_descriptors
2843 static int LengthFor(int number_of_descriptors) {
2844 return ToKeyIndex(number_of_descriptors);
2848 // WhitenessWitness is used to prove that a descriptor array is white
2849 // (unmarked), so incremental write barriers can be skipped because the
2850 // marking invariant cannot be broken and slots pointing into evacuation
2851 // candidates will be discovered when the object is scanned. A witness is
2852 // always stack-allocated right after creating an array. By allocating a
2853 // witness, incremental marking is globally disabled. The witness is then
2854 // passed along wherever needed to statically prove that the array is known to
2856 class WhitenessWitness {
2858 inline explicit WhitenessWitness(DescriptorArray* array);
2859 inline ~WhitenessWitness();
2862 IncrementalMarking* marking_;
2865 // An entry in a DescriptorArray, represented as an (array, index) pair.
2868 inline explicit Entry(DescriptorArray* descs, int index) :
2869 descs_(descs), index_(index) { }
2871 inline PropertyType type();
2872 inline Object* GetCallbackObject();
2875 DescriptorArray* descs_;
2879 // Conversion from descriptor number to array indices.
2880 static int ToKeyIndex(int descriptor_number) {
2881 return kFirstIndex +
2882 (descriptor_number * kDescriptorSize) +
2886 static int ToDetailsIndex(int descriptor_number) {
2887 return kFirstIndex +
2888 (descriptor_number * kDescriptorSize) +
2892 static int ToValueIndex(int descriptor_number) {
2893 return kFirstIndex +
2894 (descriptor_number * kDescriptorSize) +
2898 // Transfer a complete descriptor from the src descriptor array to this
2899 // descriptor array.
2900 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2902 inline void Set(int descriptor_number,
2904 const WhitenessWitness&);
2906 // Swap first and second descriptor.
2907 inline void SwapSortedKeys(int first, int second);
2909 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2913 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2915 template <SearchMode search_mode, typename T>
2916 inline int Search(T* array, Name* name, int valid_entries = 0,
2917 int* out_insertion_index = NULL);
2920 // HashTable is a subclass of FixedArray that implements a hash table
2921 // that uses open addressing and quadratic probing.
2923 // In order for the quadratic probing to work, elements that have not
2924 // yet been used and elements that have been deleted are
2925 // distinguished. Probing continues when deleted elements are
2926 // encountered and stops when unused elements are encountered.
2928 // - Elements with key == undefined have not been used yet.
2929 // - Elements with key == the_hole have been deleted.
2931 // The hash table class is parameterized with a Shape and a Key.
2932 // Shape must be a class with the following interface:
2933 // class ExampleShape {
2935 // // Tells whether key matches other.
2936 // static bool IsMatch(Key key, Object* other);
2937 // // Returns the hash value for key.
2938 // static uint32_t Hash(Key key);
2939 // // Returns the hash value for object.
2940 // static uint32_t HashForObject(Key key, Object* object);
2941 // // Convert key to an object.
2942 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2943 // // The prefix size indicates number of elements in the beginning
2944 // // of the backing storage.
2945 // static const int kPrefixSize = ..;
2946 // // The Element size indicates number of elements per entry.
2947 // static const int kEntrySize = ..;
2949 // The prefix size indicates an amount of memory in the
2950 // beginning of the backing storage that can be used for non-element
2951 // information by subclasses.
2953 template<typename Key>
2956 static const bool UsesSeed = false;
2957 static uint32_t Hash(Key key) { return 0; }
2958 static uint32_t SeededHash(Key key, uint32_t seed) {
2962 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2963 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2965 return HashForObject(key, object);
2970 class HashTableBase : public FixedArray {
2972 // Returns the number of elements in the hash table.
2973 inline int NumberOfElements();
2975 // Returns the number of deleted elements in the hash table.
2976 inline int NumberOfDeletedElements();
2978 // Returns the capacity of the hash table.
2979 inline int Capacity();
2981 // ElementAdded should be called whenever an element is added to a
2983 inline void ElementAdded();
2985 // ElementRemoved should be called whenever an element is removed from
2987 inline void ElementRemoved();
2988 inline void ElementsRemoved(int n);
2990 // Computes the required capacity for a table holding the given
2991 // number of elements. May be more than HashTable::kMaxCapacity.
2992 static inline int ComputeCapacity(int at_least_space_for);
2994 // Tells whether k is a real key. The hole and undefined are not allowed
2995 // as keys and can be used to indicate missing or deleted elements.
2996 inline bool IsKey(Object* k);
2998 // Compute the probe offset (quadratic probing).
2999 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3000 return (n + n * n) >> 1;
3003 static const int kNumberOfElementsIndex = 0;
3004 static const int kNumberOfDeletedElementsIndex = 1;
3005 static const int kCapacityIndex = 2;
3006 static const int kPrefixStartIndex = 3;
3008 // Constant used for denoting a absent entry.
3009 static const int kNotFound = -1;
3012 // Update the number of elements in the hash table.
3013 inline void SetNumberOfElements(int nof);
3015 // Update the number of deleted elements in the hash table.
3016 inline void SetNumberOfDeletedElements(int nod);
3018 // Returns probe entry.
3019 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3020 DCHECK(base::bits::IsPowerOfTwo32(size));
3021 return (hash + GetProbeOffset(number)) & (size - 1);
3024 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3025 return hash & (size - 1);
3028 inline static uint32_t NextProbe(
3029 uint32_t last, uint32_t number, uint32_t size) {
3030 return (last + number) & (size - 1);
3035 template <typename Derived, typename Shape, typename Key>
3036 class HashTable : public HashTableBase {
3039 inline uint32_t Hash(Key key) {
3040 if (Shape::UsesSeed) {
3041 return Shape::SeededHash(key, GetHeap()->HashSeed());
3043 return Shape::Hash(key);
3047 inline uint32_t HashForObject(Key key, Object* object) {
3048 if (Shape::UsesSeed) {
3049 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3051 return Shape::HashForObject(key, object);
3055 // Returns a new HashTable object.
3056 MUST_USE_RESULT static Handle<Derived> New(
3057 Isolate* isolate, int at_least_space_for,
3058 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3059 PretenureFlag pretenure = NOT_TENURED);
3061 DECLARE_CAST(HashTable)
3063 // Garbage collection support.
3064 void IteratePrefix(ObjectVisitor* visitor);
3065 void IterateElements(ObjectVisitor* visitor);
3067 // Find entry for key otherwise return kNotFound.
3068 inline int FindEntry(Key key);
3069 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3070 int FindEntry(Isolate* isolate, Key key);
3072 // Rehashes the table in-place.
3073 void Rehash(Key key);
3075 // Returns the key at entry.
3076 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3078 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3079 static const int kEntrySize = Shape::kEntrySize;
3080 static const int kElementsStartOffset =
3081 kHeaderSize + kElementsStartIndex * kPointerSize;
3082 static const int kCapacityOffset =
3083 kHeaderSize + kCapacityIndex * kPointerSize;
3085 // Returns the index for an entry (of the key)
3086 static inline int EntryToIndex(int entry) {
3087 return (entry * kEntrySize) + kElementsStartIndex;
3091 friend class ObjectHashTable;
3093 // Find the entry at which to insert element with the given key that
3094 // has the given hash value.
3095 uint32_t FindInsertionEntry(uint32_t hash);
3097 // Attempt to shrink hash table after removal of key.
3098 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3100 // Ensure enough space for n additional elements.
3101 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3102 Handle<Derived> table,
3105 PretenureFlag pretenure = NOT_TENURED);
3107 // Sets the capacity of the hash table.
3108 void SetCapacity(int capacity) {
3109 // To scale a computed hash code to fit within the hash table, we
3110 // use bit-wise AND with a mask, so the capacity must be positive
3112 DCHECK(capacity > 0);
3113 DCHECK(capacity <= kMaxCapacity);
3114 set(kCapacityIndex, Smi::FromInt(capacity));
3117 // Maximal capacity of HashTable. Based on maximal length of underlying
3118 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3120 static const int kMaxCapacity =
3121 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3124 // Returns _expected_ if one of entries given by the first _probe_ probes is
3125 // equal to _expected_. Otherwise, returns the entry given by the probe
3127 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3129 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3131 // Rehashes this hash-table into the new table.
3132 void Rehash(Handle<Derived> new_table, Key key);
3136 // HashTableKey is an abstract superclass for virtual key behavior.
3137 class HashTableKey {
3139 // Returns whether the other object matches this key.
3140 virtual bool IsMatch(Object* other) = 0;
3141 // Returns the hash value for this key.
3142 virtual uint32_t Hash() = 0;
3143 // Returns the hash value for object.
3144 virtual uint32_t HashForObject(Object* key) = 0;
3145 // Returns the key object for storing into the hash table.
3146 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3148 virtual ~HashTableKey() {}
3152 class StringTableShape : public BaseShape<HashTableKey*> {
3154 static inline bool IsMatch(HashTableKey* key, Object* value) {
3155 return key->IsMatch(value);
3158 static inline uint32_t Hash(HashTableKey* key) {
3162 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3163 return key->HashForObject(object);
3166 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3168 static const int kPrefixSize = 0;
3169 static const int kEntrySize = 1;
3172 class SeqOneByteString;
3176 // No special elements in the prefix and the element size is 1
3177 // because only the string itself (the key) needs to be stored.
3178 class StringTable: public HashTable<StringTable,
3182 // Find string in the string table. If it is not there yet, it is
3183 // added. The return value is the string found.
3184 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3185 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3186 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3188 // Tries to internalize given string and returns string handle on success
3189 // or an empty handle otherwise.
3190 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3192 Handle<String> string);
3194 // Looks up a string that is equal to the given string and returns
3195 // string handle if it is found, or an empty handle otherwise.
3196 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3198 Handle<String> str);
3199 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3204 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3206 DECLARE_CAST(StringTable)
3209 template <bool seq_one_byte>
3210 friend class JsonParser;
3212 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3216 template <typename Derived, typename Shape, typename Key>
3217 class Dictionary: public HashTable<Derived, Shape, Key> {
3218 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3221 // Returns the value at entry.
3222 Object* ValueAt(int entry) {
3223 return this->get(Derived::EntryToIndex(entry) + 1);
3226 // Set the value for entry.
3227 void ValueAtPut(int entry, Object* value) {
3228 this->set(Derived::EntryToIndex(entry) + 1, value);
3231 // Returns the property details for the property at entry.
3232 PropertyDetails DetailsAt(int entry) {
3233 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3236 // Set the details for entry.
3237 void DetailsAtPut(int entry, PropertyDetails value) {
3238 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3241 // Returns true if property at given entry is deleted.
3242 bool IsDeleted(int entry) {
3243 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3246 // Delete a property from the dictionary.
3247 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3249 // Attempt to shrink the dictionary after deletion of key.
3250 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3251 Handle<Derived> dictionary,
3253 return DerivedHashTable::Shrink(dictionary, key);
3257 // TODO(dcarney): templatize or move to SeededNumberDictionary
3258 void CopyValuesTo(FixedArray* elements);
3260 // Returns the number of elements in the dictionary filtering out properties
3261 // with the specified attributes.
3262 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3264 // Returns the number of enumerable elements in the dictionary.
3265 int NumberOfEnumElements() {
3266 return NumberOfElementsFilterAttributes(
3267 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3270 // Returns true if the dictionary contains any elements that are non-writable,
3271 // non-configurable, non-enumerable, or have getters/setters.
3272 bool HasComplexElements();
3274 enum SortMode { UNSORTED, SORTED };
3276 // Fill in details for properties into storage.
3277 // Returns the number of properties added.
3278 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3279 SortMode sort_mode);
3281 // Copies enumerable keys to preallocated fixed array.
3282 void CopyEnumKeysTo(FixedArray* storage);
3284 // Accessors for next enumeration index.
3285 void SetNextEnumerationIndex(int index) {
3287 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3290 int NextEnumerationIndex() {
3291 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3294 // Creates a new dictionary.
3295 MUST_USE_RESULT static Handle<Derived> New(
3297 int at_least_space_for,
3298 PretenureFlag pretenure = NOT_TENURED);
3300 // Ensure enough space for n additional elements.
3301 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3304 void Print(std::ostream& os); // NOLINT
3306 // Returns the key (slow).
3307 Object* SlowReverseLookup(Object* value);
3309 // Sets the entry to (key, value) pair.
3310 inline void SetEntry(int entry,
3312 Handle<Object> value);
3313 inline void SetEntry(int entry,
3315 Handle<Object> value,
3316 PropertyDetails details);
3318 MUST_USE_RESULT static Handle<Derived> Add(
3319 Handle<Derived> dictionary,
3321 Handle<Object> value,
3322 PropertyDetails details);
3324 // Returns iteration indices array for the |dictionary|.
3325 // Values are direct indices in the |HashTable| array.
3326 static Handle<FixedArray> BuildIterationIndicesArray(
3327 Handle<Derived> dictionary);
3330 // Generic at put operation.
3331 MUST_USE_RESULT static Handle<Derived> AtPut(
3332 Handle<Derived> dictionary,
3334 Handle<Object> value);
3336 // Add entry to dictionary.
3337 static void AddEntry(
3338 Handle<Derived> dictionary,
3340 Handle<Object> value,
3341 PropertyDetails details,
3344 // Generate new enumeration indices to avoid enumeration index overflow.
3345 // Returns iteration indices array for the |dictionary|.
3346 static Handle<FixedArray> GenerateNewEnumerationIndices(
3347 Handle<Derived> dictionary);
3348 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3349 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3353 template <typename Derived, typename Shape>
3354 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3355 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3358 // Find entry for key, otherwise return kNotFound. Optimized version of
3359 // HashTable::FindEntry.
3360 int FindEntry(Handle<Name> key);
3364 template <typename Key>
3365 class BaseDictionaryShape : public BaseShape<Key> {
3367 template <typename Dictionary>
3368 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3369 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3370 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3371 return PropertyDetails(
3372 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3375 template <typename Dictionary>
3376 static inline void DetailsAtPut(Dictionary* dict, int entry,
3377 PropertyDetails value) {
3378 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3379 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3382 template <typename Dictionary>
3383 static bool IsDeleted(Dictionary* dict, int entry) {
3387 template <typename Dictionary>
3388 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3389 Handle<Object> value, PropertyDetails details);
3393 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3395 static inline bool IsMatch(Handle<Name> key, Object* other);
3396 static inline uint32_t Hash(Handle<Name> key);
3397 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3398 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3399 static const int kPrefixSize = 2;
3400 static const int kEntrySize = 3;
3401 static const bool kIsEnumerable = true;
3405 class NameDictionary
3406 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3407 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3411 DECLARE_CAST(NameDictionary)
3413 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3414 Handle<NameDictionary> dictionary);
3418 class GlobalDictionaryShape : public NameDictionaryShape {
3420 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3422 template <typename Dictionary>
3423 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3425 template <typename Dictionary>
3426 static inline void DetailsAtPut(Dictionary* dict, int entry,
3427 PropertyDetails value);
3429 template <typename Dictionary>
3430 static bool IsDeleted(Dictionary* dict, int entry);
3432 template <typename Dictionary>
3433 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3434 Handle<Object> value, PropertyDetails details);
3438 class GlobalDictionary
3439 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3441 DECLARE_CAST(GlobalDictionary)
3445 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3447 static inline bool IsMatch(uint32_t key, Object* other);
3448 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3449 static const int kEntrySize = 3;
3450 static const bool kIsEnumerable = false;
3454 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3456 static const bool UsesSeed = true;
3457 static const int kPrefixSize = 2;
3459 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3460 static inline uint32_t SeededHashForObject(uint32_t key,
3466 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3468 static const int kPrefixSize = 0;
3470 static inline uint32_t Hash(uint32_t key);
3471 static inline uint32_t HashForObject(uint32_t key, Object* object);
3475 class SeededNumberDictionary
3476 : public Dictionary<SeededNumberDictionary,
3477 SeededNumberDictionaryShape,
3480 DECLARE_CAST(SeededNumberDictionary)
3482 // Type specific at put (default NONE attributes is used when adding).
3483 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3484 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3485 Handle<Object> value, bool used_as_prototype);
3486 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3487 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3488 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3490 // Set an existing entry or add a new one if needed.
3491 // Return the updated dictionary.
3492 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3493 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3494 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3496 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3498 // If slow elements are required we will never go back to fast-case
3499 // for the elements kept in this dictionary. We require slow
3500 // elements if an element has been added at an index larger than
3501 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3502 // when defining a getter or setter with a number key.
3503 inline bool requires_slow_elements();
3504 inline void set_requires_slow_elements();
3506 // Get the value of the max number key that has been added to this
3507 // dictionary. max_number_key can only be called if
3508 // requires_slow_elements returns false.
3509 inline uint32_t max_number_key();
3512 static const int kRequiresSlowElementsMask = 1;
3513 static const int kRequiresSlowElementsTagSize = 1;
3514 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3518 class UnseededNumberDictionary
3519 : public Dictionary<UnseededNumberDictionary,
3520 UnseededNumberDictionaryShape,
3523 DECLARE_CAST(UnseededNumberDictionary)
3525 // Type specific at put (default NONE attributes is used when adding).
3526 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3527 Handle<UnseededNumberDictionary> dictionary,
3529 Handle<Object> value);
3530 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3531 Handle<UnseededNumberDictionary> dictionary,
3533 Handle<Object> value);
3535 // Set an existing entry or add a new one if needed.
3536 // Return the updated dictionary.
3537 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3538 Handle<UnseededNumberDictionary> dictionary,
3540 Handle<Object> value);
3544 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3546 static inline bool IsMatch(Handle<Object> key, Object* other);
3547 static inline uint32_t Hash(Handle<Object> key);
3548 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3549 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3550 static const int kPrefixSize = 0;
3551 static const int kEntrySize = 2;
3555 // ObjectHashTable maps keys that are arbitrary objects to object values by
3556 // using the identity hash of the key for hashing purposes.
3557 class ObjectHashTable: public HashTable<ObjectHashTable,
3558 ObjectHashTableShape,
3561 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3563 DECLARE_CAST(ObjectHashTable)
3565 // Attempt to shrink hash table after removal of key.
3566 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3567 Handle<ObjectHashTable> table,
3568 Handle<Object> key);
3570 // Looks up the value associated with the given key. The hole value is
3571 // returned in case the key is not present.
3572 Object* Lookup(Handle<Object> key);
3573 Object* Lookup(Handle<Object> key, int32_t hash);
3574 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3576 // Adds (or overwrites) the value associated with the given key.
3577 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3579 Handle<Object> value);
3580 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3581 Handle<Object> key, Handle<Object> value,
3584 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3585 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3588 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3589 Handle<Object> key, bool* was_present,
3593 friend class MarkCompactCollector;
3595 void AddEntry(int entry, Object* key, Object* value);
3596 void RemoveEntry(int entry);
3598 // Returns the index to the value of an entry.
3599 static inline int EntryToValueIndex(int entry) {
3600 return EntryToIndex(entry) + 1;
3605 // OrderedHashTable is a HashTable with Object keys that preserves
3606 // insertion order. There are Map and Set interfaces (OrderedHashMap
3607 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3609 // Only Object* keys are supported, with Object::SameValueZero() used as the
3610 // equality operator and Object::GetHash() for the hash function.
3612 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3613 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3614 // Originally attributed to Tyler Close.
3617 // [0]: bucket count
3618 // [1]: element count
3619 // [2]: deleted element count
3620 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3621 // offset into the data table (see below) where the
3622 // first item in this bucket is stored.
3623 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3624 // Capacity() * kEntrySize, where the first entrysize
3625 // items are handled by the derived class and the
3626 // item at kChainOffset is another entry into the
3627 // data table indicating the next entry in this hash
3630 // When we transition the table to a new version we obsolete it and reuse parts
3631 // of the memory to store information how to transition an iterator to the new
3634 // Memory layout for obsolete table:
3635 // [0]: bucket count
3636 // [1]: Next newer table
3637 // [2]: Number of removed holes or -1 when the table was cleared.
3638 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3639 // [3 + NumberOfRemovedHoles()..length]: Not used
3641 template<class Derived, class Iterator, int entrysize>
3642 class OrderedHashTable: public FixedArray {
3644 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3645 static Handle<Derived> Allocate(
3646 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3648 // Returns an OrderedHashTable (possibly |table|) with enough space
3649 // to add at least one new element.
3650 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3652 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3654 static Handle<Derived> Shrink(Handle<Derived> table);
3656 // Returns a new empty OrderedHashTable and records the clearing so that
3657 // exisiting iterators can be updated.
3658 static Handle<Derived> Clear(Handle<Derived> table);
3660 int NumberOfElements() {
3661 return Smi::cast(get(kNumberOfElementsIndex))->value();
3664 int NumberOfDeletedElements() {
3665 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3668 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3670 int NumberOfBuckets() {
3671 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3674 // Returns an index into |this| for the given entry.
3675 int EntryToIndex(int entry) {
3676 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3679 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3682 return !get(kNextTableIndex)->IsSmi();
3685 // The next newer table. This is only valid if the table is obsolete.
3686 Derived* NextTable() {
3687 return Derived::cast(get(kNextTableIndex));
3690 // When the table is obsolete we store the indexes of the removed holes.
3691 int RemovedIndexAt(int index) {
3692 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3695 static const int kNotFound = -1;
3696 static const int kMinCapacity = 4;
3698 static const int kNumberOfBucketsIndex = 0;
3699 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3700 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3701 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3702 static const int kNextTableIndex = kNumberOfElementsIndex;
3704 static const int kNumberOfBucketsOffset =
3705 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3706 static const int kNumberOfElementsOffset =
3707 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3708 static const int kNumberOfDeletedElementsOffset =
3709 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3710 static const int kHashTableStartOffset =
3711 kHeaderSize + kHashTableStartIndex * kPointerSize;
3712 static const int kNextTableOffset =
3713 kHeaderSize + kNextTableIndex * kPointerSize;
3715 static const int kEntrySize = entrysize + 1;
3716 static const int kChainOffset = entrysize;
3718 static const int kLoadFactor = 2;
3720 // NumberOfDeletedElements is set to kClearedTableSentinel when
3721 // the table is cleared, which allows iterator transitions to
3722 // optimize that case.
3723 static const int kClearedTableSentinel = -1;
3726 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3728 void SetNumberOfBuckets(int num) {
3729 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3732 void SetNumberOfElements(int num) {
3733 set(kNumberOfElementsIndex, Smi::FromInt(num));
3736 void SetNumberOfDeletedElements(int num) {
3737 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3741 return NumberOfBuckets() * kLoadFactor;
3744 void SetNextTable(Derived* next_table) {
3745 set(kNextTableIndex, next_table);
3748 void SetRemovedIndexAt(int index, int removed_index) {
3749 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3752 static const int kRemovedHolesIndex = kHashTableStartIndex;
3754 static const int kMaxCapacity =
3755 (FixedArray::kMaxLength - kHashTableStartIndex)
3756 / (1 + (kEntrySize * kLoadFactor));
3760 class JSSetIterator;
3763 class OrderedHashSet: public OrderedHashTable<
3764 OrderedHashSet, JSSetIterator, 1> {
3766 DECLARE_CAST(OrderedHashSet)
3770 class JSMapIterator;
3773 class OrderedHashMap
3774 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3776 DECLARE_CAST(OrderedHashMap)
3778 inline Object* ValueAt(int entry);
3780 static const int kValueOffset = 1;
3784 template <int entrysize>
3785 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3787 static inline bool IsMatch(Handle<Object> key, Object* other);
3788 static inline uint32_t Hash(Handle<Object> key);
3789 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3790 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3791 static const int kPrefixSize = 0;
3792 static const int kEntrySize = entrysize;
3796 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3797 // values. The table wraps the keys in weak cells and store values directly.
3798 // Thus it references keys weakly and values strongly.
3799 class WeakHashTable: public HashTable<WeakHashTable,
3800 WeakHashTableShape<2>,
3803 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3805 DECLARE_CAST(WeakHashTable)
3807 // Looks up the value associated with the given key. The hole value is
3808 // returned in case the key is not present.
3809 Object* Lookup(Handle<HeapObject> key);
3811 // Adds (or overwrites) the value associated with the given key. Mapping a
3812 // key to the hole value causes removal of the whole entry.
3813 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3814 Handle<HeapObject> key,
3815 Handle<HeapObject> value);
3817 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3820 friend class MarkCompactCollector;
3822 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3824 // Returns the index to the value of an entry.
3825 static inline int EntryToValueIndex(int entry) {
3826 return EntryToIndex(entry) + 1;
3831 // ScopeInfo represents information about different scopes of a source
3832 // program and the allocation of the scope's variables. Scope information
3833 // is stored in a compressed form in ScopeInfo objects and is used
3834 // at runtime (stack dumps, deoptimization, etc.).
3836 // This object provides quick access to scope info details for runtime
3838 class ScopeInfo : public FixedArray {
3840 DECLARE_CAST(ScopeInfo)
3842 // Return the type of this scope.
3843 ScopeType scope_type();
3845 // Does this scope call eval?
3848 // Return the language mode of this scope.
3849 LanguageMode language_mode();
3851 // True if this scope is a (var) declaration scope.
3852 bool is_declaration_scope();
3854 // Does this scope make a sloppy eval call?
3855 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3857 // Return the total number of locals allocated on the stack and in the
3858 // context. This includes the parameters that are allocated in the context.
3861 // Return the number of stack slots for code. This number consists of two
3863 // 1. One stack slot per stack allocated local.
3864 // 2. One stack slot for the function name if it is stack allocated.
3865 int StackSlotCount();
3867 // Return the number of context slots for code if a context is allocated. This
3868 // number consists of three parts:
3869 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3870 // 2. One context slot per context allocated local.
3871 // 3. One context slot for the function name if it is context allocated.
3872 // Parameters allocated in the context count as context allocated locals. If
3873 // no contexts are allocated for this scope ContextLength returns 0.
3874 int ContextLength();
3876 // Does this scope declare a "this" binding?
3879 // Does this scope declare a "this" binding, and the "this" binding is stack-
3880 // or context-allocated?
3881 bool HasAllocatedReceiver();
3883 // Is this scope the scope of a named function expression?
3884 bool HasFunctionName();
3886 // Return if this has context allocated locals.
3887 bool HasHeapAllocatedLocals();
3889 // Return if contexts are allocated for this scope.
3892 // Return if this is a function scope with "use asm".
3893 inline bool IsAsmModule();
3895 // Return if this is a nested function within an asm module scope.
3896 inline bool IsAsmFunction();
3898 inline bool HasSimpleParameters();
3900 // Return the function_name if present.
3901 String* FunctionName();
3903 // Return the name of the given parameter.
3904 String* ParameterName(int var);
3906 // Return the name of the given local.
3907 String* LocalName(int var);
3909 // Return the name of the given stack local.
3910 String* StackLocalName(int var);
3912 // Return the name of the given stack local.
3913 int StackLocalIndex(int var);
3915 // Return the name of the given context local.
3916 String* ContextLocalName(int var);
3918 // Return the mode of the given context local.
3919 VariableMode ContextLocalMode(int var);
3921 // Return the initialization flag of the given context local.
3922 InitializationFlag ContextLocalInitFlag(int var);
3924 // Return the initialization flag of the given context local.
3925 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3927 // Return true if this local was introduced by the compiler, and should not be
3928 // exposed to the user in a debugger.
3929 bool LocalIsSynthetic(int var);
3931 String* StrongModeFreeVariableName(int var);
3932 int StrongModeFreeVariableStartPosition(int var);
3933 int StrongModeFreeVariableEndPosition(int var);
3935 // Lookup support for serialized scope info. Returns the
3936 // the stack slot index for a given slot name if the slot is
3937 // present; otherwise returns a value < 0. The name must be an internalized
3939 int StackSlotIndex(String* name);
3941 // Lookup support for serialized scope info. Returns the local context slot
3942 // index for a given slot name if the slot is present; otherwise
3943 // returns a value < 0. The name must be an internalized string.
3944 // If the slot is present and mode != NULL, sets *mode to the corresponding
3945 // mode for that variable.
3946 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3947 VariableMode* mode, InitializationFlag* init_flag,
3948 MaybeAssignedFlag* maybe_assigned_flag);
3950 // Similar to ContextSlotIndex() but this method searches only among
3951 // global slots of the serialized scope info. Returns the context slot index
3952 // for a given slot name if the slot is present; otherwise returns a
3953 // value < 0. The name must be an internalized string. If the slot is present
3954 // and mode != NULL, sets *mode to the corresponding mode for that variable.
3955 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
3956 Handle<String> name, VariableMode* mode,
3957 InitializationFlag* init_flag,
3958 MaybeAssignedFlag* maybe_assigned_flag);
3960 // Lookup the name of a certain context slot by its index.
3961 String* ContextSlotName(int slot_index);
3963 // Lookup support for serialized scope info. Returns the
3964 // parameter index for a given parameter name if the parameter is present;
3965 // otherwise returns a value < 0. The name must be an internalized string.
3966 int ParameterIndex(String* name);
3968 // Lookup support for serialized scope info. Returns the function context
3969 // slot index if the function name is present and context-allocated (named
3970 // function expressions, only), otherwise returns a value < 0. The name
3971 // must be an internalized string.
3972 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3974 // Lookup support for serialized scope info. Returns the receiver context
3975 // slot index if scope has a "this" binding, and the binding is
3976 // context-allocated. Otherwise returns a value < 0.
3977 int ReceiverContextSlotIndex();
3979 FunctionKind function_kind();
3981 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3982 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3984 // Serializes empty scope info.
3985 static ScopeInfo* Empty(Isolate* isolate);
3991 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3992 // numeric and occupies one array slot.
3993 // 1. A set of properties of the scope
3994 // 2. The number of parameters. This only applies to function scopes. For
3995 // non-function scopes this is 0.
3996 // 3. The number of non-parameter variables allocated on the stack.
3997 // 4. The number of non-parameter and parameter variables allocated in the
3999 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4002 V(StackLocalCount) \
4003 V(ContextLocalCount) \
4004 V(ContextGlobalCount) \
4005 V(StrongModeFreeVariableCount)
4007 #define FIELD_ACCESSORS(name) \
4008 inline void Set##name(int value); \
4010 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4011 #undef FIELD_ACCESSORS
4015 #define DECL_INDEX(name) k##name,
4016 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4021 // The layout of the variable part of a ScopeInfo is as follows:
4022 // 1. ParameterEntries:
4023 // This part stores the names of the parameters for function scopes. One
4024 // slot is used per parameter, so in total this part occupies
4025 // ParameterCount() slots in the array. For other scopes than function
4026 // scopes ParameterCount() is 0.
4027 // 2. StackLocalFirstSlot:
4028 // Index of a first stack slot for stack local. Stack locals belonging to
4029 // this scope are located on a stack at slots starting from this index.
4030 // 3. StackLocalEntries:
4031 // Contains the names of local variables that are allocated on the stack,
4032 // in increasing order of the stack slot index. First local variable has
4033 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4034 // One slot is used per stack local, so in total this part occupies
4035 // StackLocalCount() slots in the array.
4036 // 4. ContextLocalNameEntries:
4037 // Contains the names of local variables and parameters that are allocated
4038 // in the context. They are stored in increasing order of the context slot
4039 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4040 // context local, so in total this part occupies ContextLocalCount() slots
4042 // 5. ContextLocalInfoEntries:
4043 // Contains the variable modes and initialization flags corresponding to
4044 // the context locals in ContextLocalNameEntries. One slot is used per
4045 // context local, so in total this part occupies ContextLocalCount()
4046 // slots in the array.
4047 // 6. StrongModeFreeVariableNameEntries:
4048 // Stores the names of strong mode free variables.
4049 // 7. StrongModeFreeVariablePositionEntries:
4050 // Stores the locations (start and end position) of strong mode free
4052 // 8. RecieverEntryIndex:
4053 // If the scope binds a "this" value, one slot is reserved to hold the
4054 // context or stack slot index for the variable.
4055 // 9. FunctionNameEntryIndex:
4056 // If the scope belongs to a named function expression this part contains
4057 // information about the function variable. It always occupies two array
4058 // slots: a. The name of the function variable.
4059 // b. The context or stack slot index for the variable.
4060 int ParameterEntriesIndex();
4061 int StackLocalFirstSlotIndex();
4062 int StackLocalEntriesIndex();
4063 int ContextLocalNameEntriesIndex();
4064 int ContextGlobalNameEntriesIndex();
4065 int ContextLocalInfoEntriesIndex();
4066 int ContextGlobalInfoEntriesIndex();
4067 int StrongModeFreeVariableNameEntriesIndex();
4068 int StrongModeFreeVariablePositionEntriesIndex();
4069 int ReceiverEntryIndex();
4070 int FunctionNameEntryIndex();
4072 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4073 VariableLocation* location, InitializationFlag* init_flag,
4074 MaybeAssignedFlag* maybe_assigned_flag);
4076 // Used for the function name variable for named function expressions, and for
4078 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4080 // Properties of scopes.
4081 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4082 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4083 STATIC_ASSERT(LANGUAGE_END == 3);
4084 class LanguageModeField
4085 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4086 class DeclarationScopeField
4087 : public BitField<bool, LanguageModeField::kNext, 1> {};
4088 class ReceiverVariableField
4089 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4091 class FunctionVariableField
4092 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4094 class FunctionVariableMode
4095 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4096 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4098 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4099 class HasSimpleParametersField
4100 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4101 class FunctionKindField
4102 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4104 // BitFields representing the encoded information for context locals in the
4105 // ContextLocalInfoEntries part.
4106 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4107 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4108 class ContextLocalMaybeAssignedFlag
4109 : public BitField<MaybeAssignedFlag, 4, 1> {};
4111 friend class ScopeIterator;
4115 // The cache for maps used by normalized (dictionary mode) objects.
4116 // Such maps do not have property descriptors, so a typical program
4117 // needs very limited number of distinct normalized maps.
4118 class NormalizedMapCache: public FixedArray {
4120 static Handle<NormalizedMapCache> New(Isolate* isolate);
4122 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4123 PropertyNormalizationMode mode);
4124 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4128 DECLARE_CAST(NormalizedMapCache)
4130 static inline bool IsNormalizedMapCache(const Object* obj);
4132 DECLARE_VERIFIER(NormalizedMapCache)
4134 static const int kEntries = 64;
4136 static inline int GetIndex(Handle<Map> map);
4138 // The following declarations hide base class methods.
4139 Object* get(int index);
4140 void set(int index, Object* value);
4144 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4145 // that is attached to code objects.
4146 class ByteArray: public FixedArrayBase {
4150 // Setter and getter.
4151 inline byte get(int index);
4152 inline void set(int index, byte value);
4154 // Treat contents as an int array.
4155 inline int get_int(int index);
4157 static int SizeFor(int length) {
4158 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4160 // We use byte arrays for free blocks in the heap. Given a desired size in
4161 // bytes that is a multiple of the word size and big enough to hold a byte
4162 // array, this function returns the number of elements a byte array should
4164 static int LengthFor(int size_in_bytes) {
4165 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4166 DCHECK(size_in_bytes >= kHeaderSize);
4167 return size_in_bytes - kHeaderSize;
4170 // Returns data start address.
4171 inline Address GetDataStartAddress();
4173 // Returns a pointer to the ByteArray object for a given data start address.
4174 static inline ByteArray* FromDataStartAddress(Address address);
4176 DECLARE_CAST(ByteArray)
4178 // Dispatched behavior.
4179 inline int ByteArraySize();
4180 DECLARE_PRINTER(ByteArray)
4181 DECLARE_VERIFIER(ByteArray)
4183 // Layout description.
4184 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4186 // Maximal memory consumption for a single ByteArray.
4187 static const int kMaxSize = 512 * MB;
4188 // Maximal length of a single ByteArray.
4189 static const int kMaxLength = kMaxSize - kHeaderSize;
4192 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4196 // BytecodeArray represents a sequence of interpreter bytecodes.
4197 class BytecodeArray : public FixedArrayBase {
4199 static int SizeFor(int length) {
4200 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4203 // Setter and getter
4204 inline byte get(int index);
4205 inline void set(int index, byte value);
4207 // Returns data start address.
4208 inline Address GetFirstBytecodeAddress();
4210 // Accessors for frame size.
4211 inline int frame_size() const;
4212 inline void set_frame_size(int frame_size);
4214 // Accessor for register count (derived from frame_size).
4215 inline int register_count() const;
4217 // Accessors for parameter count (including implicit 'this' receiver).
4218 inline int parameter_count() const;
4219 inline void set_parameter_count(int number_of_parameters);
4221 // Accessors for the constant pool.
4222 DECL_ACCESSORS(constant_pool, FixedArray)
4224 DECLARE_CAST(BytecodeArray)
4226 // Dispatched behavior.
4227 inline int BytecodeArraySize();
4228 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4230 DECLARE_PRINTER(BytecodeArray)
4231 DECLARE_VERIFIER(BytecodeArray)
4233 void Disassemble(std::ostream& os);
4235 // Layout description.
4236 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4237 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4238 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4239 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4241 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4243 // Maximal memory consumption for a single BytecodeArray.
4244 static const int kMaxSize = 512 * MB;
4245 // Maximal length of a single BytecodeArray.
4246 static const int kMaxLength = kMaxSize - kHeaderSize;
4249 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4253 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4254 // They look like heap objects (are heap object tagged and have a map) so that
4255 // the heap remains iterable. They have a size and a next pointer.
4256 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4257 // in the free list.
4258 class FreeSpace: public HeapObject {
4260 // [size]: size of the free space including the header.
4261 inline int size() const;
4262 inline void set_size(int value);
4264 inline int nobarrier_size() const;
4265 inline void nobarrier_set_size(int value);
4269 // Accessors for the next field.
4270 inline FreeSpace* next();
4271 inline FreeSpace** next_address();
4272 inline void set_next(FreeSpace* next);
4274 inline static FreeSpace* cast(HeapObject* obj);
4276 // Dispatched behavior.
4277 DECLARE_PRINTER(FreeSpace)
4278 DECLARE_VERIFIER(FreeSpace)
4280 // Layout description.
4281 // Size is smi tagged when it is stored.
4282 static const int kSizeOffset = HeapObject::kHeaderSize;
4283 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4286 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4290 // V has parameters (Type, type, TYPE, C type, element_size)
4291 #define TYPED_ARRAYS(V) \
4292 V(Uint8, uint8, UINT8, uint8_t, 1) \
4293 V(Int8, int8, INT8, int8_t, 1) \
4294 V(Uint16, uint16, UINT16, uint16_t, 2) \
4295 V(Int16, int16, INT16, int16_t, 2) \
4296 V(Uint32, uint32, UINT32, uint32_t, 4) \
4297 V(Int32, int32, INT32, int32_t, 4) \
4298 V(Float32, float32, FLOAT32, float, 4) \
4299 V(Float64, float64, FLOAT64, double, 8) \
4300 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4303 class FixedTypedArrayBase: public FixedArrayBase {
4305 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4306 DECL_ACCESSORS(base_pointer, Object)
4308 // [external_pointer]: Contains the offset between base_pointer and the start
4309 // of the data. If the base_pointer is a nullptr, the external_pointer
4310 // therefore points to the actual backing store.
4311 DECL_ACCESSORS(external_pointer, void)
4313 // Dispatched behavior.
4314 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4316 template <typename StaticVisitor>
4317 inline void FixedTypedArrayBaseIterateBody();
4319 DECLARE_CAST(FixedTypedArrayBase)
4321 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4322 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4323 static const int kHeaderSize =
4324 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4326 static const int kDataOffset = kHeaderSize;
4330 static inline int TypedArraySize(InstanceType type, int length);
4331 inline int TypedArraySize(InstanceType type);
4333 // Use with care: returns raw pointer into heap.
4334 inline void* DataPtr();
4336 inline int DataSize();
4339 static inline int ElementSize(InstanceType type);
4341 inline int DataSize(InstanceType type);
4343 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4347 template <class Traits>
4348 class FixedTypedArray: public FixedTypedArrayBase {
4350 typedef typename Traits::ElementType ElementType;
4351 static const InstanceType kInstanceType = Traits::kInstanceType;
4353 DECLARE_CAST(FixedTypedArray<Traits>)
4355 inline ElementType get_scalar(int index);
4356 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4357 inline void set(int index, ElementType value);
4359 static inline ElementType from_int(int value);
4360 static inline ElementType from_double(double value);
4362 // This accessor applies the correct conversion from Smi, HeapNumber
4364 inline void SetValue(uint32_t index, Object* value);
4366 DECLARE_PRINTER(FixedTypedArray)
4367 DECLARE_VERIFIER(FixedTypedArray)
4370 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4373 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4374 class Type##ArrayTraits { \
4375 public: /* NOLINT */ \
4376 typedef elementType ElementType; \
4377 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4378 static const char* Designator() { return #type " array"; } \
4379 static inline Handle<Object> ToHandle(Isolate* isolate, \
4380 elementType scalar); \
4381 static inline elementType defaultValue(); \
4384 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4386 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4388 #undef FIXED_TYPED_ARRAY_TRAITS
4391 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4392 // data for code generated by the Hydrogen/Lithium compiler. It also
4393 // contains information about functions that were inlined. If N different
4394 // functions were inlined then first N elements of the literal array will
4395 // contain these functions.
4398 class DeoptimizationInputData: public FixedArray {
4400 // Layout description. Indices in the array.
4401 static const int kTranslationByteArrayIndex = 0;
4402 static const int kInlinedFunctionCountIndex = 1;
4403 static const int kLiteralArrayIndex = 2;
4404 static const int kOsrAstIdIndex = 3;
4405 static const int kOsrPcOffsetIndex = 4;
4406 static const int kOptimizationIdIndex = 5;
4407 static const int kSharedFunctionInfoIndex = 6;
4408 static const int kWeakCellCacheIndex = 7;
4409 static const int kFirstDeoptEntryIndex = 8;
4411 // Offsets of deopt entry elements relative to the start of the entry.
4412 static const int kAstIdRawOffset = 0;
4413 static const int kTranslationIndexOffset = 1;
4414 static const int kArgumentsStackHeightOffset = 2;
4415 static const int kPcOffset = 3;
4416 static const int kDeoptEntrySize = 4;
4418 // Simple element accessors.
4419 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4420 inline type* name(); \
4421 inline void Set##name(type* value);
4423 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4424 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4425 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4426 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4427 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4428 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4429 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4430 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4432 #undef DECLARE_ELEMENT_ACCESSORS
4434 // Accessors for elements of the ith deoptimization entry.
4435 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4436 inline type* name(int i); \
4437 inline void Set##name(int i, type* value);
4439 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4440 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4441 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4442 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4444 #undef DECLARE_ENTRY_ACCESSORS
4446 inline BailoutId AstId(int i);
4448 inline void SetAstId(int i, BailoutId value);
4450 inline int DeoptCount();
4452 // Allocates a DeoptimizationInputData.
4453 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4454 int deopt_entry_count,
4455 PretenureFlag pretenure);
4457 DECLARE_CAST(DeoptimizationInputData)
4459 #ifdef ENABLE_DISASSEMBLER
4460 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4464 static int IndexForEntry(int i) {
4465 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4469 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4473 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4474 // data for code generated by the full compiler.
4475 // The format of the these objects is
4476 // [i * 2]: Ast ID for ith deoptimization.
4477 // [i * 2 + 1]: PC and state of ith deoptimization
4478 class DeoptimizationOutputData: public FixedArray {
4480 inline int DeoptPoints();
4482 inline BailoutId AstId(int index);
4484 inline void SetAstId(int index, BailoutId id);
4486 inline Smi* PcAndState(int index);
4487 inline void SetPcAndState(int index, Smi* offset);
4489 static int LengthOfFixedArray(int deopt_points) {
4490 return deopt_points * 2;
4493 // Allocates a DeoptimizationOutputData.
4494 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4495 int number_of_deopt_points,
4496 PretenureFlag pretenure);
4498 DECLARE_CAST(DeoptimizationOutputData)
4500 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4501 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4506 // HandlerTable is a fixed array containing entries for exception handlers in
4507 // the code object it is associated with. The tables comes in two flavors:
4508 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4509 // exception handler and a range representing the try-block covered by that
4510 // handler. Layout looks as follows:
4511 // [ range-start , range-end , handler-offset , stack-depth ]
4512 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4513 // per call-site that could throw an exception. Layout looks as follows:
4514 // [ return-address-offset , handler-offset ]
4515 class HandlerTable : public FixedArray {
4517 // Conservative prediction whether a given handler will locally catch an
4518 // exception or cause a re-throw to outside the code boundary. Since this is
4519 // undecidable it is merely an approximation (e.g. useful for debugger).
4520 enum CatchPrediction { UNCAUGHT, CAUGHT };
4522 // Accessors for handler table based on ranges.
4523 inline void SetRangeStart(int index, int value);
4524 inline void SetRangeEnd(int index, int value);
4525 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4526 inline void SetRangeDepth(int index, int value);
4528 // Accessors for handler table based on return addresses.
4529 inline void SetReturnOffset(int index, int value);
4530 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4532 // Lookup handler in a table based on ranges.
4533 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4535 // Lookup handler in a table based on return addresses.
4536 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4538 // Returns the required length of the underlying fixed array.
4539 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4540 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4542 DECLARE_CAST(HandlerTable)
4544 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4545 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4546 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4550 // Layout description for handler table based on ranges.
4551 static const int kRangeStartIndex = 0;
4552 static const int kRangeEndIndex = 1;
4553 static const int kRangeHandlerIndex = 2;
4554 static const int kRangeDepthIndex = 3;
4555 static const int kRangeEntrySize = 4;
4557 // Layout description for handler table based on return addresses.
4558 static const int kReturnOffsetIndex = 0;
4559 static const int kReturnHandlerIndex = 1;
4560 static const int kReturnEntrySize = 2;
4562 // Encoding of the {handler} field.
4563 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4564 class HandlerOffsetField : public BitField<int, 1, 30> {};
4568 // Code describes objects with on-the-fly generated machine code.
4569 class Code: public HeapObject {
4571 // Opaque data type for encapsulating code flags like kind, inline
4572 // cache state, and arguments count.
4573 typedef uint32_t Flags;
4575 #define NON_IC_KIND_LIST(V) \
4577 V(OPTIMIZED_FUNCTION) \
4584 #define IC_KIND_LIST(V) \
4595 #define CODE_KIND_LIST(V) \
4596 NON_IC_KIND_LIST(V) \
4600 #define DEFINE_CODE_KIND_ENUM(name) name,
4601 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4602 #undef DEFINE_CODE_KIND_ENUM
4606 // No more than 16 kinds. The value is currently encoded in four bits in
4608 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4610 static const char* Kind2String(Kind kind);
4618 static const int kPrologueOffsetNotSet = -1;
4620 #ifdef ENABLE_DISASSEMBLER
4622 static const char* ICState2String(InlineCacheState state);
4623 static const char* StubType2String(StubType type);
4624 static void PrintExtraICState(std::ostream& os, // NOLINT
4625 Kind kind, ExtraICState extra);
4626 void Disassemble(const char* name, std::ostream& os); // NOLINT
4627 #endif // ENABLE_DISASSEMBLER
4629 // [instruction_size]: Size of the native instructions
4630 inline int instruction_size() const;
4631 inline void set_instruction_size(int value);
4633 // [relocation_info]: Code relocation information
4634 DECL_ACCESSORS(relocation_info, ByteArray)
4635 void InvalidateRelocation();
4636 void InvalidateEmbeddedObjects();
4638 // [handler_table]: Fixed array containing offsets of exception handlers.
4639 DECL_ACCESSORS(handler_table, FixedArray)
4641 // [deoptimization_data]: Array containing data for deopt.
4642 DECL_ACCESSORS(deoptimization_data, FixedArray)
4644 // [raw_type_feedback_info]: This field stores various things, depending on
4645 // the kind of the code object.
4646 // FUNCTION => type feedback information.
4647 // STUB and ICs => major/minor key as Smi.
4648 DECL_ACCESSORS(raw_type_feedback_info, Object)
4649 inline Object* type_feedback_info();
4650 inline void set_type_feedback_info(
4651 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4652 inline uint32_t stub_key();
4653 inline void set_stub_key(uint32_t key);
4655 // [next_code_link]: Link for lists of optimized or deoptimized code.
4656 // Note that storage for this field is overlapped with typefeedback_info.
4657 DECL_ACCESSORS(next_code_link, Object)
4659 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4660 // field does not have to be traced during garbage collection since
4661 // it is only used by the garbage collector itself.
4662 DECL_ACCESSORS(gc_metadata, Object)
4664 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4665 // at the moment when this object was created.
4666 inline void set_ic_age(int count);
4667 inline int ic_age() const;
4669 // [prologue_offset]: Offset of the function prologue, used for aging
4670 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4671 inline int prologue_offset() const;
4672 inline void set_prologue_offset(int offset);
4674 // [constant_pool offset]: Offset of the constant pool.
4675 // Valid for FLAG_enable_embedded_constant_pool only
4676 inline int constant_pool_offset() const;
4677 inline void set_constant_pool_offset(int offset);
4679 // Unchecked accessors to be used during GC.
4680 inline ByteArray* unchecked_relocation_info();
4682 inline int relocation_size();
4684 // [flags]: Various code flags.
4685 inline Flags flags();
4686 inline void set_flags(Flags flags);
4688 // [flags]: Access to specific code flags.
4690 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4691 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4693 inline StubType type(); // Only valid for monomorphic IC stubs.
4695 // Testers for IC stub kinds.
4696 inline bool is_inline_cache_stub();
4697 inline bool is_debug_stub();
4698 inline bool is_handler();
4699 inline bool is_load_stub();
4700 inline bool is_keyed_load_stub();
4701 inline bool is_store_stub();
4702 inline bool is_keyed_store_stub();
4703 inline bool is_call_stub();
4704 inline bool is_binary_op_stub();
4705 inline bool is_compare_ic_stub();
4706 inline bool is_compare_nil_ic_stub();
4707 inline bool is_to_boolean_ic_stub();
4708 inline bool is_keyed_stub();
4709 inline bool is_optimized_code();
4710 inline bool embeds_maps_weakly();
4712 inline bool IsCodeStubOrIC();
4713 inline bool IsJavaScriptCode();
4715 inline void set_raw_kind_specific_flags1(int value);
4716 inline void set_raw_kind_specific_flags2(int value);
4718 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4719 // object was generated by either the hydrogen or the TurboFan optimizing
4720 // compiler (but it may not be an optimized function).
4721 inline bool is_crankshafted();
4722 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4723 inline void set_is_crankshafted(bool value);
4725 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4726 // code object was generated by the TurboFan optimizing compiler.
4727 inline bool is_turbofanned();
4728 inline void set_is_turbofanned(bool value);
4730 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4731 // embedded objects in code should be treated weakly.
4732 inline bool can_have_weak_objects();
4733 inline void set_can_have_weak_objects(bool value);
4735 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4736 // deoptimization support.
4737 inline bool has_deoptimization_support();
4738 inline void set_has_deoptimization_support(bool value);
4740 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4741 // been compiled with debug break slots.
4742 inline bool has_debug_break_slots();
4743 inline void set_has_debug_break_slots(bool value);
4745 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4746 // reloc info includes runtime and external references to support
4747 // serialization/deserialization.
4748 inline bool has_reloc_info_for_serialization();
4749 inline void set_has_reloc_info_for_serialization(bool value);
4751 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4752 // how long the function has been marked for OSR and therefore which
4753 // level of loop nesting we are willing to do on-stack replacement
4755 inline void set_allow_osr_at_loop_nesting_level(int level);
4756 inline int allow_osr_at_loop_nesting_level();
4758 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4759 // the code object was seen on the stack with no IC patching going on.
4760 inline int profiler_ticks();
4761 inline void set_profiler_ticks(int ticks);
4763 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4764 // For builtins, tells which builtin index it has.
4765 // Note that builtins can have a code kind other than BUILTIN, which means
4766 // that for arbitrary code objects, this index value may be random garbage.
4767 // To verify in that case, compare the code object to the indexed builtin.
4768 inline int builtin_index();
4769 inline void set_builtin_index(int id);
4771 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4772 // reserved in the code prologue.
4773 inline unsigned stack_slots();
4774 inline void set_stack_slots(unsigned slots);
4776 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4777 // the instruction stream where the safepoint table starts.
4778 inline unsigned safepoint_table_offset();
4779 inline void set_safepoint_table_offset(unsigned offset);
4781 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4782 // instruction stream where the back edge table starts.
4783 inline unsigned back_edge_table_offset();
4784 inline void set_back_edge_table_offset(unsigned offset);
4786 inline bool back_edges_patched_for_osr();
4788 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4789 inline uint16_t to_boolean_state();
4791 // [has_function_cache]: For kind STUB tells whether there is a function
4792 // cache is passed to the stub.
4793 inline bool has_function_cache();
4794 inline void set_has_function_cache(bool flag);
4797 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4798 // the code is going to be deoptimized because of dead embedded maps.
4799 inline bool marked_for_deoptimization();
4800 inline void set_marked_for_deoptimization(bool flag);
4802 // [constant_pool]: The constant pool for this function.
4803 inline Address constant_pool();
4805 // Get the safepoint entry for the given pc.
4806 SafepointEntry GetSafepointEntry(Address pc);
4808 // Find an object in a stub with a specified map
4809 Object* FindNthObject(int n, Map* match_map);
4811 // Find the first allocation site in an IC stub.
4812 AllocationSite* FindFirstAllocationSite();
4814 // Find the first map in an IC stub.
4815 Map* FindFirstMap();
4816 void FindAllMaps(MapHandleList* maps);
4818 // Find the first handler in an IC stub.
4819 Code* FindFirstHandler();
4821 // Find |length| handlers and put them into |code_list|. Returns false if not
4822 // enough handlers can be found.
4823 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4825 // Find the handler for |map|.
4826 MaybeHandle<Code> FindHandlerForMap(Map* map);
4828 // Find the first name in an IC stub.
4829 Name* FindFirstName();
4831 class FindAndReplacePattern;
4832 // For each (map-to-find, object-to-replace) pair in the pattern, this
4833 // function replaces the corresponding placeholder in the code with the
4834 // object-to-replace. The function assumes that pairs in the pattern come in
4835 // the same order as the placeholders in the code.
4836 // If the placeholder is a weak cell, then the value of weak cell is matched
4837 // against the map-to-find.
4838 void FindAndReplace(const FindAndReplacePattern& pattern);
4840 // The entire code object including its header is copied verbatim to the
4841 // snapshot so that it can be written in one, fast, memcpy during
4842 // deserialization. The deserializer will overwrite some pointers, rather
4843 // like a runtime linker, but the random allocation addresses used in the
4844 // mksnapshot process would still be present in the unlinked snapshot data,
4845 // which would make snapshot production non-reproducible. This method wipes
4846 // out the to-be-overwritten header data for reproducible snapshots.
4847 inline void WipeOutHeader();
4849 // Flags operations.
4850 static inline Flags ComputeFlags(
4851 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4852 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4853 CacheHolderFlag holder = kCacheOnReceiver);
4855 static inline Flags ComputeMonomorphicFlags(
4856 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4857 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4859 static inline Flags ComputeHandlerFlags(
4860 Kind handler_kind, StubType type = NORMAL,
4861 CacheHolderFlag holder = kCacheOnReceiver);
4863 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4864 static inline StubType ExtractTypeFromFlags(Flags flags);
4865 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4866 static inline Kind ExtractKindFromFlags(Flags flags);
4867 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4869 static inline Flags RemoveTypeFromFlags(Flags flags);
4870 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4872 // Convert a target address into a code object.
4873 static inline Code* GetCodeFromTargetAddress(Address address);
4875 // Convert an entry address into an object.
4876 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4878 // Returns the address of the first instruction.
4879 inline byte* instruction_start();
4881 // Returns the address right after the last instruction.
4882 inline byte* instruction_end();
4884 // Returns the size of the instructions, padding, and relocation information.
4885 inline int body_size();
4887 // Returns the address of the first relocation info (read backwards!).
4888 inline byte* relocation_start();
4890 // Code entry point.
4891 inline byte* entry();
4893 // Returns true if pc is inside this object's instructions.
4894 inline bool contains(byte* pc);
4896 // Relocate the code by delta bytes. Called to signal that this code
4897 // object has been moved by delta bytes.
4898 void Relocate(intptr_t delta);
4900 // Migrate code described by desc.
4901 void CopyFrom(const CodeDesc& desc);
4903 // Returns the object size for a given body (used for allocation).
4904 static int SizeFor(int body_size) {
4905 DCHECK_SIZE_TAG_ALIGNED(body_size);
4906 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4909 // Calculate the size of the code object to report for log events. This takes
4910 // the layout of the code object into account.
4911 inline int ExecutableSize();
4913 // Locating source position.
4914 int SourcePosition(Address pc);
4915 int SourceStatementPosition(Address pc);
4919 // Dispatched behavior.
4920 inline int CodeSize();
4921 inline void CodeIterateBody(ObjectVisitor* v);
4923 template<typename StaticVisitor>
4924 inline void CodeIterateBody(Heap* heap);
4926 DECLARE_PRINTER(Code)
4927 DECLARE_VERIFIER(Code)
4929 void ClearInlineCaches();
4930 void ClearInlineCaches(Kind kind);
4932 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4933 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4935 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4937 kToBeExecutedOnceCodeAge = -3,
4938 kNotExecutedCodeAge = -2,
4939 kExecutedOnceCodeAge = -1,
4941 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4943 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4944 kLastCodeAge = kAfterLastCodeAge - 1,
4945 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4946 kIsOldCodeAge = kSexagenarianCodeAge,
4947 kPreAgedCodeAge = kIsOldCodeAge - 1
4949 #undef DECLARE_CODE_AGE_ENUM
4951 // Code aging. Indicates how many full GCs this code has survived without
4952 // being entered through the prologue. Used to determine when it is
4953 // relatively safe to flush this code object and replace it with the lazy
4954 // compilation stub.
4955 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4956 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4957 void MakeYoung(Isolate* isolate);
4958 void MarkToBeExecutedOnce(Isolate* isolate);
4959 void MakeOlder(MarkingParity);
4960 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4963 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4964 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4967 void PrintDeoptLocation(FILE* out, Address pc);
4968 bool CanDeoptAt(Address pc);
4971 void VerifyEmbeddedObjectsDependency();
4975 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4976 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4977 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4980 inline bool CanContainWeakObjects();
4982 inline bool IsWeakObject(Object* object);
4984 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4986 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4987 WeakCell* CachedWeakCell();
4989 // Max loop nesting marker used to postpose OSR. We don't take loop
4990 // nesting that is deeper than 5 levels into account.
4991 static const int kMaxLoopNestingMarker = 6;
4993 static const int kConstantPoolSize =
4994 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4996 // Layout description.
4997 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4998 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4999 static const int kDeoptimizationDataOffset =
5000 kHandlerTableOffset + kPointerSize;
5001 // For FUNCTION kind, we store the type feedback info here.
5002 static const int kTypeFeedbackInfoOffset =
5003 kDeoptimizationDataOffset + kPointerSize;
5004 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5005 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5006 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5007 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5008 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5009 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5010 static const int kKindSpecificFlags2Offset =
5011 kKindSpecificFlags1Offset + kIntSize;
5012 // Note: We might be able to squeeze this into the flags above.
5013 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5014 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5015 static const int kHeaderPaddingStart =
5016 kConstantPoolOffset + kConstantPoolSize;
5018 // Add padding to align the instruction start following right after
5019 // the Code object header.
5020 static const int kHeaderSize =
5021 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5023 // Byte offsets within kKindSpecificFlags1Offset.
5024 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5025 class FullCodeFlagsHasDeoptimizationSupportField:
5026 public BitField<bool, 0, 1> {}; // NOLINT
5027 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5028 class FullCodeFlagsHasRelocInfoForSerialization
5029 : public BitField<bool, 2, 1> {};
5030 // Bit 3 in this bitfield is unused.
5031 class ProfilerTicksField : public BitField<int, 4, 28> {};
5033 // Flags layout. BitField<type, shift, size>.
5034 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5035 class TypeField : public BitField<StubType, 4, 1> {};
5036 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5037 class KindField : public BitField<Kind, 7, 4> {};
5038 class ExtraICStateField: public BitField<ExtraICState, 11,
5039 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5041 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5042 static const int kStackSlotsFirstBit = 0;
5043 static const int kStackSlotsBitCount = 24;
5044 static const int kHasFunctionCacheBit =
5045 kStackSlotsFirstBit + kStackSlotsBitCount;
5046 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5047 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5048 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5050 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5051 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5053 class StackSlotsField: public BitField<int,
5054 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5055 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5057 class MarkedForDeoptimizationField
5058 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5059 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5061 class CanHaveWeakObjectsField
5062 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5064 // KindSpecificFlags2 layout (ALL)
5065 static const int kIsCrankshaftedBit = 0;
5066 class IsCrankshaftedField: public BitField<bool,
5067 kIsCrankshaftedBit, 1> {}; // NOLINT
5069 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5070 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5071 static const int kSafepointTableOffsetBitCount = 30;
5073 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5074 kSafepointTableOffsetBitCount <= 32);
5075 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5077 class SafepointTableOffsetField: public BitField<int,
5078 kSafepointTableOffsetFirstBit,
5079 kSafepointTableOffsetBitCount> {}; // NOLINT
5081 // KindSpecificFlags2 layout (FUNCTION)
5082 class BackEdgeTableOffsetField: public BitField<int,
5083 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5084 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5085 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5086 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5088 static const int kArgumentsBits = 16;
5089 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5091 // This constant should be encodable in an ARM instruction.
5092 static const int kFlagsNotUsedInLookup =
5093 TypeField::kMask | CacheHolderField::kMask;
5096 friend class RelocIterator;
5097 friend class Deoptimizer; // For FindCodeAgeSequence.
5099 void ClearInlineCaches(Kind* kind);
5102 byte* FindCodeAgeSequence();
5103 static void GetCodeAgeAndParity(Code* code, Age* age,
5104 MarkingParity* parity);
5105 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5106 MarkingParity* parity);
5107 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5109 // Code aging -- platform-specific
5110 static void PatchPlatformCodeAge(Isolate* isolate,
5111 byte* sequence, Age age,
5112 MarkingParity parity);
5114 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5118 // This class describes the layout of dependent codes array of a map. The
5119 // array is partitioned into several groups of dependent codes. Each group
5120 // contains codes with the same dependency on the map. The array has the
5121 // following layout for n dependency groups:
5123 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5124 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5125 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5127 // The first n elements are Smis, each of them specifies the number of codes
5128 // in the corresponding group. The subsequent elements contain grouped code
5129 // objects in weak cells. The suffix of the array can be filled with the
5130 // undefined value if the number of codes is less than the length of the
5131 // array. The order of the code objects within a group is not preserved.
5133 // All code indexes used in the class are counted starting from the first
5134 // code object of the first group. In other words, code index 0 corresponds
5135 // to array index n = kCodesStartIndex.
5137 class DependentCode: public FixedArray {
5139 enum DependencyGroup {
5140 // Group of code that weakly embed this map and depend on being
5141 // deoptimized when the map is garbage collected.
5143 // Group of code that embed a transition to this map, and depend on being
5144 // deoptimized when the transition is replaced by a new version.
5146 // Group of code that omit run-time prototype checks for prototypes
5147 // described by this map. The group is deoptimized whenever an object
5148 // described by this map changes shape (and transitions to a new map),
5149 // possibly invalidating the assumptions embedded in the code.
5150 kPrototypeCheckGroup,
5151 // Group of code that depends on global property values in property cells
5152 // not being changed.
5153 kPropertyCellChangedGroup,
5154 // Group of code that omit run-time type checks for the field(s) introduced
5157 // Group of code that omit run-time type checks for initial maps of
5159 kInitialMapChangedGroup,
5160 // Group of code that depends on tenuring information in AllocationSites
5161 // not being changed.
5162 kAllocationSiteTenuringChangedGroup,
5163 // Group of code that depends on element transition information in
5164 // AllocationSites not being changed.
5165 kAllocationSiteTransitionChangedGroup
5168 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5170 // Array for holding the index of the first code object of each group.
5171 // The last element stores the total number of code objects.
5172 class GroupStartIndexes {
5174 explicit GroupStartIndexes(DependentCode* entries);
5175 void Recompute(DependentCode* entries);
5176 int at(int i) { return start_indexes_[i]; }
5177 int number_of_entries() { return start_indexes_[kGroupCount]; }
5179 int start_indexes_[kGroupCount + 1];
5182 bool Contains(DependencyGroup group, WeakCell* code_cell);
5184 static Handle<DependentCode> InsertCompilationDependencies(
5185 Handle<DependentCode> entries, DependencyGroup group,
5186 Handle<Foreign> info);
5188 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5189 DependencyGroup group,
5190 Handle<WeakCell> code_cell);
5192 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5193 WeakCell* code_cell);
5195 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5198 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5199 DependentCode::DependencyGroup group);
5201 bool MarkCodeForDeoptimization(Isolate* isolate,
5202 DependentCode::DependencyGroup group);
5204 // The following low-level accessors should only be used by this class
5205 // and the mark compact collector.
5206 inline int number_of_entries(DependencyGroup group);
5207 inline void set_number_of_entries(DependencyGroup group, int value);
5208 inline Object* object_at(int i);
5209 inline void set_object_at(int i, Object* object);
5210 inline void clear_at(int i);
5211 inline void copy(int from, int to);
5212 DECLARE_CAST(DependentCode)
5214 static const char* DependencyGroupName(DependencyGroup group);
5215 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5218 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5219 DependencyGroup group,
5220 Handle<Object> object);
5221 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5222 // Make a room at the end of the given group by moving out the first
5223 // code objects of the subsequent groups.
5224 inline void ExtendGroup(DependencyGroup group);
5225 // Compact by removing cleared weak cells and return true if there was
5226 // any cleared weak cell.
5228 static int Grow(int number_of_entries) {
5229 if (number_of_entries < 5) return number_of_entries + 1;
5230 return number_of_entries * 5 / 4;
5232 static const int kCodesStartIndex = kGroupCount;
5236 class PrototypeInfo;
5239 // All heap objects have a Map that describes their structure.
5240 // A Map contains information about:
5241 // - Size information about the object
5242 // - How to iterate over an object (for garbage collection)
5243 class Map: public HeapObject {
5246 // Size in bytes or kVariableSizeSentinel if instances do not have
5248 inline int instance_size();
5249 inline void set_instance_size(int value);
5251 // Only to clear an unused byte, remove once byte is used.
5252 inline void clear_unused();
5254 // [inobject_properties_or_constructor_function_index]: Provides access
5255 // to the inobject properties in case of JSObject maps, or the constructor
5256 // function index in case of primitive maps.
5257 inline int inobject_properties_or_constructor_function_index();
5258 inline void set_inobject_properties_or_constructor_function_index(int value);
5259 // Count of properties allocated in the object (JSObject only).
5260 inline int GetInObjectProperties();
5261 inline void SetInObjectProperties(int value);
5262 // Index of the constructor function in the native context (primitives only),
5263 // or the special sentinel value to indicate that there is no object wrapper
5264 // for the primitive (i.e. in case of null or undefined).
5265 static const int kNoConstructorFunctionIndex = 0;
5266 inline int GetConstructorFunctionIndex();
5267 inline void SetConstructorFunctionIndex(int value);
5270 inline InstanceType instance_type();
5271 inline void set_instance_type(InstanceType value);
5273 // Tells how many unused property fields are available in the
5274 // instance (only used for JSObject in fast mode).
5275 inline int unused_property_fields();
5276 inline void set_unused_property_fields(int value);
5279 inline byte bit_field() const;
5280 inline void set_bit_field(byte value);
5283 inline byte bit_field2() const;
5284 inline void set_bit_field2(byte value);
5287 inline uint32_t bit_field3() const;
5288 inline void set_bit_field3(uint32_t bits);
5290 class EnumLengthBits: public BitField<int,
5291 0, kDescriptorIndexBitCount> {}; // NOLINT
5292 class NumberOfOwnDescriptorsBits: public BitField<int,
5293 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5294 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5295 class DictionaryMap : public BitField<bool, 20, 1> {};
5296 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5297 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5298 class Deprecated : public BitField<bool, 23, 1> {};
5299 class IsUnstable : public BitField<bool, 24, 1> {};
5300 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5301 class IsStrong : public BitField<bool, 26, 1> {};
5304 // Keep this bit field at the very end for better code in
5305 // Builtins::kJSConstructStubGeneric stub.
5306 // This counter is used for in-object slack tracking and for map aging.
5307 // The in-object slack tracking is considered enabled when the counter is
5308 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5309 class Counter : public BitField<int, 28, 4> {};
5310 static const int kSlackTrackingCounterStart = 14;
5311 static const int kSlackTrackingCounterEnd = 8;
5312 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5313 static const int kRetainingCounterEnd = 0;
5315 // Tells whether the object in the prototype property will be used
5316 // for instances created from this function. If the prototype
5317 // property is set to a value that is not a JSObject, the prototype
5318 // property will not be used to create instances of the function.
5319 // See ECMA-262, 13.2.2.
5320 inline void set_non_instance_prototype(bool value);
5321 inline bool has_non_instance_prototype();
5323 // Tells whether function has special prototype property. If not, prototype
5324 // property will not be created when accessed (will return undefined),
5325 // and construction from this function will not be allowed.
5326 inline void set_function_with_prototype(bool value);
5327 inline bool function_with_prototype();
5329 // Tells whether the instance with this map should be ignored by the
5330 // Object.getPrototypeOf() function and the __proto__ accessor.
5331 inline void set_is_hidden_prototype();
5332 inline bool is_hidden_prototype() const;
5334 // Records and queries whether the instance has a named interceptor.
5335 inline void set_has_named_interceptor();
5336 inline bool has_named_interceptor();
5338 // Records and queries whether the instance has an indexed interceptor.
5339 inline void set_has_indexed_interceptor();
5340 inline bool has_indexed_interceptor();
5342 // Tells whether the instance is undetectable.
5343 // An undetectable object is a special class of JSObject: 'typeof' operator
5344 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5345 // a normal JS object. It is useful for implementing undetectable
5346 // document.all in Firefox & Safari.
5347 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5348 inline void set_is_undetectable();
5349 inline bool is_undetectable();
5351 // Tells whether the instance has a call-as-function handler.
5352 inline void set_is_observed();
5353 inline bool is_observed();
5355 // Tells whether the instance has a [[Call]] internal field.
5356 // This property is implemented according to ES6, section 7.2.3.
5357 inline void set_is_callable();
5358 inline bool is_callable() const;
5360 inline void set_is_strong();
5361 inline bool is_strong();
5362 inline void set_is_extensible(bool value);
5363 inline bool is_extensible();
5364 inline void set_is_prototype_map(bool value);
5365 inline bool is_prototype_map() const;
5367 inline void set_elements_kind(ElementsKind elements_kind);
5368 inline ElementsKind elements_kind();
5370 // Tells whether the instance has fast elements that are only Smis.
5371 inline bool has_fast_smi_elements();
5373 // Tells whether the instance has fast elements.
5374 inline bool has_fast_object_elements();
5375 inline bool has_fast_smi_or_object_elements();
5376 inline bool has_fast_double_elements();
5377 inline bool has_fast_elements();
5378 inline bool has_sloppy_arguments_elements();
5379 inline bool has_fixed_typed_array_elements();
5380 inline bool has_dictionary_elements();
5382 static bool IsValidElementsTransition(ElementsKind from_kind,
5383 ElementsKind to_kind);
5385 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5386 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5387 bool DictionaryElementsInPrototypeChainOnly();
5389 inline Map* ElementsTransitionMap();
5391 inline FixedArrayBase* GetInitialElements();
5393 // [raw_transitions]: Provides access to the transitions storage field.
5394 // Don't call set_raw_transitions() directly to overwrite transitions, use
5395 // the TransitionArray::ReplaceTransitions() wrapper instead!
5396 DECL_ACCESSORS(raw_transitions, Object)
5397 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5398 // (which prototype maps don't have).
5399 DECL_ACCESSORS(prototype_info, Object)
5400 // PrototypeInfo is created lazily using this helper (which installs it on
5401 // the given prototype's map).
5402 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5403 Handle<JSObject> prototype, Isolate* isolate);
5404 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5405 Handle<Map> prototype_map, Isolate* isolate);
5407 // [prototype chain validity cell]: Associated with a prototype object,
5408 // stored in that object's map's PrototypeInfo, indicates that prototype
5409 // chains through this object are currently valid. The cell will be
5410 // invalidated and replaced when the prototype chain changes.
5411 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5413 static const int kPrototypeChainValid = 0;
5414 static const int kPrototypeChainInvalid = 1;
5417 Map* FindFieldOwner(int descriptor);
5419 inline int GetInObjectPropertyOffset(int index);
5421 int NumberOfFields();
5423 // TODO(ishell): candidate with JSObject::MigrateToMap().
5424 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5425 int target_inobject, int target_unused,
5426 int* old_number_of_fields);
5427 // TODO(ishell): moveit!
5428 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5429 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5430 Handle<HeapType> type1,
5431 Handle<HeapType> type2,
5433 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5434 Representation new_representation,
5435 Handle<HeapType> new_field_type);
5436 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5437 PropertyKind new_kind,
5438 PropertyAttributes new_attributes,
5439 Representation new_representation,
5440 Handle<HeapType> new_field_type,
5441 StoreMode store_mode);
5442 static Handle<Map> CopyGeneralizeAllRepresentations(
5443 Handle<Map> map, int modify_index, StoreMode store_mode,
5444 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5446 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5447 int descriptor_number,
5448 Handle<Object> value);
5450 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5451 const char* reason);
5453 // Returns the constructor name (the name (possibly, inferred name) of the
5454 // function that was used to instantiate the object).
5455 String* constructor_name();
5457 // Tells whether the map is used for JSObjects in dictionary mode (ie
5458 // normalized objects, ie objects for which HasFastProperties returns false).
5459 // A map can never be used for both dictionary mode and fast mode JSObjects.
5460 // False by default and for HeapObjects that are not JSObjects.
5461 inline void set_dictionary_map(bool value);
5462 inline bool is_dictionary_map();
5464 // Tells whether the instance needs security checks when accessing its
5466 inline void set_is_access_check_needed(bool access_check_needed);
5467 inline bool is_access_check_needed();
5469 // Returns true if map has a non-empty stub code cache.
5470 inline bool has_code_cache();
5472 // [prototype]: implicit prototype object.
5473 DECL_ACCESSORS(prototype, Object)
5474 // TODO(jkummerow): make set_prototype private.
5475 static void SetPrototype(
5476 Handle<Map> map, Handle<Object> prototype,
5477 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5479 // [constructor]: points back to the function responsible for this map.
5480 // The field overlaps with the back pointer. All maps in a transition tree
5481 // have the same constructor, so maps with back pointers can walk the
5482 // back pointer chain until they find the map holding their constructor.
5483 DECL_ACCESSORS(constructor_or_backpointer, Object)
5484 inline Object* GetConstructor() const;
5485 inline void SetConstructor(Object* constructor,
5486 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5487 // [back pointer]: points back to the parent map from which a transition
5488 // leads to this map. The field overlaps with the constructor (see above).
5489 inline Object* GetBackPointer();
5490 inline void SetBackPointer(Object* value,
5491 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5493 // [instance descriptors]: describes the object.
5494 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5496 // [layout descriptor]: describes the object layout.
5497 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5498 // |layout descriptor| accessor which can be used from GC.
5499 inline LayoutDescriptor* layout_descriptor_gc_safe();
5500 inline bool HasFastPointerLayout() const;
5502 // |layout descriptor| accessor that is safe to call even when
5503 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5504 // |layout_descriptor| field at all).
5505 inline LayoutDescriptor* GetLayoutDescriptor();
5507 inline void UpdateDescriptors(DescriptorArray* descriptors,
5508 LayoutDescriptor* layout_descriptor);
5509 inline void InitializeDescriptors(DescriptorArray* descriptors,
5510 LayoutDescriptor* layout_descriptor);
5512 // [stub cache]: contains stubs compiled for this map.
5513 DECL_ACCESSORS(code_cache, Object)
5515 // [dependent code]: list of optimized codes that weakly embed this map.
5516 DECL_ACCESSORS(dependent_code, DependentCode)
5518 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5519 DECL_ACCESSORS(weak_cell_cache, Object)
5521 inline PropertyDetails GetLastDescriptorDetails();
5523 inline int LastAdded();
5525 inline int NumberOfOwnDescriptors();
5526 inline void SetNumberOfOwnDescriptors(int number);
5528 inline Cell* RetrieveDescriptorsPointer();
5530 inline int EnumLength();
5531 inline void SetEnumLength(int length);
5533 inline bool owns_descriptors();
5534 inline void set_owns_descriptors(bool owns_descriptors);
5535 inline void mark_unstable();
5536 inline bool is_stable();
5537 inline void set_migration_target(bool value);
5538 inline bool is_migration_target();
5539 inline void set_counter(int value);
5540 inline int counter();
5541 inline void deprecate();
5542 inline bool is_deprecated();
5543 inline bool CanBeDeprecated();
5544 // Returns a non-deprecated version of the input. If the input was not
5545 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5546 // is found by re-transitioning from the root of the transition tree using the
5547 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5549 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5551 // Returns a non-deprecated version of the input. This method may deprecate
5552 // existing maps along the way if encodings conflict. Not for use while
5553 // gathering type feedback. Use TryUpdate in those cases instead.
5554 static Handle<Map> Update(Handle<Map> map);
5556 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5557 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5558 Descriptor* descriptor,
5559 TransitionFlag flag);
5561 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5564 Handle<HeapType> type,
5565 PropertyAttributes attributes,
5566 Representation representation,
5567 TransitionFlag flag);
5569 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5572 Handle<Object> constant,
5573 PropertyAttributes attributes,
5574 TransitionFlag flag);
5576 // Returns a new map with all transitions dropped from the given map and
5577 // the ElementsKind set.
5578 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5579 ElementsKind to_kind);
5581 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5583 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5585 TransitionFlag flag);
5587 static Handle<Map> CopyForObserved(Handle<Map> map);
5589 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5590 PropertyAttributes attrs_to_add,
5591 Handle<Symbol> transition_marker,
5592 const char* reason);
5594 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5597 // Maximal number of fast properties. Used to restrict the number of map
5598 // transitions to avoid an explosion in the number of maps for objects used as
5600 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5601 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5603 Handle<Object> value,
5604 PropertyAttributes attributes,
5605 StoreFromKeyed store_mode);
5606 static Handle<Map> TransitionToAccessorProperty(
5607 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5608 Handle<Object> accessor, PropertyAttributes attributes);
5609 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5612 PropertyAttributes attributes);
5614 inline void AppendDescriptor(Descriptor* desc);
5616 // Returns a copy of the map, prepared for inserting into the transition
5617 // tree (if the |map| owns descriptors then the new one will share
5618 // descriptors with |map|).
5619 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5621 // Returns a copy of the map, with all transitions dropped from the
5622 // instance descriptors.
5623 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5624 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5626 // Returns the next free property index (only valid for FAST MODE).
5627 int NextFreePropertyIndex();
5629 // Returns the number of properties described in instance_descriptors
5630 // filtering out properties with the specified attributes.
5631 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5632 PropertyAttributes filter = NONE);
5636 // Code cache operations.
5638 // Clears the code cache.
5639 inline void ClearCodeCache(Heap* heap);
5641 // Update code cache.
5642 static void UpdateCodeCache(Handle<Map> map,
5646 // Extend the descriptor array of the map with the list of descriptors.
5647 // In case of duplicates, the latest descriptor is used.
5648 static void AppendCallbackDescriptors(Handle<Map> map,
5649 Handle<Object> descriptors);
5651 static inline int SlackForArraySize(int old_size, int size_limit);
5653 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5655 // Returns the found code or undefined if absent.
5656 Object* FindInCodeCache(Name* name, Code::Flags flags);
5658 // Returns the non-negative index of the code object if it is in the
5659 // cache and -1 otherwise.
5660 int IndexInCodeCache(Object* name, Code* code);
5662 // Removes a code object from the code cache at the given index.
5663 void RemoveFromCodeCache(Name* name, Code* code, int index);
5665 // Computes a hash value for this map, to be used in HashTables and such.
5668 // Returns the map that this map transitions to if its elements_kind
5669 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5670 // |safe_to_add_transitions| is set to false if adding transitions is not
5672 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5674 // Returns the transitioned map for this map with the most generic
5675 // elements_kind that's found in |candidates|, or null handle if no match is
5677 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5678 MapHandleList* candidates);
5680 inline bool CanTransition();
5682 inline bool IsPrimitiveMap();
5683 inline bool IsJSObjectMap();
5684 inline bool IsJSArrayMap();
5685 inline bool IsStringMap();
5686 inline bool IsJSProxyMap();
5687 inline bool IsJSGlobalProxyMap();
5688 inline bool IsJSGlobalObjectMap();
5689 inline bool IsGlobalObjectMap();
5691 inline bool CanOmitMapChecks();
5693 static void AddDependentCode(Handle<Map> map,
5694 DependentCode::DependencyGroup group,
5697 bool IsMapInArrayPrototypeChain();
5699 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5701 // Dispatched behavior.
5702 DECLARE_PRINTER(Map)
5703 DECLARE_VERIFIER(Map)
5706 void DictionaryMapVerify();
5707 void VerifyOmittedMapChecks();
5710 inline int visitor_id();
5711 inline void set_visitor_id(int visitor_id);
5713 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5714 Handle<Object> prototype,
5715 PrototypeOptimizationMode mode);
5717 static const int kMaxPreAllocatedPropertyFields = 255;
5719 // Layout description.
5720 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5721 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5722 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5723 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5724 static const int kConstructorOrBackPointerOffset =
5725 kPrototypeOffset + kPointerSize;
5726 // When there is only one transition, it is stored directly in this field;
5727 // otherwise a transition array is used.
5728 // For prototype maps, this slot is used to store this map's PrototypeInfo
5730 static const int kTransitionsOrPrototypeInfoOffset =
5731 kConstructorOrBackPointerOffset + kPointerSize;
5732 static const int kDescriptorsOffset =
5733 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5734 #if V8_DOUBLE_FIELDS_UNBOXING
5735 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5736 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5738 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5739 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5741 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5742 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5743 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5745 // Layout of pointer fields. Heap iteration code relies on them
5746 // being continuously allocated.
5747 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5748 static const int kPointerFieldsEndOffset = kSize;
5750 // Byte offsets within kInstanceSizesOffset.
5751 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5752 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5753 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5754 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5755 // Note there is one byte available for use here.
5756 static const int kUnusedByte = 2;
5757 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5758 static const int kVisitorIdByte = 3;
5759 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5761 // Byte offsets within kInstanceAttributesOffset attributes.
5762 #if V8_TARGET_LITTLE_ENDIAN
5763 // Order instance type and bit field together such that they can be loaded
5764 // together as a 16-bit word with instance type in the lower 8 bits regardless
5765 // of endianess. Also provide endian-independent offset to that 16-bit word.
5766 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5767 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5769 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5770 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5772 static const int kInstanceTypeAndBitFieldOffset =
5773 kInstanceAttributesOffset + 0;
5774 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5775 static const int kUnusedPropertyFieldsByte = 3;
5776 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5778 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5779 Internals::kMapInstanceTypeAndBitFieldOffset);
5781 // Bit positions for bit field.
5782 static const int kHasNonInstancePrototype = 0;
5783 static const int kIsCallable = 1;
5784 static const int kHasNamedInterceptor = 2;
5785 static const int kHasIndexedInterceptor = 3;
5786 static const int kIsUndetectable = 4;
5787 static const int kIsObserved = 5;
5788 static const int kIsAccessCheckNeeded = 6;
5789 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5791 // Bit positions for bit field 2
5792 static const int kIsExtensible = 0;
5793 static const int kStringWrapperSafeForDefaultValueOf = 1;
5794 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5795 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5797 // Derived values from bit field 2
5798 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5799 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5800 static const int8_t kMaximumBitField2FastSmiElementValue =
5801 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5802 Map::ElementsKindBits::kShift) - 1;
5803 static const int8_t kMaximumBitField2FastHoleyElementValue =
5804 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5805 Map::ElementsKindBits::kShift) - 1;
5806 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5807 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5808 Map::ElementsKindBits::kShift) - 1;
5810 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5811 kPointerFieldsEndOffset,
5812 kSize> BodyDescriptor;
5814 // Compares this map to another to see if they describe equivalent objects.
5815 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5816 // it had exactly zero inobject properties.
5817 // The "shared" flags of both this map and |other| are ignored.
5818 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5820 // Returns true if given field is unboxed double.
5821 inline bool IsUnboxedDoubleField(FieldIndex index);
5824 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5825 static void TraceAllTransitions(Map* map);
5828 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5829 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5830 Handle<LayoutDescriptor> layout_descriptor);
5833 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5834 Handle<Name> name, SimpleTransitionFlag flag);
5836 bool EquivalentToForTransition(Map* other);
5837 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5838 static Handle<Map> ShareDescriptor(Handle<Map> map,
5839 Handle<DescriptorArray> descriptors,
5840 Descriptor* descriptor);
5841 static Handle<Map> CopyInstallDescriptors(
5842 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5843 Handle<LayoutDescriptor> layout_descriptor);
5844 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5845 Descriptor* descriptor,
5846 TransitionFlag flag);
5847 static Handle<Map> CopyReplaceDescriptors(
5848 Handle<Map> map, Handle<DescriptorArray> descriptors,
5849 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5850 MaybeHandle<Name> maybe_name, const char* reason,
5851 SimpleTransitionFlag simple_flag);
5853 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5854 Handle<DescriptorArray> descriptors,
5855 Descriptor* descriptor,
5857 TransitionFlag flag);
5858 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5859 Handle<Map> map, int descriptor, PropertyKind kind,
5860 PropertyAttributes attributes, const char** reason);
5862 static Handle<Map> CopyNormalized(Handle<Map> map,
5863 PropertyNormalizationMode mode);
5865 // Fires when the layout of an object with a leaf map changes.
5866 // This includes adding transitions to the leaf map or changing
5867 // the descriptor array.
5868 inline void NotifyLeafMapLayoutChange();
5870 void DeprecateTransitionTree();
5871 bool DeprecateTarget(PropertyKind kind, Name* key,
5872 PropertyAttributes attributes,
5873 DescriptorArray* new_descriptors,
5874 LayoutDescriptor* new_layout_descriptor);
5876 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5878 // Update field type of the given descriptor to new representation and new
5879 // type. The type must be prepared for storing in descriptor array:
5880 // it must be either a simple type or a map wrapped in a weak cell.
5881 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5882 Representation new_representation,
5883 Handle<Object> new_wrapped_type);
5885 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5886 PropertyAttributes attributes);
5887 void PrintGeneralization(FILE* file,
5892 bool constant_to_field,
5893 Representation old_representation,
5894 Representation new_representation,
5895 HeapType* old_field_type,
5896 HeapType* new_field_type);
5898 static const int kFastPropertiesSoftLimit = 12;
5899 static const int kMaxFastProperties = 128;
5901 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5905 // An abstract superclass, a marker class really, for simple structure classes.
5906 // It doesn't carry much functionality but allows struct classes to be
5907 // identified in the type system.
5908 class Struct: public HeapObject {
5910 inline void InitializeBody(int object_size);
5911 DECLARE_CAST(Struct)
5915 // A simple one-element struct, useful where smis need to be boxed.
5916 class Box : public Struct {
5918 // [value]: the boxed contents.
5919 DECL_ACCESSORS(value, Object)
5923 // Dispatched behavior.
5924 DECLARE_PRINTER(Box)
5925 DECLARE_VERIFIER(Box)
5927 static const int kValueOffset = HeapObject::kHeaderSize;
5928 static const int kSize = kValueOffset + kPointerSize;
5931 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5935 // Container for metadata stored on each prototype map.
5936 class PrototypeInfo : public Struct {
5938 static const int UNREGISTERED = -1;
5940 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5941 // or Smi(0) if uninitialized.
5942 DECL_ACCESSORS(prototype_users, Object)
5943 // [registry_slot]: Slot in prototype's user registry where this user
5944 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5945 inline int registry_slot() const;
5946 inline void set_registry_slot(int slot);
5947 // [validity_cell]: Cell containing the validity bit for prototype chains
5948 // going through this object, or Smi(0) if uninitialized.
5949 DECL_ACCESSORS(validity_cell, Object)
5950 // [constructor_name]: User-friendly name of the original constructor.
5951 DECL_ACCESSORS(constructor_name, Object)
5953 DECLARE_CAST(PrototypeInfo)
5955 // Dispatched behavior.
5956 DECLARE_PRINTER(PrototypeInfo)
5957 DECLARE_VERIFIER(PrototypeInfo)
5959 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5960 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5961 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5962 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5963 static const int kSize = kConstructorNameOffset + kPointerSize;
5966 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5970 // Pair used to store both a ScopeInfo and an extension object in the extension
5971 // slot of a block context. Needed in the rare case where a declaration block
5972 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5973 // a sloppy direct eval. (In no other case both are needed at the same time.)
5974 class SloppyBlockWithEvalContextExtension : public Struct {
5976 // [scope_info]: Scope info.
5977 DECL_ACCESSORS(scope_info, ScopeInfo)
5978 // [extension]: Extension object.
5979 DECL_ACCESSORS(extension, JSObject)
5981 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5983 // Dispatched behavior.
5984 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5985 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5987 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5988 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5989 static const int kSize = kExtensionOffset + kPointerSize;
5992 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5996 // Script describes a script which has been added to the VM.
5997 class Script: public Struct {
6006 // Script compilation types.
6007 enum CompilationType {
6008 COMPILATION_TYPE_HOST = 0,
6009 COMPILATION_TYPE_EVAL = 1
6012 // Script compilation state.
6013 enum CompilationState {
6014 COMPILATION_STATE_INITIAL = 0,
6015 COMPILATION_STATE_COMPILED = 1
6018 // [source]: the script source.
6019 DECL_ACCESSORS(source, Object)
6021 // [name]: the script name.
6022 DECL_ACCESSORS(name, Object)
6024 // [id]: the script id.
6025 DECL_ACCESSORS(id, Smi)
6027 // [line_offset]: script line offset in resource from where it was extracted.
6028 DECL_ACCESSORS(line_offset, Smi)
6030 // [column_offset]: script column offset in resource from where it was
6032 DECL_ACCESSORS(column_offset, Smi)
6034 // [context_data]: context data for the context this script was compiled in.
6035 DECL_ACCESSORS(context_data, Object)
6037 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6038 DECL_ACCESSORS(wrapper, HeapObject)
6040 // [type]: the script type.
6041 DECL_ACCESSORS(type, Smi)
6043 // [line_ends]: FixedArray of line ends positions.
6044 DECL_ACCESSORS(line_ends, Object)
6046 // [eval_from_shared]: for eval scripts the shared funcion info for the
6047 // function from which eval was called.
6048 DECL_ACCESSORS(eval_from_shared, Object)
6050 // [eval_from_instructions_offset]: the instruction offset in the code for the
6051 // function from which eval was called where eval was called.
6052 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6054 // [shared_function_infos]: weak fixed array containing all shared
6055 // function infos created from this script.
6056 DECL_ACCESSORS(shared_function_infos, Object)
6058 // [flags]: Holds an exciting bitfield.
6059 DECL_ACCESSORS(flags, Smi)
6061 // [source_url]: sourceURL from magic comment
6062 DECL_ACCESSORS(source_url, Object)
6064 // [source_url]: sourceMappingURL magic comment
6065 DECL_ACCESSORS(source_mapping_url, Object)
6067 // [compilation_type]: how the the script was compiled. Encoded in the
6069 inline CompilationType compilation_type();
6070 inline void set_compilation_type(CompilationType type);
6072 // [compilation_state]: determines whether the script has already been
6073 // compiled. Encoded in the 'flags' field.
6074 inline CompilationState compilation_state();
6075 inline void set_compilation_state(CompilationState state);
6077 // [hide_source]: determines whether the script source can be exposed as
6078 // function source. Encoded in the 'flags' field.
6079 inline bool hide_source();
6080 inline void set_hide_source(bool value);
6082 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6083 // and used by the embedder to make decisions about the script. V8 just passes
6084 // this through. Encoded in the 'flags' field.
6085 inline v8::ScriptOriginOptions origin_options();
6086 inline void set_origin_options(ScriptOriginOptions origin_options);
6088 DECLARE_CAST(Script)
6090 // If script source is an external string, check that the underlying
6091 // resource is accessible. Otherwise, always return true.
6092 inline bool HasValidSource();
6094 // Convert code position into column number.
6095 static int GetColumnNumber(Handle<Script> script, int code_pos);
6097 // Convert code position into (zero-based) line number.
6098 // The non-handlified version does not allocate, but may be much slower.
6099 static int GetLineNumber(Handle<Script> script, int code_pos);
6100 int GetLineNumber(int code_pos);
6102 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6104 // Init line_ends array with code positions of line ends inside script source.
6105 static void InitLineEnds(Handle<Script> script);
6107 // Get the JS object wrapping the given script; create it if none exists.
6108 static Handle<JSObject> GetWrapper(Handle<Script> script);
6110 // Look through the list of existing shared function infos to find one
6111 // that matches the function literal. Return empty handle if not found.
6112 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6114 // Iterate over all script objects on the heap.
6117 explicit Iterator(Isolate* isolate);
6121 WeakFixedArray::Iterator iterator_;
6122 DISALLOW_COPY_AND_ASSIGN(Iterator);
6125 // Dispatched behavior.
6126 DECLARE_PRINTER(Script)
6127 DECLARE_VERIFIER(Script)
6129 static const int kSourceOffset = HeapObject::kHeaderSize;
6130 static const int kNameOffset = kSourceOffset + kPointerSize;
6131 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6132 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6133 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6134 static const int kWrapperOffset = kContextOffset + kPointerSize;
6135 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6136 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6137 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6138 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6139 static const int kEvalFrominstructionsOffsetOffset =
6140 kEvalFromSharedOffset + kPointerSize;
6141 static const int kSharedFunctionInfosOffset =
6142 kEvalFrominstructionsOffsetOffset + kPointerSize;
6143 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6144 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6145 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6146 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6149 int GetLineNumberWithArray(int code_pos);
6151 // Bit positions in the flags field.
6152 static const int kCompilationTypeBit = 0;
6153 static const int kCompilationStateBit = 1;
6154 static const int kHideSourceBit = 2;
6155 static const int kOriginOptionsShift = 3;
6156 static const int kOriginOptionsSize = 3;
6157 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6158 << kOriginOptionsShift;
6160 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6164 // List of builtin functions we want to identify to improve code
6167 // Each entry has a name of a global object property holding an object
6168 // optionally followed by ".prototype", a name of a builtin function
6169 // on the object (the one the id is set for), and a label.
6171 // Installation of ids for the selected builtin functions is handled
6172 // by the bootstrapper.
6173 #define FUNCTIONS_WITH_ID_LIST(V) \
6174 V(Array.prototype, indexOf, ArrayIndexOf) \
6175 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6176 V(Array.prototype, push, ArrayPush) \
6177 V(Array.prototype, pop, ArrayPop) \
6178 V(Array.prototype, shift, ArrayShift) \
6179 V(Function.prototype, apply, FunctionApply) \
6180 V(Function.prototype, call, FunctionCall) \
6181 V(String.prototype, charCodeAt, StringCharCodeAt) \
6182 V(String.prototype, charAt, StringCharAt) \
6183 V(String, fromCharCode, StringFromCharCode) \
6184 V(Math, random, MathRandom) \
6185 V(Math, floor, MathFloor) \
6186 V(Math, round, MathRound) \
6187 V(Math, ceil, MathCeil) \
6188 V(Math, abs, MathAbs) \
6189 V(Math, log, MathLog) \
6190 V(Math, exp, MathExp) \
6191 V(Math, sqrt, MathSqrt) \
6192 V(Math, pow, MathPow) \
6193 V(Math, max, MathMax) \
6194 V(Math, min, MathMin) \
6195 V(Math, cos, MathCos) \
6196 V(Math, sin, MathSin) \
6197 V(Math, tan, MathTan) \
6198 V(Math, acos, MathAcos) \
6199 V(Math, asin, MathAsin) \
6200 V(Math, atan, MathAtan) \
6201 V(Math, atan2, MathAtan2) \
6202 V(Math, imul, MathImul) \
6203 V(Math, clz32, MathClz32) \
6204 V(Math, fround, MathFround)
6206 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6207 V(Atomics, load, AtomicsLoad) \
6208 V(Atomics, store, AtomicsStore)
6210 enum BuiltinFunctionId {
6212 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6214 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6215 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6216 #undef DECLARE_FUNCTION_ID
6217 // Fake id for a special case of Math.pow. Note, it continues the
6218 // list of math functions.
6223 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6224 // that both {code} and {literals} can be NULL to pass search result status.
6225 struct CodeAndLiterals {
6226 Code* code; // Cached optimized code.
6227 FixedArray* literals; // Cached literals array.
6231 // SharedFunctionInfo describes the JSFunction information that can be
6232 // shared by multiple instances of the function.
6233 class SharedFunctionInfo: public HeapObject {
6235 // [name]: Function name.
6236 DECL_ACCESSORS(name, Object)
6238 // [code]: Function code.
6239 DECL_ACCESSORS(code, Code)
6240 inline void ReplaceCode(Code* code);
6242 // [optimized_code_map]: Map from native context to optimized code
6243 // and a shared literals array or Smi(0) if none.
6244 DECL_ACCESSORS(optimized_code_map, Object)
6246 // Returns entry from optimized code map for specified context and OSR entry.
6247 // Note that {code == nullptr} indicates no matching entry has been found,
6248 // whereas {literals == nullptr} indicates the code is context-independent.
6249 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6250 BailoutId osr_ast_id);
6252 // Clear optimized code map.
6253 void ClearOptimizedCodeMap();
6255 // Removed a specific optimized code object from the optimized code map.
6256 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6258 // Trims the optimized code map after entries have been removed.
6259 void TrimOptimizedCodeMap(int shrink_by);
6261 // Add a new entry to the optimized code map for context-independent code.
6262 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6265 // Add a new entry to the optimized code map for context-dependent code.
6266 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6267 Handle<Context> native_context,
6269 Handle<FixedArray> literals,
6270 BailoutId osr_ast_id);
6272 // Set up the link between shared function info and the script. The shared
6273 // function info is added to the list on the script.
6274 static void SetScript(Handle<SharedFunctionInfo> shared,
6275 Handle<Object> script_object);
6277 // Layout description of the optimized code map.
6278 static const int kNextMapIndex = 0;
6279 static const int kSharedCodeIndex = 1;
6280 static const int kEntriesStart = 2;
6281 static const int kContextOffset = 0;
6282 static const int kCachedCodeOffset = 1;
6283 static const int kLiteralsOffset = 2;
6284 static const int kOsrAstIdOffset = 3;
6285 static const int kEntryLength = 4;
6286 static const int kInitialLength = kEntriesStart + kEntryLength;
6288 // [scope_info]: Scope info.
6289 DECL_ACCESSORS(scope_info, ScopeInfo)
6291 // [construct stub]: Code stub for constructing instances of this function.
6292 DECL_ACCESSORS(construct_stub, Code)
6294 // Returns if this function has been compiled to native code yet.
6295 inline bool is_compiled();
6297 // [length]: The function length - usually the number of declared parameters.
6298 // Use up to 2^30 parameters.
6299 inline int length() const;
6300 inline void set_length(int value);
6302 // [internal formal parameter count]: The declared number of parameters.
6303 // For subclass constructors, also includes new.target.
6304 // The size of function's frame is internal_formal_parameter_count + 1.
6305 inline int internal_formal_parameter_count() const;
6306 inline void set_internal_formal_parameter_count(int value);
6308 // Set the formal parameter count so the function code will be
6309 // called without using argument adaptor frames.
6310 inline void DontAdaptArguments();
6312 // [expected_nof_properties]: Expected number of properties for the function.
6313 inline int expected_nof_properties() const;
6314 inline void set_expected_nof_properties(int value);
6316 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6317 // (increasingly) from crankshafted code where sufficient feedback isn't
6319 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6321 // Unconditionally clear the type feedback vector (including vector ICs).
6322 void ClearTypeFeedbackInfo();
6324 // Clear the type feedback vector with a more subtle policy at GC time.
6325 void ClearTypeFeedbackInfoAtGCTime();
6328 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6329 // even if the GC moves this SharedFunctionInfo.
6330 inline int unique_id() const;
6331 inline void set_unique_id(int value);
6334 // [instance class name]: class name for instances.
6335 DECL_ACCESSORS(instance_class_name, Object)
6337 // [function data]: This field holds some additional data for function.
6338 // Currently it has one of:
6339 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6340 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6341 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6342 // In the long run we don't want all functions to have this field but
6343 // we can fix that when we have a better model for storing hidden data
6345 DECL_ACCESSORS(function_data, Object)
6347 inline bool IsApiFunction();
6348 inline FunctionTemplateInfo* get_api_func_data();
6349 inline bool HasBuiltinFunctionId();
6350 inline BuiltinFunctionId builtin_function_id();
6351 inline bool HasBytecodeArray();
6352 inline BytecodeArray* bytecode_array();
6354 // [script info]: Script from which the function originates.
6355 DECL_ACCESSORS(script, Object)
6357 // [num_literals]: Number of literals used by this function.
6358 inline int num_literals() const;
6359 inline void set_num_literals(int value);
6361 // [start_position_and_type]: Field used to store both the source code
6362 // position, whether or not the function is a function expression,
6363 // and whether or not the function is a toplevel function. The two
6364 // least significants bit indicates whether the function is an
6365 // expression and the rest contains the source code position.
6366 inline int start_position_and_type() const;
6367 inline void set_start_position_and_type(int value);
6369 // The function is subject to debugging if a debug info is attached.
6370 inline bool HasDebugInfo();
6371 inline DebugInfo* GetDebugInfo();
6373 // A function has debug code if the compiled code has debug break slots.
6374 inline bool HasDebugCode();
6376 // [debug info]: Debug information.
6377 DECL_ACCESSORS(debug_info, Object)
6379 // [inferred name]: Name inferred from variable or property
6380 // assignment of this function. Used to facilitate debugging and
6381 // profiling of JavaScript code written in OO style, where almost
6382 // all functions are anonymous but are assigned to object
6384 DECL_ACCESSORS(inferred_name, String)
6386 // The function's name if it is non-empty, otherwise the inferred name.
6387 String* DebugName();
6389 // Position of the 'function' token in the script source.
6390 inline int function_token_position() const;
6391 inline void set_function_token_position(int function_token_position);
6393 // Position of this function in the script source.
6394 inline int start_position() const;
6395 inline void set_start_position(int start_position);
6397 // End position of this function in the script source.
6398 inline int end_position() const;
6399 inline void set_end_position(int end_position);
6401 // Is this function a function expression in the source code.
6402 DECL_BOOLEAN_ACCESSORS(is_expression)
6404 // Is this function a top-level function (scripts, evals).
6405 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6407 // Bit field containing various information collected by the compiler to
6408 // drive optimization.
6409 inline int compiler_hints() const;
6410 inline void set_compiler_hints(int value);
6412 inline int ast_node_count() const;
6413 inline void set_ast_node_count(int count);
6415 inline int profiler_ticks() const;
6416 inline void set_profiler_ticks(int ticks);
6418 // Inline cache age is used to infer whether the function survived a context
6419 // disposal or not. In the former case we reset the opt_count.
6420 inline int ic_age();
6421 inline void set_ic_age(int age);
6423 // Indicates if this function can be lazy compiled.
6424 // This is used to determine if we can safely flush code from a function
6425 // when doing GC if we expect that the function will no longer be used.
6426 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6428 // Indicates if this function can be lazy compiled without a context.
6429 // This is used to determine if we can force compilation without reaching
6430 // the function through program execution but through other means (e.g. heap
6431 // iteration by the debugger).
6432 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6434 // Indicates whether optimizations have been disabled for this
6435 // shared function info. If a function is repeatedly optimized or if
6436 // we cannot optimize the function we disable optimization to avoid
6437 // spending time attempting to optimize it again.
6438 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6440 // Indicates the language mode.
6441 inline LanguageMode language_mode();
6442 inline void set_language_mode(LanguageMode language_mode);
6444 // False if the function definitely does not allocate an arguments object.
6445 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6447 // Indicates that this function uses a super property (or an eval that may
6448 // use a super property).
6449 // This is needed to set up the [[HomeObject]] on the function instance.
6450 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6452 // True if the function has any duplicated parameter names.
6453 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6455 // Indicates whether the function is a native function.
6456 // These needs special treatment in .call and .apply since
6457 // null passed as the receiver should not be translated to the
6459 DECL_BOOLEAN_ACCESSORS(native)
6461 // Indicate that this function should always be inlined in optimized code.
6462 DECL_BOOLEAN_ACCESSORS(force_inline)
6464 // Indicates that the function was created by the Function function.
6465 // Though it's anonymous, toString should treat it as if it had the name
6466 // "anonymous". We don't set the name itself so that the system does not
6467 // see a binding for it.
6468 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6470 // Indicates whether the function is a bound function created using
6471 // the bind function.
6472 DECL_BOOLEAN_ACCESSORS(bound)
6474 // Indicates that the function is anonymous (the name field can be set
6475 // through the API, which does not change this flag).
6476 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6478 // Is this a function or top-level/eval code.
6479 DECL_BOOLEAN_ACCESSORS(is_function)
6481 // Indicates that code for this function cannot be compiled with Crankshaft.
6482 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6484 // Indicates that code for this function cannot be flushed.
6485 DECL_BOOLEAN_ACCESSORS(dont_flush)
6487 // Indicates that this function is a generator.
6488 DECL_BOOLEAN_ACCESSORS(is_generator)
6490 // Indicates that this function is an arrow function.
6491 DECL_BOOLEAN_ACCESSORS(is_arrow)
6493 // Indicates that this function is a concise method.
6494 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6496 // Indicates that this function is an accessor (getter or setter).
6497 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6499 // Indicates that this function is a default constructor.
6500 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6502 // Indicates that this function is an asm function.
6503 DECL_BOOLEAN_ACCESSORS(asm_function)
6505 // Indicates that the the shared function info is deserialized from cache.
6506 DECL_BOOLEAN_ACCESSORS(deserialized)
6508 // Indicates that the the shared function info has never been compiled before.
6509 DECL_BOOLEAN_ACCESSORS(never_compiled)
6511 inline FunctionKind kind();
6512 inline void set_kind(FunctionKind kind);
6514 // Indicates whether or not the code in the shared function support
6516 inline bool has_deoptimization_support();
6518 // Enable deoptimization support through recompiled code.
6519 void EnableDeoptimizationSupport(Code* recompiled);
6521 // Disable (further) attempted optimization of all functions sharing this
6522 // shared function info.
6523 void DisableOptimization(BailoutReason reason);
6525 inline BailoutReason disable_optimization_reason();
6527 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6528 // code, returns whether it asserted (i.e., always true if assertions are
6530 bool VerifyBailoutId(BailoutId id);
6532 // [source code]: Source code for the function.
6533 bool HasSourceCode() const;
6534 Handle<Object> GetSourceCode();
6536 // Number of times the function was optimized.
6537 inline int opt_count();
6538 inline void set_opt_count(int opt_count);
6540 // Number of times the function was deoptimized.
6541 inline void set_deopt_count(int value);
6542 inline int deopt_count();
6543 inline void increment_deopt_count();
6545 // Number of time we tried to re-enable optimization after it
6546 // was disabled due to high number of deoptimizations.
6547 inline void set_opt_reenable_tries(int value);
6548 inline int opt_reenable_tries();
6550 inline void TryReenableOptimization();
6552 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6553 inline void set_counters(int value);
6554 inline int counters() const;
6556 // Stores opt_count and bailout_reason as bit-fields.
6557 inline void set_opt_count_and_bailout_reason(int value);
6558 inline int opt_count_and_bailout_reason() const;
6560 inline void set_disable_optimization_reason(BailoutReason reason);
6562 // Tells whether this function should be subject to debugging.
6563 inline bool IsSubjectToDebugging();
6565 // Whether this function is defined in native code or extensions.
6566 inline bool IsBuiltin();
6568 // Check whether or not this function is inlineable.
6569 bool IsInlineable();
6571 // Source size of this function.
6574 // Calculate the instance size.
6575 int CalculateInstanceSize();
6577 // Calculate the number of in-object properties.
6578 int CalculateInObjectProperties();
6580 inline bool has_simple_parameters();
6582 // Initialize a SharedFunctionInfo from a parsed function literal.
6583 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6584 FunctionLiteral* lit);
6586 // Dispatched behavior.
6587 DECLARE_PRINTER(SharedFunctionInfo)
6588 DECLARE_VERIFIER(SharedFunctionInfo)
6590 void ResetForNewContext(int new_ic_age);
6592 // Iterate over all shared function infos that are created from a script.
6593 // That excludes shared function infos created for API functions and C++
6597 explicit Iterator(Isolate* isolate);
6598 SharedFunctionInfo* Next();
6603 Script::Iterator script_iterator_;
6604 WeakFixedArray::Iterator sfi_iterator_;
6605 DisallowHeapAllocation no_gc_;
6606 DISALLOW_COPY_AND_ASSIGN(Iterator);
6609 DECLARE_CAST(SharedFunctionInfo)
6612 static const int kDontAdaptArgumentsSentinel = -1;
6614 // Layout description.
6616 static const int kNameOffset = HeapObject::kHeaderSize;
6617 static const int kCodeOffset = kNameOffset + kPointerSize;
6618 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6619 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6620 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6621 static const int kInstanceClassNameOffset =
6622 kConstructStubOffset + kPointerSize;
6623 static const int kFunctionDataOffset =
6624 kInstanceClassNameOffset + kPointerSize;
6625 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6626 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6627 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6628 static const int kFeedbackVectorOffset =
6629 kInferredNameOffset + kPointerSize;
6631 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6632 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6634 // Just to not break the postmortrem support with conditional offsets
6635 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6636 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6639 #if V8_HOST_ARCH_32_BIT
6641 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6642 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6643 static const int kExpectedNofPropertiesOffset =
6644 kFormalParameterCountOffset + kPointerSize;
6645 static const int kNumLiteralsOffset =
6646 kExpectedNofPropertiesOffset + kPointerSize;
6647 static const int kStartPositionAndTypeOffset =
6648 kNumLiteralsOffset + kPointerSize;
6649 static const int kEndPositionOffset =
6650 kStartPositionAndTypeOffset + kPointerSize;
6651 static const int kFunctionTokenPositionOffset =
6652 kEndPositionOffset + kPointerSize;
6653 static const int kCompilerHintsOffset =
6654 kFunctionTokenPositionOffset + kPointerSize;
6655 static const int kOptCountAndBailoutReasonOffset =
6656 kCompilerHintsOffset + kPointerSize;
6657 static const int kCountersOffset =
6658 kOptCountAndBailoutReasonOffset + kPointerSize;
6659 static const int kAstNodeCountOffset =
6660 kCountersOffset + kPointerSize;
6661 static const int kProfilerTicksOffset =
6662 kAstNodeCountOffset + kPointerSize;
6665 static const int kSize = kProfilerTicksOffset + kPointerSize;
6667 // The only reason to use smi fields instead of int fields
6668 // is to allow iteration without maps decoding during
6669 // garbage collections.
6670 // To avoid wasting space on 64-bit architectures we use
6671 // the following trick: we group integer fields into pairs
6672 // The least significant integer in each pair is shifted left by 1.
6673 // By doing this we guarantee that LSB of each kPointerSize aligned
6674 // word is not set and thus this word cannot be treated as pointer
6675 // to HeapObject during old space traversal.
6676 #if V8_TARGET_LITTLE_ENDIAN
6677 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6678 static const int kFormalParameterCountOffset =
6679 kLengthOffset + kIntSize;
6681 static const int kExpectedNofPropertiesOffset =
6682 kFormalParameterCountOffset + kIntSize;
6683 static const int kNumLiteralsOffset =
6684 kExpectedNofPropertiesOffset + kIntSize;
6686 static const int kEndPositionOffset =
6687 kNumLiteralsOffset + kIntSize;
6688 static const int kStartPositionAndTypeOffset =
6689 kEndPositionOffset + kIntSize;
6691 static const int kFunctionTokenPositionOffset =
6692 kStartPositionAndTypeOffset + kIntSize;
6693 static const int kCompilerHintsOffset =
6694 kFunctionTokenPositionOffset + kIntSize;
6696 static const int kOptCountAndBailoutReasonOffset =
6697 kCompilerHintsOffset + kIntSize;
6698 static const int kCountersOffset =
6699 kOptCountAndBailoutReasonOffset + kIntSize;
6701 static const int kAstNodeCountOffset =
6702 kCountersOffset + kIntSize;
6703 static const int kProfilerTicksOffset =
6704 kAstNodeCountOffset + kIntSize;
6707 static const int kSize = kProfilerTicksOffset + kIntSize;
6709 #elif V8_TARGET_BIG_ENDIAN
6710 static const int kFormalParameterCountOffset =
6711 kLastPointerFieldOffset + kPointerSize;
6712 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6714 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6715 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6717 static const int kStartPositionAndTypeOffset =
6718 kExpectedNofPropertiesOffset + kIntSize;
6719 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6721 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6722 static const int kFunctionTokenPositionOffset =
6723 kCompilerHintsOffset + kIntSize;
6725 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6726 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6728 static const int kProfilerTicksOffset =
6729 kOptCountAndBailoutReasonOffset + kIntSize;
6730 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6733 static const int kSize = kAstNodeCountOffset + kIntSize;
6736 #error Unknown byte ordering
6737 #endif // Big endian
6741 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6743 typedef FixedBodyDescriptor<kNameOffset,
6744 kLastPointerFieldOffset + kPointerSize,
6745 kSize> BodyDescriptor;
6747 // Bit positions in start_position_and_type.
6748 // The source code start position is in the 30 most significant bits of
6749 // the start_position_and_type field.
6750 static const int kIsExpressionBit = 0;
6751 static const int kIsTopLevelBit = 1;
6752 static const int kStartPositionShift = 2;
6753 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6755 // Bit positions in compiler_hints.
6756 enum CompilerHints {
6757 kAllowLazyCompilation,
6758 kAllowLazyCompilationWithoutContext,
6759 kOptimizationDisabled,
6761 kStrictModeFunction,
6762 kStrongModeFunction,
6765 kHasDuplicateParameters,
6769 kNameShouldPrintAsAnonymous,
6776 kIsAccessorFunction,
6777 kIsDefaultConstructor,
6778 kIsSubclassConstructor,
6784 kCompilerHintsCount // Pseudo entry
6786 // Add hints for other modes when they're added.
6787 STATIC_ASSERT(LANGUAGE_END == 3);
6789 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6791 class DeoptCountBits : public BitField<int, 0, 4> {};
6792 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6793 class ICAgeBits : public BitField<int, 22, 8> {};
6795 class OptCountBits : public BitField<int, 0, 22> {};
6796 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6799 #if V8_HOST_ARCH_32_BIT
6800 // On 32 bit platforms, compiler hints is a smi.
6801 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6802 static const int kCompilerHintsSize = kPointerSize;
6804 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6805 static const int kCompilerHintsSmiTagSize = 0;
6806 static const int kCompilerHintsSize = kIntSize;
6809 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6810 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6813 // Constants for optimizing codegen for strict mode function and
6815 // Allows to use byte-width instructions.
6816 static const int kStrictModeBitWithinByte =
6817 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6818 static const int kStrongModeBitWithinByte =
6819 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6821 static const int kNativeBitWithinByte =
6822 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6824 static const int kBoundBitWithinByte =
6825 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6827 #if defined(V8_TARGET_LITTLE_ENDIAN)
6828 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6829 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6830 static const int kStrongModeByteOffset =
6831 kCompilerHintsOffset +
6832 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6833 static const int kNativeByteOffset = kCompilerHintsOffset +
6834 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6835 static const int kBoundByteOffset =
6836 kCompilerHintsOffset +
6837 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6838 #elif defined(V8_TARGET_BIG_ENDIAN)
6839 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6840 (kCompilerHintsSize - 1) -
6841 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6842 static const int kStrongModeByteOffset =
6843 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6844 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6845 static const int kNativeByteOffset = kCompilerHintsOffset +
6846 (kCompilerHintsSize - 1) -
6847 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6848 static const int kBoundByteOffset =
6849 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6850 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6852 #error Unknown byte ordering
6856 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6860 // Printing support.
6861 struct SourceCodeOf {
6862 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6863 : value(v), max_length(max) {}
6864 const SharedFunctionInfo* value;
6869 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6872 class JSGeneratorObject: public JSObject {
6874 // [function]: The function corresponding to this generator object.
6875 DECL_ACCESSORS(function, JSFunction)
6877 // [context]: The context of the suspended computation.
6878 DECL_ACCESSORS(context, Context)
6880 // [receiver]: The receiver of the suspended computation.
6881 DECL_ACCESSORS(receiver, Object)
6883 // [continuation]: Offset into code of continuation.
6885 // A positive offset indicates a suspended generator. The special
6886 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6887 // cannot be resumed.
6888 inline int continuation() const;
6889 inline void set_continuation(int continuation);
6890 inline bool is_closed();
6891 inline bool is_executing();
6892 inline bool is_suspended();
6894 // [operand_stack]: Saved operand stack.
6895 DECL_ACCESSORS(operand_stack, FixedArray)
6897 DECLARE_CAST(JSGeneratorObject)
6899 // Dispatched behavior.
6900 DECLARE_PRINTER(JSGeneratorObject)
6901 DECLARE_VERIFIER(JSGeneratorObject)
6903 // Magic sentinel values for the continuation.
6904 static const int kGeneratorExecuting = -1;
6905 static const int kGeneratorClosed = 0;
6907 // Layout description.
6908 static const int kFunctionOffset = JSObject::kHeaderSize;
6909 static const int kContextOffset = kFunctionOffset + kPointerSize;
6910 static const int kReceiverOffset = kContextOffset + kPointerSize;
6911 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6912 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6913 static const int kSize = kOperandStackOffset + kPointerSize;
6915 // Resume mode, for use by runtime functions.
6916 enum ResumeMode { NEXT, THROW };
6919 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6923 // Representation for module instance objects.
6924 class JSModule: public JSObject {
6926 // [context]: the context holding the module's locals, or undefined if none.
6927 DECL_ACCESSORS(context, Object)
6929 // [scope_info]: Scope info.
6930 DECL_ACCESSORS(scope_info, ScopeInfo)
6932 DECLARE_CAST(JSModule)
6934 // Dispatched behavior.
6935 DECLARE_PRINTER(JSModule)
6936 DECLARE_VERIFIER(JSModule)
6938 // Layout description.
6939 static const int kContextOffset = JSObject::kHeaderSize;
6940 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6941 static const int kSize = kScopeInfoOffset + kPointerSize;
6944 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6948 // JSFunction describes JavaScript functions.
6949 class JSFunction: public JSObject {
6951 // [prototype_or_initial_map]:
6952 DECL_ACCESSORS(prototype_or_initial_map, Object)
6954 // [shared]: The information about the function that
6955 // can be shared by instances.
6956 DECL_ACCESSORS(shared, SharedFunctionInfo)
6958 // [context]: The context for this function.
6959 inline Context* context();
6960 inline void set_context(Object* context);
6961 inline JSObject* global_proxy();
6963 // [code]: The generated code object for this function. Executed
6964 // when the function is invoked, e.g. foo() or new foo(). See
6965 // [[Call]] and [[Construct]] description in ECMA-262, section
6967 inline Code* code();
6968 inline void set_code(Code* code);
6969 inline void set_code_no_write_barrier(Code* code);
6970 inline void ReplaceCode(Code* code);
6972 // Tells whether this function is builtin.
6973 inline bool IsBuiltin();
6975 // Tells whether this function inlines the given shared function info.
6976 bool Inlines(SharedFunctionInfo* candidate);
6978 // Tells whether this function should be subject to debugging.
6979 inline bool IsSubjectToDebugging();
6981 // Tells whether or not the function needs arguments adaption.
6982 inline bool NeedsArgumentsAdaption();
6984 // Tells whether or not this function has been optimized.
6985 inline bool IsOptimized();
6987 // Mark this function for lazy recompilation. The function will be
6988 // recompiled the next time it is executed.
6989 void MarkForOptimization();
6990 void AttemptConcurrentOptimization();
6992 // Tells whether or not the function is already marked for lazy
6994 inline bool IsMarkedForOptimization();
6995 inline bool IsMarkedForConcurrentOptimization();
6997 // Tells whether or not the function is on the concurrent recompilation queue.
6998 inline bool IsInOptimizationQueue();
7000 // Inobject slack tracking is the way to reclaim unused inobject space.
7002 // The instance size is initially determined by adding some slack to
7003 // expected_nof_properties (to allow for a few extra properties added
7004 // after the constructor). There is no guarantee that the extra space
7005 // will not be wasted.
7007 // Here is the algorithm to reclaim the unused inobject space:
7008 // - Detect the first constructor call for this JSFunction.
7009 // When it happens enter the "in progress" state: initialize construction
7010 // counter in the initial_map.
7011 // - While the tracking is in progress create objects filled with
7012 // one_pointer_filler_map instead of undefined_value. This way they can be
7013 // resized quickly and safely.
7014 // - Once enough objects have been created compute the 'slack'
7015 // (traverse the map transition tree starting from the
7016 // initial_map and find the lowest value of unused_property_fields).
7017 // - Traverse the transition tree again and decrease the instance size
7018 // of every map. Existing objects will resize automatically (they are
7019 // filled with one_pointer_filler_map). All further allocations will
7020 // use the adjusted instance size.
7021 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7022 // allocations made using different closures could actually create different
7023 // kind of objects (see prototype inheritance pattern).
7025 // Important: inobject slack tracking is not attempted during the snapshot
7028 // True if the initial_map is set and the object constructions countdown
7029 // counter is not zero.
7030 static const int kGenerousAllocationCount =
7031 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7032 inline bool IsInobjectSlackTrackingInProgress();
7034 // Starts the tracking.
7035 // Initializes object constructions countdown counter in the initial map.
7036 void StartInobjectSlackTracking();
7038 // Completes the tracking.
7039 void CompleteInobjectSlackTracking();
7041 // [literals_or_bindings]: Fixed array holding either
7042 // the materialized literals or the bindings of a bound function.
7044 // If the function contains object, regexp or array literals, the
7045 // literals array prefix contains the object, regexp, and array
7046 // function to be used when creating these literals. This is
7047 // necessary so that we do not dynamically lookup the object, regexp
7048 // or array functions. Performing a dynamic lookup, we might end up
7049 // using the functions from a new context that we should not have
7052 // On bound functions, the array is a (copy-on-write) fixed-array containing
7053 // the function that was bound, bound this-value and any bound
7054 // arguments. Bound functions never contain literals.
7055 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7057 inline FixedArray* literals();
7058 inline void set_literals(FixedArray* literals);
7060 inline FixedArray* function_bindings();
7061 inline void set_function_bindings(FixedArray* bindings);
7063 // The initial map for an object created by this constructor.
7064 inline Map* initial_map();
7065 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7066 Handle<Object> prototype);
7067 inline bool has_initial_map();
7068 static void EnsureHasInitialMap(Handle<JSFunction> function);
7070 // Get and set the prototype property on a JSFunction. If the
7071 // function has an initial map the prototype is set on the initial
7072 // map. Otherwise, the prototype is put in the initial map field
7073 // until an initial map is needed.
7074 inline bool has_prototype();
7075 inline bool has_instance_prototype();
7076 inline Object* prototype();
7077 inline Object* instance_prototype();
7078 static void SetPrototype(Handle<JSFunction> function,
7079 Handle<Object> value);
7080 static void SetInstancePrototype(Handle<JSFunction> function,
7081 Handle<Object> value);
7083 // Creates a new closure for the fucntion with the same bindings,
7084 // bound values, and prototype. An equivalent of spec operations
7085 // ``CloneMethod`` and ``CloneBoundFunction``.
7086 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7088 // After prototype is removed, it will not be created when accessed, and
7089 // [[Construct]] from this function will not be allowed.
7090 bool RemovePrototype();
7091 inline bool should_have_prototype();
7093 // Accessor for this function's initial map's [[class]]
7094 // property. This is primarily used by ECMA native functions. This
7095 // method sets the class_name field of this function's initial map
7096 // to a given value. It creates an initial map if this function does
7097 // not have one. Note that this method does not copy the initial map
7098 // if it has one already, but simply replaces it with the new value.
7099 // Instances created afterwards will have a map whose [[class]] is
7100 // set to 'value', but there is no guarantees on instances created
7102 void SetInstanceClassName(String* name);
7104 // Returns if this function has been compiled to native code yet.
7105 inline bool is_compiled();
7107 // Returns `false` if formal parameters include rest parameters, optional
7108 // parameters, or destructuring parameters.
7109 // TODO(caitp): make this a flag set during parsing
7110 inline bool has_simple_parameters();
7112 // [next_function_link]: Links functions into various lists, e.g. the list
7113 // of optimized functions hanging off the native_context. The CodeFlusher
7114 // uses this link to chain together flushing candidates. Treated weakly
7115 // by the garbage collector.
7116 DECL_ACCESSORS(next_function_link, Object)
7118 // Prints the name of the function using PrintF.
7119 void PrintName(FILE* out = stdout);
7121 DECLARE_CAST(JSFunction)
7123 // Iterates the objects, including code objects indirectly referenced
7124 // through pointers to the first instruction in the code object.
7125 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7127 // Dispatched behavior.
7128 DECLARE_PRINTER(JSFunction)
7129 DECLARE_VERIFIER(JSFunction)
7131 // Returns the number of allocated literals.
7132 inline int NumberOfLiterals();
7134 // Used for flags such as --hydrogen-filter.
7135 bool PassesFilter(const char* raw_filter);
7137 // The function's name if it is configured, otherwise shared function info
7139 static Handle<String> GetDebugName(Handle<JSFunction> function);
7141 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7142 // kSize) is weak and has special handling during garbage collection.
7143 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7144 static const int kPrototypeOrInitialMapOffset =
7145 kCodeEntryOffset + kPointerSize;
7146 static const int kSharedFunctionInfoOffset =
7147 kPrototypeOrInitialMapOffset + kPointerSize;
7148 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7149 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7150 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7151 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7152 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7154 // Layout of the bound-function binding array.
7155 static const int kBoundFunctionIndex = 0;
7156 static const int kBoundThisIndex = 1;
7157 static const int kBoundArgumentsStartIndex = 2;
7160 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7164 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7165 // and the prototype is hidden. JSGlobalProxy always delegates
7166 // property accesses to its prototype if the prototype is not null.
7168 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7170 // Accessing a JSGlobalProxy requires security check.
7172 class JSGlobalProxy : public JSObject {
7174 // [native_context]: the owner native context of this global proxy object.
7175 // It is null value if this object is not used by any context.
7176 DECL_ACCESSORS(native_context, Object)
7178 // [hash]: The hash code property (undefined if not initialized yet).
7179 DECL_ACCESSORS(hash, Object)
7181 DECLARE_CAST(JSGlobalProxy)
7183 inline bool IsDetachedFrom(GlobalObject* global) const;
7185 // Dispatched behavior.
7186 DECLARE_PRINTER(JSGlobalProxy)
7187 DECLARE_VERIFIER(JSGlobalProxy)
7189 // Layout description.
7190 static const int kNativeContextOffset = JSObject::kHeaderSize;
7191 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7192 static const int kSize = kHashOffset + kPointerSize;
7195 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7199 // Common super class for JavaScript global objects and the special
7200 // builtins global objects.
7201 class GlobalObject: public JSObject {
7203 // [builtins]: the object holding the runtime routines written in JS.
7204 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7206 // [native context]: the natives corresponding to this global object.
7207 DECL_ACCESSORS(native_context, Context)
7209 // [global proxy]: the global proxy object of the context
7210 DECL_ACCESSORS(global_proxy, JSObject)
7212 DECLARE_CAST(GlobalObject)
7214 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7216 // Ensure that the global object has a cell for the given property name.
7217 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7220 // Layout description.
7221 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7222 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7223 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7224 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7227 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7231 // JavaScript global object.
7232 class JSGlobalObject: public GlobalObject {
7234 DECLARE_CAST(JSGlobalObject)
7236 inline bool IsDetached();
7238 // Dispatched behavior.
7239 DECLARE_PRINTER(JSGlobalObject)
7240 DECLARE_VERIFIER(JSGlobalObject)
7242 // Layout description.
7243 static const int kSize = GlobalObject::kHeaderSize;
7246 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7250 // Builtins global object which holds the runtime routines written in
7252 class JSBuiltinsObject: public GlobalObject {
7254 DECLARE_CAST(JSBuiltinsObject)
7256 // Dispatched behavior.
7257 DECLARE_PRINTER(JSBuiltinsObject)
7258 DECLARE_VERIFIER(JSBuiltinsObject)
7260 // Layout description.
7261 static const int kSize = GlobalObject::kHeaderSize;
7264 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7268 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7269 class JSValue: public JSObject {
7271 // [value]: the object being wrapped.
7272 DECL_ACCESSORS(value, Object)
7274 DECLARE_CAST(JSValue)
7276 // Dispatched behavior.
7277 DECLARE_PRINTER(JSValue)
7278 DECLARE_VERIFIER(JSValue)
7280 // Layout description.
7281 static const int kValueOffset = JSObject::kHeaderSize;
7282 static const int kSize = kValueOffset + kPointerSize;
7285 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7291 // Representation for JS date objects.
7292 class JSDate: public JSObject {
7294 // If one component is NaN, all of them are, indicating a NaN time value.
7295 // [value]: the time value.
7296 DECL_ACCESSORS(value, Object)
7297 // [year]: caches year. Either undefined, smi, or NaN.
7298 DECL_ACCESSORS(year, Object)
7299 // [month]: caches month. Either undefined, smi, or NaN.
7300 DECL_ACCESSORS(month, Object)
7301 // [day]: caches day. Either undefined, smi, or NaN.
7302 DECL_ACCESSORS(day, Object)
7303 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7304 DECL_ACCESSORS(weekday, Object)
7305 // [hour]: caches hours. Either undefined, smi, or NaN.
7306 DECL_ACCESSORS(hour, Object)
7307 // [min]: caches minutes. Either undefined, smi, or NaN.
7308 DECL_ACCESSORS(min, Object)
7309 // [sec]: caches seconds. Either undefined, smi, or NaN.
7310 DECL_ACCESSORS(sec, Object)
7311 // [cache stamp]: sample of the date cache stamp at the
7312 // moment when chached fields were cached.
7313 DECL_ACCESSORS(cache_stamp, Object)
7315 DECLARE_CAST(JSDate)
7317 // Returns the date field with the specified index.
7318 // See FieldIndex for the list of date fields.
7319 static Object* GetField(Object* date, Smi* index);
7321 void SetValue(Object* value, bool is_value_nan);
7323 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7324 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7325 Handle<JSReceiver> receiver, Handle<Object> hint);
7327 // Dispatched behavior.
7328 DECLARE_PRINTER(JSDate)
7329 DECLARE_VERIFIER(JSDate)
7331 // The order is important. It must be kept in sync with date macros
7342 kFirstUncachedField,
7343 kMillisecond = kFirstUncachedField,
7347 kYearUTC = kFirstUTCField,
7360 // Layout description.
7361 static const int kValueOffset = JSObject::kHeaderSize;
7362 static const int kYearOffset = kValueOffset + kPointerSize;
7363 static const int kMonthOffset = kYearOffset + kPointerSize;
7364 static const int kDayOffset = kMonthOffset + kPointerSize;
7365 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7366 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7367 static const int kMinOffset = kHourOffset + kPointerSize;
7368 static const int kSecOffset = kMinOffset + kPointerSize;
7369 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7370 static const int kSize = kCacheStampOffset + kPointerSize;
7373 inline Object* DoGetField(FieldIndex index);
7375 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7377 // Computes and caches the cacheable fields of the date.
7378 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7381 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7385 // Representation of message objects used for error reporting through
7386 // the API. The messages are formatted in JavaScript so this object is
7387 // a real JavaScript object. The information used for formatting the
7388 // error messages are not directly accessible from JavaScript to
7389 // prevent leaking information to user code called during error
7391 class JSMessageObject: public JSObject {
7393 // [type]: the type of error message.
7394 inline int type() const;
7395 inline void set_type(int value);
7397 // [arguments]: the arguments for formatting the error message.
7398 DECL_ACCESSORS(argument, Object)
7400 // [script]: the script from which the error message originated.
7401 DECL_ACCESSORS(script, Object)
7403 // [stack_frames]: an array of stack frames for this error object.
7404 DECL_ACCESSORS(stack_frames, Object)
7406 // [start_position]: the start position in the script for the error message.
7407 inline int start_position() const;
7408 inline void set_start_position(int value);
7410 // [end_position]: the end position in the script for the error message.
7411 inline int end_position() const;
7412 inline void set_end_position(int value);
7414 DECLARE_CAST(JSMessageObject)
7416 // Dispatched behavior.
7417 DECLARE_PRINTER(JSMessageObject)
7418 DECLARE_VERIFIER(JSMessageObject)
7420 // Layout description.
7421 static const int kTypeOffset = JSObject::kHeaderSize;
7422 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7423 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7424 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7425 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7426 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7427 static const int kSize = kEndPositionOffset + kPointerSize;
7429 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7430 kStackFramesOffset + kPointerSize,
7431 kSize> BodyDescriptor;
7435 // Regular expressions
7436 // The regular expression holds a single reference to a FixedArray in
7437 // the kDataOffset field.
7438 // The FixedArray contains the following data:
7439 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7440 // - reference to the original source string
7441 // - reference to the original flag string
7442 // If it is an atom regexp
7443 // - a reference to a literal string to search for
7444 // If it is an irregexp regexp:
7445 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7446 // used for tracking the last usage (used for code flushing).
7447 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7448 // used for tracking the last usage (used for code flushing)..
7449 // - max number of registers used by irregexp implementations.
7450 // - number of capture registers (output values) of the regexp.
7451 class JSRegExp: public JSObject {
7454 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7455 // ATOM: A simple string to match against using an indexOf operation.
7456 // IRREGEXP: Compiled with Irregexp.
7457 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7458 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7465 UNICODE_ESCAPES = 16
7470 explicit Flags(uint32_t value) : value_(value) { }
7471 bool is_global() { return (value_ & GLOBAL) != 0; }
7472 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7473 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7474 bool is_sticky() { return (value_ & STICKY) != 0; }
7475 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7476 uint32_t value() { return value_; }
7481 DECL_ACCESSORS(data, Object)
7483 inline Type TypeTag();
7484 inline int CaptureCount();
7485 inline Flags GetFlags();
7486 inline String* Pattern();
7487 inline Object* DataAt(int index);
7488 // Set implementation data after the object has been prepared.
7489 inline void SetDataAt(int index, Object* value);
7491 static int code_index(bool is_latin1) {
7493 return kIrregexpLatin1CodeIndex;
7495 return kIrregexpUC16CodeIndex;
7499 static int saved_code_index(bool is_latin1) {
7501 return kIrregexpLatin1CodeSavedIndex;
7503 return kIrregexpUC16CodeSavedIndex;
7507 DECLARE_CAST(JSRegExp)
7509 // Dispatched behavior.
7510 DECLARE_VERIFIER(JSRegExp)
7512 static const int kDataOffset = JSObject::kHeaderSize;
7513 static const int kSize = kDataOffset + kPointerSize;
7515 // Indices in the data array.
7516 static const int kTagIndex = 0;
7517 static const int kSourceIndex = kTagIndex + 1;
7518 static const int kFlagsIndex = kSourceIndex + 1;
7519 static const int kDataIndex = kFlagsIndex + 1;
7520 // The data fields are used in different ways depending on the
7521 // value of the tag.
7522 // Atom regexps (literal strings).
7523 static const int kAtomPatternIndex = kDataIndex;
7525 static const int kAtomDataSize = kAtomPatternIndex + 1;
7527 // Irregexp compiled code or bytecode for Latin1. If compilation
7528 // fails, this fields hold an exception object that should be
7529 // thrown if the regexp is used again.
7530 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7531 // Irregexp compiled code or bytecode for UC16. 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 kIrregexpUC16CodeIndex = kDataIndex + 1;
7536 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7537 // is a potential candidate for flushing.
7538 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7539 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7540 // a potential candidate for flushing.
7541 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7543 // Maximal number of registers used by either Latin1 or UC16.
7544 // Only used to check that there is enough stack space
7545 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7546 // Number of captures in the compiled regexp.
7547 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7549 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7551 // Offsets directly into the data fixed array.
7552 static const int kDataTagOffset =
7553 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7554 static const int kDataOneByteCodeOffset =
7555 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7556 static const int kDataUC16CodeOffset =
7557 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7558 static const int kIrregexpCaptureCountOffset =
7559 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7561 // In-object fields.
7562 static const int kSourceFieldIndex = 0;
7563 static const int kGlobalFieldIndex = 1;
7564 static const int kIgnoreCaseFieldIndex = 2;
7565 static const int kMultilineFieldIndex = 3;
7566 static const int kLastIndexFieldIndex = 4;
7567 static const int kInObjectFieldCount = 5;
7569 // The uninitialized value for a regexp code object.
7570 static const int kUninitializedValue = -1;
7572 // The compilation error value for the regexp code object. The real error
7573 // object is in the saved code field.
7574 static const int kCompilationErrorValue = -2;
7576 // When we store the sweep generation at which we moved the code from the
7577 // code index to the saved code index we mask it of to be in the [0:255]
7579 static const int kCodeAgeMask = 0xff;
7583 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7585 static inline bool IsMatch(HashTableKey* key, Object* value) {
7586 return key->IsMatch(value);
7589 static inline uint32_t Hash(HashTableKey* key) {
7593 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7594 return key->HashForObject(object);
7597 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7599 static const int kPrefixSize = 0;
7600 static const int kEntrySize = 2;
7604 // This cache is used in two different variants. For regexp caching, it simply
7605 // maps identifying info of the regexp to the cached regexp object. Scripts and
7606 // eval code only gets cached after a second probe for the code object. To do
7607 // so, on first "put" only a hash identifying the source is entered into the
7608 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7609 // such lifetimes get reduced, and removed once they reach zero. If a second put
7610 // is called while such a hash is live in the cache, the hash gets replaced by
7611 // an actual cache entry. Age also removes stale live entries from the cache.
7612 // Such entries are identified by SharedFunctionInfos pointing to either the
7613 // recompilation stub, or to "old" code. This avoids memory leaks due to
7614 // premature caching of scripts and eval strings that are never needed later.
7615 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7616 CompilationCacheShape,
7619 // Find cached value for a string key, otherwise return null.
7620 Handle<Object> Lookup(
7621 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7622 Handle<Object> LookupEval(
7623 Handle<String> src, Handle<SharedFunctionInfo> shared,
7624 LanguageMode language_mode, int scope_position);
7625 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7626 static Handle<CompilationCacheTable> Put(
7627 Handle<CompilationCacheTable> cache, Handle<String> src,
7628 Handle<Context> context, LanguageMode language_mode,
7629 Handle<Object> value);
7630 static Handle<CompilationCacheTable> PutEval(
7631 Handle<CompilationCacheTable> cache, Handle<String> src,
7632 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7633 int scope_position);
7634 static Handle<CompilationCacheTable> PutRegExp(
7635 Handle<CompilationCacheTable> cache, Handle<String> src,
7636 JSRegExp::Flags flags, Handle<FixedArray> value);
7637 void Remove(Object* value);
7639 static const int kHashGenerations = 10;
7641 DECLARE_CAST(CompilationCacheTable)
7644 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7648 class CodeCache: public Struct {
7650 DECL_ACCESSORS(default_cache, FixedArray)
7651 DECL_ACCESSORS(normal_type_cache, Object)
7653 // Add the code object to the cache.
7655 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7657 // Lookup code object in the cache. Returns code object if found and undefined
7659 Object* Lookup(Name* name, Code::Flags flags);
7661 // Get the internal index of a code object in the cache. Returns -1 if the
7662 // code object is not in that cache. This index can be used to later call
7663 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7665 int GetIndex(Object* name, Code* code);
7667 // Remove an object from the cache with the provided internal index.
7668 void RemoveByIndex(Object* name, Code* code, int index);
7670 DECLARE_CAST(CodeCache)
7672 // Dispatched behavior.
7673 DECLARE_PRINTER(CodeCache)
7674 DECLARE_VERIFIER(CodeCache)
7676 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7677 static const int kNormalTypeCacheOffset =
7678 kDefaultCacheOffset + kPointerSize;
7679 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7682 static void UpdateDefaultCache(
7683 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7684 static void UpdateNormalTypeCache(
7685 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7686 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7687 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7689 // Code cache layout of the default cache. Elements are alternating name and
7690 // code objects for non normal load/store/call IC's.
7691 static const int kCodeCacheEntrySize = 2;
7692 static const int kCodeCacheEntryNameOffset = 0;
7693 static const int kCodeCacheEntryCodeOffset = 1;
7695 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7699 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7701 static inline bool IsMatch(HashTableKey* key, Object* value) {
7702 return key->IsMatch(value);
7705 static inline uint32_t Hash(HashTableKey* key) {
7709 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7710 return key->HashForObject(object);
7713 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7715 static const int kPrefixSize = 0;
7716 static const int kEntrySize = 2;
7720 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7721 CodeCacheHashTableShape,
7724 Object* Lookup(Name* name, Code::Flags flags);
7725 static Handle<CodeCacheHashTable> Put(
7726 Handle<CodeCacheHashTable> table,
7730 int GetIndex(Name* name, Code::Flags flags);
7731 void RemoveByIndex(int index);
7733 DECLARE_CAST(CodeCacheHashTable)
7735 // Initial size of the fixed array backing the hash table.
7736 static const int kInitialSize = 64;
7739 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7743 class PolymorphicCodeCache: public Struct {
7745 DECL_ACCESSORS(cache, Object)
7747 static void Update(Handle<PolymorphicCodeCache> cache,
7748 MapHandleList* maps,
7753 // Returns an undefined value if the entry is not found.
7754 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7756 DECLARE_CAST(PolymorphicCodeCache)
7758 // Dispatched behavior.
7759 DECLARE_PRINTER(PolymorphicCodeCache)
7760 DECLARE_VERIFIER(PolymorphicCodeCache)
7762 static const int kCacheOffset = HeapObject::kHeaderSize;
7763 static const int kSize = kCacheOffset + kPointerSize;
7766 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7770 class PolymorphicCodeCacheHashTable
7771 : public HashTable<PolymorphicCodeCacheHashTable,
7772 CodeCacheHashTableShape,
7775 Object* Lookup(MapHandleList* maps, int code_kind);
7777 static Handle<PolymorphicCodeCacheHashTable> Put(
7778 Handle<PolymorphicCodeCacheHashTable> hash_table,
7779 MapHandleList* maps,
7783 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7785 static const int kInitialSize = 64;
7787 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7791 class TypeFeedbackInfo: public Struct {
7793 inline int ic_total_count();
7794 inline void set_ic_total_count(int count);
7796 inline int ic_with_type_info_count();
7797 inline void change_ic_with_type_info_count(int delta);
7799 inline int ic_generic_count();
7800 inline void change_ic_generic_count(int delta);
7802 inline void initialize_storage();
7804 inline void change_own_type_change_checksum();
7805 inline int own_type_change_checksum();
7807 inline void set_inlined_type_change_checksum(int checksum);
7808 inline bool matches_inlined_type_change_checksum(int checksum);
7810 DECLARE_CAST(TypeFeedbackInfo)
7812 // Dispatched behavior.
7813 DECLARE_PRINTER(TypeFeedbackInfo)
7814 DECLARE_VERIFIER(TypeFeedbackInfo)
7816 static const int kStorage1Offset = HeapObject::kHeaderSize;
7817 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7818 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7819 static const int kSize = kStorage3Offset + kPointerSize;
7822 static const int kTypeChangeChecksumBits = 7;
7824 class ICTotalCountField: public BitField<int, 0,
7825 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7826 class OwnTypeChangeChecksum: public BitField<int,
7827 kSmiValueSize - kTypeChangeChecksumBits,
7828 kTypeChangeChecksumBits> {}; // NOLINT
7829 class ICsWithTypeInfoCountField: public BitField<int, 0,
7830 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7831 class InlinedTypeChangeChecksum: public BitField<int,
7832 kSmiValueSize - kTypeChangeChecksumBits,
7833 kTypeChangeChecksumBits> {}; // NOLINT
7835 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7839 enum AllocationSiteMode {
7840 DONT_TRACK_ALLOCATION_SITE,
7841 TRACK_ALLOCATION_SITE,
7842 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7846 class AllocationSite: public Struct {
7848 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7849 static const double kPretenureRatio;
7850 static const int kPretenureMinimumCreated = 100;
7852 // Values for pretenure decision field.
7853 enum PretenureDecision {
7859 kLastPretenureDecisionValue = kZombie
7862 const char* PretenureDecisionName(PretenureDecision decision);
7864 DECL_ACCESSORS(transition_info, Object)
7865 // nested_site threads a list of sites that represent nested literals
7866 // walked in a particular order. So [[1, 2], 1, 2] will have one
7867 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7868 DECL_ACCESSORS(nested_site, Object)
7869 DECL_ACCESSORS(pretenure_data, Smi)
7870 DECL_ACCESSORS(pretenure_create_count, Smi)
7871 DECL_ACCESSORS(dependent_code, DependentCode)
7872 DECL_ACCESSORS(weak_next, Object)
7874 inline void Initialize();
7876 // This method is expensive, it should only be called for reporting.
7877 bool IsNestedSite();
7879 // transition_info bitfields, for constructed array transition info.
7880 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7881 class UnusedBits: public BitField<int, 15, 14> {};
7882 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7884 // Bitfields for pretenure_data
7885 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7886 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7887 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7888 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7890 // Increments the mementos found counter and returns true when the first
7891 // memento was found for a given allocation site.
7892 inline bool IncrementMementoFoundCount();
7894 inline void IncrementMementoCreateCount();
7896 PretenureFlag GetPretenureMode();
7898 void ResetPretenureDecision();
7900 inline PretenureDecision pretenure_decision();
7901 inline void set_pretenure_decision(PretenureDecision decision);
7903 inline bool deopt_dependent_code();
7904 inline void set_deopt_dependent_code(bool deopt);
7906 inline int memento_found_count();
7907 inline void set_memento_found_count(int count);
7909 inline int memento_create_count();
7910 inline void set_memento_create_count(int count);
7912 // The pretenuring decision is made during gc, and the zombie state allows
7913 // us to recognize when an allocation site is just being kept alive because
7914 // a later traversal of new space may discover AllocationMementos that point
7915 // to this AllocationSite.
7916 inline bool IsZombie();
7918 inline bool IsMaybeTenure();
7920 inline void MarkZombie();
7922 inline bool MakePretenureDecision(PretenureDecision current_decision,
7924 bool maximum_size_scavenge);
7926 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7928 inline ElementsKind GetElementsKind();
7929 inline void SetElementsKind(ElementsKind kind);
7931 inline bool CanInlineCall();
7932 inline void SetDoNotInlineCall();
7934 inline bool SitePointsToLiteral();
7936 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7937 ElementsKind to_kind);
7939 DECLARE_PRINTER(AllocationSite)
7940 DECLARE_VERIFIER(AllocationSite)
7942 DECLARE_CAST(AllocationSite)
7943 static inline AllocationSiteMode GetMode(
7944 ElementsKind boilerplate_elements_kind);
7945 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7946 static inline bool CanTrack(InstanceType type);
7948 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7949 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7950 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7951 static const int kPretenureCreateCountOffset =
7952 kPretenureDataOffset + kPointerSize;
7953 static const int kDependentCodeOffset =
7954 kPretenureCreateCountOffset + kPointerSize;
7955 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7956 static const int kSize = kWeakNextOffset + kPointerSize;
7958 // During mark compact we need to take special care for the dependent code
7960 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7961 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7963 // For other visitors, use the fixed body descriptor below.
7964 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7965 kDependentCodeOffset + kPointerSize,
7966 kSize> BodyDescriptor;
7969 inline bool PretenuringDecisionMade();
7971 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7975 class AllocationMemento: public Struct {
7977 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7978 static const int kSize = kAllocationSiteOffset + kPointerSize;
7980 DECL_ACCESSORS(allocation_site, Object)
7982 inline bool IsValid();
7983 inline AllocationSite* GetAllocationSite();
7985 DECLARE_PRINTER(AllocationMemento)
7986 DECLARE_VERIFIER(AllocationMemento)
7988 DECLARE_CAST(AllocationMemento)
7991 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7995 // Representation of a slow alias as part of a sloppy arguments objects.
7996 // For fast aliases (if HasSloppyArgumentsElements()):
7997 // - the parameter map contains an index into the context
7998 // - all attributes of the element have default values
7999 // For slow aliases (if HasDictionaryArgumentsElements()):
8000 // - the parameter map contains no fast alias mapping (i.e. the hole)
8001 // - this struct (in the slow backing store) contains an index into the context
8002 // - all attributes are available as part if the property details
8003 class AliasedArgumentsEntry: public Struct {
8005 inline int aliased_context_slot() const;
8006 inline void set_aliased_context_slot(int count);
8008 DECLARE_CAST(AliasedArgumentsEntry)
8010 // Dispatched behavior.
8011 DECLARE_PRINTER(AliasedArgumentsEntry)
8012 DECLARE_VERIFIER(AliasedArgumentsEntry)
8014 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8015 static const int kSize = kAliasedContextSlot + kPointerSize;
8018 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8022 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8023 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8026 class StringHasher {
8028 explicit inline StringHasher(int length, uint32_t seed);
8030 template <typename schar>
8031 static inline uint32_t HashSequentialString(const schar* chars,
8035 // Reads all the data, even for long strings and computes the utf16 length.
8036 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8038 int* utf16_length_out);
8040 // Calculated hash value for a string consisting of 1 to
8041 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8042 // value is represented decimal value.
8043 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8045 // No string is allowed to have a hash of zero. That value is reserved
8046 // for internal properties. If the hash calculation yields zero then we
8048 static const int kZeroHash = 27;
8050 // Reusable parts of the hashing algorithm.
8051 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8052 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8053 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8054 const uc16* chars, int length));
8055 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8060 // Returns the value to store in the hash field of a string with
8061 // the given length and contents.
8062 uint32_t GetHashField();
8063 // Returns true if the hash of this string can be computed without
8064 // looking at the contents.
8065 inline bool has_trivial_hash();
8066 // Adds a block of characters to the hash.
8067 template<typename Char>
8068 inline void AddCharacters(const Char* chars, int len);
8071 // Add a character to the hash.
8072 inline void AddCharacter(uint16_t c);
8073 // Update index. Returns true if string is still an index.
8074 inline bool UpdateIndex(uint16_t c);
8077 uint32_t raw_running_hash_;
8078 uint32_t array_index_;
8079 bool is_array_index_;
8080 bool is_first_char_;
8081 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8085 class IteratingStringHasher : public StringHasher {
8087 static inline uint32_t Hash(String* string, uint32_t seed);
8088 inline void VisitOneByteString(const uint8_t* chars, int length);
8089 inline void VisitTwoByteString(const uint16_t* chars, int length);
8092 inline IteratingStringHasher(int len, uint32_t seed);
8093 void VisitConsString(ConsString* cons_string);
8094 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8098 // The characteristics of a string are stored in its map. Retrieving these
8099 // few bits of information is moderately expensive, involving two memory
8100 // loads where the second is dependent on the first. To improve efficiency
8101 // the shape of the string is given its own class so that it can be retrieved
8102 // once and used for several string operations. A StringShape is small enough
8103 // to be passed by value and is immutable, but be aware that flattening a
8104 // string can potentially alter its shape. Also be aware that a GC caused by
8105 // something else can alter the shape of a string due to ConsString
8106 // shortcutting. Keeping these restrictions in mind has proven to be error-
8107 // prone and so we no longer put StringShapes in variables unless there is a
8108 // concrete performance benefit at that particular point in the code.
8109 class StringShape BASE_EMBEDDED {
8111 inline explicit StringShape(const String* s);
8112 inline explicit StringShape(Map* s);
8113 inline explicit StringShape(InstanceType t);
8114 inline bool IsSequential();
8115 inline bool IsExternal();
8116 inline bool IsCons();
8117 inline bool IsSliced();
8118 inline bool IsIndirect();
8119 inline bool IsExternalOneByte();
8120 inline bool IsExternalTwoByte();
8121 inline bool IsSequentialOneByte();
8122 inline bool IsSequentialTwoByte();
8123 inline bool IsInternalized();
8124 inline StringRepresentationTag representation_tag();
8125 inline uint32_t encoding_tag();
8126 inline uint32_t full_representation_tag();
8127 inline uint32_t size_tag();
8129 inline uint32_t type() { return type_; }
8130 inline void invalidate() { valid_ = false; }
8131 inline bool valid() { return valid_; }
8133 inline void invalidate() { }
8139 inline void set_valid() { valid_ = true; }
8142 inline void set_valid() { }
8147 // The Name abstract class captures anything that can be used as a property
8148 // name, i.e., strings and symbols. All names store a hash value.
8149 class Name: public HeapObject {
8151 // Get and set the hash field of the name.
8152 inline uint32_t hash_field();
8153 inline void set_hash_field(uint32_t value);
8155 // Tells whether the hash code has been computed.
8156 inline bool HasHashCode();
8158 // Returns a hash value used for the property table
8159 inline uint32_t Hash();
8161 // Equality operations.
8162 inline bool Equals(Name* other);
8163 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8166 inline bool AsArrayIndex(uint32_t* index);
8168 // If the name is private, it can only name own properties.
8169 inline bool IsPrivate();
8171 // If the name is a non-flat string, this method returns a flat version of the
8172 // string. Otherwise it'll just return the input.
8173 static inline Handle<Name> Flatten(Handle<Name> name,
8174 PretenureFlag pretenure = NOT_TENURED);
8176 // Return a string version of this name that is converted according to the
8177 // rules described in ES6 section 9.2.11.
8178 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8182 DECLARE_PRINTER(Name)
8184 void NameShortPrint();
8185 int NameShortPrint(Vector<char> str);
8188 // Layout description.
8189 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8190 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8191 static const int kHashFieldOffset = kHashFieldSlot;
8193 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8195 static const int kSize = kHashFieldSlot + kPointerSize;
8197 // Mask constant for checking if a name has a computed hash code
8198 // and if it is a string that is an array index. The least significant bit
8199 // indicates whether a hash code has been computed. If the hash code has
8200 // been computed the 2nd bit tells whether the string can be used as an
8202 static const int kHashNotComputedMask = 1;
8203 static const int kIsNotArrayIndexMask = 1 << 1;
8204 static const int kNofHashBitFields = 2;
8206 // Shift constant retrieving hash code from hash field.
8207 static const int kHashShift = kNofHashBitFields;
8209 // Only these bits are relevant in the hash, since the top two are shifted
8211 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8213 // Array index strings this short can keep their index in the hash field.
8214 static const int kMaxCachedArrayIndexLength = 7;
8216 // For strings which are array indexes the hash value has the string length
8217 // mixed into the hash, mainly to avoid a hash value of zero which would be
8218 // the case for the string '0'. 24 bits are used for the array index value.
8219 static const int kArrayIndexValueBits = 24;
8220 static const int kArrayIndexLengthBits =
8221 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8223 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8225 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8226 kArrayIndexValueBits> {}; // NOLINT
8227 class ArrayIndexLengthBits : public BitField<unsigned int,
8228 kNofHashBitFields + kArrayIndexValueBits,
8229 kArrayIndexLengthBits> {}; // NOLINT
8231 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8232 // could use a mask to test if the length of string is less than or equal to
8233 // kMaxCachedArrayIndexLength.
8234 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8236 static const unsigned int kContainsCachedArrayIndexMask =
8237 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8238 << ArrayIndexLengthBits::kShift) |
8239 kIsNotArrayIndexMask;
8241 // Value of empty hash field indicating that the hash is not computed.
8242 static const int kEmptyHashField =
8243 kIsNotArrayIndexMask | kHashNotComputedMask;
8246 static inline bool IsHashFieldComputed(uint32_t field);
8249 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8254 class Symbol: public Name {
8256 // [name]: The print name of a symbol, or undefined if none.
8257 DECL_ACCESSORS(name, Object)
8259 DECL_ACCESSORS(flags, Smi)
8261 // [is_private]: Whether this is a private symbol. Private symbols can only
8262 // be used to designate own properties of objects.
8263 DECL_BOOLEAN_ACCESSORS(is_private)
8265 DECLARE_CAST(Symbol)
8267 // Dispatched behavior.
8268 DECLARE_PRINTER(Symbol)
8269 DECLARE_VERIFIER(Symbol)
8271 // Layout description.
8272 static const int kNameOffset = Name::kSize;
8273 static const int kFlagsOffset = kNameOffset + kPointerSize;
8274 static const int kSize = kFlagsOffset + kPointerSize;
8276 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8278 void SymbolShortPrint(std::ostream& os);
8281 static const int kPrivateBit = 0;
8283 const char* PrivateSymbolToName() const;
8286 friend class Name; // For PrivateSymbolToName.
8289 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8295 // The String abstract class captures JavaScript string values:
8298 // 4.3.16 String Value
8299 // A string value is a member of the type String and is a finite
8300 // ordered sequence of zero or more 16-bit unsigned integer values.
8302 // All string values have a length field.
8303 class String: public Name {
8305 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8307 // Array index strings this short can keep their index in the hash field.
8308 static const int kMaxCachedArrayIndexLength = 7;
8310 // For strings which are array indexes the hash value has the string length
8311 // mixed into the hash, mainly to avoid a hash value of zero which would be
8312 // the case for the string '0'. 24 bits are used for the array index value.
8313 static const int kArrayIndexValueBits = 24;
8314 static const int kArrayIndexLengthBits =
8315 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8317 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8319 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8320 kArrayIndexValueBits> {}; // NOLINT
8321 class ArrayIndexLengthBits : public BitField<unsigned int,
8322 kNofHashBitFields + kArrayIndexValueBits,
8323 kArrayIndexLengthBits> {}; // NOLINT
8325 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8326 // could use a mask to test if the length of string is less than or equal to
8327 // kMaxCachedArrayIndexLength.
8328 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8330 static const unsigned int kContainsCachedArrayIndexMask =
8331 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8332 << ArrayIndexLengthBits::kShift) |
8333 kIsNotArrayIndexMask;
8335 class SubStringRange {
8337 explicit inline SubStringRange(String* string, int first = 0,
8340 inline iterator begin();
8341 inline iterator end();
8349 // Representation of the flat content of a String.
8350 // A non-flat string doesn't have flat content.
8351 // A flat string has content that's encoded as a sequence of either
8352 // one-byte chars or two-byte UC16.
8353 // Returned by String::GetFlatContent().
8356 // Returns true if the string is flat and this structure contains content.
8357 bool IsFlat() { return state_ != NON_FLAT; }
8358 // Returns true if the structure contains one-byte content.
8359 bool IsOneByte() { return state_ == ONE_BYTE; }
8360 // Returns true if the structure contains two-byte content.
8361 bool IsTwoByte() { return state_ == TWO_BYTE; }
8363 // Return the one byte content of the string. Only use if IsOneByte()
8365 Vector<const uint8_t> ToOneByteVector() {
8366 DCHECK_EQ(ONE_BYTE, state_);
8367 return Vector<const uint8_t>(onebyte_start, length_);
8369 // Return the two-byte content of the string. Only use if IsTwoByte()
8371 Vector<const uc16> ToUC16Vector() {
8372 DCHECK_EQ(TWO_BYTE, state_);
8373 return Vector<const uc16>(twobyte_start, length_);
8377 DCHECK(i < length_);
8378 DCHECK(state_ != NON_FLAT);
8379 if (state_ == ONE_BYTE) return onebyte_start[i];
8380 return twobyte_start[i];
8383 bool UsesSameString(const FlatContent& other) const {
8384 return onebyte_start == other.onebyte_start;
8388 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8390 // Constructors only used by String::GetFlatContent().
8391 explicit FlatContent(const uint8_t* start, int length)
8392 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8393 explicit FlatContent(const uc16* start, int length)
8394 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8395 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8398 const uint8_t* onebyte_start;
8399 const uc16* twobyte_start;
8404 friend class String;
8405 friend class IterableSubString;
8408 template <typename Char>
8409 INLINE(Vector<const Char> GetCharVector());
8411 // Get and set the length of the string.
8412 inline int length() const;
8413 inline void set_length(int value);
8415 // Get and set the length of the string using acquire loads and release
8417 inline int synchronized_length() const;
8418 inline void synchronized_set_length(int value);
8420 // Returns whether this string has only one-byte chars, i.e. all of them can
8421 // be one-byte encoded. This might be the case even if the string is
8422 // two-byte. Such strings may appear when the embedder prefers
8423 // two-byte external representations even for one-byte data.
8424 inline bool IsOneByteRepresentation() const;
8425 inline bool IsTwoByteRepresentation() const;
8427 // Cons and slices have an encoding flag that may not represent the actual
8428 // encoding of the underlying string. This is taken into account here.
8429 // Requires: this->IsFlat()
8430 inline bool IsOneByteRepresentationUnderneath();
8431 inline bool IsTwoByteRepresentationUnderneath();
8433 // NOTE: this should be considered only a hint. False negatives are
8435 inline bool HasOnlyOneByteChars();
8437 // Get and set individual two byte chars in the string.
8438 inline void Set(int index, uint16_t value);
8439 // Get individual two byte char in the string. Repeated calls
8440 // to this method are not efficient unless the string is flat.
8441 INLINE(uint16_t Get(int index));
8443 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8444 static Handle<Object> ToNumber(Handle<String> subject);
8446 // Flattens the string. Checks first inline to see if it is
8447 // necessary. Does nothing if the string is not a cons string.
8448 // Flattening allocates a sequential string with the same data as
8449 // the given string and mutates the cons string to a degenerate
8450 // form, where the first component is the new sequential string and
8451 // the second component is the empty string. If allocation fails,
8452 // this function returns a failure. If flattening succeeds, this
8453 // function returns the sequential string that is now the first
8454 // component of the cons string.
8456 // Degenerate cons strings are handled specially by the garbage
8457 // collector (see IsShortcutCandidate).
8459 static inline Handle<String> Flatten(Handle<String> string,
8460 PretenureFlag pretenure = NOT_TENURED);
8462 // Tries to return the content of a flat string as a structure holding either
8463 // a flat vector of char or of uc16.
8464 // If the string isn't flat, and therefore doesn't have flat content, the
8465 // returned structure will report so, and can't provide a vector of either
8467 FlatContent GetFlatContent();
8469 // Returns the parent of a sliced string or first part of a flat cons string.
8470 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8471 inline String* GetUnderlying();
8473 // String equality operations.
8474 inline bool Equals(String* other);
8475 inline static bool Equals(Handle<String> one, Handle<String> two);
8476 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8477 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8478 bool IsTwoByteEqualTo(Vector<const uc16> str);
8480 // Return a UTF8 representation of the string. The string is null
8481 // terminated but may optionally contain nulls. Length is returned
8482 // in length_output if length_output is not a null pointer The string
8483 // should be nearly flat, otherwise the performance of this method may
8484 // be very slow (quadratic in the length). Setting robustness_flag to
8485 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8486 // handles unexpected data without causing assert failures and it does not
8487 // do any heap allocations. This is useful when printing stack traces.
8488 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8489 RobustnessFlag robustness_flag,
8490 int offset, int length,
8491 int* length_output = 0);
8492 base::SmartArrayPointer<char> ToCString(
8493 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8494 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8495 int* length_output = 0);
8497 // Return a 16 bit Unicode representation of the string.
8498 // The string should be nearly flat, otherwise the performance of
8499 // of this method may be very bad. Setting robustness_flag to
8500 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8501 // handles unexpected data without causing assert failures and it does not
8502 // do any heap allocations. This is useful when printing stack traces.
8503 base::SmartArrayPointer<uc16> ToWideCString(
8504 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8506 bool ComputeArrayIndex(uint32_t* index);
8509 bool MakeExternal(v8::String::ExternalStringResource* resource);
8510 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8513 inline bool AsArrayIndex(uint32_t* index);
8515 DECLARE_CAST(String)
8517 void PrintOn(FILE* out);
8519 // For use during stack traces. Performs rudimentary sanity check.
8522 // Dispatched behavior.
8523 void StringShortPrint(StringStream* accumulator);
8524 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8525 #if defined(DEBUG) || defined(OBJECT_PRINT)
8526 char* ToAsciiArray();
8528 DECLARE_PRINTER(String)
8529 DECLARE_VERIFIER(String)
8531 inline bool IsFlat();
8533 // Layout description.
8534 static const int kLengthOffset = Name::kSize;
8535 static const int kSize = kLengthOffset + kPointerSize;
8537 // Maximum number of characters to consider when trying to convert a string
8538 // value into an array index.
8539 static const int kMaxArrayIndexSize = 10;
8540 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8543 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8544 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8545 static const int kMaxUtf16CodeUnit = 0xffff;
8546 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8548 // Value of hash field containing computed hash equal to zero.
8549 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8551 // Maximal string length.
8552 static const int kMaxLength = (1 << 28) - 16;
8554 // Max length for computing hash. For strings longer than this limit the
8555 // string length is used as the hash value.
8556 static const int kMaxHashCalcLength = 16383;
8558 // Limit for truncation in short printing.
8559 static const int kMaxShortPrintLength = 1024;
8561 // Support for regular expressions.
8562 const uc16* GetTwoByteData(unsigned start);
8564 // Helper function for flattening strings.
8565 template <typename sinkchar>
8566 static void WriteToFlat(String* source,
8571 // The return value may point to the first aligned word containing the first
8572 // non-one-byte character, rather than directly to the non-one-byte character.
8573 // If the return value is >= the passed length, the entire string was
8575 static inline int NonAsciiStart(const char* chars, int length) {
8576 const char* start = chars;
8577 const char* limit = chars + length;
8579 if (length >= kIntptrSize) {
8580 // Check unaligned bytes.
8581 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8582 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8583 return static_cast<int>(chars - start);
8587 // Check aligned words.
8588 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8589 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8590 while (chars + sizeof(uintptr_t) <= limit) {
8591 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8592 return static_cast<int>(chars - start);
8594 chars += sizeof(uintptr_t);
8597 // Check remaining unaligned bytes.
8598 while (chars < limit) {
8599 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8600 return static_cast<int>(chars - start);
8605 return static_cast<int>(chars - start);
8608 static inline bool IsAscii(const char* chars, int length) {
8609 return NonAsciiStart(chars, length) >= length;
8612 static inline bool IsAscii(const uint8_t* chars, int length) {
8614 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8617 static inline int NonOneByteStart(const uc16* chars, int length) {
8618 const uc16* limit = chars + length;
8619 const uc16* start = chars;
8620 while (chars < limit) {
8621 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8624 return static_cast<int>(chars - start);
8627 static inline bool IsOneByte(const uc16* chars, int length) {
8628 return NonOneByteStart(chars, length) >= length;
8631 template<class Visitor>
8632 static inline ConsString* VisitFlat(Visitor* visitor,
8636 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8637 bool include_ending_line);
8639 // Use the hash field to forward to the canonical internalized string
8640 // when deserializing an internalized string.
8641 inline void SetForwardedInternalizedString(String* string);
8642 inline String* GetForwardedInternalizedString();
8646 friend class StringTableInsertionKey;
8648 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8649 PretenureFlag tenure);
8651 // Slow case of String::Equals. This implementation works on any strings
8652 // but it is most efficient on strings that are almost flat.
8653 bool SlowEquals(String* other);
8655 static bool SlowEquals(Handle<String> one, Handle<String> two);
8657 // Slow case of AsArrayIndex.
8658 bool SlowAsArrayIndex(uint32_t* index);
8660 // Compute and set the hash code.
8661 uint32_t ComputeAndSetHash();
8663 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8667 // The SeqString abstract class captures sequential string values.
8668 class SeqString: public String {
8670 DECLARE_CAST(SeqString)
8672 // Layout description.
8673 static const int kHeaderSize = String::kSize;
8675 // Truncate the string in-place if possible and return the result.
8676 // In case of new_length == 0, the empty string is returned without
8677 // truncating the original string.
8678 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8681 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8685 // The OneByteString class captures sequential one-byte string objects.
8686 // Each character in the OneByteString is an one-byte character.
8687 class SeqOneByteString: public SeqString {
8689 static const bool kHasOneByteEncoding = true;
8691 // Dispatched behavior.
8692 inline uint16_t SeqOneByteStringGet(int index);
8693 inline void SeqOneByteStringSet(int index, uint16_t value);
8695 // Get the address of the characters in this string.
8696 inline Address GetCharsAddress();
8698 inline uint8_t* GetChars();
8700 DECLARE_CAST(SeqOneByteString)
8702 // Garbage collection support. This method is called by the
8703 // garbage collector to compute the actual size of an OneByteString
8705 inline int SeqOneByteStringSize(InstanceType instance_type);
8707 // Computes the size for an OneByteString instance of a given length.
8708 static int SizeFor(int length) {
8709 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8712 // Maximal memory usage for a single sequential one-byte string.
8713 static const int kMaxSize = 512 * MB - 1;
8714 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8717 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8721 // The TwoByteString class captures sequential unicode string objects.
8722 // Each character in the TwoByteString is a two-byte uint16_t.
8723 class SeqTwoByteString: public SeqString {
8725 static const bool kHasOneByteEncoding = false;
8727 // Dispatched behavior.
8728 inline uint16_t SeqTwoByteStringGet(int index);
8729 inline void SeqTwoByteStringSet(int index, uint16_t value);
8731 // Get the address of the characters in this string.
8732 inline Address GetCharsAddress();
8734 inline uc16* GetChars();
8737 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8739 DECLARE_CAST(SeqTwoByteString)
8741 // Garbage collection support. This method is called by the
8742 // garbage collector to compute the actual size of a TwoByteString
8744 inline int SeqTwoByteStringSize(InstanceType instance_type);
8746 // Computes the size for a TwoByteString instance of a given length.
8747 static int SizeFor(int length) {
8748 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8751 // Maximal memory usage for a single sequential two-byte string.
8752 static const int kMaxSize = 512 * MB - 1;
8753 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8754 String::kMaxLength);
8757 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8761 // The ConsString class describes string values built by using the
8762 // addition operator on strings. A ConsString is a pair where the
8763 // first and second components are pointers to other string values.
8764 // One or both components of a ConsString can be pointers to other
8765 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8766 // are non-ConsString string values. The string value represented by
8767 // a ConsString can be obtained by concatenating the leaf string
8768 // values in a left-to-right depth-first traversal of the tree.
8769 class ConsString: public String {
8771 // First string of the cons cell.
8772 inline String* first();
8773 // Doesn't check that the result is a string, even in debug mode. This is
8774 // useful during GC where the mark bits confuse the checks.
8775 inline Object* unchecked_first();
8776 inline void set_first(String* first,
8777 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8779 // Second string of the cons cell.
8780 inline String* second();
8781 // Doesn't check that the result is a string, even in debug mode. This is
8782 // useful during GC where the mark bits confuse the checks.
8783 inline Object* unchecked_second();
8784 inline void set_second(String* second,
8785 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8787 // Dispatched behavior.
8788 uint16_t ConsStringGet(int index);
8790 DECLARE_CAST(ConsString)
8792 // Layout description.
8793 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8794 static const int kSecondOffset = kFirstOffset + kPointerSize;
8795 static const int kSize = kSecondOffset + kPointerSize;
8797 // Minimum length for a cons string.
8798 static const int kMinLength = 13;
8800 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8803 DECLARE_VERIFIER(ConsString)
8806 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8810 // The Sliced String class describes strings that are substrings of another
8811 // sequential string. The motivation is to save time and memory when creating
8812 // a substring. A Sliced String is described as a pointer to the parent,
8813 // the offset from the start of the parent string and the length. Using
8814 // a Sliced String therefore requires unpacking of the parent string and
8815 // adding the offset to the start address. A substring of a Sliced String
8816 // are not nested since the double indirection is simplified when creating
8817 // such a substring.
8818 // Currently missing features are:
8819 // - handling externalized parent strings
8820 // - external strings as parent
8821 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8822 class SlicedString: public String {
8824 inline String* parent();
8825 inline void set_parent(String* parent,
8826 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8827 inline int offset() const;
8828 inline void set_offset(int offset);
8830 // Dispatched behavior.
8831 uint16_t SlicedStringGet(int index);
8833 DECLARE_CAST(SlicedString)
8835 // Layout description.
8836 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8837 static const int kOffsetOffset = kParentOffset + kPointerSize;
8838 static const int kSize = kOffsetOffset + kPointerSize;
8840 // Minimum length for a sliced string.
8841 static const int kMinLength = 13;
8843 typedef FixedBodyDescriptor<kParentOffset,
8844 kOffsetOffset + kPointerSize, kSize>
8847 DECLARE_VERIFIER(SlicedString)
8850 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8854 // The ExternalString class describes string values that are backed by
8855 // a string resource that lies outside the V8 heap. ExternalStrings
8856 // consist of the length field common to all strings, a pointer to the
8857 // external resource. It is important to ensure (externally) that the
8858 // resource is not deallocated while the ExternalString is live in the
8861 // The API expects that all ExternalStrings are created through the
8862 // API. Therefore, ExternalStrings should not be used internally.
8863 class ExternalString: public String {
8865 DECLARE_CAST(ExternalString)
8867 // Layout description.
8868 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8869 static const int kShortSize = kResourceOffset + kPointerSize;
8870 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8871 static const int kSize = kResourceDataOffset + kPointerSize;
8873 static const int kMaxShortLength =
8874 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8876 // Return whether external string is short (data pointer is not cached).
8877 inline bool is_short();
8879 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8882 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8886 // The ExternalOneByteString class is an external string backed by an
8888 class ExternalOneByteString : public ExternalString {
8890 static const bool kHasOneByteEncoding = true;
8892 typedef v8::String::ExternalOneByteStringResource Resource;
8894 // The underlying resource.
8895 inline const Resource* resource();
8896 inline void set_resource(const Resource* buffer);
8898 // Update the pointer cache to the external character array.
8899 // The cached pointer is always valid, as the external character array does =
8900 // not move during lifetime. Deserialization is the only exception, after
8901 // which the pointer cache has to be refreshed.
8902 inline void update_data_cache();
8904 inline const uint8_t* GetChars();
8906 // Dispatched behavior.
8907 inline uint16_t ExternalOneByteStringGet(int index);
8909 DECLARE_CAST(ExternalOneByteString)
8911 // Garbage collection support.
8912 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8914 template <typename StaticVisitor>
8915 inline void ExternalOneByteStringIterateBody();
8918 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8922 // The ExternalTwoByteString class is an external string backed by a UTF-16
8924 class ExternalTwoByteString: public ExternalString {
8926 static const bool kHasOneByteEncoding = false;
8928 typedef v8::String::ExternalStringResource Resource;
8930 // The underlying string resource.
8931 inline const Resource* resource();
8932 inline void set_resource(const Resource* buffer);
8934 // Update the pointer cache to the external character array.
8935 // The cached pointer is always valid, as the external character array does =
8936 // not move during lifetime. Deserialization is the only exception, after
8937 // which the pointer cache has to be refreshed.
8938 inline void update_data_cache();
8940 inline const uint16_t* GetChars();
8942 // Dispatched behavior.
8943 inline uint16_t ExternalTwoByteStringGet(int index);
8946 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8948 DECLARE_CAST(ExternalTwoByteString)
8950 // Garbage collection support.
8951 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8953 template<typename StaticVisitor>
8954 inline void ExternalTwoByteStringIterateBody();
8957 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8961 // Utility superclass for stack-allocated objects that must be updated
8962 // on gc. It provides two ways for the gc to update instances, either
8963 // iterating or updating after gc.
8964 class Relocatable BASE_EMBEDDED {
8966 explicit inline Relocatable(Isolate* isolate);
8967 inline virtual ~Relocatable();
8968 virtual void IterateInstance(ObjectVisitor* v) { }
8969 virtual void PostGarbageCollection() { }
8971 static void PostGarbageCollectionProcessing(Isolate* isolate);
8972 static int ArchiveSpacePerThread();
8973 static char* ArchiveState(Isolate* isolate, char* to);
8974 static char* RestoreState(Isolate* isolate, char* from);
8975 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8976 static void Iterate(ObjectVisitor* v, Relocatable* top);
8977 static char* Iterate(ObjectVisitor* v, char* t);
8985 // A flat string reader provides random access to the contents of a
8986 // string independent of the character width of the string. The handle
8987 // must be valid as long as the reader is being used.
8988 class FlatStringReader : public Relocatable {
8990 FlatStringReader(Isolate* isolate, Handle<String> str);
8991 FlatStringReader(Isolate* isolate, Vector<const char> input);
8992 void PostGarbageCollection();
8993 inline uc32 Get(int index);
8994 template <typename Char>
8995 inline Char Get(int index);
8996 int length() { return length_; }
9005 // This maintains an off-stack representation of the stack frames required
9006 // to traverse a ConsString, allowing an entirely iterative and restartable
9007 // traversal of the entire string
9008 class ConsStringIterator {
9010 inline ConsStringIterator() {}
9011 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9012 Reset(cons_string, offset);
9014 inline void Reset(ConsString* cons_string, int offset = 0) {
9016 // Next will always return NULL.
9017 if (cons_string == NULL) return;
9018 Initialize(cons_string, offset);
9020 // Returns NULL when complete.
9021 inline String* Next(int* offset_out) {
9023 if (depth_ == 0) return NULL;
9024 return Continue(offset_out);
9028 static const int kStackSize = 32;
9029 // Use a mask instead of doing modulo operations for stack wrapping.
9030 static const int kDepthMask = kStackSize-1;
9031 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9032 static inline int OffsetForDepth(int depth);
9034 inline void PushLeft(ConsString* string);
9035 inline void PushRight(ConsString* string);
9036 inline void AdjustMaximumDepth();
9038 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9039 void Initialize(ConsString* cons_string, int offset);
9040 String* Continue(int* offset_out);
9041 String* NextLeaf(bool* blew_stack);
9042 String* Search(int* offset_out);
9044 // Stack must always contain only frames for which right traversal
9045 // has not yet been performed.
9046 ConsString* frames_[kStackSize];
9051 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9055 class StringCharacterStream {
9057 inline StringCharacterStream(String* string,
9059 inline uint16_t GetNext();
9060 inline bool HasMore();
9061 inline void Reset(String* string, int offset = 0);
9062 inline void VisitOneByteString(const uint8_t* chars, int length);
9063 inline void VisitTwoByteString(const uint16_t* chars, int length);
9066 ConsStringIterator iter_;
9069 const uint8_t* buffer8_;
9070 const uint16_t* buffer16_;
9072 const uint8_t* end_;
9073 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9077 template <typename T>
9078 class VectorIterator {
9080 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9081 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9082 T GetNext() { return data_[index_++]; }
9083 bool has_more() { return index_ < data_.length(); }
9085 Vector<const T> data_;
9090 // The Oddball describes objects null, undefined, true, and false.
9091 class Oddball: public HeapObject {
9093 // [to_string]: Cached to_string computed at startup.
9094 DECL_ACCESSORS(to_string, String)
9096 // [to_number]: Cached to_number computed at startup.
9097 DECL_ACCESSORS(to_number, Object)
9099 // [typeof]: Cached type_of computed at startup.
9100 DECL_ACCESSORS(type_of, String)
9102 inline byte kind() const;
9103 inline void set_kind(byte kind);
9105 DECLARE_CAST(Oddball)
9107 // Dispatched behavior.
9108 DECLARE_VERIFIER(Oddball)
9110 // Initialize the fields.
9111 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9112 const char* to_string, Handle<Object> to_number,
9113 const char* type_of, byte kind);
9115 // Layout description.
9116 static const int kToStringOffset = HeapObject::kHeaderSize;
9117 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9118 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9119 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9120 static const int kSize = kKindOffset + kPointerSize;
9122 static const byte kFalse = 0;
9123 static const byte kTrue = 1;
9124 static const byte kNotBooleanMask = ~1;
9125 static const byte kTheHole = 2;
9126 static const byte kNull = 3;
9127 static const byte kArgumentMarker = 4;
9128 static const byte kUndefined = 5;
9129 static const byte kUninitialized = 6;
9130 static const byte kOther = 7;
9131 static const byte kException = 8;
9133 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9134 kSize> BodyDescriptor;
9136 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9137 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9138 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9141 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9145 class Cell: public HeapObject {
9147 // [value]: value of the cell.
9148 DECL_ACCESSORS(value, Object)
9152 static inline Cell* FromValueAddress(Address value) {
9153 Object* result = FromAddress(value - kValueOffset);
9154 return static_cast<Cell*>(result);
9157 inline Address ValueAddress() {
9158 return address() + kValueOffset;
9161 // Dispatched behavior.
9162 DECLARE_PRINTER(Cell)
9163 DECLARE_VERIFIER(Cell)
9165 // Layout description.
9166 static const int kValueOffset = HeapObject::kHeaderSize;
9167 static const int kSize = kValueOffset + kPointerSize;
9169 typedef FixedBodyDescriptor<kValueOffset,
9170 kValueOffset + kPointerSize,
9171 kSize> BodyDescriptor;
9174 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9178 class PropertyCell : public HeapObject {
9180 // [property_details]: details of the global property.
9181 DECL_ACCESSORS(property_details_raw, Object)
9182 // [value]: value of the global property.
9183 DECL_ACCESSORS(value, Object)
9184 // [dependent_code]: dependent code that depends on the type of the global
9186 DECL_ACCESSORS(dependent_code, DependentCode)
9188 inline PropertyDetails property_details();
9189 inline void set_property_details(PropertyDetails details);
9191 PropertyCellConstantType GetConstantType();
9193 // Computes the new type of the cell's contents for the given value, but
9194 // without actually modifying the details.
9195 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9196 Handle<Object> value,
9197 PropertyDetails details);
9198 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9199 Handle<Object> value, PropertyDetails details);
9201 static Handle<PropertyCell> InvalidateEntry(
9202 Handle<GlobalDictionary> dictionary, int entry);
9204 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9205 Handle<Object> new_value);
9207 DECLARE_CAST(PropertyCell)
9209 // Dispatched behavior.
9210 DECLARE_PRINTER(PropertyCell)
9211 DECLARE_VERIFIER(PropertyCell)
9213 // Layout description.
9214 static const int kDetailsOffset = HeapObject::kHeaderSize;
9215 static const int kValueOffset = kDetailsOffset + kPointerSize;
9216 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9217 static const int kSize = kDependentCodeOffset + kPointerSize;
9219 static const int kPointerFieldsBeginOffset = kValueOffset;
9220 static const int kPointerFieldsEndOffset = kSize;
9222 typedef FixedBodyDescriptor<kValueOffset,
9224 kSize> BodyDescriptor;
9227 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9231 class WeakCell : public HeapObject {
9233 inline Object* value() const;
9235 // This should not be called by anyone except GC.
9236 inline void clear();
9238 // This should not be called by anyone except allocator.
9239 inline void initialize(HeapObject* value);
9241 inline bool cleared() const;
9243 DECL_ACCESSORS(next, Object)
9245 inline void clear_next(Heap* heap);
9247 inline bool next_cleared();
9249 DECLARE_CAST(WeakCell)
9251 DECLARE_PRINTER(WeakCell)
9252 DECLARE_VERIFIER(WeakCell)
9254 // Layout description.
9255 static const int kValueOffset = HeapObject::kHeaderSize;
9256 static const int kNextOffset = kValueOffset + kPointerSize;
9257 static const int kSize = kNextOffset + kPointerSize;
9259 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9262 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9266 // The JSProxy describes EcmaScript Harmony proxies
9267 class JSProxy: public JSReceiver {
9269 // [handler]: The handler property.
9270 DECL_ACCESSORS(handler, Object)
9272 // [hash]: The hash code property (undefined if not initialized yet).
9273 DECL_ACCESSORS(hash, Object)
9275 DECLARE_CAST(JSProxy)
9277 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9278 Handle<JSProxy> proxy,
9279 Handle<Object> receiver,
9282 // If the handler defines an accessor property with a setter, invoke it.
9283 // If it defines an accessor property without a setter, or a data property
9284 // that is read-only, throw. In all these cases set '*done' to true,
9285 // otherwise set it to false.
9287 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9288 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9289 Handle<Object> value, LanguageMode language_mode, bool* done);
9291 MUST_USE_RESULT static Maybe<PropertyAttributes>
9292 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9293 Handle<Object> receiver,
9295 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9296 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9297 Handle<Object> value, LanguageMode language_mode);
9299 // Turn the proxy into an (empty) JSObject.
9300 static void Fix(Handle<JSProxy> proxy);
9302 // Initializes the body after the handler slot.
9303 inline void InitializeBody(int object_size, Object* value);
9305 // Invoke a trap by name. If the trap does not exist on this's handler,
9306 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9307 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9308 Handle<JSProxy> proxy,
9310 Handle<Object> derived_trap,
9312 Handle<Object> args[]);
9314 // Dispatched behavior.
9315 DECLARE_PRINTER(JSProxy)
9316 DECLARE_VERIFIER(JSProxy)
9318 // Layout description. We add padding so that a proxy has the same
9319 // size as a virgin JSObject. This is essential for becoming a JSObject
9321 static const int kHandlerOffset = HeapObject::kHeaderSize;
9322 static const int kHashOffset = kHandlerOffset + kPointerSize;
9323 static const int kPaddingOffset = kHashOffset + kPointerSize;
9324 static const int kSize = JSObject::kHeaderSize;
9325 static const int kHeaderSize = kPaddingOffset;
9326 static const int kPaddingSize = kSize - kPaddingOffset;
9328 STATIC_ASSERT(kPaddingSize >= 0);
9330 typedef FixedBodyDescriptor<kHandlerOffset,
9332 kSize> BodyDescriptor;
9335 friend class JSReceiver;
9337 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9338 Handle<JSProxy> proxy, Handle<Name> name);
9340 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9341 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9343 MUST_USE_RESULT Object* GetIdentityHash();
9345 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9347 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9351 class JSFunctionProxy: public JSProxy {
9353 // [call_trap]: The call trap.
9354 DECL_ACCESSORS(call_trap, JSReceiver)
9356 // [construct_trap]: The construct trap.
9357 DECL_ACCESSORS(construct_trap, Object)
9359 DECLARE_CAST(JSFunctionProxy)
9361 // Dispatched behavior.
9362 DECLARE_PRINTER(JSFunctionProxy)
9363 DECLARE_VERIFIER(JSFunctionProxy)
9365 // Layout description.
9366 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9367 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9368 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9369 static const int kSize = JSFunction::kSize;
9370 static const int kPaddingSize = kSize - kPaddingOffset;
9372 STATIC_ASSERT(kPaddingSize >= 0);
9374 typedef FixedBodyDescriptor<kHandlerOffset,
9375 kConstructTrapOffset + kPointerSize,
9376 kSize> BodyDescriptor;
9379 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9383 class JSCollection : public JSObject {
9385 // [table]: the backing hash table
9386 DECL_ACCESSORS(table, Object)
9388 static const int kTableOffset = JSObject::kHeaderSize;
9389 static const int kSize = kTableOffset + kPointerSize;
9392 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9396 // The JSSet describes EcmaScript Harmony sets
9397 class JSSet : public JSCollection {
9401 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9402 static void Clear(Handle<JSSet> set);
9404 // Dispatched behavior.
9405 DECLARE_PRINTER(JSSet)
9406 DECLARE_VERIFIER(JSSet)
9409 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9413 // The JSMap describes EcmaScript Harmony maps
9414 class JSMap : public JSCollection {
9418 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9419 static void Clear(Handle<JSMap> map);
9421 // Dispatched behavior.
9422 DECLARE_PRINTER(JSMap)
9423 DECLARE_VERIFIER(JSMap)
9426 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9430 // OrderedHashTableIterator is an iterator that iterates over the keys and
9431 // values of an OrderedHashTable.
9433 // The iterator has a reference to the underlying OrderedHashTable data,
9434 // [table], as well as the current [index] the iterator is at.
9436 // When the OrderedHashTable is rehashed it adds a reference from the old table
9437 // to the new table as well as storing enough data about the changes so that the
9438 // iterator [index] can be adjusted accordingly.
9440 // When the [Next] result from the iterator is requested, the iterator checks if
9441 // there is a newer table that it needs to transition to.
9442 template<class Derived, class TableType>
9443 class OrderedHashTableIterator: public JSObject {
9445 // [table]: the backing hash table mapping keys to values.
9446 DECL_ACCESSORS(table, Object)
9448 // [index]: The index into the data table.
9449 DECL_ACCESSORS(index, Object)
9451 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9452 DECL_ACCESSORS(kind, Object)
9455 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9458 static const int kTableOffset = JSObject::kHeaderSize;
9459 static const int kIndexOffset = kTableOffset + kPointerSize;
9460 static const int kKindOffset = kIndexOffset + kPointerSize;
9461 static const int kSize = kKindOffset + kPointerSize;
9469 // Whether the iterator has more elements. This needs to be called before
9470 // calling |CurrentKey| and/or |CurrentValue|.
9473 // Move the index forward one.
9475 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9478 // Populates the array with the next key and value and then moves the iterator
9480 // This returns the |kind| or 0 if the iterator is already at the end.
9481 Smi* Next(JSArray* value_array);
9483 // Returns the current key of the iterator. This should only be called when
9484 // |HasMore| returns true.
9485 inline Object* CurrentKey();
9488 // Transitions the iterator to the non obsolete backing store. This is a NOP
9489 // if the [table] is not obsolete.
9492 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9496 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9499 // Dispatched behavior.
9500 DECLARE_PRINTER(JSSetIterator)
9501 DECLARE_VERIFIER(JSSetIterator)
9503 DECLARE_CAST(JSSetIterator)
9505 // Called by |Next| to populate the array. This allows the subclasses to
9506 // populate the array differently.
9507 inline void PopulateValueArray(FixedArray* array);
9510 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9514 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9517 // Dispatched behavior.
9518 DECLARE_PRINTER(JSMapIterator)
9519 DECLARE_VERIFIER(JSMapIterator)
9521 DECLARE_CAST(JSMapIterator)
9523 // Called by |Next| to populate the array. This allows the subclasses to
9524 // populate the array differently.
9525 inline void PopulateValueArray(FixedArray* array);
9528 // Returns the current value of the iterator. This should only be called when
9529 // |HasMore| returns true.
9530 inline Object* CurrentValue();
9532 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9536 // ES6 section 25.1.1.3 The IteratorResult Interface
9537 class JSIteratorResult final : public JSObject {
9539 // [done]: This is the result status of an iterator next method call. If the
9540 // end of the iterator was reached done is true. If the end was not reached
9541 // done is false and a [value] is available.
9542 DECL_ACCESSORS(done, Object)
9544 // [value]: If [done] is false, this is the current iteration element value.
9545 // If [done] is true, this is the return value of the iterator, if it supplied
9546 // one. If the iterator does not have a return value, value is undefined.
9547 // In that case, the value property may be absent from the conforming object
9548 // if it does not inherit an explicit value property.
9549 DECL_ACCESSORS(value, Object)
9551 // Dispatched behavior.
9552 DECLARE_PRINTER(JSIteratorResult)
9553 DECLARE_VERIFIER(JSIteratorResult)
9555 DECLARE_CAST(JSIteratorResult)
9557 static const int kValueOffset = JSObject::kHeaderSize;
9558 static const int kDoneOffset = kValueOffset + kPointerSize;
9559 static const int kSize = kDoneOffset + kPointerSize;
9561 // Indices of in-object properties.
9562 static const int kValueIndex = 0;
9563 static const int kDoneIndex = 1;
9566 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9570 // Base class for both JSWeakMap and JSWeakSet
9571 class JSWeakCollection: public JSObject {
9573 // [table]: the backing hash table mapping keys to values.
9574 DECL_ACCESSORS(table, Object)
9576 // [next]: linked list of encountered weak maps during GC.
9577 DECL_ACCESSORS(next, Object)
9579 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9580 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9581 Handle<Object> value, int32_t hash);
9582 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9585 static const int kTableOffset = JSObject::kHeaderSize;
9586 static const int kNextOffset = kTableOffset + kPointerSize;
9587 static const int kSize = kNextOffset + kPointerSize;
9590 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9594 // The JSWeakMap describes EcmaScript Harmony weak maps
9595 class JSWeakMap: public JSWeakCollection {
9597 DECLARE_CAST(JSWeakMap)
9599 // Dispatched behavior.
9600 DECLARE_PRINTER(JSWeakMap)
9601 DECLARE_VERIFIER(JSWeakMap)
9604 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9608 // The JSWeakSet describes EcmaScript Harmony weak sets
9609 class JSWeakSet: public JSWeakCollection {
9611 DECLARE_CAST(JSWeakSet)
9613 // Dispatched behavior.
9614 DECLARE_PRINTER(JSWeakSet)
9615 DECLARE_VERIFIER(JSWeakSet)
9618 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9622 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9623 enum class SharedFlag { kNotShared, kShared };
9626 class JSArrayBuffer: public JSObject {
9628 // [backing_store]: backing memory for this array
9629 DECL_ACCESSORS(backing_store, void)
9631 // [byte_length]: length in bytes
9632 DECL_ACCESSORS(byte_length, Object)
9634 inline uint32_t bit_field() const;
9635 inline void set_bit_field(uint32_t bits);
9637 inline bool is_external();
9638 inline void set_is_external(bool value);
9640 inline bool is_neuterable();
9641 inline void set_is_neuterable(bool value);
9643 inline bool was_neutered();
9644 inline void set_was_neutered(bool value);
9646 inline bool is_shared();
9647 inline void set_is_shared(bool value);
9649 DECLARE_CAST(JSArrayBuffer)
9653 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9654 bool is_external, void* data, size_t allocated_length,
9655 SharedFlag shared = SharedFlag::kNotShared);
9657 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9658 Isolate* isolate, size_t allocated_length,
9659 bool initialize = true,
9660 SharedFlag shared = SharedFlag::kNotShared);
9662 // Dispatched behavior.
9663 DECLARE_PRINTER(JSArrayBuffer)
9664 DECLARE_VERIFIER(JSArrayBuffer)
9666 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9667 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9668 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9669 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9670 static const int kBitFieldOffset = kBitFieldSlot;
9672 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9674 static const int kSize = kBitFieldSlot + kPointerSize;
9676 static const int kSizeWithInternalFields =
9677 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9679 class IsExternal : public BitField<bool, 1, 1> {};
9680 class IsNeuterable : public BitField<bool, 2, 1> {};
9681 class WasNeutered : public BitField<bool, 3, 1> {};
9682 class IsShared : public BitField<bool, 4, 1> {};
9685 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9689 class JSArrayBufferView: public JSObject {
9691 // [buffer]: ArrayBuffer that this typed array views.
9692 DECL_ACCESSORS(buffer, Object)
9694 // [byte_offset]: offset of typed array in bytes.
9695 DECL_ACCESSORS(byte_offset, Object)
9697 // [byte_length]: length of typed array in bytes.
9698 DECL_ACCESSORS(byte_length, Object)
9700 DECLARE_CAST(JSArrayBufferView)
9702 DECLARE_VERIFIER(JSArrayBufferView)
9704 inline bool WasNeutered() const;
9706 static const int kBufferOffset = JSObject::kHeaderSize;
9707 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9708 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9709 static const int kViewSize = kByteLengthOffset + kPointerSize;
9713 DECL_ACCESSORS(raw_byte_offset, Object)
9714 DECL_ACCESSORS(raw_byte_length, Object)
9717 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9721 class JSTypedArray: public JSArrayBufferView {
9723 // [length]: length of typed array in elements.
9724 DECL_ACCESSORS(length, Object)
9725 inline uint32_t length_value() const;
9727 DECLARE_CAST(JSTypedArray)
9729 ExternalArrayType type();
9730 size_t element_size();
9732 Handle<JSArrayBuffer> GetBuffer();
9734 // Dispatched behavior.
9735 DECLARE_PRINTER(JSTypedArray)
9736 DECLARE_VERIFIER(JSTypedArray)
9738 static const int kLengthOffset = kViewSize + kPointerSize;
9739 static const int kSize = kLengthOffset + kPointerSize;
9741 static const int kSizeWithInternalFields =
9742 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9745 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9746 Handle<JSTypedArray> typed_array);
9748 DECL_ACCESSORS(raw_length, Object)
9751 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9755 class JSDataView: public JSArrayBufferView {
9757 DECLARE_CAST(JSDataView)
9759 // Dispatched behavior.
9760 DECLARE_PRINTER(JSDataView)
9761 DECLARE_VERIFIER(JSDataView)
9763 static const int kSize = kViewSize;
9765 static const int kSizeWithInternalFields =
9766 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9769 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9773 // Foreign describes objects pointing from JavaScript to C structures.
9774 class Foreign: public HeapObject {
9776 // [address]: field containing the address.
9777 inline Address foreign_address();
9778 inline void set_foreign_address(Address value);
9780 DECLARE_CAST(Foreign)
9782 // Dispatched behavior.
9783 inline void ForeignIterateBody(ObjectVisitor* v);
9785 template<typename StaticVisitor>
9786 inline void ForeignIterateBody();
9788 // Dispatched behavior.
9789 DECLARE_PRINTER(Foreign)
9790 DECLARE_VERIFIER(Foreign)
9792 // Layout description.
9794 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9795 static const int kSize = kForeignAddressOffset + kPointerSize;
9797 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9800 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9804 // The JSArray describes JavaScript Arrays
9805 // Such an array can be in one of two modes:
9806 // - fast, backing storage is a FixedArray and length <= elements.length();
9807 // Please note: push and pop can be used to grow and shrink the array.
9808 // - slow, backing storage is a HashTable with numbers as keys.
9809 class JSArray: public JSObject {
9811 // [length]: The length property.
9812 DECL_ACCESSORS(length, Object)
9814 // Overload the length setter to skip write barrier when the length
9815 // is set to a smi. This matches the set function on FixedArray.
9816 inline void set_length(Smi* length);
9818 static bool HasReadOnlyLength(Handle<JSArray> array);
9819 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9820 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9822 // Initialize the array with the given capacity. The function may
9823 // fail due to out-of-memory situations, but only if the requested
9824 // capacity is non-zero.
9825 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9827 // If the JSArray has fast elements, and new_length would result in
9828 // normalization, returns true.
9829 bool SetLengthWouldNormalize(uint32_t new_length);
9830 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9832 // Initializes the array to a certain length.
9833 inline bool AllowsSetLength();
9835 static void SetLength(Handle<JSArray> array, uint32_t length);
9836 // Same as above but will also queue splice records if |array| is observed.
9837 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9840 // Set the content of the array to the content of storage.
9841 static inline void SetContent(Handle<JSArray> array,
9842 Handle<FixedArrayBase> storage);
9844 DECLARE_CAST(JSArray)
9846 // Dispatched behavior.
9847 DECLARE_PRINTER(JSArray)
9848 DECLARE_VERIFIER(JSArray)
9850 // Number of element slots to pre-allocate for an empty array.
9851 static const int kPreallocatedArrayElements = 4;
9853 // Layout description.
9854 static const int kLengthOffset = JSObject::kHeaderSize;
9855 static const int kSize = kLengthOffset + kPointerSize;
9858 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9862 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9863 Handle<Map> initial_map);
9866 // JSRegExpResult is just a JSArray with a specific initial map.
9867 // This initial map adds in-object properties for "index" and "input"
9868 // properties, as assigned by RegExp.prototype.exec, which allows
9869 // faster creation of RegExp exec results.
9870 // This class just holds constants used when creating the result.
9871 // After creation the result must be treated as a JSArray in all regards.
9872 class JSRegExpResult: public JSArray {
9874 // Offsets of object fields.
9875 static const int kIndexOffset = JSArray::kSize;
9876 static const int kInputOffset = kIndexOffset + kPointerSize;
9877 static const int kSize = kInputOffset + kPointerSize;
9878 // Indices of in-object properties.
9879 static const int kIndexIndex = 0;
9880 static const int kInputIndex = 1;
9882 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9886 class AccessorInfo: public Struct {
9888 DECL_ACCESSORS(name, Object)
9889 DECL_ACCESSORS(flag, Smi)
9890 DECL_ACCESSORS(expected_receiver_type, Object)
9892 inline bool all_can_read();
9893 inline void set_all_can_read(bool value);
9895 inline bool all_can_write();
9896 inline void set_all_can_write(bool value);
9898 inline bool is_special_data_property();
9899 inline void set_is_special_data_property(bool value);
9901 inline PropertyAttributes property_attributes();
9902 inline void set_property_attributes(PropertyAttributes attributes);
9904 // Checks whether the given receiver is compatible with this accessor.
9905 static bool IsCompatibleReceiverMap(Isolate* isolate,
9906 Handle<AccessorInfo> info,
9908 inline bool IsCompatibleReceiver(Object* receiver);
9910 DECLARE_CAST(AccessorInfo)
9912 // Dispatched behavior.
9913 DECLARE_VERIFIER(AccessorInfo)
9915 // Append all descriptors to the array that are not already there.
9916 // Return number added.
9917 static int AppendUnique(Handle<Object> descriptors,
9918 Handle<FixedArray> array,
9919 int valid_descriptors);
9921 static const int kNameOffset = HeapObject::kHeaderSize;
9922 static const int kFlagOffset = kNameOffset + kPointerSize;
9923 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9924 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9927 inline bool HasExpectedReceiverType();
9929 // Bit positions in flag.
9930 static const int kAllCanReadBit = 0;
9931 static const int kAllCanWriteBit = 1;
9932 static const int kSpecialDataProperty = 2;
9933 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9935 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9939 // An accessor must have a getter, but can have no setter.
9941 // When setting a property, V8 searches accessors in prototypes.
9942 // If an accessor was found and it does not have a setter,
9943 // the request is ignored.
9945 // If the accessor in the prototype has the READ_ONLY property attribute, then
9946 // a new value is added to the derived object when the property is set.
9947 // This shadows the accessor in the prototype.
9948 class ExecutableAccessorInfo: public AccessorInfo {
9950 DECL_ACCESSORS(getter, Object)
9951 DECL_ACCESSORS(setter, Object)
9952 DECL_ACCESSORS(data, Object)
9954 DECLARE_CAST(ExecutableAccessorInfo)
9956 // Dispatched behavior.
9957 DECLARE_PRINTER(ExecutableAccessorInfo)
9958 DECLARE_VERIFIER(ExecutableAccessorInfo)
9960 static const int kGetterOffset = AccessorInfo::kSize;
9961 static const int kSetterOffset = kGetterOffset + kPointerSize;
9962 static const int kDataOffset = kSetterOffset + kPointerSize;
9963 static const int kSize = kDataOffset + kPointerSize;
9965 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9968 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9972 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9973 // accessor can either be
9974 // * a pointer to a JavaScript function or proxy: a real accessor
9975 // * undefined: considered an accessor by the spec, too, strangely enough
9976 // * the hole: an accessor which has not been set
9977 // * a pointer to a map: a transition used to ensure map sharing
9978 class AccessorPair: public Struct {
9980 DECL_ACCESSORS(getter, Object)
9981 DECL_ACCESSORS(setter, Object)
9983 DECLARE_CAST(AccessorPair)
9985 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9987 inline Object* get(AccessorComponent component);
9988 inline void set(AccessorComponent component, Object* value);
9990 // Note: Returns undefined instead in case of a hole.
9991 Object* GetComponent(AccessorComponent component);
9993 // Set both components, skipping arguments which are a JavaScript null.
9994 inline void SetComponents(Object* getter, Object* setter);
9996 inline bool Equals(AccessorPair* pair);
9997 inline bool Equals(Object* getter_value, Object* setter_value);
9999 inline bool ContainsAccessor();
10001 // Dispatched behavior.
10002 DECLARE_PRINTER(AccessorPair)
10003 DECLARE_VERIFIER(AccessorPair)
10005 static const int kGetterOffset = HeapObject::kHeaderSize;
10006 static const int kSetterOffset = kGetterOffset + kPointerSize;
10007 static const int kSize = kSetterOffset + kPointerSize;
10010 // Strangely enough, in addition to functions and harmony proxies, the spec
10011 // requires us to consider undefined as a kind of accessor, too:
10013 // Object.defineProperty(obj, "foo", {get: undefined});
10014 // assertTrue("foo" in obj);
10015 inline bool IsJSAccessor(Object* obj);
10017 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10021 class AccessCheckInfo: public Struct {
10023 DECL_ACCESSORS(named_callback, Object)
10024 DECL_ACCESSORS(indexed_callback, Object)
10025 DECL_ACCESSORS(data, Object)
10027 DECLARE_CAST(AccessCheckInfo)
10029 // Dispatched behavior.
10030 DECLARE_PRINTER(AccessCheckInfo)
10031 DECLARE_VERIFIER(AccessCheckInfo)
10033 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10034 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10035 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10036 static const int kSize = kDataOffset + kPointerSize;
10039 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10043 class InterceptorInfo: public Struct {
10045 DECL_ACCESSORS(getter, Object)
10046 DECL_ACCESSORS(setter, Object)
10047 DECL_ACCESSORS(query, Object)
10048 DECL_ACCESSORS(deleter, Object)
10049 DECL_ACCESSORS(enumerator, Object)
10050 DECL_ACCESSORS(data, Object)
10051 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10052 DECL_BOOLEAN_ACCESSORS(all_can_read)
10053 DECL_BOOLEAN_ACCESSORS(non_masking)
10055 inline int flags() const;
10056 inline void set_flags(int flags);
10058 DECLARE_CAST(InterceptorInfo)
10060 // Dispatched behavior.
10061 DECLARE_PRINTER(InterceptorInfo)
10062 DECLARE_VERIFIER(InterceptorInfo)
10064 static const int kGetterOffset = HeapObject::kHeaderSize;
10065 static const int kSetterOffset = kGetterOffset + kPointerSize;
10066 static const int kQueryOffset = kSetterOffset + kPointerSize;
10067 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10068 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10069 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10070 static const int kFlagsOffset = kDataOffset + kPointerSize;
10071 static const int kSize = kFlagsOffset + kPointerSize;
10073 static const int kCanInterceptSymbolsBit = 0;
10074 static const int kAllCanReadBit = 1;
10075 static const int kNonMasking = 2;
10078 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10082 class CallHandlerInfo: public Struct {
10084 DECL_ACCESSORS(callback, Object)
10085 DECL_ACCESSORS(data, Object)
10087 DECLARE_CAST(CallHandlerInfo)
10089 // Dispatched behavior.
10090 DECLARE_PRINTER(CallHandlerInfo)
10091 DECLARE_VERIFIER(CallHandlerInfo)
10093 static const int kCallbackOffset = HeapObject::kHeaderSize;
10094 static const int kDataOffset = kCallbackOffset + kPointerSize;
10095 static const int kSize = kDataOffset + kPointerSize;
10098 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10102 class TemplateInfo: public Struct {
10104 DECL_ACCESSORS(tag, Object)
10105 inline int number_of_properties() const;
10106 inline void set_number_of_properties(int value);
10107 DECL_ACCESSORS(property_list, Object)
10108 DECL_ACCESSORS(property_accessors, Object)
10110 DECLARE_VERIFIER(TemplateInfo)
10112 static const int kTagOffset = HeapObject::kHeaderSize;
10113 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10114 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10115 static const int kPropertyAccessorsOffset =
10116 kPropertyListOffset + kPointerSize;
10117 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10120 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10124 class FunctionTemplateInfo: public TemplateInfo {
10126 DECL_ACCESSORS(serial_number, Object)
10127 DECL_ACCESSORS(call_code, Object)
10128 DECL_ACCESSORS(prototype_template, Object)
10129 DECL_ACCESSORS(parent_template, Object)
10130 DECL_ACCESSORS(named_property_handler, Object)
10131 DECL_ACCESSORS(indexed_property_handler, Object)
10132 DECL_ACCESSORS(instance_template, Object)
10133 DECL_ACCESSORS(class_name, Object)
10134 DECL_ACCESSORS(signature, Object)
10135 DECL_ACCESSORS(instance_call_handler, Object)
10136 DECL_ACCESSORS(access_check_info, Object)
10137 DECL_ACCESSORS(flag, Smi)
10139 inline int length() const;
10140 inline void set_length(int value);
10142 // Following properties use flag bits.
10143 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10144 DECL_BOOLEAN_ACCESSORS(undetectable)
10145 // If the bit is set, object instances created by this function
10146 // requires access check.
10147 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10148 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10149 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10150 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10151 DECL_BOOLEAN_ACCESSORS(instantiated)
10152 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10154 DECLARE_CAST(FunctionTemplateInfo)
10156 // Dispatched behavior.
10157 DECLARE_PRINTER(FunctionTemplateInfo)
10158 DECLARE_VERIFIER(FunctionTemplateInfo)
10160 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10161 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10162 static const int kPrototypeTemplateOffset =
10163 kCallCodeOffset + kPointerSize;
10164 static const int kParentTemplateOffset =
10165 kPrototypeTemplateOffset + kPointerSize;
10166 static const int kNamedPropertyHandlerOffset =
10167 kParentTemplateOffset + kPointerSize;
10168 static const int kIndexedPropertyHandlerOffset =
10169 kNamedPropertyHandlerOffset + kPointerSize;
10170 static const int kInstanceTemplateOffset =
10171 kIndexedPropertyHandlerOffset + kPointerSize;
10172 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10173 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10174 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10175 static const int kAccessCheckInfoOffset =
10176 kInstanceCallHandlerOffset + kPointerSize;
10177 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10178 static const int kLengthOffset = kFlagOffset + kPointerSize;
10179 static const int kSize = kLengthOffset + kPointerSize;
10181 // Returns true if |object| is an instance of this function template.
10182 bool IsTemplateFor(Object* object);
10183 bool IsTemplateFor(Map* map);
10185 // Returns the holder JSObject if the function can legally be called with this
10186 // receiver. Returns Heap::null_value() if the call is illegal.
10187 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10190 // Bit position in the flag, from least significant bit position.
10191 static const int kHiddenPrototypeBit = 0;
10192 static const int kUndetectableBit = 1;
10193 static const int kNeedsAccessCheckBit = 2;
10194 static const int kReadOnlyPrototypeBit = 3;
10195 static const int kRemovePrototypeBit = 4;
10196 static const int kDoNotCacheBit = 5;
10197 static const int kInstantiatedBit = 6;
10198 static const int kAcceptAnyReceiver = 7;
10200 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10204 class ObjectTemplateInfo: public TemplateInfo {
10206 DECL_ACCESSORS(constructor, Object)
10207 DECL_ACCESSORS(internal_field_count, Object)
10209 DECLARE_CAST(ObjectTemplateInfo)
10211 // Dispatched behavior.
10212 DECLARE_PRINTER(ObjectTemplateInfo)
10213 DECLARE_VERIFIER(ObjectTemplateInfo)
10215 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10216 static const int kInternalFieldCountOffset =
10217 kConstructorOffset + kPointerSize;
10218 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10222 class TypeSwitchInfo: public Struct {
10224 DECL_ACCESSORS(types, Object)
10226 DECLARE_CAST(TypeSwitchInfo)
10228 // Dispatched behavior.
10229 DECLARE_PRINTER(TypeSwitchInfo)
10230 DECLARE_VERIFIER(TypeSwitchInfo)
10232 static const int kTypesOffset = Struct::kHeaderSize;
10233 static const int kSize = kTypesOffset + kPointerSize;
10237 // The DebugInfo class holds additional information for a function being
10239 class DebugInfo: public Struct {
10241 // The shared function info for the source being debugged.
10242 DECL_ACCESSORS(shared, SharedFunctionInfo)
10243 // Code object for the patched code. This code object is the code object
10244 // currently active for the function.
10245 DECL_ACCESSORS(code, Code)
10246 // Fixed array holding status information for each active break point.
10247 DECL_ACCESSORS(break_points, FixedArray)
10249 // Check if there is a break point at a code position.
10250 bool HasBreakPoint(int code_position);
10251 // Get the break point info object for a code position.
10252 Object* GetBreakPointInfo(int code_position);
10253 // Clear a break point.
10254 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10256 Handle<Object> break_point_object);
10257 // Set a break point.
10258 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10259 int source_position, int statement_position,
10260 Handle<Object> break_point_object);
10261 // Get the break point objects for a code position.
10262 Handle<Object> GetBreakPointObjects(int code_position);
10263 // Find the break point info holding this break point object.
10264 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10265 Handle<Object> break_point_object);
10266 // Get the number of break points for this function.
10267 int GetBreakPointCount();
10269 DECLARE_CAST(DebugInfo)
10271 // Dispatched behavior.
10272 DECLARE_PRINTER(DebugInfo)
10273 DECLARE_VERIFIER(DebugInfo)
10275 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10276 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10277 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10278 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10280 static const int kEstimatedNofBreakPointsInFunction = 16;
10283 static const int kNoBreakPointInfo = -1;
10285 // Lookup the index in the break_points array for a code position.
10286 int GetBreakPointInfoIndex(int code_position);
10288 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10292 // The BreakPointInfo class holds information for break points set in a
10293 // function. The DebugInfo object holds a BreakPointInfo object for each code
10294 // position with one or more break points.
10295 class BreakPointInfo: public Struct {
10297 // The position in the code for the break point.
10298 DECL_ACCESSORS(code_position, Smi)
10299 // The position in the source for the break position.
10300 DECL_ACCESSORS(source_position, Smi)
10301 // The position in the source for the last statement before this break
10303 DECL_ACCESSORS(statement_position, Smi)
10304 // List of related JavaScript break points.
10305 DECL_ACCESSORS(break_point_objects, Object)
10307 // Removes a break point.
10308 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10309 Handle<Object> break_point_object);
10310 // Set a break point.
10311 static void SetBreakPoint(Handle<BreakPointInfo> info,
10312 Handle<Object> break_point_object);
10313 // Check if break point info has this break point object.
10314 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10315 Handle<Object> break_point_object);
10316 // Get the number of break points for this code position.
10317 int GetBreakPointCount();
10319 DECLARE_CAST(BreakPointInfo)
10321 // Dispatched behavior.
10322 DECLARE_PRINTER(BreakPointInfo)
10323 DECLARE_VERIFIER(BreakPointInfo)
10325 static const int kCodePositionIndex = Struct::kHeaderSize;
10326 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10327 static const int kStatementPositionIndex =
10328 kSourcePositionIndex + kPointerSize;
10329 static const int kBreakPointObjectsIndex =
10330 kStatementPositionIndex + kPointerSize;
10331 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10334 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10338 #undef DECL_BOOLEAN_ACCESSORS
10339 #undef DECL_ACCESSORS
10340 #undef DECLARE_CAST
10341 #undef DECLARE_VERIFIER
10343 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10344 V(kStringTable, "string_table", "(Internalized strings)") \
10345 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10346 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10347 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10348 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10349 V(kTop, "top", "(Isolate)") \
10350 V(kRelocatable, "relocatable", "(Relocatable)") \
10351 V(kDebug, "debug", "(Debugger)") \
10352 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10353 V(kHandleScope, "handlescope", "(Handle scope)") \
10354 V(kBuiltins, "builtins", "(Builtins)") \
10355 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10356 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10357 V(kThreadManager, "threadmanager", "(Thread manager)") \
10358 V(kStrongRoots, "strong roots", "(Strong roots)") \
10359 V(kExtensions, "Extensions", "(Extensions)")
10361 class VisitorSynchronization : public AllStatic {
10363 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10365 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10368 #undef DECLARE_ENUM
10370 static const char* const kTags[kNumberOfSyncTags];
10371 static const char* const kTagNames[kNumberOfSyncTags];
10374 // Abstract base class for visiting, and optionally modifying, the
10375 // pointers contained in Objects. Used in GC and serialization/deserialization.
10376 class ObjectVisitor BASE_EMBEDDED {
10378 virtual ~ObjectVisitor() {}
10380 // Visits a contiguous arrays of pointers in the half-open range
10381 // [start, end). Any or all of the values may be modified on return.
10382 virtual void VisitPointers(Object** start, Object** end) = 0;
10384 // Handy shorthand for visiting a single pointer.
10385 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10387 // Visit weak next_code_link in Code object.
10388 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10390 // To allow lazy clearing of inline caches the visitor has
10391 // a rich interface for iterating over Code objects..
10393 // Visits a code target in the instruction stream.
10394 virtual void VisitCodeTarget(RelocInfo* rinfo);
10396 // Visits a code entry in a JS function.
10397 virtual void VisitCodeEntry(Address entry_address);
10399 // Visits a global property cell reference in the instruction stream.
10400 virtual void VisitCell(RelocInfo* rinfo);
10402 // Visits a runtime entry in the instruction stream.
10403 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10405 // Visits the resource of an one-byte or two-byte string.
10406 virtual void VisitExternalOneByteString(
10407 v8::String::ExternalOneByteStringResource** resource) {}
10408 virtual void VisitExternalTwoByteString(
10409 v8::String::ExternalStringResource** resource) {}
10411 // Visits a debug call target in the instruction stream.
10412 virtual void VisitDebugTarget(RelocInfo* rinfo);
10414 // Visits the byte sequence in a function's prologue that contains information
10415 // about the code's age.
10416 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10418 // Visit pointer embedded into a code object.
10419 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10421 // Visits an external reference embedded into a code object.
10422 virtual void VisitExternalReference(RelocInfo* rinfo);
10424 // Visits an external reference.
10425 virtual void VisitExternalReference(Address* p) {}
10427 // Visits an (encoded) internal reference.
10428 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10430 // Visits a handle that has an embedder-assigned class ID.
10431 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10433 // Intended for serialization/deserialization checking: insert, or
10434 // check for the presence of, a tag at this position in the stream.
10435 // Also used for marking up GC roots in heap snapshots.
10436 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10440 class StructBodyDescriptor : public
10441 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10443 static inline int SizeOf(Map* map, HeapObject* object);
10447 // BooleanBit is a helper class for setting and getting a bit in an
10449 class BooleanBit : public AllStatic {
10451 static inline bool get(Smi* smi, int bit_position) {
10452 return get(smi->value(), bit_position);
10455 static inline bool get(int value, int bit_position) {
10456 return (value & (1 << bit_position)) != 0;
10459 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10460 return Smi::FromInt(set(smi->value(), bit_position, v));
10463 static inline int set(int value, int bit_position, bool v) {
10465 value |= (1 << bit_position);
10467 value &= ~(1 << bit_position);
10473 } } // namespace v8::internal
10475 #endif // V8_OBJECTS_H_