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
92 // - ScriptContextTable
103 // - ExternalOneByteString
104 // - ExternalTwoByteString
105 // - InternalizedString
106 // - SeqInternalizedString
107 // - SeqOneByteInternalizedString
108 // - SeqTwoByteInternalizedString
109 // - ConsInternalizedString
110 // - ExternalInternalizedString
111 // - ExternalOneByteInternalizedString
112 // - ExternalTwoByteInternalizedString
129 // - SharedFunctionInfo
133 // - ExecutableAccessorInfo
139 // - FunctionTemplateInfo
140 // - ObjectTemplateInfo
149 // Formats of Object*:
150 // Smi: [31 bit signed int] 0
151 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
156 enum KeyedAccessStoreMode {
158 STORE_TRANSITION_SMI_TO_OBJECT,
159 STORE_TRANSITION_SMI_TO_DOUBLE,
160 STORE_TRANSITION_DOUBLE_TO_OBJECT,
161 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
162 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
163 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
164 STORE_AND_GROW_NO_TRANSITION,
165 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
166 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
167 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
168 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
169 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
170 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
171 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
172 STORE_NO_TRANSITION_HANDLE_COW
176 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
185 enum ExternalArrayType {
186 kExternalInt8Array = 1,
189 kExternalUint16Array,
191 kExternalUint32Array,
192 kExternalFloat32Array,
193 kExternalFloat64Array,
194 kExternalUint8ClampedArray,
198 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
200 STATIC_ASSERT(STANDARD_STORE == 0);
201 STATIC_ASSERT(kGrowICDelta ==
202 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
203 STORE_TRANSITION_SMI_TO_OBJECT);
204 STATIC_ASSERT(kGrowICDelta ==
205 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
206 STORE_TRANSITION_SMI_TO_DOUBLE);
207 STATIC_ASSERT(kGrowICDelta ==
208 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
209 STORE_TRANSITION_DOUBLE_TO_OBJECT);
212 static inline KeyedAccessStoreMode GetGrowStoreMode(
213 KeyedAccessStoreMode store_mode) {
214 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
215 store_mode = static_cast<KeyedAccessStoreMode>(
216 static_cast<int>(store_mode) + kGrowICDelta);
222 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
223 return store_mode > STANDARD_STORE &&
224 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
225 store_mode != STORE_AND_GROW_NO_TRANSITION;
229 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
230 KeyedAccessStoreMode store_mode) {
231 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
234 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
235 return STORE_AND_GROW_NO_TRANSITION;
237 return STANDARD_STORE;
241 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
242 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
243 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
247 enum IcCheckType { ELEMENT, PROPERTY };
250 // SKIP_WRITE_BARRIER skips the write barrier.
251 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
252 // only performs the generational part.
253 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
254 enum WriteBarrierMode {
256 UPDATE_WEAK_WRITE_BARRIER,
261 // Indicates whether a value can be loaded as a constant.
262 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
265 // PropertyNormalizationMode is used to specify whether to keep
266 // inobject properties when normalizing properties of a JSObject.
267 enum PropertyNormalizationMode {
268 CLEAR_INOBJECT_PROPERTIES,
269 KEEP_INOBJECT_PROPERTIES
273 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
274 // will give the fastest result by tailoring the map to the prototype, but that
275 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
276 // (at least for now) when dynamically modifying the prototype chain of an
277 // object using __proto__ or Object.setPrototypeOf.
278 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
281 // Indicates whether transitions can be added to a source map or not.
282 enum TransitionFlag {
288 // Indicates whether the transition is simple: the target map of the transition
289 // either extends the current map with a new property, or it modifies the
290 // property that was added last to the current map.
291 enum SimpleTransitionFlag {
292 SIMPLE_PROPERTY_TRANSITION,
298 // Indicates whether we are only interested in the descriptors of a particular
299 // map, or in all descriptors in the descriptor array.
300 enum DescriptorFlag {
305 // The GC maintains a bit of information, the MarkingParity, which toggles
306 // from odd to even and back every time marking is completed. Incremental
307 // marking can visit an object twice during a marking phase, so algorithms that
308 // that piggy-back on marking can use the parity to ensure that they only
309 // perform an operation on an object once per marking phase: they record the
310 // MarkingParity when they visit an object, and only re-visit the object when it
311 // is marked again and the MarkingParity changes.
318 // ICs store extra state in a Code object. The default extra state is
320 typedef int ExtraICState;
321 static const ExtraICState kNoExtraICState = 0;
323 // Instance size sentinel for objects of variable size.
324 const int kVariableSizeSentinel = 0;
326 // We may store the unsigned bit field as signed Smi value and do not
328 const int kStubMajorKeyBits = 7;
329 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
331 // All Maps have a field instance_type containing a InstanceType.
332 // It describes the type of the instances.
334 // As an example, a JavaScript object is a heap object and its map
335 // instance_type is JS_OBJECT_TYPE.
337 // The names of the string instance types are intended to systematically
338 // mirror their encoding in the instance_type field of the map. The default
339 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
340 // encoding is mentioned explicitly in the name. Likewise, the default
341 // representation is considered sequential. It is not mentioned in the
342 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
343 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
344 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
346 // NOTE: The following things are some that depend on the string types having
347 // instance_types that are less than those of all other types:
348 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
351 // NOTE: Everything following JS_VALUE_TYPE is considered a
352 // JSObject for GC purposes. The first four entries here have typeof
353 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
354 #define INSTANCE_TYPE_LIST(V) \
356 V(ONE_BYTE_STRING_TYPE) \
357 V(CONS_STRING_TYPE) \
358 V(CONS_ONE_BYTE_STRING_TYPE) \
359 V(SLICED_STRING_TYPE) \
360 V(SLICED_ONE_BYTE_STRING_TYPE) \
361 V(EXTERNAL_STRING_TYPE) \
362 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
363 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
364 V(SHORT_EXTERNAL_STRING_TYPE) \
365 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
366 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
368 V(INTERNALIZED_STRING_TYPE) \
369 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
370 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
371 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
372 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
373 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
374 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
375 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
378 V(SIMD128_VALUE_TYPE) \
384 V(PROPERTY_CELL_TYPE) \
386 V(HEAP_NUMBER_TYPE) \
387 V(MUTABLE_HEAP_NUMBER_TYPE) \
390 V(BYTECODE_ARRAY_TYPE) \
393 V(FIXED_INT8_ARRAY_TYPE) \
394 V(FIXED_UINT8_ARRAY_TYPE) \
395 V(FIXED_INT16_ARRAY_TYPE) \
396 V(FIXED_UINT16_ARRAY_TYPE) \
397 V(FIXED_INT32_ARRAY_TYPE) \
398 V(FIXED_UINT32_ARRAY_TYPE) \
399 V(FIXED_FLOAT32_ARRAY_TYPE) \
400 V(FIXED_FLOAT64_ARRAY_TYPE) \
401 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
405 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
406 V(DECLARED_ACCESSOR_INFO_TYPE) \
407 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
408 V(ACCESSOR_PAIR_TYPE) \
409 V(ACCESS_CHECK_INFO_TYPE) \
410 V(INTERCEPTOR_INFO_TYPE) \
411 V(CALL_HANDLER_INFO_TYPE) \
412 V(FUNCTION_TEMPLATE_INFO_TYPE) \
413 V(OBJECT_TEMPLATE_INFO_TYPE) \
414 V(SIGNATURE_INFO_TYPE) \
415 V(TYPE_SWITCH_INFO_TYPE) \
416 V(ALLOCATION_MEMENTO_TYPE) \
417 V(ALLOCATION_SITE_TYPE) \
420 V(POLYMORPHIC_CODE_CACHE_TYPE) \
421 V(TYPE_FEEDBACK_INFO_TYPE) \
422 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
424 V(PROTOTYPE_INFO_TYPE) \
426 V(FIXED_ARRAY_TYPE) \
427 V(FIXED_DOUBLE_ARRAY_TYPE) \
428 V(SHARED_FUNCTION_INFO_TYPE) \
431 V(JS_MESSAGE_OBJECT_TYPE) \
436 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
437 V(JS_GENERATOR_OBJECT_TYPE) \
439 V(JS_GLOBAL_OBJECT_TYPE) \
440 V(JS_BUILTINS_OBJECT_TYPE) \
441 V(JS_GLOBAL_PROXY_TYPE) \
443 V(JS_ARRAY_BUFFER_TYPE) \
444 V(JS_TYPED_ARRAY_TYPE) \
445 V(JS_DATA_VIEW_TYPE) \
449 V(JS_SET_ITERATOR_TYPE) \
450 V(JS_MAP_ITERATOR_TYPE) \
451 V(JS_WEAK_MAP_TYPE) \
452 V(JS_WEAK_SET_TYPE) \
455 V(JS_FUNCTION_TYPE) \
456 V(JS_FUNCTION_PROXY_TYPE) \
458 V(BREAK_POINT_INFO_TYPE)
461 // Since string types are not consecutive, this macro is used to
462 // iterate over them.
463 #define STRING_TYPE_LIST(V) \
464 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
465 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
467 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
468 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
470 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
471 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
472 SlicedOneByteString) \
473 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
475 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
476 external_one_byte_string, ExternalOneByteString) \
477 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
478 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
479 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
480 short_external_string, ShortExternalString) \
481 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
482 short_external_one_byte_string, ShortExternalOneByteString) \
483 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
484 ExternalTwoByteString::kShortSize, \
485 short_external_string_with_one_byte_data, \
486 ShortExternalStringWithOneByteData) \
488 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
489 InternalizedString) \
490 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
491 one_byte_internalized_string, OneByteInternalizedString) \
492 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
493 external_internalized_string, ExternalInternalizedString) \
494 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
495 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
496 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
497 ExternalTwoByteString::kSize, \
498 external_internalized_string_with_one_byte_data, \
499 ExternalInternalizedStringWithOneByteData) \
500 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
501 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
502 ShortExternalInternalizedString) \
503 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
504 ExternalOneByteString::kShortSize, \
505 short_external_one_byte_internalized_string, \
506 ShortExternalOneByteInternalizedString) \
507 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
508 ExternalTwoByteString::kShortSize, \
509 short_external_internalized_string_with_one_byte_data, \
510 ShortExternalInternalizedStringWithOneByteData)
512 // A struct is a simple object a set of object-valued fields. Including an
513 // object type in this causes the compiler to generate most of the boilerplate
514 // code for the class including allocation and garbage collection routines,
515 // casts and predicates. All you need to define is the class, methods and
516 // object verification routines. Easy, no?
518 // Note that for subtle reasons related to the ordering or numerical values of
519 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
521 #define STRUCT_LIST(V) \
523 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
524 executable_accessor_info) \
525 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
526 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
527 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
528 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
529 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
530 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
531 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
532 V(SCRIPT, Script, script) \
533 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
534 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
535 V(CODE_CACHE, CodeCache, code_cache) \
536 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
537 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
538 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
539 V(DEBUG_INFO, DebugInfo, debug_info) \
540 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
541 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
543 // We use the full 8 bits of the instance_type field to encode heap object
544 // instance types. The high-order bit (bit 7) is set if the object is not a
545 // string, and cleared if it is a string.
546 const uint32_t kIsNotStringMask = 0x80;
547 const uint32_t kStringTag = 0x0;
548 const uint32_t kNotStringTag = 0x80;
550 // Bit 6 indicates that the object is an internalized string (if set) or not.
551 // Bit 7 has to be clear as well.
552 const uint32_t kIsNotInternalizedMask = 0x40;
553 const uint32_t kNotInternalizedTag = 0x40;
554 const uint32_t kInternalizedTag = 0x0;
556 // If bit 7 is clear then bit 2 indicates whether the string consists of
557 // two-byte characters or one-byte characters.
558 const uint32_t kStringEncodingMask = 0x4;
559 const uint32_t kTwoByteStringTag = 0x0;
560 const uint32_t kOneByteStringTag = 0x4;
562 // If bit 7 is clear, the low-order 2 bits indicate the representation
564 const uint32_t kStringRepresentationMask = 0x03;
565 enum StringRepresentationTag {
567 kConsStringTag = 0x1,
568 kExternalStringTag = 0x2,
569 kSlicedStringTag = 0x3
571 const uint32_t kIsIndirectStringMask = 0x1;
572 const uint32_t kIsIndirectStringTag = 0x1;
573 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
574 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
575 STATIC_ASSERT((kConsStringTag &
576 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
577 STATIC_ASSERT((kSlicedStringTag &
578 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
580 // Use this mask to distinguish between cons and slice only after making
581 // sure that the string is one of the two (an indirect string).
582 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
583 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
585 // If bit 7 is clear, then bit 3 indicates whether this two-byte
586 // string actually contains one byte data.
587 const uint32_t kOneByteDataHintMask = 0x08;
588 const uint32_t kOneByteDataHintTag = 0x08;
590 // If bit 7 is clear and string representation indicates an external string,
591 // then bit 4 indicates whether the data pointer is cached.
592 const uint32_t kShortExternalStringMask = 0x10;
593 const uint32_t kShortExternalStringTag = 0x10;
596 // A ConsString with an empty string as the right side is a candidate
597 // for being shortcut by the garbage collector. We don't allocate any
598 // non-flat internalized strings, so we do not shortcut them thereby
599 // avoiding turning internalized strings into strings. The bit-masks
600 // below contain the internalized bit as additional safety.
601 // See heap.cc, mark-compact.cc and objects-visiting.cc.
602 const uint32_t kShortcutTypeMask =
604 kIsNotInternalizedMask |
605 kStringRepresentationMask;
606 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
608 static inline bool IsShortcutCandidate(int type) {
609 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
615 INTERNALIZED_STRING_TYPE =
616 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
617 ONE_BYTE_INTERNALIZED_STRING_TYPE =
618 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
619 EXTERNAL_INTERNALIZED_STRING_TYPE =
620 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
621 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
622 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
623 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
624 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
626 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
627 kShortExternalStringTag |
629 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
630 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
632 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
633 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
634 kShortExternalStringTag | kInternalizedTag,
635 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
636 ONE_BYTE_STRING_TYPE =
637 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
638 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
639 CONS_ONE_BYTE_STRING_TYPE =
640 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
642 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
643 SLICED_ONE_BYTE_STRING_TYPE =
644 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
645 EXTERNAL_STRING_TYPE =
646 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
647 EXTERNAL_ONE_BYTE_STRING_TYPE =
648 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
649 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
650 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
652 SHORT_EXTERNAL_STRING_TYPE =
653 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
654 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
655 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
656 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
657 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
661 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
663 // Objects allocated in their own spaces (never in new space).
668 // "Data", objects that cannot contain non-map-word pointers to heap
671 MUTABLE_HEAP_NUMBER_TYPE,
677 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
678 FIXED_UINT8_ARRAY_TYPE,
679 FIXED_INT16_ARRAY_TYPE,
680 FIXED_UINT16_ARRAY_TYPE,
681 FIXED_INT32_ARRAY_TYPE,
682 FIXED_UINT32_ARRAY_TYPE,
683 FIXED_FLOAT32_ARRAY_TYPE,
684 FIXED_FLOAT64_ARRAY_TYPE,
685 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
686 FIXED_DOUBLE_ARRAY_TYPE,
687 FILLER_TYPE, // LAST_DATA_TYPE
690 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
691 DECLARED_ACCESSOR_INFO_TYPE,
692 EXECUTABLE_ACCESSOR_INFO_TYPE,
694 ACCESS_CHECK_INFO_TYPE,
695 INTERCEPTOR_INFO_TYPE,
696 CALL_HANDLER_INFO_TYPE,
697 FUNCTION_TEMPLATE_INFO_TYPE,
698 OBJECT_TEMPLATE_INFO_TYPE,
700 TYPE_SWITCH_INFO_TYPE,
701 ALLOCATION_SITE_TYPE,
702 ALLOCATION_MEMENTO_TYPE,
705 POLYMORPHIC_CODE_CACHE_TYPE,
706 TYPE_FEEDBACK_INFO_TYPE,
707 ALIASED_ARGUMENTS_ENTRY_TYPE,
710 BREAK_POINT_INFO_TYPE,
712 SHARED_FUNCTION_INFO_TYPE,
718 // All the following types are subtypes of JSReceiver, which corresponds to
719 // objects in the JS sense. The first and the last type in this range are
720 // the two forms of function. This organization enables using the same
721 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
722 // NONCALLABLE_JS_OBJECT range.
723 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
724 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
725 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
726 JS_MESSAGE_OBJECT_TYPE,
729 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
730 JS_GENERATOR_OBJECT_TYPE,
732 JS_GLOBAL_OBJECT_TYPE,
733 JS_BUILTINS_OBJECT_TYPE,
734 JS_GLOBAL_PROXY_TYPE,
736 JS_ARRAY_BUFFER_TYPE,
741 JS_SET_ITERATOR_TYPE,
742 JS_MAP_ITERATOR_TYPE,
746 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
750 LAST_TYPE = JS_FUNCTION_TYPE,
751 FIRST_NAME_TYPE = FIRST_TYPE,
752 LAST_NAME_TYPE = SYMBOL_TYPE,
753 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
754 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
755 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
756 // Boundaries for testing for a fixed typed array.
757 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
758 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
759 // Boundary for promotion to old space.
760 LAST_DATA_TYPE = FILLER_TYPE,
761 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
762 // Note that there is no range for JSObject or JSProxy, since their subtypes
763 // are not continuous in this enum! The enum ranges instead reflect the
764 // external class names, where proxies are treated as either ordinary objects,
766 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
767 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
768 // Boundaries for testing the types represented as JSObject
769 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
770 LAST_JS_OBJECT_TYPE = LAST_TYPE,
771 // Boundaries for testing the types represented as JSProxy
772 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
773 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
774 // Boundaries for testing whether the type is a JavaScript object.
775 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
776 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
777 // Boundaries for testing the types for which typeof is "object".
778 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
779 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
780 // Note that the types for which typeof is "function" are not continuous.
781 // Define this so that we can put assertions on discrete checks.
782 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
785 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
786 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
787 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
788 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
791 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
792 V(FAST_ELEMENTS_SUB_TYPE) \
793 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
794 V(FAST_PROPERTIES_SUB_TYPE) \
795 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
796 V(MAP_CODE_CACHE_SUB_TYPE) \
797 V(SCOPE_INFO_SUB_TYPE) \
798 V(STRING_TABLE_SUB_TYPE) \
799 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
800 V(TRANSITION_ARRAY_SUB_TYPE)
802 enum FixedArraySubInstanceType {
803 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
804 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
805 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
806 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
819 #define DECL_BOOLEAN_ACCESSORS(name) \
820 inline bool name() const; \
821 inline void set_##name(bool value); \
824 #define DECL_ACCESSORS(name, type) \
825 inline type* name() const; \
826 inline void set_##name(type* value, \
827 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
830 #define DECLARE_CAST(type) \
831 INLINE(static type* cast(Object* object)); \
832 INLINE(static const type* cast(const Object* object));
836 class AllocationSite;
837 class AllocationSiteCreationContext;
838 class AllocationSiteUsageContext;
841 class ElementsAccessor;
842 class FixedArrayBase;
843 class FunctionLiteral;
845 class JSBuiltinsObject;
846 class LayoutDescriptor;
847 class LookupIterator;
848 class ObjectHashTable;
851 class SafepointEntry;
852 class SharedFunctionInfo;
854 class TypeFeedbackInfo;
855 class TypeFeedbackVector;
858 // We cannot just say "class HeapType;" if it is created from a template... =8-?
859 template<class> class TypeImpl;
860 struct HeapTypeConfig;
861 typedef TypeImpl<HeapTypeConfig> HeapType;
864 // A template-ized version of the IsXXX functions.
865 template <class C> inline bool Is(Object* obj);
868 #define DECLARE_VERIFIER(Name) void Name##Verify();
870 #define DECLARE_VERIFIER(Name)
874 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
876 #define DECLARE_PRINTER(Name)
880 #define OBJECT_TYPE_LIST(V) \
885 #define HEAP_OBJECT_TYPE_LIST(V) \
887 V(MutableHeapNumber) \
903 V(ExternalTwoByteString) \
904 V(ExternalOneByteString) \
905 V(SeqTwoByteString) \
906 V(SeqOneByteString) \
907 V(InternalizedString) \
910 V(FixedTypedArrayBase) \
913 V(FixedUint16Array) \
915 V(FixedUint32Array) \
917 V(FixedFloat32Array) \
918 V(FixedFloat64Array) \
919 V(FixedUint8ClampedArray) \
925 V(JSContextExtensionObject) \
926 V(JSGeneratorObject) \
928 V(LayoutDescriptor) \
932 V(TypeFeedbackVector) \
933 V(DeoptimizationInputData) \
934 V(DeoptimizationOutputData) \
938 V(FixedDoubleArray) \
942 V(ScriptContextTable) \
948 V(SharedFunctionInfo) \
957 V(JSArrayBufferView) \
966 V(JSWeakCollection) \
973 V(NormalizedMapCache) \
974 V(CompilationCacheTable) \
975 V(CodeCacheHashTable) \
976 V(PolymorphicCodeCacheHashTable) \
981 V(JSBuiltinsObject) \
983 V(UndetectableObject) \
984 V(AccessCheckNeeded) \
990 V(WeakValueHashTable) \
993 // Object is the abstract superclass for all classes in the
995 // Object does not use any virtual functions to avoid the
996 // allocation of the C++ vtable.
997 // Since both Smi and HeapObject are subclasses of Object no
998 // data members can be present in Object.
1002 bool IsObject() const { return true; }
1004 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1005 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1006 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1007 #undef IS_TYPE_FUNCTION_DECL
1009 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1010 // a keyed store is of the form a[expression] = foo.
1011 enum StoreFromKeyed {
1012 MAY_BE_STORE_FROM_KEYED,
1013 CERTAINLY_NOT_STORE_FROM_KEYED
1016 INLINE(bool IsFixedArrayBase() const);
1017 INLINE(bool IsExternal() const);
1018 INLINE(bool IsAccessorInfo() const);
1020 INLINE(bool IsStruct() const);
1021 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1022 INLINE(bool Is##Name() const);
1023 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1024 #undef DECLARE_STRUCT_PREDICATE
1026 INLINE(bool IsSpecObject()) const;
1027 INLINE(bool IsSpecFunction()) const;
1028 INLINE(bool IsTemplateInfo()) const;
1029 INLINE(bool IsNameDictionary() const);
1030 INLINE(bool IsGlobalDictionary() const);
1031 INLINE(bool IsSeededNumberDictionary() const);
1032 INLINE(bool IsUnseededNumberDictionary() const);
1033 INLINE(bool IsOrderedHashSet() const);
1034 INLINE(bool IsOrderedHashMap() const);
1035 bool IsCallable() const;
1036 static bool IsPromise(Handle<Object> object);
1039 INLINE(bool IsUndefined() const);
1040 INLINE(bool IsNull() const);
1041 INLINE(bool IsTheHole() const);
1042 INLINE(bool IsException() const);
1043 INLINE(bool IsUninitialized() const);
1044 INLINE(bool IsTrue() const);
1045 INLINE(bool IsFalse() const);
1046 INLINE(bool IsArgumentsMarker() const);
1048 // Filler objects (fillers and free space objects).
1049 INLINE(bool IsFiller() const);
1051 // Extract the number.
1052 inline double Number();
1053 INLINE(bool IsNaN() const);
1054 INLINE(bool IsMinusZero() const);
1055 bool ToInt32(int32_t* value);
1056 bool ToUint32(uint32_t* value);
1058 inline Representation OptimalRepresentation() {
1059 if (!FLAG_track_fields) return Representation::Tagged();
1061 return Representation::Smi();
1062 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1063 return Representation::Double();
1064 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1065 return Representation::None();
1066 } else if (FLAG_track_heap_object_fields) {
1067 DCHECK(IsHeapObject());
1068 return Representation::HeapObject();
1070 return Representation::Tagged();
1074 inline ElementsKind OptimalElementsKind() {
1075 if (IsSmi()) return FAST_SMI_ELEMENTS;
1076 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1077 return FAST_ELEMENTS;
1080 inline bool FitsRepresentation(Representation representation) {
1081 if (FLAG_track_fields && representation.IsNone()) {
1083 } else if (FLAG_track_fields && representation.IsSmi()) {
1085 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1086 return IsMutableHeapNumber() || IsNumber();
1087 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1088 return IsHeapObject();
1093 // Checks whether two valid primitive encodings of a property name resolve to
1094 // the same logical property. E.g., the smi 1, the string "1" and the double
1095 // 1 all refer to the same property, so this helper will return true.
1096 inline bool KeyEquals(Object* other);
1098 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1100 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1101 Handle<Object> object,
1102 Representation representation);
1104 inline static Handle<Object> WrapForRead(Isolate* isolate,
1105 Handle<Object> object,
1106 Representation representation);
1108 // Returns true if the object is of the correct type to be used as a
1109 // implementation of a JSObject's elements.
1110 inline bool HasValidElements();
1112 inline bool HasSpecificClassOf(String* name);
1114 bool BooleanValue(); // ECMA-262 9.2.
1116 // Convert to a JSObject if needed.
1117 // native_context is used when creating wrapper object.
1118 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1119 Handle<Object> object);
1120 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1121 Handle<Object> object,
1122 Handle<Context> context);
1124 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1125 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1127 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1128 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1129 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1130 LanguageMode language_mode,
1131 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1133 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1134 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1135 StoreFromKeyed store_mode);
1137 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1138 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1139 StoreFromKeyed store_mode);
1141 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1142 LookupIterator* it, LanguageMode language_mode);
1143 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1144 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1145 LanguageMode language_mode);
1146 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1147 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1148 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1149 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1150 Handle<Object> value, LanguageMode language_mode);
1151 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1152 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1153 LanguageMode language_mode);
1154 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1155 LookupIterator* it, Handle<Object> value);
1156 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1157 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1158 LanguageMode language_mode, StoreFromKeyed store_mode);
1159 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1160 Handle<Object> object, Handle<Name> name,
1161 LanguageMode language_mode = SLOPPY);
1162 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1163 Isolate* isolate, Handle<Object> object, const char* key,
1164 LanguageMode language_mode = SLOPPY);
1165 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1166 Handle<Object> object, Handle<Name> name,
1167 LanguageMode language_mode = SLOPPY);
1169 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1170 LookupIterator* it, LanguageMode language_mode);
1171 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1172 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1174 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1175 Handle<Object> receiver,
1176 Handle<JSReceiver> getter);
1177 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1178 Handle<Object> receiver,
1179 Handle<JSReceiver> setter,
1180 Handle<Object> value);
1182 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1183 Isolate* isolate, Handle<Object> object, uint32_t index,
1184 LanguageMode language_mode = SLOPPY);
1186 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1187 Isolate* isolate, Handle<Object> object, uint32_t index,
1188 Handle<Object> value, LanguageMode language_mode);
1190 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1191 Isolate* isolate, Handle<Object> receiver);
1193 // Returns the permanent hash code associated with this object. May return
1194 // undefined if not yet created.
1197 // Returns undefined for JSObjects, but returns the hash code for simple
1198 // objects. This avoids a double lookup in the cases where we know we will
1199 // add the hash to the JSObject if it does not already exist.
1200 Object* GetSimpleHash();
1202 // Returns the permanent hash code associated with this object depending on
1203 // the actual object type. May create and store a hash code if needed and none
1205 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1207 // Checks whether this object has the same value as the given one. This
1208 // function is implemented according to ES5, section 9.12 and can be used
1209 // to implement the Harmony "egal" function.
1210 bool SameValue(Object* other);
1212 // Checks whether this object has the same value as the given one.
1213 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1214 // This function is implemented according to ES6, section 7.2.4 and is used
1215 // by ES6 Map and Set.
1216 bool SameValueZero(Object* other);
1218 // Tries to convert an object to an array length. Returns true and sets the
1219 // output parameter if it succeeds.
1220 inline bool ToArrayLength(uint32_t* index);
1222 // Tries to convert an object to an array index. Returns true and sets the
1223 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1224 // allow kMaxUInt32.
1225 inline bool ToArrayIndex(uint32_t* index);
1227 // Returns true if this is a JSValue containing a string and the index is
1228 // < the length of the string. Used to implement [] on strings.
1229 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1231 DECLARE_VERIFIER(Object)
1233 // Verify a pointer is a valid object pointer.
1234 static void VerifyPointer(Object* p);
1237 inline void VerifyApiCallResultType();
1239 // Prints this object without details.
1240 void ShortPrint(FILE* out = stdout);
1242 // Prints this object without details to a message accumulator.
1243 void ShortPrint(StringStream* accumulator);
1245 void ShortPrint(std::ostream& os); // NOLINT
1247 DECLARE_CAST(Object)
1249 // Layout description.
1250 static const int kHeaderSize = 0; // Object does not take up any space.
1253 // For our gdb macros, we should perhaps change these in the future.
1256 // Prints this object with details.
1257 void Print(std::ostream& os); // NOLINT
1259 void Print() { ShortPrint(); }
1260 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1264 friend class LookupIterator;
1265 friend class PrototypeIterator;
1267 // Return the map of the root of object's prototype chain.
1268 Map* GetRootMap(Isolate* isolate);
1270 // Helper for SetProperty and SetSuperProperty.
1271 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1272 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1273 StoreFromKeyed store_mode, bool* found);
1275 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1280 explicit Brief(const Object* const v) : value(v) {}
1281 const Object* value;
1285 std::ostream& operator<<(std::ostream& os, const Brief& v);
1288 // Smi represents integer Numbers that can be stored in 31 bits.
1289 // Smis are immediate which means they are NOT allocated in the heap.
1290 // The this pointer has the following format: [31 bit signed int] 0
1291 // For long smis it has the following format:
1292 // [32 bit signed int] [31 bits zero padding] 0
1293 // Smi stands for small integer.
1294 class Smi: public Object {
1296 // Returns the integer value.
1297 inline int value() const;
1299 // Convert a value to a Smi object.
1300 static inline Smi* FromInt(int value);
1302 static inline Smi* FromIntptr(intptr_t value);
1304 // Returns whether value can be represented in a Smi.
1305 static inline bool IsValid(intptr_t value);
1309 // Dispatched behavior.
1310 void SmiPrint(std::ostream& os) const; // NOLINT
1311 DECLARE_VERIFIER(Smi)
1313 static const int kMinValue =
1314 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1315 static const int kMaxValue = -(kMinValue + 1);
1318 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1322 // Heap objects typically have a map pointer in their first word. However,
1323 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1324 // encoded in the first word. The class MapWord is an abstraction of the
1325 // value in a heap object's first word.
1326 class MapWord BASE_EMBEDDED {
1328 // Normal state: the map word contains a map pointer.
1330 // Create a map word from a map pointer.
1331 static inline MapWord FromMap(const Map* map);
1333 // View this map word as a map pointer.
1334 inline Map* ToMap();
1337 // Scavenge collection: the map word of live objects in the from space
1338 // contains a forwarding address (a heap object pointer in the to space).
1340 // True if this map word is a forwarding address for a scavenge
1341 // collection. Only valid during a scavenge collection (specifically,
1342 // when all map words are heap object pointers, i.e. not during a full GC).
1343 inline bool IsForwardingAddress();
1345 // Create a map word from a forwarding address.
1346 static inline MapWord FromForwardingAddress(HeapObject* object);
1348 // View this map word as a forwarding address.
1349 inline HeapObject* ToForwardingAddress();
1351 static inline MapWord FromRawValue(uintptr_t value) {
1352 return MapWord(value);
1355 inline uintptr_t ToRawValue() {
1360 // HeapObject calls the private constructor and directly reads the value.
1361 friend class HeapObject;
1363 explicit MapWord(uintptr_t value) : value_(value) {}
1369 // The content of an heap object (except for the map pointer). kTaggedValues
1370 // objects can contain both heap pointers and Smis, kMixedValues can contain
1371 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1372 // objects can contain raw values and Smis.
1373 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1376 // HeapObject is the superclass for all classes describing heap allocated
1378 class HeapObject: public Object {
1380 // [map]: Contains a map which contains the object's reflective
1382 inline Map* map() const;
1383 inline void set_map(Map* value);
1384 // The no-write-barrier version. This is OK if the object is white and in
1385 // new space, or if the value is an immortal immutable object, like the maps
1386 // of primitive (non-JS) objects like strings, heap numbers etc.
1387 inline void set_map_no_write_barrier(Map* value);
1389 // Get the map using acquire load.
1390 inline Map* synchronized_map();
1391 inline MapWord synchronized_map_word() const;
1393 // Set the map using release store
1394 inline void synchronized_set_map(Map* value);
1395 inline void synchronized_set_map_no_write_barrier(Map* value);
1396 inline void synchronized_set_map_word(MapWord map_word);
1398 // During garbage collection, the map word of a heap object does not
1399 // necessarily contain a map pointer.
1400 inline MapWord map_word() const;
1401 inline void set_map_word(MapWord map_word);
1403 // The Heap the object was allocated in. Used also to access Isolate.
1404 inline Heap* GetHeap() const;
1406 // Convenience method to get current isolate.
1407 inline Isolate* GetIsolate() const;
1409 // Converts an address to a HeapObject pointer.
1410 static inline HeapObject* FromAddress(Address address);
1412 // Returns the address of this HeapObject.
1413 inline Address address();
1415 // Iterates over pointers contained in the object (including the Map)
1416 void Iterate(ObjectVisitor* v);
1418 // Iterates over all pointers contained in the object except the
1419 // first map pointer. The object type is given in the first
1420 // parameter. This function does not access the map pointer in the
1421 // object, and so is safe to call while the map pointer is modified.
1422 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1424 // Returns the heap object's size in bytes
1427 // Indicates what type of values this heap object may contain.
1428 inline HeapObjectContents ContentType();
1430 // Given a heap object's map pointer, returns the heap size in bytes
1431 // Useful when the map pointer field is used for other purposes.
1433 inline int SizeFromMap(Map* map);
1435 // Returns the field at offset in obj, as a read/write Object* reference.
1436 // Does no checking, and is safe to use during GC, while maps are invalid.
1437 // Does not invoke write barrier, so should only be assigned to
1438 // during marking GC.
1439 static inline Object** RawField(HeapObject* obj, int offset);
1441 // Adds the |code| object related to |name| to the code cache of this map. If
1442 // this map is a dictionary map that is shared, the map copied and installed
1444 static void UpdateMapCodeCache(Handle<HeapObject> object,
1448 DECLARE_CAST(HeapObject)
1450 // Return the write barrier mode for this. Callers of this function
1451 // must be able to present a reference to an DisallowHeapAllocation
1452 // object as a sign that they are not going to use this function
1453 // from code that allocates and thus invalidates the returned write
1455 inline WriteBarrierMode GetWriteBarrierMode(
1456 const DisallowHeapAllocation& promise);
1458 // Dispatched behavior.
1459 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1461 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1463 DECLARE_PRINTER(HeapObject)
1464 DECLARE_VERIFIER(HeapObject)
1466 inline void VerifyObjectField(int offset);
1467 inline void VerifySmiField(int offset);
1469 // Verify a pointer is a valid HeapObject pointer that points to object
1470 // areas in the heap.
1471 static void VerifyHeapPointer(Object* p);
1474 inline AllocationAlignment RequiredAlignment();
1476 // Layout description.
1477 // First field in a heap object is map.
1478 static const int kMapOffset = Object::kHeaderSize;
1479 static const int kHeaderSize = kMapOffset + kPointerSize;
1481 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1484 // helpers for calling an ObjectVisitor to iterate over pointers in the
1485 // half-open range [start, end) specified as integer offsets
1486 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1487 // as above, for the single element at "offset"
1488 inline void IteratePointer(ObjectVisitor* v, int offset);
1489 // as above, for the next code link of a code object.
1490 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1493 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1497 // This class describes a body of an object of a fixed size
1498 // in which all pointer fields are located in the [start_offset, end_offset)
1500 template<int start_offset, int end_offset, int size>
1501 class FixedBodyDescriptor {
1503 static const int kStartOffset = start_offset;
1504 static const int kEndOffset = end_offset;
1505 static const int kSize = size;
1507 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1509 template<typename StaticVisitor>
1510 static inline void IterateBody(HeapObject* obj) {
1511 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1512 HeapObject::RawField(obj, end_offset));
1517 // This class describes a body of an object of a variable size
1518 // in which all pointer fields are located in the [start_offset, object_size)
1520 template<int start_offset>
1521 class FlexibleBodyDescriptor {
1523 static const int kStartOffset = start_offset;
1525 static inline void IterateBody(HeapObject* obj,
1529 template<typename StaticVisitor>
1530 static inline void IterateBody(HeapObject* obj, int object_size) {
1531 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1532 HeapObject::RawField(obj, object_size));
1537 // The HeapNumber class describes heap allocated numbers that cannot be
1538 // represented in a Smi (small integer)
1539 class HeapNumber: public HeapObject {
1541 // [value]: number value.
1542 inline double value() const;
1543 inline void set_value(double value);
1545 DECLARE_CAST(HeapNumber)
1547 // Dispatched behavior.
1548 bool HeapNumberBooleanValue();
1550 void HeapNumberPrint(std::ostream& os); // NOLINT
1551 DECLARE_VERIFIER(HeapNumber)
1553 inline int get_exponent();
1554 inline int get_sign();
1556 // Layout description.
1557 static const int kValueOffset = HeapObject::kHeaderSize;
1558 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1559 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1560 // words within double numbers are endian dependent and they are set
1562 #if defined(V8_TARGET_LITTLE_ENDIAN)
1563 static const int kMantissaOffset = kValueOffset;
1564 static const int kExponentOffset = kValueOffset + 4;
1565 #elif defined(V8_TARGET_BIG_ENDIAN)
1566 static const int kMantissaOffset = kValueOffset + 4;
1567 static const int kExponentOffset = kValueOffset;
1569 #error Unknown byte ordering
1572 static const int kSize = kValueOffset + kDoubleSize;
1573 static const uint32_t kSignMask = 0x80000000u;
1574 static const uint32_t kExponentMask = 0x7ff00000u;
1575 static const uint32_t kMantissaMask = 0xfffffu;
1576 static const int kMantissaBits = 52;
1577 static const int kExponentBits = 11;
1578 static const int kExponentBias = 1023;
1579 static const int kExponentShift = 20;
1580 static const int kInfinityOrNanExponent =
1581 (kExponentMask >> kExponentShift) - kExponentBias;
1582 static const int kMantissaBitsInTopWord = 20;
1583 static const int kNonMantissaBitsInTopWord = 12;
1586 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1590 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1591 class Simd128Value : public HeapObject {
1593 DECLARE_CAST(Simd128Value)
1595 DECLARE_PRINTER(Simd128Value)
1596 DECLARE_VERIFIER(Simd128Value)
1598 // Checks that another instance is bit-wise equal.
1599 bool BitwiseEquals(const Simd128Value* other) const;
1600 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1601 uint32_t Hash() const;
1602 // Copies the 16 bytes of SIMD data to the destination address.
1603 void CopyBits(void* destination) const;
1605 // Layout description.
1606 static const int kValueOffset = HeapObject::kHeaderSize;
1607 static const int kSize = kValueOffset + kSimd128Size;
1610 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1614 // V has parameters (TYPE, Type, type, lane count, lane type)
1615 #define SIMD128_TYPES(V) \
1616 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1617 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1618 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1619 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1620 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1621 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1622 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1624 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1625 class Type final : public Simd128Value { \
1627 inline lane_type get_lane(int lane) const; \
1628 inline void set_lane(int lane, lane_type value); \
1630 DECLARE_CAST(Type) \
1632 DECLARE_PRINTER(Type) \
1635 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1637 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1638 #undef SIMD128_VALUE_CLASS
1641 enum EnsureElementsMode {
1642 DONT_ALLOW_DOUBLE_ELEMENTS,
1643 ALLOW_COPIED_DOUBLE_ELEMENTS,
1644 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1648 // Indicator for one component of an AccessorPair.
1649 enum AccessorComponent {
1655 // JSReceiver includes types on which properties can be defined, i.e.,
1656 // JSObject and JSProxy.
1657 class JSReceiver: public HeapObject {
1659 DECLARE_CAST(JSReceiver)
1661 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1662 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1663 Handle<JSReceiver> object, Handle<Name> name);
1664 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1666 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1667 Handle<JSReceiver> object, uint32_t index);
1668 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1669 Handle<JSReceiver> object, uint32_t index);
1671 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1672 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1673 Handle<JSReceiver> object, Handle<Name> name,
1674 LanguageMode language_mode = SLOPPY);
1675 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1676 Handle<JSReceiver> object, Handle<Name> name,
1677 LanguageMode language_mode = SLOPPY);
1678 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1679 LookupIterator* it, LanguageMode language_mode);
1680 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1681 Handle<JSReceiver> object, uint32_t index,
1682 LanguageMode language_mode = SLOPPY);
1684 // Tests for the fast common case for property enumeration.
1685 bool IsSimpleEnum();
1687 // Returns the class name ([[Class]] property in the specification).
1688 String* class_name();
1690 // Returns the constructor name (the name (possibly, inferred name) of the
1691 // function that was used to instantiate the object).
1692 String* constructor_name();
1694 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1695 Handle<JSReceiver> object, Handle<Name> name);
1696 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1697 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1699 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1700 Handle<JSReceiver> object, uint32_t index);
1701 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1702 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1704 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1705 LookupIterator* it);
1708 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1710 static Handle<Object> GetDataProperty(LookupIterator* it);
1713 // Retrieves a permanent object identity hash code. The undefined value might
1714 // be returned in case no hash was created yet.
1715 inline Object* GetIdentityHash();
1717 // Retrieves a permanent object identity hash code. May create and store a
1718 // hash code if needed and none exists.
1719 inline static Handle<Smi> GetOrCreateIdentityHash(
1720 Handle<JSReceiver> object);
1722 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1724 // Computes the enumerable keys for a JSObject. Used for implementing
1725 // "for (n in object) { }".
1726 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1727 Handle<JSReceiver> object,
1728 KeyCollectionType type);
1731 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1735 // The JSObject describes real heap allocated JavaScript objects with
1737 // Note that the map of JSObject changes during execution to enable inline
1739 class JSObject: public JSReceiver {
1741 // [properties]: Backing storage for properties.
1742 // properties is a FixedArray in the fast case and a Dictionary in the
1744 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1745 inline void initialize_properties();
1746 inline bool HasFastProperties();
1747 // Gets slow properties for non-global objects.
1748 inline NameDictionary* property_dictionary();
1749 // Gets global object properties.
1750 inline GlobalDictionary* global_dictionary();
1752 // [elements]: The elements (properties with names that are integers).
1754 // Elements can be in two general modes: fast and slow. Each mode
1755 // corrensponds to a set of object representations of elements that
1756 // have something in common.
1758 // In the fast mode elements is a FixedArray and so each element can
1759 // be quickly accessed. This fact is used in the generated code. The
1760 // elements array can have one of three maps in this mode:
1761 // fixed_array_map, sloppy_arguments_elements_map or
1762 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1763 // the elements array may be shared by a few objects and so before
1764 // writing to any element the array must be copied. Use
1765 // EnsureWritableFastElements in this case.
1767 // In the slow mode the elements is either a NumberDictionary, a
1768 // FixedArray parameter map for a (sloppy) arguments object.
1769 DECL_ACCESSORS(elements, FixedArrayBase)
1770 inline void initialize_elements();
1771 static void ResetElements(Handle<JSObject> object);
1772 static inline void SetMapAndElements(Handle<JSObject> object,
1774 Handle<FixedArrayBase> elements);
1775 inline ElementsKind GetElementsKind();
1776 ElementsAccessor* GetElementsAccessor();
1777 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1778 inline bool HasFastSmiElements();
1779 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1780 inline bool HasFastObjectElements();
1781 // Returns true if an object has elements of FAST_ELEMENTS or
1782 // FAST_SMI_ONLY_ELEMENTS.
1783 inline bool HasFastSmiOrObjectElements();
1784 // Returns true if an object has any of the fast elements kinds.
1785 inline bool HasFastElements();
1786 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1788 inline bool HasFastDoubleElements();
1789 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1791 inline bool HasFastHoleyElements();
1792 inline bool HasSloppyArgumentsElements();
1793 inline bool HasDictionaryElements();
1795 inline bool HasFixedTypedArrayElements();
1797 inline bool HasFixedUint8ClampedElements();
1798 inline bool HasFixedArrayElements();
1799 inline bool HasFixedInt8Elements();
1800 inline bool HasFixedUint8Elements();
1801 inline bool HasFixedInt16Elements();
1802 inline bool HasFixedUint16Elements();
1803 inline bool HasFixedInt32Elements();
1804 inline bool HasFixedUint32Elements();
1805 inline bool HasFixedFloat32Elements();
1806 inline bool HasFixedFloat64Elements();
1808 inline bool HasFastArgumentsElements();
1809 inline bool HasSlowArgumentsElements();
1810 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1812 // Requires: HasFastElements().
1813 static Handle<FixedArray> EnsureWritableFastElements(
1814 Handle<JSObject> object);
1816 // Collects elements starting at index 0.
1817 // Undefined values are placed after non-undefined values.
1818 // Returns the number of non-undefined values.
1819 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1821 // As PrepareElementsForSort, but only on objects where elements is
1822 // a dictionary, and it will stay a dictionary. Collates undefined and
1823 // unexisting elements below limit from position zero of the elements.
1824 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1827 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1828 LookupIterator* it, Handle<Object> value);
1830 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1831 // grant an exemption to ExecutableAccessor callbacks in some cases.
1832 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1834 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1835 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1836 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1838 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1839 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1840 PropertyAttributes attributes,
1841 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1843 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1844 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1845 PropertyAttributes attributes,
1846 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1848 // Equivalent to one of the above depending on whether |name| can be converted
1849 // to an array index.
1850 MUST_USE_RESULT static MaybeHandle<Object>
1851 DefinePropertyOrElementIgnoreAttributes(
1852 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1853 PropertyAttributes attributes = NONE,
1854 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1856 // Adds or reconfigures a property to attributes NONE. It will fail when it
1858 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1859 Handle<Object> value);
1861 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1862 Handle<Object> value, PropertyAttributes attributes);
1864 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1865 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1866 PropertyAttributes attributes);
1868 // Extend the receiver with a single fast property appeared first in the
1869 // passed map. This also extends the property backing store if necessary.
1870 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1872 // Migrates the given object to a map whose field representations are the
1873 // lowest upper bound of all known representations for that field.
1874 static void MigrateInstance(Handle<JSObject> instance);
1876 // Migrates the given object only if the target map is already available,
1877 // or returns false if such a map is not yet available.
1878 static bool TryMigrateInstance(Handle<JSObject> instance);
1880 // Sets the property value in a normalized object given (key, value, details).
1881 // Handles the special representation of JS global objects.
1882 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1883 Handle<Object> value,
1884 PropertyDetails details);
1885 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1886 Handle<Object> value,
1887 PropertyAttributes attributes);
1888 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1890 Handle<Object> value,
1891 PropertyAttributes attributes);
1893 static void OptimizeAsPrototype(Handle<JSObject> object,
1894 PrototypeOptimizationMode mode);
1895 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1896 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1897 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1898 static void InvalidatePrototypeChains(Map* map);
1900 // Alternative implementation of WeakFixedArray::NullCallback.
1901 class PrototypeRegistryCompactionCallback {
1903 static void Callback(Object* value, int old_index, int new_index);
1906 // Retrieve interceptors.
1907 InterceptorInfo* GetNamedInterceptor();
1908 InterceptorInfo* GetIndexedInterceptor();
1910 // Used from JSReceiver.
1911 MUST_USE_RESULT static Maybe<PropertyAttributes>
1912 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1913 MUST_USE_RESULT static Maybe<PropertyAttributes>
1914 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1916 // Retrieves an AccessorPair property from the given object. Might return
1917 // undefined if the property doesn't exist or is of a different kind.
1918 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1919 Handle<JSObject> object,
1921 AccessorComponent component);
1923 // Defines an AccessorPair property on the given object.
1924 // TODO(mstarzinger): Rename to SetAccessor().
1925 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1927 Handle<Object> getter,
1928 Handle<Object> setter,
1929 PropertyAttributes attributes);
1931 // Defines an AccessorInfo property on the given object.
1932 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1933 Handle<JSObject> object,
1934 Handle<AccessorInfo> info);
1936 // The result must be checked first for exceptions. If there's no exception,
1937 // the output parameter |done| indicates whether the interceptor has a result
1939 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1940 LookupIterator* it, bool* done);
1942 // Accessors for hidden properties object.
1944 // Hidden properties are not own properties of the object itself.
1945 // Instead they are stored in an auxiliary structure kept as an own
1946 // property with a special name Heap::hidden_string(). But if the
1947 // receiver is a JSGlobalProxy then the auxiliary object is a property
1948 // of its prototype, and if it's a detached proxy, then you can't have
1949 // hidden properties.
1951 // Sets a hidden property on this object. Returns this object if successful,
1952 // undefined if called on a detached proxy.
1953 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1955 Handle<Object> value);
1956 // Gets the value of a hidden property with the given key. Returns the hole
1957 // if the property doesn't exist (or if called on a detached proxy),
1958 // otherwise returns the value set for the key.
1959 Object* GetHiddenProperty(Handle<Name> key);
1960 // Deletes a hidden property. Deleting a non-existing property is
1961 // considered successful.
1962 static void DeleteHiddenProperty(Handle<JSObject> object,
1964 // Returns true if the object has a property with the hidden string as name.
1965 static bool HasHiddenProperties(Handle<JSObject> object);
1967 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1969 static void ValidateElements(Handle<JSObject> object);
1971 // Makes sure that this object can contain HeapObject as elements.
1972 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1974 // Makes sure that this object can contain the specified elements.
1975 static inline void EnsureCanContainElements(
1976 Handle<JSObject> object,
1979 EnsureElementsMode mode);
1980 static inline void EnsureCanContainElements(
1981 Handle<JSObject> object,
1982 Handle<FixedArrayBase> elements,
1984 EnsureElementsMode mode);
1985 static void EnsureCanContainElements(
1986 Handle<JSObject> object,
1987 Arguments* arguments,
1990 EnsureElementsMode mode);
1992 // Would we convert a fast elements array to dictionary mode given
1993 // an access at key?
1994 bool WouldConvertToSlowElements(uint32_t index);
1996 // Computes the new capacity when expanding the elements of a JSObject.
1997 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1998 // (old_capacity + 50%) + 16
1999 return old_capacity + (old_capacity >> 1) + 16;
2002 // These methods do not perform access checks!
2003 static void UpdateAllocationSite(Handle<JSObject> object,
2004 ElementsKind to_kind);
2006 // Lookup interceptors are used for handling properties controlled by host
2008 inline bool HasNamedInterceptor();
2009 inline bool HasIndexedInterceptor();
2011 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2012 // by JSReceiver::GetKeys.
2013 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2014 Handle<JSObject> object,
2015 Handle<JSReceiver> receiver);
2016 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2017 Handle<JSObject> object,
2018 Handle<JSReceiver> receiver);
2020 // Support functions for v8 api (needed for correct interceptor behavior).
2021 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2022 Handle<JSObject> object, Handle<Name> name);
2023 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2024 Handle<JSObject> object, uint32_t index);
2025 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2026 Handle<JSObject> object, Handle<Name> name);
2028 // Get the header size for a JSObject. Used to compute the index of
2029 // internal fields as well as the number of internal fields.
2030 inline int GetHeaderSize();
2032 inline int GetInternalFieldCount();
2033 inline int GetInternalFieldOffset(int index);
2034 inline Object* GetInternalField(int index);
2035 inline void SetInternalField(int index, Object* value);
2036 inline void SetInternalField(int index, Smi* value);
2038 // Returns the number of properties on this object filtering out properties
2039 // with the specified attributes (ignoring interceptors).
2040 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2041 // Fill in details for properties into storage starting at the specified
2042 // index. Returns the number of properties added.
2043 int GetOwnPropertyNames(FixedArray* storage, int index,
2044 PropertyAttributes filter = NONE);
2046 // Returns the number of properties on this object filtering out properties
2047 // with the specified attributes (ignoring interceptors).
2048 int NumberOfOwnElements(PropertyAttributes filter);
2049 // Returns the number of enumerable elements (ignoring interceptors).
2050 int NumberOfEnumElements();
2051 // Returns the number of elements on this object filtering out elements
2052 // with the specified attributes (ignoring interceptors).
2053 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2054 // Count and fill in the enumerable elements into storage.
2055 // (storage->length() == NumberOfEnumElements()).
2056 // If storage is NULL, will count the elements without adding
2057 // them to any storage.
2058 // Returns the number of enumerable elements.
2059 int GetEnumElementKeys(FixedArray* storage);
2061 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2064 // Returns a new map with all transitions dropped from the object's current
2065 // map and the ElementsKind set.
2066 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2067 ElementsKind to_kind);
2068 static void TransitionElementsKind(Handle<JSObject> object,
2069 ElementsKind to_kind);
2071 // Always use this to migrate an object to a new map.
2072 // |expected_additional_properties| is only used for fast-to-slow transitions
2073 // and ignored otherwise.
2074 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2075 int expected_additional_properties = 0);
2077 // Convert the object to use the canonical dictionary
2078 // representation. If the object is expected to have additional properties
2079 // added this number can be indicated to have the backing store allocated to
2080 // an initial capacity for holding these properties.
2081 static void NormalizeProperties(Handle<JSObject> object,
2082 PropertyNormalizationMode mode,
2083 int expected_additional_properties,
2084 const char* reason);
2086 // Convert and update the elements backing store to be a
2087 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2088 static Handle<SeededNumberDictionary> NormalizeElements(
2089 Handle<JSObject> object);
2091 void RequireSlowElements(SeededNumberDictionary* dictionary);
2093 // Transform slow named properties to fast variants.
2094 static void MigrateSlowToFast(Handle<JSObject> object,
2095 int unused_property_fields, const char* reason);
2097 inline bool IsUnboxedDoubleField(FieldIndex index);
2099 // Access fast-case object properties at index.
2100 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2101 Representation representation,
2103 inline Object* RawFastPropertyAt(FieldIndex index);
2104 inline double RawFastDoublePropertyAt(FieldIndex index);
2106 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2107 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2108 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2109 inline void WriteToField(int descriptor, Object* value);
2111 // Access to in object properties.
2112 inline int GetInObjectPropertyOffset(int index);
2113 inline Object* InObjectPropertyAt(int index);
2114 inline Object* InObjectPropertyAtPut(int index,
2116 WriteBarrierMode mode
2117 = UPDATE_WRITE_BARRIER);
2119 // Set the object's prototype (only JSReceiver and null are allowed values).
2120 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2121 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2123 // Initializes the body after properties slot, properties slot is
2124 // initialized by set_properties. Fill the pre-allocated fields with
2125 // pre_allocated_value and the rest with filler_value.
2126 // Note: this call does not update write barrier, the caller is responsible
2127 // to ensure that |filler_value| can be collected without WB here.
2128 inline void InitializeBody(Map* map,
2129 Object* pre_allocated_value,
2130 Object* filler_value);
2132 // Check whether this object references another object
2133 bool ReferencesObject(Object* obj);
2135 // Disalow further properties to be added to the oject.
2136 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2137 Handle<JSObject> object);
2139 bool IsExtensible();
2142 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2144 // ES5 Object.freeze
2145 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2147 // Called the first time an object is observed with ES7 Object.observe.
2148 static void SetObserved(Handle<JSObject> object);
2151 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2153 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2154 Handle<JSObject> object,
2155 AllocationSiteUsageContext* site_context,
2156 DeepCopyHints hints = kNoHints);
2157 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2158 Handle<JSObject> object,
2159 AllocationSiteCreationContext* site_context);
2161 DECLARE_CAST(JSObject)
2163 // Dispatched behavior.
2164 void JSObjectShortPrint(StringStream* accumulator);
2165 DECLARE_PRINTER(JSObject)
2166 DECLARE_VERIFIER(JSObject)
2168 void PrintProperties(std::ostream& os); // NOLINT
2169 void PrintElements(std::ostream& os); // NOLINT
2171 #if defined(DEBUG) || defined(OBJECT_PRINT)
2172 void PrintTransitions(std::ostream& os); // NOLINT
2175 static void PrintElementsTransition(
2176 FILE* file, Handle<JSObject> object,
2177 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2178 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2180 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2183 // Structure for collecting spill information about JSObjects.
2184 class SpillInformation {
2188 int number_of_objects_;
2189 int number_of_objects_with_fast_properties_;
2190 int number_of_objects_with_fast_elements_;
2191 int number_of_fast_used_fields_;
2192 int number_of_fast_unused_fields_;
2193 int number_of_slow_used_properties_;
2194 int number_of_slow_unused_properties_;
2195 int number_of_fast_used_elements_;
2196 int number_of_fast_unused_elements_;
2197 int number_of_slow_used_elements_;
2198 int number_of_slow_unused_elements_;
2201 void IncrementSpillStatistics(SpillInformation* info);
2205 // If a GC was caused while constructing this object, the elements pointer
2206 // may point to a one pointer filler map. The object won't be rooted, but
2207 // our heap verification code could stumble across it.
2208 bool ElementsAreSafeToExamine();
2211 Object* SlowReverseLookup(Object* value);
2213 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2214 // Also maximal value of JSArray's length property.
2215 static const uint32_t kMaxElementCount = 0xffffffffu;
2217 // Constants for heuristics controlling conversion of fast elements
2218 // to slow elements.
2220 // Maximal gap that can be introduced by adding an element beyond
2221 // the current elements length.
2222 static const uint32_t kMaxGap = 1024;
2224 // Maximal length of fast elements array that won't be checked for
2225 // being dense enough on expansion.
2226 static const int kMaxUncheckedFastElementsLength = 5000;
2228 // Same as above but for old arrays. This limit is more strict. We
2229 // don't want to be wasteful with long lived objects.
2230 static const int kMaxUncheckedOldFastElementsLength = 500;
2232 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2233 // permissible values (see the DCHECK in heap.cc).
2234 static const int kInitialMaxFastElementArray = 100000;
2236 // This constant applies only to the initial map of "global.Object" and
2237 // not to arbitrary other JSObject maps.
2238 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2240 static const int kMaxInstanceSize = 255 * kPointerSize;
2241 // When extending the backing storage for property values, we increase
2242 // its size by more than the 1 entry necessary, so sequentially adding fields
2243 // to the same object requires fewer allocations and copies.
2244 static const int kFieldsAdded = 3;
2246 // Layout description.
2247 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2248 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2249 static const int kHeaderSize = kElementsOffset + kPointerSize;
2251 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2253 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2255 static inline int SizeOf(Map* map, HeapObject* object);
2258 Context* GetCreationContext();
2260 // Enqueue change record for Object.observe. May cause GC.
2261 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2262 Handle<JSObject> object, const char* type, Handle<Name> name,
2263 Handle<Object> old_value);
2265 // Gets the number of currently used elements.
2266 int GetFastElementsUsage();
2268 // Deletes an existing named property in a normalized object.
2269 static void DeleteNormalizedProperty(Handle<JSObject> object,
2270 Handle<Name> name, int entry);
2272 static bool AllCanRead(LookupIterator* it);
2273 static bool AllCanWrite(LookupIterator* it);
2276 friend class JSReceiver;
2277 friend class Object;
2279 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2280 static void MigrateFastToSlow(Handle<JSObject> object,
2281 Handle<Map> new_map,
2282 int expected_additional_properties);
2284 // Used from Object::GetProperty().
2285 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2286 LookupIterator* it);
2288 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2289 LookupIterator* it, Handle<Object> value);
2291 // Add a property to a slow-case object.
2292 static void AddSlowProperty(Handle<JSObject> object,
2294 Handle<Object> value,
2295 PropertyAttributes attributes);
2297 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2298 LookupIterator* it);
2300 bool ReferencesObjectFromElements(FixedArray* elements,
2304 // Return the hash table backing store or the inline stored identity hash,
2305 // whatever is found.
2306 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2308 // Return the hash table backing store for hidden properties. If there is no
2309 // backing store, allocate one.
2310 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2311 Handle<JSObject> object);
2313 // Set the hidden property backing store to either a hash table or
2314 // the inline-stored identity hash.
2315 static Handle<Object> SetHiddenPropertiesHashTable(
2316 Handle<JSObject> object,
2317 Handle<Object> value);
2319 MUST_USE_RESULT Object* GetIdentityHash();
2321 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2323 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2324 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2326 // Helper for fast versions of preventExtensions, seal, and freeze.
2327 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2328 template <PropertyAttributes attrs>
2329 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2330 Handle<JSObject> object);
2332 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2336 // Common superclass for FixedArrays that allow implementations to share
2337 // common accessors and some code paths.
2338 class FixedArrayBase: public HeapObject {
2340 // [length]: length of the array.
2341 inline int length() const;
2342 inline void set_length(int value);
2344 // Get and set the length using acquire loads and release stores.
2345 inline int synchronized_length() const;
2346 inline void synchronized_set_length(int value);
2348 DECLARE_CAST(FixedArrayBase)
2350 // Layout description.
2351 // Length is smi tagged when it is stored.
2352 static const int kLengthOffset = HeapObject::kHeaderSize;
2353 static const int kHeaderSize = kLengthOffset + kPointerSize;
2357 class FixedDoubleArray;
2358 class IncrementalMarking;
2361 // FixedArray describes fixed-sized arrays with element type Object*.
2362 class FixedArray: public FixedArrayBase {
2364 // Setter and getter for elements.
2365 inline Object* get(int index) const;
2366 void SetValue(uint32_t index, Object* value);
2367 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2368 // Setter that uses write barrier.
2369 inline void set(int index, Object* value);
2370 inline bool is_the_hole(int index);
2372 // Setter that doesn't need write barrier.
2373 inline void set(int index, Smi* value);
2374 // Setter with explicit barrier mode.
2375 inline void set(int index, Object* value, WriteBarrierMode mode);
2377 // Setters for frequently used oddballs located in old space.
2378 inline void set_undefined(int index);
2379 inline void set_null(int index);
2380 inline void set_the_hole(int index);
2382 inline Object** GetFirstElementAddress();
2383 inline bool ContainsOnlySmisOrHoles();
2385 // Gives access to raw memory which stores the array's data.
2386 inline Object** data_start();
2388 inline void FillWithHoles(int from, int to);
2390 // Shrink length and insert filler objects.
2391 void Shrink(int length);
2393 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2395 // Add the elements of a JSArray to this FixedArray.
2396 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2397 Handle<FixedArray> content, Handle<JSObject> array,
2398 KeyFilter filter = ALL_KEYS);
2400 // Computes the union of keys and return the result.
2401 // Used for implementing "for (n in object) { }"
2402 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2403 Handle<FixedArray> first,
2404 Handle<FixedArray> second);
2406 // Copy a sub array from the receiver to dest.
2407 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2409 // Garbage collection support.
2410 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2412 // Code Generation support.
2413 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2415 // Garbage collection support.
2416 Object** RawFieldOfElementAt(int index) {
2417 return HeapObject::RawField(this, OffsetOfElementAt(index));
2420 DECLARE_CAST(FixedArray)
2422 // Maximal allowed size, in bytes, of a single FixedArray.
2423 // Prevents overflowing size computations, as well as extreme memory
2425 static const int kMaxSize = 128 * MB * kPointerSize;
2426 // Maximally allowed length of a FixedArray.
2427 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2429 // Dispatched behavior.
2430 DECLARE_PRINTER(FixedArray)
2431 DECLARE_VERIFIER(FixedArray)
2433 // Checks if two FixedArrays have identical contents.
2434 bool IsEqualTo(FixedArray* other);
2437 // Swap two elements in a pair of arrays. If this array and the
2438 // numbers array are the same object, the elements are only swapped
2440 void SwapPairs(FixedArray* numbers, int i, int j);
2442 // Sort prefix of this array and the numbers array as pairs wrt. the
2443 // numbers. If the numbers array and the this array are the same
2444 // object, the prefix of this array is sorted.
2445 void SortPairs(FixedArray* numbers, uint32_t len);
2447 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2449 static inline int SizeOf(Map* map, HeapObject* object) {
2451 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2456 // Set operation on FixedArray without using write barriers. Can
2457 // only be used for storing old space objects or smis.
2458 static inline void NoWriteBarrierSet(FixedArray* array,
2462 // Set operation on FixedArray without incremental write barrier. Can
2463 // only be used if the object is guaranteed to be white (whiteness witness
2465 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2470 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2472 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2476 // FixedDoubleArray describes fixed-sized arrays with element type double.
2477 class FixedDoubleArray: public FixedArrayBase {
2479 // Setter and getter for elements.
2480 inline double get_scalar(int index);
2481 inline uint64_t get_representation(int index);
2482 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2483 // This accessor has to get a Number as |value|.
2484 void SetValue(uint32_t index, Object* value);
2485 inline void set(int index, double value);
2486 inline void set_the_hole(int index);
2488 // Checking for the hole.
2489 inline bool is_the_hole(int index);
2491 // Garbage collection support.
2492 inline static int SizeFor(int length) {
2493 return kHeaderSize + length * kDoubleSize;
2496 // Gives access to raw memory which stores the array's data.
2497 inline double* data_start();
2499 inline void FillWithHoles(int from, int to);
2501 // Code Generation support.
2502 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2504 DECLARE_CAST(FixedDoubleArray)
2506 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2507 // Prevents overflowing size computations, as well as extreme memory
2509 static const int kMaxSize = 512 * MB;
2510 // Maximally allowed length of a FixedArray.
2511 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2513 // Dispatched behavior.
2514 DECLARE_PRINTER(FixedDoubleArray)
2515 DECLARE_VERIFIER(FixedDoubleArray)
2518 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2522 class WeakFixedArray : public FixedArray {
2524 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2525 // This function does not check if the value exists already, callers must
2526 // ensure this themselves if necessary.
2527 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2528 Handle<HeapObject> value,
2529 int* assigned_index = NULL);
2531 // Returns true if an entry was found and removed.
2532 bool Remove(Handle<HeapObject> value);
2534 class NullCallback {
2536 static void Callback(Object* value, int old_index, int new_index) {}
2539 template <class CompactionCallback>
2542 inline Object* Get(int index) const;
2543 inline void Clear(int index);
2544 inline int Length() const;
2546 inline bool IsEmptySlot(int index) const;
2547 static Object* Empty() { return Smi::FromInt(0); }
2549 DECLARE_CAST(WeakFixedArray)
2552 static const int kLastUsedIndexIndex = 0;
2553 static const int kFirstIndex = 1;
2555 static Handle<WeakFixedArray> Allocate(
2556 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2558 static void Set(Handle<WeakFixedArray> array, int index,
2559 Handle<HeapObject> value);
2560 inline void clear(int index);
2562 inline int last_used_index() const;
2563 inline void set_last_used_index(int index);
2565 // Disallow inherited setters.
2566 void set(int index, Smi* value);
2567 void set(int index, Object* value);
2568 void set(int index, Object* value, WriteBarrierMode mode);
2569 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2573 // Generic array grows dynamically with O(1) amortized insertion.
2574 class ArrayList : public FixedArray {
2578 // Use this if GC can delete elements from the array.
2579 kReloadLengthAfterAllocation,
2581 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2582 AddMode mode = kNone);
2583 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2584 Handle<Object> obj2, AddMode = kNone);
2585 inline int Length();
2586 inline void SetLength(int length);
2587 inline Object* Get(int index);
2588 inline Object** Slot(int index);
2589 inline void Set(int index, Object* obj);
2590 inline void Clear(int index, Object* undefined);
2591 DECLARE_CAST(ArrayList)
2594 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2595 static const int kLengthIndex = 0;
2596 static const int kFirstIndex = 1;
2597 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2601 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2602 // The format of the these objects is:
2603 // [0]: Number of descriptors
2604 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2605 // [0]: pointer to fixed array with enum cache
2606 // [1]: either Smi(0) or pointer to fixed array with indices
2608 // [2 + number of descriptors * kDescriptorSize]: start of slack
2609 class DescriptorArray: public FixedArray {
2611 // Returns true for both shared empty_descriptor_array and for smis, which the
2612 // map uses to encode additional bit fields when the descriptor array is not
2614 inline bool IsEmpty();
2616 // Returns the number of descriptors in the array.
2617 int number_of_descriptors() {
2618 DCHECK(length() >= kFirstIndex || IsEmpty());
2620 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2623 int number_of_descriptors_storage() {
2625 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2628 int NumberOfSlackDescriptors() {
2629 return number_of_descriptors_storage() - number_of_descriptors();
2632 inline void SetNumberOfDescriptors(int number_of_descriptors);
2633 inline int number_of_entries() { return number_of_descriptors(); }
2635 bool HasEnumCache() {
2636 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2639 void CopyEnumCacheFrom(DescriptorArray* array) {
2640 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2643 FixedArray* GetEnumCache() {
2644 DCHECK(HasEnumCache());
2645 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2646 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2649 bool HasEnumIndicesCache() {
2650 if (IsEmpty()) return false;
2651 Object* object = get(kEnumCacheIndex);
2652 if (object->IsSmi()) return false;
2653 FixedArray* bridge = FixedArray::cast(object);
2654 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2657 FixedArray* GetEnumIndicesCache() {
2658 DCHECK(HasEnumIndicesCache());
2659 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2660 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2663 Object** GetEnumCacheSlot() {
2664 DCHECK(HasEnumCache());
2665 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2669 void ClearEnumCache();
2671 // Initialize or change the enum cache,
2672 // using the supplied storage for the small "bridge".
2673 void SetEnumCache(FixedArray* bridge_storage,
2674 FixedArray* new_cache,
2675 Object* new_index_cache);
2677 bool CanHoldValue(int descriptor, Object* value);
2679 // Accessors for fetching instance descriptor at descriptor number.
2680 inline Name* GetKey(int descriptor_number);
2681 inline Object** GetKeySlot(int descriptor_number);
2682 inline Object* GetValue(int descriptor_number);
2683 inline void SetValue(int descriptor_number, Object* value);
2684 inline Object** GetValueSlot(int descriptor_number);
2685 static inline int GetValueOffset(int descriptor_number);
2686 inline Object** GetDescriptorStartSlot(int descriptor_number);
2687 inline Object** GetDescriptorEndSlot(int descriptor_number);
2688 inline PropertyDetails GetDetails(int descriptor_number);
2689 inline PropertyType GetType(int descriptor_number);
2690 inline int GetFieldIndex(int descriptor_number);
2691 inline HeapType* GetFieldType(int descriptor_number);
2692 inline Object* GetConstant(int descriptor_number);
2693 inline Object* GetCallbacksObject(int descriptor_number);
2694 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2696 inline Name* GetSortedKey(int descriptor_number);
2697 inline int GetSortedKeyIndex(int descriptor_number);
2698 inline void SetSortedKey(int pointer, int descriptor_number);
2699 inline void SetRepresentation(int descriptor_number,
2700 Representation representation);
2702 // Accessor for complete descriptor.
2703 inline void Get(int descriptor_number, Descriptor* desc);
2704 inline void Set(int descriptor_number, Descriptor* desc);
2705 void Replace(int descriptor_number, Descriptor* descriptor);
2707 // Append automatically sets the enumeration index. This should only be used
2708 // to add descriptors in bulk at the end, followed by sorting the descriptor
2710 inline void Append(Descriptor* desc);
2712 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2713 int enumeration_index,
2716 static Handle<DescriptorArray> CopyUpToAddAttributes(
2717 Handle<DescriptorArray> desc,
2718 int enumeration_index,
2719 PropertyAttributes attributes,
2722 // Sort the instance descriptors by the hash codes of their keys.
2725 // Search the instance descriptors for given name.
2726 INLINE(int Search(Name* name, int number_of_own_descriptors));
2728 // As the above, but uses DescriptorLookupCache and updates it when
2730 INLINE(int SearchWithCache(Name* name, Map* map));
2732 // Allocates a DescriptorArray, but returns the singleton
2733 // empty descriptor array object if number_of_descriptors is 0.
2734 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2735 int number_of_descriptors,
2738 DECLARE_CAST(DescriptorArray)
2740 // Constant for denoting key was not found.
2741 static const int kNotFound = -1;
2743 static const int kDescriptorLengthIndex = 0;
2744 static const int kEnumCacheIndex = 1;
2745 static const int kFirstIndex = 2;
2747 // The length of the "bridge" to the enum cache.
2748 static const int kEnumCacheBridgeLength = 2;
2749 static const int kEnumCacheBridgeCacheIndex = 0;
2750 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2752 // Layout description.
2753 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2754 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2755 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2757 // Layout description for the bridge array.
2758 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2760 // Layout of descriptor.
2761 static const int kDescriptorKey = 0;
2762 static const int kDescriptorDetails = 1;
2763 static const int kDescriptorValue = 2;
2764 static const int kDescriptorSize = 3;
2766 #if defined(DEBUG) || defined(OBJECT_PRINT)
2767 // For our gdb macros, we should perhaps change these in the future.
2770 // Print all the descriptors.
2771 void PrintDescriptors(std::ostream& os); // NOLINT
2775 // Is the descriptor array sorted and without duplicates?
2776 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2778 // Is the descriptor array consistent with the back pointers in targets?
2779 bool IsConsistentWithBackPointers(Map* current_map);
2781 // Are two DescriptorArrays equal?
2782 bool IsEqualTo(DescriptorArray* other);
2785 // Returns the fixed array length required to hold number_of_descriptors
2787 static int LengthFor(int number_of_descriptors) {
2788 return ToKeyIndex(number_of_descriptors);
2792 // WhitenessWitness is used to prove that a descriptor array is white
2793 // (unmarked), so incremental write barriers can be skipped because the
2794 // marking invariant cannot be broken and slots pointing into evacuation
2795 // candidates will be discovered when the object is scanned. A witness is
2796 // always stack-allocated right after creating an array. By allocating a
2797 // witness, incremental marking is globally disabled. The witness is then
2798 // passed along wherever needed to statically prove that the array is known to
2800 class WhitenessWitness {
2802 inline explicit WhitenessWitness(DescriptorArray* array);
2803 inline ~WhitenessWitness();
2806 IncrementalMarking* marking_;
2809 // An entry in a DescriptorArray, represented as an (array, index) pair.
2812 inline explicit Entry(DescriptorArray* descs, int index) :
2813 descs_(descs), index_(index) { }
2815 inline PropertyType type() { return descs_->GetType(index_); }
2816 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2819 DescriptorArray* descs_;
2823 // Conversion from descriptor number to array indices.
2824 static int ToKeyIndex(int descriptor_number) {
2825 return kFirstIndex +
2826 (descriptor_number * kDescriptorSize) +
2830 static int ToDetailsIndex(int descriptor_number) {
2831 return kFirstIndex +
2832 (descriptor_number * kDescriptorSize) +
2836 static int ToValueIndex(int descriptor_number) {
2837 return kFirstIndex +
2838 (descriptor_number * kDescriptorSize) +
2842 // Transfer a complete descriptor from the src descriptor array to this
2843 // descriptor array.
2844 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2846 inline void Set(int descriptor_number,
2848 const WhitenessWitness&);
2850 // Swap first and second descriptor.
2851 inline void SwapSortedKeys(int first, int second);
2853 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2857 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2859 template <SearchMode search_mode, typename T>
2860 inline int Search(T* array, Name* name, int valid_entries = 0,
2861 int* out_insertion_index = NULL);
2864 // HashTable is a subclass of FixedArray that implements a hash table
2865 // that uses open addressing and quadratic probing.
2867 // In order for the quadratic probing to work, elements that have not
2868 // yet been used and elements that have been deleted are
2869 // distinguished. Probing continues when deleted elements are
2870 // encountered and stops when unused elements are encountered.
2872 // - Elements with key == undefined have not been used yet.
2873 // - Elements with key == the_hole have been deleted.
2875 // The hash table class is parameterized with a Shape and a Key.
2876 // Shape must be a class with the following interface:
2877 // class ExampleShape {
2879 // // Tells whether key matches other.
2880 // static bool IsMatch(Key key, Object* other);
2881 // // Returns the hash value for key.
2882 // static uint32_t Hash(Key key);
2883 // // Returns the hash value for object.
2884 // static uint32_t HashForObject(Key key, Object* object);
2885 // // Convert key to an object.
2886 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2887 // // The prefix size indicates number of elements in the beginning
2888 // // of the backing storage.
2889 // static const int kPrefixSize = ..;
2890 // // The Element size indicates number of elements per entry.
2891 // static const int kEntrySize = ..;
2893 // The prefix size indicates an amount of memory in the
2894 // beginning of the backing storage that can be used for non-element
2895 // information by subclasses.
2897 template<typename Key>
2900 static const bool UsesSeed = false;
2901 static uint32_t Hash(Key key) { return 0; }
2902 static uint32_t SeededHash(Key key, uint32_t seed) {
2906 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2907 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2909 return HashForObject(key, object);
2914 class HashTableBase : public FixedArray {
2916 // Returns the number of elements in the hash table.
2917 int NumberOfElements() {
2918 return Smi::cast(get(kNumberOfElementsIndex))->value();
2921 // Returns the number of deleted elements in the hash table.
2922 int NumberOfDeletedElements() {
2923 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2926 // Returns the capacity of the hash table.
2928 return Smi::cast(get(kCapacityIndex))->value();
2931 // ElementAdded should be called whenever an element is added to a
2933 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2935 // ElementRemoved should be called whenever an element is removed from
2937 void ElementRemoved() {
2938 SetNumberOfElements(NumberOfElements() - 1);
2939 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2941 void ElementsRemoved(int n) {
2942 SetNumberOfElements(NumberOfElements() - n);
2943 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2946 // Computes the required capacity for a table holding the given
2947 // number of elements. May be more than HashTable::kMaxCapacity.
2948 static inline int ComputeCapacity(int at_least_space_for);
2950 // Tells whether k is a real key. The hole and undefined are not allowed
2951 // as keys and can be used to indicate missing or deleted elements.
2952 bool IsKey(Object* k) {
2953 return !k->IsTheHole() && !k->IsUndefined();
2956 // Compute the probe offset (quadratic probing).
2957 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2958 return (n + n * n) >> 1;
2961 static const int kNumberOfElementsIndex = 0;
2962 static const int kNumberOfDeletedElementsIndex = 1;
2963 static const int kCapacityIndex = 2;
2964 static const int kPrefixStartIndex = 3;
2966 // Constant used for denoting a absent entry.
2967 static const int kNotFound = -1;
2970 // Update the number of elements in the hash table.
2971 void SetNumberOfElements(int nof) {
2972 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2975 // Update the number of deleted elements in the hash table.
2976 void SetNumberOfDeletedElements(int nod) {
2977 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2980 // Returns probe entry.
2981 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2982 DCHECK(base::bits::IsPowerOfTwo32(size));
2983 return (hash + GetProbeOffset(number)) & (size - 1);
2986 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2987 return hash & (size - 1);
2990 inline static uint32_t NextProbe(
2991 uint32_t last, uint32_t number, uint32_t size) {
2992 return (last + number) & (size - 1);
2997 template <typename Derived, typename Shape, typename Key>
2998 class HashTable : public HashTableBase {
3001 inline uint32_t Hash(Key key) {
3002 if (Shape::UsesSeed) {
3003 return Shape::SeededHash(key, GetHeap()->HashSeed());
3005 return Shape::Hash(key);
3009 inline uint32_t HashForObject(Key key, Object* object) {
3010 if (Shape::UsesSeed) {
3011 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3013 return Shape::HashForObject(key, object);
3017 // Returns a new HashTable object.
3018 MUST_USE_RESULT static Handle<Derived> New(
3019 Isolate* isolate, int at_least_space_for,
3020 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3021 PretenureFlag pretenure = NOT_TENURED);
3023 DECLARE_CAST(HashTable)
3025 // Garbage collection support.
3026 void IteratePrefix(ObjectVisitor* visitor);
3027 void IterateElements(ObjectVisitor* visitor);
3029 // Find entry for key otherwise return kNotFound.
3030 inline int FindEntry(Key key);
3031 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3032 int FindEntry(Isolate* isolate, Key key);
3034 // Rehashes the table in-place.
3035 void Rehash(Key key);
3037 // Returns the key at entry.
3038 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3040 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3041 static const int kEntrySize = Shape::kEntrySize;
3042 static const int kElementsStartOffset =
3043 kHeaderSize + kElementsStartIndex * kPointerSize;
3044 static const int kCapacityOffset =
3045 kHeaderSize + kCapacityIndex * kPointerSize;
3047 // Returns the index for an entry (of the key)
3048 static inline int EntryToIndex(int entry) {
3049 return (entry * kEntrySize) + kElementsStartIndex;
3053 friend class ObjectHashTable;
3055 // Find the entry at which to insert element with the given key that
3056 // has the given hash value.
3057 uint32_t FindInsertionEntry(uint32_t hash);
3059 // Attempt to shrink hash table after removal of key.
3060 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3062 // Ensure enough space for n additional elements.
3063 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3064 Handle<Derived> table,
3067 PretenureFlag pretenure = NOT_TENURED);
3069 // Sets the capacity of the hash table.
3070 void SetCapacity(int capacity) {
3071 // To scale a computed hash code to fit within the hash table, we
3072 // use bit-wise AND with a mask, so the capacity must be positive
3074 DCHECK(capacity > 0);
3075 DCHECK(capacity <= kMaxCapacity);
3076 set(kCapacityIndex, Smi::FromInt(capacity));
3079 // Maximal capacity of HashTable. Based on maximal length of underlying
3080 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3082 static const int kMaxCapacity =
3083 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3086 // Returns _expected_ if one of entries given by the first _probe_ probes is
3087 // equal to _expected_. Otherwise, returns the entry given by the probe
3089 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3091 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3093 // Rehashes this hash-table into the new table.
3094 void Rehash(Handle<Derived> new_table, Key key);
3098 // HashTableKey is an abstract superclass for virtual key behavior.
3099 class HashTableKey {
3101 // Returns whether the other object matches this key.
3102 virtual bool IsMatch(Object* other) = 0;
3103 // Returns the hash value for this key.
3104 virtual uint32_t Hash() = 0;
3105 // Returns the hash value for object.
3106 virtual uint32_t HashForObject(Object* key) = 0;
3107 // Returns the key object for storing into the hash table.
3108 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3110 virtual ~HashTableKey() {}
3114 class StringTableShape : public BaseShape<HashTableKey*> {
3116 static inline bool IsMatch(HashTableKey* key, Object* value) {
3117 return key->IsMatch(value);
3120 static inline uint32_t Hash(HashTableKey* key) {
3124 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3125 return key->HashForObject(object);
3128 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3130 static const int kPrefixSize = 0;
3131 static const int kEntrySize = 1;
3134 class SeqOneByteString;
3138 // No special elements in the prefix and the element size is 1
3139 // because only the string itself (the key) needs to be stored.
3140 class StringTable: public HashTable<StringTable,
3144 // Find string in the string table. If it is not there yet, it is
3145 // added. The return value is the string found.
3146 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3147 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3148 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3150 // Tries to internalize given string and returns string handle on success
3151 // or an empty handle otherwise.
3152 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3154 Handle<String> string);
3156 // Looks up a string that is equal to the given string and returns
3157 // string handle if it is found, or an empty handle otherwise.
3158 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3160 Handle<String> str);
3161 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3166 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3168 DECLARE_CAST(StringTable)
3171 template <bool seq_one_byte>
3172 friend class JsonParser;
3174 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3178 template <typename Derived, typename Shape, typename Key>
3179 class Dictionary: public HashTable<Derived, Shape, Key> {
3180 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3183 // Returns the value at entry.
3184 Object* ValueAt(int entry) {
3185 return this->get(Derived::EntryToIndex(entry) + 1);
3188 // Set the value for entry.
3189 void ValueAtPut(int entry, Object* value) {
3190 this->set(Derived::EntryToIndex(entry) + 1, value);
3193 // Returns the property details for the property at entry.
3194 PropertyDetails DetailsAt(int entry) {
3195 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3198 // Set the details for entry.
3199 void DetailsAtPut(int entry, PropertyDetails value) {
3200 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3203 // Returns true if property at given entry is deleted.
3204 bool IsDeleted(int entry) {
3205 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3208 // Delete a property from the dictionary.
3209 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3211 // Attempt to shrink the dictionary after deletion of key.
3212 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3213 Handle<Derived> dictionary,
3215 return DerivedHashTable::Shrink(dictionary, key);
3219 // TODO(dcarney): templatize or move to SeededNumberDictionary
3220 void CopyValuesTo(FixedArray* elements);
3222 // Returns the number of elements in the dictionary filtering out properties
3223 // with the specified attributes.
3224 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3226 // Returns the number of enumerable elements in the dictionary.
3227 int NumberOfEnumElements() {
3228 return NumberOfElementsFilterAttributes(
3229 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3232 // Returns true if the dictionary contains any elements that are non-writable,
3233 // non-configurable, non-enumerable, or have getters/setters.
3234 bool HasComplexElements();
3236 enum SortMode { UNSORTED, SORTED };
3238 // Fill in details for properties into storage.
3239 // Returns the number of properties added.
3240 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3241 SortMode sort_mode);
3243 // Copies enumerable keys to preallocated fixed array.
3244 void CopyEnumKeysTo(FixedArray* storage);
3246 // Accessors for next enumeration index.
3247 void SetNextEnumerationIndex(int index) {
3249 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3252 int NextEnumerationIndex() {
3253 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3256 // Creates a new dictionary.
3257 MUST_USE_RESULT static Handle<Derived> New(
3259 int at_least_space_for,
3260 PretenureFlag pretenure = NOT_TENURED);
3262 // Ensure enough space for n additional elements.
3263 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3266 void Print(std::ostream& os); // NOLINT
3268 // Returns the key (slow).
3269 Object* SlowReverseLookup(Object* value);
3271 // Sets the entry to (key, value) pair.
3272 inline void SetEntry(int entry,
3274 Handle<Object> value);
3275 inline void SetEntry(int entry,
3277 Handle<Object> value,
3278 PropertyDetails details);
3280 MUST_USE_RESULT static Handle<Derived> Add(
3281 Handle<Derived> dictionary,
3283 Handle<Object> value,
3284 PropertyDetails details);
3286 // Returns iteration indices array for the |dictionary|.
3287 // Values are direct indices in the |HashTable| array.
3288 static Handle<FixedArray> BuildIterationIndicesArray(
3289 Handle<Derived> dictionary);
3292 // Generic at put operation.
3293 MUST_USE_RESULT static Handle<Derived> AtPut(
3294 Handle<Derived> dictionary,
3296 Handle<Object> value);
3298 // Add entry to dictionary.
3299 static void AddEntry(
3300 Handle<Derived> dictionary,
3302 Handle<Object> value,
3303 PropertyDetails details,
3306 // Generate new enumeration indices to avoid enumeration index overflow.
3307 // Returns iteration indices array for the |dictionary|.
3308 static Handle<FixedArray> GenerateNewEnumerationIndices(
3309 Handle<Derived> dictionary);
3310 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3311 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3315 template <typename Derived, typename Shape>
3316 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3317 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3320 // Find entry for key, otherwise return kNotFound. Optimized version of
3321 // HashTable::FindEntry.
3322 int FindEntry(Handle<Name> key);
3326 template <typename Key>
3327 class BaseDictionaryShape : public BaseShape<Key> {
3329 template <typename Dictionary>
3330 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3331 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3332 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3333 return PropertyDetails(
3334 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3337 template <typename Dictionary>
3338 static inline void DetailsAtPut(Dictionary* dict, int entry,
3339 PropertyDetails value) {
3340 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3341 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3344 template <typename Dictionary>
3345 static bool IsDeleted(Dictionary* dict, int entry) {
3349 template <typename Dictionary>
3350 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3351 Handle<Object> value, PropertyDetails details);
3355 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3357 static inline bool IsMatch(Handle<Name> key, Object* other);
3358 static inline uint32_t Hash(Handle<Name> key);
3359 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3360 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3361 static const int kPrefixSize = 2;
3362 static const int kEntrySize = 3;
3363 static const bool kIsEnumerable = true;
3367 class NameDictionary
3368 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3369 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3373 DECLARE_CAST(NameDictionary)
3375 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3376 Handle<NameDictionary> dictionary);
3380 class GlobalDictionaryShape : public NameDictionaryShape {
3382 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3384 template <typename Dictionary>
3385 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3387 template <typename Dictionary>
3388 static inline void DetailsAtPut(Dictionary* dict, int entry,
3389 PropertyDetails value);
3391 template <typename Dictionary>
3392 static bool IsDeleted(Dictionary* dict, int entry);
3394 template <typename Dictionary>
3395 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3396 Handle<Object> value, PropertyDetails details);
3400 class GlobalDictionary
3401 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3403 DECLARE_CAST(GlobalDictionary)
3407 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3409 static inline bool IsMatch(uint32_t key, Object* other);
3410 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3411 static const int kEntrySize = 3;
3412 static const bool kIsEnumerable = false;
3416 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3418 static const bool UsesSeed = true;
3419 static const int kPrefixSize = 2;
3421 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3422 static inline uint32_t SeededHashForObject(uint32_t key,
3428 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3430 static const int kPrefixSize = 0;
3432 static inline uint32_t Hash(uint32_t key);
3433 static inline uint32_t HashForObject(uint32_t key, Object* object);
3437 class SeededNumberDictionary
3438 : public Dictionary<SeededNumberDictionary,
3439 SeededNumberDictionaryShape,
3442 DECLARE_CAST(SeededNumberDictionary)
3444 // Type specific at put (default NONE attributes is used when adding).
3445 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3446 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3447 Handle<Object> value, bool used_as_prototype);
3448 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3449 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3450 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3452 // Set an existing entry or add a new one if needed.
3453 // Return the updated dictionary.
3454 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3455 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3456 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3458 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3460 // If slow elements are required we will never go back to fast-case
3461 // for the elements kept in this dictionary. We require slow
3462 // elements if an element has been added at an index larger than
3463 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3464 // when defining a getter or setter with a number key.
3465 inline bool requires_slow_elements();
3466 inline void set_requires_slow_elements();
3468 // Get the value of the max number key that has been added to this
3469 // dictionary. max_number_key can only be called if
3470 // requires_slow_elements returns false.
3471 inline uint32_t max_number_key();
3474 static const int kRequiresSlowElementsMask = 1;
3475 static const int kRequiresSlowElementsTagSize = 1;
3476 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3480 class UnseededNumberDictionary
3481 : public Dictionary<UnseededNumberDictionary,
3482 UnseededNumberDictionaryShape,
3485 DECLARE_CAST(UnseededNumberDictionary)
3487 // Type specific at put (default NONE attributes is used when adding).
3488 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3489 Handle<UnseededNumberDictionary> dictionary,
3491 Handle<Object> value);
3492 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3493 Handle<UnseededNumberDictionary> dictionary,
3495 Handle<Object> value);
3497 // Set an existing entry or add a new one if needed.
3498 // Return the updated dictionary.
3499 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3500 Handle<UnseededNumberDictionary> dictionary,
3502 Handle<Object> value);
3506 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3508 static inline bool IsMatch(Handle<Object> key, Object* other);
3509 static inline uint32_t Hash(Handle<Object> key);
3510 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3511 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3512 static const int kPrefixSize = 0;
3513 static const int kEntrySize = 2;
3517 // ObjectHashTable maps keys that are arbitrary objects to object values by
3518 // using the identity hash of the key for hashing purposes.
3519 class ObjectHashTable: public HashTable<ObjectHashTable,
3520 ObjectHashTableShape,
3523 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3525 DECLARE_CAST(ObjectHashTable)
3527 // Attempt to shrink hash table after removal of key.
3528 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3529 Handle<ObjectHashTable> table,
3530 Handle<Object> key);
3532 // Looks up the value associated with the given key. The hole value is
3533 // returned in case the key is not present.
3534 Object* Lookup(Handle<Object> key);
3535 Object* Lookup(Handle<Object> key, int32_t hash);
3536 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3538 // Adds (or overwrites) the value associated with the given key.
3539 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3541 Handle<Object> value);
3542 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3543 Handle<Object> key, Handle<Object> value,
3546 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3547 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3550 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3551 Handle<Object> key, bool* was_present,
3555 friend class MarkCompactCollector;
3557 void AddEntry(int entry, Object* key, Object* value);
3558 void RemoveEntry(int entry);
3560 // Returns the index to the value of an entry.
3561 static inline int EntryToValueIndex(int entry) {
3562 return EntryToIndex(entry) + 1;
3567 // OrderedHashTable is a HashTable with Object keys that preserves
3568 // insertion order. There are Map and Set interfaces (OrderedHashMap
3569 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3571 // Only Object* keys are supported, with Object::SameValueZero() used as the
3572 // equality operator and Object::GetHash() for the hash function.
3574 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3575 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3576 // Originally attributed to Tyler Close.
3579 // [0]: bucket count
3580 // [1]: element count
3581 // [2]: deleted element count
3582 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3583 // offset into the data table (see below) where the
3584 // first item in this bucket is stored.
3585 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3586 // Capacity() * kEntrySize, where the first entrysize
3587 // items are handled by the derived class and the
3588 // item at kChainOffset is another entry into the
3589 // data table indicating the next entry in this hash
3592 // When we transition the table to a new version we obsolete it and reuse parts
3593 // of the memory to store information how to transition an iterator to the new
3596 // Memory layout for obsolete table:
3597 // [0]: bucket count
3598 // [1]: Next newer table
3599 // [2]: Number of removed holes or -1 when the table was cleared.
3600 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3601 // [3 + NumberOfRemovedHoles()..length]: Not used
3603 template<class Derived, class Iterator, int entrysize>
3604 class OrderedHashTable: public FixedArray {
3606 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3607 static Handle<Derived> Allocate(
3608 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3610 // Returns an OrderedHashTable (possibly |table|) with enough space
3611 // to add at least one new element.
3612 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3614 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3616 static Handle<Derived> Shrink(Handle<Derived> table);
3618 // Returns a new empty OrderedHashTable and records the clearing so that
3619 // exisiting iterators can be updated.
3620 static Handle<Derived> Clear(Handle<Derived> table);
3622 int NumberOfElements() {
3623 return Smi::cast(get(kNumberOfElementsIndex))->value();
3626 int NumberOfDeletedElements() {
3627 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3630 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3632 int NumberOfBuckets() {
3633 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3636 // Returns an index into |this| for the given entry.
3637 int EntryToIndex(int entry) {
3638 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3641 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3644 return !get(kNextTableIndex)->IsSmi();
3647 // The next newer table. This is only valid if the table is obsolete.
3648 Derived* NextTable() {
3649 return Derived::cast(get(kNextTableIndex));
3652 // When the table is obsolete we store the indexes of the removed holes.
3653 int RemovedIndexAt(int index) {
3654 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3657 static const int kNotFound = -1;
3658 static const int kMinCapacity = 4;
3660 static const int kNumberOfBucketsIndex = 0;
3661 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3662 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3663 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3664 static const int kNextTableIndex = kNumberOfElementsIndex;
3666 static const int kNumberOfBucketsOffset =
3667 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3668 static const int kNumberOfElementsOffset =
3669 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3670 static const int kNumberOfDeletedElementsOffset =
3671 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3672 static const int kHashTableStartOffset =
3673 kHeaderSize + kHashTableStartIndex * kPointerSize;
3674 static const int kNextTableOffset =
3675 kHeaderSize + kNextTableIndex * kPointerSize;
3677 static const int kEntrySize = entrysize + 1;
3678 static const int kChainOffset = entrysize;
3680 static const int kLoadFactor = 2;
3682 // NumberOfDeletedElements is set to kClearedTableSentinel when
3683 // the table is cleared, which allows iterator transitions to
3684 // optimize that case.
3685 static const int kClearedTableSentinel = -1;
3688 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3690 void SetNumberOfBuckets(int num) {
3691 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3694 void SetNumberOfElements(int num) {
3695 set(kNumberOfElementsIndex, Smi::FromInt(num));
3698 void SetNumberOfDeletedElements(int num) {
3699 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3703 return NumberOfBuckets() * kLoadFactor;
3706 void SetNextTable(Derived* next_table) {
3707 set(kNextTableIndex, next_table);
3710 void SetRemovedIndexAt(int index, int removed_index) {
3711 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3714 static const int kRemovedHolesIndex = kHashTableStartIndex;
3716 static const int kMaxCapacity =
3717 (FixedArray::kMaxLength - kHashTableStartIndex)
3718 / (1 + (kEntrySize * kLoadFactor));
3722 class JSSetIterator;
3725 class OrderedHashSet: public OrderedHashTable<
3726 OrderedHashSet, JSSetIterator, 1> {
3728 DECLARE_CAST(OrderedHashSet)
3732 class JSMapIterator;
3735 class OrderedHashMap
3736 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3738 DECLARE_CAST(OrderedHashMap)
3740 Object* ValueAt(int entry) {
3741 return get(EntryToIndex(entry) + kValueOffset);
3744 static const int kValueOffset = 1;
3748 template <int entrysize>
3749 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3751 static inline bool IsMatch(Handle<Object> key, Object* other);
3752 static inline uint32_t Hash(Handle<Object> key);
3753 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3754 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3755 static const int kPrefixSize = 0;
3756 static const int kEntrySize = entrysize;
3760 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3761 // values. The table wraps the keys in weak cells and store values directly.
3762 // Thus it references keys weakly and values strongly.
3763 class WeakHashTable: public HashTable<WeakHashTable,
3764 WeakHashTableShape<2>,
3767 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3769 DECLARE_CAST(WeakHashTable)
3771 // Looks up the value associated with the given key. The hole value is
3772 // returned in case the key is not present.
3773 Object* Lookup(Handle<HeapObject> key);
3775 // Adds (or overwrites) the value associated with the given key. Mapping a
3776 // key to the hole value causes removal of the whole entry.
3777 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3778 Handle<HeapObject> key,
3779 Handle<HeapObject> value);
3781 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3784 friend class MarkCompactCollector;
3786 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3788 // Returns the index to the value of an entry.
3789 static inline int EntryToValueIndex(int entry) {
3790 return EntryToIndex(entry) + 1;
3795 class WeakValueHashTable : public ObjectHashTable {
3797 DECLARE_CAST(WeakValueHashTable)
3800 // Looks up the value associated with the given key. The hole value is
3801 // returned in case the key is not present.
3802 Object* LookupWeak(Handle<Object> key);
3805 // Adds (or overwrites) the value associated with the given key. Mapping a
3806 // key to the hole value causes removal of the whole entry.
3807 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3808 Handle<WeakValueHashTable> table, Handle<Object> key,
3809 Handle<HeapObject> value);
3811 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3815 // ScopeInfo represents information about different scopes of a source
3816 // program and the allocation of the scope's variables. Scope information
3817 // is stored in a compressed form in ScopeInfo objects and is used
3818 // at runtime (stack dumps, deoptimization, etc.).
3820 // This object provides quick access to scope info details for runtime
3822 class ScopeInfo : public FixedArray {
3824 DECLARE_CAST(ScopeInfo)
3826 // Return the type of this scope.
3827 ScopeType scope_type();
3829 // Does this scope call eval?
3832 // Return the language mode of this scope.
3833 LanguageMode language_mode();
3835 // Does this scope make a sloppy eval call?
3836 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3838 // Return the total number of locals allocated on the stack and in the
3839 // context. This includes the parameters that are allocated in the context.
3842 // Return the number of stack slots for code. This number consists of two
3844 // 1. One stack slot per stack allocated local.
3845 // 2. One stack slot for the function name if it is stack allocated.
3846 int StackSlotCount();
3848 // Return the number of context slots for code if a context is allocated. This
3849 // number consists of three parts:
3850 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3851 // 2. One context slot per context allocated local.
3852 // 3. One context slot for the function name if it is context allocated.
3853 // Parameters allocated in the context count as context allocated locals. If
3854 // no contexts are allocated for this scope ContextLength returns 0.
3855 int ContextLength();
3857 // Does this scope declare a "this" binding?
3860 // Does this scope declare a "this" binding, and the "this" binding is stack-
3861 // or context-allocated?
3862 bool HasAllocatedReceiver();
3864 // Is this scope the scope of a named function expression?
3865 bool HasFunctionName();
3867 // Return if this has context allocated locals.
3868 bool HasHeapAllocatedLocals();
3870 // Return if contexts are allocated for this scope.
3873 // Return if this is a function scope with "use asm".
3874 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3876 // Return if this is a nested function within an asm module scope.
3877 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3879 bool HasSimpleParameters() {
3880 return HasSimpleParametersField::decode(Flags());
3883 // Return the function_name if present.
3884 String* FunctionName();
3886 // Return the name of the given parameter.
3887 String* ParameterName(int var);
3889 // Return the name of the given local.
3890 String* LocalName(int var);
3892 // Return the name of the given stack local.
3893 String* StackLocalName(int var);
3895 // Return the name of the given stack local.
3896 int StackLocalIndex(int var);
3898 // Return the name of the given context local.
3899 String* ContextLocalName(int var);
3901 // Return the mode of the given context local.
3902 VariableMode ContextLocalMode(int var);
3904 // Return the initialization flag of the given context local.
3905 InitializationFlag ContextLocalInitFlag(int var);
3907 // Return the initialization flag of the given context local.
3908 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3910 // Return true if this local was introduced by the compiler, and should not be
3911 // exposed to the user in a debugger.
3912 bool LocalIsSynthetic(int var);
3914 String* StrongModeFreeVariableName(int var);
3915 int StrongModeFreeVariableStartPosition(int var);
3916 int StrongModeFreeVariableEndPosition(int var);
3918 // Lookup support for serialized scope info. Returns the
3919 // the stack slot index for a given slot name if the slot is
3920 // present; otherwise returns a value < 0. The name must be an internalized
3922 int StackSlotIndex(String* name);
3924 // Lookup support for serialized scope info. Returns the
3925 // context slot index for a given slot name if the slot is present; otherwise
3926 // returns a value < 0. The name must be an internalized string.
3927 // If the slot is present and mode != NULL, sets *mode to the corresponding
3928 // mode for that variable.
3929 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3930 VariableMode* mode, VariableLocation* location,
3931 InitializationFlag* init_flag,
3932 MaybeAssignedFlag* maybe_assigned_flag);
3934 static int LexicalContextSlotIndex(Handle<ScopeInfo> scope_info,
3935 Handle<String> name);
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 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3959 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3961 // Serializes empty scope info.
3962 static ScopeInfo* Empty(Isolate* isolate);
3968 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3969 // numeric and occupies one array slot.
3970 // 1. A set of properties of the scope
3971 // 2. The number of parameters. This only applies to function scopes. For
3972 // non-function scopes this is 0.
3973 // 3. The number of non-parameter variables allocated on the stack.
3974 // 4. The number of non-parameter and parameter variables allocated in the
3976 #define FOR_EACH_NUMERIC_FIELD(V) \
3979 V(StackLocalCount) \
3980 V(ContextLocalCount) \
3981 V(LexicalContextLocalCount) \
3982 V(ContextGlobalCount) \
3983 V(StrongModeFreeVariableCount)
3985 #define FIELD_ACCESSORS(name) \
3986 void Set##name(int value) { \
3987 set(k##name, Smi::FromInt(value)); \
3990 if (length() > 0) { \
3991 return Smi::cast(get(k##name))->value(); \
3996 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
3997 #undef FIELD_ACCESSORS
4001 #define DECL_INDEX(name) k##name,
4002 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4004 #undef FOR_EACH_NUMERIC_FIELD
4008 // The layout of the variable part of a ScopeInfo is as follows:
4009 // 1. ParameterEntries:
4010 // This part stores the names of the parameters for function scopes. One
4011 // slot is used per parameter, so in total this part occupies
4012 // ParameterCount() slots in the array. For other scopes than function
4013 // scopes ParameterCount() is 0.
4014 // 2. StackLocalFirstSlot:
4015 // Index of a first stack slot for stack local. Stack locals belonging to
4016 // this scope are located on a stack at slots starting from this index.
4017 // 3. StackLocalEntries:
4018 // Contains the names of local variables that are allocated on the stack,
4019 // in increasing order of the stack slot index. First local variable has
4020 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4021 // One slot is used per stack local, so in total this part occupies
4022 // StackLocalCount() slots in the array.
4023 // 4. ContextLocalNameEntries:
4024 // Contains the names of local variables and parameters that are allocated
4025 // in the context. They are stored in increasing order of the context slot
4026 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4027 // context local, so in total this part occupies ContextLocalCount() slots
4029 // 5. ContextLocalInfoEntries:
4030 // Contains the variable modes and initialization flags corresponding to
4031 // the context locals in ContextLocalNameEntries. One slot is used per
4032 // context local, so in total this part occupies ContextLocalCount()
4033 // slots in the array.
4034 // 6. StrongModeFreeVariableNameEntries:
4035 // Stores the names of strong mode free variables.
4036 // 7. StrongModeFreeVariablePositionEntries:
4037 // Stores the locations (start and end position) of strong mode free
4039 // 8. RecieverEntryIndex:
4040 // If the scope binds a "this" value, one slot is reserved to hold the
4041 // context or stack slot index for the variable.
4042 // 9. FunctionNameEntryIndex:
4043 // If the scope belongs to a named function expression this part contains
4044 // information about the function variable. It always occupies two array
4045 // slots: a. The name of the function variable.
4046 // b. The context or stack slot index for the variable.
4047 int ParameterEntriesIndex();
4048 int StackLocalFirstSlotIndex();
4049 int StackLocalEntriesIndex();
4050 int ContextLocalNameEntriesIndex();
4051 int ContextGlobalNameEntriesIndex();
4052 int ContextLocalInfoEntriesIndex();
4053 int ContextGlobalInfoEntriesIndex();
4054 int StrongModeFreeVariableNameEntriesIndex();
4055 int StrongModeFreeVariablePositionEntriesIndex();
4056 int ReceiverEntryIndex();
4057 int FunctionNameEntryIndex();
4059 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4060 VariableLocation* location, InitializationFlag* init_flag,
4061 MaybeAssignedFlag* maybe_assigned_flag);
4063 // Used for the function name variable for named function expressions, and for
4065 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4067 // Properties of scopes.
4068 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4069 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4070 STATIC_ASSERT(LANGUAGE_END == 3);
4071 class LanguageModeField
4072 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4073 class ReceiverVariableField
4074 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4075 class FunctionVariableField
4076 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4078 class FunctionVariableMode
4079 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4080 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4082 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4083 class HasSimpleParametersField
4084 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4085 class FunctionKindField
4086 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4088 // BitFields representing the encoded information for context locals in the
4089 // ContextLocalInfoEntries part.
4090 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4091 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4092 class ContextLocalMaybeAssignedFlag
4093 : public BitField<MaybeAssignedFlag, 4, 1> {};
4095 friend class ScopeIterator;
4099 // The cache for maps used by normalized (dictionary mode) objects.
4100 // Such maps do not have property descriptors, so a typical program
4101 // needs very limited number of distinct normalized maps.
4102 class NormalizedMapCache: public FixedArray {
4104 static Handle<NormalizedMapCache> New(Isolate* isolate);
4106 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4107 PropertyNormalizationMode mode);
4108 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4112 DECLARE_CAST(NormalizedMapCache)
4114 static inline bool IsNormalizedMapCache(const Object* obj);
4116 DECLARE_VERIFIER(NormalizedMapCache)
4118 static const int kEntries = 64;
4120 static inline int GetIndex(Handle<Map> map);
4122 // The following declarations hide base class methods.
4123 Object* get(int index);
4124 void set(int index, Object* value);
4128 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4129 // that is attached to code objects.
4130 class ByteArray: public FixedArrayBase {
4132 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4134 // Setter and getter.
4135 inline byte get(int index);
4136 inline void set(int index, byte value);
4138 // Treat contents as an int array.
4139 inline int get_int(int index);
4141 static int SizeFor(int length) {
4142 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4144 // We use byte arrays for free blocks in the heap. Given a desired size in
4145 // bytes that is a multiple of the word size and big enough to hold a byte
4146 // array, this function returns the number of elements a byte array should
4148 static int LengthFor(int size_in_bytes) {
4149 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4150 DCHECK(size_in_bytes >= kHeaderSize);
4151 return size_in_bytes - kHeaderSize;
4154 // Returns data start address.
4155 inline Address GetDataStartAddress();
4157 // Returns a pointer to the ByteArray object for a given data start address.
4158 static inline ByteArray* FromDataStartAddress(Address address);
4160 DECLARE_CAST(ByteArray)
4162 // Dispatched behavior.
4163 inline int ByteArraySize() {
4164 return SizeFor(this->length());
4166 DECLARE_PRINTER(ByteArray)
4167 DECLARE_VERIFIER(ByteArray)
4169 // Layout description.
4170 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4172 // Maximal memory consumption for a single ByteArray.
4173 static const int kMaxSize = 512 * MB;
4174 // Maximal length of a single ByteArray.
4175 static const int kMaxLength = kMaxSize - kHeaderSize;
4178 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4182 // BytecodeArray represents a sequence of interpreter bytecodes.
4183 class BytecodeArray : public FixedArrayBase {
4185 static int SizeFor(int length) {
4186 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4189 // Setter and getter
4190 inline byte get(int index);
4191 inline void set(int index, byte value);
4193 // Returns data start address.
4194 inline Address GetFirstBytecodeAddress();
4196 // Accessors for frame size and the number of locals
4197 inline int frame_size() const;
4198 inline void set_frame_size(int value);
4200 DECLARE_CAST(BytecodeArray)
4202 // Dispatched behavior.
4203 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4205 DECLARE_PRINTER(BytecodeArray)
4206 DECLARE_VERIFIER(BytecodeArray)
4208 void Disassemble(std::ostream& os);
4210 // Layout description.
4211 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4212 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4214 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4216 // Maximal memory consumption for a single BytecodeArray.
4217 static const int kMaxSize = 512 * MB;
4218 // Maximal length of a single BytecodeArray.
4219 static const int kMaxLength = kMaxSize - kHeaderSize;
4222 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4226 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4227 // They look like heap objects (are heap object tagged and have a map) so that
4228 // the heap remains iterable. They have a size and a next pointer.
4229 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4230 // in the free list.
4231 class FreeSpace: public HeapObject {
4233 // [size]: size of the free space including the header.
4234 inline int size() const;
4235 inline void set_size(int value);
4237 inline int nobarrier_size() const;
4238 inline void nobarrier_set_size(int value);
4240 inline int Size() { return size(); }
4242 // Accessors for the next field.
4243 inline FreeSpace* next();
4244 inline FreeSpace** next_address();
4245 inline void set_next(FreeSpace* next);
4247 inline static FreeSpace* cast(HeapObject* obj);
4249 // Dispatched behavior.
4250 DECLARE_PRINTER(FreeSpace)
4251 DECLARE_VERIFIER(FreeSpace)
4253 // Layout description.
4254 // Size is smi tagged when it is stored.
4255 static const int kSizeOffset = HeapObject::kHeaderSize;
4256 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4259 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4263 // V has parameters (Type, type, TYPE, C type, element_size)
4264 #define TYPED_ARRAYS(V) \
4265 V(Uint8, uint8, UINT8, uint8_t, 1) \
4266 V(Int8, int8, INT8, int8_t, 1) \
4267 V(Uint16, uint16, UINT16, uint16_t, 2) \
4268 V(Int16, int16, INT16, int16_t, 2) \
4269 V(Uint32, uint32, UINT32, uint32_t, 4) \
4270 V(Int32, int32, INT32, int32_t, 4) \
4271 V(Float32, float32, FLOAT32, float, 4) \
4272 V(Float64, float64, FLOAT64, double, 8) \
4273 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4276 class FixedTypedArrayBase: public FixedArrayBase {
4278 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4279 DECL_ACCESSORS(base_pointer, Object)
4281 // [external_pointer]: Contains the offset between base_pointer and the start
4282 // of the data. If the base_pointer is a nullptr, the external_pointer
4283 // therefore points to the actual backing store.
4284 DECL_ACCESSORS(external_pointer, void)
4286 // Dispatched behavior.
4287 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4289 template <typename StaticVisitor>
4290 inline void FixedTypedArrayBaseIterateBody();
4292 DECLARE_CAST(FixedTypedArrayBase)
4294 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4295 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4296 static const int kHeaderSize =
4297 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4299 static const int kDataOffset = kHeaderSize;
4303 static inline int TypedArraySize(InstanceType type, int length);
4304 inline int TypedArraySize(InstanceType type);
4306 // Use with care: returns raw pointer into heap.
4307 inline void* DataPtr();
4309 inline int DataSize();
4312 static inline int ElementSize(InstanceType type);
4314 inline int DataSize(InstanceType type);
4316 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4320 template <class Traits>
4321 class FixedTypedArray: public FixedTypedArrayBase {
4323 typedef typename Traits::ElementType ElementType;
4324 static const InstanceType kInstanceType = Traits::kInstanceType;
4326 DECLARE_CAST(FixedTypedArray<Traits>)
4328 inline ElementType get_scalar(int index);
4329 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4330 inline void set(int index, ElementType value);
4332 static inline ElementType from_int(int value);
4333 static inline ElementType from_double(double value);
4335 // This accessor applies the correct conversion from Smi, HeapNumber
4337 void SetValue(uint32_t index, Object* value);
4339 DECLARE_PRINTER(FixedTypedArray)
4340 DECLARE_VERIFIER(FixedTypedArray)
4343 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4346 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4347 class Type##ArrayTraits { \
4348 public: /* NOLINT */ \
4349 typedef elementType ElementType; \
4350 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4351 static const char* Designator() { return #type " array"; } \
4352 static inline Handle<Object> ToHandle(Isolate* isolate, \
4353 elementType scalar); \
4354 static inline elementType defaultValue(); \
4357 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4359 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4361 #undef FIXED_TYPED_ARRAY_TRAITS
4364 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4365 // data for code generated by the Hydrogen/Lithium compiler. It also
4366 // contains information about functions that were inlined. If N different
4367 // functions were inlined then first N elements of the literal array will
4368 // contain these functions.
4371 class DeoptimizationInputData: public FixedArray {
4373 // Layout description. Indices in the array.
4374 static const int kTranslationByteArrayIndex = 0;
4375 static const int kInlinedFunctionCountIndex = 1;
4376 static const int kLiteralArrayIndex = 2;
4377 static const int kOsrAstIdIndex = 3;
4378 static const int kOsrPcOffsetIndex = 4;
4379 static const int kOptimizationIdIndex = 5;
4380 static const int kSharedFunctionInfoIndex = 6;
4381 static const int kWeakCellCacheIndex = 7;
4382 static const int kFirstDeoptEntryIndex = 8;
4384 // Offsets of deopt entry elements relative to the start of the entry.
4385 static const int kAstIdRawOffset = 0;
4386 static const int kTranslationIndexOffset = 1;
4387 static const int kArgumentsStackHeightOffset = 2;
4388 static const int kPcOffset = 3;
4389 static const int kDeoptEntrySize = 4;
4391 // Simple element accessors.
4392 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4394 return type::cast(get(k##name##Index)); \
4396 void Set##name(type* value) { \
4397 set(k##name##Index, value); \
4400 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4401 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4402 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4403 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4404 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4405 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4406 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4407 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4409 #undef DEFINE_ELEMENT_ACCESSORS
4411 // Accessors for elements of the ith deoptimization entry.
4412 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4413 type* name(int i) { \
4414 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4416 void Set##name(int i, type* value) { \
4417 set(IndexForEntry(i) + k##name##Offset, value); \
4420 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4421 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4422 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4423 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4425 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4427 BailoutId AstId(int i) {
4428 return BailoutId(AstIdRaw(i)->value());
4431 void SetAstId(int i, BailoutId value) {
4432 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4436 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4439 // Allocates a DeoptimizationInputData.
4440 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4441 int deopt_entry_count,
4442 PretenureFlag pretenure);
4444 DECLARE_CAST(DeoptimizationInputData)
4446 #ifdef ENABLE_DISASSEMBLER
4447 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4451 static int IndexForEntry(int i) {
4452 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4456 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4460 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4461 // data for code generated by the full compiler.
4462 // The format of the these objects is
4463 // [i * 2]: Ast ID for ith deoptimization.
4464 // [i * 2 + 1]: PC and state of ith deoptimization
4465 class DeoptimizationOutputData: public FixedArray {
4467 int DeoptPoints() { return length() / 2; }
4469 BailoutId AstId(int index) {
4470 return BailoutId(Smi::cast(get(index * 2))->value());
4473 void SetAstId(int index, BailoutId id) {
4474 set(index * 2, Smi::FromInt(id.ToInt()));
4477 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4478 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4480 static int LengthOfFixedArray(int deopt_points) {
4481 return deopt_points * 2;
4484 // Allocates a DeoptimizationOutputData.
4485 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4486 int number_of_deopt_points,
4487 PretenureFlag pretenure);
4489 DECLARE_CAST(DeoptimizationOutputData)
4491 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4492 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4497 // HandlerTable is a fixed array containing entries for exception handlers in
4498 // the code object it is associated with. The tables comes in two flavors:
4499 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4500 // exception handler and a range representing the try-block covered by that
4501 // handler. Layout looks as follows:
4502 // [ range-start , range-end , handler-offset , stack-depth ]
4503 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4504 // per call-site that could throw an exception. Layout looks as follows:
4505 // [ return-address-offset , handler-offset ]
4506 class HandlerTable : public FixedArray {
4508 // Conservative prediction whether a given handler will locally catch an
4509 // exception or cause a re-throw to outside the code boundary. Since this is
4510 // undecidable it is merely an approximation (e.g. useful for debugger).
4511 enum CatchPrediction { UNCAUGHT, CAUGHT };
4513 // Accessors for handler table based on ranges.
4514 void SetRangeStart(int index, int value) {
4515 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4517 void SetRangeEnd(int index, int value) {
4518 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4520 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4521 int value = HandlerOffsetField::encode(offset) |
4522 HandlerPredictionField::encode(prediction);
4523 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4525 void SetRangeDepth(int index, int value) {
4526 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4529 // Accessors for handler table based on return addresses.
4530 void SetReturnOffset(int index, int value) {
4531 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4533 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4534 int value = HandlerOffsetField::encode(offset) |
4535 HandlerPredictionField::encode(prediction);
4536 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4539 // Lookup handler in a table based on ranges.
4540 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4542 // Lookup handler in a table based on return addresses.
4543 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4545 // Returns the required length of the underlying fixed array.
4546 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4547 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4549 DECLARE_CAST(HandlerTable)
4551 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4552 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4553 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4557 // Layout description for handler table based on ranges.
4558 static const int kRangeStartIndex = 0;
4559 static const int kRangeEndIndex = 1;
4560 static const int kRangeHandlerIndex = 2;
4561 static const int kRangeDepthIndex = 3;
4562 static const int kRangeEntrySize = 4;
4564 // Layout description for handler table based on return addresses.
4565 static const int kReturnOffsetIndex = 0;
4566 static const int kReturnHandlerIndex = 1;
4567 static const int kReturnEntrySize = 2;
4569 // Encoding of the {handler} field.
4570 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4571 class HandlerOffsetField : public BitField<int, 1, 30> {};
4575 // Code describes objects with on-the-fly generated machine code.
4576 class Code: public HeapObject {
4578 // Opaque data type for encapsulating code flags like kind, inline
4579 // cache state, and arguments count.
4580 typedef uint32_t Flags;
4582 #define NON_IC_KIND_LIST(V) \
4584 V(OPTIMIZED_FUNCTION) \
4590 #define IC_KIND_LIST(V) \
4601 #define CODE_KIND_LIST(V) \
4602 NON_IC_KIND_LIST(V) \
4606 #define DEFINE_CODE_KIND_ENUM(name) name,
4607 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4608 #undef DEFINE_CODE_KIND_ENUM
4612 // No more than 16 kinds. The value is currently encoded in four bits in
4614 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4616 static const char* Kind2String(Kind kind);
4624 static const int kPrologueOffsetNotSet = -1;
4626 #ifdef ENABLE_DISASSEMBLER
4628 static const char* ICState2String(InlineCacheState state);
4629 static const char* StubType2String(StubType type);
4630 static void PrintExtraICState(std::ostream& os, // NOLINT
4631 Kind kind, ExtraICState extra);
4632 void Disassemble(const char* name, std::ostream& os); // NOLINT
4633 #endif // ENABLE_DISASSEMBLER
4635 // [instruction_size]: Size of the native instructions
4636 inline int instruction_size() const;
4637 inline void set_instruction_size(int value);
4639 // [relocation_info]: Code relocation information
4640 DECL_ACCESSORS(relocation_info, ByteArray)
4641 void InvalidateRelocation();
4642 void InvalidateEmbeddedObjects();
4644 // [handler_table]: Fixed array containing offsets of exception handlers.
4645 DECL_ACCESSORS(handler_table, FixedArray)
4647 // [deoptimization_data]: Array containing data for deopt.
4648 DECL_ACCESSORS(deoptimization_data, FixedArray)
4650 // [raw_type_feedback_info]: This field stores various things, depending on
4651 // the kind of the code object.
4652 // FUNCTION => type feedback information.
4653 // STUB and ICs => major/minor key as Smi.
4654 DECL_ACCESSORS(raw_type_feedback_info, Object)
4655 inline Object* type_feedback_info();
4656 inline void set_type_feedback_info(
4657 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4658 inline uint32_t stub_key();
4659 inline void set_stub_key(uint32_t key);
4661 // [next_code_link]: Link for lists of optimized or deoptimized code.
4662 // Note that storage for this field is overlapped with typefeedback_info.
4663 DECL_ACCESSORS(next_code_link, Object)
4665 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4666 // field does not have to be traced during garbage collection since
4667 // it is only used by the garbage collector itself.
4668 DECL_ACCESSORS(gc_metadata, Object)
4670 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4671 // at the moment when this object was created.
4672 inline void set_ic_age(int count);
4673 inline int ic_age() const;
4675 // [prologue_offset]: Offset of the function prologue, used for aging
4676 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4677 inline int prologue_offset() const;
4678 inline void set_prologue_offset(int offset);
4680 // [constant_pool offset]: Offset of the constant pool.
4681 // Valid for FLAG_enable_embedded_constant_pool only
4682 inline int constant_pool_offset() const;
4683 inline void set_constant_pool_offset(int offset);
4685 // Unchecked accessors to be used during GC.
4686 inline ByteArray* unchecked_relocation_info();
4688 inline int relocation_size();
4690 // [flags]: Various code flags.
4691 inline Flags flags();
4692 inline void set_flags(Flags flags);
4694 // [flags]: Access to specific code flags.
4696 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4697 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4699 inline StubType type(); // Only valid for monomorphic IC stubs.
4701 // Testers for IC stub kinds.
4702 inline bool is_inline_cache_stub();
4703 inline bool is_debug_stub();
4704 inline bool is_handler() { return kind() == HANDLER; }
4705 inline bool is_load_stub() { return kind() == LOAD_IC; }
4706 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4707 inline bool is_store_stub() { return kind() == STORE_IC; }
4708 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4709 inline bool is_call_stub() { return kind() == CALL_IC; }
4710 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4711 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4712 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4713 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4714 inline bool is_keyed_stub();
4715 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4716 inline bool embeds_maps_weakly() {
4718 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4719 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4720 ic_state() == MONOMORPHIC;
4723 inline bool IsCodeStubOrIC();
4725 inline void set_raw_kind_specific_flags1(int value);
4726 inline void set_raw_kind_specific_flags2(int value);
4728 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4729 // object was generated by either the hydrogen or the TurboFan optimizing
4730 // compiler (but it may not be an optimized function).
4731 inline bool is_crankshafted();
4732 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4733 inline void set_is_crankshafted(bool value);
4735 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4736 // code object was generated by the TurboFan optimizing compiler.
4737 inline bool is_turbofanned();
4738 inline void set_is_turbofanned(bool value);
4740 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4741 // embedded objects in code should be treated weakly.
4742 inline bool can_have_weak_objects();
4743 inline void set_can_have_weak_objects(bool value);
4745 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4746 // deoptimization support.
4747 inline bool has_deoptimization_support();
4748 inline void set_has_deoptimization_support(bool value);
4750 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4751 // been compiled with debug break slots.
4752 inline bool has_debug_break_slots();
4753 inline void set_has_debug_break_slots(bool value);
4755 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4756 // reloc info includes runtime and external references to support
4757 // serialization/deserialization.
4758 inline bool has_reloc_info_for_serialization();
4759 inline void set_has_reloc_info_for_serialization(bool value);
4761 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4762 // how long the function has been marked for OSR and therefore which
4763 // level of loop nesting we are willing to do on-stack replacement
4765 inline void set_allow_osr_at_loop_nesting_level(int level);
4766 inline int allow_osr_at_loop_nesting_level();
4768 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4769 // the code object was seen on the stack with no IC patching going on.
4770 inline int profiler_ticks();
4771 inline void set_profiler_ticks(int ticks);
4773 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4774 // For builtins, tells which builtin index it has.
4775 // Note that builtins can have a code kind other than BUILTIN, which means
4776 // that for arbitrary code objects, this index value may be random garbage.
4777 // To verify in that case, compare the code object to the indexed builtin.
4778 inline int builtin_index();
4779 inline void set_builtin_index(int id);
4781 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4782 // reserved in the code prologue.
4783 inline unsigned stack_slots();
4784 inline void set_stack_slots(unsigned slots);
4786 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4787 // the instruction stream where the safepoint table starts.
4788 inline unsigned safepoint_table_offset();
4789 inline void set_safepoint_table_offset(unsigned offset);
4791 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4792 // instruction stream where the back edge table starts.
4793 inline unsigned back_edge_table_offset();
4794 inline void set_back_edge_table_offset(unsigned offset);
4796 inline bool back_edges_patched_for_osr();
4798 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4799 inline uint16_t to_boolean_state();
4801 // [has_function_cache]: For kind STUB tells whether there is a function
4802 // cache is passed to the stub.
4803 inline bool has_function_cache();
4804 inline void set_has_function_cache(bool flag);
4807 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4808 // the code is going to be deoptimized because of dead embedded maps.
4809 inline bool marked_for_deoptimization();
4810 inline void set_marked_for_deoptimization(bool flag);
4812 // [constant_pool]: The constant pool for this function.
4813 inline Address constant_pool();
4815 // Get the safepoint entry for the given pc.
4816 SafepointEntry GetSafepointEntry(Address pc);
4818 // Find an object in a stub with a specified map
4819 Object* FindNthObject(int n, Map* match_map);
4821 // Find the first allocation site in an IC stub.
4822 AllocationSite* FindFirstAllocationSite();
4824 // Find the first map in an IC stub.
4825 Map* FindFirstMap();
4826 void FindAllMaps(MapHandleList* maps);
4828 // Find the first handler in an IC stub.
4829 Code* FindFirstHandler();
4831 // Find |length| handlers and put them into |code_list|. Returns false if not
4832 // enough handlers can be found.
4833 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4835 // Find the handler for |map|.
4836 MaybeHandle<Code> FindHandlerForMap(Map* map);
4838 // Find the first name in an IC stub.
4839 Name* FindFirstName();
4841 class FindAndReplacePattern;
4842 // For each (map-to-find, object-to-replace) pair in the pattern, this
4843 // function replaces the corresponding placeholder in the code with the
4844 // object-to-replace. The function assumes that pairs in the pattern come in
4845 // the same order as the placeholders in the code.
4846 // If the placeholder is a weak cell, then the value of weak cell is matched
4847 // against the map-to-find.
4848 void FindAndReplace(const FindAndReplacePattern& pattern);
4850 // The entire code object including its header is copied verbatim to the
4851 // snapshot so that it can be written in one, fast, memcpy during
4852 // deserialization. The deserializer will overwrite some pointers, rather
4853 // like a runtime linker, but the random allocation addresses used in the
4854 // mksnapshot process would still be present in the unlinked snapshot data,
4855 // which would make snapshot production non-reproducible. This method wipes
4856 // out the to-be-overwritten header data for reproducible snapshots.
4857 inline void WipeOutHeader();
4859 // Flags operations.
4860 static inline Flags ComputeFlags(
4861 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4862 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4863 CacheHolderFlag holder = kCacheOnReceiver);
4865 static inline Flags ComputeMonomorphicFlags(
4866 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4867 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4869 static inline Flags ComputeHandlerFlags(
4870 Kind handler_kind, StubType type = NORMAL,
4871 CacheHolderFlag holder = kCacheOnReceiver);
4873 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4874 static inline StubType ExtractTypeFromFlags(Flags flags);
4875 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4876 static inline Kind ExtractKindFromFlags(Flags flags);
4877 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4879 static inline Flags RemoveTypeFromFlags(Flags flags);
4880 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4882 // Convert a target address into a code object.
4883 static inline Code* GetCodeFromTargetAddress(Address address);
4885 // Convert an entry address into an object.
4886 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4888 // Returns the address of the first instruction.
4889 inline byte* instruction_start();
4891 // Returns the address right after the last instruction.
4892 inline byte* instruction_end();
4894 // Returns the size of the instructions, padding, and relocation information.
4895 inline int body_size();
4897 // Returns the address of the first relocation info (read backwards!).
4898 inline byte* relocation_start();
4900 // Code entry point.
4901 inline byte* entry();
4903 // Returns true if pc is inside this object's instructions.
4904 inline bool contains(byte* pc);
4906 // Relocate the code by delta bytes. Called to signal that this code
4907 // object has been moved by delta bytes.
4908 void Relocate(intptr_t delta);
4910 // Migrate code described by desc.
4911 void CopyFrom(const CodeDesc& desc);
4913 // Returns the object size for a given body (used for allocation).
4914 static int SizeFor(int body_size) {
4915 DCHECK_SIZE_TAG_ALIGNED(body_size);
4916 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4919 // Calculate the size of the code object to report for log events. This takes
4920 // the layout of the code object into account.
4921 int ExecutableSize() {
4922 // Check that the assumptions about the layout of the code object holds.
4923 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
4925 return instruction_size() + Code::kHeaderSize;
4928 // Locating source position.
4929 int SourcePosition(Address pc);
4930 int SourceStatementPosition(Address pc);
4934 // Dispatched behavior.
4935 int CodeSize() { return SizeFor(body_size()); }
4936 inline void CodeIterateBody(ObjectVisitor* v);
4938 template<typename StaticVisitor>
4939 inline void CodeIterateBody(Heap* heap);
4941 DECLARE_PRINTER(Code)
4942 DECLARE_VERIFIER(Code)
4944 void ClearInlineCaches();
4945 void ClearInlineCaches(Kind kind);
4947 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4948 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4950 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4952 kToBeExecutedOnceCodeAge = -3,
4953 kNotExecutedCodeAge = -2,
4954 kExecutedOnceCodeAge = -1,
4956 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4958 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4959 kLastCodeAge = kAfterLastCodeAge - 1,
4960 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4961 kIsOldCodeAge = kSexagenarianCodeAge,
4962 kPreAgedCodeAge = kIsOldCodeAge - 1
4964 #undef DECLARE_CODE_AGE_ENUM
4966 // Code aging. Indicates how many full GCs this code has survived without
4967 // being entered through the prologue. Used to determine when it is
4968 // relatively safe to flush this code object and replace it with the lazy
4969 // compilation stub.
4970 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4971 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4972 void MakeYoung(Isolate* isolate);
4973 void MarkToBeExecutedOnce(Isolate* isolate);
4974 void MakeOlder(MarkingParity);
4975 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4978 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4979 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4982 void PrintDeoptLocation(FILE* out, Address pc);
4983 bool CanDeoptAt(Address pc);
4986 void VerifyEmbeddedObjectsDependency();
4990 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4991 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4992 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4995 inline bool CanContainWeakObjects() {
4996 // is_turbofanned() implies !can_have_weak_objects().
4997 DCHECK(!is_optimized_code() || !is_turbofanned() ||
4998 !can_have_weak_objects());
4999 return is_optimized_code() && can_have_weak_objects();
5002 inline bool IsWeakObject(Object* object) {
5003 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5006 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5008 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5009 WeakCell* CachedWeakCell();
5011 // Max loop nesting marker used to postpose OSR. We don't take loop
5012 // nesting that is deeper than 5 levels into account.
5013 static const int kMaxLoopNestingMarker = 6;
5015 static const int kConstantPoolSize =
5016 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5018 // Layout description.
5019 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5020 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5021 static const int kDeoptimizationDataOffset =
5022 kHandlerTableOffset + kPointerSize;
5023 // For FUNCTION kind, we store the type feedback info here.
5024 static const int kTypeFeedbackInfoOffset =
5025 kDeoptimizationDataOffset + kPointerSize;
5026 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5027 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5028 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5029 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5030 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5031 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5032 static const int kKindSpecificFlags2Offset =
5033 kKindSpecificFlags1Offset + kIntSize;
5034 // Note: We might be able to squeeze this into the flags above.
5035 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5036 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5037 static const int kHeaderPaddingStart =
5038 kConstantPoolOffset + kConstantPoolSize;
5040 // Add padding to align the instruction start following right after
5041 // the Code object header.
5042 static const int kHeaderSize =
5043 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5045 // Byte offsets within kKindSpecificFlags1Offset.
5046 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5047 class FullCodeFlagsHasDeoptimizationSupportField:
5048 public BitField<bool, 0, 1> {}; // NOLINT
5049 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5050 class FullCodeFlagsHasRelocInfoForSerialization
5051 : public BitField<bool, 2, 1> {};
5052 // Bit 3 in this bitfield is unused.
5053 class ProfilerTicksField : public BitField<int, 4, 28> {};
5055 // Flags layout. BitField<type, shift, size>.
5056 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5057 class TypeField : public BitField<StubType, 4, 1> {};
5058 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5059 class KindField : public BitField<Kind, 7, 4> {};
5060 class ExtraICStateField: public BitField<ExtraICState, 11,
5061 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5063 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5064 static const int kStackSlotsFirstBit = 0;
5065 static const int kStackSlotsBitCount = 24;
5066 static const int kHasFunctionCacheBit =
5067 kStackSlotsFirstBit + kStackSlotsBitCount;
5068 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5069 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5070 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5072 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5073 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5075 class StackSlotsField: public BitField<int,
5076 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5077 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5079 class MarkedForDeoptimizationField
5080 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5081 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5083 class CanHaveWeakObjectsField
5084 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5086 // KindSpecificFlags2 layout (ALL)
5087 static const int kIsCrankshaftedBit = 0;
5088 class IsCrankshaftedField: public BitField<bool,
5089 kIsCrankshaftedBit, 1> {}; // NOLINT
5091 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5092 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5093 static const int kSafepointTableOffsetBitCount = 30;
5095 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5096 kSafepointTableOffsetBitCount <= 32);
5097 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5099 class SafepointTableOffsetField: public BitField<int,
5100 kSafepointTableOffsetFirstBit,
5101 kSafepointTableOffsetBitCount> {}; // NOLINT
5103 // KindSpecificFlags2 layout (FUNCTION)
5104 class BackEdgeTableOffsetField: public BitField<int,
5105 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5106 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5107 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5108 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5110 static const int kArgumentsBits = 16;
5111 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5113 // This constant should be encodable in an ARM instruction.
5114 static const int kFlagsNotUsedInLookup =
5115 TypeField::kMask | CacheHolderField::kMask;
5118 friend class RelocIterator;
5119 friend class Deoptimizer; // For FindCodeAgeSequence.
5121 void ClearInlineCaches(Kind* kind);
5124 byte* FindCodeAgeSequence();
5125 static void GetCodeAgeAndParity(Code* code, Age* age,
5126 MarkingParity* parity);
5127 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5128 MarkingParity* parity);
5129 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5131 // Code aging -- platform-specific
5132 static void PatchPlatformCodeAge(Isolate* isolate,
5133 byte* sequence, Age age,
5134 MarkingParity parity);
5136 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5140 // This class describes the layout of dependent codes array of a map. The
5141 // array is partitioned into several groups of dependent codes. Each group
5142 // contains codes with the same dependency on the map. The array has the
5143 // following layout for n dependency groups:
5145 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5146 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5147 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5149 // The first n elements are Smis, each of them specifies the number of codes
5150 // in the corresponding group. The subsequent elements contain grouped code
5151 // objects in weak cells. The suffix of the array can be filled with the
5152 // undefined value if the number of codes is less than the length of the
5153 // array. The order of the code objects within a group is not preserved.
5155 // All code indexes used in the class are counted starting from the first
5156 // code object of the first group. In other words, code index 0 corresponds
5157 // to array index n = kCodesStartIndex.
5159 class DependentCode: public FixedArray {
5161 enum DependencyGroup {
5162 // Group of code that weakly embed this map and depend on being
5163 // deoptimized when the map is garbage collected.
5165 // Group of code that embed a transition to this map, and depend on being
5166 // deoptimized when the transition is replaced by a new version.
5168 // Group of code that omit run-time prototype checks for prototypes
5169 // described by this map. The group is deoptimized whenever an object
5170 // described by this map changes shape (and transitions to a new map),
5171 // possibly invalidating the assumptions embedded in the code.
5172 kPrototypeCheckGroup,
5173 // Group of code that depends on global property values in property cells
5174 // not being changed.
5175 kPropertyCellChangedGroup,
5176 // Group of code that omit run-time type checks for the field(s) introduced
5179 // Group of code that omit run-time type checks for initial maps of
5181 kInitialMapChangedGroup,
5182 // Group of code that depends on tenuring information in AllocationSites
5183 // not being changed.
5184 kAllocationSiteTenuringChangedGroup,
5185 // Group of code that depends on element transition information in
5186 // AllocationSites not being changed.
5187 kAllocationSiteTransitionChangedGroup
5190 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5192 // Array for holding the index of the first code object of each group.
5193 // The last element stores the total number of code objects.
5194 class GroupStartIndexes {
5196 explicit GroupStartIndexes(DependentCode* entries);
5197 void Recompute(DependentCode* entries);
5198 int at(int i) { return start_indexes_[i]; }
5199 int number_of_entries() { return start_indexes_[kGroupCount]; }
5201 int start_indexes_[kGroupCount + 1];
5204 bool Contains(DependencyGroup group, WeakCell* code_cell);
5206 static Handle<DependentCode> InsertCompilationDependencies(
5207 Handle<DependentCode> entries, DependencyGroup group,
5208 Handle<Foreign> info);
5210 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5211 DependencyGroup group,
5212 Handle<WeakCell> code_cell);
5214 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5215 WeakCell* code_cell);
5217 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5220 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5221 DependentCode::DependencyGroup group);
5223 bool MarkCodeForDeoptimization(Isolate* isolate,
5224 DependentCode::DependencyGroup group);
5226 // The following low-level accessors should only be used by this class
5227 // and the mark compact collector.
5228 inline int number_of_entries(DependencyGroup group);
5229 inline void set_number_of_entries(DependencyGroup group, int value);
5230 inline Object* object_at(int i);
5231 inline void set_object_at(int i, Object* object);
5232 inline void clear_at(int i);
5233 inline void copy(int from, int to);
5234 DECLARE_CAST(DependentCode)
5236 static const char* DependencyGroupName(DependencyGroup group);
5237 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5240 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5241 DependencyGroup group,
5242 Handle<Object> object);
5243 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5244 // Make a room at the end of the given group by moving out the first
5245 // code objects of the subsequent groups.
5246 inline void ExtendGroup(DependencyGroup group);
5247 // Compact by removing cleared weak cells and return true if there was
5248 // any cleared weak cell.
5250 static int Grow(int number_of_entries) {
5251 if (number_of_entries < 5) return number_of_entries + 1;
5252 return number_of_entries * 5 / 4;
5254 static const int kCodesStartIndex = kGroupCount;
5258 class PrototypeInfo;
5261 // All heap objects have a Map that describes their structure.
5262 // A Map contains information about:
5263 // - Size information about the object
5264 // - How to iterate over an object (for garbage collection)
5265 class Map: public HeapObject {
5268 // Size in bytes or kVariableSizeSentinel if instances do not have
5270 inline int instance_size();
5271 inline void set_instance_size(int value);
5273 // Only to clear an unused byte, remove once byte is used.
5274 inline void clear_unused();
5276 // Count of properties allocated in the object.
5277 inline int inobject_properties();
5278 inline void set_inobject_properties(int value);
5281 inline InstanceType instance_type();
5282 inline void set_instance_type(InstanceType value);
5284 // Tells how many unused property fields are available in the
5285 // instance (only used for JSObject in fast mode).
5286 inline int unused_property_fields();
5287 inline void set_unused_property_fields(int value);
5290 inline byte bit_field() const;
5291 inline void set_bit_field(byte value);
5294 inline byte bit_field2() const;
5295 inline void set_bit_field2(byte value);
5298 inline uint32_t bit_field3() const;
5299 inline void set_bit_field3(uint32_t bits);
5301 class EnumLengthBits: public BitField<int,
5302 0, kDescriptorIndexBitCount> {}; // NOLINT
5303 class NumberOfOwnDescriptorsBits: public BitField<int,
5304 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5305 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5306 class DictionaryMap : public BitField<bool, 20, 1> {};
5307 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5308 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5309 class Deprecated : public BitField<bool, 23, 1> {};
5310 class IsUnstable : public BitField<bool, 24, 1> {};
5311 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5312 class IsStrong : public BitField<bool, 26, 1> {};
5315 // Keep this bit field at the very end for better code in
5316 // Builtins::kJSConstructStubGeneric stub.
5317 // This counter is used for in-object slack tracking and for map aging.
5318 // The in-object slack tracking is considered enabled when the counter is
5319 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5320 class Counter : public BitField<int, 28, 4> {};
5321 static const int kSlackTrackingCounterStart = 14;
5322 static const int kSlackTrackingCounterEnd = 8;
5323 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5324 static const int kRetainingCounterEnd = 0;
5326 // Tells whether the object in the prototype property will be used
5327 // for instances created from this function. If the prototype
5328 // property is set to a value that is not a JSObject, the prototype
5329 // property will not be used to create instances of the function.
5330 // See ECMA-262, 13.2.2.
5331 inline void set_non_instance_prototype(bool value);
5332 inline bool has_non_instance_prototype();
5334 // Tells whether function has special prototype property. If not, prototype
5335 // property will not be created when accessed (will return undefined),
5336 // and construction from this function will not be allowed.
5337 inline void set_function_with_prototype(bool value);
5338 inline bool function_with_prototype();
5340 // Tells whether the instance with this map should be ignored by the
5341 // Object.getPrototypeOf() function and the __proto__ accessor.
5342 inline void set_is_hidden_prototype() {
5343 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5346 inline bool is_hidden_prototype() {
5347 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5350 // Records and queries whether the instance has a named interceptor.
5351 inline void set_has_named_interceptor() {
5352 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5355 inline bool has_named_interceptor() {
5356 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5359 // Records and queries whether the instance has an indexed interceptor.
5360 inline void set_has_indexed_interceptor() {
5361 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5364 inline bool has_indexed_interceptor() {
5365 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5368 // Tells whether the instance is undetectable.
5369 // An undetectable object is a special class of JSObject: 'typeof' operator
5370 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5371 // a normal JS object. It is useful for implementing undetectable
5372 // document.all in Firefox & Safari.
5373 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5374 inline void set_is_undetectable() {
5375 set_bit_field(bit_field() | (1 << kIsUndetectable));
5378 inline bool is_undetectable() {
5379 return ((1 << kIsUndetectable) & bit_field()) != 0;
5382 // Tells whether the instance has a call-as-function handler.
5383 inline void set_is_observed() {
5384 set_bit_field(bit_field() | (1 << kIsObserved));
5387 inline bool is_observed() {
5388 return ((1 << kIsObserved) & bit_field()) != 0;
5391 inline void set_is_strong();
5392 inline bool is_strong();
5393 inline void set_is_extensible(bool value);
5394 inline bool is_extensible();
5395 inline void set_is_prototype_map(bool value);
5396 inline bool is_prototype_map() const;
5398 inline void set_elements_kind(ElementsKind elements_kind) {
5399 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5400 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5401 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5402 DCHECK(this->elements_kind() == elements_kind);
5405 inline ElementsKind elements_kind() {
5406 return Map::ElementsKindBits::decode(bit_field2());
5409 // Tells whether the instance has fast elements that are only Smis.
5410 inline bool has_fast_smi_elements() {
5411 return IsFastSmiElementsKind(elements_kind());
5414 // Tells whether the instance has fast elements.
5415 inline bool has_fast_object_elements() {
5416 return IsFastObjectElementsKind(elements_kind());
5419 inline bool has_fast_smi_or_object_elements() {
5420 return IsFastSmiOrObjectElementsKind(elements_kind());
5423 inline bool has_fast_double_elements() {
5424 return IsFastDoubleElementsKind(elements_kind());
5427 inline bool has_fast_elements() {
5428 return IsFastElementsKind(elements_kind());
5431 inline bool has_sloppy_arguments_elements() {
5432 return IsSloppyArgumentsElements(elements_kind());
5435 inline bool has_fixed_typed_array_elements() {
5436 return IsFixedTypedArrayElementsKind(elements_kind());
5439 inline bool has_dictionary_elements() {
5440 return IsDictionaryElementsKind(elements_kind());
5443 static bool IsValidElementsTransition(ElementsKind from_kind,
5444 ElementsKind to_kind);
5446 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5447 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5448 bool DictionaryElementsInPrototypeChainOnly();
5450 inline Map* ElementsTransitionMap();
5452 inline FixedArrayBase* GetInitialElements();
5454 // [raw_transitions]: Provides access to the transitions storage field.
5455 // Don't call set_raw_transitions() directly to overwrite transitions, use
5456 // the TransitionArray::ReplaceTransitions() wrapper instead!
5457 DECL_ACCESSORS(raw_transitions, Object)
5458 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5459 // (which prototype maps don't have).
5460 DECL_ACCESSORS(prototype_info, Object)
5461 // PrototypeInfo is created lazily using this helper (which installs it on
5462 // the given prototype's map).
5463 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5464 Handle<JSObject> prototype, Isolate* isolate);
5465 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5466 Handle<Map> prototype_map, Isolate* isolate);
5468 // [prototype chain validity cell]: Associated with a prototype object,
5469 // stored in that object's map's PrototypeInfo, indicates that prototype
5470 // chains through this object are currently valid. The cell will be
5471 // invalidated and replaced when the prototype chain changes.
5472 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5474 static const int kPrototypeChainValid = 0;
5475 static const int kPrototypeChainInvalid = 1;
5478 Map* FindFieldOwner(int descriptor);
5480 inline int GetInObjectPropertyOffset(int index);
5482 int NumberOfFields();
5484 // TODO(ishell): candidate with JSObject::MigrateToMap().
5485 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5486 int target_inobject, int target_unused,
5487 int* old_number_of_fields);
5488 // TODO(ishell): moveit!
5489 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5490 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5491 Handle<HeapType> type1,
5492 Handle<HeapType> type2,
5494 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5495 Representation new_representation,
5496 Handle<HeapType> new_field_type);
5497 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5498 PropertyKind new_kind,
5499 PropertyAttributes new_attributes,
5500 Representation new_representation,
5501 Handle<HeapType> new_field_type,
5502 StoreMode store_mode);
5503 static Handle<Map> CopyGeneralizeAllRepresentations(
5504 Handle<Map> map, int modify_index, StoreMode store_mode,
5505 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5507 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5508 int descriptor_number,
5509 Handle<Object> value);
5511 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5512 const char* reason);
5514 // Returns the constructor name (the name (possibly, inferred name) of the
5515 // function that was used to instantiate the object).
5516 String* constructor_name();
5518 // Tells whether the map is used for JSObjects in dictionary mode (ie
5519 // normalized objects, ie objects for which HasFastProperties returns false).
5520 // A map can never be used for both dictionary mode and fast mode JSObjects.
5521 // False by default and for HeapObjects that are not JSObjects.
5522 inline void set_dictionary_map(bool value);
5523 inline bool is_dictionary_map();
5525 // Tells whether the instance needs security checks when accessing its
5527 inline void set_is_access_check_needed(bool access_check_needed);
5528 inline bool is_access_check_needed();
5530 // Returns true if map has a non-empty stub code cache.
5531 inline bool has_code_cache();
5533 // [prototype]: implicit prototype object.
5534 DECL_ACCESSORS(prototype, Object)
5535 // TODO(jkummerow): make set_prototype private.
5536 static void SetPrototype(
5537 Handle<Map> map, Handle<Object> prototype,
5538 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5540 // [constructor]: points back to the function responsible for this map.
5541 // The field overlaps with the back pointer. All maps in a transition tree
5542 // have the same constructor, so maps with back pointers can walk the
5543 // back pointer chain until they find the map holding their constructor.
5544 DECL_ACCESSORS(constructor_or_backpointer, Object)
5545 inline Object* GetConstructor() const;
5546 inline void SetConstructor(Object* constructor,
5547 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5548 // [back pointer]: points back to the parent map from which a transition
5549 // leads to this map. The field overlaps with the constructor (see above).
5550 inline Object* GetBackPointer();
5551 inline void SetBackPointer(Object* value,
5552 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5554 // [instance descriptors]: describes the object.
5555 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5557 // [layout descriptor]: describes the object layout.
5558 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5559 // |layout descriptor| accessor which can be used from GC.
5560 inline LayoutDescriptor* layout_descriptor_gc_safe();
5561 inline bool HasFastPointerLayout() const;
5563 // |layout descriptor| accessor that is safe to call even when
5564 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5565 // |layout_descriptor| field at all).
5566 inline LayoutDescriptor* GetLayoutDescriptor();
5568 inline void UpdateDescriptors(DescriptorArray* descriptors,
5569 LayoutDescriptor* layout_descriptor);
5570 inline void InitializeDescriptors(DescriptorArray* descriptors,
5571 LayoutDescriptor* layout_descriptor);
5573 // [stub cache]: contains stubs compiled for this map.
5574 DECL_ACCESSORS(code_cache, Object)
5576 // [dependent code]: list of optimized codes that weakly embed this map.
5577 DECL_ACCESSORS(dependent_code, DependentCode)
5579 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5580 DECL_ACCESSORS(weak_cell_cache, Object)
5582 inline PropertyDetails GetLastDescriptorDetails();
5585 int number_of_own_descriptors = NumberOfOwnDescriptors();
5586 DCHECK(number_of_own_descriptors > 0);
5587 return number_of_own_descriptors - 1;
5590 int NumberOfOwnDescriptors() {
5591 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5594 void SetNumberOfOwnDescriptors(int number) {
5595 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5596 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5599 inline Cell* RetrieveDescriptorsPointer();
5602 return EnumLengthBits::decode(bit_field3());
5605 void SetEnumLength(int length) {
5606 if (length != kInvalidEnumCacheSentinel) {
5607 DCHECK(length >= 0);
5608 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5609 DCHECK(length <= NumberOfOwnDescriptors());
5611 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5614 inline bool owns_descriptors();
5615 inline void set_owns_descriptors(bool owns_descriptors);
5616 inline bool has_instance_call_handler();
5617 inline void set_has_instance_call_handler();
5618 inline void mark_unstable();
5619 inline bool is_stable();
5620 inline void set_migration_target(bool value);
5621 inline bool is_migration_target();
5622 inline void set_counter(int value);
5623 inline int counter();
5624 inline void deprecate();
5625 inline bool is_deprecated();
5626 inline bool CanBeDeprecated();
5627 // Returns a non-deprecated version of the input. If the input was not
5628 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5629 // is found by re-transitioning from the root of the transition tree using the
5630 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5632 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5634 // Returns a non-deprecated version of the input. This method may deprecate
5635 // existing maps along the way if encodings conflict. Not for use while
5636 // gathering type feedback. Use TryUpdate in those cases instead.
5637 static Handle<Map> Update(Handle<Map> map);
5639 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5640 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5641 Descriptor* descriptor,
5642 TransitionFlag flag);
5644 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5647 Handle<HeapType> type,
5648 PropertyAttributes attributes,
5649 Representation representation,
5650 TransitionFlag flag);
5652 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5655 Handle<Object> constant,
5656 PropertyAttributes attributes,
5657 TransitionFlag flag);
5659 // Returns a new map with all transitions dropped from the given map and
5660 // the ElementsKind set.
5661 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5662 ElementsKind to_kind);
5664 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5666 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5668 TransitionFlag flag);
5670 static Handle<Map> CopyForObserved(Handle<Map> map);
5672 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5673 PropertyAttributes attrs_to_add,
5674 Handle<Symbol> transition_marker,
5675 const char* reason);
5677 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5680 // Maximal number of fast properties. Used to restrict the number of map
5681 // transitions to avoid an explosion in the number of maps for objects used as
5683 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5684 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5686 Handle<Object> value,
5687 PropertyAttributes attributes,
5688 StoreFromKeyed store_mode);
5689 static Handle<Map> TransitionToAccessorProperty(
5690 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5691 Handle<Object> accessor, PropertyAttributes attributes);
5692 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5695 PropertyAttributes attributes);
5697 inline void AppendDescriptor(Descriptor* desc);
5699 // Returns a copy of the map, prepared for inserting into the transition
5700 // tree (if the |map| owns descriptors then the new one will share
5701 // descriptors with |map|).
5702 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5704 // Returns a copy of the map, with all transitions dropped from the
5705 // instance descriptors.
5706 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5707 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5709 // Returns the next free property index (only valid for FAST MODE).
5710 int NextFreePropertyIndex();
5712 // Returns the number of properties described in instance_descriptors
5713 // filtering out properties with the specified attributes.
5714 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5715 PropertyAttributes filter = NONE);
5719 // Code cache operations.
5721 // Clears the code cache.
5722 inline void ClearCodeCache(Heap* heap);
5724 // Update code cache.
5725 static void UpdateCodeCache(Handle<Map> map,
5729 // Extend the descriptor array of the map with the list of descriptors.
5730 // In case of duplicates, the latest descriptor is used.
5731 static void AppendCallbackDescriptors(Handle<Map> map,
5732 Handle<Object> descriptors);
5734 static inline int SlackForArraySize(int old_size, int size_limit);
5736 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5738 // Returns the found code or undefined if absent.
5739 Object* FindInCodeCache(Name* name, Code::Flags flags);
5741 // Returns the non-negative index of the code object if it is in the
5742 // cache and -1 otherwise.
5743 int IndexInCodeCache(Object* name, Code* code);
5745 // Removes a code object from the code cache at the given index.
5746 void RemoveFromCodeCache(Name* name, Code* code, int index);
5748 // Computes a hash value for this map, to be used in HashTables and such.
5751 // Returns the map that this map transitions to if its elements_kind
5752 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5753 // |safe_to_add_transitions| is set to false if adding transitions is not
5755 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5757 // Returns the transitioned map for this map with the most generic
5758 // elements_kind that's found in |candidates|, or null handle if no match is
5760 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5761 MapHandleList* candidates);
5763 bool CanTransition() {
5764 // Only JSObject and subtypes have map transitions and back pointers.
5765 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
5766 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5769 bool IsJSObjectMap() {
5770 return instance_type() >= FIRST_JS_OBJECT_TYPE;
5772 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
5773 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
5774 bool IsJSProxyMap() {
5775 InstanceType type = instance_type();
5776 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
5778 bool IsJSGlobalProxyMap() {
5779 return instance_type() == JS_GLOBAL_PROXY_TYPE;
5781 bool IsJSGlobalObjectMap() {
5782 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
5784 bool IsGlobalObjectMap() {
5785 const InstanceType type = instance_type();
5786 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
5789 inline bool CanOmitMapChecks();
5791 static void AddDependentCode(Handle<Map> map,
5792 DependentCode::DependencyGroup group,
5795 bool IsMapInArrayPrototypeChain();
5797 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5799 // Dispatched behavior.
5800 DECLARE_PRINTER(Map)
5801 DECLARE_VERIFIER(Map)
5804 void DictionaryMapVerify();
5805 void VerifyOmittedMapChecks();
5808 inline int visitor_id();
5809 inline void set_visitor_id(int visitor_id);
5811 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5812 Handle<Object> prototype,
5813 PrototypeOptimizationMode mode);
5815 static const int kMaxPreAllocatedPropertyFields = 255;
5817 // Layout description.
5818 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5819 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5820 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5821 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5822 static const int kConstructorOrBackPointerOffset =
5823 kPrototypeOffset + kPointerSize;
5824 // When there is only one transition, it is stored directly in this field;
5825 // otherwise a transition array is used.
5826 // For prototype maps, this slot is used to store this map's PrototypeInfo
5828 static const int kTransitionsOrPrototypeInfoOffset =
5829 kConstructorOrBackPointerOffset + kPointerSize;
5830 static const int kDescriptorsOffset =
5831 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5832 #if V8_DOUBLE_FIELDS_UNBOXING
5833 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5834 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5836 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5837 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5839 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5840 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5841 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5843 // Layout of pointer fields. Heap iteration code relies on them
5844 // being continuously allocated.
5845 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5846 static const int kPointerFieldsEndOffset = kSize;
5848 // Byte offsets within kInstanceSizesOffset.
5849 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5850 static const int kInObjectPropertiesByte = 1;
5851 static const int kInObjectPropertiesOffset =
5852 kInstanceSizesOffset + kInObjectPropertiesByte;
5853 // Note there is one byte available for use here.
5854 static const int kUnusedByte = 2;
5855 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5856 static const int kVisitorIdByte = 3;
5857 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5859 // Byte offsets within kInstanceAttributesOffset attributes.
5860 #if V8_TARGET_LITTLE_ENDIAN
5861 // Order instance type and bit field together such that they can be loaded
5862 // together as a 16-bit word with instance type in the lower 8 bits regardless
5863 // of endianess. Also provide endian-independent offset to that 16-bit word.
5864 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5865 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5867 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5868 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5870 static const int kInstanceTypeAndBitFieldOffset =
5871 kInstanceAttributesOffset + 0;
5872 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5873 static const int kUnusedPropertyFieldsByte = 3;
5874 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5876 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5877 Internals::kMapInstanceTypeAndBitFieldOffset);
5879 // Bit positions for bit field.
5880 static const int kHasNonInstancePrototype = 0;
5881 static const int kIsHiddenPrototype = 1;
5882 static const int kHasNamedInterceptor = 2;
5883 static const int kHasIndexedInterceptor = 3;
5884 static const int kIsUndetectable = 4;
5885 static const int kIsObserved = 5;
5886 static const int kIsAccessCheckNeeded = 6;
5887 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5889 // Bit positions for bit field 2
5890 static const int kIsExtensible = 0;
5891 static const int kStringWrapperSafeForDefaultValueOf = 1;
5892 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5893 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5895 // Derived values from bit field 2
5896 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5897 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5898 static const int8_t kMaximumBitField2FastSmiElementValue =
5899 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5900 Map::ElementsKindBits::kShift) - 1;
5901 static const int8_t kMaximumBitField2FastHoleyElementValue =
5902 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5903 Map::ElementsKindBits::kShift) - 1;
5904 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5905 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5906 Map::ElementsKindBits::kShift) - 1;
5908 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5909 kPointerFieldsEndOffset,
5910 kSize> BodyDescriptor;
5912 // Compares this map to another to see if they describe equivalent objects.
5913 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5914 // it had exactly zero inobject properties.
5915 // The "shared" flags of both this map and |other| are ignored.
5916 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5918 // Returns true if given field is unboxed double.
5919 inline bool IsUnboxedDoubleField(FieldIndex index);
5922 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5923 static void TraceAllTransitions(Map* map);
5926 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5927 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5928 Handle<LayoutDescriptor> layout_descriptor);
5931 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5932 Handle<Name> name, SimpleTransitionFlag flag);
5934 bool EquivalentToForTransition(Map* other);
5935 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5936 static Handle<Map> ShareDescriptor(Handle<Map> map,
5937 Handle<DescriptorArray> descriptors,
5938 Descriptor* descriptor);
5939 static Handle<Map> CopyInstallDescriptors(
5940 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5941 Handle<LayoutDescriptor> layout_descriptor);
5942 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5943 Descriptor* descriptor,
5944 TransitionFlag flag);
5945 static Handle<Map> CopyReplaceDescriptors(
5946 Handle<Map> map, Handle<DescriptorArray> descriptors,
5947 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5948 MaybeHandle<Name> maybe_name, const char* reason,
5949 SimpleTransitionFlag simple_flag);
5951 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5952 Handle<DescriptorArray> descriptors,
5953 Descriptor* descriptor,
5955 TransitionFlag flag);
5956 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5957 Handle<Map> map, int descriptor, PropertyKind kind,
5958 PropertyAttributes attributes, const char** reason);
5960 static Handle<Map> CopyNormalized(Handle<Map> map,
5961 PropertyNormalizationMode mode);
5963 // Fires when the layout of an object with a leaf map changes.
5964 // This includes adding transitions to the leaf map or changing
5965 // the descriptor array.
5966 inline void NotifyLeafMapLayoutChange();
5968 void DeprecateTransitionTree();
5969 bool DeprecateTarget(PropertyKind kind, Name* key,
5970 PropertyAttributes attributes,
5971 DescriptorArray* new_descriptors,
5972 LayoutDescriptor* new_layout_descriptor);
5974 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5976 // Update field type of the given descriptor to new representation and new
5977 // type. The type must be prepared for storing in descriptor array:
5978 // it must be either a simple type or a map wrapped in a weak cell.
5979 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5980 Representation new_representation,
5981 Handle<Object> new_wrapped_type);
5983 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5984 PropertyAttributes attributes);
5985 void PrintGeneralization(FILE* file,
5990 bool constant_to_field,
5991 Representation old_representation,
5992 Representation new_representation,
5993 HeapType* old_field_type,
5994 HeapType* new_field_type);
5996 static const int kFastPropertiesSoftLimit = 12;
5997 static const int kMaxFastProperties = 128;
5999 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6003 // An abstract superclass, a marker class really, for simple structure classes.
6004 // It doesn't carry much functionality but allows struct classes to be
6005 // identified in the type system.
6006 class Struct: public HeapObject {
6008 inline void InitializeBody(int object_size);
6009 DECLARE_CAST(Struct)
6013 // A simple one-element struct, useful where smis need to be boxed.
6014 class Box : public Struct {
6016 // [value]: the boxed contents.
6017 DECL_ACCESSORS(value, Object)
6021 // Dispatched behavior.
6022 DECLARE_PRINTER(Box)
6023 DECLARE_VERIFIER(Box)
6025 static const int kValueOffset = HeapObject::kHeaderSize;
6026 static const int kSize = kValueOffset + kPointerSize;
6029 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6033 // Container for metadata stored on each prototype map.
6034 class PrototypeInfo : public Struct {
6036 static const int UNREGISTERED = -1;
6038 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6039 // or Smi(0) if uninitialized.
6040 DECL_ACCESSORS(prototype_users, Object)
6041 // [registry_slot]: Slot in prototype's user registry where this user
6042 // is stored. Returns UNREGISTERED if this prototype has not been registered.
6043 inline int registry_slot() const;
6044 inline void set_registry_slot(int slot);
6045 // [validity_cell]: Cell containing the validity bit for prototype chains
6046 // going through this object, or Smi(0) if uninitialized.
6047 DECL_ACCESSORS(validity_cell, Object)
6048 // [constructor_name]: User-friendly name of the original constructor.
6049 DECL_ACCESSORS(constructor_name, Object)
6051 DECLARE_CAST(PrototypeInfo)
6053 // Dispatched behavior.
6054 DECLARE_PRINTER(PrototypeInfo)
6055 DECLARE_VERIFIER(PrototypeInfo)
6057 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6058 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
6059 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
6060 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6061 static const int kSize = kConstructorNameOffset + kPointerSize;
6064 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6068 // Script describes a script which has been added to the VM.
6069 class Script: public Struct {
6078 // Script compilation types.
6079 enum CompilationType {
6080 COMPILATION_TYPE_HOST = 0,
6081 COMPILATION_TYPE_EVAL = 1
6084 // Script compilation state.
6085 enum CompilationState {
6086 COMPILATION_STATE_INITIAL = 0,
6087 COMPILATION_STATE_COMPILED = 1
6090 // [source]: the script source.
6091 DECL_ACCESSORS(source, Object)
6093 // [name]: the script name.
6094 DECL_ACCESSORS(name, Object)
6096 // [id]: the script id.
6097 DECL_ACCESSORS(id, Smi)
6099 // [line_offset]: script line offset in resource from where it was extracted.
6100 DECL_ACCESSORS(line_offset, Smi)
6102 // [column_offset]: script column offset in resource from where it was
6104 DECL_ACCESSORS(column_offset, Smi)
6106 // [context_data]: context data for the context this script was compiled in.
6107 DECL_ACCESSORS(context_data, Object)
6109 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6110 DECL_ACCESSORS(wrapper, HeapObject)
6112 // [type]: the script type.
6113 DECL_ACCESSORS(type, Smi)
6115 // [line_ends]: FixedArray of line ends positions.
6116 DECL_ACCESSORS(line_ends, Object)
6118 // [eval_from_shared]: for eval scripts the shared funcion info for the
6119 // function from which eval was called.
6120 DECL_ACCESSORS(eval_from_shared, Object)
6122 // [eval_from_instructions_offset]: the instruction offset in the code for the
6123 // function from which eval was called where eval was called.
6124 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6126 // [shared_function_infos]: weak fixed array containing all shared
6127 // function infos created from this script.
6128 DECL_ACCESSORS(shared_function_infos, Object)
6130 // [flags]: Holds an exciting bitfield.
6131 DECL_ACCESSORS(flags, Smi)
6133 // [source_url]: sourceURL from magic comment
6134 DECL_ACCESSORS(source_url, Object)
6136 // [source_url]: sourceMappingURL magic comment
6137 DECL_ACCESSORS(source_mapping_url, Object)
6139 // [compilation_type]: how the the script was compiled. Encoded in the
6141 inline CompilationType compilation_type();
6142 inline void set_compilation_type(CompilationType type);
6144 // [compilation_state]: determines whether the script has already been
6145 // compiled. Encoded in the 'flags' field.
6146 inline CompilationState compilation_state();
6147 inline void set_compilation_state(CompilationState state);
6149 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6150 // and used by the embedder to make decisions about the script. V8 just passes
6151 // this through. Encoded in the 'flags' field.
6152 inline v8::ScriptOriginOptions origin_options();
6153 inline void set_origin_options(ScriptOriginOptions origin_options);
6155 DECLARE_CAST(Script)
6157 // If script source is an external string, check that the underlying
6158 // resource is accessible. Otherwise, always return true.
6159 inline bool HasValidSource();
6161 // Convert code position into column number.
6162 static int GetColumnNumber(Handle<Script> script, int code_pos);
6164 // Convert code position into (zero-based) line number.
6165 // The non-handlified version does not allocate, but may be much slower.
6166 static int GetLineNumber(Handle<Script> script, int code_pos);
6167 int GetLineNumber(int code_pos);
6169 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6171 // Init line_ends array with code positions of line ends inside script source.
6172 static void InitLineEnds(Handle<Script> script);
6174 // Get the JS object wrapping the given script; create it if none exists.
6175 static Handle<JSObject> GetWrapper(Handle<Script> script);
6177 // Look through the list of existing shared function infos to find one
6178 // that matches the function literal. Return empty handle if not found.
6179 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6181 // Dispatched behavior.
6182 DECLARE_PRINTER(Script)
6183 DECLARE_VERIFIER(Script)
6185 static const int kSourceOffset = HeapObject::kHeaderSize;
6186 static const int kNameOffset = kSourceOffset + kPointerSize;
6187 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6188 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6189 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6190 static const int kWrapperOffset = kContextOffset + kPointerSize;
6191 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6192 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6193 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6194 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6195 static const int kEvalFrominstructionsOffsetOffset =
6196 kEvalFromSharedOffset + kPointerSize;
6197 static const int kSharedFunctionInfosOffset =
6198 kEvalFrominstructionsOffsetOffset + kPointerSize;
6199 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6200 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6201 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6202 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6205 int GetLineNumberWithArray(int code_pos);
6207 // Bit positions in the flags field.
6208 static const int kCompilationTypeBit = 0;
6209 static const int kCompilationStateBit = 1;
6210 static const int kOriginOptionsShift = 2;
6211 static const int kOriginOptionsSize = 3;
6212 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6213 << kOriginOptionsShift;
6215 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6219 // List of builtin functions we want to identify to improve code
6222 // Each entry has a name of a global object property holding an object
6223 // optionally followed by ".prototype", a name of a builtin function
6224 // on the object (the one the id is set for), and a label.
6226 // Installation of ids for the selected builtin functions is handled
6227 // by the bootstrapper.
6228 #define FUNCTIONS_WITH_ID_LIST(V) \
6229 V(Array.prototype, indexOf, ArrayIndexOf) \
6230 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6231 V(Array.prototype, push, ArrayPush) \
6232 V(Array.prototype, pop, ArrayPop) \
6233 V(Array.prototype, shift, ArrayShift) \
6234 V(Function.prototype, apply, FunctionApply) \
6235 V(Function.prototype, call, FunctionCall) \
6236 V(String.prototype, charCodeAt, StringCharCodeAt) \
6237 V(String.prototype, charAt, StringCharAt) \
6238 V(String, fromCharCode, StringFromCharCode) \
6239 V(Math, random, MathRandom) \
6240 V(Math, floor, MathFloor) \
6241 V(Math, round, MathRound) \
6242 V(Math, ceil, MathCeil) \
6243 V(Math, abs, MathAbs) \
6244 V(Math, log, MathLog) \
6245 V(Math, exp, MathExp) \
6246 V(Math, sqrt, MathSqrt) \
6247 V(Math, pow, MathPow) \
6248 V(Math, max, MathMax) \
6249 V(Math, min, MathMin) \
6250 V(Math, cos, MathCos) \
6251 V(Math, sin, MathSin) \
6252 V(Math, tan, MathTan) \
6253 V(Math, acos, MathAcos) \
6254 V(Math, asin, MathAsin) \
6255 V(Math, atan, MathAtan) \
6256 V(Math, atan2, MathAtan2) \
6257 V(Math, imul, MathImul) \
6258 V(Math, clz32, MathClz32) \
6259 V(Math, fround, MathFround)
6261 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6262 V(Atomics, load, AtomicsLoad) \
6263 V(Atomics, store, AtomicsStore)
6265 enum BuiltinFunctionId {
6267 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6269 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6270 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6271 #undef DECLARE_FUNCTION_ID
6272 // Fake id for a special case of Math.pow. Note, it continues the
6273 // list of math functions.
6278 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6279 // that both {code} and {literals} can be NULL to pass search result status.
6280 struct CodeAndLiterals {
6281 Code* code; // Cached optimized code.
6282 FixedArray* literals; // Cached literals array.
6286 // SharedFunctionInfo describes the JSFunction information that can be
6287 // shared by multiple instances of the function.
6288 class SharedFunctionInfo: public HeapObject {
6290 // [name]: Function name.
6291 DECL_ACCESSORS(name, Object)
6293 // [code]: Function code.
6294 DECL_ACCESSORS(code, Code)
6295 inline void ReplaceCode(Code* code);
6297 // [optimized_code_map]: Map from native context to optimized code
6298 // and a shared literals array or Smi(0) if none.
6299 DECL_ACCESSORS(optimized_code_map, Object)
6301 // Returns entry from optimized code map for specified context and OSR entry.
6302 // Note that {code == nullptr} indicates no matching entry has been found,
6303 // whereas {literals == nullptr} indicates the code is context-independent.
6304 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6305 BailoutId osr_ast_id);
6307 // Clear optimized code map.
6308 void ClearOptimizedCodeMap();
6310 // Removed a specific optimized code object from the optimized code map.
6311 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6313 // Trims the optimized code map after entries have been removed.
6314 void TrimOptimizedCodeMap(int shrink_by);
6316 // Add a new entry to the optimized code map for context-independent code.
6317 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6320 // Add a new entry to the optimized code map for context-dependent code.
6321 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6322 Handle<Context> native_context,
6324 Handle<FixedArray> literals,
6325 BailoutId osr_ast_id);
6327 // Set up the link between shared function info and the script. The shared
6328 // function info is added to the list on the script.
6329 static void SetScript(Handle<SharedFunctionInfo> shared,
6330 Handle<Object> script_object);
6332 // Layout description of the optimized code map.
6333 static const int kNextMapIndex = 0;
6334 static const int kSharedCodeIndex = 1;
6335 static const int kEntriesStart = 2;
6336 static const int kContextOffset = 0;
6337 static const int kCachedCodeOffset = 1;
6338 static const int kLiteralsOffset = 2;
6339 static const int kOsrAstIdOffset = 3;
6340 static const int kEntryLength = 4;
6341 static const int kInitialLength = kEntriesStart + kEntryLength;
6343 // [scope_info]: Scope info.
6344 DECL_ACCESSORS(scope_info, ScopeInfo)
6346 // [construct stub]: Code stub for constructing instances of this function.
6347 DECL_ACCESSORS(construct_stub, Code)
6349 // Returns if this function has been compiled to native code yet.
6350 inline bool is_compiled();
6352 // [length]: The function length - usually the number of declared parameters.
6353 // Use up to 2^30 parameters.
6354 inline int length() const;
6355 inline void set_length(int value);
6357 // [internal formal parameter count]: The declared number of parameters.
6358 // For subclass constructors, also includes new.target.
6359 // The size of function's frame is internal_formal_parameter_count + 1.
6360 inline int internal_formal_parameter_count() const;
6361 inline void set_internal_formal_parameter_count(int value);
6363 // Set the formal parameter count so the function code will be
6364 // called without using argument adaptor frames.
6365 inline void DontAdaptArguments();
6367 // [expected_nof_properties]: Expected number of properties for the function.
6368 inline int expected_nof_properties() const;
6369 inline void set_expected_nof_properties(int value);
6371 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6372 // (increasingly) from crankshafted code where sufficient feedback isn't
6374 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6376 // Unconditionally clear the type feedback vector (including vector ICs).
6377 void ClearTypeFeedbackInfo();
6379 // Clear the type feedback vector with a more subtle policy at GC time.
6380 void ClearTypeFeedbackInfoAtGCTime();
6383 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6384 // even if the GC moves this SharedFunctionInfo.
6385 inline int unique_id() const;
6386 inline void set_unique_id(int value);
6389 // [instance class name]: class name for instances.
6390 DECL_ACCESSORS(instance_class_name, Object)
6392 // [function data]: This field holds some additional data for function.
6393 // Currently it has one of:
6394 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6395 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6396 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6397 // In the long run we don't want all functions to have this field but
6398 // we can fix that when we have a better model for storing hidden data
6400 DECL_ACCESSORS(function_data, Object)
6402 inline bool IsApiFunction();
6403 inline FunctionTemplateInfo* get_api_func_data();
6404 inline bool HasBuiltinFunctionId();
6405 inline BuiltinFunctionId builtin_function_id();
6406 inline bool HasBytecodeArray();
6407 inline BytecodeArray* bytecode_array();
6409 // [script info]: Script from which the function originates.
6410 DECL_ACCESSORS(script, Object)
6412 // [num_literals]: Number of literals used by this function.
6413 inline int num_literals() const;
6414 inline void set_num_literals(int value);
6416 // [start_position_and_type]: Field used to store both the source code
6417 // position, whether or not the function is a function expression,
6418 // and whether or not the function is a toplevel function. The two
6419 // least significants bit indicates whether the function is an
6420 // expression and the rest contains the source code position.
6421 inline int start_position_and_type() const;
6422 inline void set_start_position_and_type(int value);
6424 // The function is subject to debugging if a debug info is attached.
6425 inline bool HasDebugInfo();
6426 inline DebugInfo* GetDebugInfo();
6428 // A function has debug code if the compiled code has debug break slots.
6429 inline bool HasDebugCode();
6431 // [debug info]: Debug information.
6432 DECL_ACCESSORS(debug_info, Object)
6434 // [inferred name]: Name inferred from variable or property
6435 // assignment of this function. Used to facilitate debugging and
6436 // profiling of JavaScript code written in OO style, where almost
6437 // all functions are anonymous but are assigned to object
6439 DECL_ACCESSORS(inferred_name, String)
6441 // The function's name if it is non-empty, otherwise the inferred name.
6442 String* DebugName();
6444 // Position of the 'function' token in the script source.
6445 inline int function_token_position() const;
6446 inline void set_function_token_position(int function_token_position);
6448 // Position of this function in the script source.
6449 inline int start_position() const;
6450 inline void set_start_position(int start_position);
6452 // End position of this function in the script source.
6453 inline int end_position() const;
6454 inline void set_end_position(int end_position);
6456 // Is this function a function expression in the source code.
6457 DECL_BOOLEAN_ACCESSORS(is_expression)
6459 // Is this function a top-level function (scripts, evals).
6460 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6462 // Bit field containing various information collected by the compiler to
6463 // drive optimization.
6464 inline int compiler_hints() const;
6465 inline void set_compiler_hints(int value);
6467 inline int ast_node_count() const;
6468 inline void set_ast_node_count(int count);
6470 inline int profiler_ticks() const;
6471 inline void set_profiler_ticks(int ticks);
6473 // Inline cache age is used to infer whether the function survived a context
6474 // disposal or not. In the former case we reset the opt_count.
6475 inline int ic_age();
6476 inline void set_ic_age(int age);
6478 // Indicates if this function can be lazy compiled.
6479 // This is used to determine if we can safely flush code from a function
6480 // when doing GC if we expect that the function will no longer be used.
6481 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6483 // Indicates if this function can be lazy compiled without a context.
6484 // This is used to determine if we can force compilation without reaching
6485 // the function through program execution but through other means (e.g. heap
6486 // iteration by the debugger).
6487 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6489 // Indicates whether optimizations have been disabled for this
6490 // shared function info. If a function is repeatedly optimized or if
6491 // we cannot optimize the function we disable optimization to avoid
6492 // spending time attempting to optimize it again.
6493 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6495 // Indicates the language mode.
6496 inline LanguageMode language_mode();
6497 inline void set_language_mode(LanguageMode language_mode);
6499 // False if the function definitely does not allocate an arguments object.
6500 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6502 // Indicates that this function uses a super property (or an eval that may
6503 // use a super property).
6504 // This is needed to set up the [[HomeObject]] on the function instance.
6505 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6507 // True if the function has any duplicated parameter names.
6508 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6510 // Indicates whether the function is a native function.
6511 // These needs special treatment in .call and .apply since
6512 // null passed as the receiver should not be translated to the
6514 DECL_BOOLEAN_ACCESSORS(native)
6516 // Indicate that this function should always be inlined in optimized code.
6517 DECL_BOOLEAN_ACCESSORS(force_inline)
6519 // Indicates that the function was created by the Function function.
6520 // Though it's anonymous, toString should treat it as if it had the name
6521 // "anonymous". We don't set the name itself so that the system does not
6522 // see a binding for it.
6523 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6525 // Indicates whether the function is a bound function created using
6526 // the bind function.
6527 DECL_BOOLEAN_ACCESSORS(bound)
6529 // Indicates that the function is anonymous (the name field can be set
6530 // through the API, which does not change this flag).
6531 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6533 // Is this a function or top-level/eval code.
6534 DECL_BOOLEAN_ACCESSORS(is_function)
6536 // Indicates that code for this function cannot be compiled with Crankshaft.
6537 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6539 // Indicates that code for this function cannot be flushed.
6540 DECL_BOOLEAN_ACCESSORS(dont_flush)
6542 // Indicates that this function is a generator.
6543 DECL_BOOLEAN_ACCESSORS(is_generator)
6545 // Indicates that this function is an arrow function.
6546 DECL_BOOLEAN_ACCESSORS(is_arrow)
6548 // Indicates that this function is a concise method.
6549 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6551 // Indicates that this function is an accessor (getter or setter).
6552 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6554 // Indicates that this function is a default constructor.
6555 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6557 // Indicates that this function is an asm function.
6558 DECL_BOOLEAN_ACCESSORS(asm_function)
6560 // Indicates that the the shared function info is deserialized from cache.
6561 DECL_BOOLEAN_ACCESSORS(deserialized)
6563 // Indicates that the the shared function info has never been compiled before.
6564 DECL_BOOLEAN_ACCESSORS(never_compiled)
6566 inline FunctionKind kind();
6567 inline void set_kind(FunctionKind kind);
6569 // Indicates whether or not the code in the shared function support
6571 inline bool has_deoptimization_support();
6573 // Enable deoptimization support through recompiled code.
6574 void EnableDeoptimizationSupport(Code* recompiled);
6576 // Disable (further) attempted optimization of all functions sharing this
6577 // shared function info.
6578 void DisableOptimization(BailoutReason reason);
6580 inline BailoutReason disable_optimization_reason();
6582 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6583 // code, returns whether it asserted (i.e., always true if assertions are
6585 bool VerifyBailoutId(BailoutId id);
6587 // [source code]: Source code for the function.
6588 bool HasSourceCode() const;
6589 Handle<Object> GetSourceCode();
6591 // Number of times the function was optimized.
6592 inline int opt_count();
6593 inline void set_opt_count(int opt_count);
6595 // Number of times the function was deoptimized.
6596 inline void set_deopt_count(int value);
6597 inline int deopt_count();
6598 inline void increment_deopt_count();
6600 // Number of time we tried to re-enable optimization after it
6601 // was disabled due to high number of deoptimizations.
6602 inline void set_opt_reenable_tries(int value);
6603 inline int opt_reenable_tries();
6605 inline void TryReenableOptimization();
6607 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6608 inline void set_counters(int value);
6609 inline int counters() const;
6611 // Stores opt_count and bailout_reason as bit-fields.
6612 inline void set_opt_count_and_bailout_reason(int value);
6613 inline int opt_count_and_bailout_reason() const;
6615 void set_disable_optimization_reason(BailoutReason reason) {
6616 set_opt_count_and_bailout_reason(
6617 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6621 // Tells whether this function should be subject to debugging.
6622 inline bool IsSubjectToDebugging();
6624 // Check whether or not this function is inlineable.
6625 bool IsInlineable();
6627 // Source size of this function.
6630 // Calculate the instance size.
6631 int CalculateInstanceSize();
6633 // Calculate the number of in-object properties.
6634 int CalculateInObjectProperties();
6636 inline bool has_simple_parameters();
6638 // Initialize a SharedFunctionInfo from a parsed function literal.
6639 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6640 FunctionLiteral* lit);
6642 // Dispatched behavior.
6643 DECLARE_PRINTER(SharedFunctionInfo)
6644 DECLARE_VERIFIER(SharedFunctionInfo)
6646 void ResetForNewContext(int new_ic_age);
6648 DECLARE_CAST(SharedFunctionInfo)
6651 static const int kDontAdaptArgumentsSentinel = -1;
6653 // Layout description.
6655 static const int kNameOffset = HeapObject::kHeaderSize;
6656 static const int kCodeOffset = kNameOffset + kPointerSize;
6657 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6658 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6659 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6660 static const int kInstanceClassNameOffset =
6661 kConstructStubOffset + kPointerSize;
6662 static const int kFunctionDataOffset =
6663 kInstanceClassNameOffset + kPointerSize;
6664 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6665 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6666 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6667 static const int kFeedbackVectorOffset =
6668 kInferredNameOffset + kPointerSize;
6670 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6671 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6673 // Just to not break the postmortrem support with conditional offsets
6674 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6675 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6678 #if V8_HOST_ARCH_32_BIT
6680 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6681 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6682 static const int kExpectedNofPropertiesOffset =
6683 kFormalParameterCountOffset + kPointerSize;
6684 static const int kNumLiteralsOffset =
6685 kExpectedNofPropertiesOffset + kPointerSize;
6686 static const int kStartPositionAndTypeOffset =
6687 kNumLiteralsOffset + kPointerSize;
6688 static const int kEndPositionOffset =
6689 kStartPositionAndTypeOffset + kPointerSize;
6690 static const int kFunctionTokenPositionOffset =
6691 kEndPositionOffset + kPointerSize;
6692 static const int kCompilerHintsOffset =
6693 kFunctionTokenPositionOffset + kPointerSize;
6694 static const int kOptCountAndBailoutReasonOffset =
6695 kCompilerHintsOffset + kPointerSize;
6696 static const int kCountersOffset =
6697 kOptCountAndBailoutReasonOffset + kPointerSize;
6698 static const int kAstNodeCountOffset =
6699 kCountersOffset + kPointerSize;
6700 static const int kProfilerTicksOffset =
6701 kAstNodeCountOffset + kPointerSize;
6704 static const int kSize = kProfilerTicksOffset + kPointerSize;
6706 // The only reason to use smi fields instead of int fields
6707 // is to allow iteration without maps decoding during
6708 // garbage collections.
6709 // To avoid wasting space on 64-bit architectures we use
6710 // the following trick: we group integer fields into pairs
6711 // The least significant integer in each pair is shifted left by 1.
6712 // By doing this we guarantee that LSB of each kPointerSize aligned
6713 // word is not set and thus this word cannot be treated as pointer
6714 // to HeapObject during old space traversal.
6715 #if V8_TARGET_LITTLE_ENDIAN
6716 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6717 static const int kFormalParameterCountOffset =
6718 kLengthOffset + kIntSize;
6720 static const int kExpectedNofPropertiesOffset =
6721 kFormalParameterCountOffset + kIntSize;
6722 static const int kNumLiteralsOffset =
6723 kExpectedNofPropertiesOffset + kIntSize;
6725 static const int kEndPositionOffset =
6726 kNumLiteralsOffset + kIntSize;
6727 static const int kStartPositionAndTypeOffset =
6728 kEndPositionOffset + kIntSize;
6730 static const int kFunctionTokenPositionOffset =
6731 kStartPositionAndTypeOffset + kIntSize;
6732 static const int kCompilerHintsOffset =
6733 kFunctionTokenPositionOffset + kIntSize;
6735 static const int kOptCountAndBailoutReasonOffset =
6736 kCompilerHintsOffset + kIntSize;
6737 static const int kCountersOffset =
6738 kOptCountAndBailoutReasonOffset + kIntSize;
6740 static const int kAstNodeCountOffset =
6741 kCountersOffset + kIntSize;
6742 static const int kProfilerTicksOffset =
6743 kAstNodeCountOffset + kIntSize;
6746 static const int kSize = kProfilerTicksOffset + kIntSize;
6748 #elif V8_TARGET_BIG_ENDIAN
6749 static const int kFormalParameterCountOffset =
6750 kLastPointerFieldOffset + kPointerSize;
6751 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6753 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6754 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6756 static const int kStartPositionAndTypeOffset =
6757 kExpectedNofPropertiesOffset + kIntSize;
6758 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6760 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6761 static const int kFunctionTokenPositionOffset =
6762 kCompilerHintsOffset + kIntSize;
6764 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6765 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6767 static const int kProfilerTicksOffset =
6768 kOptCountAndBailoutReasonOffset + kIntSize;
6769 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6772 static const int kSize = kAstNodeCountOffset + kIntSize;
6775 #error Unknown byte ordering
6776 #endif // Big endian
6780 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6782 typedef FixedBodyDescriptor<kNameOffset,
6783 kLastPointerFieldOffset + kPointerSize,
6784 kSize> BodyDescriptor;
6786 // Bit positions in start_position_and_type.
6787 // The source code start position is in the 30 most significant bits of
6788 // the start_position_and_type field.
6789 static const int kIsExpressionBit = 0;
6790 static const int kIsTopLevelBit = 1;
6791 static const int kStartPositionShift = 2;
6792 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6794 // Bit positions in compiler_hints.
6795 enum CompilerHints {
6796 kAllowLazyCompilation,
6797 kAllowLazyCompilationWithoutContext,
6798 kOptimizationDisabled,
6799 kStrictModeFunction,
6800 kStrongModeFunction,
6803 kHasDuplicateParameters,
6808 kNameShouldPrintAsAnonymous,
6815 kIsAccessorFunction,
6816 kIsDefaultConstructor,
6817 kIsSubclassConstructor,
6823 kCompilerHintsCount // Pseudo entry
6825 // Add hints for other modes when they're added.
6826 STATIC_ASSERT(LANGUAGE_END == 3);
6828 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6830 class DeoptCountBits : public BitField<int, 0, 4> {};
6831 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6832 class ICAgeBits : public BitField<int, 22, 8> {};
6834 class OptCountBits : public BitField<int, 0, 22> {};
6835 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6838 #if V8_HOST_ARCH_32_BIT
6839 // On 32 bit platforms, compiler hints is a smi.
6840 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6841 static const int kCompilerHintsSize = kPointerSize;
6843 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6844 static const int kCompilerHintsSmiTagSize = 0;
6845 static const int kCompilerHintsSize = kIntSize;
6848 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6849 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6852 // Constants for optimizing codegen for strict mode function and
6854 // Allows to use byte-width instructions.
6855 static const int kStrictModeBitWithinByte =
6856 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6857 static const int kStrongModeBitWithinByte =
6858 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6860 static const int kNativeBitWithinByte =
6861 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6863 #if defined(V8_TARGET_LITTLE_ENDIAN)
6864 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6865 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6866 static const int kStrongModeByteOffset =
6867 kCompilerHintsOffset +
6868 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6869 static const int kNativeByteOffset = kCompilerHintsOffset +
6870 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6871 #elif defined(V8_TARGET_BIG_ENDIAN)
6872 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6873 (kCompilerHintsSize - 1) -
6874 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6875 static const int kStrongModeByteOffset =
6876 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6877 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6878 static const int kNativeByteOffset = kCompilerHintsOffset +
6879 (kCompilerHintsSize - 1) -
6880 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6882 #error Unknown byte ordering
6886 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6890 // Printing support.
6891 struct SourceCodeOf {
6892 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6893 : value(v), max_length(max) {}
6894 const SharedFunctionInfo* value;
6899 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6902 class JSGeneratorObject: public JSObject {
6904 // [function]: The function corresponding to this generator object.
6905 DECL_ACCESSORS(function, JSFunction)
6907 // [context]: The context of the suspended computation.
6908 DECL_ACCESSORS(context, Context)
6910 // [receiver]: The receiver of the suspended computation.
6911 DECL_ACCESSORS(receiver, Object)
6913 // [continuation]: Offset into code of continuation.
6915 // A positive offset indicates a suspended generator. The special
6916 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6917 // cannot be resumed.
6918 inline int continuation() const;
6919 inline void set_continuation(int continuation);
6920 inline bool is_closed();
6921 inline bool is_executing();
6922 inline bool is_suspended();
6924 // [operand_stack]: Saved operand stack.
6925 DECL_ACCESSORS(operand_stack, FixedArray)
6927 DECLARE_CAST(JSGeneratorObject)
6929 // Dispatched behavior.
6930 DECLARE_PRINTER(JSGeneratorObject)
6931 DECLARE_VERIFIER(JSGeneratorObject)
6933 // Magic sentinel values for the continuation.
6934 static const int kGeneratorExecuting = -1;
6935 static const int kGeneratorClosed = 0;
6937 // Layout description.
6938 static const int kFunctionOffset = JSObject::kHeaderSize;
6939 static const int kContextOffset = kFunctionOffset + kPointerSize;
6940 static const int kReceiverOffset = kContextOffset + kPointerSize;
6941 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6942 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6943 static const int kSize = kOperandStackOffset + kPointerSize;
6945 // Resume mode, for use by runtime functions.
6946 enum ResumeMode { NEXT, THROW };
6948 // Yielding from a generator returns an object with the following inobject
6949 // properties. See Context::iterator_result_map() for the map.
6950 static const int kResultValuePropertyIndex = 0;
6951 static const int kResultDonePropertyIndex = 1;
6952 static const int kResultPropertyCount = 2;
6954 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6955 static const int kResultDonePropertyOffset =
6956 kResultValuePropertyOffset + kPointerSize;
6957 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6960 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6964 // Representation for module instance objects.
6965 class JSModule: public JSObject {
6967 // [context]: the context holding the module's locals, or undefined if none.
6968 DECL_ACCESSORS(context, Object)
6970 // [scope_info]: Scope info.
6971 DECL_ACCESSORS(scope_info, ScopeInfo)
6973 DECLARE_CAST(JSModule)
6975 // Dispatched behavior.
6976 DECLARE_PRINTER(JSModule)
6977 DECLARE_VERIFIER(JSModule)
6979 // Layout description.
6980 static const int kContextOffset = JSObject::kHeaderSize;
6981 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6982 static const int kSize = kScopeInfoOffset + kPointerSize;
6985 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6989 // JSFunction describes JavaScript functions.
6990 class JSFunction: public JSObject {
6992 // [prototype_or_initial_map]:
6993 DECL_ACCESSORS(prototype_or_initial_map, Object)
6995 // [shared]: The information about the function that
6996 // can be shared by instances.
6997 DECL_ACCESSORS(shared, SharedFunctionInfo)
6999 // [context]: The context for this function.
7000 inline Context* context();
7001 inline void set_context(Object* context);
7002 inline JSObject* global_proxy();
7004 // [code]: The generated code object for this function. Executed
7005 // when the function is invoked, e.g. foo() or new foo(). See
7006 // [[Call]] and [[Construct]] description in ECMA-262, section
7008 inline Code* code();
7009 inline void set_code(Code* code);
7010 inline void set_code_no_write_barrier(Code* code);
7011 inline void ReplaceCode(Code* code);
7013 // Tells whether this function is builtin.
7014 inline bool IsBuiltin();
7016 // Tells whether this function inlines the given shared function info.
7017 bool Inlines(SharedFunctionInfo* candidate);
7019 // Tells whether this function should be subject to debugging.
7020 inline bool IsSubjectToDebugging();
7022 // Tells whether or not the function needs arguments adaption.
7023 inline bool NeedsArgumentsAdaption();
7025 // Tells whether or not this function has been optimized.
7026 inline bool IsOptimized();
7028 // Mark this function for lazy recompilation. The function will be
7029 // recompiled the next time it is executed.
7030 void MarkForOptimization();
7031 void AttemptConcurrentOptimization();
7033 // Tells whether or not the function is already marked for lazy
7035 inline bool IsMarkedForOptimization();
7036 inline bool IsMarkedForConcurrentOptimization();
7038 // Tells whether or not the function is on the concurrent recompilation queue.
7039 inline bool IsInOptimizationQueue();
7041 // Inobject slack tracking is the way to reclaim unused inobject space.
7043 // The instance size is initially determined by adding some slack to
7044 // expected_nof_properties (to allow for a few extra properties added
7045 // after the constructor). There is no guarantee that the extra space
7046 // will not be wasted.
7048 // Here is the algorithm to reclaim the unused inobject space:
7049 // - Detect the first constructor call for this JSFunction.
7050 // When it happens enter the "in progress" state: initialize construction
7051 // counter in the initial_map.
7052 // - While the tracking is in progress create objects filled with
7053 // one_pointer_filler_map instead of undefined_value. This way they can be
7054 // resized quickly and safely.
7055 // - Once enough objects have been created compute the 'slack'
7056 // (traverse the map transition tree starting from the
7057 // initial_map and find the lowest value of unused_property_fields).
7058 // - Traverse the transition tree again and decrease the instance size
7059 // of every map. Existing objects will resize automatically (they are
7060 // filled with one_pointer_filler_map). All further allocations will
7061 // use the adjusted instance size.
7062 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7063 // allocations made using different closures could actually create different
7064 // kind of objects (see prototype inheritance pattern).
7066 // Important: inobject slack tracking is not attempted during the snapshot
7069 // True if the initial_map is set and the object constructions countdown
7070 // counter is not zero.
7071 static const int kGenerousAllocationCount =
7072 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7073 inline bool IsInobjectSlackTrackingInProgress();
7075 // Starts the tracking.
7076 // Initializes object constructions countdown counter in the initial map.
7077 void StartInobjectSlackTracking();
7079 // Completes the tracking.
7080 void CompleteInobjectSlackTracking();
7082 // [literals_or_bindings]: Fixed array holding either
7083 // the materialized literals or the bindings of a bound function.
7085 // If the function contains object, regexp or array literals, the
7086 // literals array prefix contains the object, regexp, and array
7087 // function to be used when creating these literals. This is
7088 // necessary so that we do not dynamically lookup the object, regexp
7089 // or array functions. Performing a dynamic lookup, we might end up
7090 // using the functions from a new context that we should not have
7093 // On bound functions, the array is a (copy-on-write) fixed-array containing
7094 // the function that was bound, bound this-value and any bound
7095 // arguments. Bound functions never contain literals.
7096 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7098 inline FixedArray* literals();
7099 inline void set_literals(FixedArray* literals);
7101 inline FixedArray* function_bindings();
7102 inline void set_function_bindings(FixedArray* bindings);
7104 // The initial map for an object created by this constructor.
7105 inline Map* initial_map();
7106 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7107 Handle<Object> prototype);
7108 inline bool has_initial_map();
7109 static void EnsureHasInitialMap(Handle<JSFunction> function);
7111 // Get and set the prototype property on a JSFunction. If the
7112 // function has an initial map the prototype is set on the initial
7113 // map. Otherwise, the prototype is put in the initial map field
7114 // until an initial map is needed.
7115 inline bool has_prototype();
7116 inline bool has_instance_prototype();
7117 inline Object* prototype();
7118 inline Object* instance_prototype();
7119 static void SetPrototype(Handle<JSFunction> function,
7120 Handle<Object> value);
7121 static void SetInstancePrototype(Handle<JSFunction> function,
7122 Handle<Object> value);
7124 // Creates a new closure for the fucntion with the same bindings,
7125 // bound values, and prototype. An equivalent of spec operations
7126 // ``CloneMethod`` and ``CloneBoundFunction``.
7127 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7129 // After prototype is removed, it will not be created when accessed, and
7130 // [[Construct]] from this function will not be allowed.
7131 bool RemovePrototype();
7132 inline bool should_have_prototype();
7134 // Accessor for this function's initial map's [[class]]
7135 // property. This is primarily used by ECMA native functions. This
7136 // method sets the class_name field of this function's initial map
7137 // to a given value. It creates an initial map if this function does
7138 // not have one. Note that this method does not copy the initial map
7139 // if it has one already, but simply replaces it with the new value.
7140 // Instances created afterwards will have a map whose [[class]] is
7141 // set to 'value', but there is no guarantees on instances created
7143 void SetInstanceClassName(String* name);
7145 // Returns if this function has been compiled to native code yet.
7146 inline bool is_compiled();
7148 // Returns `false` if formal parameters include rest parameters, optional
7149 // parameters, or destructuring parameters.
7150 // TODO(caitp): make this a flag set during parsing
7151 inline bool has_simple_parameters();
7153 // [next_function_link]: Links functions into various lists, e.g. the list
7154 // of optimized functions hanging off the native_context. The CodeFlusher
7155 // uses this link to chain together flushing candidates. Treated weakly
7156 // by the garbage collector.
7157 DECL_ACCESSORS(next_function_link, Object)
7159 // Prints the name of the function using PrintF.
7160 void PrintName(FILE* out = stdout);
7162 DECLARE_CAST(JSFunction)
7164 // Iterates the objects, including code objects indirectly referenced
7165 // through pointers to the first instruction in the code object.
7166 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7168 // Dispatched behavior.
7169 DECLARE_PRINTER(JSFunction)
7170 DECLARE_VERIFIER(JSFunction)
7172 // Returns the number of allocated literals.
7173 inline int NumberOfLiterals();
7175 // Used for flags such as --hydrogen-filter.
7176 bool PassesFilter(const char* raw_filter);
7178 // The function's name if it is configured, otherwise shared function info
7180 static Handle<String> GetDebugName(Handle<JSFunction> function);
7182 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7183 // kSize) is weak and has special handling during garbage collection.
7184 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7185 static const int kPrototypeOrInitialMapOffset =
7186 kCodeEntryOffset + kPointerSize;
7187 static const int kSharedFunctionInfoOffset =
7188 kPrototypeOrInitialMapOffset + kPointerSize;
7189 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7190 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7191 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7192 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7193 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7195 // Layout of the bound-function binding array.
7196 static const int kBoundFunctionIndex = 0;
7197 static const int kBoundThisIndex = 1;
7198 static const int kBoundArgumentsStartIndex = 2;
7201 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7205 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7206 // and the prototype is hidden. JSGlobalProxy always delegates
7207 // property accesses to its prototype if the prototype is not null.
7209 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7211 // Accessing a JSGlobalProxy requires security check.
7213 class JSGlobalProxy : public JSObject {
7215 // [native_context]: the owner native context of this global proxy object.
7216 // It is null value if this object is not used by any context.
7217 DECL_ACCESSORS(native_context, Object)
7219 // [hash]: The hash code property (undefined if not initialized yet).
7220 DECL_ACCESSORS(hash, Object)
7222 DECLARE_CAST(JSGlobalProxy)
7224 inline bool IsDetachedFrom(GlobalObject* global) const;
7226 // Dispatched behavior.
7227 DECLARE_PRINTER(JSGlobalProxy)
7228 DECLARE_VERIFIER(JSGlobalProxy)
7230 // Layout description.
7231 static const int kNativeContextOffset = JSObject::kHeaderSize;
7232 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7233 static const int kSize = kHashOffset + kPointerSize;
7236 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7240 // Common super class for JavaScript global objects and the special
7241 // builtins global objects.
7242 class GlobalObject: public JSObject {
7244 // [builtins]: the object holding the runtime routines written in JS.
7245 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7247 // [native context]: the natives corresponding to this global object.
7248 DECL_ACCESSORS(native_context, Context)
7250 // [global proxy]: the global proxy object of the context
7251 DECL_ACCESSORS(global_proxy, JSObject)
7253 DECLARE_CAST(GlobalObject)
7255 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7257 // Ensure that the global object has a cell for the given property name.
7258 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7261 // Layout description.
7262 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7263 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7264 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7265 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7268 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7272 // JavaScript global object.
7273 class JSGlobalObject: public GlobalObject {
7275 DECLARE_CAST(JSGlobalObject)
7277 inline bool IsDetached();
7279 // Dispatched behavior.
7280 DECLARE_PRINTER(JSGlobalObject)
7281 DECLARE_VERIFIER(JSGlobalObject)
7283 // Layout description.
7284 static const int kSize = GlobalObject::kHeaderSize;
7287 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7291 // Builtins global object which holds the runtime routines written in
7293 class JSBuiltinsObject: public GlobalObject {
7295 // Accessors for the runtime routines written in JavaScript.
7296 inline Object* javascript_builtin(Builtins::JavaScript id);
7297 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7299 DECLARE_CAST(JSBuiltinsObject)
7301 // Dispatched behavior.
7302 DECLARE_PRINTER(JSBuiltinsObject)
7303 DECLARE_VERIFIER(JSBuiltinsObject)
7305 // Layout description. The size of the builtins object includes
7306 // room for two pointers per runtime routine written in javascript
7307 // (function and code object).
7308 static const int kJSBuiltinsCount = Builtins::id_count;
7309 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7310 static const int kSize =
7311 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7313 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7314 return kJSBuiltinsOffset + id * kPointerSize;
7318 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7322 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7323 class JSValue: public JSObject {
7325 // [value]: the object being wrapped.
7326 DECL_ACCESSORS(value, Object)
7328 DECLARE_CAST(JSValue)
7330 // Dispatched behavior.
7331 DECLARE_PRINTER(JSValue)
7332 DECLARE_VERIFIER(JSValue)
7334 // Layout description.
7335 static const int kValueOffset = JSObject::kHeaderSize;
7336 static const int kSize = kValueOffset + kPointerSize;
7339 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7345 // Representation for JS date objects.
7346 class JSDate: public JSObject {
7348 // If one component is NaN, all of them are, indicating a NaN time value.
7349 // [value]: the time value.
7350 DECL_ACCESSORS(value, Object)
7351 // [year]: caches year. Either undefined, smi, or NaN.
7352 DECL_ACCESSORS(year, Object)
7353 // [month]: caches month. Either undefined, smi, or NaN.
7354 DECL_ACCESSORS(month, Object)
7355 // [day]: caches day. Either undefined, smi, or NaN.
7356 DECL_ACCESSORS(day, Object)
7357 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7358 DECL_ACCESSORS(weekday, Object)
7359 // [hour]: caches hours. Either undefined, smi, or NaN.
7360 DECL_ACCESSORS(hour, Object)
7361 // [min]: caches minutes. Either undefined, smi, or NaN.
7362 DECL_ACCESSORS(min, Object)
7363 // [sec]: caches seconds. Either undefined, smi, or NaN.
7364 DECL_ACCESSORS(sec, Object)
7365 // [cache stamp]: sample of the date cache stamp at the
7366 // moment when chached fields were cached.
7367 DECL_ACCESSORS(cache_stamp, Object)
7369 DECLARE_CAST(JSDate)
7371 // Returns the date field with the specified index.
7372 // See FieldIndex for the list of date fields.
7373 static Object* GetField(Object* date, Smi* index);
7375 void SetValue(Object* value, bool is_value_nan);
7378 // Dispatched behavior.
7379 DECLARE_PRINTER(JSDate)
7380 DECLARE_VERIFIER(JSDate)
7382 // The order is important. It must be kept in sync with date macros
7393 kFirstUncachedField,
7394 kMillisecond = kFirstUncachedField,
7398 kYearUTC = kFirstUTCField,
7411 // Layout description.
7412 static const int kValueOffset = JSObject::kHeaderSize;
7413 static const int kYearOffset = kValueOffset + kPointerSize;
7414 static const int kMonthOffset = kYearOffset + kPointerSize;
7415 static const int kDayOffset = kMonthOffset + kPointerSize;
7416 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7417 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7418 static const int kMinOffset = kHourOffset + kPointerSize;
7419 static const int kSecOffset = kMinOffset + kPointerSize;
7420 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7421 static const int kSize = kCacheStampOffset + kPointerSize;
7424 inline Object* DoGetField(FieldIndex index);
7426 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7428 // Computes and caches the cacheable fields of the date.
7429 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7432 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7436 // Representation of message objects used for error reporting through
7437 // the API. The messages are formatted in JavaScript so this object is
7438 // a real JavaScript object. The information used for formatting the
7439 // error messages are not directly accessible from JavaScript to
7440 // prevent leaking information to user code called during error
7442 class JSMessageObject: public JSObject {
7444 // [type]: the type of error message.
7445 inline int type() const;
7446 inline void set_type(int value);
7448 // [arguments]: the arguments for formatting the error message.
7449 DECL_ACCESSORS(argument, Object)
7451 // [script]: the script from which the error message originated.
7452 DECL_ACCESSORS(script, Object)
7454 // [stack_frames]: an array of stack frames for this error object.
7455 DECL_ACCESSORS(stack_frames, Object)
7457 // [start_position]: the start position in the script for the error message.
7458 inline int start_position() const;
7459 inline void set_start_position(int value);
7461 // [end_position]: the end position in the script for the error message.
7462 inline int end_position() const;
7463 inline void set_end_position(int value);
7465 DECLARE_CAST(JSMessageObject)
7467 // Dispatched behavior.
7468 DECLARE_PRINTER(JSMessageObject)
7469 DECLARE_VERIFIER(JSMessageObject)
7471 // Layout description.
7472 static const int kTypeOffset = JSObject::kHeaderSize;
7473 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7474 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7475 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7476 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7477 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7478 static const int kSize = kEndPositionOffset + kPointerSize;
7480 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7481 kStackFramesOffset + kPointerSize,
7482 kSize> BodyDescriptor;
7486 // Regular expressions
7487 // The regular expression holds a single reference to a FixedArray in
7488 // the kDataOffset field.
7489 // The FixedArray contains the following data:
7490 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7491 // - reference to the original source string
7492 // - reference to the original flag string
7493 // If it is an atom regexp
7494 // - a reference to a literal string to search for
7495 // If it is an irregexp regexp:
7496 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7497 // used for tracking the last usage (used for code flushing).
7498 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7499 // used for tracking the last usage (used for code flushing)..
7500 // - max number of registers used by irregexp implementations.
7501 // - number of capture registers (output values) of the regexp.
7502 class JSRegExp: public JSObject {
7505 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7506 // ATOM: A simple string to match against using an indexOf operation.
7507 // IRREGEXP: Compiled with Irregexp.
7508 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7509 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7516 UNICODE_ESCAPES = 16
7521 explicit Flags(uint32_t value) : value_(value) { }
7522 bool is_global() { return (value_ & GLOBAL) != 0; }
7523 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7524 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7525 bool is_sticky() { return (value_ & STICKY) != 0; }
7526 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7527 uint32_t value() { return value_; }
7532 DECL_ACCESSORS(data, Object)
7534 inline Type TypeTag();
7535 inline int CaptureCount();
7536 inline Flags GetFlags();
7537 inline String* Pattern();
7538 inline Object* DataAt(int index);
7539 // Set implementation data after the object has been prepared.
7540 inline void SetDataAt(int index, Object* value);
7542 static int code_index(bool is_latin1) {
7544 return kIrregexpLatin1CodeIndex;
7546 return kIrregexpUC16CodeIndex;
7550 static int saved_code_index(bool is_latin1) {
7552 return kIrregexpLatin1CodeSavedIndex;
7554 return kIrregexpUC16CodeSavedIndex;
7558 DECLARE_CAST(JSRegExp)
7560 // Dispatched behavior.
7561 DECLARE_VERIFIER(JSRegExp)
7563 static const int kDataOffset = JSObject::kHeaderSize;
7564 static const int kSize = kDataOffset + kPointerSize;
7566 // Indices in the data array.
7567 static const int kTagIndex = 0;
7568 static const int kSourceIndex = kTagIndex + 1;
7569 static const int kFlagsIndex = kSourceIndex + 1;
7570 static const int kDataIndex = kFlagsIndex + 1;
7571 // The data fields are used in different ways depending on the
7572 // value of the tag.
7573 // Atom regexps (literal strings).
7574 static const int kAtomPatternIndex = kDataIndex;
7576 static const int kAtomDataSize = kAtomPatternIndex + 1;
7578 // Irregexp compiled code or bytecode for Latin1. If compilation
7579 // fails, this fields hold an exception object that should be
7580 // thrown if the regexp is used again.
7581 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7582 // Irregexp compiled code or bytecode for UC16. If compilation
7583 // fails, this fields hold an exception object that should be
7584 // thrown if the regexp is used again.
7585 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7587 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7588 // is a potential candidate for flushing.
7589 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7590 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7591 // a potential candidate for flushing.
7592 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7594 // Maximal number of registers used by either Latin1 or UC16.
7595 // Only used to check that there is enough stack space
7596 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7597 // Number of captures in the compiled regexp.
7598 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7600 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7602 // Offsets directly into the data fixed array.
7603 static const int kDataTagOffset =
7604 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7605 static const int kDataOneByteCodeOffset =
7606 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7607 static const int kDataUC16CodeOffset =
7608 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7609 static const int kIrregexpCaptureCountOffset =
7610 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7612 // In-object fields.
7613 static const int kSourceFieldIndex = 0;
7614 static const int kGlobalFieldIndex = 1;
7615 static const int kIgnoreCaseFieldIndex = 2;
7616 static const int kMultilineFieldIndex = 3;
7617 static const int kLastIndexFieldIndex = 4;
7618 static const int kInObjectFieldCount = 5;
7620 // The uninitialized value for a regexp code object.
7621 static const int kUninitializedValue = -1;
7623 // The compilation error value for the regexp code object. The real error
7624 // object is in the saved code field.
7625 static const int kCompilationErrorValue = -2;
7627 // When we store the sweep generation at which we moved the code from the
7628 // code index to the saved code index we mask it of to be in the [0:255]
7630 static const int kCodeAgeMask = 0xff;
7634 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7636 static inline bool IsMatch(HashTableKey* key, Object* value) {
7637 return key->IsMatch(value);
7640 static inline uint32_t Hash(HashTableKey* key) {
7644 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7645 return key->HashForObject(object);
7648 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7650 static const int kPrefixSize = 0;
7651 static const int kEntrySize = 2;
7655 // This cache is used in two different variants. For regexp caching, it simply
7656 // maps identifying info of the regexp to the cached regexp object. Scripts and
7657 // eval code only gets cached after a second probe for the code object. To do
7658 // so, on first "put" only a hash identifying the source is entered into the
7659 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7660 // such lifetimes get reduced, and removed once they reach zero. If a second put
7661 // is called while such a hash is live in the cache, the hash gets replaced by
7662 // an actual cache entry. Age also removes stale live entries from the cache.
7663 // Such entries are identified by SharedFunctionInfos pointing to either the
7664 // recompilation stub, or to "old" code. This avoids memory leaks due to
7665 // premature caching of scripts and eval strings that are never needed later.
7666 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7667 CompilationCacheShape,
7670 // Find cached value for a string key, otherwise return null.
7671 Handle<Object> Lookup(
7672 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7673 Handle<Object> LookupEval(
7674 Handle<String> src, Handle<SharedFunctionInfo> shared,
7675 LanguageMode language_mode, int scope_position);
7676 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7677 static Handle<CompilationCacheTable> Put(
7678 Handle<CompilationCacheTable> cache, Handle<String> src,
7679 Handle<Context> context, LanguageMode language_mode,
7680 Handle<Object> value);
7681 static Handle<CompilationCacheTable> PutEval(
7682 Handle<CompilationCacheTable> cache, Handle<String> src,
7683 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7684 int scope_position);
7685 static Handle<CompilationCacheTable> PutRegExp(
7686 Handle<CompilationCacheTable> cache, Handle<String> src,
7687 JSRegExp::Flags flags, Handle<FixedArray> value);
7688 void Remove(Object* value);
7690 static const int kHashGenerations = 10;
7692 DECLARE_CAST(CompilationCacheTable)
7695 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7699 class CodeCache: public Struct {
7701 DECL_ACCESSORS(default_cache, FixedArray)
7702 DECL_ACCESSORS(normal_type_cache, Object)
7704 // Add the code object to the cache.
7706 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7708 // Lookup code object in the cache. Returns code object if found and undefined
7710 Object* Lookup(Name* name, Code::Flags flags);
7712 // Get the internal index of a code object in the cache. Returns -1 if the
7713 // code object is not in that cache. This index can be used to later call
7714 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7716 int GetIndex(Object* name, Code* code);
7718 // Remove an object from the cache with the provided internal index.
7719 void RemoveByIndex(Object* name, Code* code, int index);
7721 DECLARE_CAST(CodeCache)
7723 // Dispatched behavior.
7724 DECLARE_PRINTER(CodeCache)
7725 DECLARE_VERIFIER(CodeCache)
7727 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7728 static const int kNormalTypeCacheOffset =
7729 kDefaultCacheOffset + kPointerSize;
7730 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7733 static void UpdateDefaultCache(
7734 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7735 static void UpdateNormalTypeCache(
7736 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7737 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7738 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7740 // Code cache layout of the default cache. Elements are alternating name and
7741 // code objects for non normal load/store/call IC's.
7742 static const int kCodeCacheEntrySize = 2;
7743 static const int kCodeCacheEntryNameOffset = 0;
7744 static const int kCodeCacheEntryCodeOffset = 1;
7746 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7750 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7752 static inline bool IsMatch(HashTableKey* key, Object* value) {
7753 return key->IsMatch(value);
7756 static inline uint32_t Hash(HashTableKey* key) {
7760 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7761 return key->HashForObject(object);
7764 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7766 static const int kPrefixSize = 0;
7767 static const int kEntrySize = 2;
7771 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7772 CodeCacheHashTableShape,
7775 Object* Lookup(Name* name, Code::Flags flags);
7776 static Handle<CodeCacheHashTable> Put(
7777 Handle<CodeCacheHashTable> table,
7781 int GetIndex(Name* name, Code::Flags flags);
7782 void RemoveByIndex(int index);
7784 DECLARE_CAST(CodeCacheHashTable)
7786 // Initial size of the fixed array backing the hash table.
7787 static const int kInitialSize = 64;
7790 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7794 class PolymorphicCodeCache: public Struct {
7796 DECL_ACCESSORS(cache, Object)
7798 static void Update(Handle<PolymorphicCodeCache> cache,
7799 MapHandleList* maps,
7804 // Returns an undefined value if the entry is not found.
7805 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7807 DECLARE_CAST(PolymorphicCodeCache)
7809 // Dispatched behavior.
7810 DECLARE_PRINTER(PolymorphicCodeCache)
7811 DECLARE_VERIFIER(PolymorphicCodeCache)
7813 static const int kCacheOffset = HeapObject::kHeaderSize;
7814 static const int kSize = kCacheOffset + kPointerSize;
7817 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7821 class PolymorphicCodeCacheHashTable
7822 : public HashTable<PolymorphicCodeCacheHashTable,
7823 CodeCacheHashTableShape,
7826 Object* Lookup(MapHandleList* maps, int code_kind);
7828 static Handle<PolymorphicCodeCacheHashTable> Put(
7829 Handle<PolymorphicCodeCacheHashTable> hash_table,
7830 MapHandleList* maps,
7834 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7836 static const int kInitialSize = 64;
7838 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7842 class TypeFeedbackInfo: public Struct {
7844 inline int ic_total_count();
7845 inline void set_ic_total_count(int count);
7847 inline int ic_with_type_info_count();
7848 inline void change_ic_with_type_info_count(int delta);
7850 inline int ic_generic_count();
7851 inline void change_ic_generic_count(int delta);
7853 inline void initialize_storage();
7855 inline void change_own_type_change_checksum();
7856 inline int own_type_change_checksum();
7858 inline void set_inlined_type_change_checksum(int checksum);
7859 inline bool matches_inlined_type_change_checksum(int checksum);
7861 DECLARE_CAST(TypeFeedbackInfo)
7863 // Dispatched behavior.
7864 DECLARE_PRINTER(TypeFeedbackInfo)
7865 DECLARE_VERIFIER(TypeFeedbackInfo)
7867 static const int kStorage1Offset = HeapObject::kHeaderSize;
7868 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7869 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7870 static const int kSize = kStorage3Offset + kPointerSize;
7873 static const int kTypeChangeChecksumBits = 7;
7875 class ICTotalCountField: public BitField<int, 0,
7876 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7877 class OwnTypeChangeChecksum: public BitField<int,
7878 kSmiValueSize - kTypeChangeChecksumBits,
7879 kTypeChangeChecksumBits> {}; // NOLINT
7880 class ICsWithTypeInfoCountField: public BitField<int, 0,
7881 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7882 class InlinedTypeChangeChecksum: public BitField<int,
7883 kSmiValueSize - kTypeChangeChecksumBits,
7884 kTypeChangeChecksumBits> {}; // NOLINT
7886 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7890 enum AllocationSiteMode {
7891 DONT_TRACK_ALLOCATION_SITE,
7892 TRACK_ALLOCATION_SITE,
7893 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7897 class AllocationSite: public Struct {
7899 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7900 static const double kPretenureRatio;
7901 static const int kPretenureMinimumCreated = 100;
7903 // Values for pretenure decision field.
7904 enum PretenureDecision {
7910 kLastPretenureDecisionValue = kZombie
7913 const char* PretenureDecisionName(PretenureDecision decision);
7915 DECL_ACCESSORS(transition_info, Object)
7916 // nested_site threads a list of sites that represent nested literals
7917 // walked in a particular order. So [[1, 2], 1, 2] will have one
7918 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7919 DECL_ACCESSORS(nested_site, Object)
7920 DECL_ACCESSORS(pretenure_data, Smi)
7921 DECL_ACCESSORS(pretenure_create_count, Smi)
7922 DECL_ACCESSORS(dependent_code, DependentCode)
7923 DECL_ACCESSORS(weak_next, Object)
7925 inline void Initialize();
7927 // This method is expensive, it should only be called for reporting.
7928 bool IsNestedSite();
7930 // transition_info bitfields, for constructed array transition info.
7931 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7932 class UnusedBits: public BitField<int, 15, 14> {};
7933 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7935 // Bitfields for pretenure_data
7936 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7937 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7938 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7939 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7941 // Increments the mementos found counter and returns true when the first
7942 // memento was found for a given allocation site.
7943 inline bool IncrementMementoFoundCount();
7945 inline void IncrementMementoCreateCount();
7947 PretenureFlag GetPretenureMode();
7949 void ResetPretenureDecision();
7951 PretenureDecision pretenure_decision() {
7952 int value = pretenure_data()->value();
7953 return PretenureDecisionBits::decode(value);
7956 void set_pretenure_decision(PretenureDecision decision) {
7957 int value = pretenure_data()->value();
7959 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
7960 SKIP_WRITE_BARRIER);
7963 bool deopt_dependent_code() {
7964 int value = pretenure_data()->value();
7965 return DeoptDependentCodeBit::decode(value);
7968 void set_deopt_dependent_code(bool deopt) {
7969 int value = pretenure_data()->value();
7971 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
7972 SKIP_WRITE_BARRIER);
7975 int memento_found_count() {
7976 int value = pretenure_data()->value();
7977 return MementoFoundCountBits::decode(value);
7980 inline void set_memento_found_count(int count);
7982 int memento_create_count() {
7983 return pretenure_create_count()->value();
7986 void set_memento_create_count(int count) {
7987 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
7990 // The pretenuring decision is made during gc, and the zombie state allows
7991 // us to recognize when an allocation site is just being kept alive because
7992 // a later traversal of new space may discover AllocationMementos that point
7993 // to this AllocationSite.
7995 return pretenure_decision() == kZombie;
7998 bool IsMaybeTenure() {
7999 return pretenure_decision() == kMaybeTenure;
8002 inline void MarkZombie();
8004 inline bool MakePretenureDecision(PretenureDecision current_decision,
8006 bool maximum_size_scavenge);
8008 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8010 ElementsKind GetElementsKind() {
8011 DCHECK(!SitePointsToLiteral());
8012 int value = Smi::cast(transition_info())->value();
8013 return ElementsKindBits::decode(value);
8016 void SetElementsKind(ElementsKind kind) {
8017 int value = Smi::cast(transition_info())->value();
8018 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8019 SKIP_WRITE_BARRIER);
8022 bool CanInlineCall() {
8023 int value = Smi::cast(transition_info())->value();
8024 return DoNotInlineBit::decode(value) == 0;
8027 void SetDoNotInlineCall() {
8028 int value = Smi::cast(transition_info())->value();
8029 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8030 SKIP_WRITE_BARRIER);
8033 bool SitePointsToLiteral() {
8034 // If transition_info is a smi, then it represents an ElementsKind
8035 // for a constructed array. Otherwise, it must be a boilerplate
8036 // for an object or array literal.
8037 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8040 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8041 ElementsKind to_kind);
8043 DECLARE_PRINTER(AllocationSite)
8044 DECLARE_VERIFIER(AllocationSite)
8046 DECLARE_CAST(AllocationSite)
8047 static inline AllocationSiteMode GetMode(
8048 ElementsKind boilerplate_elements_kind);
8049 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8050 static inline bool CanTrack(InstanceType type);
8052 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8053 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8054 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8055 static const int kPretenureCreateCountOffset =
8056 kPretenureDataOffset + kPointerSize;
8057 static const int kDependentCodeOffset =
8058 kPretenureCreateCountOffset + kPointerSize;
8059 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8060 static const int kSize = kWeakNextOffset + kPointerSize;
8062 // During mark compact we need to take special care for the dependent code
8064 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8065 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8067 // For other visitors, use the fixed body descriptor below.
8068 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8069 kDependentCodeOffset + kPointerSize,
8070 kSize> BodyDescriptor;
8073 bool PretenuringDecisionMade() {
8074 return pretenure_decision() != kUndecided;
8077 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8081 class AllocationMemento: public Struct {
8083 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8084 static const int kSize = kAllocationSiteOffset + kPointerSize;
8086 DECL_ACCESSORS(allocation_site, Object)
8089 return allocation_site()->IsAllocationSite() &&
8090 !AllocationSite::cast(allocation_site())->IsZombie();
8092 AllocationSite* GetAllocationSite() {
8094 return AllocationSite::cast(allocation_site());
8097 DECLARE_PRINTER(AllocationMemento)
8098 DECLARE_VERIFIER(AllocationMemento)
8100 DECLARE_CAST(AllocationMemento)
8103 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8107 // Representation of a slow alias as part of a sloppy arguments objects.
8108 // For fast aliases (if HasSloppyArgumentsElements()):
8109 // - the parameter map contains an index into the context
8110 // - all attributes of the element have default values
8111 // For slow aliases (if HasDictionaryArgumentsElements()):
8112 // - the parameter map contains no fast alias mapping (i.e. the hole)
8113 // - this struct (in the slow backing store) contains an index into the context
8114 // - all attributes are available as part if the property details
8115 class AliasedArgumentsEntry: public Struct {
8117 inline int aliased_context_slot() const;
8118 inline void set_aliased_context_slot(int count);
8120 DECLARE_CAST(AliasedArgumentsEntry)
8122 // Dispatched behavior.
8123 DECLARE_PRINTER(AliasedArgumentsEntry)
8124 DECLARE_VERIFIER(AliasedArgumentsEntry)
8126 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8127 static const int kSize = kAliasedContextSlot + kPointerSize;
8130 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8134 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8135 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8138 class StringHasher {
8140 explicit inline StringHasher(int length, uint32_t seed);
8142 template <typename schar>
8143 static inline uint32_t HashSequentialString(const schar* chars,
8147 // Reads all the data, even for long strings and computes the utf16 length.
8148 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8150 int* utf16_length_out);
8152 // Calculated hash value for a string consisting of 1 to
8153 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8154 // value is represented decimal value.
8155 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8157 // No string is allowed to have a hash of zero. That value is reserved
8158 // for internal properties. If the hash calculation yields zero then we
8160 static const int kZeroHash = 27;
8162 // Reusable parts of the hashing algorithm.
8163 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8164 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8165 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8166 const uc16* chars, int length));
8167 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8172 // Returns the value to store in the hash field of a string with
8173 // the given length and contents.
8174 uint32_t GetHashField();
8175 // Returns true if the hash of this string can be computed without
8176 // looking at the contents.
8177 inline bool has_trivial_hash();
8178 // Adds a block of characters to the hash.
8179 template<typename Char>
8180 inline void AddCharacters(const Char* chars, int len);
8183 // Add a character to the hash.
8184 inline void AddCharacter(uint16_t c);
8185 // Update index. Returns true if string is still an index.
8186 inline bool UpdateIndex(uint16_t c);
8189 uint32_t raw_running_hash_;
8190 uint32_t array_index_;
8191 bool is_array_index_;
8192 bool is_first_char_;
8193 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8197 class IteratingStringHasher : public StringHasher {
8199 static inline uint32_t Hash(String* string, uint32_t seed);
8200 inline void VisitOneByteString(const uint8_t* chars, int length);
8201 inline void VisitTwoByteString(const uint16_t* chars, int length);
8204 inline IteratingStringHasher(int len, uint32_t seed)
8205 : StringHasher(len, seed) {}
8206 void VisitConsString(ConsString* cons_string);
8207 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8211 // The characteristics of a string are stored in its map. Retrieving these
8212 // few bits of information is moderately expensive, involving two memory
8213 // loads where the second is dependent on the first. To improve efficiency
8214 // the shape of the string is given its own class so that it can be retrieved
8215 // once and used for several string operations. A StringShape is small enough
8216 // to be passed by value and is immutable, but be aware that flattening a
8217 // string can potentially alter its shape. Also be aware that a GC caused by
8218 // something else can alter the shape of a string due to ConsString
8219 // shortcutting. Keeping these restrictions in mind has proven to be error-
8220 // prone and so we no longer put StringShapes in variables unless there is a
8221 // concrete performance benefit at that particular point in the code.
8222 class StringShape BASE_EMBEDDED {
8224 inline explicit StringShape(const String* s);
8225 inline explicit StringShape(Map* s);
8226 inline explicit StringShape(InstanceType t);
8227 inline bool IsSequential();
8228 inline bool IsExternal();
8229 inline bool IsCons();
8230 inline bool IsSliced();
8231 inline bool IsIndirect();
8232 inline bool IsExternalOneByte();
8233 inline bool IsExternalTwoByte();
8234 inline bool IsSequentialOneByte();
8235 inline bool IsSequentialTwoByte();
8236 inline bool IsInternalized();
8237 inline StringRepresentationTag representation_tag();
8238 inline uint32_t encoding_tag();
8239 inline uint32_t full_representation_tag();
8240 inline uint32_t size_tag();
8242 inline uint32_t type() { return type_; }
8243 inline void invalidate() { valid_ = false; }
8244 inline bool valid() { return valid_; }
8246 inline void invalidate() { }
8252 inline void set_valid() { valid_ = true; }
8255 inline void set_valid() { }
8260 // The Name abstract class captures anything that can be used as a property
8261 // name, i.e., strings and symbols. All names store a hash value.
8262 class Name: public HeapObject {
8264 // Get and set the hash field of the name.
8265 inline uint32_t hash_field();
8266 inline void set_hash_field(uint32_t value);
8268 // Tells whether the hash code has been computed.
8269 inline bool HasHashCode();
8271 // Returns a hash value used for the property table
8272 inline uint32_t Hash();
8274 // Equality operations.
8275 inline bool Equals(Name* other);
8276 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8279 inline bool AsArrayIndex(uint32_t* index);
8281 // If the name is private, it can only name own properties.
8282 inline bool IsPrivate();
8284 // If the name is a non-flat string, this method returns a flat version of the
8285 // string. Otherwise it'll just return the input.
8286 static inline Handle<Name> Flatten(Handle<Name> name,
8287 PretenureFlag pretenure = NOT_TENURED);
8291 DECLARE_PRINTER(Name)
8293 void NameShortPrint();
8294 int NameShortPrint(Vector<char> str);
8297 // Layout description.
8298 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8299 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8300 static const int kHashFieldOffset = kHashFieldSlot;
8302 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8304 static const int kSize = kHashFieldSlot + kPointerSize;
8306 // Mask constant for checking if a name has a computed hash code
8307 // and if it is a string that is an array index. The least significant bit
8308 // indicates whether a hash code has been computed. If the hash code has
8309 // been computed the 2nd bit tells whether the string can be used as an
8311 static const int kHashNotComputedMask = 1;
8312 static const int kIsNotArrayIndexMask = 1 << 1;
8313 static const int kNofHashBitFields = 2;
8315 // Shift constant retrieving hash code from hash field.
8316 static const int kHashShift = kNofHashBitFields;
8318 // Only these bits are relevant in the hash, since the top two are shifted
8320 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8322 // Array index strings this short can keep their index in the hash field.
8323 static const int kMaxCachedArrayIndexLength = 7;
8325 // For strings which are array indexes the hash value has the string length
8326 // mixed into the hash, mainly to avoid a hash value of zero which would be
8327 // the case for the string '0'. 24 bits are used for the array index value.
8328 static const int kArrayIndexValueBits = 24;
8329 static const int kArrayIndexLengthBits =
8330 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8332 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8334 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8335 kArrayIndexValueBits> {}; // NOLINT
8336 class ArrayIndexLengthBits : public BitField<unsigned int,
8337 kNofHashBitFields + kArrayIndexValueBits,
8338 kArrayIndexLengthBits> {}; // NOLINT
8340 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8341 // could use a mask to test if the length of string is less than or equal to
8342 // kMaxCachedArrayIndexLength.
8343 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8345 static const unsigned int kContainsCachedArrayIndexMask =
8346 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8347 << ArrayIndexLengthBits::kShift) |
8348 kIsNotArrayIndexMask;
8350 // Value of empty hash field indicating that the hash is not computed.
8351 static const int kEmptyHashField =
8352 kIsNotArrayIndexMask | kHashNotComputedMask;
8355 static inline bool IsHashFieldComputed(uint32_t field);
8358 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8363 class Symbol: public Name {
8365 // [name]: The print name of a symbol, or undefined if none.
8366 DECL_ACCESSORS(name, Object)
8368 DECL_ACCESSORS(flags, Smi)
8370 // [is_private]: Whether this is a private symbol. Private symbols can only
8371 // be used to designate own properties of objects.
8372 DECL_BOOLEAN_ACCESSORS(is_private)
8374 DECLARE_CAST(Symbol)
8376 // Dispatched behavior.
8377 DECLARE_PRINTER(Symbol)
8378 DECLARE_VERIFIER(Symbol)
8380 // Layout description.
8381 static const int kNameOffset = Name::kSize;
8382 static const int kFlagsOffset = kNameOffset + kPointerSize;
8383 static const int kSize = kFlagsOffset + kPointerSize;
8385 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8387 void SymbolShortPrint(std::ostream& os);
8390 static const int kPrivateBit = 0;
8392 const char* PrivateSymbolToName() const;
8395 friend class Name; // For PrivateSymbolToName.
8398 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8404 // The String abstract class captures JavaScript string values:
8407 // 4.3.16 String Value
8408 // A string value is a member of the type String and is a finite
8409 // ordered sequence of zero or more 16-bit unsigned integer values.
8411 // All string values have a length field.
8412 class String: public Name {
8414 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8416 // Array index strings this short can keep their index in the hash field.
8417 static const int kMaxCachedArrayIndexLength = 7;
8419 // For strings which are array indexes the hash value has the string length
8420 // mixed into the hash, mainly to avoid a hash value of zero which would be
8421 // the case for the string '0'. 24 bits are used for the array index value.
8422 static const int kArrayIndexValueBits = 24;
8423 static const int kArrayIndexLengthBits =
8424 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8426 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8428 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8429 kArrayIndexValueBits> {}; // NOLINT
8430 class ArrayIndexLengthBits : public BitField<unsigned int,
8431 kNofHashBitFields + kArrayIndexValueBits,
8432 kArrayIndexLengthBits> {}; // NOLINT
8434 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8435 // could use a mask to test if the length of string is less than or equal to
8436 // kMaxCachedArrayIndexLength.
8437 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8439 static const unsigned int kContainsCachedArrayIndexMask =
8440 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8441 << ArrayIndexLengthBits::kShift) |
8442 kIsNotArrayIndexMask;
8444 class SubStringRange {
8446 explicit SubStringRange(String* string, int first = 0, int length = -1)
8449 length_(length == -1 ? string->length() : length) {}
8451 inline iterator begin();
8452 inline iterator end();
8460 // Representation of the flat content of a String.
8461 // A non-flat string doesn't have flat content.
8462 // A flat string has content that's encoded as a sequence of either
8463 // one-byte chars or two-byte UC16.
8464 // Returned by String::GetFlatContent().
8467 // Returns true if the string is flat and this structure contains content.
8468 bool IsFlat() { return state_ != NON_FLAT; }
8469 // Returns true if the structure contains one-byte content.
8470 bool IsOneByte() { return state_ == ONE_BYTE; }
8471 // Returns true if the structure contains two-byte content.
8472 bool IsTwoByte() { return state_ == TWO_BYTE; }
8474 // Return the one byte content of the string. Only use if IsOneByte()
8476 Vector<const uint8_t> ToOneByteVector() {
8477 DCHECK_EQ(ONE_BYTE, state_);
8478 return Vector<const uint8_t>(onebyte_start, length_);
8480 // Return the two-byte content of the string. Only use if IsTwoByte()
8482 Vector<const uc16> ToUC16Vector() {
8483 DCHECK_EQ(TWO_BYTE, state_);
8484 return Vector<const uc16>(twobyte_start, length_);
8488 DCHECK(i < length_);
8489 DCHECK(state_ != NON_FLAT);
8490 if (state_ == ONE_BYTE) return onebyte_start[i];
8491 return twobyte_start[i];
8494 bool UsesSameString(const FlatContent& other) const {
8495 return onebyte_start == other.onebyte_start;
8499 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8501 // Constructors only used by String::GetFlatContent().
8502 explicit FlatContent(const uint8_t* start, int length)
8503 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8504 explicit FlatContent(const uc16* start, int length)
8505 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8506 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8509 const uint8_t* onebyte_start;
8510 const uc16* twobyte_start;
8515 friend class String;
8516 friend class IterableSubString;
8519 template <typename Char>
8520 INLINE(Vector<const Char> GetCharVector());
8522 // Get and set the length of the string.
8523 inline int length() const;
8524 inline void set_length(int value);
8526 // Get and set the length of the string using acquire loads and release
8528 inline int synchronized_length() const;
8529 inline void synchronized_set_length(int value);
8531 // Returns whether this string has only one-byte chars, i.e. all of them can
8532 // be one-byte encoded. This might be the case even if the string is
8533 // two-byte. Such strings may appear when the embedder prefers
8534 // two-byte external representations even for one-byte data.
8535 inline bool IsOneByteRepresentation() const;
8536 inline bool IsTwoByteRepresentation() const;
8538 // Cons and slices have an encoding flag that may not represent the actual
8539 // encoding of the underlying string. This is taken into account here.
8540 // Requires: this->IsFlat()
8541 inline bool IsOneByteRepresentationUnderneath();
8542 inline bool IsTwoByteRepresentationUnderneath();
8544 // NOTE: this should be considered only a hint. False negatives are
8546 inline bool HasOnlyOneByteChars();
8548 // Get and set individual two byte chars in the string.
8549 inline void Set(int index, uint16_t value);
8550 // Get individual two byte char in the string. Repeated calls
8551 // to this method are not efficient unless the string is flat.
8552 INLINE(uint16_t Get(int index));
8554 // Flattens the string. Checks first inline to see if it is
8555 // necessary. Does nothing if the string is not a cons string.
8556 // Flattening allocates a sequential string with the same data as
8557 // the given string and mutates the cons string to a degenerate
8558 // form, where the first component is the new sequential string and
8559 // the second component is the empty string. If allocation fails,
8560 // this function returns a failure. If flattening succeeds, this
8561 // function returns the sequential string that is now the first
8562 // component of the cons string.
8564 // Degenerate cons strings are handled specially by the garbage
8565 // collector (see IsShortcutCandidate).
8567 static inline Handle<String> Flatten(Handle<String> string,
8568 PretenureFlag pretenure = NOT_TENURED);
8570 // Tries to return the content of a flat string as a structure holding either
8571 // a flat vector of char or of uc16.
8572 // If the string isn't flat, and therefore doesn't have flat content, the
8573 // returned structure will report so, and can't provide a vector of either
8575 FlatContent GetFlatContent();
8577 // Returns the parent of a sliced string or first part of a flat cons string.
8578 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8579 inline String* GetUnderlying();
8581 // String equality operations.
8582 inline bool Equals(String* other);
8583 inline static bool Equals(Handle<String> one, Handle<String> two);
8584 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8585 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8586 bool IsTwoByteEqualTo(Vector<const uc16> str);
8588 // Return a UTF8 representation of the string. The string is null
8589 // terminated but may optionally contain nulls. Length is returned
8590 // in length_output if length_output is not a null pointer The string
8591 // should be nearly flat, otherwise the performance of this method may
8592 // be very slow (quadratic in the length). Setting robustness_flag to
8593 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8594 // handles unexpected data without causing assert failures and it does not
8595 // do any heap allocations. This is useful when printing stack traces.
8596 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8597 RobustnessFlag robustness_flag,
8598 int offset, int length,
8599 int* length_output = 0);
8600 base::SmartArrayPointer<char> ToCString(
8601 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8602 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8603 int* length_output = 0);
8605 // Return a 16 bit Unicode representation of the string.
8606 // The string should be nearly flat, otherwise the performance of
8607 // of this method may be very bad. Setting robustness_flag to
8608 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8609 // handles unexpected data without causing assert failures and it does not
8610 // do any heap allocations. This is useful when printing stack traces.
8611 base::SmartArrayPointer<uc16> ToWideCString(
8612 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8614 bool ComputeArrayIndex(uint32_t* index);
8617 bool MakeExternal(v8::String::ExternalStringResource* resource);
8618 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8621 inline bool AsArrayIndex(uint32_t* index);
8623 DECLARE_CAST(String)
8625 void PrintOn(FILE* out);
8627 // For use during stack traces. Performs rudimentary sanity check.
8630 // Dispatched behavior.
8631 void StringShortPrint(StringStream* accumulator);
8632 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8633 #if defined(DEBUG) || defined(OBJECT_PRINT)
8634 char* ToAsciiArray();
8636 DECLARE_PRINTER(String)
8637 DECLARE_VERIFIER(String)
8639 inline bool IsFlat();
8641 // Layout description.
8642 static const int kLengthOffset = Name::kSize;
8643 static const int kSize = kLengthOffset + kPointerSize;
8645 // Maximum number of characters to consider when trying to convert a string
8646 // value into an array index.
8647 static const int kMaxArrayIndexSize = 10;
8648 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8651 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8652 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8653 static const int kMaxUtf16CodeUnit = 0xffff;
8654 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8656 // Value of hash field containing computed hash equal to zero.
8657 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8659 // Maximal string length.
8660 static const int kMaxLength = (1 << 28) - 16;
8662 // Max length for computing hash. For strings longer than this limit the
8663 // string length is used as the hash value.
8664 static const int kMaxHashCalcLength = 16383;
8666 // Limit for truncation in short printing.
8667 static const int kMaxShortPrintLength = 1024;
8669 // Support for regular expressions.
8670 const uc16* GetTwoByteData(unsigned start);
8672 // Helper function for flattening strings.
8673 template <typename sinkchar>
8674 static void WriteToFlat(String* source,
8679 // The return value may point to the first aligned word containing the first
8680 // non-one-byte character, rather than directly to the non-one-byte character.
8681 // If the return value is >= the passed length, the entire string was
8683 static inline int NonAsciiStart(const char* chars, int length) {
8684 const char* start = chars;
8685 const char* limit = chars + length;
8687 if (length >= kIntptrSize) {
8688 // Check unaligned bytes.
8689 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8690 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8691 return static_cast<int>(chars - start);
8695 // Check aligned words.
8696 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8697 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8698 while (chars + sizeof(uintptr_t) <= limit) {
8699 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8700 return static_cast<int>(chars - start);
8702 chars += sizeof(uintptr_t);
8705 // Check remaining unaligned bytes.
8706 while (chars < limit) {
8707 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8708 return static_cast<int>(chars - start);
8713 return static_cast<int>(chars - start);
8716 static inline bool IsAscii(const char* chars, int length) {
8717 return NonAsciiStart(chars, length) >= length;
8720 static inline bool IsAscii(const uint8_t* chars, int length) {
8722 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8725 static inline int NonOneByteStart(const uc16* chars, int length) {
8726 const uc16* limit = chars + length;
8727 const uc16* start = chars;
8728 while (chars < limit) {
8729 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8732 return static_cast<int>(chars - start);
8735 static inline bool IsOneByte(const uc16* chars, int length) {
8736 return NonOneByteStart(chars, length) >= length;
8739 template<class Visitor>
8740 static inline ConsString* VisitFlat(Visitor* visitor,
8744 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8745 bool include_ending_line);
8747 // Use the hash field to forward to the canonical internalized string
8748 // when deserializing an internalized string.
8749 inline void SetForwardedInternalizedString(String* string);
8750 inline String* GetForwardedInternalizedString();
8754 friend class StringTableInsertionKey;
8756 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8757 PretenureFlag tenure);
8759 // Slow case of String::Equals. This implementation works on any strings
8760 // but it is most efficient on strings that are almost flat.
8761 bool SlowEquals(String* other);
8763 static bool SlowEquals(Handle<String> one, Handle<String> two);
8765 // Slow case of AsArrayIndex.
8766 bool SlowAsArrayIndex(uint32_t* index);
8768 // Compute and set the hash code.
8769 uint32_t ComputeAndSetHash();
8771 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8775 // The SeqString abstract class captures sequential string values.
8776 class SeqString: public String {
8778 DECLARE_CAST(SeqString)
8780 // Layout description.
8781 static const int kHeaderSize = String::kSize;
8783 // Truncate the string in-place if possible and return the result.
8784 // In case of new_length == 0, the empty string is returned without
8785 // truncating the original string.
8786 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8789 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8793 // The OneByteString class captures sequential one-byte string objects.
8794 // Each character in the OneByteString is an one-byte character.
8795 class SeqOneByteString: public SeqString {
8797 static const bool kHasOneByteEncoding = true;
8799 // Dispatched behavior.
8800 inline uint16_t SeqOneByteStringGet(int index);
8801 inline void SeqOneByteStringSet(int index, uint16_t value);
8803 // Get the address of the characters in this string.
8804 inline Address GetCharsAddress();
8806 inline uint8_t* GetChars();
8808 DECLARE_CAST(SeqOneByteString)
8810 // Garbage collection support. This method is called by the
8811 // garbage collector to compute the actual size of an OneByteString
8813 inline int SeqOneByteStringSize(InstanceType instance_type);
8815 // Computes the size for an OneByteString instance of a given length.
8816 static int SizeFor(int length) {
8817 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8820 // Maximal memory usage for a single sequential one-byte string.
8821 static const int kMaxSize = 512 * MB - 1;
8822 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8825 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8829 // The TwoByteString class captures sequential unicode string objects.
8830 // Each character in the TwoByteString is a two-byte uint16_t.
8831 class SeqTwoByteString: public SeqString {
8833 static const bool kHasOneByteEncoding = false;
8835 // Dispatched behavior.
8836 inline uint16_t SeqTwoByteStringGet(int index);
8837 inline void SeqTwoByteStringSet(int index, uint16_t value);
8839 // Get the address of the characters in this string.
8840 inline Address GetCharsAddress();
8842 inline uc16* GetChars();
8845 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8847 DECLARE_CAST(SeqTwoByteString)
8849 // Garbage collection support. This method is called by the
8850 // garbage collector to compute the actual size of a TwoByteString
8852 inline int SeqTwoByteStringSize(InstanceType instance_type);
8854 // Computes the size for a TwoByteString instance of a given length.
8855 static int SizeFor(int length) {
8856 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8859 // Maximal memory usage for a single sequential two-byte string.
8860 static const int kMaxSize = 512 * MB - 1;
8861 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8862 String::kMaxLength);
8865 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8869 // The ConsString class describes string values built by using the
8870 // addition operator on strings. A ConsString is a pair where the
8871 // first and second components are pointers to other string values.
8872 // One or both components of a ConsString can be pointers to other
8873 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8874 // are non-ConsString string values. The string value represented by
8875 // a ConsString can be obtained by concatenating the leaf string
8876 // values in a left-to-right depth-first traversal of the tree.
8877 class ConsString: public String {
8879 // First string of the cons cell.
8880 inline String* first();
8881 // Doesn't check that the result is a string, even in debug mode. This is
8882 // useful during GC where the mark bits confuse the checks.
8883 inline Object* unchecked_first();
8884 inline void set_first(String* first,
8885 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8887 // Second string of the cons cell.
8888 inline String* second();
8889 // Doesn't check that the result is a string, even in debug mode. This is
8890 // useful during GC where the mark bits confuse the checks.
8891 inline Object* unchecked_second();
8892 inline void set_second(String* second,
8893 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8895 // Dispatched behavior.
8896 uint16_t ConsStringGet(int index);
8898 DECLARE_CAST(ConsString)
8900 // Layout description.
8901 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8902 static const int kSecondOffset = kFirstOffset + kPointerSize;
8903 static const int kSize = kSecondOffset + kPointerSize;
8905 // Minimum length for a cons string.
8906 static const int kMinLength = 13;
8908 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8911 DECLARE_VERIFIER(ConsString)
8914 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8918 // The Sliced String class describes strings that are substrings of another
8919 // sequential string. The motivation is to save time and memory when creating
8920 // a substring. A Sliced String is described as a pointer to the parent,
8921 // the offset from the start of the parent string and the length. Using
8922 // a Sliced String therefore requires unpacking of the parent string and
8923 // adding the offset to the start address. A substring of a Sliced String
8924 // are not nested since the double indirection is simplified when creating
8925 // such a substring.
8926 // Currently missing features are:
8927 // - handling externalized parent strings
8928 // - external strings as parent
8929 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8930 class SlicedString: public String {
8932 inline String* parent();
8933 inline void set_parent(String* parent,
8934 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8935 inline int offset() const;
8936 inline void set_offset(int offset);
8938 // Dispatched behavior.
8939 uint16_t SlicedStringGet(int index);
8941 DECLARE_CAST(SlicedString)
8943 // Layout description.
8944 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8945 static const int kOffsetOffset = kParentOffset + kPointerSize;
8946 static const int kSize = kOffsetOffset + kPointerSize;
8948 // Minimum length for a sliced string.
8949 static const int kMinLength = 13;
8951 typedef FixedBodyDescriptor<kParentOffset,
8952 kOffsetOffset + kPointerSize, kSize>
8955 DECLARE_VERIFIER(SlicedString)
8958 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8962 // The ExternalString class describes string values that are backed by
8963 // a string resource that lies outside the V8 heap. ExternalStrings
8964 // consist of the length field common to all strings, a pointer to the
8965 // external resource. It is important to ensure (externally) that the
8966 // resource is not deallocated while the ExternalString is live in the
8969 // The API expects that all ExternalStrings are created through the
8970 // API. Therefore, ExternalStrings should not be used internally.
8971 class ExternalString: public String {
8973 DECLARE_CAST(ExternalString)
8975 // Layout description.
8976 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8977 static const int kShortSize = kResourceOffset + kPointerSize;
8978 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8979 static const int kSize = kResourceDataOffset + kPointerSize;
8981 static const int kMaxShortLength =
8982 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8984 // Return whether external string is short (data pointer is not cached).
8985 inline bool is_short();
8987 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8990 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8994 // The ExternalOneByteString class is an external string backed by an
8996 class ExternalOneByteString : public ExternalString {
8998 static const bool kHasOneByteEncoding = true;
9000 typedef v8::String::ExternalOneByteStringResource Resource;
9002 // The underlying resource.
9003 inline const Resource* resource();
9004 inline void set_resource(const Resource* buffer);
9006 // Update the pointer cache to the external character array.
9007 // The cached pointer is always valid, as the external character array does =
9008 // not move during lifetime. Deserialization is the only exception, after
9009 // which the pointer cache has to be refreshed.
9010 inline void update_data_cache();
9012 inline const uint8_t* GetChars();
9014 // Dispatched behavior.
9015 inline uint16_t ExternalOneByteStringGet(int index);
9017 DECLARE_CAST(ExternalOneByteString)
9019 // Garbage collection support.
9020 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9022 template <typename StaticVisitor>
9023 inline void ExternalOneByteStringIterateBody();
9026 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9030 // The ExternalTwoByteString class is an external string backed by a UTF-16
9032 class ExternalTwoByteString: public ExternalString {
9034 static const bool kHasOneByteEncoding = false;
9036 typedef v8::String::ExternalStringResource Resource;
9038 // The underlying string resource.
9039 inline const Resource* resource();
9040 inline void set_resource(const Resource* buffer);
9042 // Update the pointer cache to the external character array.
9043 // The cached pointer is always valid, as the external character array does =
9044 // not move during lifetime. Deserialization is the only exception, after
9045 // which the pointer cache has to be refreshed.
9046 inline void update_data_cache();
9048 inline const uint16_t* GetChars();
9050 // Dispatched behavior.
9051 inline uint16_t ExternalTwoByteStringGet(int index);
9054 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9056 DECLARE_CAST(ExternalTwoByteString)
9058 // Garbage collection support.
9059 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9061 template<typename StaticVisitor>
9062 inline void ExternalTwoByteStringIterateBody();
9065 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9069 // Utility superclass for stack-allocated objects that must be updated
9070 // on gc. It provides two ways for the gc to update instances, either
9071 // iterating or updating after gc.
9072 class Relocatable BASE_EMBEDDED {
9074 explicit inline Relocatable(Isolate* isolate);
9075 inline virtual ~Relocatable();
9076 virtual void IterateInstance(ObjectVisitor* v) { }
9077 virtual void PostGarbageCollection() { }
9079 static void PostGarbageCollectionProcessing(Isolate* isolate);
9080 static int ArchiveSpacePerThread();
9081 static char* ArchiveState(Isolate* isolate, char* to);
9082 static char* RestoreState(Isolate* isolate, char* from);
9083 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9084 static void Iterate(ObjectVisitor* v, Relocatable* top);
9085 static char* Iterate(ObjectVisitor* v, char* t);
9093 // A flat string reader provides random access to the contents of a
9094 // string independent of the character width of the string. The handle
9095 // must be valid as long as the reader is being used.
9096 class FlatStringReader : public Relocatable {
9098 FlatStringReader(Isolate* isolate, Handle<String> str);
9099 FlatStringReader(Isolate* isolate, Vector<const char> input);
9100 void PostGarbageCollection();
9101 inline uc32 Get(int index);
9102 template <typename Char>
9103 inline Char Get(int index);
9104 int length() { return length_; }
9113 // This maintains an off-stack representation of the stack frames required
9114 // to traverse a ConsString, allowing an entirely iterative and restartable
9115 // traversal of the entire string
9116 class ConsStringIterator {
9118 inline ConsStringIterator() {}
9119 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9120 Reset(cons_string, offset);
9122 inline void Reset(ConsString* cons_string, int offset = 0) {
9124 // Next will always return NULL.
9125 if (cons_string == NULL) return;
9126 Initialize(cons_string, offset);
9128 // Returns NULL when complete.
9129 inline String* Next(int* offset_out) {
9131 if (depth_ == 0) return NULL;
9132 return Continue(offset_out);
9136 static const int kStackSize = 32;
9137 // Use a mask instead of doing modulo operations for stack wrapping.
9138 static const int kDepthMask = kStackSize-1;
9139 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9140 static inline int OffsetForDepth(int depth);
9142 inline void PushLeft(ConsString* string);
9143 inline void PushRight(ConsString* string);
9144 inline void AdjustMaximumDepth();
9146 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9147 void Initialize(ConsString* cons_string, int offset);
9148 String* Continue(int* offset_out);
9149 String* NextLeaf(bool* blew_stack);
9150 String* Search(int* offset_out);
9152 // Stack must always contain only frames for which right traversal
9153 // has not yet been performed.
9154 ConsString* frames_[kStackSize];
9159 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9163 class StringCharacterStream {
9165 inline StringCharacterStream(String* string,
9167 inline uint16_t GetNext();
9168 inline bool HasMore();
9169 inline void Reset(String* string, int offset = 0);
9170 inline void VisitOneByteString(const uint8_t* chars, int length);
9171 inline void VisitTwoByteString(const uint16_t* chars, int length);
9174 ConsStringIterator iter_;
9177 const uint8_t* buffer8_;
9178 const uint16_t* buffer16_;
9180 const uint8_t* end_;
9181 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9185 template <typename T>
9186 class VectorIterator {
9188 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9189 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9190 T GetNext() { return data_[index_++]; }
9191 bool has_more() { return index_ < data_.length(); }
9193 Vector<const T> data_;
9198 // The Oddball describes objects null, undefined, true, and false.
9199 class Oddball: public HeapObject {
9201 // [to_string]: Cached to_string computed at startup.
9202 DECL_ACCESSORS(to_string, String)
9204 // [to_number]: Cached to_number computed at startup.
9205 DECL_ACCESSORS(to_number, Object)
9207 inline byte kind() const;
9208 inline void set_kind(byte kind);
9210 DECLARE_CAST(Oddball)
9212 // Dispatched behavior.
9213 DECLARE_VERIFIER(Oddball)
9215 // Initialize the fields.
9216 static void Initialize(Isolate* isolate,
9217 Handle<Oddball> oddball,
9218 const char* to_string,
9219 Handle<Object> to_number,
9222 // Layout description.
9223 static const int kToStringOffset = HeapObject::kHeaderSize;
9224 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9225 static const int kKindOffset = kToNumberOffset + kPointerSize;
9226 static const int kSize = kKindOffset + kPointerSize;
9228 static const byte kFalse = 0;
9229 static const byte kTrue = 1;
9230 static const byte kNotBooleanMask = ~1;
9231 static const byte kTheHole = 2;
9232 static const byte kNull = 3;
9233 static const byte kArgumentMarker = 4;
9234 static const byte kUndefined = 5;
9235 static const byte kUninitialized = 6;
9236 static const byte kOther = 7;
9237 static const byte kException = 8;
9239 typedef FixedBodyDescriptor<kToStringOffset,
9240 kToNumberOffset + kPointerSize,
9241 kSize> BodyDescriptor;
9243 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9244 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9245 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9248 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9252 class Cell: public HeapObject {
9254 // [value]: value of the cell.
9255 DECL_ACCESSORS(value, Object)
9259 static inline Cell* FromValueAddress(Address value) {
9260 Object* result = FromAddress(value - kValueOffset);
9261 return static_cast<Cell*>(result);
9264 inline Address ValueAddress() {
9265 return address() + kValueOffset;
9268 // Dispatched behavior.
9269 DECLARE_PRINTER(Cell)
9270 DECLARE_VERIFIER(Cell)
9272 // Layout description.
9273 static const int kValueOffset = HeapObject::kHeaderSize;
9274 static const int kSize = kValueOffset + kPointerSize;
9276 typedef FixedBodyDescriptor<kValueOffset,
9277 kValueOffset + kPointerSize,
9278 kSize> BodyDescriptor;
9281 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9285 class PropertyCell : public HeapObject {
9287 // [property_details]: details of the global property.
9288 DECL_ACCESSORS(property_details_raw, Object)
9289 // [value]: value of the global property.
9290 DECL_ACCESSORS(value, Object)
9291 // [dependent_code]: dependent code that depends on the type of the global
9293 DECL_ACCESSORS(dependent_code, DependentCode)
9295 PropertyDetails property_details() {
9296 return PropertyDetails(Smi::cast(property_details_raw()));
9299 void set_property_details(PropertyDetails details) {
9300 set_property_details_raw(details.AsSmi());
9303 PropertyCellConstantType GetConstantType();
9305 // Computes the new type of the cell's contents for the given value, but
9306 // without actually modifying the details.
9307 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9308 Handle<Object> value,
9309 PropertyDetails details);
9310 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9311 Handle<Object> value, PropertyDetails details);
9313 static Handle<PropertyCell> InvalidateEntry(
9314 Handle<GlobalDictionary> dictionary, int entry);
9316 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9317 Handle<Object> new_value);
9319 DECLARE_CAST(PropertyCell)
9321 // Dispatched behavior.
9322 DECLARE_PRINTER(PropertyCell)
9323 DECLARE_VERIFIER(PropertyCell)
9325 // Layout description.
9326 static const int kDetailsOffset = HeapObject::kHeaderSize;
9327 static const int kValueOffset = kDetailsOffset + kPointerSize;
9328 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9329 static const int kSize = kDependentCodeOffset + kPointerSize;
9331 static const int kPointerFieldsBeginOffset = kValueOffset;
9332 static const int kPointerFieldsEndOffset = kSize;
9334 typedef FixedBodyDescriptor<kValueOffset,
9336 kSize> BodyDescriptor;
9339 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9343 class WeakCell : public HeapObject {
9345 inline Object* value() const;
9347 // This should not be called by anyone except GC.
9348 inline void clear();
9350 // This should not be called by anyone except allocator.
9351 inline void initialize(HeapObject* value);
9353 inline bool cleared() const;
9355 DECL_ACCESSORS(next, Object)
9357 inline void clear_next(Heap* heap);
9359 inline bool next_cleared();
9361 DECLARE_CAST(WeakCell)
9363 DECLARE_PRINTER(WeakCell)
9364 DECLARE_VERIFIER(WeakCell)
9366 // Layout description.
9367 static const int kValueOffset = HeapObject::kHeaderSize;
9368 static const int kNextOffset = kValueOffset + kPointerSize;
9369 static const int kSize = kNextOffset + kPointerSize;
9371 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9374 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9378 // The JSProxy describes EcmaScript Harmony proxies
9379 class JSProxy: public JSReceiver {
9381 // [handler]: The handler property.
9382 DECL_ACCESSORS(handler, Object)
9384 // [hash]: The hash code property (undefined if not initialized yet).
9385 DECL_ACCESSORS(hash, Object)
9387 DECLARE_CAST(JSProxy)
9389 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9390 Handle<JSProxy> proxy,
9391 Handle<Object> receiver,
9394 // If the handler defines an accessor property with a setter, invoke it.
9395 // If it defines an accessor property without a setter, or a data property
9396 // that is read-only, throw. In all these cases set '*done' to true,
9397 // otherwise set it to false.
9399 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9400 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9401 Handle<Object> value, LanguageMode language_mode, bool* done);
9403 MUST_USE_RESULT static Maybe<PropertyAttributes>
9404 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9405 Handle<Object> receiver,
9407 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9408 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9409 Handle<Object> value, LanguageMode language_mode);
9411 // Turn the proxy into an (empty) JSObject.
9412 static void Fix(Handle<JSProxy> proxy);
9414 // Initializes the body after the handler slot.
9415 inline void InitializeBody(int object_size, Object* value);
9417 // Invoke a trap by name. If the trap does not exist on this's handler,
9418 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9419 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9420 Handle<JSProxy> proxy,
9422 Handle<Object> derived_trap,
9424 Handle<Object> args[]);
9426 // Dispatched behavior.
9427 DECLARE_PRINTER(JSProxy)
9428 DECLARE_VERIFIER(JSProxy)
9430 // Layout description. We add padding so that a proxy has the same
9431 // size as a virgin JSObject. This is essential for becoming a JSObject
9433 static const int kHandlerOffset = HeapObject::kHeaderSize;
9434 static const int kHashOffset = kHandlerOffset + kPointerSize;
9435 static const int kPaddingOffset = kHashOffset + kPointerSize;
9436 static const int kSize = JSObject::kHeaderSize;
9437 static const int kHeaderSize = kPaddingOffset;
9438 static const int kPaddingSize = kSize - kPaddingOffset;
9440 STATIC_ASSERT(kPaddingSize >= 0);
9442 typedef FixedBodyDescriptor<kHandlerOffset,
9444 kSize> BodyDescriptor;
9447 friend class JSReceiver;
9449 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9450 Handle<JSProxy> proxy, Handle<Name> name);
9452 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9453 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9455 MUST_USE_RESULT Object* GetIdentityHash();
9457 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9459 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9463 class JSFunctionProxy: public JSProxy {
9465 // [call_trap]: The call trap.
9466 DECL_ACCESSORS(call_trap, Object)
9468 // [construct_trap]: The construct trap.
9469 DECL_ACCESSORS(construct_trap, Object)
9471 DECLARE_CAST(JSFunctionProxy)
9473 // Dispatched behavior.
9474 DECLARE_PRINTER(JSFunctionProxy)
9475 DECLARE_VERIFIER(JSFunctionProxy)
9477 // Layout description.
9478 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9479 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9480 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9481 static const int kSize = JSFunction::kSize;
9482 static const int kPaddingSize = kSize - kPaddingOffset;
9484 STATIC_ASSERT(kPaddingSize >= 0);
9486 typedef FixedBodyDescriptor<kHandlerOffset,
9487 kConstructTrapOffset + kPointerSize,
9488 kSize> BodyDescriptor;
9491 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9495 class JSCollection : public JSObject {
9497 // [table]: the backing hash table
9498 DECL_ACCESSORS(table, Object)
9500 static const int kTableOffset = JSObject::kHeaderSize;
9501 static const int kSize = kTableOffset + kPointerSize;
9504 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9508 // The JSSet describes EcmaScript Harmony sets
9509 class JSSet : public JSCollection {
9513 // Dispatched behavior.
9514 DECLARE_PRINTER(JSSet)
9515 DECLARE_VERIFIER(JSSet)
9518 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9522 // The JSMap describes EcmaScript Harmony maps
9523 class JSMap : public JSCollection {
9527 // Dispatched behavior.
9528 DECLARE_PRINTER(JSMap)
9529 DECLARE_VERIFIER(JSMap)
9532 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9536 // OrderedHashTableIterator is an iterator that iterates over the keys and
9537 // values of an OrderedHashTable.
9539 // The iterator has a reference to the underlying OrderedHashTable data,
9540 // [table], as well as the current [index] the iterator is at.
9542 // When the OrderedHashTable is rehashed it adds a reference from the old table
9543 // to the new table as well as storing enough data about the changes so that the
9544 // iterator [index] can be adjusted accordingly.
9546 // When the [Next] result from the iterator is requested, the iterator checks if
9547 // there is a newer table that it needs to transition to.
9548 template<class Derived, class TableType>
9549 class OrderedHashTableIterator: public JSObject {
9551 // [table]: the backing hash table mapping keys to values.
9552 DECL_ACCESSORS(table, Object)
9554 // [index]: The index into the data table.
9555 DECL_ACCESSORS(index, Object)
9557 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9558 DECL_ACCESSORS(kind, Object)
9561 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9564 static const int kTableOffset = JSObject::kHeaderSize;
9565 static const int kIndexOffset = kTableOffset + kPointerSize;
9566 static const int kKindOffset = kIndexOffset + kPointerSize;
9567 static const int kSize = kKindOffset + kPointerSize;
9575 // Whether the iterator has more elements. This needs to be called before
9576 // calling |CurrentKey| and/or |CurrentValue|.
9579 // Move the index forward one.
9581 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9584 // Populates the array with the next key and value and then moves the iterator
9586 // This returns the |kind| or 0 if the iterator is already at the end.
9587 Smi* Next(JSArray* value_array);
9589 // Returns the current key of the iterator. This should only be called when
9590 // |HasMore| returns true.
9591 inline Object* CurrentKey();
9594 // Transitions the iterator to the non obsolete backing store. This is a NOP
9595 // if the [table] is not obsolete.
9598 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9602 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9605 // Dispatched behavior.
9606 DECLARE_PRINTER(JSSetIterator)
9607 DECLARE_VERIFIER(JSSetIterator)
9609 DECLARE_CAST(JSSetIterator)
9611 // Called by |Next| to populate the array. This allows the subclasses to
9612 // populate the array differently.
9613 inline void PopulateValueArray(FixedArray* array);
9616 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9620 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9623 // Dispatched behavior.
9624 DECLARE_PRINTER(JSMapIterator)
9625 DECLARE_VERIFIER(JSMapIterator)
9627 DECLARE_CAST(JSMapIterator)
9629 // Called by |Next| to populate the array. This allows the subclasses to
9630 // populate the array differently.
9631 inline void PopulateValueArray(FixedArray* array);
9634 // Returns the current value of the iterator. This should only be called when
9635 // |HasMore| returns true.
9636 inline Object* CurrentValue();
9638 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9642 // Base class for both JSWeakMap and JSWeakSet
9643 class JSWeakCollection: public JSObject {
9645 // [table]: the backing hash table mapping keys to values.
9646 DECL_ACCESSORS(table, Object)
9648 // [next]: linked list of encountered weak maps during GC.
9649 DECL_ACCESSORS(next, Object)
9651 static const int kTableOffset = JSObject::kHeaderSize;
9652 static const int kNextOffset = kTableOffset + kPointerSize;
9653 static const int kSize = kNextOffset + kPointerSize;
9656 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9660 // The JSWeakMap describes EcmaScript Harmony weak maps
9661 class JSWeakMap: public JSWeakCollection {
9663 DECLARE_CAST(JSWeakMap)
9665 // Dispatched behavior.
9666 DECLARE_PRINTER(JSWeakMap)
9667 DECLARE_VERIFIER(JSWeakMap)
9670 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9674 // The JSWeakSet describes EcmaScript Harmony weak sets
9675 class JSWeakSet: public JSWeakCollection {
9677 DECLARE_CAST(JSWeakSet)
9679 // Dispatched behavior.
9680 DECLARE_PRINTER(JSWeakSet)
9681 DECLARE_VERIFIER(JSWeakSet)
9684 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9688 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9689 enum class SharedFlag { kNotShared, kShared };
9692 class JSArrayBuffer: public JSObject {
9694 // [backing_store]: backing memory for this array
9695 DECL_ACCESSORS(backing_store, void)
9697 // [byte_length]: length in bytes
9698 DECL_ACCESSORS(byte_length, Object)
9700 inline uint32_t bit_field() const;
9701 inline void set_bit_field(uint32_t bits);
9703 inline bool is_external();
9704 inline void set_is_external(bool value);
9706 inline bool is_neuterable();
9707 inline void set_is_neuterable(bool value);
9709 inline bool was_neutered();
9710 inline void set_was_neutered(bool value);
9712 inline bool is_shared();
9713 inline void set_is_shared(bool value);
9715 DECLARE_CAST(JSArrayBuffer)
9719 // Dispatched behavior.
9720 DECLARE_PRINTER(JSArrayBuffer)
9721 DECLARE_VERIFIER(JSArrayBuffer)
9723 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9724 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9725 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9726 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9727 static const int kBitFieldOffset = kBitFieldSlot;
9729 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9731 static const int kSize = kBitFieldSlot + kPointerSize;
9733 static const int kSizeWithInternalFields =
9734 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9736 class IsExternal : public BitField<bool, 1, 1> {};
9737 class IsNeuterable : public BitField<bool, 2, 1> {};
9738 class WasNeutered : public BitField<bool, 3, 1> {};
9739 class IsShared : public BitField<bool, 4, 1> {};
9742 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9746 class JSArrayBufferView: public JSObject {
9748 // [buffer]: ArrayBuffer that this typed array views.
9749 DECL_ACCESSORS(buffer, Object)
9751 // [byte_offset]: offset of typed array in bytes.
9752 DECL_ACCESSORS(byte_offset, Object)
9754 // [byte_length]: length of typed array in bytes.
9755 DECL_ACCESSORS(byte_length, Object)
9757 DECLARE_CAST(JSArrayBufferView)
9759 DECLARE_VERIFIER(JSArrayBufferView)
9761 inline bool WasNeutered() const;
9763 static const int kBufferOffset = JSObject::kHeaderSize;
9764 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9765 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9766 static const int kViewSize = kByteLengthOffset + kPointerSize;
9770 DECL_ACCESSORS(raw_byte_offset, Object)
9771 DECL_ACCESSORS(raw_byte_length, Object)
9774 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9778 class JSTypedArray: public JSArrayBufferView {
9780 // [length]: length of typed array in elements.
9781 DECL_ACCESSORS(length, Object)
9782 inline uint32_t length_value() const;
9784 DECLARE_CAST(JSTypedArray)
9786 ExternalArrayType type();
9787 size_t element_size();
9789 Handle<JSArrayBuffer> GetBuffer();
9791 // Dispatched behavior.
9792 DECLARE_PRINTER(JSTypedArray)
9793 DECLARE_VERIFIER(JSTypedArray)
9795 static const int kLengthOffset = kViewSize + kPointerSize;
9796 static const int kSize = kLengthOffset + kPointerSize;
9798 static const int kSizeWithInternalFields =
9799 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9802 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9803 Handle<JSTypedArray> typed_array);
9805 DECL_ACCESSORS(raw_length, Object)
9808 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9812 class JSDataView: public JSArrayBufferView {
9814 DECLARE_CAST(JSDataView)
9816 // Dispatched behavior.
9817 DECLARE_PRINTER(JSDataView)
9818 DECLARE_VERIFIER(JSDataView)
9820 static const int kSize = kViewSize;
9822 static const int kSizeWithInternalFields =
9823 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9826 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9830 // Foreign describes objects pointing from JavaScript to C structures.
9831 class Foreign: public HeapObject {
9833 // [address]: field containing the address.
9834 inline Address foreign_address();
9835 inline void set_foreign_address(Address value);
9837 DECLARE_CAST(Foreign)
9839 // Dispatched behavior.
9840 inline void ForeignIterateBody(ObjectVisitor* v);
9842 template<typename StaticVisitor>
9843 inline void ForeignIterateBody();
9845 // Dispatched behavior.
9846 DECLARE_PRINTER(Foreign)
9847 DECLARE_VERIFIER(Foreign)
9849 // Layout description.
9851 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9852 static const int kSize = kForeignAddressOffset + kPointerSize;
9854 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9857 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9861 // The JSArray describes JavaScript Arrays
9862 // Such an array can be in one of two modes:
9863 // - fast, backing storage is a FixedArray and length <= elements.length();
9864 // Please note: push and pop can be used to grow and shrink the array.
9865 // - slow, backing storage is a HashTable with numbers as keys.
9866 class JSArray: public JSObject {
9868 // [length]: The length property.
9869 DECL_ACCESSORS(length, Object)
9871 // Overload the length setter to skip write barrier when the length
9872 // is set to a smi. This matches the set function on FixedArray.
9873 inline void set_length(Smi* length);
9875 static bool HasReadOnlyLength(Handle<JSArray> array);
9876 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9877 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9879 // Initialize the array with the given capacity. The function may
9880 // fail due to out-of-memory situations, but only if the requested
9881 // capacity is non-zero.
9882 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9884 // If the JSArray has fast elements, and new_length would result in
9885 // normalization, returns true.
9886 bool SetLengthWouldNormalize(uint32_t new_length);
9887 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9889 // Initializes the array to a certain length.
9890 inline bool AllowsSetLength();
9892 static void SetLength(Handle<JSArray> array, uint32_t length);
9893 // Same as above but will also queue splice records if |array| is observed.
9894 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9897 // Set the content of the array to the content of storage.
9898 static inline void SetContent(Handle<JSArray> array,
9899 Handle<FixedArrayBase> storage);
9901 DECLARE_CAST(JSArray)
9903 // Dispatched behavior.
9904 DECLARE_PRINTER(JSArray)
9905 DECLARE_VERIFIER(JSArray)
9907 // Number of element slots to pre-allocate for an empty array.
9908 static const int kPreallocatedArrayElements = 4;
9910 // Layout description.
9911 static const int kLengthOffset = JSObject::kHeaderSize;
9912 static const int kSize = kLengthOffset + kPointerSize;
9915 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9919 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9920 Handle<Map> initial_map);
9923 // JSRegExpResult is just a JSArray with a specific initial map.
9924 // This initial map adds in-object properties for "index" and "input"
9925 // properties, as assigned by RegExp.prototype.exec, which allows
9926 // faster creation of RegExp exec results.
9927 // This class just holds constants used when creating the result.
9928 // After creation the result must be treated as a JSArray in all regards.
9929 class JSRegExpResult: public JSArray {
9931 // Offsets of object fields.
9932 static const int kIndexOffset = JSArray::kSize;
9933 static const int kInputOffset = kIndexOffset + kPointerSize;
9934 static const int kSize = kInputOffset + kPointerSize;
9935 // Indices of in-object properties.
9936 static const int kIndexIndex = 0;
9937 static const int kInputIndex = 1;
9939 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9943 class AccessorInfo: public Struct {
9945 DECL_ACCESSORS(name, Object)
9946 DECL_ACCESSORS(flag, Smi)
9947 DECL_ACCESSORS(expected_receiver_type, Object)
9949 inline bool all_can_read();
9950 inline void set_all_can_read(bool value);
9952 inline bool all_can_write();
9953 inline void set_all_can_write(bool value);
9955 inline bool is_special_data_property();
9956 inline void set_is_special_data_property(bool value);
9958 inline PropertyAttributes property_attributes();
9959 inline void set_property_attributes(PropertyAttributes attributes);
9961 // Checks whether the given receiver is compatible with this accessor.
9962 static bool IsCompatibleReceiverMap(Isolate* isolate,
9963 Handle<AccessorInfo> info,
9965 inline bool IsCompatibleReceiver(Object* receiver);
9967 DECLARE_CAST(AccessorInfo)
9969 // Dispatched behavior.
9970 DECLARE_VERIFIER(AccessorInfo)
9972 // Append all descriptors to the array that are not already there.
9973 // Return number added.
9974 static int AppendUnique(Handle<Object> descriptors,
9975 Handle<FixedArray> array,
9976 int valid_descriptors);
9978 static const int kNameOffset = HeapObject::kHeaderSize;
9979 static const int kFlagOffset = kNameOffset + kPointerSize;
9980 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9981 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9984 inline bool HasExpectedReceiverType() {
9985 return expected_receiver_type()->IsFunctionTemplateInfo();
9987 // Bit positions in flag.
9988 static const int kAllCanReadBit = 0;
9989 static const int kAllCanWriteBit = 1;
9990 static const int kSpecialDataProperty = 2;
9991 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9993 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9997 // An accessor must have a getter, but can have no setter.
9999 // When setting a property, V8 searches accessors in prototypes.
10000 // If an accessor was found and it does not have a setter,
10001 // the request is ignored.
10003 // If the accessor in the prototype has the READ_ONLY property attribute, then
10004 // a new value is added to the derived object when the property is set.
10005 // This shadows the accessor in the prototype.
10006 class ExecutableAccessorInfo: public AccessorInfo {
10008 DECL_ACCESSORS(getter, Object)
10009 DECL_ACCESSORS(setter, Object)
10010 DECL_ACCESSORS(data, Object)
10012 DECLARE_CAST(ExecutableAccessorInfo)
10014 // Dispatched behavior.
10015 DECLARE_PRINTER(ExecutableAccessorInfo)
10016 DECLARE_VERIFIER(ExecutableAccessorInfo)
10018 static const int kGetterOffset = AccessorInfo::kSize;
10019 static const int kSetterOffset = kGetterOffset + kPointerSize;
10020 static const int kDataOffset = kSetterOffset + kPointerSize;
10021 static const int kSize = kDataOffset + kPointerSize;
10023 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10026 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10030 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10031 // accessor can either be
10032 // * a pointer to a JavaScript function or proxy: a real accessor
10033 // * undefined: considered an accessor by the spec, too, strangely enough
10034 // * the hole: an accessor which has not been set
10035 // * a pointer to a map: a transition used to ensure map sharing
10036 class AccessorPair: public Struct {
10038 DECL_ACCESSORS(getter, Object)
10039 DECL_ACCESSORS(setter, Object)
10041 DECLARE_CAST(AccessorPair)
10043 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10045 Object* get(AccessorComponent component) {
10046 return component == ACCESSOR_GETTER ? getter() : setter();
10049 void set(AccessorComponent component, Object* value) {
10050 if (component == ACCESSOR_GETTER) {
10057 // Note: Returns undefined instead in case of a hole.
10058 Object* GetComponent(AccessorComponent component);
10060 // Set both components, skipping arguments which are a JavaScript null.
10061 void SetComponents(Object* getter, Object* setter) {
10062 if (!getter->IsNull()) set_getter(getter);
10063 if (!setter->IsNull()) set_setter(setter);
10066 bool Equals(AccessorPair* pair) {
10067 return (this == pair) || pair->Equals(getter(), setter());
10070 bool Equals(Object* getter_value, Object* setter_value) {
10071 return (getter() == getter_value) && (setter() == setter_value);
10074 bool ContainsAccessor() {
10075 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10078 // Dispatched behavior.
10079 DECLARE_PRINTER(AccessorPair)
10080 DECLARE_VERIFIER(AccessorPair)
10082 static const int kGetterOffset = HeapObject::kHeaderSize;
10083 static const int kSetterOffset = kGetterOffset + kPointerSize;
10084 static const int kSize = kSetterOffset + kPointerSize;
10087 // Strangely enough, in addition to functions and harmony proxies, the spec
10088 // requires us to consider undefined as a kind of accessor, too:
10090 // Object.defineProperty(obj, "foo", {get: undefined});
10091 // assertTrue("foo" in obj);
10092 bool IsJSAccessor(Object* obj) {
10093 return obj->IsSpecFunction() || obj->IsUndefined();
10096 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10100 class AccessCheckInfo: public Struct {
10102 DECL_ACCESSORS(named_callback, Object)
10103 DECL_ACCESSORS(indexed_callback, Object)
10104 DECL_ACCESSORS(data, Object)
10106 DECLARE_CAST(AccessCheckInfo)
10108 // Dispatched behavior.
10109 DECLARE_PRINTER(AccessCheckInfo)
10110 DECLARE_VERIFIER(AccessCheckInfo)
10112 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10113 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10114 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10115 static const int kSize = kDataOffset + kPointerSize;
10118 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10122 class InterceptorInfo: public Struct {
10124 DECL_ACCESSORS(getter, Object)
10125 DECL_ACCESSORS(setter, Object)
10126 DECL_ACCESSORS(query, Object)
10127 DECL_ACCESSORS(deleter, Object)
10128 DECL_ACCESSORS(enumerator, Object)
10129 DECL_ACCESSORS(data, Object)
10130 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10131 DECL_BOOLEAN_ACCESSORS(all_can_read)
10132 DECL_BOOLEAN_ACCESSORS(non_masking)
10134 inline int flags() const;
10135 inline void set_flags(int flags);
10137 DECLARE_CAST(InterceptorInfo)
10139 // Dispatched behavior.
10140 DECLARE_PRINTER(InterceptorInfo)
10141 DECLARE_VERIFIER(InterceptorInfo)
10143 static const int kGetterOffset = HeapObject::kHeaderSize;
10144 static const int kSetterOffset = kGetterOffset + kPointerSize;
10145 static const int kQueryOffset = kSetterOffset + kPointerSize;
10146 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10147 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10148 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10149 static const int kFlagsOffset = kDataOffset + kPointerSize;
10150 static const int kSize = kFlagsOffset + kPointerSize;
10152 static const int kCanInterceptSymbolsBit = 0;
10153 static const int kAllCanReadBit = 1;
10154 static const int kNonMasking = 2;
10157 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10161 class CallHandlerInfo: public Struct {
10163 DECL_ACCESSORS(callback, Object)
10164 DECL_ACCESSORS(data, Object)
10166 DECLARE_CAST(CallHandlerInfo)
10168 // Dispatched behavior.
10169 DECLARE_PRINTER(CallHandlerInfo)
10170 DECLARE_VERIFIER(CallHandlerInfo)
10172 static const int kCallbackOffset = HeapObject::kHeaderSize;
10173 static const int kDataOffset = kCallbackOffset + kPointerSize;
10174 static const int kSize = kDataOffset + kPointerSize;
10177 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10181 class TemplateInfo: public Struct {
10183 DECL_ACCESSORS(tag, Object)
10184 inline int number_of_properties() const;
10185 inline void set_number_of_properties(int value);
10186 DECL_ACCESSORS(property_list, Object)
10187 DECL_ACCESSORS(property_accessors, Object)
10189 DECLARE_VERIFIER(TemplateInfo)
10191 static const int kTagOffset = HeapObject::kHeaderSize;
10192 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10193 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10194 static const int kPropertyAccessorsOffset =
10195 kPropertyListOffset + kPointerSize;
10196 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10199 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10203 class FunctionTemplateInfo: public TemplateInfo {
10205 DECL_ACCESSORS(serial_number, Object)
10206 DECL_ACCESSORS(call_code, Object)
10207 DECL_ACCESSORS(prototype_template, Object)
10208 DECL_ACCESSORS(parent_template, Object)
10209 DECL_ACCESSORS(named_property_handler, Object)
10210 DECL_ACCESSORS(indexed_property_handler, Object)
10211 DECL_ACCESSORS(instance_template, Object)
10212 DECL_ACCESSORS(class_name, Object)
10213 DECL_ACCESSORS(signature, Object)
10214 DECL_ACCESSORS(instance_call_handler, Object)
10215 DECL_ACCESSORS(access_check_info, Object)
10216 DECL_ACCESSORS(flag, Smi)
10218 inline int length() const;
10219 inline void set_length(int value);
10221 // Following properties use flag bits.
10222 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10223 DECL_BOOLEAN_ACCESSORS(undetectable)
10224 // If the bit is set, object instances created by this function
10225 // requires access check.
10226 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10227 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10228 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10229 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10230 DECL_BOOLEAN_ACCESSORS(instantiated)
10231 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10233 DECLARE_CAST(FunctionTemplateInfo)
10235 // Dispatched behavior.
10236 DECLARE_PRINTER(FunctionTemplateInfo)
10237 DECLARE_VERIFIER(FunctionTemplateInfo)
10239 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10240 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10241 static const int kPrototypeTemplateOffset =
10242 kCallCodeOffset + kPointerSize;
10243 static const int kParentTemplateOffset =
10244 kPrototypeTemplateOffset + kPointerSize;
10245 static const int kNamedPropertyHandlerOffset =
10246 kParentTemplateOffset + kPointerSize;
10247 static const int kIndexedPropertyHandlerOffset =
10248 kNamedPropertyHandlerOffset + kPointerSize;
10249 static const int kInstanceTemplateOffset =
10250 kIndexedPropertyHandlerOffset + kPointerSize;
10251 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10252 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10253 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10254 static const int kAccessCheckInfoOffset =
10255 kInstanceCallHandlerOffset + kPointerSize;
10256 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10257 static const int kLengthOffset = kFlagOffset + kPointerSize;
10258 static const int kSize = kLengthOffset + kPointerSize;
10260 // Returns true if |object| is an instance of this function template.
10261 bool IsTemplateFor(Object* object);
10262 bool IsTemplateFor(Map* map);
10264 // Returns the holder JSObject if the function can legally be called with this
10265 // receiver. Returns Heap::null_value() if the call is illegal.
10266 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10269 // Bit position in the flag, from least significant bit position.
10270 static const int kHiddenPrototypeBit = 0;
10271 static const int kUndetectableBit = 1;
10272 static const int kNeedsAccessCheckBit = 2;
10273 static const int kReadOnlyPrototypeBit = 3;
10274 static const int kRemovePrototypeBit = 4;
10275 static const int kDoNotCacheBit = 5;
10276 static const int kInstantiatedBit = 6;
10277 static const int kAcceptAnyReceiver = 7;
10279 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10283 class ObjectTemplateInfo: public TemplateInfo {
10285 DECL_ACCESSORS(constructor, Object)
10286 DECL_ACCESSORS(internal_field_count, Object)
10288 DECLARE_CAST(ObjectTemplateInfo)
10290 // Dispatched behavior.
10291 DECLARE_PRINTER(ObjectTemplateInfo)
10292 DECLARE_VERIFIER(ObjectTemplateInfo)
10294 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10295 static const int kInternalFieldCountOffset =
10296 kConstructorOffset + kPointerSize;
10297 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10301 class TypeSwitchInfo: public Struct {
10303 DECL_ACCESSORS(types, Object)
10305 DECLARE_CAST(TypeSwitchInfo)
10307 // Dispatched behavior.
10308 DECLARE_PRINTER(TypeSwitchInfo)
10309 DECLARE_VERIFIER(TypeSwitchInfo)
10311 static const int kTypesOffset = Struct::kHeaderSize;
10312 static const int kSize = kTypesOffset + kPointerSize;
10316 // The DebugInfo class holds additional information for a function being
10318 class DebugInfo: public Struct {
10320 // The shared function info for the source being debugged.
10321 DECL_ACCESSORS(shared, SharedFunctionInfo)
10322 // Code object for the patched code. This code object is the code object
10323 // currently active for the function.
10324 DECL_ACCESSORS(code, Code)
10325 // Fixed array holding status information for each active break point.
10326 DECL_ACCESSORS(break_points, FixedArray)
10328 // Check if there is a break point at a code position.
10329 bool HasBreakPoint(int code_position);
10330 // Get the break point info object for a code position.
10331 Object* GetBreakPointInfo(int code_position);
10332 // Clear a break point.
10333 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10335 Handle<Object> break_point_object);
10336 // Set a break point.
10337 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10338 int source_position, int statement_position,
10339 Handle<Object> break_point_object);
10340 // Get the break point objects for a code position.
10341 Handle<Object> GetBreakPointObjects(int code_position);
10342 // Find the break point info holding this break point object.
10343 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10344 Handle<Object> break_point_object);
10345 // Get the number of break points for this function.
10346 int GetBreakPointCount();
10348 DECLARE_CAST(DebugInfo)
10350 // Dispatched behavior.
10351 DECLARE_PRINTER(DebugInfo)
10352 DECLARE_VERIFIER(DebugInfo)
10354 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10355 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10356 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10357 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10359 static const int kEstimatedNofBreakPointsInFunction = 16;
10362 static const int kNoBreakPointInfo = -1;
10364 // Lookup the index in the break_points array for a code position.
10365 int GetBreakPointInfoIndex(int code_position);
10367 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10371 // The BreakPointInfo class holds information for break points set in a
10372 // function. The DebugInfo object holds a BreakPointInfo object for each code
10373 // position with one or more break points.
10374 class BreakPointInfo: public Struct {
10376 // The position in the code for the break point.
10377 DECL_ACCESSORS(code_position, Smi)
10378 // The position in the source for the break position.
10379 DECL_ACCESSORS(source_position, Smi)
10380 // The position in the source for the last statement before this break
10382 DECL_ACCESSORS(statement_position, Smi)
10383 // List of related JavaScript break points.
10384 DECL_ACCESSORS(break_point_objects, Object)
10386 // Removes a break point.
10387 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10388 Handle<Object> break_point_object);
10389 // Set a break point.
10390 static void SetBreakPoint(Handle<BreakPointInfo> info,
10391 Handle<Object> break_point_object);
10392 // Check if break point info has this break point object.
10393 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10394 Handle<Object> break_point_object);
10395 // Get the number of break points for this code position.
10396 int GetBreakPointCount();
10398 DECLARE_CAST(BreakPointInfo)
10400 // Dispatched behavior.
10401 DECLARE_PRINTER(BreakPointInfo)
10402 DECLARE_VERIFIER(BreakPointInfo)
10404 static const int kCodePositionIndex = Struct::kHeaderSize;
10405 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10406 static const int kStatementPositionIndex =
10407 kSourcePositionIndex + kPointerSize;
10408 static const int kBreakPointObjectsIndex =
10409 kStatementPositionIndex + kPointerSize;
10410 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10413 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10417 #undef DECL_BOOLEAN_ACCESSORS
10418 #undef DECL_ACCESSORS
10419 #undef DECLARE_CAST
10420 #undef DECLARE_VERIFIER
10422 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10423 V(kStringTable, "string_table", "(Internalized strings)") \
10424 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10425 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10426 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10427 V(kInternalizedString, "internalized_string", "(Internal string)") \
10428 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10429 V(kTop, "top", "(Isolate)") \
10430 V(kRelocatable, "relocatable", "(Relocatable)") \
10431 V(kDebug, "debug", "(Debugger)") \
10432 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10433 V(kHandleScope, "handlescope", "(Handle scope)") \
10434 V(kBuiltins, "builtins", "(Builtins)") \
10435 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10436 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10437 V(kThreadManager, "threadmanager", "(Thread manager)") \
10438 V(kStrongRoots, "strong roots", "(Strong roots)") \
10439 V(kExtensions, "Extensions", "(Extensions)")
10441 class VisitorSynchronization : public AllStatic {
10443 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10445 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10448 #undef DECLARE_ENUM
10450 static const char* const kTags[kNumberOfSyncTags];
10451 static const char* const kTagNames[kNumberOfSyncTags];
10454 // Abstract base class for visiting, and optionally modifying, the
10455 // pointers contained in Objects. Used in GC and serialization/deserialization.
10456 class ObjectVisitor BASE_EMBEDDED {
10458 virtual ~ObjectVisitor() {}
10460 // Visits a contiguous arrays of pointers in the half-open range
10461 // [start, end). Any or all of the values may be modified on return.
10462 virtual void VisitPointers(Object** start, Object** end) = 0;
10464 // Handy shorthand for visiting a single pointer.
10465 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10467 // Visit weak next_code_link in Code object.
10468 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10470 // To allow lazy clearing of inline caches the visitor has
10471 // a rich interface for iterating over Code objects..
10473 // Visits a code target in the instruction stream.
10474 virtual void VisitCodeTarget(RelocInfo* rinfo);
10476 // Visits a code entry in a JS function.
10477 virtual void VisitCodeEntry(Address entry_address);
10479 // Visits a global property cell reference in the instruction stream.
10480 virtual void VisitCell(RelocInfo* rinfo);
10482 // Visits a runtime entry in the instruction stream.
10483 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10485 // Visits the resource of an one-byte or two-byte string.
10486 virtual void VisitExternalOneByteString(
10487 v8::String::ExternalOneByteStringResource** resource) {}
10488 virtual void VisitExternalTwoByteString(
10489 v8::String::ExternalStringResource** resource) {}
10491 // Visits a debug call target in the instruction stream.
10492 virtual void VisitDebugTarget(RelocInfo* rinfo);
10494 // Visits the byte sequence in a function's prologue that contains information
10495 // about the code's age.
10496 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10498 // Visit pointer embedded into a code object.
10499 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10501 // Visits an external reference embedded into a code object.
10502 virtual void VisitExternalReference(RelocInfo* rinfo);
10504 // Visits an external reference.
10505 virtual void VisitExternalReference(Address* p) {}
10507 // Visits an (encoded) internal reference.
10508 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10510 // Visits a handle that has an embedder-assigned class ID.
10511 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10513 // Intended for serialization/deserialization checking: insert, or
10514 // check for the presence of, a tag at this position in the stream.
10515 // Also used for marking up GC roots in heap snapshots.
10516 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10520 class StructBodyDescriptor : public
10521 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10523 static inline int SizeOf(Map* map, HeapObject* object) {
10524 return map->instance_size();
10529 // BooleanBit is a helper class for setting and getting a bit in an
10531 class BooleanBit : public AllStatic {
10533 static inline bool get(Smi* smi, int bit_position) {
10534 return get(smi->value(), bit_position);
10537 static inline bool get(int value, int bit_position) {
10538 return (value & (1 << bit_position)) != 0;
10541 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10542 return Smi::FromInt(set(smi->value(), bit_position, v));
10545 static inline int set(int value, int bit_position, bool v) {
10547 value |= (1 << bit_position);
10549 value &= ~(1 << bit_position);
10555 } } // namespace v8::internal
10557 #endif // V8_OBJECTS_H_