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-inl.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
90 // - JSFunctionResultCache
93 // - ScriptContextTable
100 // - SeqTwoByteString
104 // - ExternalOneByteString
105 // - ExternalTwoByteString
106 // - InternalizedString
107 // - SeqInternalizedString
108 // - SeqOneByteInternalizedString
109 // - SeqTwoByteInternalizedString
110 // - ConsInternalizedString
111 // - ExternalInternalizedString
112 // - ExternalOneByteInternalizedString
113 // - ExternalTwoByteInternalizedString
123 // - SharedFunctionInfo
127 // - ExecutableAccessorInfo
133 // - FunctionTemplateInfo
134 // - ObjectTemplateInfo
143 // Formats of Object*:
144 // Smi: [31 bit signed int] 0
145 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
150 enum KeyedAccessStoreMode {
152 STORE_TRANSITION_SMI_TO_OBJECT,
153 STORE_TRANSITION_SMI_TO_DOUBLE,
154 STORE_TRANSITION_DOUBLE_TO_OBJECT,
155 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
156 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
157 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
158 STORE_AND_GROW_NO_TRANSITION,
159 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
160 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
161 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
162 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
163 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
164 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
165 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
166 STORE_NO_TRANSITION_HANDLE_COW
170 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
179 enum ExternalArrayType {
180 kExternalInt8Array = 1,
183 kExternalUint16Array,
185 kExternalUint32Array,
186 kExternalFloat32Array,
187 kExternalFloat64Array,
188 kExternalUint8ClampedArray,
192 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
194 STATIC_ASSERT(STANDARD_STORE == 0);
195 STATIC_ASSERT(kGrowICDelta ==
196 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
197 STORE_TRANSITION_SMI_TO_OBJECT);
198 STATIC_ASSERT(kGrowICDelta ==
199 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
200 STORE_TRANSITION_SMI_TO_DOUBLE);
201 STATIC_ASSERT(kGrowICDelta ==
202 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
203 STORE_TRANSITION_DOUBLE_TO_OBJECT);
206 static inline KeyedAccessStoreMode GetGrowStoreMode(
207 KeyedAccessStoreMode store_mode) {
208 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
209 store_mode = static_cast<KeyedAccessStoreMode>(
210 static_cast<int>(store_mode) + kGrowICDelta);
216 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
217 return store_mode > STANDARD_STORE &&
218 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
219 store_mode != STORE_AND_GROW_NO_TRANSITION;
223 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
224 KeyedAccessStoreMode store_mode) {
225 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
228 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
229 return STORE_AND_GROW_NO_TRANSITION;
231 return STANDARD_STORE;
235 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
236 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
237 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
241 enum IcCheckType { ELEMENT, PROPERTY };
244 // SKIP_WRITE_BARRIER skips the write barrier.
245 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
246 // only performs the generational part.
247 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
248 enum WriteBarrierMode {
250 UPDATE_WEAK_WRITE_BARRIER,
255 // Indicates whether a value can be loaded as a constant.
256 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
259 // PropertyNormalizationMode is used to specify whether to keep
260 // inobject properties when normalizing properties of a JSObject.
261 enum PropertyNormalizationMode {
262 CLEAR_INOBJECT_PROPERTIES,
263 KEEP_INOBJECT_PROPERTIES
267 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
268 // will give the fastest result by tailoring the map to the prototype, but that
269 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
270 // (at least for now) when dynamically modifying the prototype chain of an
271 // object using __proto__ or Object.setPrototypeOf.
272 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
275 // Indicates whether transitions can be added to a source map or not.
276 enum TransitionFlag {
282 // Indicates whether the transition is simple: the target map of the transition
283 // either extends the current map with a new property, or it modifies the
284 // property that was added last to the current map.
285 enum SimpleTransitionFlag {
286 SIMPLE_PROPERTY_TRANSITION,
292 // Indicates whether we are only interested in the descriptors of a particular
293 // map, or in all descriptors in the descriptor array.
294 enum DescriptorFlag {
299 // The GC maintains a bit of information, the MarkingParity, which toggles
300 // from odd to even and back every time marking is completed. Incremental
301 // marking can visit an object twice during a marking phase, so algorithms that
302 // that piggy-back on marking can use the parity to ensure that they only
303 // perform an operation on an object once per marking phase: they record the
304 // MarkingParity when they visit an object, and only re-visit the object when it
305 // is marked again and the MarkingParity changes.
312 // ICs store extra state in a Code object. The default extra state is
314 typedef int ExtraICState;
315 static const ExtraICState kNoExtraICState = 0;
317 // Instance size sentinel for objects of variable size.
318 const int kVariableSizeSentinel = 0;
320 // We may store the unsigned bit field as signed Smi value and do not
322 const int kStubMajorKeyBits = 7;
323 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
325 // All Maps have a field instance_type containing a InstanceType.
326 // It describes the type of the instances.
328 // As an example, a JavaScript object is a heap object and its map
329 // instance_type is JS_OBJECT_TYPE.
331 // The names of the string instance types are intended to systematically
332 // mirror their encoding in the instance_type field of the map. The default
333 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
334 // encoding is mentioned explicitly in the name. Likewise, the default
335 // representation is considered sequential. It is not mentioned in the
336 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
337 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
338 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
340 // NOTE: The following things are some that depend on the string types having
341 // instance_types that are less than those of all other types:
342 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
345 // NOTE: Everything following JS_VALUE_TYPE is considered a
346 // JSObject for GC purposes. The first four entries here have typeof
347 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
348 #define INSTANCE_TYPE_LIST(V) \
350 V(ONE_BYTE_STRING_TYPE) \
351 V(CONS_STRING_TYPE) \
352 V(CONS_ONE_BYTE_STRING_TYPE) \
353 V(SLICED_STRING_TYPE) \
354 V(SLICED_ONE_BYTE_STRING_TYPE) \
355 V(EXTERNAL_STRING_TYPE) \
356 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
357 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
358 V(SHORT_EXTERNAL_STRING_TYPE) \
359 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
360 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
362 V(INTERNALIZED_STRING_TYPE) \
363 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
364 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
365 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
366 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
367 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
368 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
369 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
378 V(PROPERTY_CELL_TYPE) \
380 V(HEAP_NUMBER_TYPE) \
381 V(MUTABLE_HEAP_NUMBER_TYPE) \
384 V(BYTECODE_ARRAY_TYPE) \
387 V(FIXED_INT8_ARRAY_TYPE) \
388 V(FIXED_UINT8_ARRAY_TYPE) \
389 V(FIXED_INT16_ARRAY_TYPE) \
390 V(FIXED_UINT16_ARRAY_TYPE) \
391 V(FIXED_INT32_ARRAY_TYPE) \
392 V(FIXED_UINT32_ARRAY_TYPE) \
393 V(FIXED_FLOAT32_ARRAY_TYPE) \
394 V(FIXED_FLOAT64_ARRAY_TYPE) \
395 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
399 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
400 V(DECLARED_ACCESSOR_INFO_TYPE) \
401 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
402 V(ACCESSOR_PAIR_TYPE) \
403 V(ACCESS_CHECK_INFO_TYPE) \
404 V(INTERCEPTOR_INFO_TYPE) \
405 V(CALL_HANDLER_INFO_TYPE) \
406 V(FUNCTION_TEMPLATE_INFO_TYPE) \
407 V(OBJECT_TEMPLATE_INFO_TYPE) \
408 V(SIGNATURE_INFO_TYPE) \
409 V(TYPE_SWITCH_INFO_TYPE) \
410 V(ALLOCATION_MEMENTO_TYPE) \
411 V(ALLOCATION_SITE_TYPE) \
414 V(POLYMORPHIC_CODE_CACHE_TYPE) \
415 V(TYPE_FEEDBACK_INFO_TYPE) \
416 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
418 V(PROTOTYPE_INFO_TYPE) \
420 V(FIXED_ARRAY_TYPE) \
421 V(FIXED_DOUBLE_ARRAY_TYPE) \
422 V(SHARED_FUNCTION_INFO_TYPE) \
425 V(JS_MESSAGE_OBJECT_TYPE) \
430 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
431 V(JS_GENERATOR_OBJECT_TYPE) \
433 V(JS_GLOBAL_OBJECT_TYPE) \
434 V(JS_BUILTINS_OBJECT_TYPE) \
435 V(JS_GLOBAL_PROXY_TYPE) \
437 V(JS_ARRAY_BUFFER_TYPE) \
438 V(JS_TYPED_ARRAY_TYPE) \
439 V(JS_DATA_VIEW_TYPE) \
443 V(JS_SET_ITERATOR_TYPE) \
444 V(JS_MAP_ITERATOR_TYPE) \
445 V(JS_WEAK_MAP_TYPE) \
446 V(JS_WEAK_SET_TYPE) \
449 V(JS_FUNCTION_TYPE) \
450 V(JS_FUNCTION_PROXY_TYPE) \
452 V(BREAK_POINT_INFO_TYPE)
455 // Since string types are not consecutive, this macro is used to
456 // iterate over them.
457 #define STRING_TYPE_LIST(V) \
458 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
459 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
461 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
462 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
464 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
465 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
466 SlicedOneByteString) \
467 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
469 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
470 external_one_byte_string, ExternalOneByteString) \
471 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
472 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
473 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
474 short_external_string, ShortExternalString) \
475 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
476 short_external_one_byte_string, ShortExternalOneByteString) \
477 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
478 ExternalTwoByteString::kShortSize, \
479 short_external_string_with_one_byte_data, \
480 ShortExternalStringWithOneByteData) \
482 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
483 InternalizedString) \
484 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
485 one_byte_internalized_string, OneByteInternalizedString) \
486 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
487 external_internalized_string, ExternalInternalizedString) \
488 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
489 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
490 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
491 ExternalTwoByteString::kSize, \
492 external_internalized_string_with_one_byte_data, \
493 ExternalInternalizedStringWithOneByteData) \
494 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
495 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
496 ShortExternalInternalizedString) \
497 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
498 ExternalOneByteString::kShortSize, \
499 short_external_one_byte_internalized_string, \
500 ShortExternalOneByteInternalizedString) \
501 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
502 ExternalTwoByteString::kShortSize, \
503 short_external_internalized_string_with_one_byte_data, \
504 ShortExternalInternalizedStringWithOneByteData)
506 // A struct is a simple object a set of object-valued fields. Including an
507 // object type in this causes the compiler to generate most of the boilerplate
508 // code for the class including allocation and garbage collection routines,
509 // casts and predicates. All you need to define is the class, methods and
510 // object verification routines. Easy, no?
512 // Note that for subtle reasons related to the ordering or numerical values of
513 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
515 #define STRUCT_LIST(V) \
517 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
518 executable_accessor_info) \
519 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
520 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
521 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
522 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
523 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
524 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
525 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
526 V(SCRIPT, Script, script) \
527 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
528 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
529 V(CODE_CACHE, CodeCache, code_cache) \
530 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
531 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
532 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
533 V(DEBUG_INFO, DebugInfo, debug_info) \
534 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
535 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
537 // We use the full 8 bits of the instance_type field to encode heap object
538 // instance types. The high-order bit (bit 7) is set if the object is not a
539 // string, and cleared if it is a string.
540 const uint32_t kIsNotStringMask = 0x80;
541 const uint32_t kStringTag = 0x0;
542 const uint32_t kNotStringTag = 0x80;
544 // Bit 6 indicates that the object is an internalized string (if set) or not.
545 // Bit 7 has to be clear as well.
546 const uint32_t kIsNotInternalizedMask = 0x40;
547 const uint32_t kNotInternalizedTag = 0x40;
548 const uint32_t kInternalizedTag = 0x0;
550 // If bit 7 is clear then bit 2 indicates whether the string consists of
551 // two-byte characters or one-byte characters.
552 const uint32_t kStringEncodingMask = 0x4;
553 const uint32_t kTwoByteStringTag = 0x0;
554 const uint32_t kOneByteStringTag = 0x4;
556 // If bit 7 is clear, the low-order 2 bits indicate the representation
558 const uint32_t kStringRepresentationMask = 0x03;
559 enum StringRepresentationTag {
561 kConsStringTag = 0x1,
562 kExternalStringTag = 0x2,
563 kSlicedStringTag = 0x3
565 const uint32_t kIsIndirectStringMask = 0x1;
566 const uint32_t kIsIndirectStringTag = 0x1;
567 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
568 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
569 STATIC_ASSERT((kConsStringTag &
570 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
571 STATIC_ASSERT((kSlicedStringTag &
572 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
574 // Use this mask to distinguish between cons and slice only after making
575 // sure that the string is one of the two (an indirect string).
576 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
577 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
579 // If bit 7 is clear, then bit 3 indicates whether this two-byte
580 // string actually contains one byte data.
581 const uint32_t kOneByteDataHintMask = 0x08;
582 const uint32_t kOneByteDataHintTag = 0x08;
584 // If bit 7 is clear and string representation indicates an external string,
585 // then bit 4 indicates whether the data pointer is cached.
586 const uint32_t kShortExternalStringMask = 0x10;
587 const uint32_t kShortExternalStringTag = 0x10;
590 // A ConsString with an empty string as the right side is a candidate
591 // for being shortcut by the garbage collector. We don't allocate any
592 // non-flat internalized strings, so we do not shortcut them thereby
593 // avoiding turning internalized strings into strings. The bit-masks
594 // below contain the internalized bit as additional safety.
595 // See heap.cc, mark-compact.cc and objects-visiting.cc.
596 const uint32_t kShortcutTypeMask =
598 kIsNotInternalizedMask |
599 kStringRepresentationMask;
600 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
602 static inline bool IsShortcutCandidate(int type) {
603 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
609 INTERNALIZED_STRING_TYPE =
610 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
611 ONE_BYTE_INTERNALIZED_STRING_TYPE =
612 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
613 EXTERNAL_INTERNALIZED_STRING_TYPE =
614 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
615 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
616 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
617 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
618 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
620 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
621 kShortExternalStringTag |
623 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
624 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
626 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
627 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
628 kShortExternalStringTag | kInternalizedTag,
629 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
630 ONE_BYTE_STRING_TYPE =
631 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
632 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
633 CONS_ONE_BYTE_STRING_TYPE =
634 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
636 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
637 SLICED_ONE_BYTE_STRING_TYPE =
638 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
639 EXTERNAL_STRING_TYPE =
640 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
641 EXTERNAL_ONE_BYTE_STRING_TYPE =
642 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
643 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
644 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
646 SHORT_EXTERNAL_STRING_TYPE =
647 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
648 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
649 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
650 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
651 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
655 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
657 // Objects allocated in their own spaces (never in new space).
662 // "Data", objects that cannot contain non-map-word pointers to heap
665 MUTABLE_HEAP_NUMBER_TYPE,
666 FLOAT32X4_TYPE, // FIRST_SIMD_TYPE, LAST_SIMD_TYPE
671 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
672 FIXED_UINT8_ARRAY_TYPE,
673 FIXED_INT16_ARRAY_TYPE,
674 FIXED_UINT16_ARRAY_TYPE,
675 FIXED_INT32_ARRAY_TYPE,
676 FIXED_UINT32_ARRAY_TYPE,
677 FIXED_FLOAT32_ARRAY_TYPE,
678 FIXED_FLOAT64_ARRAY_TYPE,
679 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
680 FIXED_DOUBLE_ARRAY_TYPE,
681 FILLER_TYPE, // LAST_DATA_TYPE
684 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
685 DECLARED_ACCESSOR_INFO_TYPE,
686 EXECUTABLE_ACCESSOR_INFO_TYPE,
688 ACCESS_CHECK_INFO_TYPE,
689 INTERCEPTOR_INFO_TYPE,
690 CALL_HANDLER_INFO_TYPE,
691 FUNCTION_TEMPLATE_INFO_TYPE,
692 OBJECT_TEMPLATE_INFO_TYPE,
694 TYPE_SWITCH_INFO_TYPE,
695 ALLOCATION_SITE_TYPE,
696 ALLOCATION_MEMENTO_TYPE,
699 POLYMORPHIC_CODE_CACHE_TYPE,
700 TYPE_FEEDBACK_INFO_TYPE,
701 ALIASED_ARGUMENTS_ENTRY_TYPE,
704 BREAK_POINT_INFO_TYPE,
706 SHARED_FUNCTION_INFO_TYPE,
712 // All the following types are subtypes of JSReceiver, which corresponds to
713 // objects in the JS sense. The first and the last type in this range are
714 // the two forms of function. This organization enables using the same
715 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
716 // NONCALLABLE_JS_OBJECT range.
717 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
718 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
719 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
720 JS_MESSAGE_OBJECT_TYPE,
723 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
724 JS_GENERATOR_OBJECT_TYPE,
726 JS_GLOBAL_OBJECT_TYPE,
727 JS_BUILTINS_OBJECT_TYPE,
728 JS_GLOBAL_PROXY_TYPE,
730 JS_ARRAY_BUFFER_TYPE,
735 JS_SET_ITERATOR_TYPE,
736 JS_MAP_ITERATOR_TYPE,
740 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
744 LAST_TYPE = JS_FUNCTION_TYPE,
745 FIRST_NAME_TYPE = FIRST_TYPE,
746 LAST_NAME_TYPE = SYMBOL_TYPE,
747 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
748 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
749 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
750 // Boundaries for testing for a SIMD type.
751 FIRST_SIMD_TYPE = FLOAT32X4_TYPE,
752 LAST_SIMD_TYPE = FLOAT32X4_TYPE,
753 // Boundaries for testing for a fixed typed array.
754 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
755 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
756 // Boundary for promotion to old space.
757 LAST_DATA_TYPE = FILLER_TYPE,
758 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
759 // Note that there is no range for JSObject or JSProxy, since their subtypes
760 // are not continuous in this enum! The enum ranges instead reflect the
761 // external class names, where proxies are treated as either ordinary objects,
763 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
764 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
765 // Boundaries for testing the types represented as JSObject
766 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
767 LAST_JS_OBJECT_TYPE = LAST_TYPE,
768 // Boundaries for testing the types represented as JSProxy
769 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
770 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
771 // Boundaries for testing whether the type is a JavaScript object.
772 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
773 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
774 // Boundaries for testing the types for which typeof is "object".
775 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
776 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
777 // Note that the types for which typeof is "function" are not continuous.
778 // Define this so that we can put assertions on discrete checks.
779 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
782 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
783 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
784 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
785 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
788 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
789 V(FAST_ELEMENTS_SUB_TYPE) \
790 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
791 V(FAST_PROPERTIES_SUB_TYPE) \
792 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
793 V(MAP_CODE_CACHE_SUB_TYPE) \
794 V(SCOPE_INFO_SUB_TYPE) \
795 V(STRING_TABLE_SUB_TYPE) \
796 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
797 V(TRANSITION_ARRAY_SUB_TYPE)
799 enum FixedArraySubInstanceType {
800 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
801 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
802 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
803 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
816 #define DECL_BOOLEAN_ACCESSORS(name) \
817 inline bool name() const; \
818 inline void set_##name(bool value); \
821 #define DECL_ACCESSORS(name, type) \
822 inline type* name() const; \
823 inline void set_##name(type* value, \
824 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
827 #define DECLARE_CAST(type) \
828 INLINE(static type* cast(Object* object)); \
829 INLINE(static const type* cast(const Object* object));
833 class AllocationSite;
834 class AllocationSiteCreationContext;
835 class AllocationSiteUsageContext;
838 class ElementsAccessor;
839 class FixedArrayBase;
840 class FunctionLiteral;
842 class JSBuiltinsObject;
843 class LayoutDescriptor;
844 class LookupIterator;
845 class ObjectHashTable;
848 class SafepointEntry;
849 class SharedFunctionInfo;
851 class TypeFeedbackInfo;
852 class TypeFeedbackVector;
855 // We cannot just say "class HeapType;" if it is created from a template... =8-?
856 template<class> class TypeImpl;
857 struct HeapTypeConfig;
858 typedef TypeImpl<HeapTypeConfig> HeapType;
861 // A template-ized version of the IsXXX functions.
862 template <class C> inline bool Is(Object* obj);
865 #define DECLARE_VERIFIER(Name) void Name##Verify();
867 #define DECLARE_VERIFIER(Name)
871 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
873 #define DECLARE_PRINTER(Name)
877 #define OBJECT_TYPE_LIST(V) \
882 #define HEAP_OBJECT_TYPE_LIST(V) \
884 V(MutableHeapNumber) \
893 V(ExternalTwoByteString) \
894 V(ExternalOneByteString) \
895 V(SeqTwoByteString) \
896 V(SeqOneByteString) \
897 V(InternalizedString) \
900 V(FixedTypedArrayBase) \
903 V(FixedUint16Array) \
905 V(FixedUint32Array) \
907 V(FixedFloat32Array) \
908 V(FixedFloat64Array) \
909 V(FixedUint8ClampedArray) \
915 V(JSContextExtensionObject) \
916 V(JSGeneratorObject) \
918 V(LayoutDescriptor) \
922 V(TypeFeedbackVector) \
923 V(DeoptimizationInputData) \
924 V(DeoptimizationOutputData) \
928 V(FixedDoubleArray) \
932 V(ScriptContextTable) \
938 V(SharedFunctionInfo) \
947 V(JSArrayBufferView) \
956 V(JSWeakCollection) \
963 V(JSFunctionResultCache) \
964 V(NormalizedMapCache) \
965 V(CompilationCacheTable) \
966 V(CodeCacheHashTable) \
967 V(PolymorphicCodeCacheHashTable) \
972 V(JSBuiltinsObject) \
974 V(UndetectableObject) \
975 V(AccessCheckNeeded) \
981 V(WeakValueHashTable) \
984 // Object is the abstract superclass for all classes in the
986 // Object does not use any virtual functions to avoid the
987 // allocation of the C++ vtable.
988 // Since both Smi and HeapObject are subclasses of Object no
989 // data members can be present in Object.
993 bool IsObject() const { return true; }
995 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
996 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
997 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
998 #undef IS_TYPE_FUNCTION_DECL
1000 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1001 // a keyed store is of the form a[expression] = foo.
1002 enum StoreFromKeyed {
1003 MAY_BE_STORE_FROM_KEYED,
1004 CERTAINLY_NOT_STORE_FROM_KEYED
1007 INLINE(bool IsFixedArrayBase() const);
1008 INLINE(bool IsExternal() const);
1009 INLINE(bool IsAccessorInfo() const);
1011 INLINE(bool IsStruct() const);
1012 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1013 INLINE(bool Is##Name() const);
1014 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1015 #undef DECLARE_STRUCT_PREDICATE
1017 INLINE(bool IsSpecObject()) const;
1018 INLINE(bool IsSpecFunction()) const;
1019 INLINE(bool IsTemplateInfo()) const;
1020 INLINE(bool IsNameDictionary() const);
1021 INLINE(bool IsGlobalDictionary() const);
1022 INLINE(bool IsSeededNumberDictionary() const);
1023 INLINE(bool IsUnseededNumberDictionary() const);
1024 INLINE(bool IsOrderedHashSet() const);
1025 INLINE(bool IsOrderedHashMap() const);
1026 bool IsCallable() const;
1027 static bool IsPromise(Handle<Object> object);
1030 INLINE(bool IsUndefined() const);
1031 INLINE(bool IsNull() const);
1032 INLINE(bool IsTheHole() const);
1033 INLINE(bool IsException() const);
1034 INLINE(bool IsUninitialized() const);
1035 INLINE(bool IsTrue() const);
1036 INLINE(bool IsFalse() const);
1037 INLINE(bool IsArgumentsMarker() const);
1039 // Filler objects (fillers and free space objects).
1040 INLINE(bool IsFiller() const);
1042 // Extract the number.
1043 inline double Number();
1044 INLINE(bool IsNaN() const);
1045 INLINE(bool IsMinusZero() const);
1046 bool ToInt32(int32_t* value);
1047 bool ToUint32(uint32_t* value);
1049 inline Representation OptimalRepresentation() {
1050 if (!FLAG_track_fields) return Representation::Tagged();
1052 return Representation::Smi();
1053 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1054 return Representation::Double();
1055 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1056 return Representation::None();
1057 } else if (FLAG_track_heap_object_fields) {
1058 DCHECK(IsHeapObject());
1059 return Representation::HeapObject();
1061 return Representation::Tagged();
1065 inline ElementsKind OptimalElementsKind() {
1066 if (IsSmi()) return FAST_SMI_ELEMENTS;
1067 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1068 return FAST_ELEMENTS;
1071 inline bool FitsRepresentation(Representation representation) {
1072 if (FLAG_track_fields && representation.IsNone()) {
1074 } else if (FLAG_track_fields && representation.IsSmi()) {
1076 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1077 return IsMutableHeapNumber() || IsNumber();
1078 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1079 return IsHeapObject();
1084 // Checks whether two valid primitive encodings of a property name resolve to
1085 // the same logical property. E.g., the smi 1, the string "1" and the double
1086 // 1 all refer to the same property, so this helper will return true.
1087 inline bool KeyEquals(Object* other);
1089 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1091 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1092 Handle<Object> object,
1093 Representation representation);
1095 inline static Handle<Object> WrapForRead(Isolate* isolate,
1096 Handle<Object> object,
1097 Representation representation);
1099 // Returns true if the object is of the correct type to be used as a
1100 // implementation of a JSObject's elements.
1101 inline bool HasValidElements();
1103 inline bool HasSpecificClassOf(String* name);
1105 bool BooleanValue(); // ECMA-262 9.2.
1107 // Convert to a JSObject if needed.
1108 // native_context is used when creating wrapper object.
1109 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1110 Handle<Object> object);
1111 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1112 Handle<Object> object,
1113 Handle<Context> context);
1115 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1116 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1118 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1119 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1120 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1121 LanguageMode language_mode,
1122 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1124 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1125 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1126 StoreFromKeyed store_mode);
1128 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1129 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1130 StoreFromKeyed store_mode);
1132 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1133 LookupIterator* it, LanguageMode language_mode);
1134 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1135 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1136 LanguageMode language_mode);
1137 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1138 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1139 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1140 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1141 Handle<Object> value, LanguageMode language_mode);
1142 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1143 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1144 LanguageMode language_mode);
1145 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1146 LookupIterator* it, Handle<Object> value);
1147 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1148 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1149 LanguageMode language_mode, StoreFromKeyed store_mode);
1150 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1151 Handle<Object> object, Handle<Name> name,
1152 LanguageMode language_mode = SLOPPY);
1153 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1154 Isolate* isolate, Handle<Object> object, const char* key,
1155 LanguageMode language_mode = SLOPPY);
1156 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1157 Handle<Object> object, Handle<Name> name,
1158 LanguageMode language_mode = SLOPPY);
1160 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1161 LookupIterator* it, LanguageMode language_mode);
1162 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1163 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1165 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1166 Handle<Object> receiver,
1167 Handle<JSReceiver> getter);
1168 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1169 Handle<Object> receiver,
1170 Handle<JSReceiver> setter,
1171 Handle<Object> value);
1173 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1174 Isolate* isolate, Handle<Object> object, uint32_t index,
1175 LanguageMode language_mode = SLOPPY);
1177 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1178 Isolate* isolate, Handle<Object> object, uint32_t index,
1179 Handle<Object> value, LanguageMode language_mode);
1181 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1182 Isolate* isolate, Handle<Object> receiver);
1184 // Returns the permanent hash code associated with this object. May return
1185 // undefined if not yet created.
1188 // Returns undefined for JSObjects, but returns the hash code for simple
1189 // objects. This avoids a double lookup in the cases where we know we will
1190 // add the hash to the JSObject if it does not already exist.
1191 Object* GetSimpleHash();
1193 // Returns the permanent hash code associated with this object depending on
1194 // the actual object type. May create and store a hash code if needed and none
1196 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1198 // Checks whether this object has the same value as the given one. This
1199 // function is implemented according to ES5, section 9.12 and can be used
1200 // to implement the Harmony "egal" function.
1201 bool SameValue(Object* other);
1203 // Checks whether this object has the same value as the given one.
1204 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1205 // This function is implemented according to ES6, section 7.2.4 and is used
1206 // by ES6 Map and Set.
1207 bool SameValueZero(Object* other);
1209 // Tries to convert an object to an array length. Returns true and sets the
1210 // output parameter if it succeeds.
1211 inline bool ToArrayLength(uint32_t* index);
1213 // Tries to convert an object to an array index. Returns true and sets the
1214 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1215 // allow kMaxUInt32.
1216 inline bool ToArrayIndex(uint32_t* index);
1218 // Returns true if this is a JSValue containing a string and the index is
1219 // < the length of the string. Used to implement [] on strings.
1220 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1222 DECLARE_VERIFIER(Object)
1224 // Verify a pointer is a valid object pointer.
1225 static void VerifyPointer(Object* p);
1228 inline void VerifyApiCallResultType();
1230 // Prints this object without details.
1231 void ShortPrint(FILE* out = stdout);
1233 // Prints this object without details to a message accumulator.
1234 void ShortPrint(StringStream* accumulator);
1236 void ShortPrint(std::ostream& os); // NOLINT
1238 DECLARE_CAST(Object)
1240 // Layout description.
1241 static const int kHeaderSize = 0; // Object does not take up any space.
1244 // For our gdb macros, we should perhaps change these in the future.
1247 // Prints this object with details.
1248 void Print(std::ostream& os); // NOLINT
1250 void Print() { ShortPrint(); }
1251 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1255 friend class LookupIterator;
1256 friend class PrototypeIterator;
1258 // Return the map of the root of object's prototype chain.
1259 Map* GetRootMap(Isolate* isolate);
1261 // Helper for SetProperty and SetSuperProperty.
1262 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1263 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1264 StoreFromKeyed store_mode, bool* found);
1266 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1271 explicit Brief(const Object* const v) : value(v) {}
1272 const Object* value;
1276 std::ostream& operator<<(std::ostream& os, const Brief& v);
1279 // Smi represents integer Numbers that can be stored in 31 bits.
1280 // Smis are immediate which means they are NOT allocated in the heap.
1281 // The this pointer has the following format: [31 bit signed int] 0
1282 // For long smis it has the following format:
1283 // [32 bit signed int] [31 bits zero padding] 0
1284 // Smi stands for small integer.
1285 class Smi: public Object {
1287 // Returns the integer value.
1288 inline int value() const;
1290 // Convert a value to a Smi object.
1291 static inline Smi* FromInt(int value);
1293 static inline Smi* FromIntptr(intptr_t value);
1295 // Returns whether value can be represented in a Smi.
1296 static inline bool IsValid(intptr_t value);
1300 // Dispatched behavior.
1301 void SmiPrint(std::ostream& os) const; // NOLINT
1302 DECLARE_VERIFIER(Smi)
1304 static const int kMinValue =
1305 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1306 static const int kMaxValue = -(kMinValue + 1);
1309 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1313 // Heap objects typically have a map pointer in their first word. However,
1314 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1315 // encoded in the first word. The class MapWord is an abstraction of the
1316 // value in a heap object's first word.
1317 class MapWord BASE_EMBEDDED {
1319 // Normal state: the map word contains a map pointer.
1321 // Create a map word from a map pointer.
1322 static inline MapWord FromMap(const Map* map);
1324 // View this map word as a map pointer.
1325 inline Map* ToMap();
1328 // Scavenge collection: the map word of live objects in the from space
1329 // contains a forwarding address (a heap object pointer in the to space).
1331 // True if this map word is a forwarding address for a scavenge
1332 // collection. Only valid during a scavenge collection (specifically,
1333 // when all map words are heap object pointers, i.e. not during a full GC).
1334 inline bool IsForwardingAddress();
1336 // Create a map word from a forwarding address.
1337 static inline MapWord FromForwardingAddress(HeapObject* object);
1339 // View this map word as a forwarding address.
1340 inline HeapObject* ToForwardingAddress();
1342 static inline MapWord FromRawValue(uintptr_t value) {
1343 return MapWord(value);
1346 inline uintptr_t ToRawValue() {
1351 // HeapObject calls the private constructor and directly reads the value.
1352 friend class HeapObject;
1354 explicit MapWord(uintptr_t value) : value_(value) {}
1360 // The content of an heap object (except for the map pointer). kTaggedValues
1361 // objects can contain both heap pointers and Smis, kMixedValues can contain
1362 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1363 // objects can contain raw values and Smis.
1364 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1367 // HeapObject is the superclass for all classes describing heap allocated
1369 class HeapObject: public Object {
1371 // [map]: Contains a map which contains the object's reflective
1373 inline Map* map() const;
1374 inline void set_map(Map* value);
1375 // The no-write-barrier version. This is OK if the object is white and in
1376 // new space, or if the value is an immortal immutable object, like the maps
1377 // of primitive (non-JS) objects like strings, heap numbers etc.
1378 inline void set_map_no_write_barrier(Map* value);
1380 // Get the map using acquire load.
1381 inline Map* synchronized_map();
1382 inline MapWord synchronized_map_word() const;
1384 // Set the map using release store
1385 inline void synchronized_set_map(Map* value);
1386 inline void synchronized_set_map_no_write_barrier(Map* value);
1387 inline void synchronized_set_map_word(MapWord map_word);
1389 // During garbage collection, the map word of a heap object does not
1390 // necessarily contain a map pointer.
1391 inline MapWord map_word() const;
1392 inline void set_map_word(MapWord map_word);
1394 // The Heap the object was allocated in. Used also to access Isolate.
1395 inline Heap* GetHeap() const;
1397 // Convenience method to get current isolate.
1398 inline Isolate* GetIsolate() const;
1400 // Converts an address to a HeapObject pointer.
1401 static inline HeapObject* FromAddress(Address address);
1403 // Returns the address of this HeapObject.
1404 inline Address address();
1406 // Iterates over pointers contained in the object (including the Map)
1407 void Iterate(ObjectVisitor* v);
1409 // Iterates over all pointers contained in the object except the
1410 // first map pointer. The object type is given in the first
1411 // parameter. This function does not access the map pointer in the
1412 // object, and so is safe to call while the map pointer is modified.
1413 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1415 // Returns the heap object's size in bytes
1418 // Indicates what type of values this heap object may contain.
1419 inline HeapObjectContents ContentType();
1421 // Given a heap object's map pointer, returns the heap size in bytes
1422 // Useful when the map pointer field is used for other purposes.
1424 inline int SizeFromMap(Map* map);
1426 // Returns the field at offset in obj, as a read/write Object* reference.
1427 // Does no checking, and is safe to use during GC, while maps are invalid.
1428 // Does not invoke write barrier, so should only be assigned to
1429 // during marking GC.
1430 static inline Object** RawField(HeapObject* obj, int offset);
1432 // Adds the |code| object related to |name| to the code cache of this map. If
1433 // this map is a dictionary map that is shared, the map copied and installed
1435 static void UpdateMapCodeCache(Handle<HeapObject> object,
1439 DECLARE_CAST(HeapObject)
1441 // Return the write barrier mode for this. Callers of this function
1442 // must be able to present a reference to an DisallowHeapAllocation
1443 // object as a sign that they are not going to use this function
1444 // from code that allocates and thus invalidates the returned write
1446 inline WriteBarrierMode GetWriteBarrierMode(
1447 const DisallowHeapAllocation& promise);
1449 // Dispatched behavior.
1450 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1452 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1454 DECLARE_PRINTER(HeapObject)
1455 DECLARE_VERIFIER(HeapObject)
1457 inline void VerifyObjectField(int offset);
1458 inline void VerifySmiField(int offset);
1460 // Verify a pointer is a valid HeapObject pointer that points to object
1461 // areas in the heap.
1462 static void VerifyHeapPointer(Object* p);
1465 inline AllocationAlignment RequiredAlignment();
1467 // Layout description.
1468 // First field in a heap object is map.
1469 static const int kMapOffset = Object::kHeaderSize;
1470 static const int kHeaderSize = kMapOffset + kPointerSize;
1472 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1475 // helpers for calling an ObjectVisitor to iterate over pointers in the
1476 // half-open range [start, end) specified as integer offsets
1477 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1478 // as above, for the single element at "offset"
1479 inline void IteratePointer(ObjectVisitor* v, int offset);
1480 // as above, for the next code link of a code object.
1481 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1484 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1488 // This class describes a body of an object of a fixed size
1489 // in which all pointer fields are located in the [start_offset, end_offset)
1491 template<int start_offset, int end_offset, int size>
1492 class FixedBodyDescriptor {
1494 static const int kStartOffset = start_offset;
1495 static const int kEndOffset = end_offset;
1496 static const int kSize = size;
1498 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1500 template<typename StaticVisitor>
1501 static inline void IterateBody(HeapObject* obj) {
1502 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1503 HeapObject::RawField(obj, end_offset));
1508 // This class describes a body of an object of a variable size
1509 // in which all pointer fields are located in the [start_offset, object_size)
1511 template<int start_offset>
1512 class FlexibleBodyDescriptor {
1514 static const int kStartOffset = start_offset;
1516 static inline void IterateBody(HeapObject* obj,
1520 template<typename StaticVisitor>
1521 static inline void IterateBody(HeapObject* obj, int object_size) {
1522 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1523 HeapObject::RawField(obj, object_size));
1528 // The HeapNumber class describes heap allocated numbers that cannot be
1529 // represented in a Smi (small integer)
1530 class HeapNumber: public HeapObject {
1532 // [value]: number value.
1533 inline double value() const;
1534 inline void set_value(double value);
1536 DECLARE_CAST(HeapNumber)
1538 // Dispatched behavior.
1539 bool HeapNumberBooleanValue();
1541 void HeapNumberPrint(std::ostream& os); // NOLINT
1542 DECLARE_VERIFIER(HeapNumber)
1544 inline int get_exponent();
1545 inline int get_sign();
1547 // Layout description.
1548 static const int kValueOffset = HeapObject::kHeaderSize;
1549 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1550 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1551 // words within double numbers are endian dependent and they are set
1553 #if defined(V8_TARGET_LITTLE_ENDIAN)
1554 static const int kMantissaOffset = kValueOffset;
1555 static const int kExponentOffset = kValueOffset + 4;
1556 #elif defined(V8_TARGET_BIG_ENDIAN)
1557 static const int kMantissaOffset = kValueOffset + 4;
1558 static const int kExponentOffset = kValueOffset;
1560 #error Unknown byte ordering
1563 static const int kSize = kValueOffset + kDoubleSize;
1564 static const uint32_t kSignMask = 0x80000000u;
1565 static const uint32_t kExponentMask = 0x7ff00000u;
1566 static const uint32_t kMantissaMask = 0xfffffu;
1567 static const int kMantissaBits = 52;
1568 static const int kExponentBits = 11;
1569 static const int kExponentBias = 1023;
1570 static const int kExponentShift = 20;
1571 static const int kInfinityOrNanExponent =
1572 (kExponentMask >> kExponentShift) - kExponentBias;
1573 static const int kMantissaBitsInTopWord = 20;
1574 static const int kNonMantissaBitsInTopWord = 12;
1577 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1581 // The Float32x4 class describes heap allocated SIMD values holding 4 32-bit
1583 class Float32x4 : public HeapObject {
1585 inline float get_lane(int lane) const;
1586 inline void set_lane(int lane, float value);
1588 DECLARE_CAST(Float32x4)
1590 // Dispatched behavior.
1591 void Float32x4Print(std::ostream& os); // NOLINT
1592 DECLARE_VERIFIER(Float32x4)
1594 // Layout description.
1595 static const int kValueOffset = HeapObject::kHeaderSize;
1596 static const int kSize = kValueOffset + kSimd128Size;
1599 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
1603 enum EnsureElementsMode {
1604 DONT_ALLOW_DOUBLE_ELEMENTS,
1605 ALLOW_COPIED_DOUBLE_ELEMENTS,
1606 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1610 // Indicator for one component of an AccessorPair.
1611 enum AccessorComponent {
1617 // JSReceiver includes types on which properties can be defined, i.e.,
1618 // JSObject and JSProxy.
1619 class JSReceiver: public HeapObject {
1621 DECLARE_CAST(JSReceiver)
1623 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1624 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1625 Handle<JSReceiver> object, Handle<Name> name);
1626 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1628 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1629 Handle<JSReceiver> object, uint32_t index);
1630 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1631 Handle<JSReceiver> object, uint32_t index);
1633 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1634 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1635 Handle<JSReceiver> object, Handle<Name> name,
1636 LanguageMode language_mode = SLOPPY);
1637 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1638 Handle<JSReceiver> object, Handle<Name> name,
1639 LanguageMode language_mode = SLOPPY);
1640 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1641 LookupIterator* it, LanguageMode language_mode);
1642 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1643 Handle<JSReceiver> object, uint32_t index,
1644 LanguageMode language_mode = SLOPPY);
1646 // Tests for the fast common case for property enumeration.
1647 bool IsSimpleEnum();
1649 // Returns the class name ([[Class]] property in the specification).
1650 String* class_name();
1652 // Returns the constructor name (the name (possibly, inferred name) of the
1653 // function that was used to instantiate the object).
1654 String* constructor_name();
1656 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1657 Handle<JSReceiver> object, Handle<Name> name);
1658 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1659 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1661 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1662 Handle<JSReceiver> object, uint32_t index);
1663 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1664 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1666 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1667 LookupIterator* it);
1670 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1672 static Handle<Object> GetDataProperty(LookupIterator* it);
1675 // Retrieves a permanent object identity hash code. The undefined value might
1676 // be returned in case no hash was created yet.
1677 inline Object* GetIdentityHash();
1679 // Retrieves a permanent object identity hash code. May create and store a
1680 // hash code if needed and none exists.
1681 inline static Handle<Smi> GetOrCreateIdentityHash(
1682 Handle<JSReceiver> object);
1684 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1686 // Computes the enumerable keys for a JSObject. Used for implementing
1687 // "for (n in object) { }".
1688 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1689 Handle<JSReceiver> object,
1690 KeyCollectionType type);
1693 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1697 // The JSObject describes real heap allocated JavaScript objects with
1699 // Note that the map of JSObject changes during execution to enable inline
1701 class JSObject: public JSReceiver {
1703 // [properties]: Backing storage for properties.
1704 // properties is a FixedArray in the fast case and a Dictionary in the
1706 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1707 inline void initialize_properties();
1708 inline bool HasFastProperties();
1709 // Gets slow properties for non-global objects.
1710 inline NameDictionary* property_dictionary();
1711 // Gets global object properties.
1712 inline GlobalDictionary* global_dictionary();
1714 // [elements]: The elements (properties with names that are integers).
1716 // Elements can be in two general modes: fast and slow. Each mode
1717 // corrensponds to a set of object representations of elements that
1718 // have something in common.
1720 // In the fast mode elements is a FixedArray and so each element can
1721 // be quickly accessed. This fact is used in the generated code. The
1722 // elements array can have one of three maps in this mode:
1723 // fixed_array_map, sloppy_arguments_elements_map or
1724 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1725 // the elements array may be shared by a few objects and so before
1726 // writing to any element the array must be copied. Use
1727 // EnsureWritableFastElements in this case.
1729 // In the slow mode the elements is either a NumberDictionary, a
1730 // FixedArray parameter map for a (sloppy) arguments object.
1731 DECL_ACCESSORS(elements, FixedArrayBase)
1732 inline void initialize_elements();
1733 static void ResetElements(Handle<JSObject> object);
1734 static inline void SetMapAndElements(Handle<JSObject> object,
1736 Handle<FixedArrayBase> elements);
1737 inline ElementsKind GetElementsKind();
1738 ElementsAccessor* GetElementsAccessor();
1739 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1740 inline bool HasFastSmiElements();
1741 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1742 inline bool HasFastObjectElements();
1743 // Returns true if an object has elements of FAST_ELEMENTS or
1744 // FAST_SMI_ONLY_ELEMENTS.
1745 inline bool HasFastSmiOrObjectElements();
1746 // Returns true if an object has any of the fast elements kinds.
1747 inline bool HasFastElements();
1748 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1750 inline bool HasFastDoubleElements();
1751 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1753 inline bool HasFastHoleyElements();
1754 inline bool HasSloppyArgumentsElements();
1755 inline bool HasDictionaryElements();
1757 inline bool HasFixedTypedArrayElements();
1759 inline bool HasFixedUint8ClampedElements();
1760 inline bool HasFixedArrayElements();
1761 inline bool HasFixedInt8Elements();
1762 inline bool HasFixedUint8Elements();
1763 inline bool HasFixedInt16Elements();
1764 inline bool HasFixedUint16Elements();
1765 inline bool HasFixedInt32Elements();
1766 inline bool HasFixedUint32Elements();
1767 inline bool HasFixedFloat32Elements();
1768 inline bool HasFixedFloat64Elements();
1770 inline bool HasFastArgumentsElements();
1771 inline bool HasSlowArgumentsElements();
1772 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1774 // Requires: HasFastElements().
1775 static Handle<FixedArray> EnsureWritableFastElements(
1776 Handle<JSObject> object);
1778 // Collects elements starting at index 0.
1779 // Undefined values are placed after non-undefined values.
1780 // Returns the number of non-undefined values.
1781 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1783 // As PrepareElementsForSort, but only on objects where elements is
1784 // a dictionary, and it will stay a dictionary. Collates undefined and
1785 // unexisting elements below limit from position zero of the elements.
1786 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1789 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1790 LookupIterator* it, Handle<Object> value);
1792 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1793 // grant an exemption to ExecutableAccessor callbacks in some cases.
1794 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1796 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1797 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1798 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1800 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1801 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1802 PropertyAttributes attributes,
1803 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1805 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1806 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1807 PropertyAttributes attributes,
1808 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1810 // Equivalent to one of the above depending on whether |name| can be converted
1811 // to an array index.
1812 MUST_USE_RESULT static MaybeHandle<Object>
1813 DefinePropertyOrElementIgnoreAttributes(
1814 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1815 PropertyAttributes attributes = NONE,
1816 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1818 // Adds or reconfigures a property to attributes NONE. It will fail when it
1820 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1821 Handle<Object> value);
1823 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1824 Handle<Object> value, PropertyAttributes attributes);
1826 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1827 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1828 PropertyAttributes attributes);
1830 // Extend the receiver with a single fast property appeared first in the
1831 // passed map. This also extends the property backing store if necessary.
1832 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1834 // Migrates the given object to a map whose field representations are the
1835 // lowest upper bound of all known representations for that field.
1836 static void MigrateInstance(Handle<JSObject> instance);
1838 // Migrates the given object only if the target map is already available,
1839 // or returns false if such a map is not yet available.
1840 static bool TryMigrateInstance(Handle<JSObject> instance);
1842 // Sets the property value in a normalized object given (key, value, details).
1843 // Handles the special representation of JS global objects.
1844 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1845 Handle<Object> value,
1846 PropertyDetails details);
1847 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1848 Handle<Object> value,
1849 PropertyAttributes attributes);
1850 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1852 Handle<Object> value,
1853 PropertyAttributes attributes);
1855 static void OptimizeAsPrototype(Handle<JSObject> object,
1856 PrototypeOptimizationMode mode);
1857 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1858 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1859 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1860 Handle<HeapObject> user,
1862 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1863 Handle<HeapObject> user);
1864 static void InvalidatePrototypeChains(Map* map);
1866 // Retrieve interceptors.
1867 InterceptorInfo* GetNamedInterceptor();
1868 InterceptorInfo* GetIndexedInterceptor();
1870 // Used from JSReceiver.
1871 MUST_USE_RESULT static Maybe<PropertyAttributes>
1872 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1873 MUST_USE_RESULT static Maybe<PropertyAttributes>
1874 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1876 // Retrieves an AccessorPair property from the given object. Might return
1877 // undefined if the property doesn't exist or is of a different kind.
1878 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1879 Handle<JSObject> object,
1881 AccessorComponent component);
1883 // Defines an AccessorPair property on the given object.
1884 // TODO(mstarzinger): Rename to SetAccessor().
1885 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1887 Handle<Object> getter,
1888 Handle<Object> setter,
1889 PropertyAttributes attributes);
1891 // Defines an AccessorInfo property on the given object.
1892 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1893 Handle<JSObject> object,
1894 Handle<AccessorInfo> info);
1896 // The result must be checked first for exceptions. If there's no exception,
1897 // the output parameter |done| indicates whether the interceptor has a result
1899 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1900 LookupIterator* it, bool* done);
1902 // Accessors for hidden properties object.
1904 // Hidden properties are not own properties of the object itself.
1905 // Instead they are stored in an auxiliary structure kept as an own
1906 // property with a special name Heap::hidden_string(). But if the
1907 // receiver is a JSGlobalProxy then the auxiliary object is a property
1908 // of its prototype, and if it's a detached proxy, then you can't have
1909 // hidden properties.
1911 // Sets a hidden property on this object. Returns this object if successful,
1912 // undefined if called on a detached proxy.
1913 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1915 Handle<Object> value);
1916 // Gets the value of a hidden property with the given key. Returns the hole
1917 // if the property doesn't exist (or if called on a detached proxy),
1918 // otherwise returns the value set for the key.
1919 Object* GetHiddenProperty(Handle<Name> key);
1920 // Deletes a hidden property. Deleting a non-existing property is
1921 // considered successful.
1922 static void DeleteHiddenProperty(Handle<JSObject> object,
1924 // Returns true if the object has a property with the hidden string as name.
1925 static bool HasHiddenProperties(Handle<JSObject> object);
1927 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1929 static void ValidateElements(Handle<JSObject> object);
1931 // Makes sure that this object can contain HeapObject as elements.
1932 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1934 // Makes sure that this object can contain the specified elements.
1935 static inline void EnsureCanContainElements(
1936 Handle<JSObject> object,
1939 EnsureElementsMode mode);
1940 static inline void EnsureCanContainElements(
1941 Handle<JSObject> object,
1942 Handle<FixedArrayBase> elements,
1944 EnsureElementsMode mode);
1945 static void EnsureCanContainElements(
1946 Handle<JSObject> object,
1947 Arguments* arguments,
1950 EnsureElementsMode mode);
1952 // Would we convert a fast elements array to dictionary mode given
1953 // an access at key?
1954 bool WouldConvertToSlowElements(uint32_t index);
1956 // Computes the new capacity when expanding the elements of a JSObject.
1957 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1958 // (old_capacity + 50%) + 16
1959 return old_capacity + (old_capacity >> 1) + 16;
1962 // These methods do not perform access checks!
1963 static void UpdateAllocationSite(Handle<JSObject> object,
1964 ElementsKind to_kind);
1966 // Lookup interceptors are used for handling properties controlled by host
1968 inline bool HasNamedInterceptor();
1969 inline bool HasIndexedInterceptor();
1971 // Computes the enumerable keys from interceptors. Used for debug mirrors and
1972 // by JSReceiver::GetKeys.
1973 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
1974 Handle<JSObject> object,
1975 Handle<JSReceiver> receiver);
1976 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
1977 Handle<JSObject> object,
1978 Handle<JSReceiver> receiver);
1980 // Support functions for v8 api (needed for correct interceptor behavior).
1981 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
1982 Handle<JSObject> object, Handle<Name> name);
1983 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
1984 Handle<JSObject> object, uint32_t index);
1985 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
1986 Handle<JSObject> object, Handle<Name> name);
1988 // Get the header size for a JSObject. Used to compute the index of
1989 // internal fields as well as the number of internal fields.
1990 inline int GetHeaderSize();
1992 inline int GetInternalFieldCount();
1993 inline int GetInternalFieldOffset(int index);
1994 inline Object* GetInternalField(int index);
1995 inline void SetInternalField(int index, Object* value);
1996 inline void SetInternalField(int index, Smi* value);
1998 // Returns the number of properties on this object filtering out properties
1999 // with the specified attributes (ignoring interceptors).
2000 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2001 // Fill in details for properties into storage starting at the specified
2002 // index. Returns the number of properties added.
2003 int GetOwnPropertyNames(FixedArray* storage, int index,
2004 PropertyAttributes filter = NONE);
2006 // Returns the number of properties on this object filtering out properties
2007 // with the specified attributes (ignoring interceptors).
2008 int NumberOfOwnElements(PropertyAttributes filter);
2009 // Returns the number of enumerable elements (ignoring interceptors).
2010 int NumberOfEnumElements();
2011 // Returns the number of elements on this object filtering out elements
2012 // with the specified attributes (ignoring interceptors).
2013 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2014 // Count and fill in the enumerable elements into storage.
2015 // (storage->length() == NumberOfEnumElements()).
2016 // If storage is NULL, will count the elements without adding
2017 // them to any storage.
2018 // Returns the number of enumerable elements.
2019 int GetEnumElementKeys(FixedArray* storage);
2021 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2024 // Returns a new map with all transitions dropped from the object's current
2025 // map and the ElementsKind set.
2026 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2027 ElementsKind to_kind);
2028 static void TransitionElementsKind(Handle<JSObject> object,
2029 ElementsKind to_kind);
2031 // Always use this to migrate an object to a new map.
2032 // |expected_additional_properties| is only used for fast-to-slow transitions
2033 // and ignored otherwise.
2034 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2035 int expected_additional_properties = 0);
2037 // Convert the object to use the canonical dictionary
2038 // representation. If the object is expected to have additional properties
2039 // added this number can be indicated to have the backing store allocated to
2040 // an initial capacity for holding these properties.
2041 static void NormalizeProperties(Handle<JSObject> object,
2042 PropertyNormalizationMode mode,
2043 int expected_additional_properties,
2044 const char* reason);
2046 // Convert and update the elements backing store to be a
2047 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2048 static Handle<SeededNumberDictionary> NormalizeElements(
2049 Handle<JSObject> object);
2051 void RequireSlowElements(SeededNumberDictionary* dictionary);
2053 // Transform slow named properties to fast variants.
2054 static void MigrateSlowToFast(Handle<JSObject> object,
2055 int unused_property_fields, const char* reason);
2057 inline bool IsUnboxedDoubleField(FieldIndex index);
2059 // Access fast-case object properties at index.
2060 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2061 Representation representation,
2063 inline Object* RawFastPropertyAt(FieldIndex index);
2064 inline double RawFastDoublePropertyAt(FieldIndex index);
2066 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2067 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2068 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2069 inline void WriteToField(int descriptor, Object* value);
2071 // Access to in object properties.
2072 inline int GetInObjectPropertyOffset(int index);
2073 inline Object* InObjectPropertyAt(int index);
2074 inline Object* InObjectPropertyAtPut(int index,
2076 WriteBarrierMode mode
2077 = UPDATE_WRITE_BARRIER);
2079 // Set the object's prototype (only JSReceiver and null are allowed values).
2080 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2081 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2083 // Initializes the body after properties slot, properties slot is
2084 // initialized by set_properties. Fill the pre-allocated fields with
2085 // pre_allocated_value and the rest with filler_value.
2086 // Note: this call does not update write barrier, the caller is responsible
2087 // to ensure that |filler_value| can be collected without WB here.
2088 inline void InitializeBody(Map* map,
2089 Object* pre_allocated_value,
2090 Object* filler_value);
2092 // Check whether this object references another object
2093 bool ReferencesObject(Object* obj);
2095 // Disalow further properties to be added to the oject.
2096 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2097 Handle<JSObject> object);
2099 bool IsExtensible();
2102 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2104 // ES5 Object.freeze
2105 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2107 // Called the first time an object is observed with ES7 Object.observe.
2108 static void SetObserved(Handle<JSObject> object);
2111 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2113 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2114 Handle<JSObject> object,
2115 AllocationSiteUsageContext* site_context,
2116 DeepCopyHints hints = kNoHints);
2117 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2118 Handle<JSObject> object,
2119 AllocationSiteCreationContext* site_context);
2121 DECLARE_CAST(JSObject)
2123 // Dispatched behavior.
2124 void JSObjectShortPrint(StringStream* accumulator);
2125 DECLARE_PRINTER(JSObject)
2126 DECLARE_VERIFIER(JSObject)
2128 void PrintProperties(std::ostream& os); // NOLINT
2129 void PrintElements(std::ostream& os); // NOLINT
2131 #if defined(DEBUG) || defined(OBJECT_PRINT)
2132 void PrintTransitions(std::ostream& os); // NOLINT
2135 static void PrintElementsTransition(
2136 FILE* file, Handle<JSObject> object,
2137 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2138 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2140 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2143 // Structure for collecting spill information about JSObjects.
2144 class SpillInformation {
2148 int number_of_objects_;
2149 int number_of_objects_with_fast_properties_;
2150 int number_of_objects_with_fast_elements_;
2151 int number_of_fast_used_fields_;
2152 int number_of_fast_unused_fields_;
2153 int number_of_slow_used_properties_;
2154 int number_of_slow_unused_properties_;
2155 int number_of_fast_used_elements_;
2156 int number_of_fast_unused_elements_;
2157 int number_of_slow_used_elements_;
2158 int number_of_slow_unused_elements_;
2161 void IncrementSpillStatistics(SpillInformation* info);
2165 // If a GC was caused while constructing this object, the elements pointer
2166 // may point to a one pointer filler map. The object won't be rooted, but
2167 // our heap verification code could stumble across it.
2168 bool ElementsAreSafeToExamine();
2171 Object* SlowReverseLookup(Object* value);
2173 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2174 // Also maximal value of JSArray's length property.
2175 static const uint32_t kMaxElementCount = 0xffffffffu;
2177 // Constants for heuristics controlling conversion of fast elements
2178 // to slow elements.
2180 // Maximal gap that can be introduced by adding an element beyond
2181 // the current elements length.
2182 static const uint32_t kMaxGap = 1024;
2184 // Maximal length of fast elements array that won't be checked for
2185 // being dense enough on expansion.
2186 static const int kMaxUncheckedFastElementsLength = 5000;
2188 // Same as above but for old arrays. This limit is more strict. We
2189 // don't want to be wasteful with long lived objects.
2190 static const int kMaxUncheckedOldFastElementsLength = 500;
2192 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2193 // permissible values (see the DCHECK in heap.cc).
2194 static const int kInitialMaxFastElementArray = 100000;
2196 // This constant applies only to the initial map of "global.Object" and
2197 // not to arbitrary other JSObject maps.
2198 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2200 static const int kMaxInstanceSize = 255 * kPointerSize;
2201 // When extending the backing storage for property values, we increase
2202 // its size by more than the 1 entry necessary, so sequentially adding fields
2203 // to the same object requires fewer allocations and copies.
2204 static const int kFieldsAdded = 3;
2206 // Layout description.
2207 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2208 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2209 static const int kHeaderSize = kElementsOffset + kPointerSize;
2211 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2213 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2215 static inline int SizeOf(Map* map, HeapObject* object);
2218 Context* GetCreationContext();
2220 // Enqueue change record for Object.observe. May cause GC.
2221 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2222 Handle<JSObject> object, const char* type, Handle<Name> name,
2223 Handle<Object> old_value);
2225 // Gets the number of currently used elements.
2226 int GetFastElementsUsage();
2228 // Deletes an existing named property in a normalized object.
2229 static void DeleteNormalizedProperty(Handle<JSObject> object,
2230 Handle<Name> name, int entry);
2232 static bool AllCanRead(LookupIterator* it);
2233 static bool AllCanWrite(LookupIterator* it);
2236 friend class JSReceiver;
2237 friend class Object;
2239 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2240 static void MigrateFastToSlow(Handle<JSObject> object,
2241 Handle<Map> new_map,
2242 int expected_additional_properties);
2244 // Used from Object::GetProperty().
2245 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2246 LookupIterator* it);
2248 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2249 LookupIterator* it, Handle<Object> value);
2251 // Add a property to a slow-case object.
2252 static void AddSlowProperty(Handle<JSObject> object,
2254 Handle<Object> value,
2255 PropertyAttributes attributes);
2257 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2258 LookupIterator* it);
2260 bool ReferencesObjectFromElements(FixedArray* elements,
2264 // Return the hash table backing store or the inline stored identity hash,
2265 // whatever is found.
2266 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2268 // Return the hash table backing store for hidden properties. If there is no
2269 // backing store, allocate one.
2270 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2271 Handle<JSObject> object);
2273 // Set the hidden property backing store to either a hash table or
2274 // the inline-stored identity hash.
2275 static Handle<Object> SetHiddenPropertiesHashTable(
2276 Handle<JSObject> object,
2277 Handle<Object> value);
2279 MUST_USE_RESULT Object* GetIdentityHash();
2281 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2283 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2284 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2286 // Helper for fast versions of preventExtensions, seal, and freeze.
2287 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2288 template <PropertyAttributes attrs>
2289 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2290 Handle<JSObject> object);
2292 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2296 // Common superclass for FixedArrays that allow implementations to share
2297 // common accessors and some code paths.
2298 class FixedArrayBase: public HeapObject {
2300 // [length]: length of the array.
2301 inline int length() const;
2302 inline void set_length(int value);
2304 // Get and set the length using acquire loads and release stores.
2305 inline int synchronized_length() const;
2306 inline void synchronized_set_length(int value);
2308 DECLARE_CAST(FixedArrayBase)
2310 // Layout description.
2311 // Length is smi tagged when it is stored.
2312 static const int kLengthOffset = HeapObject::kHeaderSize;
2313 static const int kHeaderSize = kLengthOffset + kPointerSize;
2317 class FixedDoubleArray;
2318 class IncrementalMarking;
2321 // FixedArray describes fixed-sized arrays with element type Object*.
2322 class FixedArray: public FixedArrayBase {
2324 // Setter and getter for elements.
2325 inline Object* get(int index) const;
2326 void SetValue(uint32_t index, Object* value);
2327 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2328 // Setter that uses write barrier.
2329 inline void set(int index, Object* value);
2330 inline bool is_the_hole(int index);
2332 // Setter that doesn't need write barrier.
2333 inline void set(int index, Smi* value);
2334 // Setter with explicit barrier mode.
2335 inline void set(int index, Object* value, WriteBarrierMode mode);
2337 // Setters for frequently used oddballs located in old space.
2338 inline void set_undefined(int index);
2339 inline void set_null(int index);
2340 inline void set_the_hole(int index);
2342 inline Object** GetFirstElementAddress();
2343 inline bool ContainsOnlySmisOrHoles();
2345 // Gives access to raw memory which stores the array's data.
2346 inline Object** data_start();
2348 inline void FillWithHoles(int from, int to);
2350 // Shrink length and insert filler objects.
2351 void Shrink(int length);
2354 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2356 PretenureFlag pretenure = NOT_TENURED);
2358 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2360 // Add the elements of a JSArray to this FixedArray.
2361 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2362 Handle<FixedArray> content, Handle<JSObject> array,
2363 KeyFilter filter = ALL_KEYS);
2365 // Computes the union of keys and return the result.
2366 // Used for implementing "for (n in object) { }"
2367 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2368 Handle<FixedArray> first,
2369 Handle<FixedArray> second);
2371 // Copy a sub array from the receiver to dest.
2372 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2374 // Garbage collection support.
2375 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2377 // Code Generation support.
2378 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2380 // Garbage collection support.
2381 Object** RawFieldOfElementAt(int index) {
2382 return HeapObject::RawField(this, OffsetOfElementAt(index));
2385 DECLARE_CAST(FixedArray)
2387 // Maximal allowed size, in bytes, of a single FixedArray.
2388 // Prevents overflowing size computations, as well as extreme memory
2390 static const int kMaxSize = 128 * MB * kPointerSize;
2391 // Maximally allowed length of a FixedArray.
2392 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2394 // Dispatched behavior.
2395 DECLARE_PRINTER(FixedArray)
2396 DECLARE_VERIFIER(FixedArray)
2398 // Checks if two FixedArrays have identical contents.
2399 bool IsEqualTo(FixedArray* other);
2402 // Swap two elements in a pair of arrays. If this array and the
2403 // numbers array are the same object, the elements are only swapped
2405 void SwapPairs(FixedArray* numbers, int i, int j);
2407 // Sort prefix of this array and the numbers array as pairs wrt. the
2408 // numbers. If the numbers array and the this array are the same
2409 // object, the prefix of this array is sorted.
2410 void SortPairs(FixedArray* numbers, uint32_t len);
2412 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2414 static inline int SizeOf(Map* map, HeapObject* object) {
2416 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2421 // Set operation on FixedArray without using write barriers. Can
2422 // only be used for storing old space objects or smis.
2423 static inline void NoWriteBarrierSet(FixedArray* array,
2427 // Set operation on FixedArray without incremental write barrier. Can
2428 // only be used if the object is guaranteed to be white (whiteness witness
2430 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2435 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2437 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2441 // FixedDoubleArray describes fixed-sized arrays with element type double.
2442 class FixedDoubleArray: public FixedArrayBase {
2444 // Setter and getter for elements.
2445 inline double get_scalar(int index);
2446 inline uint64_t get_representation(int index);
2447 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2448 // This accessor has to get a Number as |value|.
2449 void SetValue(uint32_t index, Object* value);
2450 inline void set(int index, double value);
2451 inline void set_the_hole(int index);
2453 // Checking for the hole.
2454 inline bool is_the_hole(int index);
2456 // Garbage collection support.
2457 inline static int SizeFor(int length) {
2458 return kHeaderSize + length * kDoubleSize;
2461 // Gives access to raw memory which stores the array's data.
2462 inline double* data_start();
2464 inline void FillWithHoles(int from, int to);
2466 // Code Generation support.
2467 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2469 DECLARE_CAST(FixedDoubleArray)
2471 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2472 // Prevents overflowing size computations, as well as extreme memory
2474 static const int kMaxSize = 512 * MB;
2475 // Maximally allowed length of a FixedArray.
2476 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2478 // Dispatched behavior.
2479 DECLARE_PRINTER(FixedDoubleArray)
2480 DECLARE_VERIFIER(FixedDoubleArray)
2483 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2487 class WeakFixedArray : public FixedArray {
2489 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2491 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2492 static Handle<WeakFixedArray> Add(
2493 Handle<Object> maybe_array, Handle<HeapObject> value,
2494 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2495 bool* was_present = NULL);
2497 // Returns true if an entry was found and removed.
2498 bool Remove(Handle<HeapObject> value);
2502 inline Object* Get(int index) const;
2503 inline void Clear(int index);
2504 inline int Length() const;
2506 inline bool IsEmptySlot(int index) const;
2507 static Object* Empty() { return Smi::FromInt(0); }
2509 DECLARE_CAST(WeakFixedArray)
2512 static const int kLastUsedIndexIndex = 0;
2513 static const int kFirstIndex = 1;
2515 static Handle<WeakFixedArray> Allocate(
2516 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2518 static void Set(Handle<WeakFixedArray> array, int index,
2519 Handle<HeapObject> value);
2520 inline void clear(int index);
2522 inline int last_used_index() const;
2523 inline void set_last_used_index(int index);
2525 // Disallow inherited setters.
2526 void set(int index, Smi* value);
2527 void set(int index, Object* value);
2528 void set(int index, Object* value, WriteBarrierMode mode);
2529 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2533 // Generic array grows dynamically with O(1) amortized insertion.
2534 class ArrayList : public FixedArray {
2538 // Use this if GC can delete elements from the array.
2539 kReloadLengthAfterAllocation,
2541 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2542 AddMode mode = kNone);
2543 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2544 Handle<Object> obj2, AddMode = kNone);
2545 inline int Length();
2546 inline void SetLength(int length);
2547 inline Object* Get(int index);
2548 inline Object** Slot(int index);
2549 inline void Set(int index, Object* obj);
2550 inline void Clear(int index, Object* undefined);
2551 DECLARE_CAST(ArrayList)
2554 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2555 static const int kLengthIndex = 0;
2556 static const int kFirstIndex = 1;
2557 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2561 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2562 // The format of the these objects is:
2563 // [0]: Number of descriptors
2564 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2565 // [0]: pointer to fixed array with enum cache
2566 // [1]: either Smi(0) or pointer to fixed array with indices
2568 // [2 + number of descriptors * kDescriptorSize]: start of slack
2569 class DescriptorArray: public FixedArray {
2571 // Returns true for both shared empty_descriptor_array and for smis, which the
2572 // map uses to encode additional bit fields when the descriptor array is not
2574 inline bool IsEmpty();
2576 // Returns the number of descriptors in the array.
2577 int number_of_descriptors() {
2578 DCHECK(length() >= kFirstIndex || IsEmpty());
2580 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2583 int number_of_descriptors_storage() {
2585 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2588 int NumberOfSlackDescriptors() {
2589 return number_of_descriptors_storage() - number_of_descriptors();
2592 inline void SetNumberOfDescriptors(int number_of_descriptors);
2593 inline int number_of_entries() { return number_of_descriptors(); }
2595 bool HasEnumCache() {
2596 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2599 void CopyEnumCacheFrom(DescriptorArray* array) {
2600 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2603 FixedArray* GetEnumCache() {
2604 DCHECK(HasEnumCache());
2605 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2606 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2609 bool HasEnumIndicesCache() {
2610 if (IsEmpty()) return false;
2611 Object* object = get(kEnumCacheIndex);
2612 if (object->IsSmi()) return false;
2613 FixedArray* bridge = FixedArray::cast(object);
2614 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2617 FixedArray* GetEnumIndicesCache() {
2618 DCHECK(HasEnumIndicesCache());
2619 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2620 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2623 Object** GetEnumCacheSlot() {
2624 DCHECK(HasEnumCache());
2625 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2629 void ClearEnumCache();
2631 // Initialize or change the enum cache,
2632 // using the supplied storage for the small "bridge".
2633 void SetEnumCache(FixedArray* bridge_storage,
2634 FixedArray* new_cache,
2635 Object* new_index_cache);
2637 bool CanHoldValue(int descriptor, Object* value);
2639 // Accessors for fetching instance descriptor at descriptor number.
2640 inline Name* GetKey(int descriptor_number);
2641 inline Object** GetKeySlot(int descriptor_number);
2642 inline Object* GetValue(int descriptor_number);
2643 inline void SetValue(int descriptor_number, Object* value);
2644 inline Object** GetValueSlot(int descriptor_number);
2645 static inline int GetValueOffset(int descriptor_number);
2646 inline Object** GetDescriptorStartSlot(int descriptor_number);
2647 inline Object** GetDescriptorEndSlot(int descriptor_number);
2648 inline PropertyDetails GetDetails(int descriptor_number);
2649 inline PropertyType GetType(int descriptor_number);
2650 inline int GetFieldIndex(int descriptor_number);
2651 inline HeapType* GetFieldType(int descriptor_number);
2652 inline Object* GetConstant(int descriptor_number);
2653 inline Object* GetCallbacksObject(int descriptor_number);
2654 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2656 inline Name* GetSortedKey(int descriptor_number);
2657 inline int GetSortedKeyIndex(int descriptor_number);
2658 inline void SetSortedKey(int pointer, int descriptor_number);
2659 inline void SetRepresentation(int descriptor_number,
2660 Representation representation);
2662 // Accessor for complete descriptor.
2663 inline void Get(int descriptor_number, Descriptor* desc);
2664 inline void Set(int descriptor_number, Descriptor* desc);
2665 void Replace(int descriptor_number, Descriptor* descriptor);
2667 // Append automatically sets the enumeration index. This should only be used
2668 // to add descriptors in bulk at the end, followed by sorting the descriptor
2670 inline void Append(Descriptor* desc);
2672 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2673 int enumeration_index,
2676 static Handle<DescriptorArray> CopyUpToAddAttributes(
2677 Handle<DescriptorArray> desc,
2678 int enumeration_index,
2679 PropertyAttributes attributes,
2682 // Sort the instance descriptors by the hash codes of their keys.
2685 // Search the instance descriptors for given name.
2686 INLINE(int Search(Name* name, int number_of_own_descriptors));
2688 // As the above, but uses DescriptorLookupCache and updates it when
2690 INLINE(int SearchWithCache(Name* name, Map* map));
2692 // Allocates a DescriptorArray, but returns the singleton
2693 // empty descriptor array object if number_of_descriptors is 0.
2694 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2695 int number_of_descriptors,
2698 DECLARE_CAST(DescriptorArray)
2700 // Constant for denoting key was not found.
2701 static const int kNotFound = -1;
2703 static const int kDescriptorLengthIndex = 0;
2704 static const int kEnumCacheIndex = 1;
2705 static const int kFirstIndex = 2;
2707 // The length of the "bridge" to the enum cache.
2708 static const int kEnumCacheBridgeLength = 2;
2709 static const int kEnumCacheBridgeCacheIndex = 0;
2710 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2712 // Layout description.
2713 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2714 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2715 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2717 // Layout description for the bridge array.
2718 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2720 // Layout of descriptor.
2721 static const int kDescriptorKey = 0;
2722 static const int kDescriptorDetails = 1;
2723 static const int kDescriptorValue = 2;
2724 static const int kDescriptorSize = 3;
2726 #if defined(DEBUG) || defined(OBJECT_PRINT)
2727 // For our gdb macros, we should perhaps change these in the future.
2730 // Print all the descriptors.
2731 void PrintDescriptors(std::ostream& os); // NOLINT
2735 // Is the descriptor array sorted and without duplicates?
2736 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2738 // Is the descriptor array consistent with the back pointers in targets?
2739 bool IsConsistentWithBackPointers(Map* current_map);
2741 // Are two DescriptorArrays equal?
2742 bool IsEqualTo(DescriptorArray* other);
2745 // Returns the fixed array length required to hold number_of_descriptors
2747 static int LengthFor(int number_of_descriptors) {
2748 return ToKeyIndex(number_of_descriptors);
2752 // WhitenessWitness is used to prove that a descriptor array is white
2753 // (unmarked), so incremental write barriers can be skipped because the
2754 // marking invariant cannot be broken and slots pointing into evacuation
2755 // candidates will be discovered when the object is scanned. A witness is
2756 // always stack-allocated right after creating an array. By allocating a
2757 // witness, incremental marking is globally disabled. The witness is then
2758 // passed along wherever needed to statically prove that the array is known to
2760 class WhitenessWitness {
2762 inline explicit WhitenessWitness(DescriptorArray* array);
2763 inline ~WhitenessWitness();
2766 IncrementalMarking* marking_;
2769 // An entry in a DescriptorArray, represented as an (array, index) pair.
2772 inline explicit Entry(DescriptorArray* descs, int index) :
2773 descs_(descs), index_(index) { }
2775 inline PropertyType type() { return descs_->GetType(index_); }
2776 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2779 DescriptorArray* descs_;
2783 // Conversion from descriptor number to array indices.
2784 static int ToKeyIndex(int descriptor_number) {
2785 return kFirstIndex +
2786 (descriptor_number * kDescriptorSize) +
2790 static int ToDetailsIndex(int descriptor_number) {
2791 return kFirstIndex +
2792 (descriptor_number * kDescriptorSize) +
2796 static int ToValueIndex(int descriptor_number) {
2797 return kFirstIndex +
2798 (descriptor_number * kDescriptorSize) +
2802 // Transfer a complete descriptor from the src descriptor array to this
2803 // descriptor array.
2804 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2806 inline void Set(int descriptor_number,
2808 const WhitenessWitness&);
2810 // Swap first and second descriptor.
2811 inline void SwapSortedKeys(int first, int second);
2813 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2817 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2819 template <SearchMode search_mode, typename T>
2820 inline int Search(T* array, Name* name, int valid_entries = 0,
2821 int* out_insertion_index = NULL);
2824 // HashTable is a subclass of FixedArray that implements a hash table
2825 // that uses open addressing and quadratic probing.
2827 // In order for the quadratic probing to work, elements that have not
2828 // yet been used and elements that have been deleted are
2829 // distinguished. Probing continues when deleted elements are
2830 // encountered and stops when unused elements are encountered.
2832 // - Elements with key == undefined have not been used yet.
2833 // - Elements with key == the_hole have been deleted.
2835 // The hash table class is parameterized with a Shape and a Key.
2836 // Shape must be a class with the following interface:
2837 // class ExampleShape {
2839 // // Tells whether key matches other.
2840 // static bool IsMatch(Key key, Object* other);
2841 // // Returns the hash value for key.
2842 // static uint32_t Hash(Key key);
2843 // // Returns the hash value for object.
2844 // static uint32_t HashForObject(Key key, Object* object);
2845 // // Convert key to an object.
2846 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2847 // // The prefix size indicates number of elements in the beginning
2848 // // of the backing storage.
2849 // static const int kPrefixSize = ..;
2850 // // The Element size indicates number of elements per entry.
2851 // static const int kEntrySize = ..;
2853 // The prefix size indicates an amount of memory in the
2854 // beginning of the backing storage that can be used for non-element
2855 // information by subclasses.
2857 template<typename Key>
2860 static const bool UsesSeed = false;
2861 static uint32_t Hash(Key key) { return 0; }
2862 static uint32_t SeededHash(Key key, uint32_t seed) {
2866 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2867 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2869 return HashForObject(key, object);
2874 class HashTableBase : public FixedArray {
2876 // Returns the number of elements in the hash table.
2877 int NumberOfElements() {
2878 return Smi::cast(get(kNumberOfElementsIndex))->value();
2881 // Returns the number of deleted elements in the hash table.
2882 int NumberOfDeletedElements() {
2883 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2886 // Returns the capacity of the hash table.
2888 return Smi::cast(get(kCapacityIndex))->value();
2891 // ElementAdded should be called whenever an element is added to a
2893 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2895 // ElementRemoved should be called whenever an element is removed from
2897 void ElementRemoved() {
2898 SetNumberOfElements(NumberOfElements() - 1);
2899 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2901 void ElementsRemoved(int n) {
2902 SetNumberOfElements(NumberOfElements() - n);
2903 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2906 // Computes the required capacity for a table holding the given
2907 // number of elements. May be more than HashTable::kMaxCapacity.
2908 static inline int ComputeCapacity(int at_least_space_for);
2910 // Use a different heuristic to compute capacity when serializing.
2911 static inline int ComputeCapacityForSerialization(int at_least_space_for);
2913 // Tells whether k is a real key. The hole and undefined are not allowed
2914 // as keys and can be used to indicate missing or deleted elements.
2915 bool IsKey(Object* k) {
2916 return !k->IsTheHole() && !k->IsUndefined();
2919 // Compute the probe offset (quadratic probing).
2920 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2921 return (n + n * n) >> 1;
2924 static const int kNumberOfElementsIndex = 0;
2925 static const int kNumberOfDeletedElementsIndex = 1;
2926 static const int kCapacityIndex = 2;
2927 static const int kPrefixStartIndex = 3;
2929 // Constant used for denoting a absent entry.
2930 static const int kNotFound = -1;
2933 // Update the number of elements in the hash table.
2934 void SetNumberOfElements(int nof) {
2935 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2938 // Update the number of deleted elements in the hash table.
2939 void SetNumberOfDeletedElements(int nod) {
2940 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2943 // Returns probe entry.
2944 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2945 DCHECK(base::bits::IsPowerOfTwo32(size));
2946 return (hash + GetProbeOffset(number)) & (size - 1);
2949 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2950 return hash & (size - 1);
2953 inline static uint32_t NextProbe(
2954 uint32_t last, uint32_t number, uint32_t size) {
2955 return (last + number) & (size - 1);
2960 template <typename Derived, typename Shape, typename Key>
2961 class HashTable : public HashTableBase {
2964 inline uint32_t Hash(Key key) {
2965 if (Shape::UsesSeed) {
2966 return Shape::SeededHash(key, GetHeap()->HashSeed());
2968 return Shape::Hash(key);
2972 inline uint32_t HashForObject(Key key, Object* object) {
2973 if (Shape::UsesSeed) {
2974 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2976 return Shape::HashForObject(key, object);
2980 // Returns a new HashTable object.
2981 MUST_USE_RESULT static Handle<Derived> New(
2982 Isolate* isolate, int at_least_space_for,
2983 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2984 PretenureFlag pretenure = NOT_TENURED);
2986 DECLARE_CAST(HashTable)
2988 // Garbage collection support.
2989 void IteratePrefix(ObjectVisitor* visitor);
2990 void IterateElements(ObjectVisitor* visitor);
2992 // Find entry for key otherwise return kNotFound.
2993 inline int FindEntry(Key key);
2994 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2995 int FindEntry(Isolate* isolate, Key key);
2997 // Rehashes the table in-place.
2998 void Rehash(Key key);
3000 // Returns the key at entry.
3001 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3003 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3004 static const int kEntrySize = Shape::kEntrySize;
3005 static const int kElementsStartOffset =
3006 kHeaderSize + kElementsStartIndex * kPointerSize;
3007 static const int kCapacityOffset =
3008 kHeaderSize + kCapacityIndex * kPointerSize;
3010 // Returns the index for an entry (of the key)
3011 static inline int EntryToIndex(int entry) {
3012 return (entry * kEntrySize) + kElementsStartIndex;
3016 friend class ObjectHashTable;
3018 // Find the entry at which to insert element with the given key that
3019 // has the given hash value.
3020 uint32_t FindInsertionEntry(uint32_t hash);
3022 // Attempt to shrink hash table after removal of key.
3023 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3025 // Ensure enough space for n additional elements.
3026 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3027 Handle<Derived> table,
3030 PretenureFlag pretenure = NOT_TENURED);
3032 // Sets the capacity of the hash table.
3033 void SetCapacity(int capacity) {
3034 // To scale a computed hash code to fit within the hash table, we
3035 // use bit-wise AND with a mask, so the capacity must be positive
3037 DCHECK(capacity > 0);
3038 DCHECK(capacity <= kMaxCapacity);
3039 set(kCapacityIndex, Smi::FromInt(capacity));
3042 // Maximal capacity of HashTable. Based on maximal length of underlying
3043 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3045 static const int kMaxCapacity =
3046 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3049 // Returns _expected_ if one of entries given by the first _probe_ probes is
3050 // equal to _expected_. Otherwise, returns the entry given by the probe
3052 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3054 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3056 // Rehashes this hash-table into the new table.
3057 void Rehash(Handle<Derived> new_table, Key key);
3061 // HashTableKey is an abstract superclass for virtual key behavior.
3062 class HashTableKey {
3064 // Returns whether the other object matches this key.
3065 virtual bool IsMatch(Object* other) = 0;
3066 // Returns the hash value for this key.
3067 virtual uint32_t Hash() = 0;
3068 // Returns the hash value for object.
3069 virtual uint32_t HashForObject(Object* key) = 0;
3070 // Returns the key object for storing into the hash table.
3071 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3073 virtual ~HashTableKey() {}
3077 class StringTableShape : public BaseShape<HashTableKey*> {
3079 static inline bool IsMatch(HashTableKey* key, Object* value) {
3080 return key->IsMatch(value);
3083 static inline uint32_t Hash(HashTableKey* key) {
3087 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3088 return key->HashForObject(object);
3091 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3093 static const int kPrefixSize = 0;
3094 static const int kEntrySize = 1;
3097 class SeqOneByteString;
3101 // No special elements in the prefix and the element size is 1
3102 // because only the string itself (the key) needs to be stored.
3103 class StringTable: public HashTable<StringTable,
3107 // Find string in the string table. If it is not there yet, it is
3108 // added. The return value is the string found.
3109 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3110 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3111 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3113 // Tries to internalize given string and returns string handle on success
3114 // or an empty handle otherwise.
3115 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3117 Handle<String> string);
3119 // Looks up a string that is equal to the given string and returns
3120 // string handle if it is found, or an empty handle otherwise.
3121 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3123 Handle<String> str);
3124 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3129 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3131 DECLARE_CAST(StringTable)
3134 template <bool seq_one_byte>
3135 friend class JsonParser;
3137 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3141 template <typename Derived, typename Shape, typename Key>
3142 class Dictionary: public HashTable<Derived, Shape, Key> {
3143 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3146 // Returns the value at entry.
3147 Object* ValueAt(int entry) {
3148 return this->get(Derived::EntryToIndex(entry) + 1);
3151 // Set the value for entry.
3152 void ValueAtPut(int entry, Object* value) {
3153 this->set(Derived::EntryToIndex(entry) + 1, value);
3156 // Returns the property details for the property at entry.
3157 PropertyDetails DetailsAt(int entry) {
3158 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3161 // Set the details for entry.
3162 void DetailsAtPut(int entry, PropertyDetails value) {
3163 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3166 // Returns true if property at given entry is deleted.
3167 bool IsDeleted(int entry) {
3168 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3171 // Delete a property from the dictionary.
3172 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3174 // Attempt to shrink the dictionary after deletion of key.
3175 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3176 Handle<Derived> dictionary,
3178 return DerivedHashTable::Shrink(dictionary, key);
3182 // TODO(dcarney): templatize or move to SeededNumberDictionary
3183 void CopyValuesTo(FixedArray* elements);
3185 // Returns the number of elements in the dictionary filtering out properties
3186 // with the specified attributes.
3187 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3189 // Returns the number of enumerable elements in the dictionary.
3190 int NumberOfEnumElements() {
3191 return NumberOfElementsFilterAttributes(
3192 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3195 // Returns true if the dictionary contains any elements that are non-writable,
3196 // non-configurable, non-enumerable, or have getters/setters.
3197 bool HasComplexElements();
3199 enum SortMode { UNSORTED, SORTED };
3201 // Fill in details for properties into storage.
3202 // Returns the number of properties added.
3203 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3204 SortMode sort_mode);
3206 // Copies enumerable keys to preallocated fixed array.
3207 void CopyEnumKeysTo(FixedArray* storage);
3209 // Accessors for next enumeration index.
3210 void SetNextEnumerationIndex(int index) {
3212 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3215 int NextEnumerationIndex() {
3216 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3219 // Creates a new dictionary.
3220 MUST_USE_RESULT static Handle<Derived> New(
3222 int at_least_space_for,
3223 PretenureFlag pretenure = NOT_TENURED);
3225 // Ensure enough space for n additional elements.
3226 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3229 void Print(std::ostream& os); // NOLINT
3231 // Returns the key (slow).
3232 Object* SlowReverseLookup(Object* value);
3234 // Sets the entry to (key, value) pair.
3235 inline void SetEntry(int entry,
3237 Handle<Object> value);
3238 inline void SetEntry(int entry,
3240 Handle<Object> value,
3241 PropertyDetails details);
3243 MUST_USE_RESULT static Handle<Derived> Add(
3244 Handle<Derived> dictionary,
3246 Handle<Object> value,
3247 PropertyDetails details);
3249 // Returns iteration indices array for the |dictionary|.
3250 // Values are direct indices in the |HashTable| array.
3251 static Handle<FixedArray> BuildIterationIndicesArray(
3252 Handle<Derived> dictionary);
3255 // Generic at put operation.
3256 MUST_USE_RESULT static Handle<Derived> AtPut(
3257 Handle<Derived> dictionary,
3259 Handle<Object> value);
3261 // Add entry to dictionary.
3262 static void AddEntry(
3263 Handle<Derived> dictionary,
3265 Handle<Object> value,
3266 PropertyDetails details,
3269 // Generate new enumeration indices to avoid enumeration index overflow.
3270 // Returns iteration indices array for the |dictionary|.
3271 static Handle<FixedArray> GenerateNewEnumerationIndices(
3272 Handle<Derived> dictionary);
3273 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3274 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3278 template <typename Derived, typename Shape>
3279 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3280 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3283 // Find entry for key, otherwise return kNotFound. Optimized version of
3284 // HashTable::FindEntry.
3285 int FindEntry(Handle<Name> key);
3289 template <typename Key>
3290 class BaseDictionaryShape : public BaseShape<Key> {
3292 template <typename Dictionary>
3293 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3294 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3295 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3296 return PropertyDetails(
3297 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3300 template <typename Dictionary>
3301 static inline void DetailsAtPut(Dictionary* dict, int entry,
3302 PropertyDetails value) {
3303 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3304 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3307 template <typename Dictionary>
3308 static bool IsDeleted(Dictionary* dict, int entry) {
3312 template <typename Dictionary>
3313 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3314 Handle<Object> value, PropertyDetails details);
3318 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3320 static inline bool IsMatch(Handle<Name> key, Object* other);
3321 static inline uint32_t Hash(Handle<Name> key);
3322 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3323 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3324 static const int kPrefixSize = 2;
3325 static const int kEntrySize = 3;
3326 static const bool kIsEnumerable = true;
3330 class NameDictionary
3331 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3332 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3336 DECLARE_CAST(NameDictionary)
3338 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3339 Handle<NameDictionary> dictionary);
3343 class GlobalDictionaryShape : public NameDictionaryShape {
3345 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3347 template <typename Dictionary>
3348 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3350 template <typename Dictionary>
3351 static inline void DetailsAtPut(Dictionary* dict, int entry,
3352 PropertyDetails value);
3354 template <typename Dictionary>
3355 static bool IsDeleted(Dictionary* dict, int entry);
3357 template <typename Dictionary>
3358 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3359 Handle<Object> value, PropertyDetails details);
3363 class GlobalDictionary
3364 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3366 DECLARE_CAST(GlobalDictionary)
3370 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3372 static inline bool IsMatch(uint32_t key, Object* other);
3373 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3374 static const int kEntrySize = 3;
3375 static const bool kIsEnumerable = false;
3379 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3381 static const bool UsesSeed = true;
3382 static const int kPrefixSize = 2;
3384 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3385 static inline uint32_t SeededHashForObject(uint32_t key,
3391 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3393 static const int kPrefixSize = 0;
3395 static inline uint32_t Hash(uint32_t key);
3396 static inline uint32_t HashForObject(uint32_t key, Object* object);
3400 class SeededNumberDictionary
3401 : public Dictionary<SeededNumberDictionary,
3402 SeededNumberDictionaryShape,
3405 DECLARE_CAST(SeededNumberDictionary)
3407 // Type specific at put (default NONE attributes is used when adding).
3408 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3409 Handle<SeededNumberDictionary> dictionary,
3411 Handle<Object> value);
3412 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3413 Handle<SeededNumberDictionary> dictionary,
3415 Handle<Object> value,
3416 PropertyDetails details);
3418 // Set an existing entry or add a new one if needed.
3419 // Return the updated dictionary.
3420 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3421 Handle<SeededNumberDictionary> dictionary,
3423 Handle<Object> value,
3424 PropertyDetails details);
3426 void UpdateMaxNumberKey(uint32_t key);
3428 // If slow elements are required we will never go back to fast-case
3429 // for the elements kept in this dictionary. We require slow
3430 // elements if an element has been added at an index larger than
3431 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3432 // when defining a getter or setter with a number key.
3433 inline bool requires_slow_elements();
3434 inline void set_requires_slow_elements();
3436 // Get the value of the max number key that has been added to this
3437 // dictionary. max_number_key can only be called if
3438 // requires_slow_elements returns false.
3439 inline uint32_t max_number_key();
3442 static const int kRequiresSlowElementsMask = 1;
3443 static const int kRequiresSlowElementsTagSize = 1;
3444 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3448 class UnseededNumberDictionary
3449 : public Dictionary<UnseededNumberDictionary,
3450 UnseededNumberDictionaryShape,
3453 DECLARE_CAST(UnseededNumberDictionary)
3455 // Type specific at put (default NONE attributes is used when adding).
3456 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3457 Handle<UnseededNumberDictionary> dictionary,
3459 Handle<Object> value);
3460 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3461 Handle<UnseededNumberDictionary> dictionary,
3463 Handle<Object> value);
3465 // Set an existing entry or add a new one if needed.
3466 // Return the updated dictionary.
3467 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3468 Handle<UnseededNumberDictionary> dictionary,
3470 Handle<Object> value);
3474 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3476 static inline bool IsMatch(Handle<Object> key, Object* other);
3477 static inline uint32_t Hash(Handle<Object> key);
3478 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3479 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3480 static const int kPrefixSize = 0;
3481 static const int kEntrySize = 2;
3485 // ObjectHashTable maps keys that are arbitrary objects to object values by
3486 // using the identity hash of the key for hashing purposes.
3487 class ObjectHashTable: public HashTable<ObjectHashTable,
3488 ObjectHashTableShape,
3491 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3493 DECLARE_CAST(ObjectHashTable)
3495 // Attempt to shrink hash table after removal of key.
3496 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3497 Handle<ObjectHashTable> table,
3498 Handle<Object> key);
3500 // Looks up the value associated with the given key. The hole value is
3501 // returned in case the key is not present.
3502 Object* Lookup(Handle<Object> key);
3503 Object* Lookup(Handle<Object> key, int32_t hash);
3504 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3506 // Adds (or overwrites) the value associated with the given key.
3507 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3509 Handle<Object> value);
3510 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3511 Handle<Object> key, Handle<Object> value,
3514 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3515 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3518 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3519 Handle<Object> key, bool* was_present,
3523 friend class MarkCompactCollector;
3525 void AddEntry(int entry, Object* key, Object* value);
3526 void RemoveEntry(int entry);
3528 // Returns the index to the value of an entry.
3529 static inline int EntryToValueIndex(int entry) {
3530 return EntryToIndex(entry) + 1;
3535 // OrderedHashTable is a HashTable with Object keys that preserves
3536 // insertion order. There are Map and Set interfaces (OrderedHashMap
3537 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3539 // Only Object* keys are supported, with Object::SameValueZero() used as the
3540 // equality operator and Object::GetHash() for the hash function.
3542 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3543 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3544 // Originally attributed to Tyler Close.
3547 // [0]: bucket count
3548 // [1]: element count
3549 // [2]: deleted element count
3550 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3551 // offset into the data table (see below) where the
3552 // first item in this bucket is stored.
3553 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3554 // Capacity() * kEntrySize, where the first entrysize
3555 // items are handled by the derived class and the
3556 // item at kChainOffset is another entry into the
3557 // data table indicating the next entry in this hash
3560 // When we transition the table to a new version we obsolete it and reuse parts
3561 // of the memory to store information how to transition an iterator to the new
3564 // Memory layout for obsolete table:
3565 // [0]: bucket count
3566 // [1]: Next newer table
3567 // [2]: Number of removed holes or -1 when the table was cleared.
3568 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3569 // [3 + NumberOfRemovedHoles()..length]: Not used
3571 template<class Derived, class Iterator, int entrysize>
3572 class OrderedHashTable: public FixedArray {
3574 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3575 static Handle<Derived> Allocate(
3576 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3578 // Returns an OrderedHashTable (possibly |table|) with enough space
3579 // to add at least one new element.
3580 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3582 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3584 static Handle<Derived> Shrink(Handle<Derived> table);
3586 // Returns a new empty OrderedHashTable and records the clearing so that
3587 // exisiting iterators can be updated.
3588 static Handle<Derived> Clear(Handle<Derived> table);
3590 int NumberOfElements() {
3591 return Smi::cast(get(kNumberOfElementsIndex))->value();
3594 int NumberOfDeletedElements() {
3595 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3598 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3600 int NumberOfBuckets() {
3601 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3604 // Returns an index into |this| for the given entry.
3605 int EntryToIndex(int entry) {
3606 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3609 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3612 return !get(kNextTableIndex)->IsSmi();
3615 // The next newer table. This is only valid if the table is obsolete.
3616 Derived* NextTable() {
3617 return Derived::cast(get(kNextTableIndex));
3620 // When the table is obsolete we store the indexes of the removed holes.
3621 int RemovedIndexAt(int index) {
3622 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3625 static const int kNotFound = -1;
3626 static const int kMinCapacity = 4;
3628 static const int kNumberOfBucketsIndex = 0;
3629 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3630 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3631 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3632 static const int kNextTableIndex = kNumberOfElementsIndex;
3634 static const int kNumberOfBucketsOffset =
3635 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3636 static const int kNumberOfElementsOffset =
3637 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3638 static const int kNumberOfDeletedElementsOffset =
3639 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3640 static const int kHashTableStartOffset =
3641 kHeaderSize + kHashTableStartIndex * kPointerSize;
3642 static const int kNextTableOffset =
3643 kHeaderSize + kNextTableIndex * kPointerSize;
3645 static const int kEntrySize = entrysize + 1;
3646 static const int kChainOffset = entrysize;
3648 static const int kLoadFactor = 2;
3650 // NumberOfDeletedElements is set to kClearedTableSentinel when
3651 // the table is cleared, which allows iterator transitions to
3652 // optimize that case.
3653 static const int kClearedTableSentinel = -1;
3656 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3658 void SetNumberOfBuckets(int num) {
3659 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3662 void SetNumberOfElements(int num) {
3663 set(kNumberOfElementsIndex, Smi::FromInt(num));
3666 void SetNumberOfDeletedElements(int num) {
3667 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3671 return NumberOfBuckets() * kLoadFactor;
3674 void SetNextTable(Derived* next_table) {
3675 set(kNextTableIndex, next_table);
3678 void SetRemovedIndexAt(int index, int removed_index) {
3679 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3682 static const int kRemovedHolesIndex = kHashTableStartIndex;
3684 static const int kMaxCapacity =
3685 (FixedArray::kMaxLength - kHashTableStartIndex)
3686 / (1 + (kEntrySize * kLoadFactor));
3690 class JSSetIterator;
3693 class OrderedHashSet: public OrderedHashTable<
3694 OrderedHashSet, JSSetIterator, 1> {
3696 DECLARE_CAST(OrderedHashSet)
3700 class JSMapIterator;
3703 class OrderedHashMap
3704 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3706 DECLARE_CAST(OrderedHashMap)
3708 Object* ValueAt(int entry) {
3709 return get(EntryToIndex(entry) + kValueOffset);
3712 static const int kValueOffset = 1;
3716 template <int entrysize>
3717 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3719 static inline bool IsMatch(Handle<Object> key, Object* other);
3720 static inline uint32_t Hash(Handle<Object> key);
3721 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3722 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3723 static const int kPrefixSize = 0;
3724 static const int kEntrySize = entrysize;
3728 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3729 // values. The table wraps the keys in weak cells and store values directly.
3730 // Thus it references keys weakly and values strongly.
3731 class WeakHashTable: public HashTable<WeakHashTable,
3732 WeakHashTableShape<2>,
3735 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3737 DECLARE_CAST(WeakHashTable)
3739 // Looks up the value associated with the given key. The hole value is
3740 // returned in case the key is not present.
3741 Object* Lookup(Handle<HeapObject> key);
3743 // Adds (or overwrites) the value associated with the given key. Mapping a
3744 // key to the hole value causes removal of the whole entry.
3745 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3746 Handle<HeapObject> key,
3747 Handle<HeapObject> value);
3749 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3752 friend class MarkCompactCollector;
3754 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3756 // Returns the index to the value of an entry.
3757 static inline int EntryToValueIndex(int entry) {
3758 return EntryToIndex(entry) + 1;
3763 class WeakValueHashTable : public ObjectHashTable {
3765 DECLARE_CAST(WeakValueHashTable)
3768 // Looks up the value associated with the given key. The hole value is
3769 // returned in case the key is not present.
3770 Object* LookupWeak(Handle<Object> key);
3773 // Adds (or overwrites) the value associated with the given key. Mapping a
3774 // key to the hole value causes removal of the whole entry.
3775 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3776 Handle<WeakValueHashTable> table, Handle<Object> key,
3777 Handle<HeapObject> value);
3779 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3783 // JSFunctionResultCache caches results of some JSFunction invocation.
3784 // It is a fixed array with fixed structure:
3785 // [0]: factory function
3786 // [1]: finger index
3787 // [2]: current cache size
3788 // [3]: dummy field.
3789 // The rest of array are key/value pairs.
3790 class JSFunctionResultCache : public FixedArray {
3792 static const int kFactoryIndex = 0;
3793 static const int kFingerIndex = kFactoryIndex + 1;
3794 static const int kCacheSizeIndex = kFingerIndex + 1;
3795 static const int kDummyIndex = kCacheSizeIndex + 1;
3796 static const int kEntriesIndex = kDummyIndex + 1;
3798 static const int kEntrySize = 2; // key + value
3800 static const int kFactoryOffset = kHeaderSize;
3801 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3802 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3804 inline void MakeZeroSize();
3805 inline void Clear();
3808 inline void set_size(int size);
3809 inline int finger_index();
3810 inline void set_finger_index(int finger_index);
3812 DECLARE_CAST(JSFunctionResultCache)
3814 DECLARE_VERIFIER(JSFunctionResultCache)
3818 // ScopeInfo represents information about different scopes of a source
3819 // program and the allocation of the scope's variables. Scope information
3820 // is stored in a compressed form in ScopeInfo objects and is used
3821 // at runtime (stack dumps, deoptimization, etc.).
3823 // This object provides quick access to scope info details for runtime
3825 class ScopeInfo : public FixedArray {
3827 DECLARE_CAST(ScopeInfo)
3829 // Return the type of this scope.
3830 ScopeType scope_type();
3832 // Does this scope call eval?
3835 // Return the language mode of this scope.
3836 LanguageMode language_mode();
3838 // Does this scope make a sloppy eval call?
3839 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3841 // Return the total number of locals allocated on the stack and in the
3842 // context. This includes the parameters that are allocated in the context.
3845 // Return the number of stack slots for code. This number consists of two
3847 // 1. One stack slot per stack allocated local.
3848 // 2. One stack slot for the function name if it is stack allocated.
3849 int StackSlotCount();
3851 // Return the number of context slots for code if a context is allocated. This
3852 // number consists of three parts:
3853 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3854 // 2. One context slot per context allocated local.
3855 // 3. One context slot for the function name if it is context allocated.
3856 // Parameters allocated in the context count as context allocated locals. If
3857 // no contexts are allocated for this scope ContextLength returns 0.
3858 int ContextLength();
3860 // Does this scope declare a "this" binding?
3863 // Does this scope declare a "this" binding, and the "this" binding is stack-
3864 // or context-allocated?
3865 bool HasAllocatedReceiver();
3867 // Is this scope the scope of a named function expression?
3868 bool HasFunctionName();
3870 // Return if this has context allocated locals.
3871 bool HasHeapAllocatedLocals();
3873 // Return if contexts are allocated for this scope.
3876 // Return if this is a function scope with "use asm".
3877 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3879 // Return if this is a nested function within an asm module scope.
3880 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3882 bool IsSimpleParameterList() {
3883 return IsSimpleParameterListField::decode(Flags());
3886 // Return the function_name if present.
3887 String* FunctionName();
3889 // Return the name of the given parameter.
3890 String* ParameterName(int var);
3892 // Return the name of the given local.
3893 String* LocalName(int var);
3895 // Return the name of the given stack local.
3896 String* StackLocalName(int var);
3898 // Return the name of the given stack local.
3899 int StackLocalIndex(int var);
3901 // Return the name of the given context local.
3902 String* ContextLocalName(int var);
3904 // Return the mode of the given context local.
3905 VariableMode ContextLocalMode(int var);
3907 // Return the initialization flag of the given context local.
3908 InitializationFlag ContextLocalInitFlag(int var);
3910 // Return the initialization flag of the given context local.
3911 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3913 // Return true if this local was introduced by the compiler, and should not be
3914 // exposed to the user in a debugger.
3915 bool LocalIsSynthetic(int var);
3917 String* StrongModeFreeVariableName(int var);
3918 int StrongModeFreeVariableStartPosition(int var);
3919 int StrongModeFreeVariableEndPosition(int var);
3921 // Lookup support for serialized scope info. Returns the
3922 // the stack slot index for a given slot name if the slot is
3923 // present; otherwise returns a value < 0. The name must be an internalized
3925 int StackSlotIndex(String* name);
3927 // Lookup support for serialized scope info. Returns the
3928 // context slot index for a given slot name if the slot is present; otherwise
3929 // returns a value < 0. The name must be an internalized string.
3930 // If the slot is present and mode != NULL, sets *mode to the corresponding
3931 // mode for that variable.
3932 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3933 VariableMode* mode, VariableLocation* location,
3934 InitializationFlag* init_flag,
3935 MaybeAssignedFlag* maybe_assigned_flag);
3937 // Lookup the name of a certain context slot by its index.
3938 String* ContextSlotName(int slot_index);
3940 // Lookup support for serialized scope info. Returns the
3941 // parameter index for a given parameter name if the parameter is present;
3942 // otherwise returns a value < 0. The name must be an internalized string.
3943 int ParameterIndex(String* name);
3945 // Lookup support for serialized scope info. Returns the function context
3946 // slot index if the function name is present and context-allocated (named
3947 // function expressions, only), otherwise returns a value < 0. The name
3948 // must be an internalized string.
3949 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3951 // Lookup support for serialized scope info. Returns the receiver context
3952 // slot index if scope has a "this" binding, and the binding is
3953 // context-allocated. Otherwise returns a value < 0.
3954 int ReceiverContextSlotIndex();
3956 FunctionKind function_kind();
3958 // Copies all the context locals into an object used to materialize a scope.
3959 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
3960 Handle<Context> context,
3961 Handle<JSObject> scope_object);
3964 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3965 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3967 // Serializes empty scope info.
3968 static ScopeInfo* Empty(Isolate* isolate);
3974 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3975 // numeric and occupies one array slot.
3976 // 1. A set of properties of the scope
3977 // 2. The number of parameters. This only applies to function scopes. For
3978 // non-function scopes this is 0.
3979 // 3. The number of non-parameter variables allocated on the stack.
3980 // 4. The number of non-parameter and parameter variables allocated in the
3982 #define FOR_EACH_NUMERIC_FIELD(V) \
3985 V(StackLocalCount) \
3986 V(ContextLocalCount) \
3987 V(ContextGlobalCount) \
3988 V(StrongModeFreeVariableCount)
3990 #define FIELD_ACCESSORS(name) \
3991 void Set##name(int value) { \
3992 set(k##name, Smi::FromInt(value)); \
3995 if (length() > 0) { \
3996 return Smi::cast(get(k##name))->value(); \
4001 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4002 #undef FIELD_ACCESSORS
4006 #define DECL_INDEX(name) k##name,
4007 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4009 #undef FOR_EACH_NUMERIC_FIELD
4013 // The layout of the variable part of a ScopeInfo is as follows:
4014 // 1. ParameterEntries:
4015 // This part stores the names of the parameters for function scopes. One
4016 // slot is used per parameter, so in total this part occupies
4017 // ParameterCount() slots in the array. For other scopes than function
4018 // scopes ParameterCount() is 0.
4019 // 2. StackLocalFirstSlot:
4020 // Index of a first stack slot for stack local. Stack locals belonging to
4021 // this scope are located on a stack at slots starting from this index.
4022 // 3. StackLocalEntries:
4023 // Contains the names of local variables that are allocated on the stack,
4024 // in increasing order of the stack slot index. First local variable has
4025 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4026 // One slot is used per stack local, so in total this part occupies
4027 // StackLocalCount() slots in the array.
4028 // 4. ContextLocalNameEntries:
4029 // Contains the names of local variables and parameters that are allocated
4030 // in the context. They are stored in increasing order of the context slot
4031 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4032 // context local, so in total this part occupies ContextLocalCount() slots
4034 // 5. ContextLocalInfoEntries:
4035 // Contains the variable modes and initialization flags corresponding to
4036 // the context locals in ContextLocalNameEntries. One slot is used per
4037 // context local, so in total this part occupies ContextLocalCount()
4038 // slots in the array.
4039 // 6. StrongModeFreeVariableNameEntries:
4040 // Stores the names of strong mode free variables.
4041 // 7. StrongModeFreeVariablePositionEntries:
4042 // Stores the locations (start and end position) of strong mode free
4044 // 8. RecieverEntryIndex:
4045 // If the scope binds a "this" value, one slot is reserved to hold the
4046 // context or stack slot index for the variable.
4047 // 9. FunctionNameEntryIndex:
4048 // If the scope belongs to a named function expression this part contains
4049 // information about the function variable. It always occupies two array
4050 // slots: a. The name of the function variable.
4051 // b. The context or stack slot index for the variable.
4052 int ParameterEntriesIndex();
4053 int StackLocalFirstSlotIndex();
4054 int StackLocalEntriesIndex();
4055 int ContextLocalNameEntriesIndex();
4056 int ContextGlobalNameEntriesIndex();
4057 int ContextLocalInfoEntriesIndex();
4058 int ContextGlobalInfoEntriesIndex();
4059 int StrongModeFreeVariableNameEntriesIndex();
4060 int StrongModeFreeVariablePositionEntriesIndex();
4061 int ReceiverEntryIndex();
4062 int FunctionNameEntryIndex();
4064 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4065 VariableLocation* location, InitializationFlag* init_flag,
4066 MaybeAssignedFlag* maybe_assigned_flag);
4068 // Used for the function name variable for named function expressions, and for
4070 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4072 // Properties of scopes.
4073 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4074 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4075 STATIC_ASSERT(LANGUAGE_END == 3);
4076 class LanguageModeField
4077 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4078 class ReceiverVariableField
4079 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4080 class FunctionVariableField
4081 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4083 class FunctionVariableMode
4084 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4085 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4087 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4088 class IsSimpleParameterListField
4089 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4090 class FunctionKindField
4091 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4093 // BitFields representing the encoded information for context locals in the
4094 // ContextLocalInfoEntries part.
4095 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4096 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4097 class ContextLocalMaybeAssignedFlag
4098 : public BitField<MaybeAssignedFlag, 4, 1> {};
4102 // The cache for maps used by normalized (dictionary mode) objects.
4103 // Such maps do not have property descriptors, so a typical program
4104 // needs very limited number of distinct normalized maps.
4105 class NormalizedMapCache: public FixedArray {
4107 static Handle<NormalizedMapCache> New(Isolate* isolate);
4109 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4110 PropertyNormalizationMode mode);
4111 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4115 DECLARE_CAST(NormalizedMapCache)
4117 static inline bool IsNormalizedMapCache(const Object* obj);
4119 DECLARE_VERIFIER(NormalizedMapCache)
4121 static const int kEntries = 64;
4123 static inline int GetIndex(Handle<Map> map);
4125 // The following declarations hide base class methods.
4126 Object* get(int index);
4127 void set(int index, Object* value);
4131 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4132 // that is attached to code objects.
4133 class ByteArray: public FixedArrayBase {
4135 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4137 // Setter and getter.
4138 inline byte get(int index);
4139 inline void set(int index, byte value);
4141 // Treat contents as an int array.
4142 inline int get_int(int index);
4144 static int SizeFor(int length) {
4145 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4147 // We use byte arrays for free blocks in the heap. Given a desired size in
4148 // bytes that is a multiple of the word size and big enough to hold a byte
4149 // array, this function returns the number of elements a byte array should
4151 static int LengthFor(int size_in_bytes) {
4152 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4153 DCHECK(size_in_bytes >= kHeaderSize);
4154 return size_in_bytes - kHeaderSize;
4157 // Returns data start address.
4158 inline Address GetDataStartAddress();
4160 // Returns a pointer to the ByteArray object for a given data start address.
4161 static inline ByteArray* FromDataStartAddress(Address address);
4163 DECLARE_CAST(ByteArray)
4165 // Dispatched behavior.
4166 inline int ByteArraySize() {
4167 return SizeFor(this->length());
4169 DECLARE_PRINTER(ByteArray)
4170 DECLARE_VERIFIER(ByteArray)
4172 // Layout description.
4173 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4175 // Maximal memory consumption for a single ByteArray.
4176 static const int kMaxSize = 512 * MB;
4177 // Maximal length of a single ByteArray.
4178 static const int kMaxLength = kMaxSize - kHeaderSize;
4181 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4185 // BytecodeArray represents a sequence of interpreter bytecodes.
4186 class BytecodeArray : public FixedArrayBase {
4188 static int SizeFor(int length) {
4189 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4192 // Setter and getter
4193 inline byte get(int index);
4194 inline void set(int index, byte value);
4196 // Returns data start address.
4197 inline Address GetFirstBytecodeAddress();
4199 // Accessors for frame size and the number of locals
4200 inline int frame_size() const;
4201 inline void set_frame_size(int value);
4203 DECLARE_CAST(BytecodeArray)
4205 // Dispatched behavior.
4206 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4208 DECLARE_PRINTER(BytecodeArray)
4209 DECLARE_VERIFIER(BytecodeArray)
4211 void Disassemble(std::ostream& os);
4213 // Layout description.
4214 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4215 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4217 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4219 // Maximal memory consumption for a single BytecodeArray.
4220 static const int kMaxSize = 512 * MB;
4221 // Maximal length of a single BytecodeArray.
4222 static const int kMaxLength = kMaxSize - kHeaderSize;
4225 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4229 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4230 // They look like heap objects (are heap object tagged and have a map) so that
4231 // the heap remains iterable. They have a size and a next pointer.
4232 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4233 // in the free list.
4234 class FreeSpace: public HeapObject {
4236 // [size]: size of the free space including the header.
4237 inline int size() const;
4238 inline void set_size(int value);
4240 inline int nobarrier_size() const;
4241 inline void nobarrier_set_size(int value);
4243 inline int Size() { return size(); }
4245 // Accessors for the next field.
4246 inline FreeSpace* next();
4247 inline FreeSpace** next_address();
4248 inline void set_next(FreeSpace* next);
4250 inline static FreeSpace* cast(HeapObject* obj);
4252 // Dispatched behavior.
4253 DECLARE_PRINTER(FreeSpace)
4254 DECLARE_VERIFIER(FreeSpace)
4256 // Layout description.
4257 // Size is smi tagged when it is stored.
4258 static const int kSizeOffset = HeapObject::kHeaderSize;
4259 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4262 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4266 // V has parameters (Type, type, TYPE, C type, element_size)
4267 #define TYPED_ARRAYS(V) \
4268 V(Uint8, uint8, UINT8, uint8_t, 1) \
4269 V(Int8, int8, INT8, int8_t, 1) \
4270 V(Uint16, uint16, UINT16, uint16_t, 2) \
4271 V(Int16, int16, INT16, int16_t, 2) \
4272 V(Uint32, uint32, UINT32, uint32_t, 4) \
4273 V(Int32, int32, INT32, int32_t, 4) \
4274 V(Float32, float32, FLOAT32, float, 4) \
4275 V(Float64, float64, FLOAT64, double, 8) \
4276 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4279 class FixedTypedArrayBase: public FixedArrayBase {
4281 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4282 DECL_ACCESSORS(base_pointer, Object)
4284 // [external_pointer]: Contains the offset between base_pointer and the start
4285 // of the data. If the base_pointer is a nullptr, the external_pointer
4286 // therefore points to the actual backing store.
4287 DECL_ACCESSORS(external_pointer, void)
4289 // Dispatched behavior.
4290 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4292 template <typename StaticVisitor>
4293 inline void FixedTypedArrayBaseIterateBody();
4295 DECLARE_CAST(FixedTypedArrayBase)
4297 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4298 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4299 static const int kHeaderSize =
4300 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4302 static const int kDataOffset = kHeaderSize;
4306 static inline int TypedArraySize(InstanceType type, int length);
4307 inline int TypedArraySize(InstanceType type);
4309 // Use with care: returns raw pointer into heap.
4310 inline void* DataPtr();
4312 inline int DataSize();
4315 static inline int ElementSize(InstanceType type);
4317 inline int DataSize(InstanceType type);
4319 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4323 template <class Traits>
4324 class FixedTypedArray: public FixedTypedArrayBase {
4326 typedef typename Traits::ElementType ElementType;
4327 static const InstanceType kInstanceType = Traits::kInstanceType;
4329 DECLARE_CAST(FixedTypedArray<Traits>)
4331 inline ElementType get_scalar(int index);
4332 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4333 inline void set(int index, ElementType value);
4335 static inline ElementType from_int(int value);
4336 static inline ElementType from_double(double value);
4338 // This accessor applies the correct conversion from Smi, HeapNumber
4340 void SetValue(uint32_t index, Object* value);
4342 DECLARE_PRINTER(FixedTypedArray)
4343 DECLARE_VERIFIER(FixedTypedArray)
4346 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4349 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4350 class Type##ArrayTraits { \
4351 public: /* NOLINT */ \
4352 typedef elementType ElementType; \
4353 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4354 static const char* Designator() { return #type " array"; } \
4355 static inline Handle<Object> ToHandle(Isolate* isolate, \
4356 elementType scalar); \
4357 static inline elementType defaultValue(); \
4360 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4362 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4364 #undef FIXED_TYPED_ARRAY_TRAITS
4367 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4368 // data for code generated by the Hydrogen/Lithium compiler. It also
4369 // contains information about functions that were inlined. If N different
4370 // functions were inlined then first N elements of the literal array will
4371 // contain these functions.
4374 class DeoptimizationInputData: public FixedArray {
4376 // Layout description. Indices in the array.
4377 static const int kTranslationByteArrayIndex = 0;
4378 static const int kInlinedFunctionCountIndex = 1;
4379 static const int kLiteralArrayIndex = 2;
4380 static const int kOsrAstIdIndex = 3;
4381 static const int kOsrPcOffsetIndex = 4;
4382 static const int kOptimizationIdIndex = 5;
4383 static const int kSharedFunctionInfoIndex = 6;
4384 static const int kWeakCellCacheIndex = 7;
4385 static const int kFirstDeoptEntryIndex = 8;
4387 // Offsets of deopt entry elements relative to the start of the entry.
4388 static const int kAstIdRawOffset = 0;
4389 static const int kTranslationIndexOffset = 1;
4390 static const int kArgumentsStackHeightOffset = 2;
4391 static const int kPcOffset = 3;
4392 static const int kDeoptEntrySize = 4;
4394 // Simple element accessors.
4395 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4397 return type::cast(get(k##name##Index)); \
4399 void Set##name(type* value) { \
4400 set(k##name##Index, value); \
4403 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4404 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4405 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4406 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4407 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4408 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4409 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4410 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4412 #undef DEFINE_ELEMENT_ACCESSORS
4414 // Accessors for elements of the ith deoptimization entry.
4415 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4416 type* name(int i) { \
4417 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4419 void Set##name(int i, type* value) { \
4420 set(IndexForEntry(i) + k##name##Offset, value); \
4423 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4424 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4425 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4426 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4428 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4430 BailoutId AstId(int i) {
4431 return BailoutId(AstIdRaw(i)->value());
4434 void SetAstId(int i, BailoutId value) {
4435 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4439 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4442 // Allocates a DeoptimizationInputData.
4443 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4444 int deopt_entry_count,
4445 PretenureFlag pretenure);
4447 DECLARE_CAST(DeoptimizationInputData)
4449 #ifdef ENABLE_DISASSEMBLER
4450 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4454 static int IndexForEntry(int i) {
4455 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4459 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4463 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4464 // data for code generated by the full compiler.
4465 // The format of the these objects is
4466 // [i * 2]: Ast ID for ith deoptimization.
4467 // [i * 2 + 1]: PC and state of ith deoptimization
4468 class DeoptimizationOutputData: public FixedArray {
4470 int DeoptPoints() { return length() / 2; }
4472 BailoutId AstId(int index) {
4473 return BailoutId(Smi::cast(get(index * 2))->value());
4476 void SetAstId(int index, BailoutId id) {
4477 set(index * 2, Smi::FromInt(id.ToInt()));
4480 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4481 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4483 static int LengthOfFixedArray(int deopt_points) {
4484 return deopt_points * 2;
4487 // Allocates a DeoptimizationOutputData.
4488 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4489 int number_of_deopt_points,
4490 PretenureFlag pretenure);
4492 DECLARE_CAST(DeoptimizationOutputData)
4494 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4495 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4500 // HandlerTable is a fixed array containing entries for exception handlers in
4501 // the code object it is associated with. The tables comes in two flavors:
4502 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4503 // exception handler and a range representing the try-block covered by that
4504 // handler. Layout looks as follows:
4505 // [ range-start , range-end , handler-offset , stack-depth ]
4506 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4507 // per call-site that could throw an exception. Layout looks as follows:
4508 // [ return-address-offset , handler-offset ]
4509 class HandlerTable : public FixedArray {
4511 // Conservative prediction whether a given handler will locally catch an
4512 // exception or cause a re-throw to outside the code boundary. Since this is
4513 // undecidable it is merely an approximation (e.g. useful for debugger).
4514 enum CatchPrediction { UNCAUGHT, CAUGHT };
4516 // Accessors for handler table based on ranges.
4517 void SetRangeStart(int index, int value) {
4518 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4520 void SetRangeEnd(int index, int value) {
4521 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4523 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4524 int value = HandlerOffsetField::encode(offset) |
4525 HandlerPredictionField::encode(prediction);
4526 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4528 void SetRangeDepth(int index, int value) {
4529 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4532 // Accessors for handler table based on return addresses.
4533 void SetReturnOffset(int index, int value) {
4534 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4536 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4537 int value = HandlerOffsetField::encode(offset) |
4538 HandlerPredictionField::encode(prediction);
4539 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4542 // Lookup handler in a table based on ranges.
4543 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4545 // Lookup handler in a table based on return addresses.
4546 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4548 // Returns the required length of the underlying fixed array.
4549 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4550 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4552 DECLARE_CAST(HandlerTable)
4554 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4555 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4556 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4560 // Layout description for handler table based on ranges.
4561 static const int kRangeStartIndex = 0;
4562 static const int kRangeEndIndex = 1;
4563 static const int kRangeHandlerIndex = 2;
4564 static const int kRangeDepthIndex = 3;
4565 static const int kRangeEntrySize = 4;
4567 // Layout description for handler table based on return addresses.
4568 static const int kReturnOffsetIndex = 0;
4569 static const int kReturnHandlerIndex = 1;
4570 static const int kReturnEntrySize = 2;
4572 // Encoding of the {handler} field.
4573 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4574 class HandlerOffsetField : public BitField<int, 1, 30> {};
4578 // Code describes objects with on-the-fly generated machine code.
4579 class Code: public HeapObject {
4581 // Opaque data type for encapsulating code flags like kind, inline
4582 // cache state, and arguments count.
4583 typedef uint32_t Flags;
4585 #define NON_IC_KIND_LIST(V) \
4587 V(OPTIMIZED_FUNCTION) \
4593 #define IC_KIND_LIST(V) \
4604 #define CODE_KIND_LIST(V) \
4605 NON_IC_KIND_LIST(V) \
4609 #define DEFINE_CODE_KIND_ENUM(name) name,
4610 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4611 #undef DEFINE_CODE_KIND_ENUM
4615 // No more than 16 kinds. The value is currently encoded in four bits in
4617 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4619 static const char* Kind2String(Kind kind);
4627 static const int kPrologueOffsetNotSet = -1;
4629 #ifdef ENABLE_DISASSEMBLER
4631 static const char* ICState2String(InlineCacheState state);
4632 static const char* StubType2String(StubType type);
4633 static void PrintExtraICState(std::ostream& os, // NOLINT
4634 Kind kind, ExtraICState extra);
4635 void Disassemble(const char* name, std::ostream& os); // NOLINT
4636 #endif // ENABLE_DISASSEMBLER
4638 // [instruction_size]: Size of the native instructions
4639 inline int instruction_size() const;
4640 inline void set_instruction_size(int value);
4642 // [relocation_info]: Code relocation information
4643 DECL_ACCESSORS(relocation_info, ByteArray)
4644 void InvalidateRelocation();
4645 void InvalidateEmbeddedObjects();
4647 // [handler_table]: Fixed array containing offsets of exception handlers.
4648 DECL_ACCESSORS(handler_table, FixedArray)
4650 // [deoptimization_data]: Array containing data for deopt.
4651 DECL_ACCESSORS(deoptimization_data, FixedArray)
4653 // [raw_type_feedback_info]: This field stores various things, depending on
4654 // the kind of the code object.
4655 // FUNCTION => type feedback information.
4656 // STUB and ICs => major/minor key as Smi.
4657 DECL_ACCESSORS(raw_type_feedback_info, Object)
4658 inline Object* type_feedback_info();
4659 inline void set_type_feedback_info(
4660 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4661 inline uint32_t stub_key();
4662 inline void set_stub_key(uint32_t key);
4664 // [next_code_link]: Link for lists of optimized or deoptimized code.
4665 // Note that storage for this field is overlapped with typefeedback_info.
4666 DECL_ACCESSORS(next_code_link, Object)
4668 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4669 // field does not have to be traced during garbage collection since
4670 // it is only used by the garbage collector itself.
4671 DECL_ACCESSORS(gc_metadata, Object)
4673 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4674 // at the moment when this object was created.
4675 inline void set_ic_age(int count);
4676 inline int ic_age() const;
4678 // [prologue_offset]: Offset of the function prologue, used for aging
4679 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4680 inline int prologue_offset() const;
4681 inline void set_prologue_offset(int offset);
4683 // [constant_pool offset]: Offset of the constant pool.
4684 // Valid for FLAG_enable_embedded_constant_pool only
4685 inline int constant_pool_offset() const;
4686 inline void set_constant_pool_offset(int offset);
4688 // Unchecked accessors to be used during GC.
4689 inline ByteArray* unchecked_relocation_info();
4691 inline int relocation_size();
4693 // [flags]: Various code flags.
4694 inline Flags flags();
4695 inline void set_flags(Flags flags);
4697 // [flags]: Access to specific code flags.
4699 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4700 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4702 inline StubType type(); // Only valid for monomorphic IC stubs.
4704 // Testers for IC stub kinds.
4705 inline bool is_inline_cache_stub();
4706 inline bool is_debug_stub();
4707 inline bool is_handler() { return kind() == HANDLER; }
4708 inline bool is_load_stub() { return kind() == LOAD_IC; }
4709 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4710 inline bool is_store_stub() { return kind() == STORE_IC; }
4711 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4712 inline bool is_call_stub() { return kind() == CALL_IC; }
4713 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4714 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4715 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4716 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4717 inline bool is_keyed_stub();
4718 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4719 inline bool embeds_maps_weakly() {
4721 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4722 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4723 ic_state() == MONOMORPHIC;
4726 inline bool IsCodeStubOrIC();
4728 inline void set_raw_kind_specific_flags1(int value);
4729 inline void set_raw_kind_specific_flags2(int value);
4731 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4732 // object was generated by either the hydrogen or the TurboFan optimizing
4733 // compiler (but it may not be an optimized function).
4734 inline bool is_crankshafted();
4735 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4736 inline void set_is_crankshafted(bool value);
4738 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4739 // code object was generated by the TurboFan optimizing compiler.
4740 inline bool is_turbofanned();
4741 inline void set_is_turbofanned(bool value);
4743 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4744 // embedded objects in code should be treated weakly.
4745 inline bool can_have_weak_objects();
4746 inline void set_can_have_weak_objects(bool value);
4748 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4749 // deoptimization support.
4750 inline bool has_deoptimization_support();
4751 inline void set_has_deoptimization_support(bool value);
4753 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4754 // been compiled with debug break slots.
4755 inline bool has_debug_break_slots();
4756 inline void set_has_debug_break_slots(bool value);
4758 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4759 // reloc info includes runtime and external references to support
4760 // serialization/deserialization.
4761 inline bool has_reloc_info_for_serialization();
4762 inline void set_has_reloc_info_for_serialization(bool value);
4764 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4765 // how long the function has been marked for OSR and therefore which
4766 // level of loop nesting we are willing to do on-stack replacement
4768 inline void set_allow_osr_at_loop_nesting_level(int level);
4769 inline int allow_osr_at_loop_nesting_level();
4771 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4772 // the code object was seen on the stack with no IC patching going on.
4773 inline int profiler_ticks();
4774 inline void set_profiler_ticks(int ticks);
4776 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4777 // For builtins, tells which builtin index it has.
4778 // Note that builtins can have a code kind other than BUILTIN, which means
4779 // that for arbitrary code objects, this index value may be random garbage.
4780 // To verify in that case, compare the code object to the indexed builtin.
4781 inline int builtin_index();
4782 inline void set_builtin_index(int id);
4784 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4785 // reserved in the code prologue.
4786 inline unsigned stack_slots();
4787 inline void set_stack_slots(unsigned slots);
4789 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4790 // the instruction stream where the safepoint table starts.
4791 inline unsigned safepoint_table_offset();
4792 inline void set_safepoint_table_offset(unsigned offset);
4794 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4795 // instruction stream where the back edge table starts.
4796 inline unsigned back_edge_table_offset();
4797 inline void set_back_edge_table_offset(unsigned offset);
4799 inline bool back_edges_patched_for_osr();
4801 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4802 inline uint16_t to_boolean_state();
4804 // [has_function_cache]: For kind STUB tells whether there is a function
4805 // cache is passed to the stub.
4806 inline bool has_function_cache();
4807 inline void set_has_function_cache(bool flag);
4810 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4811 // the code is going to be deoptimized because of dead embedded maps.
4812 inline bool marked_for_deoptimization();
4813 inline void set_marked_for_deoptimization(bool flag);
4815 // [constant_pool]: The constant pool for this function.
4816 inline Address constant_pool();
4818 // Get the safepoint entry for the given pc.
4819 SafepointEntry GetSafepointEntry(Address pc);
4821 // Find an object in a stub with a specified map
4822 Object* FindNthObject(int n, Map* match_map);
4824 // Find the first allocation site in an IC stub.
4825 AllocationSite* FindFirstAllocationSite();
4827 // Find the first map in an IC stub.
4828 Map* FindFirstMap();
4829 void FindAllMaps(MapHandleList* maps);
4831 // Find the first handler in an IC stub.
4832 Code* FindFirstHandler();
4834 // Find |length| handlers and put them into |code_list|. Returns false if not
4835 // enough handlers can be found.
4836 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4838 // Find the handler for |map|.
4839 MaybeHandle<Code> FindHandlerForMap(Map* map);
4841 // Find the first name in an IC stub.
4842 Name* FindFirstName();
4844 class FindAndReplacePattern;
4845 // For each (map-to-find, object-to-replace) pair in the pattern, this
4846 // function replaces the corresponding placeholder in the code with the
4847 // object-to-replace. The function assumes that pairs in the pattern come in
4848 // the same order as the placeholders in the code.
4849 // If the placeholder is a weak cell, then the value of weak cell is matched
4850 // against the map-to-find.
4851 void FindAndReplace(const FindAndReplacePattern& pattern);
4853 // The entire code object including its header is copied verbatim to the
4854 // snapshot so that it can be written in one, fast, memcpy during
4855 // deserialization. The deserializer will overwrite some pointers, rather
4856 // like a runtime linker, but the random allocation addresses used in the
4857 // mksnapshot process would still be present in the unlinked snapshot data,
4858 // which would make snapshot production non-reproducible. This method wipes
4859 // out the to-be-overwritten header data for reproducible snapshots.
4860 inline void WipeOutHeader();
4862 // Flags operations.
4863 static inline Flags ComputeFlags(
4864 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4865 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4866 CacheHolderFlag holder = kCacheOnReceiver);
4868 static inline Flags ComputeMonomorphicFlags(
4869 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4870 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4872 static inline Flags ComputeHandlerFlags(
4873 Kind handler_kind, StubType type = NORMAL,
4874 CacheHolderFlag holder = kCacheOnReceiver);
4876 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4877 static inline StubType ExtractTypeFromFlags(Flags flags);
4878 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4879 static inline Kind ExtractKindFromFlags(Flags flags);
4880 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4882 static inline Flags RemoveTypeFromFlags(Flags flags);
4883 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4885 // Convert a target address into a code object.
4886 static inline Code* GetCodeFromTargetAddress(Address address);
4888 // Convert an entry address into an object.
4889 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4891 // Returns the address of the first instruction.
4892 inline byte* instruction_start();
4894 // Returns the address right after the last instruction.
4895 inline byte* instruction_end();
4897 // Returns the size of the instructions, padding, and relocation information.
4898 inline int body_size();
4900 // Returns the address of the first relocation info (read backwards!).
4901 inline byte* relocation_start();
4903 // Code entry point.
4904 inline byte* entry();
4906 // Returns true if pc is inside this object's instructions.
4907 inline bool contains(byte* pc);
4909 // Relocate the code by delta bytes. Called to signal that this code
4910 // object has been moved by delta bytes.
4911 void Relocate(intptr_t delta);
4913 // Migrate code described by desc.
4914 void CopyFrom(const CodeDesc& desc);
4916 // Returns the object size for a given body (used for allocation).
4917 static int SizeFor(int body_size) {
4918 DCHECK_SIZE_TAG_ALIGNED(body_size);
4919 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4922 // Calculate the size of the code object to report for log events. This takes
4923 // the layout of the code object into account.
4924 int ExecutableSize() {
4925 // Check that the assumptions about the layout of the code object holds.
4926 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
4928 return instruction_size() + Code::kHeaderSize;
4931 // Locating source position.
4932 int SourcePosition(Address pc);
4933 int SourceStatementPosition(Address pc);
4937 // Dispatched behavior.
4938 int CodeSize() { return SizeFor(body_size()); }
4939 inline void CodeIterateBody(ObjectVisitor* v);
4941 template<typename StaticVisitor>
4942 inline void CodeIterateBody(Heap* heap);
4944 DECLARE_PRINTER(Code)
4945 DECLARE_VERIFIER(Code)
4947 void ClearInlineCaches();
4948 void ClearInlineCaches(Kind kind);
4950 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4951 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4953 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4955 kToBeExecutedOnceCodeAge = -3,
4956 kNotExecutedCodeAge = -2,
4957 kExecutedOnceCodeAge = -1,
4959 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4961 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4962 kLastCodeAge = kAfterLastCodeAge - 1,
4963 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4964 kIsOldCodeAge = kSexagenarianCodeAge,
4965 kPreAgedCodeAge = kIsOldCodeAge - 1
4967 #undef DECLARE_CODE_AGE_ENUM
4969 // Code aging. Indicates how many full GCs this code has survived without
4970 // being entered through the prologue. Used to determine when it is
4971 // relatively safe to flush this code object and replace it with the lazy
4972 // compilation stub.
4973 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4974 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4975 void MakeYoung(Isolate* isolate);
4976 void MarkToBeExecutedOnce(Isolate* isolate);
4977 void MakeOlder(MarkingParity);
4978 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4981 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4982 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4985 void PrintDeoptLocation(FILE* out, Address pc);
4986 bool CanDeoptAt(Address pc);
4989 void VerifyEmbeddedObjectsDependency();
4993 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4994 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4995 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4998 inline bool CanContainWeakObjects() {
4999 // is_turbofanned() implies !can_have_weak_objects().
5000 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5001 !can_have_weak_objects());
5002 return is_optimized_code() && can_have_weak_objects();
5005 inline bool IsWeakObject(Object* object) {
5006 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5009 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5011 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5012 WeakCell* CachedWeakCell();
5014 // Max loop nesting marker used to postpose OSR. We don't take loop
5015 // nesting that is deeper than 5 levels into account.
5016 static const int kMaxLoopNestingMarker = 6;
5018 static const int kConstantPoolSize =
5019 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5021 // Layout description.
5022 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5023 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5024 static const int kDeoptimizationDataOffset =
5025 kHandlerTableOffset + kPointerSize;
5026 // For FUNCTION kind, we store the type feedback info here.
5027 static const int kTypeFeedbackInfoOffset =
5028 kDeoptimizationDataOffset + kPointerSize;
5029 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5030 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5031 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5032 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5033 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5034 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5035 static const int kKindSpecificFlags2Offset =
5036 kKindSpecificFlags1Offset + kIntSize;
5037 // Note: We might be able to squeeze this into the flags above.
5038 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5039 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5040 static const int kHeaderPaddingStart =
5041 kConstantPoolOffset + kConstantPoolSize;
5043 // Add padding to align the instruction start following right after
5044 // the Code object header.
5045 static const int kHeaderSize =
5046 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5048 // Byte offsets within kKindSpecificFlags1Offset.
5049 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5050 class FullCodeFlagsHasDeoptimizationSupportField:
5051 public BitField<bool, 0, 1> {}; // NOLINT
5052 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5053 class FullCodeFlagsHasRelocInfoForSerialization
5054 : public BitField<bool, 2, 1> {};
5055 // Bit 3 in this bitfield is unused.
5056 class ProfilerTicksField : public BitField<int, 4, 28> {};
5058 // Flags layout. BitField<type, shift, size>.
5059 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5060 class TypeField : public BitField<StubType, 4, 1> {};
5061 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5062 class KindField : public BitField<Kind, 7, 4> {};
5063 class ExtraICStateField: public BitField<ExtraICState, 11,
5064 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5066 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5067 static const int kStackSlotsFirstBit = 0;
5068 static const int kStackSlotsBitCount = 24;
5069 static const int kHasFunctionCacheBit =
5070 kStackSlotsFirstBit + kStackSlotsBitCount;
5071 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5072 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5073 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5075 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5076 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5078 class StackSlotsField: public BitField<int,
5079 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5080 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5082 class MarkedForDeoptimizationField
5083 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5084 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5086 class CanHaveWeakObjectsField
5087 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5089 // KindSpecificFlags2 layout (ALL)
5090 static const int kIsCrankshaftedBit = 0;
5091 class IsCrankshaftedField: public BitField<bool,
5092 kIsCrankshaftedBit, 1> {}; // NOLINT
5094 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5095 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5096 static const int kSafepointTableOffsetBitCount = 30;
5098 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5099 kSafepointTableOffsetBitCount <= 32);
5100 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5102 class SafepointTableOffsetField: public BitField<int,
5103 kSafepointTableOffsetFirstBit,
5104 kSafepointTableOffsetBitCount> {}; // NOLINT
5106 // KindSpecificFlags2 layout (FUNCTION)
5107 class BackEdgeTableOffsetField: public BitField<int,
5108 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5109 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5110 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5111 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5113 static const int kArgumentsBits = 16;
5114 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5116 // This constant should be encodable in an ARM instruction.
5117 static const int kFlagsNotUsedInLookup =
5118 TypeField::kMask | CacheHolderField::kMask;
5121 friend class RelocIterator;
5122 friend class Deoptimizer; // For FindCodeAgeSequence.
5124 void ClearInlineCaches(Kind* kind);
5127 byte* FindCodeAgeSequence();
5128 static void GetCodeAgeAndParity(Code* code, Age* age,
5129 MarkingParity* parity);
5130 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5131 MarkingParity* parity);
5132 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5134 // Code aging -- platform-specific
5135 static void PatchPlatformCodeAge(Isolate* isolate,
5136 byte* sequence, Age age,
5137 MarkingParity parity);
5139 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5143 // This class describes the layout of dependent codes array of a map. The
5144 // array is partitioned into several groups of dependent codes. Each group
5145 // contains codes with the same dependency on the map. The array has the
5146 // following layout for n dependency groups:
5148 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5149 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5150 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5152 // The first n elements are Smis, each of them specifies the number of codes
5153 // in the corresponding group. The subsequent elements contain grouped code
5154 // objects in weak cells. The suffix of the array can be filled with the
5155 // undefined value if the number of codes is less than the length of the
5156 // array. The order of the code objects within a group is not preserved.
5158 // All code indexes used in the class are counted starting from the first
5159 // code object of the first group. In other words, code index 0 corresponds
5160 // to array index n = kCodesStartIndex.
5162 class DependentCode: public FixedArray {
5164 enum DependencyGroup {
5165 // Group of code that weakly embed this map and depend on being
5166 // deoptimized when the map is garbage collected.
5168 // Group of code that embed a transition to this map, and depend on being
5169 // deoptimized when the transition is replaced by a new version.
5171 // Group of code that omit run-time prototype checks for prototypes
5172 // described by this map. The group is deoptimized whenever an object
5173 // described by this map changes shape (and transitions to a new map),
5174 // possibly invalidating the assumptions embedded in the code.
5175 kPrototypeCheckGroup,
5176 // Group of code that depends on global property values in property cells
5177 // not being changed.
5178 kPropertyCellChangedGroup,
5179 // Group of code that omit run-time type checks for the field(s) introduced
5182 // Group of code that omit run-time type checks for initial maps of
5184 kInitialMapChangedGroup,
5185 // Group of code that depends on tenuring information in AllocationSites
5186 // not being changed.
5187 kAllocationSiteTenuringChangedGroup,
5188 // Group of code that depends on element transition information in
5189 // AllocationSites not being changed.
5190 kAllocationSiteTransitionChangedGroup
5193 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5195 // Array for holding the index of the first code object of each group.
5196 // The last element stores the total number of code objects.
5197 class GroupStartIndexes {
5199 explicit GroupStartIndexes(DependentCode* entries);
5200 void Recompute(DependentCode* entries);
5201 int at(int i) { return start_indexes_[i]; }
5202 int number_of_entries() { return start_indexes_[kGroupCount]; }
5204 int start_indexes_[kGroupCount + 1];
5207 bool Contains(DependencyGroup group, WeakCell* code_cell);
5209 static Handle<DependentCode> InsertCompilationDependencies(
5210 Handle<DependentCode> entries, DependencyGroup group,
5211 Handle<Foreign> info);
5213 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5214 DependencyGroup group,
5215 Handle<WeakCell> code_cell);
5217 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5218 WeakCell* code_cell);
5220 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5223 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5224 DependentCode::DependencyGroup group);
5226 bool MarkCodeForDeoptimization(Isolate* isolate,
5227 DependentCode::DependencyGroup group);
5229 // The following low-level accessors should only be used by this class
5230 // and the mark compact collector.
5231 inline int number_of_entries(DependencyGroup group);
5232 inline void set_number_of_entries(DependencyGroup group, int value);
5233 inline Object* object_at(int i);
5234 inline void set_object_at(int i, Object* object);
5235 inline void clear_at(int i);
5236 inline void copy(int from, int to);
5237 DECLARE_CAST(DependentCode)
5239 static const char* DependencyGroupName(DependencyGroup group);
5240 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5243 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5244 DependencyGroup group,
5245 Handle<Object> object);
5246 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5247 // Make a room at the end of the given group by moving out the first
5248 // code objects of the subsequent groups.
5249 inline void ExtendGroup(DependencyGroup group);
5250 // Compact by removing cleared weak cells and return true if there was
5251 // any cleared weak cell.
5253 static int Grow(int number_of_entries) {
5254 if (number_of_entries < 5) return number_of_entries + 1;
5255 return number_of_entries * 5 / 4;
5257 static const int kCodesStartIndex = kGroupCount;
5261 class PrototypeInfo;
5264 // All heap objects have a Map that describes their structure.
5265 // A Map contains information about:
5266 // - Size information about the object
5267 // - How to iterate over an object (for garbage collection)
5268 class Map: public HeapObject {
5271 // Size in bytes or kVariableSizeSentinel if instances do not have
5273 inline int instance_size();
5274 inline void set_instance_size(int value);
5276 // Only to clear an unused byte, remove once byte is used.
5277 inline void clear_unused();
5279 // Count of properties allocated in the object.
5280 inline int inobject_properties();
5281 inline void set_inobject_properties(int value);
5284 inline InstanceType instance_type();
5285 inline void set_instance_type(InstanceType value);
5287 // Tells how many unused property fields are available in the
5288 // instance (only used for JSObject in fast mode).
5289 inline int unused_property_fields();
5290 inline void set_unused_property_fields(int value);
5293 inline byte bit_field() const;
5294 inline void set_bit_field(byte value);
5297 inline byte bit_field2() const;
5298 inline void set_bit_field2(byte value);
5301 inline uint32_t bit_field3() const;
5302 inline void set_bit_field3(uint32_t bits);
5304 class EnumLengthBits: public BitField<int,
5305 0, kDescriptorIndexBitCount> {}; // NOLINT
5306 class NumberOfOwnDescriptorsBits: public BitField<int,
5307 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5308 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5309 class DictionaryMap : public BitField<bool, 20, 1> {};
5310 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5311 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5312 class Deprecated : public BitField<bool, 23, 1> {};
5313 class IsUnstable : public BitField<bool, 24, 1> {};
5314 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5315 class IsStrong : public BitField<bool, 26, 1> {};
5318 // Keep this bit field at the very end for better code in
5319 // Builtins::kJSConstructStubGeneric stub.
5320 // This counter is used for in-object slack tracking and for map aging.
5321 // The in-object slack tracking is considered enabled when the counter is
5322 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5323 class Counter : public BitField<int, 28, 4> {};
5324 static const int kSlackTrackingCounterStart = 14;
5325 static const int kSlackTrackingCounterEnd = 8;
5326 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5327 static const int kRetainingCounterEnd = 0;
5329 // Tells whether the object in the prototype property will be used
5330 // for instances created from this function. If the prototype
5331 // property is set to a value that is not a JSObject, the prototype
5332 // property will not be used to create instances of the function.
5333 // See ECMA-262, 13.2.2.
5334 inline void set_non_instance_prototype(bool value);
5335 inline bool has_non_instance_prototype();
5337 // Tells whether function has special prototype property. If not, prototype
5338 // property will not be created when accessed (will return undefined),
5339 // and construction from this function will not be allowed.
5340 inline void set_function_with_prototype(bool value);
5341 inline bool function_with_prototype();
5343 // Tells whether the instance with this map should be ignored by the
5344 // Object.getPrototypeOf() function and the __proto__ accessor.
5345 inline void set_is_hidden_prototype() {
5346 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5349 inline bool is_hidden_prototype() {
5350 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5353 // Records and queries whether the instance has a named interceptor.
5354 inline void set_has_named_interceptor() {
5355 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5358 inline bool has_named_interceptor() {
5359 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5362 // Records and queries whether the instance has an indexed interceptor.
5363 inline void set_has_indexed_interceptor() {
5364 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5367 inline bool has_indexed_interceptor() {
5368 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5371 // Tells whether the instance is undetectable.
5372 // An undetectable object is a special class of JSObject: 'typeof' operator
5373 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5374 // a normal JS object. It is useful for implementing undetectable
5375 // document.all in Firefox & Safari.
5376 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5377 inline void set_is_undetectable() {
5378 set_bit_field(bit_field() | (1 << kIsUndetectable));
5381 inline bool is_undetectable() {
5382 return ((1 << kIsUndetectable) & bit_field()) != 0;
5385 // Tells whether the instance has a call-as-function handler.
5386 inline void set_is_observed() {
5387 set_bit_field(bit_field() | (1 << kIsObserved));
5390 inline bool is_observed() {
5391 return ((1 << kIsObserved) & bit_field()) != 0;
5394 inline void set_is_strong();
5395 inline bool is_strong();
5396 inline void set_is_extensible(bool value);
5397 inline bool is_extensible();
5398 inline void set_is_prototype_map(bool value);
5399 inline bool is_prototype_map() const;
5401 inline void set_elements_kind(ElementsKind elements_kind) {
5402 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5403 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5404 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5405 DCHECK(this->elements_kind() == elements_kind);
5408 inline ElementsKind elements_kind() {
5409 return Map::ElementsKindBits::decode(bit_field2());
5412 // Tells whether the instance has fast elements that are only Smis.
5413 inline bool has_fast_smi_elements() {
5414 return IsFastSmiElementsKind(elements_kind());
5417 // Tells whether the instance has fast elements.
5418 inline bool has_fast_object_elements() {
5419 return IsFastObjectElementsKind(elements_kind());
5422 inline bool has_fast_smi_or_object_elements() {
5423 return IsFastSmiOrObjectElementsKind(elements_kind());
5426 inline bool has_fast_double_elements() {
5427 return IsFastDoubleElementsKind(elements_kind());
5430 inline bool has_fast_elements() {
5431 return IsFastElementsKind(elements_kind());
5434 inline bool has_sloppy_arguments_elements() {
5435 return IsSloppyArgumentsElements(elements_kind());
5438 inline bool has_fixed_typed_array_elements() {
5439 return IsFixedTypedArrayElementsKind(elements_kind());
5442 inline bool has_dictionary_elements() {
5443 return IsDictionaryElementsKind(elements_kind());
5446 static bool IsValidElementsTransition(ElementsKind from_kind,
5447 ElementsKind to_kind);
5449 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5450 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5451 bool DictionaryElementsInPrototypeChainOnly();
5453 inline Map* ElementsTransitionMap();
5455 inline FixedArrayBase* GetInitialElements();
5457 // [raw_transitions]: Provides access to the transitions storage field.
5458 // Don't call set_raw_transitions() directly to overwrite transitions, use
5459 // the TransitionArray::ReplaceTransitions() wrapper instead!
5460 DECL_ACCESSORS(raw_transitions, Object)
5461 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5462 // (which prototype maps don't have).
5463 DECL_ACCESSORS(prototype_info, Object)
5464 // PrototypeInfo is created lazily using this helper (which installs it on
5465 // the given prototype's map).
5466 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5467 Handle<JSObject> prototype, Isolate* isolate);
5469 // [prototype chain validity cell]: Associated with a prototype object,
5470 // stored in that object's map's PrototypeInfo, indicates that prototype
5471 // chains through this object are currently valid. The cell will be
5472 // invalidated and replaced when the prototype chain changes.
5473 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5475 static const int kPrototypeChainValid = 0;
5476 static const int kPrototypeChainInvalid = 1;
5479 Map* FindFieldOwner(int descriptor);
5481 inline int GetInObjectPropertyOffset(int index);
5483 int NumberOfFields();
5485 // TODO(ishell): candidate with JSObject::MigrateToMap().
5486 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5487 int target_inobject, int target_unused,
5488 int* old_number_of_fields);
5489 // TODO(ishell): moveit!
5490 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5491 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5492 Handle<HeapType> type1,
5493 Handle<HeapType> type2,
5495 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5496 Representation new_representation,
5497 Handle<HeapType> new_field_type);
5498 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5499 PropertyKind new_kind,
5500 PropertyAttributes new_attributes,
5501 Representation new_representation,
5502 Handle<HeapType> new_field_type,
5503 StoreMode store_mode);
5504 static Handle<Map> CopyGeneralizeAllRepresentations(
5505 Handle<Map> map, int modify_index, StoreMode store_mode,
5506 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5508 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5509 int descriptor_number,
5510 Handle<Object> value);
5512 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5513 const char* reason);
5515 // Returns the constructor name (the name (possibly, inferred name) of the
5516 // function that was used to instantiate the object).
5517 String* constructor_name();
5519 // Tells whether the map is used for JSObjects in dictionary mode (ie
5520 // normalized objects, ie objects for which HasFastProperties returns false).
5521 // A map can never be used for both dictionary mode and fast mode JSObjects.
5522 // False by default and for HeapObjects that are not JSObjects.
5523 inline void set_dictionary_map(bool value);
5524 inline bool is_dictionary_map();
5526 // Tells whether the instance needs security checks when accessing its
5528 inline void set_is_access_check_needed(bool access_check_needed);
5529 inline bool is_access_check_needed();
5531 // Returns true if map has a non-empty stub code cache.
5532 inline bool has_code_cache();
5534 // [prototype]: implicit prototype object.
5535 DECL_ACCESSORS(prototype, Object)
5536 // TODO(jkummerow): make set_prototype private.
5537 static void SetPrototype(
5538 Handle<Map> map, Handle<Object> prototype,
5539 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5541 // [constructor]: points back to the function responsible for this map.
5542 // The field overlaps with the back pointer. All maps in a transition tree
5543 // have the same constructor, so maps with back pointers can walk the
5544 // back pointer chain until they find the map holding their constructor.
5545 DECL_ACCESSORS(constructor_or_backpointer, Object)
5546 inline Object* GetConstructor() const;
5547 inline void SetConstructor(Object* constructor,
5548 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5549 // [back pointer]: points back to the parent map from which a transition
5550 // leads to this map. The field overlaps with the constructor (see above).
5551 inline Object* GetBackPointer();
5552 inline void SetBackPointer(Object* value,
5553 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5555 // [instance descriptors]: describes the object.
5556 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5558 // [layout descriptor]: describes the object layout.
5559 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5560 // |layout descriptor| accessor which can be used from GC.
5561 inline LayoutDescriptor* layout_descriptor_gc_safe();
5562 inline bool HasFastPointerLayout() const;
5564 // |layout descriptor| accessor that is safe to call even when
5565 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5566 // |layout_descriptor| field at all).
5567 inline LayoutDescriptor* GetLayoutDescriptor();
5569 inline void UpdateDescriptors(DescriptorArray* descriptors,
5570 LayoutDescriptor* layout_descriptor);
5571 inline void InitializeDescriptors(DescriptorArray* descriptors,
5572 LayoutDescriptor* layout_descriptor);
5574 // [stub cache]: contains stubs compiled for this map.
5575 DECL_ACCESSORS(code_cache, Object)
5577 // [dependent code]: list of optimized codes that weakly embed this map.
5578 DECL_ACCESSORS(dependent_code, DependentCode)
5580 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5581 DECL_ACCESSORS(weak_cell_cache, Object)
5583 inline PropertyDetails GetLastDescriptorDetails();
5586 int number_of_own_descriptors = NumberOfOwnDescriptors();
5587 DCHECK(number_of_own_descriptors > 0);
5588 return number_of_own_descriptors - 1;
5591 int NumberOfOwnDescriptors() {
5592 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5595 void SetNumberOfOwnDescriptors(int number) {
5596 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5597 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5600 inline Cell* RetrieveDescriptorsPointer();
5603 return EnumLengthBits::decode(bit_field3());
5606 void SetEnumLength(int length) {
5607 if (length != kInvalidEnumCacheSentinel) {
5608 DCHECK(length >= 0);
5609 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5610 DCHECK(length <= NumberOfOwnDescriptors());
5612 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5615 inline bool owns_descriptors();
5616 inline void set_owns_descriptors(bool owns_descriptors);
5617 inline bool has_instance_call_handler();
5618 inline void set_has_instance_call_handler();
5619 inline void mark_unstable();
5620 inline bool is_stable();
5621 inline void set_migration_target(bool value);
5622 inline bool is_migration_target();
5623 inline void set_counter(int value);
5624 inline int counter();
5625 inline void deprecate();
5626 inline bool is_deprecated();
5627 inline bool CanBeDeprecated();
5628 // Returns a non-deprecated version of the input. If the input was not
5629 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5630 // is found by re-transitioning from the root of the transition tree using the
5631 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5633 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5635 // Returns a non-deprecated version of the input. This method may deprecate
5636 // existing maps along the way if encodings conflict. Not for use while
5637 // gathering type feedback. Use TryUpdate in those cases instead.
5638 static Handle<Map> Update(Handle<Map> map);
5640 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5641 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5642 Descriptor* descriptor,
5643 TransitionFlag flag);
5645 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5648 Handle<HeapType> type,
5649 PropertyAttributes attributes,
5650 Representation representation,
5651 TransitionFlag flag);
5653 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5656 Handle<Object> constant,
5657 PropertyAttributes attributes,
5658 TransitionFlag flag);
5660 // Returns a new map with all transitions dropped from the given map and
5661 // the ElementsKind set.
5662 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5663 ElementsKind to_kind);
5665 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5667 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5669 TransitionFlag flag);
5671 static Handle<Map> CopyForObserved(Handle<Map> map);
5673 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5674 PropertyAttributes attrs_to_add,
5675 Handle<Symbol> transition_marker,
5676 const char* reason);
5678 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5681 // Maximal number of fast properties. Used to restrict the number of map
5682 // transitions to avoid an explosion in the number of maps for objects used as
5684 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5685 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5687 Handle<Object> value,
5688 PropertyAttributes attributes,
5689 StoreFromKeyed store_mode);
5690 static Handle<Map> TransitionToAccessorProperty(
5691 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5692 Handle<Object> accessor, PropertyAttributes attributes);
5693 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5696 PropertyAttributes attributes);
5698 inline void AppendDescriptor(Descriptor* desc);
5700 // Returns a copy of the map, prepared for inserting into the transition
5701 // tree (if the |map| owns descriptors then the new one will share
5702 // descriptors with |map|).
5703 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5705 // Returns a copy of the map, with all transitions dropped from the
5706 // instance descriptors.
5707 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5708 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5710 // Returns the next free property index (only valid for FAST MODE).
5711 int NextFreePropertyIndex();
5713 // Returns the number of properties described in instance_descriptors
5714 // filtering out properties with the specified attributes.
5715 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5716 PropertyAttributes filter = NONE);
5720 // Code cache operations.
5722 // Clears the code cache.
5723 inline void ClearCodeCache(Heap* heap);
5725 // Update code cache.
5726 static void UpdateCodeCache(Handle<Map> map,
5730 // Extend the descriptor array of the map with the list of descriptors.
5731 // In case of duplicates, the latest descriptor is used.
5732 static void AppendCallbackDescriptors(Handle<Map> map,
5733 Handle<Object> descriptors);
5735 static inline int SlackForArraySize(int old_size, int size_limit);
5737 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5739 // Returns the found code or undefined if absent.
5740 Object* FindInCodeCache(Name* name, Code::Flags flags);
5742 // Returns the non-negative index of the code object if it is in the
5743 // cache and -1 otherwise.
5744 int IndexInCodeCache(Object* name, Code* code);
5746 // Removes a code object from the code cache at the given index.
5747 void RemoveFromCodeCache(Name* name, Code* code, int index);
5749 // Computes a hash value for this map, to be used in HashTables and such.
5752 // Returns the map that this map transitions to if its elements_kind
5753 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5754 // |safe_to_add_transitions| is set to false if adding transitions is not
5756 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5758 // Returns the transitioned map for this map with the most generic
5759 // elements_kind that's found in |candidates|, or null handle if no match is
5761 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5762 MapHandleList* candidates);
5764 bool CanTransition() {
5765 // Only JSObject and subtypes have map transitions and back pointers.
5766 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
5767 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5770 bool IsJSObjectMap() {
5771 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5773 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
5774 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
5775 bool IsJSProxyMap() {
5776 InstanceType type = instance_type();
5777 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
5779 bool IsJSGlobalProxyMap() {
5780 return instance_type() == JS_GLOBAL_PROXY_TYPE;
5782 bool IsJSGlobalObjectMap() {
5783 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
5785 bool IsGlobalObjectMap() {
5786 const InstanceType type = instance_type();
5787 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
5790 inline bool CanOmitMapChecks();
5792 static void AddDependentCode(Handle<Map> map,
5793 DependentCode::DependencyGroup group,
5796 bool IsMapInArrayPrototypeChain();
5798 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5800 // Dispatched behavior.
5801 DECLARE_PRINTER(Map)
5802 DECLARE_VERIFIER(Map)
5805 void DictionaryMapVerify();
5806 void VerifyOmittedMapChecks();
5809 inline int visitor_id();
5810 inline void set_visitor_id(int visitor_id);
5812 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5813 Handle<Object> prototype,
5814 PrototypeOptimizationMode mode);
5816 static const int kMaxPreAllocatedPropertyFields = 255;
5818 // Layout description.
5819 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5820 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5821 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5822 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5823 static const int kConstructorOrBackPointerOffset =
5824 kPrototypeOffset + kPointerSize;
5825 // When there is only one transition, it is stored directly in this field;
5826 // otherwise a transition array is used.
5827 // For prototype maps, this slot is used to store this map's PrototypeInfo
5829 static const int kTransitionsOrPrototypeInfoOffset =
5830 kConstructorOrBackPointerOffset + kPointerSize;
5831 static const int kDescriptorsOffset =
5832 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5833 #if V8_DOUBLE_FIELDS_UNBOXING
5834 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5835 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5837 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5838 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5840 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5841 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5842 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5844 // Layout of pointer fields. Heap iteration code relies on them
5845 // being continuously allocated.
5846 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5847 static const int kPointerFieldsEndOffset = kSize;
5849 // Byte offsets within kInstanceSizesOffset.
5850 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5851 static const int kInObjectPropertiesByte = 1;
5852 static const int kInObjectPropertiesOffset =
5853 kInstanceSizesOffset + kInObjectPropertiesByte;
5854 // Note there is one byte available for use here.
5855 static const int kUnusedByte = 2;
5856 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5857 static const int kVisitorIdByte = 3;
5858 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5860 // Byte offsets within kInstanceAttributesOffset attributes.
5861 #if V8_TARGET_LITTLE_ENDIAN
5862 // Order instance type and bit field together such that they can be loaded
5863 // together as a 16-bit word with instance type in the lower 8 bits regardless
5864 // of endianess. Also provide endian-independent offset to that 16-bit word.
5865 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5866 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5868 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5869 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5871 static const int kInstanceTypeAndBitFieldOffset =
5872 kInstanceAttributesOffset + 0;
5873 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5874 static const int kUnusedPropertyFieldsByte = 3;
5875 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5877 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5878 Internals::kMapInstanceTypeAndBitFieldOffset);
5880 // Bit positions for bit field.
5881 static const int kHasNonInstancePrototype = 0;
5882 static const int kIsHiddenPrototype = 1;
5883 static const int kHasNamedInterceptor = 2;
5884 static const int kHasIndexedInterceptor = 3;
5885 static const int kIsUndetectable = 4;
5886 static const int kIsObserved = 5;
5887 static const int kIsAccessCheckNeeded = 6;
5888 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5890 // Bit positions for bit field 2
5891 static const int kIsExtensible = 0;
5892 static const int kStringWrapperSafeForDefaultValueOf = 1;
5893 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5894 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5896 // Derived values from bit field 2
5897 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5898 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5899 static const int8_t kMaximumBitField2FastSmiElementValue =
5900 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5901 Map::ElementsKindBits::kShift) - 1;
5902 static const int8_t kMaximumBitField2FastHoleyElementValue =
5903 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5904 Map::ElementsKindBits::kShift) - 1;
5905 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5906 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5907 Map::ElementsKindBits::kShift) - 1;
5909 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5910 kPointerFieldsEndOffset,
5911 kSize> BodyDescriptor;
5913 // Compares this map to another to see if they describe equivalent objects.
5914 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5915 // it had exactly zero inobject properties.
5916 // The "shared" flags of both this map and |other| are ignored.
5917 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5919 // Returns true if given field is unboxed double.
5920 inline bool IsUnboxedDoubleField(FieldIndex index);
5923 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5924 static void TraceAllTransitions(Map* map);
5927 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5928 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5929 Handle<LayoutDescriptor> layout_descriptor);
5932 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5933 Handle<Name> name, SimpleTransitionFlag flag);
5935 bool EquivalentToForTransition(Map* other);
5936 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5937 static Handle<Map> ShareDescriptor(Handle<Map> map,
5938 Handle<DescriptorArray> descriptors,
5939 Descriptor* descriptor);
5940 static Handle<Map> CopyInstallDescriptors(
5941 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5942 Handle<LayoutDescriptor> layout_descriptor);
5943 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5944 Descriptor* descriptor,
5945 TransitionFlag flag);
5946 static Handle<Map> CopyReplaceDescriptors(
5947 Handle<Map> map, Handle<DescriptorArray> descriptors,
5948 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5949 MaybeHandle<Name> maybe_name, const char* reason,
5950 SimpleTransitionFlag simple_flag);
5952 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5953 Handle<DescriptorArray> descriptors,
5954 Descriptor* descriptor,
5956 TransitionFlag flag);
5957 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5958 Handle<Map> map, int descriptor, PropertyKind kind,
5959 PropertyAttributes attributes, const char** reason);
5961 static Handle<Map> CopyNormalized(Handle<Map> map,
5962 PropertyNormalizationMode mode);
5964 // Fires when the layout of an object with a leaf map changes.
5965 // This includes adding transitions to the leaf map or changing
5966 // the descriptor array.
5967 inline void NotifyLeafMapLayoutChange();
5969 void DeprecateTransitionTree();
5970 bool DeprecateTarget(PropertyKind kind, Name* key,
5971 PropertyAttributes attributes,
5972 DescriptorArray* new_descriptors,
5973 LayoutDescriptor* new_layout_descriptor);
5975 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5977 // Update field type of the given descriptor to new representation and new
5978 // type. The type must be prepared for storing in descriptor array:
5979 // it must be either a simple type or a map wrapped in a weak cell.
5980 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5981 Representation new_representation,
5982 Handle<Object> new_wrapped_type);
5984 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5985 PropertyAttributes attributes);
5986 void PrintGeneralization(FILE* file,
5991 bool constant_to_field,
5992 Representation old_representation,
5993 Representation new_representation,
5994 HeapType* old_field_type,
5995 HeapType* new_field_type);
5997 static const int kFastPropertiesSoftLimit = 12;
5998 static const int kMaxFastProperties = 128;
6000 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6004 // An abstract superclass, a marker class really, for simple structure classes.
6005 // It doesn't carry much functionality but allows struct classes to be
6006 // identified in the type system.
6007 class Struct: public HeapObject {
6009 inline void InitializeBody(int object_size);
6010 DECLARE_CAST(Struct)
6014 // A simple one-element struct, useful where smis need to be boxed.
6015 class Box : public Struct {
6017 // [value]: the boxed contents.
6018 DECL_ACCESSORS(value, Object)
6022 // Dispatched behavior.
6023 DECLARE_PRINTER(Box)
6024 DECLARE_VERIFIER(Box)
6026 static const int kValueOffset = HeapObject::kHeaderSize;
6027 static const int kSize = kValueOffset + kPointerSize;
6030 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6034 // Container for metadata stored on each prototype map.
6035 class PrototypeInfo : public Struct {
6037 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6038 // or Smi(0) if uninitialized.
6039 DECL_ACCESSORS(prototype_users, Object)
6040 // [validity_cell]: Cell containing the validity bit for prototype chains
6041 // going through this object, or Smi(0) if uninitialized.
6042 DECL_ACCESSORS(validity_cell, Object)
6043 // [constructor_name]: User-friendly name of the original constructor.
6044 DECL_ACCESSORS(constructor_name, Object)
6046 DECLARE_CAST(PrototypeInfo)
6048 // Dispatched behavior.
6049 DECLARE_PRINTER(PrototypeInfo)
6050 DECLARE_VERIFIER(PrototypeInfo)
6052 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6053 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6054 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6055 static const int kSize = kConstructorNameOffset + kPointerSize;
6058 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6062 // Script describes a script which has been added to the VM.
6063 class Script: public Struct {
6072 // Script compilation types.
6073 enum CompilationType {
6074 COMPILATION_TYPE_HOST = 0,
6075 COMPILATION_TYPE_EVAL = 1
6078 // Script compilation state.
6079 enum CompilationState {
6080 COMPILATION_STATE_INITIAL = 0,
6081 COMPILATION_STATE_COMPILED = 1
6084 // [source]: the script source.
6085 DECL_ACCESSORS(source, Object)
6087 // [name]: the script name.
6088 DECL_ACCESSORS(name, Object)
6090 // [id]: the script id.
6091 DECL_ACCESSORS(id, Smi)
6093 // [line_offset]: script line offset in resource from where it was extracted.
6094 DECL_ACCESSORS(line_offset, Smi)
6096 // [column_offset]: script column offset in resource from where it was
6098 DECL_ACCESSORS(column_offset, Smi)
6100 // [context_data]: context data for the context this script was compiled in.
6101 DECL_ACCESSORS(context_data, Object)
6103 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6104 DECL_ACCESSORS(wrapper, HeapObject)
6106 // [type]: the script type.
6107 DECL_ACCESSORS(type, Smi)
6109 // [line_ends]: FixedArray of line ends positions.
6110 DECL_ACCESSORS(line_ends, Object)
6112 // [eval_from_shared]: for eval scripts the shared funcion info for the
6113 // function from which eval was called.
6114 DECL_ACCESSORS(eval_from_shared, Object)
6116 // [eval_from_instructions_offset]: the instruction offset in the code for the
6117 // function from which eval was called where eval was called.
6118 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6120 // [shared_function_infos]: weak fixed array containing all shared
6121 // function infos created from this script.
6122 DECL_ACCESSORS(shared_function_infos, Object)
6124 // [flags]: Holds an exciting bitfield.
6125 DECL_ACCESSORS(flags, Smi)
6127 // [source_url]: sourceURL from magic comment
6128 DECL_ACCESSORS(source_url, Object)
6130 // [source_url]: sourceMappingURL magic comment
6131 DECL_ACCESSORS(source_mapping_url, Object)
6133 // [compilation_type]: how the the script was compiled. Encoded in the
6135 inline CompilationType compilation_type();
6136 inline void set_compilation_type(CompilationType type);
6138 // [compilation_state]: determines whether the script has already been
6139 // compiled. Encoded in the 'flags' field.
6140 inline CompilationState compilation_state();
6141 inline void set_compilation_state(CompilationState state);
6143 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6144 // and used by the embedder to make decisions about the script. V8 just passes
6145 // this through. Encoded in the 'flags' field.
6146 inline v8::ScriptOriginOptions origin_options();
6147 inline void set_origin_options(ScriptOriginOptions origin_options);
6149 DECLARE_CAST(Script)
6151 // If script source is an external string, check that the underlying
6152 // resource is accessible. Otherwise, always return true.
6153 inline bool HasValidSource();
6155 // Convert code position into column number.
6156 static int GetColumnNumber(Handle<Script> script, int code_pos);
6158 // Convert code position into (zero-based) line number.
6159 // The non-handlified version does not allocate, but may be much slower.
6160 static int GetLineNumber(Handle<Script> script, int code_pos);
6161 int GetLineNumber(int code_pos);
6163 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6165 // Init line_ends array with code positions of line ends inside script source.
6166 static void InitLineEnds(Handle<Script> script);
6168 // Get the JS object wrapping the given script; create it if none exists.
6169 static Handle<JSObject> GetWrapper(Handle<Script> script);
6171 // Look through the list of existing shared function infos to find one
6172 // that matches the function literal. Return empty handle if not found.
6173 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6175 // Dispatched behavior.
6176 DECLARE_PRINTER(Script)
6177 DECLARE_VERIFIER(Script)
6179 static const int kSourceOffset = HeapObject::kHeaderSize;
6180 static const int kNameOffset = kSourceOffset + kPointerSize;
6181 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6182 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6183 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6184 static const int kWrapperOffset = kContextOffset + kPointerSize;
6185 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6186 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6187 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6188 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6189 static const int kEvalFrominstructionsOffsetOffset =
6190 kEvalFromSharedOffset + kPointerSize;
6191 static const int kSharedFunctionInfosOffset =
6192 kEvalFrominstructionsOffsetOffset + kPointerSize;
6193 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6194 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6195 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6196 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6199 int GetLineNumberWithArray(int code_pos);
6201 // Bit positions in the flags field.
6202 static const int kCompilationTypeBit = 0;
6203 static const int kCompilationStateBit = 1;
6204 static const int kOriginOptionsShift = 2;
6205 static const int kOriginOptionsSize = 3;
6206 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6207 << kOriginOptionsShift;
6209 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6213 // List of builtin functions we want to identify to improve code
6216 // Each entry has a name of a global object property holding an object
6217 // optionally followed by ".prototype", a name of a builtin function
6218 // on the object (the one the id is set for), and a label.
6220 // Installation of ids for the selected builtin functions is handled
6221 // by the bootstrapper.
6222 #define FUNCTIONS_WITH_ID_LIST(V) \
6223 V(Array.prototype, indexOf, ArrayIndexOf) \
6224 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6225 V(Array.prototype, push, ArrayPush) \
6226 V(Array.prototype, pop, ArrayPop) \
6227 V(Array.prototype, shift, ArrayShift) \
6228 V(Function.prototype, apply, FunctionApply) \
6229 V(Function.prototype, call, FunctionCall) \
6230 V(String.prototype, charCodeAt, StringCharCodeAt) \
6231 V(String.prototype, charAt, StringCharAt) \
6232 V(String, fromCharCode, StringFromCharCode) \
6233 V(Math, random, MathRandom) \
6234 V(Math, floor, MathFloor) \
6235 V(Math, round, MathRound) \
6236 V(Math, ceil, MathCeil) \
6237 V(Math, abs, MathAbs) \
6238 V(Math, log, MathLog) \
6239 V(Math, exp, MathExp) \
6240 V(Math, sqrt, MathSqrt) \
6241 V(Math, pow, MathPow) \
6242 V(Math, max, MathMax) \
6243 V(Math, min, MathMin) \
6244 V(Math, cos, MathCos) \
6245 V(Math, sin, MathSin) \
6246 V(Math, tan, MathTan) \
6247 V(Math, acos, MathAcos) \
6248 V(Math, asin, MathAsin) \
6249 V(Math, atan, MathAtan) \
6250 V(Math, atan2, MathAtan2) \
6251 V(Math, imul, MathImul) \
6252 V(Math, clz32, MathClz32) \
6253 V(Math, fround, MathFround)
6255 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6256 V(Atomics, load, AtomicsLoad) \
6257 V(Atomics, store, AtomicsStore)
6259 enum BuiltinFunctionId {
6261 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6263 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6264 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6265 #undef DECLARE_FUNCTION_ID
6266 // Fake id for a special case of Math.pow. Note, it continues the
6267 // list of math functions.
6272 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6273 // that both {code} and {literals} can be NULL to pass search result status.
6274 struct CodeAndLiterals {
6275 Code* code; // Cached optimized code.
6276 FixedArray* literals; // Cached literals array.
6280 // SharedFunctionInfo describes the JSFunction information that can be
6281 // shared by multiple instances of the function.
6282 class SharedFunctionInfo: public HeapObject {
6284 // [name]: Function name.
6285 DECL_ACCESSORS(name, Object)
6287 // [code]: Function code.
6288 DECL_ACCESSORS(code, Code)
6289 inline void ReplaceCode(Code* code);
6291 // [optimized_code_map]: Map from native context to optimized code
6292 // and a shared literals array or Smi(0) if none.
6293 DECL_ACCESSORS(optimized_code_map, Object)
6295 // Returns entry from optimized code map for specified context and OSR entry.
6296 // Note that {code == nullptr} indicates no matching entry has been found,
6297 // whereas {literals == nullptr} indicates the code is context-independent.
6298 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6299 BailoutId osr_ast_id);
6301 // Clear optimized code map.
6302 void ClearOptimizedCodeMap();
6304 // Removed a specific optimized code object from the optimized code map.
6305 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6307 // Trims the optimized code map after entries have been removed.
6308 void TrimOptimizedCodeMap(int shrink_by);
6310 // Add a new entry to the optimized code map for context-independent code.
6311 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6314 // Add a new entry to the optimized code map for context-dependent code.
6315 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6316 Handle<Context> native_context,
6318 Handle<FixedArray> literals,
6319 BailoutId osr_ast_id);
6321 // Set up the link between shared function info and the script. The shared
6322 // function info is added to the list on the script.
6323 static void SetScript(Handle<SharedFunctionInfo> shared,
6324 Handle<Object> script_object);
6326 // Layout description of the optimized code map.
6327 static const int kNextMapIndex = 0;
6328 static const int kSharedCodeIndex = 1;
6329 static const int kEntriesStart = 2;
6330 static const int kContextOffset = 0;
6331 static const int kCachedCodeOffset = 1;
6332 static const int kLiteralsOffset = 2;
6333 static const int kOsrAstIdOffset = 3;
6334 static const int kEntryLength = 4;
6335 static const int kInitialLength = kEntriesStart + kEntryLength;
6337 // [scope_info]: Scope info.
6338 DECL_ACCESSORS(scope_info, ScopeInfo)
6340 // [construct stub]: Code stub for constructing instances of this function.
6341 DECL_ACCESSORS(construct_stub, Code)
6343 // Returns if this function has been compiled to native code yet.
6344 inline bool is_compiled();
6346 // [length]: The function length - usually the number of declared parameters.
6347 // Use up to 2^30 parameters.
6348 inline int length() const;
6349 inline void set_length(int value);
6351 // [internal formal parameter count]: The declared number of parameters.
6352 // For subclass constructors, also includes new.target.
6353 // The size of function's frame is internal_formal_parameter_count + 1.
6354 inline int internal_formal_parameter_count() const;
6355 inline void set_internal_formal_parameter_count(int value);
6357 // Set the formal parameter count so the function code will be
6358 // called without using argument adaptor frames.
6359 inline void DontAdaptArguments();
6361 // [expected_nof_properties]: Expected number of properties for the function.
6362 inline int expected_nof_properties() const;
6363 inline void set_expected_nof_properties(int value);
6365 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6366 // (increasingly) from crankshafted code where sufficient feedback isn't
6368 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6370 // Unconditionally clear the type feedback vector (including vector ICs).
6371 void ClearTypeFeedbackInfo();
6373 // Clear the type feedback vector with a more subtle policy at GC time.
6374 void ClearTypeFeedbackInfoAtGCTime();
6377 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6378 // even if the GC moves this SharedFunctionInfo.
6379 inline int unique_id() const;
6380 inline void set_unique_id(int value);
6383 // [instance class name]: class name for instances.
6384 DECL_ACCESSORS(instance_class_name, Object)
6386 // [function data]: This field holds some additional data for function.
6387 // Currently it has one of:
6388 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6389 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6390 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6391 // In the long run we don't want all functions to have this field but
6392 // we can fix that when we have a better model for storing hidden data
6394 DECL_ACCESSORS(function_data, Object)
6396 inline bool IsApiFunction();
6397 inline FunctionTemplateInfo* get_api_func_data();
6398 inline bool HasBuiltinFunctionId();
6399 inline BuiltinFunctionId builtin_function_id();
6400 inline bool HasBytecodeArray();
6401 inline BytecodeArray* bytecode_array();
6403 // [script info]: Script from which the function originates.
6404 DECL_ACCESSORS(script, Object)
6406 // [num_literals]: Number of literals used by this function.
6407 inline int num_literals() const;
6408 inline void set_num_literals(int value);
6410 // [start_position_and_type]: Field used to store both the source code
6411 // position, whether or not the function is a function expression,
6412 // and whether or not the function is a toplevel function. The two
6413 // least significants bit indicates whether the function is an
6414 // expression and the rest contains the source code position.
6415 inline int start_position_and_type() const;
6416 inline void set_start_position_and_type(int value);
6418 // The function is subject to debugging if a debug info is attached.
6419 inline bool HasDebugInfo();
6420 inline DebugInfo* GetDebugInfo();
6422 // A function has debug code if the compiled code has debug break slots.
6423 inline bool HasDebugCode();
6425 // [debug info]: Debug information.
6426 DECL_ACCESSORS(debug_info, Object)
6428 // [inferred name]: Name inferred from variable or property
6429 // assignment of this function. Used to facilitate debugging and
6430 // profiling of JavaScript code written in OO style, where almost
6431 // all functions are anonymous but are assigned to object
6433 DECL_ACCESSORS(inferred_name, String)
6435 // The function's name if it is non-empty, otherwise the inferred name.
6436 String* DebugName();
6438 // Position of the 'function' token in the script source.
6439 inline int function_token_position() const;
6440 inline void set_function_token_position(int function_token_position);
6442 // Position of this function in the script source.
6443 inline int start_position() const;
6444 inline void set_start_position(int start_position);
6446 // End position of this function in the script source.
6447 inline int end_position() const;
6448 inline void set_end_position(int end_position);
6450 // Is this function a function expression in the source code.
6451 DECL_BOOLEAN_ACCESSORS(is_expression)
6453 // Is this function a top-level function (scripts, evals).
6454 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6456 // Bit field containing various information collected by the compiler to
6457 // drive optimization.
6458 inline int compiler_hints() const;
6459 inline void set_compiler_hints(int value);
6461 inline int ast_node_count() const;
6462 inline void set_ast_node_count(int count);
6464 inline int profiler_ticks() const;
6465 inline void set_profiler_ticks(int ticks);
6467 // Inline cache age is used to infer whether the function survived a context
6468 // disposal or not. In the former case we reset the opt_count.
6469 inline int ic_age();
6470 inline void set_ic_age(int age);
6472 // Indicates if this function can be lazy compiled.
6473 // This is used to determine if we can safely flush code from a function
6474 // when doing GC if we expect that the function will no longer be used.
6475 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6477 // Indicates if this function can be lazy compiled without a context.
6478 // This is used to determine if we can force compilation without reaching
6479 // the function through program execution but through other means (e.g. heap
6480 // iteration by the debugger).
6481 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6483 // Indicates whether optimizations have been disabled for this
6484 // shared function info. If a function is repeatedly optimized or if
6485 // we cannot optimize the function we disable optimization to avoid
6486 // spending time attempting to optimize it again.
6487 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6489 // Indicates the language mode.
6490 inline LanguageMode language_mode();
6491 inline void set_language_mode(LanguageMode language_mode);
6493 // False if the function definitely does not allocate an arguments object.
6494 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6496 // Indicates that this function uses a super property (or an eval that may
6497 // use a super property).
6498 // This is needed to set up the [[HomeObject]] on the function instance.
6499 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6501 // True if the function has any duplicated parameter names.
6502 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6504 // Indicates whether the function is a native function.
6505 // These needs special treatment in .call and .apply since
6506 // null passed as the receiver should not be translated to the
6508 DECL_BOOLEAN_ACCESSORS(native)
6510 // Indicate that this function should always be inlined in optimized code.
6511 DECL_BOOLEAN_ACCESSORS(force_inline)
6513 // Indicates that the function was created by the Function function.
6514 // Though it's anonymous, toString should treat it as if it had the name
6515 // "anonymous". We don't set the name itself so that the system does not
6516 // see a binding for it.
6517 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6519 // Indicates whether the function is a bound function created using
6520 // the bind function.
6521 DECL_BOOLEAN_ACCESSORS(bound)
6523 // Indicates that the function is anonymous (the name field can be set
6524 // through the API, which does not change this flag).
6525 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6527 // Is this a function or top-level/eval code.
6528 DECL_BOOLEAN_ACCESSORS(is_function)
6530 // Indicates that code for this function cannot be compiled with Crankshaft.
6531 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6533 // Indicates that code for this function cannot be flushed.
6534 DECL_BOOLEAN_ACCESSORS(dont_flush)
6536 // Indicates that this function is a generator.
6537 DECL_BOOLEAN_ACCESSORS(is_generator)
6539 // Indicates that this function is an arrow function.
6540 DECL_BOOLEAN_ACCESSORS(is_arrow)
6542 // Indicates that this function is a concise method.
6543 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6545 // Indicates that this function is an accessor (getter or setter).
6546 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6548 // Indicates that this function is a default constructor.
6549 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6551 // Indicates that this function is an asm function.
6552 DECL_BOOLEAN_ACCESSORS(asm_function)
6554 // Indicates that the the shared function info is deserialized from cache.
6555 DECL_BOOLEAN_ACCESSORS(deserialized)
6557 // Indicates that the the shared function info has never been compiled before.
6558 DECL_BOOLEAN_ACCESSORS(never_compiled)
6560 inline FunctionKind kind();
6561 inline void set_kind(FunctionKind kind);
6563 // Indicates whether or not the code in the shared function support
6565 inline bool has_deoptimization_support();
6567 // Enable deoptimization support through recompiled code.
6568 void EnableDeoptimizationSupport(Code* recompiled);
6570 // Disable (further) attempted optimization of all functions sharing this
6571 // shared function info.
6572 void DisableOptimization(BailoutReason reason);
6574 inline BailoutReason disable_optimization_reason();
6576 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6577 // code, returns whether it asserted (i.e., always true if assertions are
6579 bool VerifyBailoutId(BailoutId id);
6581 // [source code]: Source code for the function.
6582 bool HasSourceCode() const;
6583 Handle<Object> GetSourceCode();
6585 // Number of times the function was optimized.
6586 inline int opt_count();
6587 inline void set_opt_count(int opt_count);
6589 // Number of times the function was deoptimized.
6590 inline void set_deopt_count(int value);
6591 inline int deopt_count();
6592 inline void increment_deopt_count();
6594 // Number of time we tried to re-enable optimization after it
6595 // was disabled due to high number of deoptimizations.
6596 inline void set_opt_reenable_tries(int value);
6597 inline int opt_reenable_tries();
6599 inline void TryReenableOptimization();
6601 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6602 inline void set_counters(int value);
6603 inline int counters() const;
6605 // Stores opt_count and bailout_reason as bit-fields.
6606 inline void set_opt_count_and_bailout_reason(int value);
6607 inline int opt_count_and_bailout_reason() const;
6609 void set_disable_optimization_reason(BailoutReason reason) {
6610 set_opt_count_and_bailout_reason(
6611 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6615 // Tells whether this function should be subject to debugging.
6616 inline bool IsSubjectToDebugging();
6618 // Check whether or not this function is inlineable.
6619 bool IsInlineable();
6621 // Source size of this function.
6624 // Calculate the instance size.
6625 int CalculateInstanceSize();
6627 // Calculate the number of in-object properties.
6628 int CalculateInObjectProperties();
6630 inline bool is_simple_parameter_list();
6632 // Initialize a SharedFunctionInfo from a parsed function literal.
6633 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6634 FunctionLiteral* lit);
6636 // Dispatched behavior.
6637 DECLARE_PRINTER(SharedFunctionInfo)
6638 DECLARE_VERIFIER(SharedFunctionInfo)
6640 void ResetForNewContext(int new_ic_age);
6642 DECLARE_CAST(SharedFunctionInfo)
6645 static const int kDontAdaptArgumentsSentinel = -1;
6647 // Layout description.
6649 static const int kNameOffset = HeapObject::kHeaderSize;
6650 static const int kCodeOffset = kNameOffset + kPointerSize;
6651 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6652 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6653 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6654 static const int kInstanceClassNameOffset =
6655 kConstructStubOffset + kPointerSize;
6656 static const int kFunctionDataOffset =
6657 kInstanceClassNameOffset + kPointerSize;
6658 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6659 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6660 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6661 static const int kFeedbackVectorOffset =
6662 kInferredNameOffset + kPointerSize;
6664 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6665 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6667 // Just to not break the postmortrem support with conditional offsets
6668 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6669 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6672 #if V8_HOST_ARCH_32_BIT
6674 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6675 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6676 static const int kExpectedNofPropertiesOffset =
6677 kFormalParameterCountOffset + kPointerSize;
6678 static const int kNumLiteralsOffset =
6679 kExpectedNofPropertiesOffset + kPointerSize;
6680 static const int kStartPositionAndTypeOffset =
6681 kNumLiteralsOffset + kPointerSize;
6682 static const int kEndPositionOffset =
6683 kStartPositionAndTypeOffset + kPointerSize;
6684 static const int kFunctionTokenPositionOffset =
6685 kEndPositionOffset + kPointerSize;
6686 static const int kCompilerHintsOffset =
6687 kFunctionTokenPositionOffset + kPointerSize;
6688 static const int kOptCountAndBailoutReasonOffset =
6689 kCompilerHintsOffset + kPointerSize;
6690 static const int kCountersOffset =
6691 kOptCountAndBailoutReasonOffset + kPointerSize;
6692 static const int kAstNodeCountOffset =
6693 kCountersOffset + kPointerSize;
6694 static const int kProfilerTicksOffset =
6695 kAstNodeCountOffset + kPointerSize;
6698 static const int kSize = kProfilerTicksOffset + kPointerSize;
6700 // The only reason to use smi fields instead of int fields
6701 // is to allow iteration without maps decoding during
6702 // garbage collections.
6703 // To avoid wasting space on 64-bit architectures we use
6704 // the following trick: we group integer fields into pairs
6705 // The least significant integer in each pair is shifted left by 1.
6706 // By doing this we guarantee that LSB of each kPointerSize aligned
6707 // word is not set and thus this word cannot be treated as pointer
6708 // to HeapObject during old space traversal.
6709 #if V8_TARGET_LITTLE_ENDIAN
6710 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6711 static const int kFormalParameterCountOffset =
6712 kLengthOffset + kIntSize;
6714 static const int kExpectedNofPropertiesOffset =
6715 kFormalParameterCountOffset + kIntSize;
6716 static const int kNumLiteralsOffset =
6717 kExpectedNofPropertiesOffset + kIntSize;
6719 static const int kEndPositionOffset =
6720 kNumLiteralsOffset + kIntSize;
6721 static const int kStartPositionAndTypeOffset =
6722 kEndPositionOffset + kIntSize;
6724 static const int kFunctionTokenPositionOffset =
6725 kStartPositionAndTypeOffset + kIntSize;
6726 static const int kCompilerHintsOffset =
6727 kFunctionTokenPositionOffset + kIntSize;
6729 static const int kOptCountAndBailoutReasonOffset =
6730 kCompilerHintsOffset + kIntSize;
6731 static const int kCountersOffset =
6732 kOptCountAndBailoutReasonOffset + kIntSize;
6734 static const int kAstNodeCountOffset =
6735 kCountersOffset + kIntSize;
6736 static const int kProfilerTicksOffset =
6737 kAstNodeCountOffset + kIntSize;
6740 static const int kSize = kProfilerTicksOffset + kIntSize;
6742 #elif V8_TARGET_BIG_ENDIAN
6743 static const int kFormalParameterCountOffset =
6744 kLastPointerFieldOffset + kPointerSize;
6745 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6747 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6748 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6750 static const int kStartPositionAndTypeOffset =
6751 kExpectedNofPropertiesOffset + kIntSize;
6752 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6754 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6755 static const int kFunctionTokenPositionOffset =
6756 kCompilerHintsOffset + kIntSize;
6758 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6759 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6761 static const int kProfilerTicksOffset =
6762 kOptCountAndBailoutReasonOffset + kIntSize;
6763 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6766 static const int kSize = kAstNodeCountOffset + kIntSize;
6769 #error Unknown byte ordering
6770 #endif // Big endian
6774 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6776 typedef FixedBodyDescriptor<kNameOffset,
6777 kLastPointerFieldOffset + kPointerSize,
6778 kSize> BodyDescriptor;
6780 // Bit positions in start_position_and_type.
6781 // The source code start position is in the 30 most significant bits of
6782 // the start_position_and_type field.
6783 static const int kIsExpressionBit = 0;
6784 static const int kIsTopLevelBit = 1;
6785 static const int kStartPositionShift = 2;
6786 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6788 // Bit positions in compiler_hints.
6789 enum CompilerHints {
6790 kAllowLazyCompilation,
6791 kAllowLazyCompilationWithoutContext,
6792 kOptimizationDisabled,
6793 kStrictModeFunction,
6794 kStrongModeFunction,
6797 kHasDuplicateParameters,
6802 kNameShouldPrintAsAnonymous,
6809 kIsAccessorFunction,
6810 kIsDefaultConstructor,
6811 kIsSubclassConstructor,
6817 kCompilerHintsCount // Pseudo entry
6819 // Add hints for other modes when they're added.
6820 STATIC_ASSERT(LANGUAGE_END == 3);
6822 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6824 class DeoptCountBits : public BitField<int, 0, 4> {};
6825 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6826 class ICAgeBits : public BitField<int, 22, 8> {};
6828 class OptCountBits : public BitField<int, 0, 22> {};
6829 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6832 #if V8_HOST_ARCH_32_BIT
6833 // On 32 bit platforms, compiler hints is a smi.
6834 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6835 static const int kCompilerHintsSize = kPointerSize;
6837 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6838 static const int kCompilerHintsSmiTagSize = 0;
6839 static const int kCompilerHintsSize = kIntSize;
6842 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6843 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6846 // Constants for optimizing codegen for strict mode function and
6848 // Allows to use byte-width instructions.
6849 static const int kStrictModeBitWithinByte =
6850 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6851 static const int kStrongModeBitWithinByte =
6852 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6854 static const int kNativeBitWithinByte =
6855 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6857 #if defined(V8_TARGET_LITTLE_ENDIAN)
6858 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6859 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6860 static const int kStrongModeByteOffset =
6861 kCompilerHintsOffset +
6862 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6863 static const int kNativeByteOffset = kCompilerHintsOffset +
6864 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6865 #elif defined(V8_TARGET_BIG_ENDIAN)
6866 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6867 (kCompilerHintsSize - 1) -
6868 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6869 static const int kStrongModeByteOffset =
6870 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6871 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6872 static const int kNativeByteOffset = kCompilerHintsOffset +
6873 (kCompilerHintsSize - 1) -
6874 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6876 #error Unknown byte ordering
6880 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6884 // Printing support.
6885 struct SourceCodeOf {
6886 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6887 : value(v), max_length(max) {}
6888 const SharedFunctionInfo* value;
6893 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6896 class JSGeneratorObject: public JSObject {
6898 // [function]: The function corresponding to this generator object.
6899 DECL_ACCESSORS(function, JSFunction)
6901 // [context]: The context of the suspended computation.
6902 DECL_ACCESSORS(context, Context)
6904 // [receiver]: The receiver of the suspended computation.
6905 DECL_ACCESSORS(receiver, Object)
6907 // [continuation]: Offset into code of continuation.
6909 // A positive offset indicates a suspended generator. The special
6910 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6911 // cannot be resumed.
6912 inline int continuation() const;
6913 inline void set_continuation(int continuation);
6914 inline bool is_closed();
6915 inline bool is_executing();
6916 inline bool is_suspended();
6918 // [operand_stack]: Saved operand stack.
6919 DECL_ACCESSORS(operand_stack, FixedArray)
6921 DECLARE_CAST(JSGeneratorObject)
6923 // Dispatched behavior.
6924 DECLARE_PRINTER(JSGeneratorObject)
6925 DECLARE_VERIFIER(JSGeneratorObject)
6927 // Magic sentinel values for the continuation.
6928 static const int kGeneratorExecuting = -1;
6929 static const int kGeneratorClosed = 0;
6931 // Layout description.
6932 static const int kFunctionOffset = JSObject::kHeaderSize;
6933 static const int kContextOffset = kFunctionOffset + kPointerSize;
6934 static const int kReceiverOffset = kContextOffset + kPointerSize;
6935 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6936 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6937 static const int kSize = kOperandStackOffset + kPointerSize;
6939 // Resume mode, for use by runtime functions.
6940 enum ResumeMode { NEXT, THROW };
6942 // Yielding from a generator returns an object with the following inobject
6943 // properties. See Context::iterator_result_map() for the map.
6944 static const int kResultValuePropertyIndex = 0;
6945 static const int kResultDonePropertyIndex = 1;
6946 static const int kResultPropertyCount = 2;
6948 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6949 static const int kResultDonePropertyOffset =
6950 kResultValuePropertyOffset + kPointerSize;
6951 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6954 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6958 // Representation for module instance objects.
6959 class JSModule: public JSObject {
6961 // [context]: the context holding the module's locals, or undefined if none.
6962 DECL_ACCESSORS(context, Object)
6964 // [scope_info]: Scope info.
6965 DECL_ACCESSORS(scope_info, ScopeInfo)
6967 DECLARE_CAST(JSModule)
6969 // Dispatched behavior.
6970 DECLARE_PRINTER(JSModule)
6971 DECLARE_VERIFIER(JSModule)
6973 // Layout description.
6974 static const int kContextOffset = JSObject::kHeaderSize;
6975 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6976 static const int kSize = kScopeInfoOffset + kPointerSize;
6979 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6983 // JSFunction describes JavaScript functions.
6984 class JSFunction: public JSObject {
6986 // [prototype_or_initial_map]:
6987 DECL_ACCESSORS(prototype_or_initial_map, Object)
6989 // [shared]: The information about the function that
6990 // can be shared by instances.
6991 DECL_ACCESSORS(shared, SharedFunctionInfo)
6993 // [context]: The context for this function.
6994 inline Context* context();
6995 inline void set_context(Object* context);
6996 inline JSObject* global_proxy();
6998 // [code]: The generated code object for this function. Executed
6999 // when the function is invoked, e.g. foo() or new foo(). See
7000 // [[Call]] and [[Construct]] description in ECMA-262, section
7002 inline Code* code();
7003 inline void set_code(Code* code);
7004 inline void set_code_no_write_barrier(Code* code);
7005 inline void ReplaceCode(Code* code);
7007 // Tells whether this function is builtin.
7008 inline bool IsBuiltin();
7010 // Tells whether this function inlines the given shared function info.
7011 bool Inlines(SharedFunctionInfo* candidate);
7013 // Tells whether this function should be subject to debugging.
7014 inline bool IsSubjectToDebugging();
7016 // Tells whether or not the function needs arguments adaption.
7017 inline bool NeedsArgumentsAdaption();
7019 // Tells whether or not this function has been optimized.
7020 inline bool IsOptimized();
7022 // Mark this function for lazy recompilation. The function will be
7023 // recompiled the next time it is executed.
7024 void MarkForOptimization();
7025 void AttemptConcurrentOptimization();
7027 // Tells whether or not the function is already marked for lazy
7029 inline bool IsMarkedForOptimization();
7030 inline bool IsMarkedForConcurrentOptimization();
7032 // Tells whether or not the function is on the concurrent recompilation queue.
7033 inline bool IsInOptimizationQueue();
7035 // Inobject slack tracking is the way to reclaim unused inobject space.
7037 // The instance size is initially determined by adding some slack to
7038 // expected_nof_properties (to allow for a few extra properties added
7039 // after the constructor). There is no guarantee that the extra space
7040 // will not be wasted.
7042 // Here is the algorithm to reclaim the unused inobject space:
7043 // - Detect the first constructor call for this JSFunction.
7044 // When it happens enter the "in progress" state: initialize construction
7045 // counter in the initial_map.
7046 // - While the tracking is in progress create objects filled with
7047 // one_pointer_filler_map instead of undefined_value. This way they can be
7048 // resized quickly and safely.
7049 // - Once enough objects have been created compute the 'slack'
7050 // (traverse the map transition tree starting from the
7051 // initial_map and find the lowest value of unused_property_fields).
7052 // - Traverse the transition tree again and decrease the instance size
7053 // of every map. Existing objects will resize automatically (they are
7054 // filled with one_pointer_filler_map). All further allocations will
7055 // use the adjusted instance size.
7056 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7057 // allocations made using different closures could actually create different
7058 // kind of objects (see prototype inheritance pattern).
7060 // Important: inobject slack tracking is not attempted during the snapshot
7063 // True if the initial_map is set and the object constructions countdown
7064 // counter is not zero.
7065 static const int kGenerousAllocationCount =
7066 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7067 inline bool IsInobjectSlackTrackingInProgress();
7069 // Starts the tracking.
7070 // Initializes object constructions countdown counter in the initial map.
7071 void StartInobjectSlackTracking();
7073 // Completes the tracking.
7074 void CompleteInobjectSlackTracking();
7076 // [literals_or_bindings]: Fixed array holding either
7077 // the materialized literals or the bindings of a bound function.
7079 // If the function contains object, regexp or array literals, the
7080 // literals array prefix contains the object, regexp, and array
7081 // function to be used when creating these literals. This is
7082 // necessary so that we do not dynamically lookup the object, regexp
7083 // or array functions. Performing a dynamic lookup, we might end up
7084 // using the functions from a new context that we should not have
7087 // On bound functions, the array is a (copy-on-write) fixed-array containing
7088 // the function that was bound, bound this-value and any bound
7089 // arguments. Bound functions never contain literals.
7090 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7092 inline FixedArray* literals();
7093 inline void set_literals(FixedArray* literals);
7095 inline FixedArray* function_bindings();
7096 inline void set_function_bindings(FixedArray* bindings);
7098 // The initial map for an object created by this constructor.
7099 inline Map* initial_map();
7100 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7101 Handle<Object> prototype);
7102 inline bool has_initial_map();
7103 static void EnsureHasInitialMap(Handle<JSFunction> function);
7105 // Get and set the prototype property on a JSFunction. If the
7106 // function has an initial map the prototype is set on the initial
7107 // map. Otherwise, the prototype is put in the initial map field
7108 // until an initial map is needed.
7109 inline bool has_prototype();
7110 inline bool has_instance_prototype();
7111 inline Object* prototype();
7112 inline Object* instance_prototype();
7113 static void SetPrototype(Handle<JSFunction> function,
7114 Handle<Object> value);
7115 static void SetInstancePrototype(Handle<JSFunction> function,
7116 Handle<Object> value);
7118 // Creates a new closure for the fucntion with the same bindings,
7119 // bound values, and prototype. An equivalent of spec operations
7120 // ``CloneMethod`` and ``CloneBoundFunction``.
7121 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7123 // After prototype is removed, it will not be created when accessed, and
7124 // [[Construct]] from this function will not be allowed.
7125 bool RemovePrototype();
7126 inline bool should_have_prototype();
7128 // Accessor for this function's initial map's [[class]]
7129 // property. This is primarily used by ECMA native functions. This
7130 // method sets the class_name field of this function's initial map
7131 // to a given value. It creates an initial map if this function does
7132 // not have one. Note that this method does not copy the initial map
7133 // if it has one already, but simply replaces it with the new value.
7134 // Instances created afterwards will have a map whose [[class]] is
7135 // set to 'value', but there is no guarantees on instances created
7137 void SetInstanceClassName(String* name);
7139 // Returns if this function has been compiled to native code yet.
7140 inline bool is_compiled();
7142 // Returns `false` if formal parameters include rest parameters, optional
7143 // parameters, or destructuring parameters.
7144 // TODO(caitp): make this a flag set during parsing
7145 inline bool is_simple_parameter_list();
7147 // [next_function_link]: Links functions into various lists, e.g. the list
7148 // of optimized functions hanging off the native_context. The CodeFlusher
7149 // uses this link to chain together flushing candidates. Treated weakly
7150 // by the garbage collector.
7151 DECL_ACCESSORS(next_function_link, Object)
7153 // Prints the name of the function using PrintF.
7154 void PrintName(FILE* out = stdout);
7156 DECLARE_CAST(JSFunction)
7158 // Iterates the objects, including code objects indirectly referenced
7159 // through pointers to the first instruction in the code object.
7160 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7162 // Dispatched behavior.
7163 DECLARE_PRINTER(JSFunction)
7164 DECLARE_VERIFIER(JSFunction)
7166 // Returns the number of allocated literals.
7167 inline int NumberOfLiterals();
7169 // Used for flags such as --hydrogen-filter.
7170 bool PassesFilter(const char* raw_filter);
7172 // The function's name if it is configured, otherwise shared function info
7174 static Handle<String> GetDebugName(Handle<JSFunction> function);
7176 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7177 // kSize) is weak and has special handling during garbage collection.
7178 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7179 static const int kPrototypeOrInitialMapOffset =
7180 kCodeEntryOffset + kPointerSize;
7181 static const int kSharedFunctionInfoOffset =
7182 kPrototypeOrInitialMapOffset + kPointerSize;
7183 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7184 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7185 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7186 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7187 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7189 // Layout of the bound-function binding array.
7190 static const int kBoundFunctionIndex = 0;
7191 static const int kBoundThisIndex = 1;
7192 static const int kBoundArgumentsStartIndex = 2;
7195 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7199 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7200 // and the prototype is hidden. JSGlobalProxy always delegates
7201 // property accesses to its prototype if the prototype is not null.
7203 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7205 // Accessing a JSGlobalProxy requires security check.
7207 class JSGlobalProxy : public JSObject {
7209 // [native_context]: the owner native context of this global proxy object.
7210 // It is null value if this object is not used by any context.
7211 DECL_ACCESSORS(native_context, Object)
7213 // [hash]: The hash code property (undefined if not initialized yet).
7214 DECL_ACCESSORS(hash, Object)
7216 DECLARE_CAST(JSGlobalProxy)
7218 inline bool IsDetachedFrom(GlobalObject* global) const;
7220 // Dispatched behavior.
7221 DECLARE_PRINTER(JSGlobalProxy)
7222 DECLARE_VERIFIER(JSGlobalProxy)
7224 // Layout description.
7225 static const int kNativeContextOffset = JSObject::kHeaderSize;
7226 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7227 static const int kSize = kHashOffset + kPointerSize;
7230 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7234 // Common super class for JavaScript global objects and the special
7235 // builtins global objects.
7236 class GlobalObject: public JSObject {
7238 // [builtins]: the object holding the runtime routines written in JS.
7239 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7241 // [native context]: the natives corresponding to this global object.
7242 DECL_ACCESSORS(native_context, Context)
7244 // [global proxy]: the global proxy object of the context
7245 DECL_ACCESSORS(global_proxy, JSObject)
7247 DECLARE_CAST(GlobalObject)
7249 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7251 // Ensure that the global object has a cell for the given property name.
7252 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7255 // Layout description.
7256 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7257 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7258 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7259 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7262 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7266 // JavaScript global object.
7267 class JSGlobalObject: public GlobalObject {
7269 DECLARE_CAST(JSGlobalObject)
7271 inline bool IsDetached();
7273 // Dispatched behavior.
7274 DECLARE_PRINTER(JSGlobalObject)
7275 DECLARE_VERIFIER(JSGlobalObject)
7277 // Layout description.
7278 static const int kSize = GlobalObject::kHeaderSize;
7281 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7285 // Builtins global object which holds the runtime routines written in
7287 class JSBuiltinsObject: public GlobalObject {
7289 // Accessors for the runtime routines written in JavaScript.
7290 inline Object* javascript_builtin(Builtins::JavaScript id);
7291 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7293 DECLARE_CAST(JSBuiltinsObject)
7295 // Dispatched behavior.
7296 DECLARE_PRINTER(JSBuiltinsObject)
7297 DECLARE_VERIFIER(JSBuiltinsObject)
7299 // Layout description. The size of the builtins object includes
7300 // room for two pointers per runtime routine written in javascript
7301 // (function and code object).
7302 static const int kJSBuiltinsCount = Builtins::id_count;
7303 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7304 static const int kSize =
7305 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7307 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7308 return kJSBuiltinsOffset + id * kPointerSize;
7312 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7316 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7317 class JSValue: public JSObject {
7319 // [value]: the object being wrapped.
7320 DECL_ACCESSORS(value, Object)
7322 DECLARE_CAST(JSValue)
7324 // Dispatched behavior.
7325 DECLARE_PRINTER(JSValue)
7326 DECLARE_VERIFIER(JSValue)
7328 // Layout description.
7329 static const int kValueOffset = JSObject::kHeaderSize;
7330 static const int kSize = kValueOffset + kPointerSize;
7333 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7339 // Representation for JS date objects.
7340 class JSDate: public JSObject {
7342 // If one component is NaN, all of them are, indicating a NaN time value.
7343 // [value]: the time value.
7344 DECL_ACCESSORS(value, Object)
7345 // [year]: caches year. Either undefined, smi, or NaN.
7346 DECL_ACCESSORS(year, Object)
7347 // [month]: caches month. Either undefined, smi, or NaN.
7348 DECL_ACCESSORS(month, Object)
7349 // [day]: caches day. Either undefined, smi, or NaN.
7350 DECL_ACCESSORS(day, Object)
7351 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7352 DECL_ACCESSORS(weekday, Object)
7353 // [hour]: caches hours. Either undefined, smi, or NaN.
7354 DECL_ACCESSORS(hour, Object)
7355 // [min]: caches minutes. Either undefined, smi, or NaN.
7356 DECL_ACCESSORS(min, Object)
7357 // [sec]: caches seconds. Either undefined, smi, or NaN.
7358 DECL_ACCESSORS(sec, Object)
7359 // [cache stamp]: sample of the date cache stamp at the
7360 // moment when chached fields were cached.
7361 DECL_ACCESSORS(cache_stamp, Object)
7363 DECLARE_CAST(JSDate)
7365 // Returns the date field with the specified index.
7366 // See FieldIndex for the list of date fields.
7367 static Object* GetField(Object* date, Smi* index);
7369 void SetValue(Object* value, bool is_value_nan);
7372 // Dispatched behavior.
7373 DECLARE_PRINTER(JSDate)
7374 DECLARE_VERIFIER(JSDate)
7376 // The order is important. It must be kept in sync with date macros
7387 kFirstUncachedField,
7388 kMillisecond = kFirstUncachedField,
7392 kYearUTC = kFirstUTCField,
7405 // Layout description.
7406 static const int kValueOffset = JSObject::kHeaderSize;
7407 static const int kYearOffset = kValueOffset + kPointerSize;
7408 static const int kMonthOffset = kYearOffset + kPointerSize;
7409 static const int kDayOffset = kMonthOffset + kPointerSize;
7410 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7411 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7412 static const int kMinOffset = kHourOffset + kPointerSize;
7413 static const int kSecOffset = kMinOffset + kPointerSize;
7414 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7415 static const int kSize = kCacheStampOffset + kPointerSize;
7418 inline Object* DoGetField(FieldIndex index);
7420 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7422 // Computes and caches the cacheable fields of the date.
7423 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7426 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7430 // Representation of message objects used for error reporting through
7431 // the API. The messages are formatted in JavaScript so this object is
7432 // a real JavaScript object. The information used for formatting the
7433 // error messages are not directly accessible from JavaScript to
7434 // prevent leaking information to user code called during error
7436 class JSMessageObject: public JSObject {
7438 // [type]: the type of error message.
7439 inline int type() const;
7440 inline void set_type(int value);
7442 // [arguments]: the arguments for formatting the error message.
7443 DECL_ACCESSORS(argument, Object)
7445 // [script]: the script from which the error message originated.
7446 DECL_ACCESSORS(script, Object)
7448 // [stack_frames]: an array of stack frames for this error object.
7449 DECL_ACCESSORS(stack_frames, Object)
7451 // [start_position]: the start position in the script for the error message.
7452 inline int start_position() const;
7453 inline void set_start_position(int value);
7455 // [end_position]: the end position in the script for the error message.
7456 inline int end_position() const;
7457 inline void set_end_position(int value);
7459 DECLARE_CAST(JSMessageObject)
7461 // Dispatched behavior.
7462 DECLARE_PRINTER(JSMessageObject)
7463 DECLARE_VERIFIER(JSMessageObject)
7465 // Layout description.
7466 static const int kTypeOffset = JSObject::kHeaderSize;
7467 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7468 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7469 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7470 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7471 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7472 static const int kSize = kEndPositionOffset + kPointerSize;
7474 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7475 kStackFramesOffset + kPointerSize,
7476 kSize> BodyDescriptor;
7480 // Regular expressions
7481 // The regular expression holds a single reference to a FixedArray in
7482 // the kDataOffset field.
7483 // The FixedArray contains the following data:
7484 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7485 // - reference to the original source string
7486 // - reference to the original flag string
7487 // If it is an atom regexp
7488 // - a reference to a literal string to search for
7489 // If it is an irregexp regexp:
7490 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7491 // used for tracking the last usage (used for code flushing).
7492 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7493 // used for tracking the last usage (used for code flushing)..
7494 // - max number of registers used by irregexp implementations.
7495 // - number of capture registers (output values) of the regexp.
7496 class JSRegExp: public JSObject {
7499 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7500 // ATOM: A simple string to match against using an indexOf operation.
7501 // IRREGEXP: Compiled with Irregexp.
7502 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7503 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7510 UNICODE_ESCAPES = 16
7515 explicit Flags(uint32_t value) : value_(value) { }
7516 bool is_global() { return (value_ & GLOBAL) != 0; }
7517 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7518 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7519 bool is_sticky() { return (value_ & STICKY) != 0; }
7520 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7521 uint32_t value() { return value_; }
7526 DECL_ACCESSORS(data, Object)
7528 inline Type TypeTag();
7529 inline int CaptureCount();
7530 inline Flags GetFlags();
7531 inline String* Pattern();
7532 inline Object* DataAt(int index);
7533 // Set implementation data after the object has been prepared.
7534 inline void SetDataAt(int index, Object* value);
7536 static int code_index(bool is_latin1) {
7538 return kIrregexpLatin1CodeIndex;
7540 return kIrregexpUC16CodeIndex;
7544 static int saved_code_index(bool is_latin1) {
7546 return kIrregexpLatin1CodeSavedIndex;
7548 return kIrregexpUC16CodeSavedIndex;
7552 DECLARE_CAST(JSRegExp)
7554 // Dispatched behavior.
7555 DECLARE_VERIFIER(JSRegExp)
7557 static const int kDataOffset = JSObject::kHeaderSize;
7558 static const int kSize = kDataOffset + kPointerSize;
7560 // Indices in the data array.
7561 static const int kTagIndex = 0;
7562 static const int kSourceIndex = kTagIndex + 1;
7563 static const int kFlagsIndex = kSourceIndex + 1;
7564 static const int kDataIndex = kFlagsIndex + 1;
7565 // The data fields are used in different ways depending on the
7566 // value of the tag.
7567 // Atom regexps (literal strings).
7568 static const int kAtomPatternIndex = kDataIndex;
7570 static const int kAtomDataSize = kAtomPatternIndex + 1;
7572 // Irregexp compiled code or bytecode for Latin1. If compilation
7573 // fails, this fields hold an exception object that should be
7574 // thrown if the regexp is used again.
7575 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7576 // Irregexp compiled code or bytecode for UC16. If compilation
7577 // fails, this fields hold an exception object that should be
7578 // thrown if the regexp is used again.
7579 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7581 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7582 // is a potential candidate for flushing.
7583 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7584 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7585 // a potential candidate for flushing.
7586 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7588 // Maximal number of registers used by either Latin1 or UC16.
7589 // Only used to check that there is enough stack space
7590 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7591 // Number of captures in the compiled regexp.
7592 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7594 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7596 // Offsets directly into the data fixed array.
7597 static const int kDataTagOffset =
7598 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7599 static const int kDataOneByteCodeOffset =
7600 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7601 static const int kDataUC16CodeOffset =
7602 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7603 static const int kIrregexpCaptureCountOffset =
7604 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7606 // In-object fields.
7607 static const int kSourceFieldIndex = 0;
7608 static const int kGlobalFieldIndex = 1;
7609 static const int kIgnoreCaseFieldIndex = 2;
7610 static const int kMultilineFieldIndex = 3;
7611 static const int kLastIndexFieldIndex = 4;
7612 static const int kInObjectFieldCount = 5;
7614 // The uninitialized value for a regexp code object.
7615 static const int kUninitializedValue = -1;
7617 // The compilation error value for the regexp code object. The real error
7618 // object is in the saved code field.
7619 static const int kCompilationErrorValue = -2;
7621 // When we store the sweep generation at which we moved the code from the
7622 // code index to the saved code index we mask it of to be in the [0:255]
7624 static const int kCodeAgeMask = 0xff;
7628 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7630 static inline bool IsMatch(HashTableKey* key, Object* value) {
7631 return key->IsMatch(value);
7634 static inline uint32_t Hash(HashTableKey* key) {
7638 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7639 return key->HashForObject(object);
7642 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7644 static const int kPrefixSize = 0;
7645 static const int kEntrySize = 2;
7649 // This cache is used in two different variants. For regexp caching, it simply
7650 // maps identifying info of the regexp to the cached regexp object. Scripts and
7651 // eval code only gets cached after a second probe for the code object. To do
7652 // so, on first "put" only a hash identifying the source is entered into the
7653 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7654 // such lifetimes get reduced, and removed once they reach zero. If a second put
7655 // is called while such a hash is live in the cache, the hash gets replaced by
7656 // an actual cache entry. Age also removes stale live entries from the cache.
7657 // Such entries are identified by SharedFunctionInfos pointing to either the
7658 // recompilation stub, or to "old" code. This avoids memory leaks due to
7659 // premature caching of scripts and eval strings that are never needed later.
7660 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7661 CompilationCacheShape,
7664 // Find cached value for a string key, otherwise return null.
7665 Handle<Object> Lookup(
7666 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7667 Handle<Object> LookupEval(
7668 Handle<String> src, Handle<SharedFunctionInfo> shared,
7669 LanguageMode language_mode, int scope_position);
7670 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7671 static Handle<CompilationCacheTable> Put(
7672 Handle<CompilationCacheTable> cache, Handle<String> src,
7673 Handle<Context> context, LanguageMode language_mode,
7674 Handle<Object> value);
7675 static Handle<CompilationCacheTable> PutEval(
7676 Handle<CompilationCacheTable> cache, Handle<String> src,
7677 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7678 int scope_position);
7679 static Handle<CompilationCacheTable> PutRegExp(
7680 Handle<CompilationCacheTable> cache, Handle<String> src,
7681 JSRegExp::Flags flags, Handle<FixedArray> value);
7682 void Remove(Object* value);
7684 static const int kHashGenerations = 10;
7686 DECLARE_CAST(CompilationCacheTable)
7689 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7693 class CodeCache: public Struct {
7695 DECL_ACCESSORS(default_cache, FixedArray)
7696 DECL_ACCESSORS(normal_type_cache, Object)
7698 // Add the code object to the cache.
7700 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7702 // Lookup code object in the cache. Returns code object if found and undefined
7704 Object* Lookup(Name* name, Code::Flags flags);
7706 // Get the internal index of a code object in the cache. Returns -1 if the
7707 // code object is not in that cache. This index can be used to later call
7708 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7710 int GetIndex(Object* name, Code* code);
7712 // Remove an object from the cache with the provided internal index.
7713 void RemoveByIndex(Object* name, Code* code, int index);
7715 DECLARE_CAST(CodeCache)
7717 // Dispatched behavior.
7718 DECLARE_PRINTER(CodeCache)
7719 DECLARE_VERIFIER(CodeCache)
7721 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7722 static const int kNormalTypeCacheOffset =
7723 kDefaultCacheOffset + kPointerSize;
7724 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7727 static void UpdateDefaultCache(
7728 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7729 static void UpdateNormalTypeCache(
7730 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7731 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7732 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7734 // Code cache layout of the default cache. Elements are alternating name and
7735 // code objects for non normal load/store/call IC's.
7736 static const int kCodeCacheEntrySize = 2;
7737 static const int kCodeCacheEntryNameOffset = 0;
7738 static const int kCodeCacheEntryCodeOffset = 1;
7740 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7744 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7746 static inline bool IsMatch(HashTableKey* key, Object* value) {
7747 return key->IsMatch(value);
7750 static inline uint32_t Hash(HashTableKey* key) {
7754 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7755 return key->HashForObject(object);
7758 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7760 static const int kPrefixSize = 0;
7761 static const int kEntrySize = 2;
7765 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7766 CodeCacheHashTableShape,
7769 Object* Lookup(Name* name, Code::Flags flags);
7770 static Handle<CodeCacheHashTable> Put(
7771 Handle<CodeCacheHashTable> table,
7775 int GetIndex(Name* name, Code::Flags flags);
7776 void RemoveByIndex(int index);
7778 DECLARE_CAST(CodeCacheHashTable)
7780 // Initial size of the fixed array backing the hash table.
7781 static const int kInitialSize = 64;
7784 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7788 class PolymorphicCodeCache: public Struct {
7790 DECL_ACCESSORS(cache, Object)
7792 static void Update(Handle<PolymorphicCodeCache> cache,
7793 MapHandleList* maps,
7798 // Returns an undefined value if the entry is not found.
7799 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7801 DECLARE_CAST(PolymorphicCodeCache)
7803 // Dispatched behavior.
7804 DECLARE_PRINTER(PolymorphicCodeCache)
7805 DECLARE_VERIFIER(PolymorphicCodeCache)
7807 static const int kCacheOffset = HeapObject::kHeaderSize;
7808 static const int kSize = kCacheOffset + kPointerSize;
7811 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7815 class PolymorphicCodeCacheHashTable
7816 : public HashTable<PolymorphicCodeCacheHashTable,
7817 CodeCacheHashTableShape,
7820 Object* Lookup(MapHandleList* maps, int code_kind);
7822 static Handle<PolymorphicCodeCacheHashTable> Put(
7823 Handle<PolymorphicCodeCacheHashTable> hash_table,
7824 MapHandleList* maps,
7828 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7830 static const int kInitialSize = 64;
7832 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7836 class TypeFeedbackInfo: public Struct {
7838 inline int ic_total_count();
7839 inline void set_ic_total_count(int count);
7841 inline int ic_with_type_info_count();
7842 inline void change_ic_with_type_info_count(int delta);
7844 inline int ic_generic_count();
7845 inline void change_ic_generic_count(int delta);
7847 inline void initialize_storage();
7849 inline void change_own_type_change_checksum();
7850 inline int own_type_change_checksum();
7852 inline void set_inlined_type_change_checksum(int checksum);
7853 inline bool matches_inlined_type_change_checksum(int checksum);
7855 DECLARE_CAST(TypeFeedbackInfo)
7857 // Dispatched behavior.
7858 DECLARE_PRINTER(TypeFeedbackInfo)
7859 DECLARE_VERIFIER(TypeFeedbackInfo)
7861 static const int kStorage1Offset = HeapObject::kHeaderSize;
7862 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7863 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7864 static const int kSize = kStorage3Offset + kPointerSize;
7867 static const int kTypeChangeChecksumBits = 7;
7869 class ICTotalCountField: public BitField<int, 0,
7870 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7871 class OwnTypeChangeChecksum: public BitField<int,
7872 kSmiValueSize - kTypeChangeChecksumBits,
7873 kTypeChangeChecksumBits> {}; // NOLINT
7874 class ICsWithTypeInfoCountField: public BitField<int, 0,
7875 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7876 class InlinedTypeChangeChecksum: public BitField<int,
7877 kSmiValueSize - kTypeChangeChecksumBits,
7878 kTypeChangeChecksumBits> {}; // NOLINT
7880 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7884 enum AllocationSiteMode {
7885 DONT_TRACK_ALLOCATION_SITE,
7886 TRACK_ALLOCATION_SITE,
7887 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7891 class AllocationSite: public Struct {
7893 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7894 static const double kPretenureRatio;
7895 static const int kPretenureMinimumCreated = 100;
7897 // Values for pretenure decision field.
7898 enum PretenureDecision {
7904 kLastPretenureDecisionValue = kZombie
7907 const char* PretenureDecisionName(PretenureDecision decision);
7909 DECL_ACCESSORS(transition_info, Object)
7910 // nested_site threads a list of sites that represent nested literals
7911 // walked in a particular order. So [[1, 2], 1, 2] will have one
7912 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7913 DECL_ACCESSORS(nested_site, Object)
7914 DECL_ACCESSORS(pretenure_data, Smi)
7915 DECL_ACCESSORS(pretenure_create_count, Smi)
7916 DECL_ACCESSORS(dependent_code, DependentCode)
7917 DECL_ACCESSORS(weak_next, Object)
7919 inline void Initialize();
7921 // This method is expensive, it should only be called for reporting.
7922 bool IsNestedSite();
7924 // transition_info bitfields, for constructed array transition info.
7925 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7926 class UnusedBits: public BitField<int, 15, 14> {};
7927 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7929 // Bitfields for pretenure_data
7930 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7931 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7932 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7933 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7935 // Increments the mementos found counter and returns true when the first
7936 // memento was found for a given allocation site.
7937 inline bool IncrementMementoFoundCount();
7939 inline void IncrementMementoCreateCount();
7941 PretenureFlag GetPretenureMode();
7943 void ResetPretenureDecision();
7945 PretenureDecision pretenure_decision() {
7946 int value = pretenure_data()->value();
7947 return PretenureDecisionBits::decode(value);
7950 void set_pretenure_decision(PretenureDecision decision) {
7951 int value = pretenure_data()->value();
7953 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
7954 SKIP_WRITE_BARRIER);
7957 bool deopt_dependent_code() {
7958 int value = pretenure_data()->value();
7959 return DeoptDependentCodeBit::decode(value);
7962 void set_deopt_dependent_code(bool deopt) {
7963 int value = pretenure_data()->value();
7965 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
7966 SKIP_WRITE_BARRIER);
7969 int memento_found_count() {
7970 int value = pretenure_data()->value();
7971 return MementoFoundCountBits::decode(value);
7974 inline void set_memento_found_count(int count);
7976 int memento_create_count() {
7977 return pretenure_create_count()->value();
7980 void set_memento_create_count(int count) {
7981 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
7984 // The pretenuring decision is made during gc, and the zombie state allows
7985 // us to recognize when an allocation site is just being kept alive because
7986 // a later traversal of new space may discover AllocationMementos that point
7987 // to this AllocationSite.
7989 return pretenure_decision() == kZombie;
7992 bool IsMaybeTenure() {
7993 return pretenure_decision() == kMaybeTenure;
7996 inline void MarkZombie();
7998 inline bool MakePretenureDecision(PretenureDecision current_decision,
8000 bool maximum_size_scavenge);
8002 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8004 ElementsKind GetElementsKind() {
8005 DCHECK(!SitePointsToLiteral());
8006 int value = Smi::cast(transition_info())->value();
8007 return ElementsKindBits::decode(value);
8010 void SetElementsKind(ElementsKind kind) {
8011 int value = Smi::cast(transition_info())->value();
8012 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8013 SKIP_WRITE_BARRIER);
8016 bool CanInlineCall() {
8017 int value = Smi::cast(transition_info())->value();
8018 return DoNotInlineBit::decode(value) == 0;
8021 void SetDoNotInlineCall() {
8022 int value = Smi::cast(transition_info())->value();
8023 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8024 SKIP_WRITE_BARRIER);
8027 bool SitePointsToLiteral() {
8028 // If transition_info is a smi, then it represents an ElementsKind
8029 // for a constructed array. Otherwise, it must be a boilerplate
8030 // for an object or array literal.
8031 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8034 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8035 ElementsKind to_kind);
8037 DECLARE_PRINTER(AllocationSite)
8038 DECLARE_VERIFIER(AllocationSite)
8040 DECLARE_CAST(AllocationSite)
8041 static inline AllocationSiteMode GetMode(
8042 ElementsKind boilerplate_elements_kind);
8043 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8044 static inline bool CanTrack(InstanceType type);
8046 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8047 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8048 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8049 static const int kPretenureCreateCountOffset =
8050 kPretenureDataOffset + kPointerSize;
8051 static const int kDependentCodeOffset =
8052 kPretenureCreateCountOffset + kPointerSize;
8053 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8054 static const int kSize = kWeakNextOffset + kPointerSize;
8056 // During mark compact we need to take special care for the dependent code
8058 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8059 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8061 // For other visitors, use the fixed body descriptor below.
8062 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8063 kDependentCodeOffset + kPointerSize,
8064 kSize> BodyDescriptor;
8067 bool PretenuringDecisionMade() {
8068 return pretenure_decision() != kUndecided;
8071 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8075 class AllocationMemento: public Struct {
8077 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8078 static const int kSize = kAllocationSiteOffset + kPointerSize;
8080 DECL_ACCESSORS(allocation_site, Object)
8083 return allocation_site()->IsAllocationSite() &&
8084 !AllocationSite::cast(allocation_site())->IsZombie();
8086 AllocationSite* GetAllocationSite() {
8088 return AllocationSite::cast(allocation_site());
8091 DECLARE_PRINTER(AllocationMemento)
8092 DECLARE_VERIFIER(AllocationMemento)
8094 DECLARE_CAST(AllocationMemento)
8097 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8101 // Representation of a slow alias as part of a sloppy arguments objects.
8102 // For fast aliases (if HasSloppyArgumentsElements()):
8103 // - the parameter map contains an index into the context
8104 // - all attributes of the element have default values
8105 // For slow aliases (if HasDictionaryArgumentsElements()):
8106 // - the parameter map contains no fast alias mapping (i.e. the hole)
8107 // - this struct (in the slow backing store) contains an index into the context
8108 // - all attributes are available as part if the property details
8109 class AliasedArgumentsEntry: public Struct {
8111 inline int aliased_context_slot() const;
8112 inline void set_aliased_context_slot(int count);
8114 DECLARE_CAST(AliasedArgumentsEntry)
8116 // Dispatched behavior.
8117 DECLARE_PRINTER(AliasedArgumentsEntry)
8118 DECLARE_VERIFIER(AliasedArgumentsEntry)
8120 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8121 static const int kSize = kAliasedContextSlot + kPointerSize;
8124 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8128 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8129 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8132 class StringHasher {
8134 explicit inline StringHasher(int length, uint32_t seed);
8136 template <typename schar>
8137 static inline uint32_t HashSequentialString(const schar* chars,
8141 // Reads all the data, even for long strings and computes the utf16 length.
8142 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8144 int* utf16_length_out);
8146 // Calculated hash value for a string consisting of 1 to
8147 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8148 // value is represented decimal value.
8149 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8151 // No string is allowed to have a hash of zero. That value is reserved
8152 // for internal properties. If the hash calculation yields zero then we
8154 static const int kZeroHash = 27;
8156 // Reusable parts of the hashing algorithm.
8157 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8158 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8159 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8160 const uc16* chars, int length));
8161 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8166 // Returns the value to store in the hash field of a string with
8167 // the given length and contents.
8168 uint32_t GetHashField();
8169 // Returns true if the hash of this string can be computed without
8170 // looking at the contents.
8171 inline bool has_trivial_hash();
8172 // Adds a block of characters to the hash.
8173 template<typename Char>
8174 inline void AddCharacters(const Char* chars, int len);
8177 // Add a character to the hash.
8178 inline void AddCharacter(uint16_t c);
8179 // Update index. Returns true if string is still an index.
8180 inline bool UpdateIndex(uint16_t c);
8183 uint32_t raw_running_hash_;
8184 uint32_t array_index_;
8185 bool is_array_index_;
8186 bool is_first_char_;
8187 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8191 class IteratingStringHasher : public StringHasher {
8193 static inline uint32_t Hash(String* string, uint32_t seed);
8194 inline void VisitOneByteString(const uint8_t* chars, int length);
8195 inline void VisitTwoByteString(const uint16_t* chars, int length);
8198 inline IteratingStringHasher(int len, uint32_t seed)
8199 : StringHasher(len, seed) {}
8200 void VisitConsString(ConsString* cons_string);
8201 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8205 // The characteristics of a string are stored in its map. Retrieving these
8206 // few bits of information is moderately expensive, involving two memory
8207 // loads where the second is dependent on the first. To improve efficiency
8208 // the shape of the string is given its own class so that it can be retrieved
8209 // once and used for several string operations. A StringShape is small enough
8210 // to be passed by value and is immutable, but be aware that flattening a
8211 // string can potentially alter its shape. Also be aware that a GC caused by
8212 // something else can alter the shape of a string due to ConsString
8213 // shortcutting. Keeping these restrictions in mind has proven to be error-
8214 // prone and so we no longer put StringShapes in variables unless there is a
8215 // concrete performance benefit at that particular point in the code.
8216 class StringShape BASE_EMBEDDED {
8218 inline explicit StringShape(const String* s);
8219 inline explicit StringShape(Map* s);
8220 inline explicit StringShape(InstanceType t);
8221 inline bool IsSequential();
8222 inline bool IsExternal();
8223 inline bool IsCons();
8224 inline bool IsSliced();
8225 inline bool IsIndirect();
8226 inline bool IsExternalOneByte();
8227 inline bool IsExternalTwoByte();
8228 inline bool IsSequentialOneByte();
8229 inline bool IsSequentialTwoByte();
8230 inline bool IsInternalized();
8231 inline StringRepresentationTag representation_tag();
8232 inline uint32_t encoding_tag();
8233 inline uint32_t full_representation_tag();
8234 inline uint32_t size_tag();
8236 inline uint32_t type() { return type_; }
8237 inline void invalidate() { valid_ = false; }
8238 inline bool valid() { return valid_; }
8240 inline void invalidate() { }
8246 inline void set_valid() { valid_ = true; }
8249 inline void set_valid() { }
8254 // The Name abstract class captures anything that can be used as a property
8255 // name, i.e., strings and symbols. All names store a hash value.
8256 class Name: public HeapObject {
8258 // Get and set the hash field of the name.
8259 inline uint32_t hash_field();
8260 inline void set_hash_field(uint32_t value);
8262 // Tells whether the hash code has been computed.
8263 inline bool HasHashCode();
8265 // Returns a hash value used for the property table
8266 inline uint32_t Hash();
8268 // Equality operations.
8269 inline bool Equals(Name* other);
8270 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8273 inline bool AsArrayIndex(uint32_t* index);
8275 // If the name is private, it can only name own properties.
8276 inline bool IsPrivate();
8278 // If the name is a non-flat string, this method returns a flat version of the
8279 // string. Otherwise it'll just return the input.
8280 static inline Handle<Name> Flatten(Handle<Name> name,
8281 PretenureFlag pretenure = NOT_TENURED);
8285 DECLARE_PRINTER(Name)
8287 void NameShortPrint();
8288 int NameShortPrint(Vector<char> str);
8291 // Layout description.
8292 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8293 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8294 static const int kHashFieldOffset = kHashFieldSlot;
8296 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8298 static const int kSize = kHashFieldSlot + kPointerSize;
8300 // Mask constant for checking if a name has a computed hash code
8301 // and if it is a string that is an array index. The least significant bit
8302 // indicates whether a hash code has been computed. If the hash code has
8303 // been computed the 2nd bit tells whether the string can be used as an
8305 static const int kHashNotComputedMask = 1;
8306 static const int kIsNotArrayIndexMask = 1 << 1;
8307 static const int kNofHashBitFields = 2;
8309 // Shift constant retrieving hash code from hash field.
8310 static const int kHashShift = kNofHashBitFields;
8312 // Only these bits are relevant in the hash, since the top two are shifted
8314 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8316 // Array index strings this short can keep their index in the hash field.
8317 static const int kMaxCachedArrayIndexLength = 7;
8319 // For strings which are array indexes the hash value has the string length
8320 // mixed into the hash, mainly to avoid a hash value of zero which would be
8321 // the case for the string '0'. 24 bits are used for the array index value.
8322 static const int kArrayIndexValueBits = 24;
8323 static const int kArrayIndexLengthBits =
8324 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8326 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8328 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8329 kArrayIndexValueBits> {}; // NOLINT
8330 class ArrayIndexLengthBits : public BitField<unsigned int,
8331 kNofHashBitFields + kArrayIndexValueBits,
8332 kArrayIndexLengthBits> {}; // NOLINT
8334 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8335 // could use a mask to test if the length of string is less than or equal to
8336 // kMaxCachedArrayIndexLength.
8337 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8339 static const unsigned int kContainsCachedArrayIndexMask =
8340 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8341 << ArrayIndexLengthBits::kShift) |
8342 kIsNotArrayIndexMask;
8344 // Value of empty hash field indicating that the hash is not computed.
8345 static const int kEmptyHashField =
8346 kIsNotArrayIndexMask | kHashNotComputedMask;
8349 static inline bool IsHashFieldComputed(uint32_t field);
8352 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8357 class Symbol: public Name {
8359 // [name]: The print name of a symbol, or undefined if none.
8360 DECL_ACCESSORS(name, Object)
8362 DECL_ACCESSORS(flags, Smi)
8364 // [is_private]: Whether this is a private symbol. Private symbols can only
8365 // be used to designate own properties of objects.
8366 DECL_BOOLEAN_ACCESSORS(is_private)
8368 DECLARE_CAST(Symbol)
8370 // Dispatched behavior.
8371 DECLARE_PRINTER(Symbol)
8372 DECLARE_VERIFIER(Symbol)
8374 // Layout description.
8375 static const int kNameOffset = Name::kSize;
8376 static const int kFlagsOffset = kNameOffset + kPointerSize;
8377 static const int kSize = kFlagsOffset + kPointerSize;
8379 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8381 void SymbolShortPrint(std::ostream& os);
8384 static const int kPrivateBit = 0;
8386 const char* PrivateSymbolToName() const;
8389 friend class Name; // For PrivateSymbolToName.
8392 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8398 // The String abstract class captures JavaScript string values:
8401 // 4.3.16 String Value
8402 // A string value is a member of the type String and is a finite
8403 // ordered sequence of zero or more 16-bit unsigned integer values.
8405 // All string values have a length field.
8406 class String: public Name {
8408 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8410 // Array index strings this short can keep their index in the hash field.
8411 static const int kMaxCachedArrayIndexLength = 7;
8413 // For strings which are array indexes the hash value has the string length
8414 // mixed into the hash, mainly to avoid a hash value of zero which would be
8415 // the case for the string '0'. 24 bits are used for the array index value.
8416 static const int kArrayIndexValueBits = 24;
8417 static const int kArrayIndexLengthBits =
8418 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8420 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8422 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8423 kArrayIndexValueBits> {}; // NOLINT
8424 class ArrayIndexLengthBits : public BitField<unsigned int,
8425 kNofHashBitFields + kArrayIndexValueBits,
8426 kArrayIndexLengthBits> {}; // NOLINT
8428 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8429 // could use a mask to test if the length of string is less than or equal to
8430 // kMaxCachedArrayIndexLength.
8431 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8433 static const unsigned int kContainsCachedArrayIndexMask =
8434 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8435 << ArrayIndexLengthBits::kShift) |
8436 kIsNotArrayIndexMask;
8438 class SubStringRange {
8440 explicit SubStringRange(String* string, int first = 0, int length = -1)
8443 length_(length == -1 ? string->length() : length) {}
8445 inline iterator begin();
8446 inline iterator end();
8454 // Representation of the flat content of a String.
8455 // A non-flat string doesn't have flat content.
8456 // A flat string has content that's encoded as a sequence of either
8457 // one-byte chars or two-byte UC16.
8458 // Returned by String::GetFlatContent().
8461 // Returns true if the string is flat and this structure contains content.
8462 bool IsFlat() { return state_ != NON_FLAT; }
8463 // Returns true if the structure contains one-byte content.
8464 bool IsOneByte() { return state_ == ONE_BYTE; }
8465 // Returns true if the structure contains two-byte content.
8466 bool IsTwoByte() { return state_ == TWO_BYTE; }
8468 // Return the one byte content of the string. Only use if IsOneByte()
8470 Vector<const uint8_t> ToOneByteVector() {
8471 DCHECK_EQ(ONE_BYTE, state_);
8472 return Vector<const uint8_t>(onebyte_start, length_);
8474 // Return the two-byte content of the string. Only use if IsTwoByte()
8476 Vector<const uc16> ToUC16Vector() {
8477 DCHECK_EQ(TWO_BYTE, state_);
8478 return Vector<const uc16>(twobyte_start, length_);
8482 DCHECK(i < length_);
8483 DCHECK(state_ != NON_FLAT);
8484 if (state_ == ONE_BYTE) return onebyte_start[i];
8485 return twobyte_start[i];
8488 bool UsesSameString(const FlatContent& other) const {
8489 return onebyte_start == other.onebyte_start;
8493 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8495 // Constructors only used by String::GetFlatContent().
8496 explicit FlatContent(const uint8_t* start, int length)
8497 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8498 explicit FlatContent(const uc16* start, int length)
8499 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8500 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8503 const uint8_t* onebyte_start;
8504 const uc16* twobyte_start;
8509 friend class String;
8510 friend class IterableSubString;
8513 template <typename Char>
8514 INLINE(Vector<const Char> GetCharVector());
8516 // Get and set the length of the string.
8517 inline int length() const;
8518 inline void set_length(int value);
8520 // Get and set the length of the string using acquire loads and release
8522 inline int synchronized_length() const;
8523 inline void synchronized_set_length(int value);
8525 // Returns whether this string has only one-byte chars, i.e. all of them can
8526 // be one-byte encoded. This might be the case even if the string is
8527 // two-byte. Such strings may appear when the embedder prefers
8528 // two-byte external representations even for one-byte data.
8529 inline bool IsOneByteRepresentation() const;
8530 inline bool IsTwoByteRepresentation() const;
8532 // Cons and slices have an encoding flag that may not represent the actual
8533 // encoding of the underlying string. This is taken into account here.
8534 // Requires: this->IsFlat()
8535 inline bool IsOneByteRepresentationUnderneath();
8536 inline bool IsTwoByteRepresentationUnderneath();
8538 // NOTE: this should be considered only a hint. False negatives are
8540 inline bool HasOnlyOneByteChars();
8542 // Get and set individual two byte chars in the string.
8543 inline void Set(int index, uint16_t value);
8544 // Get individual two byte char in the string. Repeated calls
8545 // to this method are not efficient unless the string is flat.
8546 INLINE(uint16_t Get(int index));
8548 // Flattens the string. Checks first inline to see if it is
8549 // necessary. Does nothing if the string is not a cons string.
8550 // Flattening allocates a sequential string with the same data as
8551 // the given string and mutates the cons string to a degenerate
8552 // form, where the first component is the new sequential string and
8553 // the second component is the empty string. If allocation fails,
8554 // this function returns a failure. If flattening succeeds, this
8555 // function returns the sequential string that is now the first
8556 // component of the cons string.
8558 // Degenerate cons strings are handled specially by the garbage
8559 // collector (see IsShortcutCandidate).
8561 static inline Handle<String> Flatten(Handle<String> string,
8562 PretenureFlag pretenure = NOT_TENURED);
8564 // Tries to return the content of a flat string as a structure holding either
8565 // a flat vector of char or of uc16.
8566 // If the string isn't flat, and therefore doesn't have flat content, the
8567 // returned structure will report so, and can't provide a vector of either
8569 FlatContent GetFlatContent();
8571 // Returns the parent of a sliced string or first part of a flat cons string.
8572 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8573 inline String* GetUnderlying();
8575 // String equality operations.
8576 inline bool Equals(String* other);
8577 inline static bool Equals(Handle<String> one, Handle<String> two);
8578 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8579 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8580 bool IsTwoByteEqualTo(Vector<const uc16> str);
8582 // Return a UTF8 representation of the string. The string is null
8583 // terminated but may optionally contain nulls. Length is returned
8584 // in length_output if length_output is not a null pointer The string
8585 // should be nearly flat, otherwise the performance of this method may
8586 // be very slow (quadratic in the length). Setting robustness_flag to
8587 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8588 // handles unexpected data without causing assert failures and it does not
8589 // do any heap allocations. This is useful when printing stack traces.
8590 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8591 RobustnessFlag robustness_flag,
8592 int offset, int length,
8593 int* length_output = 0);
8594 base::SmartArrayPointer<char> ToCString(
8595 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8596 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8597 int* length_output = 0);
8599 // Return a 16 bit Unicode representation of the string.
8600 // The string should be nearly flat, otherwise the performance of
8601 // of this method may be very bad. Setting robustness_flag to
8602 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8603 // handles unexpected data without causing assert failures and it does not
8604 // do any heap allocations. This is useful when printing stack traces.
8605 base::SmartArrayPointer<uc16> ToWideCString(
8606 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8608 bool ComputeArrayIndex(uint32_t* index);
8611 bool MakeExternal(v8::String::ExternalStringResource* resource);
8612 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8615 inline bool AsArrayIndex(uint32_t* index);
8617 DECLARE_CAST(String)
8619 void PrintOn(FILE* out);
8621 // For use during stack traces. Performs rudimentary sanity check.
8624 // Dispatched behavior.
8625 void StringShortPrint(StringStream* accumulator);
8626 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8627 #if defined(DEBUG) || defined(OBJECT_PRINT)
8628 char* ToAsciiArray();
8630 DECLARE_PRINTER(String)
8631 DECLARE_VERIFIER(String)
8633 inline bool IsFlat();
8635 // Layout description.
8636 static const int kLengthOffset = Name::kSize;
8637 static const int kSize = kLengthOffset + kPointerSize;
8639 // Maximum number of characters to consider when trying to convert a string
8640 // value into an array index.
8641 static const int kMaxArrayIndexSize = 10;
8642 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8645 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8646 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8647 static const int kMaxUtf16CodeUnit = 0xffff;
8648 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8650 // Value of hash field containing computed hash equal to zero.
8651 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8653 // Maximal string length.
8654 static const int kMaxLength = (1 << 28) - 16;
8656 // Max length for computing hash. For strings longer than this limit the
8657 // string length is used as the hash value.
8658 static const int kMaxHashCalcLength = 16383;
8660 // Limit for truncation in short printing.
8661 static const int kMaxShortPrintLength = 1024;
8663 // Support for regular expressions.
8664 const uc16* GetTwoByteData(unsigned start);
8666 // Helper function for flattening strings.
8667 template <typename sinkchar>
8668 static void WriteToFlat(String* source,
8673 // The return value may point to the first aligned word containing the first
8674 // non-one-byte character, rather than directly to the non-one-byte character.
8675 // If the return value is >= the passed length, the entire string was
8677 static inline int NonAsciiStart(const char* chars, int length) {
8678 const char* start = chars;
8679 const char* limit = chars + length;
8681 if (length >= kIntptrSize) {
8682 // Check unaligned bytes.
8683 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8684 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8685 return static_cast<int>(chars - start);
8689 // Check aligned words.
8690 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8691 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8692 while (chars + sizeof(uintptr_t) <= limit) {
8693 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8694 return static_cast<int>(chars - start);
8696 chars += sizeof(uintptr_t);
8699 // Check remaining unaligned bytes.
8700 while (chars < limit) {
8701 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8702 return static_cast<int>(chars - start);
8707 return static_cast<int>(chars - start);
8710 static inline bool IsAscii(const char* chars, int length) {
8711 return NonAsciiStart(chars, length) >= length;
8714 static inline bool IsAscii(const uint8_t* chars, int length) {
8716 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8719 static inline int NonOneByteStart(const uc16* chars, int length) {
8720 const uc16* limit = chars + length;
8721 const uc16* start = chars;
8722 while (chars < limit) {
8723 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8726 return static_cast<int>(chars - start);
8729 static inline bool IsOneByte(const uc16* chars, int length) {
8730 return NonOneByteStart(chars, length) >= length;
8733 template<class Visitor>
8734 static inline ConsString* VisitFlat(Visitor* visitor,
8738 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8739 bool include_ending_line);
8741 // Use the hash field to forward to the canonical internalized string
8742 // when deserializing an internalized string.
8743 inline void SetForwardedInternalizedString(String* string);
8744 inline String* GetForwardedInternalizedString();
8748 friend class StringTableInsertionKey;
8750 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8751 PretenureFlag tenure);
8753 // Slow case of String::Equals. This implementation works on any strings
8754 // but it is most efficient on strings that are almost flat.
8755 bool SlowEquals(String* other);
8757 static bool SlowEquals(Handle<String> one, Handle<String> two);
8759 // Slow case of AsArrayIndex.
8760 bool SlowAsArrayIndex(uint32_t* index);
8762 // Compute and set the hash code.
8763 uint32_t ComputeAndSetHash();
8765 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8769 // The SeqString abstract class captures sequential string values.
8770 class SeqString: public String {
8772 DECLARE_CAST(SeqString)
8774 // Layout description.
8775 static const int kHeaderSize = String::kSize;
8777 // Truncate the string in-place if possible and return the result.
8778 // In case of new_length == 0, the empty string is returned without
8779 // truncating the original string.
8780 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8783 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8787 // The OneByteString class captures sequential one-byte string objects.
8788 // Each character in the OneByteString is an one-byte character.
8789 class SeqOneByteString: public SeqString {
8791 static const bool kHasOneByteEncoding = true;
8793 // Dispatched behavior.
8794 inline uint16_t SeqOneByteStringGet(int index);
8795 inline void SeqOneByteStringSet(int index, uint16_t value);
8797 // Get the address of the characters in this string.
8798 inline Address GetCharsAddress();
8800 inline uint8_t* GetChars();
8802 DECLARE_CAST(SeqOneByteString)
8804 // Garbage collection support. This method is called by the
8805 // garbage collector to compute the actual size of an OneByteString
8807 inline int SeqOneByteStringSize(InstanceType instance_type);
8809 // Computes the size for an OneByteString instance of a given length.
8810 static int SizeFor(int length) {
8811 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8814 // Maximal memory usage for a single sequential one-byte string.
8815 static const int kMaxSize = 512 * MB - 1;
8816 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8819 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8823 // The TwoByteString class captures sequential unicode string objects.
8824 // Each character in the TwoByteString is a two-byte uint16_t.
8825 class SeqTwoByteString: public SeqString {
8827 static const bool kHasOneByteEncoding = false;
8829 // Dispatched behavior.
8830 inline uint16_t SeqTwoByteStringGet(int index);
8831 inline void SeqTwoByteStringSet(int index, uint16_t value);
8833 // Get the address of the characters in this string.
8834 inline Address GetCharsAddress();
8836 inline uc16* GetChars();
8839 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8841 DECLARE_CAST(SeqTwoByteString)
8843 // Garbage collection support. This method is called by the
8844 // garbage collector to compute the actual size of a TwoByteString
8846 inline int SeqTwoByteStringSize(InstanceType instance_type);
8848 // Computes the size for a TwoByteString instance of a given length.
8849 static int SizeFor(int length) {
8850 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8853 // Maximal memory usage for a single sequential two-byte string.
8854 static const int kMaxSize = 512 * MB - 1;
8855 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8856 String::kMaxLength);
8859 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8863 // The ConsString class describes string values built by using the
8864 // addition operator on strings. A ConsString is a pair where the
8865 // first and second components are pointers to other string values.
8866 // One or both components of a ConsString can be pointers to other
8867 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8868 // are non-ConsString string values. The string value represented by
8869 // a ConsString can be obtained by concatenating the leaf string
8870 // values in a left-to-right depth-first traversal of the tree.
8871 class ConsString: public String {
8873 // First string of the cons cell.
8874 inline String* first();
8875 // Doesn't check that the result is a string, even in debug mode. This is
8876 // useful during GC where the mark bits confuse the checks.
8877 inline Object* unchecked_first();
8878 inline void set_first(String* first,
8879 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8881 // Second string of the cons cell.
8882 inline String* second();
8883 // Doesn't check that the result is a string, even in debug mode. This is
8884 // useful during GC where the mark bits confuse the checks.
8885 inline Object* unchecked_second();
8886 inline void set_second(String* second,
8887 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8889 // Dispatched behavior.
8890 uint16_t ConsStringGet(int index);
8892 DECLARE_CAST(ConsString)
8894 // Layout description.
8895 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8896 static const int kSecondOffset = kFirstOffset + kPointerSize;
8897 static const int kSize = kSecondOffset + kPointerSize;
8899 // Minimum length for a cons string.
8900 static const int kMinLength = 13;
8902 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8905 DECLARE_VERIFIER(ConsString)
8908 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8912 // The Sliced String class describes strings that are substrings of another
8913 // sequential string. The motivation is to save time and memory when creating
8914 // a substring. A Sliced String is described as a pointer to the parent,
8915 // the offset from the start of the parent string and the length. Using
8916 // a Sliced String therefore requires unpacking of the parent string and
8917 // adding the offset to the start address. A substring of a Sliced String
8918 // are not nested since the double indirection is simplified when creating
8919 // such a substring.
8920 // Currently missing features are:
8921 // - handling externalized parent strings
8922 // - external strings as parent
8923 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8924 class SlicedString: public String {
8926 inline String* parent();
8927 inline void set_parent(String* parent,
8928 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8929 inline int offset() const;
8930 inline void set_offset(int offset);
8932 // Dispatched behavior.
8933 uint16_t SlicedStringGet(int index);
8935 DECLARE_CAST(SlicedString)
8937 // Layout description.
8938 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8939 static const int kOffsetOffset = kParentOffset + kPointerSize;
8940 static const int kSize = kOffsetOffset + kPointerSize;
8942 // Minimum length for a sliced string.
8943 static const int kMinLength = 13;
8945 typedef FixedBodyDescriptor<kParentOffset,
8946 kOffsetOffset + kPointerSize, kSize>
8949 DECLARE_VERIFIER(SlicedString)
8952 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8956 // The ExternalString class describes string values that are backed by
8957 // a string resource that lies outside the V8 heap. ExternalStrings
8958 // consist of the length field common to all strings, a pointer to the
8959 // external resource. It is important to ensure (externally) that the
8960 // resource is not deallocated while the ExternalString is live in the
8963 // The API expects that all ExternalStrings are created through the
8964 // API. Therefore, ExternalStrings should not be used internally.
8965 class ExternalString: public String {
8967 DECLARE_CAST(ExternalString)
8969 // Layout description.
8970 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8971 static const int kShortSize = kResourceOffset + kPointerSize;
8972 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8973 static const int kSize = kResourceDataOffset + kPointerSize;
8975 static const int kMaxShortLength =
8976 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8978 // Return whether external string is short (data pointer is not cached).
8979 inline bool is_short();
8981 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8984 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8988 // The ExternalOneByteString class is an external string backed by an
8990 class ExternalOneByteString : public ExternalString {
8992 static const bool kHasOneByteEncoding = true;
8994 typedef v8::String::ExternalOneByteStringResource Resource;
8996 // The underlying resource.
8997 inline const Resource* resource();
8998 inline void set_resource(const Resource* buffer);
9000 // Update the pointer cache to the external character array.
9001 // The cached pointer is always valid, as the external character array does =
9002 // not move during lifetime. Deserialization is the only exception, after
9003 // which the pointer cache has to be refreshed.
9004 inline void update_data_cache();
9006 inline const uint8_t* GetChars();
9008 // Dispatched behavior.
9009 inline uint16_t ExternalOneByteStringGet(int index);
9011 DECLARE_CAST(ExternalOneByteString)
9013 // Garbage collection support.
9014 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9016 template <typename StaticVisitor>
9017 inline void ExternalOneByteStringIterateBody();
9020 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9024 // The ExternalTwoByteString class is an external string backed by a UTF-16
9026 class ExternalTwoByteString: public ExternalString {
9028 static const bool kHasOneByteEncoding = false;
9030 typedef v8::String::ExternalStringResource Resource;
9032 // The underlying string resource.
9033 inline const Resource* resource();
9034 inline void set_resource(const Resource* buffer);
9036 // Update the pointer cache to the external character array.
9037 // The cached pointer is always valid, as the external character array does =
9038 // not move during lifetime. Deserialization is the only exception, after
9039 // which the pointer cache has to be refreshed.
9040 inline void update_data_cache();
9042 inline const uint16_t* GetChars();
9044 // Dispatched behavior.
9045 inline uint16_t ExternalTwoByteStringGet(int index);
9048 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9050 DECLARE_CAST(ExternalTwoByteString)
9052 // Garbage collection support.
9053 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9055 template<typename StaticVisitor>
9056 inline void ExternalTwoByteStringIterateBody();
9059 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9063 // Utility superclass for stack-allocated objects that must be updated
9064 // on gc. It provides two ways for the gc to update instances, either
9065 // iterating or updating after gc.
9066 class Relocatable BASE_EMBEDDED {
9068 explicit inline Relocatable(Isolate* isolate);
9069 inline virtual ~Relocatable();
9070 virtual void IterateInstance(ObjectVisitor* v) { }
9071 virtual void PostGarbageCollection() { }
9073 static void PostGarbageCollectionProcessing(Isolate* isolate);
9074 static int ArchiveSpacePerThread();
9075 static char* ArchiveState(Isolate* isolate, char* to);
9076 static char* RestoreState(Isolate* isolate, char* from);
9077 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9078 static void Iterate(ObjectVisitor* v, Relocatable* top);
9079 static char* Iterate(ObjectVisitor* v, char* t);
9087 // A flat string reader provides random access to the contents of a
9088 // string independent of the character width of the string. The handle
9089 // must be valid as long as the reader is being used.
9090 class FlatStringReader : public Relocatable {
9092 FlatStringReader(Isolate* isolate, Handle<String> str);
9093 FlatStringReader(Isolate* isolate, Vector<const char> input);
9094 void PostGarbageCollection();
9095 inline uc32 Get(int index);
9096 template <typename Char>
9097 inline Char Get(int index);
9098 int length() { return length_; }
9107 // This maintains an off-stack representation of the stack frames required
9108 // to traverse a ConsString, allowing an entirely iterative and restartable
9109 // traversal of the entire string
9110 class ConsStringIterator {
9112 inline ConsStringIterator() {}
9113 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9114 Reset(cons_string, offset);
9116 inline void Reset(ConsString* cons_string, int offset = 0) {
9118 // Next will always return NULL.
9119 if (cons_string == NULL) return;
9120 Initialize(cons_string, offset);
9122 // Returns NULL when complete.
9123 inline String* Next(int* offset_out) {
9125 if (depth_ == 0) return NULL;
9126 return Continue(offset_out);
9130 static const int kStackSize = 32;
9131 // Use a mask instead of doing modulo operations for stack wrapping.
9132 static const int kDepthMask = kStackSize-1;
9133 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9134 static inline int OffsetForDepth(int depth);
9136 inline void PushLeft(ConsString* string);
9137 inline void PushRight(ConsString* string);
9138 inline void AdjustMaximumDepth();
9140 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9141 void Initialize(ConsString* cons_string, int offset);
9142 String* Continue(int* offset_out);
9143 String* NextLeaf(bool* blew_stack);
9144 String* Search(int* offset_out);
9146 // Stack must always contain only frames for which right traversal
9147 // has not yet been performed.
9148 ConsString* frames_[kStackSize];
9153 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9157 class StringCharacterStream {
9159 inline StringCharacterStream(String* string,
9161 inline uint16_t GetNext();
9162 inline bool HasMore();
9163 inline void Reset(String* string, int offset = 0);
9164 inline void VisitOneByteString(const uint8_t* chars, int length);
9165 inline void VisitTwoByteString(const uint16_t* chars, int length);
9168 ConsStringIterator iter_;
9171 const uint8_t* buffer8_;
9172 const uint16_t* buffer16_;
9174 const uint8_t* end_;
9175 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9179 template <typename T>
9180 class VectorIterator {
9182 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9183 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9184 T GetNext() { return data_[index_++]; }
9185 bool has_more() { return index_ < data_.length(); }
9187 Vector<const T> data_;
9192 // The Oddball describes objects null, undefined, true, and false.
9193 class Oddball: public HeapObject {
9195 // [to_string]: Cached to_string computed at startup.
9196 DECL_ACCESSORS(to_string, String)
9198 // [to_number]: Cached to_number computed at startup.
9199 DECL_ACCESSORS(to_number, Object)
9201 inline byte kind() const;
9202 inline void set_kind(byte kind);
9204 DECLARE_CAST(Oddball)
9206 // Dispatched behavior.
9207 DECLARE_VERIFIER(Oddball)
9209 // Initialize the fields.
9210 static void Initialize(Isolate* isolate,
9211 Handle<Oddball> oddball,
9212 const char* to_string,
9213 Handle<Object> to_number,
9216 // Layout description.
9217 static const int kToStringOffset = HeapObject::kHeaderSize;
9218 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9219 static const int kKindOffset = kToNumberOffset + kPointerSize;
9220 static const int kSize = kKindOffset + kPointerSize;
9222 static const byte kFalse = 0;
9223 static const byte kTrue = 1;
9224 static const byte kNotBooleanMask = ~1;
9225 static const byte kTheHole = 2;
9226 static const byte kNull = 3;
9227 static const byte kArgumentMarker = 4;
9228 static const byte kUndefined = 5;
9229 static const byte kUninitialized = 6;
9230 static const byte kOther = 7;
9231 static const byte kException = 8;
9233 typedef FixedBodyDescriptor<kToStringOffset,
9234 kToNumberOffset + kPointerSize,
9235 kSize> BodyDescriptor;
9237 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9238 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9239 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9242 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9246 class Cell: public HeapObject {
9248 // [value]: value of the cell.
9249 DECL_ACCESSORS(value, Object)
9253 static inline Cell* FromValueAddress(Address value) {
9254 Object* result = FromAddress(value - kValueOffset);
9255 return static_cast<Cell*>(result);
9258 inline Address ValueAddress() {
9259 return address() + kValueOffset;
9262 // Dispatched behavior.
9263 DECLARE_PRINTER(Cell)
9264 DECLARE_VERIFIER(Cell)
9266 // Layout description.
9267 static const int kValueOffset = HeapObject::kHeaderSize;
9268 static const int kSize = kValueOffset + kPointerSize;
9270 typedef FixedBodyDescriptor<kValueOffset,
9271 kValueOffset + kPointerSize,
9272 kSize> BodyDescriptor;
9275 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9279 class PropertyCell : public HeapObject {
9281 // [property_details]: details of the global property.
9282 DECL_ACCESSORS(property_details_raw, Object)
9283 // [value]: value of the global property.
9284 DECL_ACCESSORS(value, Object)
9285 // [dependent_code]: dependent code that depends on the type of the global
9287 DECL_ACCESSORS(dependent_code, DependentCode)
9289 PropertyDetails property_details() {
9290 return PropertyDetails(Smi::cast(property_details_raw()));
9293 void set_property_details(PropertyDetails details) {
9294 set_property_details_raw(details.AsSmi());
9297 PropertyCellConstantType GetConstantType();
9299 // Computes the new type of the cell's contents for the given value, but
9300 // without actually modifying the details.
9301 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9302 Handle<Object> value,
9303 PropertyDetails details);
9304 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9305 Handle<Object> value, PropertyDetails details);
9307 static Handle<PropertyCell> InvalidateEntry(
9308 Handle<GlobalDictionary> dictionary, int entry);
9310 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9311 Handle<Object> new_value);
9313 DECLARE_CAST(PropertyCell)
9315 // Dispatched behavior.
9316 DECLARE_PRINTER(PropertyCell)
9317 DECLARE_VERIFIER(PropertyCell)
9319 // Layout description.
9320 static const int kDetailsOffset = HeapObject::kHeaderSize;
9321 static const int kValueOffset = kDetailsOffset + kPointerSize;
9322 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9323 static const int kSize = kDependentCodeOffset + kPointerSize;
9325 static const int kPointerFieldsBeginOffset = kValueOffset;
9326 static const int kPointerFieldsEndOffset = kSize;
9328 typedef FixedBodyDescriptor<kValueOffset,
9330 kSize> BodyDescriptor;
9333 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9337 class WeakCell : public HeapObject {
9339 inline Object* value() const;
9341 // This should not be called by anyone except GC.
9342 inline void clear();
9344 // This should not be called by anyone except allocator.
9345 inline void initialize(HeapObject* value);
9347 inline bool cleared() const;
9349 DECL_ACCESSORS(next, Object)
9351 inline void clear_next(Heap* heap);
9353 inline bool next_cleared();
9355 DECLARE_CAST(WeakCell)
9357 DECLARE_PRINTER(WeakCell)
9358 DECLARE_VERIFIER(WeakCell)
9360 // Layout description.
9361 static const int kValueOffset = HeapObject::kHeaderSize;
9362 static const int kNextOffset = kValueOffset + kPointerSize;
9363 static const int kSize = kNextOffset + kPointerSize;
9365 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9368 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9372 // The JSProxy describes EcmaScript Harmony proxies
9373 class JSProxy: public JSReceiver {
9375 // [handler]: The handler property.
9376 DECL_ACCESSORS(handler, Object)
9378 // [hash]: The hash code property (undefined if not initialized yet).
9379 DECL_ACCESSORS(hash, Object)
9381 DECLARE_CAST(JSProxy)
9383 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9384 Handle<JSProxy> proxy,
9385 Handle<Object> receiver,
9388 // If the handler defines an accessor property with a setter, invoke it.
9389 // If it defines an accessor property without a setter, or a data property
9390 // that is read-only, throw. In all these cases set '*done' to true,
9391 // otherwise set it to false.
9393 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9394 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9395 Handle<Object> value, LanguageMode language_mode, bool* done);
9397 MUST_USE_RESULT static Maybe<PropertyAttributes>
9398 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9399 Handle<Object> receiver,
9401 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9402 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9403 Handle<Object> value, LanguageMode language_mode);
9405 // Turn the proxy into an (empty) JSObject.
9406 static void Fix(Handle<JSProxy> proxy);
9408 // Initializes the body after the handler slot.
9409 inline void InitializeBody(int object_size, Object* value);
9411 // Invoke a trap by name. If the trap does not exist on this's handler,
9412 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9413 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9414 Handle<JSProxy> proxy,
9416 Handle<Object> derived_trap,
9418 Handle<Object> args[]);
9420 // Dispatched behavior.
9421 DECLARE_PRINTER(JSProxy)
9422 DECLARE_VERIFIER(JSProxy)
9424 // Layout description. We add padding so that a proxy has the same
9425 // size as a virgin JSObject. This is essential for becoming a JSObject
9427 static const int kHandlerOffset = HeapObject::kHeaderSize;
9428 static const int kHashOffset = kHandlerOffset + kPointerSize;
9429 static const int kPaddingOffset = kHashOffset + kPointerSize;
9430 static const int kSize = JSObject::kHeaderSize;
9431 static const int kHeaderSize = kPaddingOffset;
9432 static const int kPaddingSize = kSize - kPaddingOffset;
9434 STATIC_ASSERT(kPaddingSize >= 0);
9436 typedef FixedBodyDescriptor<kHandlerOffset,
9438 kSize> BodyDescriptor;
9441 friend class JSReceiver;
9443 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9444 Handle<JSProxy> proxy, Handle<Name> name);
9446 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9447 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9449 MUST_USE_RESULT Object* GetIdentityHash();
9451 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9453 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9457 class JSFunctionProxy: public JSProxy {
9459 // [call_trap]: The call trap.
9460 DECL_ACCESSORS(call_trap, Object)
9462 // [construct_trap]: The construct trap.
9463 DECL_ACCESSORS(construct_trap, Object)
9465 DECLARE_CAST(JSFunctionProxy)
9467 // Dispatched behavior.
9468 DECLARE_PRINTER(JSFunctionProxy)
9469 DECLARE_VERIFIER(JSFunctionProxy)
9471 // Layout description.
9472 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9473 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9474 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9475 static const int kSize = JSFunction::kSize;
9476 static const int kPaddingSize = kSize - kPaddingOffset;
9478 STATIC_ASSERT(kPaddingSize >= 0);
9480 typedef FixedBodyDescriptor<kHandlerOffset,
9481 kConstructTrapOffset + kPointerSize,
9482 kSize> BodyDescriptor;
9485 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9489 class JSCollection : public JSObject {
9491 // [table]: the backing hash table
9492 DECL_ACCESSORS(table, Object)
9494 static const int kTableOffset = JSObject::kHeaderSize;
9495 static const int kSize = kTableOffset + kPointerSize;
9498 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9502 // The JSSet describes EcmaScript Harmony sets
9503 class JSSet : public JSCollection {
9507 // Dispatched behavior.
9508 DECLARE_PRINTER(JSSet)
9509 DECLARE_VERIFIER(JSSet)
9512 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9516 // The JSMap describes EcmaScript Harmony maps
9517 class JSMap : public JSCollection {
9521 // Dispatched behavior.
9522 DECLARE_PRINTER(JSMap)
9523 DECLARE_VERIFIER(JSMap)
9526 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9530 // OrderedHashTableIterator is an iterator that iterates over the keys and
9531 // values of an OrderedHashTable.
9533 // The iterator has a reference to the underlying OrderedHashTable data,
9534 // [table], as well as the current [index] the iterator is at.
9536 // When the OrderedHashTable is rehashed it adds a reference from the old table
9537 // to the new table as well as storing enough data about the changes so that the
9538 // iterator [index] can be adjusted accordingly.
9540 // When the [Next] result from the iterator is requested, the iterator checks if
9541 // there is a newer table that it needs to transition to.
9542 template<class Derived, class TableType>
9543 class OrderedHashTableIterator: public JSObject {
9545 // [table]: the backing hash table mapping keys to values.
9546 DECL_ACCESSORS(table, Object)
9548 // [index]: The index into the data table.
9549 DECL_ACCESSORS(index, Object)
9551 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9552 DECL_ACCESSORS(kind, Object)
9555 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9558 static const int kTableOffset = JSObject::kHeaderSize;
9559 static const int kIndexOffset = kTableOffset + kPointerSize;
9560 static const int kKindOffset = kIndexOffset + kPointerSize;
9561 static const int kSize = kKindOffset + kPointerSize;
9569 // Whether the iterator has more elements. This needs to be called before
9570 // calling |CurrentKey| and/or |CurrentValue|.
9573 // Move the index forward one.
9575 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9578 // Populates the array with the next key and value and then moves the iterator
9580 // This returns the |kind| or 0 if the iterator is already at the end.
9581 Smi* Next(JSArray* value_array);
9583 // Returns the current key of the iterator. This should only be called when
9584 // |HasMore| returns true.
9585 inline Object* CurrentKey();
9588 // Transitions the iterator to the non obsolete backing store. This is a NOP
9589 // if the [table] is not obsolete.
9592 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9596 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9599 // Dispatched behavior.
9600 DECLARE_PRINTER(JSSetIterator)
9601 DECLARE_VERIFIER(JSSetIterator)
9603 DECLARE_CAST(JSSetIterator)
9605 // Called by |Next| to populate the array. This allows the subclasses to
9606 // populate the array differently.
9607 inline void PopulateValueArray(FixedArray* array);
9610 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9614 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9617 // Dispatched behavior.
9618 DECLARE_PRINTER(JSMapIterator)
9619 DECLARE_VERIFIER(JSMapIterator)
9621 DECLARE_CAST(JSMapIterator)
9623 // Called by |Next| to populate the array. This allows the subclasses to
9624 // populate the array differently.
9625 inline void PopulateValueArray(FixedArray* array);
9628 // Returns the current value of the iterator. This should only be called when
9629 // |HasMore| returns true.
9630 inline Object* CurrentValue();
9632 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9636 // Base class for both JSWeakMap and JSWeakSet
9637 class JSWeakCollection: public JSObject {
9639 // [table]: the backing hash table mapping keys to values.
9640 DECL_ACCESSORS(table, Object)
9642 // [next]: linked list of encountered weak maps during GC.
9643 DECL_ACCESSORS(next, Object)
9645 static const int kTableOffset = JSObject::kHeaderSize;
9646 static const int kNextOffset = kTableOffset + kPointerSize;
9647 static const int kSize = kNextOffset + kPointerSize;
9650 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9654 // The JSWeakMap describes EcmaScript Harmony weak maps
9655 class JSWeakMap: public JSWeakCollection {
9657 DECLARE_CAST(JSWeakMap)
9659 // Dispatched behavior.
9660 DECLARE_PRINTER(JSWeakMap)
9661 DECLARE_VERIFIER(JSWeakMap)
9664 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9668 // The JSWeakSet describes EcmaScript Harmony weak sets
9669 class JSWeakSet: public JSWeakCollection {
9671 DECLARE_CAST(JSWeakSet)
9673 // Dispatched behavior.
9674 DECLARE_PRINTER(JSWeakSet)
9675 DECLARE_VERIFIER(JSWeakSet)
9678 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9682 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9683 enum class SharedFlag { kNotShared, kShared };
9686 class JSArrayBuffer: public JSObject {
9688 // [backing_store]: backing memory for this array
9689 DECL_ACCESSORS(backing_store, void)
9691 // [byte_length]: length in bytes
9692 DECL_ACCESSORS(byte_length, Object)
9694 inline uint32_t bit_field() const;
9695 inline void set_bit_field(uint32_t bits);
9697 inline bool is_external();
9698 inline void set_is_external(bool value);
9700 inline bool is_neuterable();
9701 inline void set_is_neuterable(bool value);
9703 inline bool was_neutered();
9704 inline void set_was_neutered(bool value);
9706 inline bool is_shared();
9707 inline void set_is_shared(bool value);
9709 DECLARE_CAST(JSArrayBuffer)
9713 // Dispatched behavior.
9714 DECLARE_PRINTER(JSArrayBuffer)
9715 DECLARE_VERIFIER(JSArrayBuffer)
9717 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9718 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9719 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9720 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9721 static const int kBitFieldOffset = kBitFieldSlot;
9723 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9725 static const int kSize = kBitFieldSlot + kPointerSize;
9727 static const int kSizeWithInternalFields =
9728 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9730 class IsExternal : public BitField<bool, 1, 1> {};
9731 class IsNeuterable : public BitField<bool, 2, 1> {};
9732 class WasNeutered : public BitField<bool, 3, 1> {};
9733 class IsShared : public BitField<bool, 4, 1> {};
9736 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9740 class JSArrayBufferView: public JSObject {
9742 // [buffer]: ArrayBuffer that this typed array views.
9743 DECL_ACCESSORS(buffer, Object)
9745 // [byte_offset]: offset of typed array in bytes.
9746 DECL_ACCESSORS(byte_offset, Object)
9748 // [byte_length]: length of typed array in bytes.
9749 DECL_ACCESSORS(byte_length, Object)
9751 DECLARE_CAST(JSArrayBufferView)
9753 DECLARE_VERIFIER(JSArrayBufferView)
9755 inline bool WasNeutered() const;
9757 static const int kBufferOffset = JSObject::kHeaderSize;
9758 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9759 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9760 static const int kViewSize = kByteLengthOffset + kPointerSize;
9764 DECL_ACCESSORS(raw_byte_offset, Object)
9765 DECL_ACCESSORS(raw_byte_length, Object)
9768 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9772 class JSTypedArray: public JSArrayBufferView {
9774 // [length]: length of typed array in elements.
9775 DECL_ACCESSORS(length, Object)
9776 inline uint32_t length_value() const;
9778 DECLARE_CAST(JSTypedArray)
9780 ExternalArrayType type();
9781 size_t element_size();
9783 Handle<JSArrayBuffer> GetBuffer();
9785 // Dispatched behavior.
9786 DECLARE_PRINTER(JSTypedArray)
9787 DECLARE_VERIFIER(JSTypedArray)
9789 static const int kLengthOffset = kViewSize + kPointerSize;
9790 static const int kSize = kLengthOffset + kPointerSize;
9792 static const int kSizeWithInternalFields =
9793 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9796 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9797 Handle<JSTypedArray> typed_array);
9799 DECL_ACCESSORS(raw_length, Object)
9802 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9806 class JSDataView: public JSArrayBufferView {
9808 DECLARE_CAST(JSDataView)
9810 // Dispatched behavior.
9811 DECLARE_PRINTER(JSDataView)
9812 DECLARE_VERIFIER(JSDataView)
9814 static const int kSize = kViewSize;
9816 static const int kSizeWithInternalFields =
9817 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9820 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9824 // Foreign describes objects pointing from JavaScript to C structures.
9825 class Foreign: public HeapObject {
9827 // [address]: field containing the address.
9828 inline Address foreign_address();
9829 inline void set_foreign_address(Address value);
9831 DECLARE_CAST(Foreign)
9833 // Dispatched behavior.
9834 inline void ForeignIterateBody(ObjectVisitor* v);
9836 template<typename StaticVisitor>
9837 inline void ForeignIterateBody();
9839 // Dispatched behavior.
9840 DECLARE_PRINTER(Foreign)
9841 DECLARE_VERIFIER(Foreign)
9843 // Layout description.
9845 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9846 static const int kSize = kForeignAddressOffset + kPointerSize;
9848 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9851 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9855 // The JSArray describes JavaScript Arrays
9856 // Such an array can be in one of two modes:
9857 // - fast, backing storage is a FixedArray and length <= elements.length();
9858 // Please note: push and pop can be used to grow and shrink the array.
9859 // - slow, backing storage is a HashTable with numbers as keys.
9860 class JSArray: public JSObject {
9862 // [length]: The length property.
9863 DECL_ACCESSORS(length, Object)
9865 // Overload the length setter to skip write barrier when the length
9866 // is set to a smi. This matches the set function on FixedArray.
9867 inline void set_length(Smi* length);
9869 static bool HasReadOnlyLength(Handle<JSArray> array);
9870 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9871 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9873 // Initialize the array with the given capacity. The function may
9874 // fail due to out-of-memory situations, but only if the requested
9875 // capacity is non-zero.
9876 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9878 // If the JSArray has fast elements, and new_length would result in
9879 // normalization, returns true.
9880 bool SetLengthWouldNormalize(uint32_t new_length);
9881 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9883 // Initializes the array to a certain length.
9884 inline bool AllowsSetLength();
9886 static void SetLength(Handle<JSArray> array, uint32_t length);
9887 // Same as above but will also queue splice records if |array| is observed.
9888 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9891 // Set the content of the array to the content of storage.
9892 static inline void SetContent(Handle<JSArray> array,
9893 Handle<FixedArrayBase> storage);
9895 DECLARE_CAST(JSArray)
9897 // Dispatched behavior.
9898 DECLARE_PRINTER(JSArray)
9899 DECLARE_VERIFIER(JSArray)
9901 // Number of element slots to pre-allocate for an empty array.
9902 static const int kPreallocatedArrayElements = 4;
9904 // Layout description.
9905 static const int kLengthOffset = JSObject::kHeaderSize;
9906 static const int kSize = kLengthOffset + kPointerSize;
9909 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9913 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9914 Handle<Map> initial_map);
9917 // JSRegExpResult is just a JSArray with a specific initial map.
9918 // This initial map adds in-object properties for "index" and "input"
9919 // properties, as assigned by RegExp.prototype.exec, which allows
9920 // faster creation of RegExp exec results.
9921 // This class just holds constants used when creating the result.
9922 // After creation the result must be treated as a JSArray in all regards.
9923 class JSRegExpResult: public JSArray {
9925 // Offsets of object fields.
9926 static const int kIndexOffset = JSArray::kSize;
9927 static const int kInputOffset = kIndexOffset + kPointerSize;
9928 static const int kSize = kInputOffset + kPointerSize;
9929 // Indices of in-object properties.
9930 static const int kIndexIndex = 0;
9931 static const int kInputIndex = 1;
9933 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9937 class AccessorInfo: public Struct {
9939 DECL_ACCESSORS(name, Object)
9940 DECL_ACCESSORS(flag, Smi)
9941 DECL_ACCESSORS(expected_receiver_type, Object)
9943 inline bool all_can_read();
9944 inline void set_all_can_read(bool value);
9946 inline bool all_can_write();
9947 inline void set_all_can_write(bool value);
9949 inline bool is_special_data_property();
9950 inline void set_is_special_data_property(bool value);
9952 inline PropertyAttributes property_attributes();
9953 inline void set_property_attributes(PropertyAttributes attributes);
9955 // Checks whether the given receiver is compatible with this accessor.
9956 static bool IsCompatibleReceiverMap(Isolate* isolate,
9957 Handle<AccessorInfo> info,
9959 inline bool IsCompatibleReceiver(Object* receiver);
9961 DECLARE_CAST(AccessorInfo)
9963 // Dispatched behavior.
9964 DECLARE_VERIFIER(AccessorInfo)
9966 // Append all descriptors to the array that are not already there.
9967 // Return number added.
9968 static int AppendUnique(Handle<Object> descriptors,
9969 Handle<FixedArray> array,
9970 int valid_descriptors);
9972 static const int kNameOffset = HeapObject::kHeaderSize;
9973 static const int kFlagOffset = kNameOffset + kPointerSize;
9974 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9975 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9978 inline bool HasExpectedReceiverType() {
9979 return expected_receiver_type()->IsFunctionTemplateInfo();
9981 // Bit positions in flag.
9982 static const int kAllCanReadBit = 0;
9983 static const int kAllCanWriteBit = 1;
9984 static const int kSpecialDataProperty = 2;
9985 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9987 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9991 // An accessor must have a getter, but can have no setter.
9993 // When setting a property, V8 searches accessors in prototypes.
9994 // If an accessor was found and it does not have a setter,
9995 // the request is ignored.
9997 // If the accessor in the prototype has the READ_ONLY property attribute, then
9998 // a new value is added to the derived object when the property is set.
9999 // This shadows the accessor in the prototype.
10000 class ExecutableAccessorInfo: public AccessorInfo {
10002 DECL_ACCESSORS(getter, Object)
10003 DECL_ACCESSORS(setter, Object)
10004 DECL_ACCESSORS(data, Object)
10006 DECLARE_CAST(ExecutableAccessorInfo)
10008 // Dispatched behavior.
10009 DECLARE_PRINTER(ExecutableAccessorInfo)
10010 DECLARE_VERIFIER(ExecutableAccessorInfo)
10012 static const int kGetterOffset = AccessorInfo::kSize;
10013 static const int kSetterOffset = kGetterOffset + kPointerSize;
10014 static const int kDataOffset = kSetterOffset + kPointerSize;
10015 static const int kSize = kDataOffset + kPointerSize;
10017 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10020 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10024 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10025 // accessor can either be
10026 // * a pointer to a JavaScript function or proxy: a real accessor
10027 // * undefined: considered an accessor by the spec, too, strangely enough
10028 // * the hole: an accessor which has not been set
10029 // * a pointer to a map: a transition used to ensure map sharing
10030 class AccessorPair: public Struct {
10032 DECL_ACCESSORS(getter, Object)
10033 DECL_ACCESSORS(setter, Object)
10035 DECLARE_CAST(AccessorPair)
10037 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10039 Object* get(AccessorComponent component) {
10040 return component == ACCESSOR_GETTER ? getter() : setter();
10043 void set(AccessorComponent component, Object* value) {
10044 if (component == ACCESSOR_GETTER) {
10051 // Note: Returns undefined instead in case of a hole.
10052 Object* GetComponent(AccessorComponent component);
10054 // Set both components, skipping arguments which are a JavaScript null.
10055 void SetComponents(Object* getter, Object* setter) {
10056 if (!getter->IsNull()) set_getter(getter);
10057 if (!setter->IsNull()) set_setter(setter);
10060 bool Equals(AccessorPair* pair) {
10061 return (this == pair) || pair->Equals(getter(), setter());
10064 bool Equals(Object* getter_value, Object* setter_value) {
10065 return (getter() == getter_value) && (setter() == setter_value);
10068 bool ContainsAccessor() {
10069 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10072 // Dispatched behavior.
10073 DECLARE_PRINTER(AccessorPair)
10074 DECLARE_VERIFIER(AccessorPair)
10076 static const int kGetterOffset = HeapObject::kHeaderSize;
10077 static const int kSetterOffset = kGetterOffset + kPointerSize;
10078 static const int kSize = kSetterOffset + kPointerSize;
10081 // Strangely enough, in addition to functions and harmony proxies, the spec
10082 // requires us to consider undefined as a kind of accessor, too:
10084 // Object.defineProperty(obj, "foo", {get: undefined});
10085 // assertTrue("foo" in obj);
10086 bool IsJSAccessor(Object* obj) {
10087 return obj->IsSpecFunction() || obj->IsUndefined();
10090 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10094 class AccessCheckInfo: public Struct {
10096 DECL_ACCESSORS(named_callback, Object)
10097 DECL_ACCESSORS(indexed_callback, Object)
10098 DECL_ACCESSORS(data, Object)
10100 DECLARE_CAST(AccessCheckInfo)
10102 // Dispatched behavior.
10103 DECLARE_PRINTER(AccessCheckInfo)
10104 DECLARE_VERIFIER(AccessCheckInfo)
10106 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10107 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10108 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10109 static const int kSize = kDataOffset + kPointerSize;
10112 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10116 class InterceptorInfo: public Struct {
10118 DECL_ACCESSORS(getter, Object)
10119 DECL_ACCESSORS(setter, Object)
10120 DECL_ACCESSORS(query, Object)
10121 DECL_ACCESSORS(deleter, Object)
10122 DECL_ACCESSORS(enumerator, Object)
10123 DECL_ACCESSORS(data, Object)
10124 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10125 DECL_BOOLEAN_ACCESSORS(all_can_read)
10126 DECL_BOOLEAN_ACCESSORS(non_masking)
10128 inline int flags() const;
10129 inline void set_flags(int flags);
10131 DECLARE_CAST(InterceptorInfo)
10133 // Dispatched behavior.
10134 DECLARE_PRINTER(InterceptorInfo)
10135 DECLARE_VERIFIER(InterceptorInfo)
10137 static const int kGetterOffset = HeapObject::kHeaderSize;
10138 static const int kSetterOffset = kGetterOffset + kPointerSize;
10139 static const int kQueryOffset = kSetterOffset + kPointerSize;
10140 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10141 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10142 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10143 static const int kFlagsOffset = kDataOffset + kPointerSize;
10144 static const int kSize = kFlagsOffset + kPointerSize;
10146 static const int kCanInterceptSymbolsBit = 0;
10147 static const int kAllCanReadBit = 1;
10148 static const int kNonMasking = 2;
10151 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10155 class CallHandlerInfo: public Struct {
10157 DECL_ACCESSORS(callback, Object)
10158 DECL_ACCESSORS(data, Object)
10160 DECLARE_CAST(CallHandlerInfo)
10162 // Dispatched behavior.
10163 DECLARE_PRINTER(CallHandlerInfo)
10164 DECLARE_VERIFIER(CallHandlerInfo)
10166 static const int kCallbackOffset = HeapObject::kHeaderSize;
10167 static const int kDataOffset = kCallbackOffset + kPointerSize;
10168 static const int kSize = kDataOffset + kPointerSize;
10171 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10175 class TemplateInfo: public Struct {
10177 DECL_ACCESSORS(tag, Object)
10178 inline int number_of_properties() const;
10179 inline void set_number_of_properties(int value);
10180 DECL_ACCESSORS(property_list, Object)
10181 DECL_ACCESSORS(property_accessors, Object)
10183 DECLARE_VERIFIER(TemplateInfo)
10185 static const int kTagOffset = HeapObject::kHeaderSize;
10186 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10187 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10188 static const int kPropertyAccessorsOffset =
10189 kPropertyListOffset + kPointerSize;
10190 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10193 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10197 class FunctionTemplateInfo: public TemplateInfo {
10199 DECL_ACCESSORS(serial_number, Object)
10200 DECL_ACCESSORS(call_code, Object)
10201 DECL_ACCESSORS(prototype_template, Object)
10202 DECL_ACCESSORS(parent_template, Object)
10203 DECL_ACCESSORS(named_property_handler, Object)
10204 DECL_ACCESSORS(indexed_property_handler, Object)
10205 DECL_ACCESSORS(instance_template, Object)
10206 DECL_ACCESSORS(class_name, Object)
10207 DECL_ACCESSORS(signature, Object)
10208 DECL_ACCESSORS(instance_call_handler, Object)
10209 DECL_ACCESSORS(access_check_info, Object)
10210 DECL_ACCESSORS(flag, Smi)
10212 inline int length() const;
10213 inline void set_length(int value);
10215 // Following properties use flag bits.
10216 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10217 DECL_BOOLEAN_ACCESSORS(undetectable)
10218 // If the bit is set, object instances created by this function
10219 // requires access check.
10220 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10221 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10222 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10223 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10224 DECL_BOOLEAN_ACCESSORS(instantiated)
10225 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10227 DECLARE_CAST(FunctionTemplateInfo)
10229 // Dispatched behavior.
10230 DECLARE_PRINTER(FunctionTemplateInfo)
10231 DECLARE_VERIFIER(FunctionTemplateInfo)
10233 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10234 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10235 static const int kPrototypeTemplateOffset =
10236 kCallCodeOffset + kPointerSize;
10237 static const int kParentTemplateOffset =
10238 kPrototypeTemplateOffset + kPointerSize;
10239 static const int kNamedPropertyHandlerOffset =
10240 kParentTemplateOffset + kPointerSize;
10241 static const int kIndexedPropertyHandlerOffset =
10242 kNamedPropertyHandlerOffset + kPointerSize;
10243 static const int kInstanceTemplateOffset =
10244 kIndexedPropertyHandlerOffset + kPointerSize;
10245 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10246 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10247 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10248 static const int kAccessCheckInfoOffset =
10249 kInstanceCallHandlerOffset + kPointerSize;
10250 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10251 static const int kLengthOffset = kFlagOffset + kPointerSize;
10252 static const int kSize = kLengthOffset + kPointerSize;
10254 // Returns true if |object| is an instance of this function template.
10255 bool IsTemplateFor(Object* object);
10256 bool IsTemplateFor(Map* map);
10258 // Returns the holder JSObject if the function can legally be called with this
10259 // receiver. Returns Heap::null_value() if the call is illegal.
10260 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10263 // Bit position in the flag, from least significant bit position.
10264 static const int kHiddenPrototypeBit = 0;
10265 static const int kUndetectableBit = 1;
10266 static const int kNeedsAccessCheckBit = 2;
10267 static const int kReadOnlyPrototypeBit = 3;
10268 static const int kRemovePrototypeBit = 4;
10269 static const int kDoNotCacheBit = 5;
10270 static const int kInstantiatedBit = 6;
10271 static const int kAcceptAnyReceiver = 7;
10273 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10277 class ObjectTemplateInfo: public TemplateInfo {
10279 DECL_ACCESSORS(constructor, Object)
10280 DECL_ACCESSORS(internal_field_count, Object)
10282 DECLARE_CAST(ObjectTemplateInfo)
10284 // Dispatched behavior.
10285 DECLARE_PRINTER(ObjectTemplateInfo)
10286 DECLARE_VERIFIER(ObjectTemplateInfo)
10288 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10289 static const int kInternalFieldCountOffset =
10290 kConstructorOffset + kPointerSize;
10291 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10295 class TypeSwitchInfo: public Struct {
10297 DECL_ACCESSORS(types, Object)
10299 DECLARE_CAST(TypeSwitchInfo)
10301 // Dispatched behavior.
10302 DECLARE_PRINTER(TypeSwitchInfo)
10303 DECLARE_VERIFIER(TypeSwitchInfo)
10305 static const int kTypesOffset = Struct::kHeaderSize;
10306 static const int kSize = kTypesOffset + kPointerSize;
10310 // The DebugInfo class holds additional information for a function being
10312 class DebugInfo: public Struct {
10314 // The shared function info for the source being debugged.
10315 DECL_ACCESSORS(shared, SharedFunctionInfo)
10316 // Code object for the patched code. This code object is the code object
10317 // currently active for the function.
10318 DECL_ACCESSORS(code, Code)
10319 // Fixed array holding status information for each active break point.
10320 DECL_ACCESSORS(break_points, FixedArray)
10322 // Check if there is a break point at a code position.
10323 bool HasBreakPoint(int code_position);
10324 // Get the break point info object for a code position.
10325 Object* GetBreakPointInfo(int code_position);
10326 // Clear a break point.
10327 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10329 Handle<Object> break_point_object);
10330 // Set a break point.
10331 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10332 int source_position, int statement_position,
10333 Handle<Object> break_point_object);
10334 // Get the break point objects for a code position.
10335 Handle<Object> GetBreakPointObjects(int code_position);
10336 // Find the break point info holding this break point object.
10337 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10338 Handle<Object> break_point_object);
10339 // Get the number of break points for this function.
10340 int GetBreakPointCount();
10342 DECLARE_CAST(DebugInfo)
10344 // Dispatched behavior.
10345 DECLARE_PRINTER(DebugInfo)
10346 DECLARE_VERIFIER(DebugInfo)
10348 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10349 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10350 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10351 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10353 static const int kEstimatedNofBreakPointsInFunction = 16;
10356 static const int kNoBreakPointInfo = -1;
10358 // Lookup the index in the break_points array for a code position.
10359 int GetBreakPointInfoIndex(int code_position);
10361 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10365 // The BreakPointInfo class holds information for break points set in a
10366 // function. The DebugInfo object holds a BreakPointInfo object for each code
10367 // position with one or more break points.
10368 class BreakPointInfo: public Struct {
10370 // The position in the code for the break point.
10371 DECL_ACCESSORS(code_position, Smi)
10372 // The position in the source for the break position.
10373 DECL_ACCESSORS(source_position, Smi)
10374 // The position in the source for the last statement before this break
10376 DECL_ACCESSORS(statement_position, Smi)
10377 // List of related JavaScript break points.
10378 DECL_ACCESSORS(break_point_objects, Object)
10380 // Removes a break point.
10381 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10382 Handle<Object> break_point_object);
10383 // Set a break point.
10384 static void SetBreakPoint(Handle<BreakPointInfo> info,
10385 Handle<Object> break_point_object);
10386 // Check if break point info has this break point object.
10387 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10388 Handle<Object> break_point_object);
10389 // Get the number of break points for this code position.
10390 int GetBreakPointCount();
10392 DECLARE_CAST(BreakPointInfo)
10394 // Dispatched behavior.
10395 DECLARE_PRINTER(BreakPointInfo)
10396 DECLARE_VERIFIER(BreakPointInfo)
10398 static const int kCodePositionIndex = Struct::kHeaderSize;
10399 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10400 static const int kStatementPositionIndex =
10401 kSourcePositionIndex + kPointerSize;
10402 static const int kBreakPointObjectsIndex =
10403 kStatementPositionIndex + kPointerSize;
10404 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10407 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10411 #undef DECL_BOOLEAN_ACCESSORS
10412 #undef DECL_ACCESSORS
10413 #undef DECLARE_CAST
10414 #undef DECLARE_VERIFIER
10416 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10417 V(kStringTable, "string_table", "(Internalized strings)") \
10418 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10419 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10420 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10421 V(kInternalizedString, "internalized_string", "(Internal string)") \
10422 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10423 V(kTop, "top", "(Isolate)") \
10424 V(kRelocatable, "relocatable", "(Relocatable)") \
10425 V(kDebug, "debug", "(Debugger)") \
10426 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10427 V(kHandleScope, "handlescope", "(Handle scope)") \
10428 V(kBuiltins, "builtins", "(Builtins)") \
10429 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10430 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10431 V(kThreadManager, "threadmanager", "(Thread manager)") \
10432 V(kStrongRoots, "strong roots", "(Strong roots)") \
10433 V(kExtensions, "Extensions", "(Extensions)")
10435 class VisitorSynchronization : public AllStatic {
10437 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10439 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10442 #undef DECLARE_ENUM
10444 static const char* const kTags[kNumberOfSyncTags];
10445 static const char* const kTagNames[kNumberOfSyncTags];
10448 // Abstract base class for visiting, and optionally modifying, the
10449 // pointers contained in Objects. Used in GC and serialization/deserialization.
10450 class ObjectVisitor BASE_EMBEDDED {
10452 virtual ~ObjectVisitor() {}
10454 // Visits a contiguous arrays of pointers in the half-open range
10455 // [start, end). Any or all of the values may be modified on return.
10456 virtual void VisitPointers(Object** start, Object** end) = 0;
10458 // Handy shorthand for visiting a single pointer.
10459 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10461 // Visit weak next_code_link in Code object.
10462 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10464 // To allow lazy clearing of inline caches the visitor has
10465 // a rich interface for iterating over Code objects..
10467 // Visits a code target in the instruction stream.
10468 virtual void VisitCodeTarget(RelocInfo* rinfo);
10470 // Visits a code entry in a JS function.
10471 virtual void VisitCodeEntry(Address entry_address);
10473 // Visits a global property cell reference in the instruction stream.
10474 virtual void VisitCell(RelocInfo* rinfo);
10476 // Visits a runtime entry in the instruction stream.
10477 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10479 // Visits the resource of an one-byte or two-byte string.
10480 virtual void VisitExternalOneByteString(
10481 v8::String::ExternalOneByteStringResource** resource) {}
10482 virtual void VisitExternalTwoByteString(
10483 v8::String::ExternalStringResource** resource) {}
10485 // Visits a debug call target in the instruction stream.
10486 virtual void VisitDebugTarget(RelocInfo* rinfo);
10488 // Visits the byte sequence in a function's prologue that contains information
10489 // about the code's age.
10490 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10492 // Visit pointer embedded into a code object.
10493 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10495 // Visits an external reference embedded into a code object.
10496 virtual void VisitExternalReference(RelocInfo* rinfo);
10498 // Visits an external reference.
10499 virtual void VisitExternalReference(Address* p) {}
10501 // Visits an (encoded) internal reference.
10502 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10504 // Visits a handle that has an embedder-assigned class ID.
10505 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10507 // Intended for serialization/deserialization checking: insert, or
10508 // check for the presence of, a tag at this position in the stream.
10509 // Also used for marking up GC roots in heap snapshots.
10510 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10514 class StructBodyDescriptor : public
10515 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10517 static inline int SizeOf(Map* map, HeapObject* object) {
10518 return map->instance_size();
10523 // BooleanBit is a helper class for setting and getting a bit in an
10525 class BooleanBit : public AllStatic {
10527 static inline bool get(Smi* smi, int bit_position) {
10528 return get(smi->value(), bit_position);
10531 static inline bool get(int value, int bit_position) {
10532 return (value & (1 << bit_position)) != 0;
10535 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10536 return Smi::FromInt(set(smi->value(), bit_position, v));
10539 static inline int set(int value, int bit_position, bool v) {
10541 value |= (1 << bit_position);
10543 value &= ~(1 << bit_position);
10549 } } // namespace v8::internal
10551 #endif // V8_OBJECTS_H_