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 = kTwoByteStringTag | kSeqStringTag |
616 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
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 // Other primitives (cannot contain non-map-word pointers to heap objects).
666 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
668 // Objects allocated in their own spaces (never in new space).
672 // "Data", objects that cannot contain non-map-word pointers to heap
674 MUTABLE_HEAP_NUMBER_TYPE,
679 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
680 FIXED_UINT8_ARRAY_TYPE,
681 FIXED_INT16_ARRAY_TYPE,
682 FIXED_UINT16_ARRAY_TYPE,
683 FIXED_INT32_ARRAY_TYPE,
684 FIXED_UINT32_ARRAY_TYPE,
685 FIXED_FLOAT32_ARRAY_TYPE,
686 FIXED_FLOAT64_ARRAY_TYPE,
687 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
688 FIXED_DOUBLE_ARRAY_TYPE,
689 FILLER_TYPE, // LAST_DATA_TYPE
692 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
693 DECLARED_ACCESSOR_INFO_TYPE,
694 EXECUTABLE_ACCESSOR_INFO_TYPE,
696 ACCESS_CHECK_INFO_TYPE,
697 INTERCEPTOR_INFO_TYPE,
698 CALL_HANDLER_INFO_TYPE,
699 FUNCTION_TEMPLATE_INFO_TYPE,
700 OBJECT_TEMPLATE_INFO_TYPE,
702 TYPE_SWITCH_INFO_TYPE,
703 ALLOCATION_SITE_TYPE,
704 ALLOCATION_MEMENTO_TYPE,
707 POLYMORPHIC_CODE_CACHE_TYPE,
708 TYPE_FEEDBACK_INFO_TYPE,
709 ALIASED_ARGUMENTS_ENTRY_TYPE,
712 BREAK_POINT_INFO_TYPE,
714 SHARED_FUNCTION_INFO_TYPE,
720 // All the following types are subtypes of JSReceiver, which corresponds to
721 // objects in the JS sense. The first and the last type in this range are
722 // the two forms of function. This organization enables using the same
723 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
724 // NONCALLABLE_JS_OBJECT range.
725 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
726 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
727 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
728 JS_MESSAGE_OBJECT_TYPE,
731 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
732 JS_GENERATOR_OBJECT_TYPE,
734 JS_GLOBAL_OBJECT_TYPE,
735 JS_BUILTINS_OBJECT_TYPE,
736 JS_GLOBAL_PROXY_TYPE,
738 JS_ARRAY_BUFFER_TYPE,
743 JS_SET_ITERATOR_TYPE,
744 JS_MAP_ITERATOR_TYPE,
748 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
752 LAST_TYPE = JS_FUNCTION_TYPE,
753 FIRST_NAME_TYPE = FIRST_TYPE,
754 LAST_NAME_TYPE = SYMBOL_TYPE,
755 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
756 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
757 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
758 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
759 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
760 // Boundaries for testing for a fixed typed array.
761 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
762 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
763 // Boundary for promotion to old space.
764 LAST_DATA_TYPE = FILLER_TYPE,
765 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
766 // Note that there is no range for JSObject or JSProxy, since their subtypes
767 // are not continuous in this enum! The enum ranges instead reflect the
768 // external class names, where proxies are treated as either ordinary objects,
770 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
771 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
772 // Boundaries for testing the types represented as JSObject
773 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
774 LAST_JS_OBJECT_TYPE = LAST_TYPE,
775 // Boundaries for testing the types represented as JSProxy
776 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
777 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
778 // Boundaries for testing whether the type is a JavaScript object.
779 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
780 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
781 // Boundaries for testing the types for which typeof is "object".
782 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
783 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
784 // Note that the types for which typeof is "function" are not continuous.
785 // Define this so that we can put assertions on discrete checks.
786 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
789 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
790 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
791 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
792 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
795 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
796 V(FAST_ELEMENTS_SUB_TYPE) \
797 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
798 V(FAST_PROPERTIES_SUB_TYPE) \
799 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
800 V(MAP_CODE_CACHE_SUB_TYPE) \
801 V(SCOPE_INFO_SUB_TYPE) \
802 V(STRING_TABLE_SUB_TYPE) \
803 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
804 V(TRANSITION_ARRAY_SUB_TYPE)
806 enum FixedArraySubInstanceType {
807 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
808 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
809 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
810 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
823 #define DECL_BOOLEAN_ACCESSORS(name) \
824 inline bool name() const; \
825 inline void set_##name(bool value); \
828 #define DECL_ACCESSORS(name, type) \
829 inline type* name() const; \
830 inline void set_##name(type* value, \
831 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
834 #define DECLARE_CAST(type) \
835 INLINE(static type* cast(Object* object)); \
836 INLINE(static const type* cast(const Object* object));
840 class AllocationSite;
841 class AllocationSiteCreationContext;
842 class AllocationSiteUsageContext;
845 class ElementsAccessor;
846 class FixedArrayBase;
847 class FunctionLiteral;
849 class JSBuiltinsObject;
850 class LayoutDescriptor;
851 class LookupIterator;
852 class ObjectHashTable;
855 class SafepointEntry;
856 class SharedFunctionInfo;
858 class TypeFeedbackInfo;
859 class TypeFeedbackVector;
862 // We cannot just say "class HeapType;" if it is created from a template... =8-?
863 template<class> class TypeImpl;
864 struct HeapTypeConfig;
865 typedef TypeImpl<HeapTypeConfig> HeapType;
868 // A template-ized version of the IsXXX functions.
869 template <class C> inline bool Is(Object* obj);
872 #define DECLARE_VERIFIER(Name) void Name##Verify();
874 #define DECLARE_VERIFIER(Name)
878 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
880 #define DECLARE_PRINTER(Name)
884 #define OBJECT_TYPE_LIST(V) \
889 #define HEAP_OBJECT_TYPE_LIST(V) \
891 V(MutableHeapNumber) \
907 V(ExternalTwoByteString) \
908 V(ExternalOneByteString) \
909 V(SeqTwoByteString) \
910 V(SeqOneByteString) \
911 V(InternalizedString) \
914 V(FixedTypedArrayBase) \
917 V(FixedUint16Array) \
919 V(FixedUint32Array) \
921 V(FixedFloat32Array) \
922 V(FixedFloat64Array) \
923 V(FixedUint8ClampedArray) \
929 V(JSContextExtensionObject) \
930 V(JSGeneratorObject) \
932 V(LayoutDescriptor) \
936 V(TypeFeedbackVector) \
937 V(DeoptimizationInputData) \
938 V(DeoptimizationOutputData) \
942 V(FixedDoubleArray) \
946 V(ScriptContextTable) \
952 V(SharedFunctionInfo) \
961 V(JSArrayBufferView) \
970 V(JSWeakCollection) \
977 V(NormalizedMapCache) \
978 V(CompilationCacheTable) \
979 V(CodeCacheHashTable) \
980 V(PolymorphicCodeCacheHashTable) \
985 V(JSBuiltinsObject) \
987 V(UndetectableObject) \
988 V(AccessCheckNeeded) \
996 // Object is the abstract superclass for all classes in the
998 // Object does not use any virtual functions to avoid the
999 // allocation of the C++ vtable.
1000 // Since both Smi and HeapObject are subclasses of Object no
1001 // data members can be present in Object.
1005 bool IsObject() const { return true; }
1007 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1008 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1009 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1010 #undef IS_TYPE_FUNCTION_DECL
1012 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1013 // a keyed store is of the form a[expression] = foo.
1014 enum StoreFromKeyed {
1015 MAY_BE_STORE_FROM_KEYED,
1016 CERTAINLY_NOT_STORE_FROM_KEYED
1019 INLINE(bool IsFixedArrayBase() const);
1020 INLINE(bool IsExternal() const);
1021 INLINE(bool IsAccessorInfo() const);
1023 INLINE(bool IsStruct() const);
1024 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1025 INLINE(bool Is##Name() const);
1026 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1027 #undef DECLARE_STRUCT_PREDICATE
1029 INLINE(bool IsSpecObject()) const;
1030 INLINE(bool IsSpecFunction()) const;
1031 INLINE(bool IsTemplateInfo()) const;
1032 INLINE(bool IsNameDictionary() const);
1033 INLINE(bool IsGlobalDictionary() const);
1034 INLINE(bool IsSeededNumberDictionary() const);
1035 INLINE(bool IsUnseededNumberDictionary() const);
1036 INLINE(bool IsOrderedHashSet() const);
1037 INLINE(bool IsOrderedHashMap() const);
1038 bool IsCallable() const;
1039 static bool IsPromise(Handle<Object> object);
1042 INLINE(bool IsUndefined() const);
1043 INLINE(bool IsNull() const);
1044 INLINE(bool IsTheHole() const);
1045 INLINE(bool IsException() const);
1046 INLINE(bool IsUninitialized() const);
1047 INLINE(bool IsTrue() const);
1048 INLINE(bool IsFalse() const);
1049 INLINE(bool IsArgumentsMarker() const);
1051 // Filler objects (fillers and free space objects).
1052 INLINE(bool IsFiller() const);
1054 // Extract the number.
1055 inline double Number();
1056 INLINE(bool IsNaN() const);
1057 INLINE(bool IsMinusZero() const);
1058 bool ToInt32(int32_t* value);
1059 bool ToUint32(uint32_t* value);
1061 inline Representation OptimalRepresentation();
1063 inline ElementsKind OptimalElementsKind();
1065 inline bool FitsRepresentation(Representation representation);
1067 // Checks whether two valid primitive encodings of a property name resolve to
1068 // the same logical property. E.g., the smi 1, the string "1" and the double
1069 // 1 all refer to the same property, so this helper will return true.
1070 inline bool KeyEquals(Object* other);
1072 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1074 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1075 Handle<Object> object,
1076 Representation representation);
1078 inline static Handle<Object> WrapForRead(Isolate* isolate,
1079 Handle<Object> object,
1080 Representation representation);
1082 // Returns true if the object is of the correct type to be used as a
1083 // implementation of a JSObject's elements.
1084 inline bool HasValidElements();
1086 inline bool HasSpecificClassOf(String* name);
1088 bool BooleanValue(); // ECMA-262 9.2.
1090 // ES6 section 7.2.13 Strict Equality Comparison
1091 bool StrictEquals(Object* that);
1093 // Convert to a JSObject if needed.
1094 // native_context is used when creating wrapper object.
1095 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1096 Handle<Object> object);
1097 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1098 Handle<Object> object,
1099 Handle<Context> context);
1101 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1102 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1104 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1105 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1106 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1107 LanguageMode language_mode,
1108 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1110 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1111 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1112 StoreFromKeyed store_mode);
1114 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1115 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1116 StoreFromKeyed store_mode);
1118 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1119 LookupIterator* it, LanguageMode language_mode);
1120 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1121 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1122 LanguageMode language_mode);
1123 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1124 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1125 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1126 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1127 Handle<Object> value, LanguageMode language_mode);
1128 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1129 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1130 LanguageMode language_mode);
1131 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1132 LookupIterator* it, Handle<Object> value);
1133 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1134 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1135 LanguageMode language_mode, StoreFromKeyed store_mode);
1136 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1137 Handle<Object> object, Handle<Name> name,
1138 LanguageMode language_mode = SLOPPY);
1139 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1140 Isolate* isolate, Handle<Object> object, const char* key,
1141 LanguageMode language_mode = SLOPPY);
1142 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1143 Handle<Object> object, Handle<Name> name,
1144 LanguageMode language_mode = SLOPPY);
1146 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1147 LookupIterator* it, LanguageMode language_mode);
1148 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1149 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1151 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1152 Handle<Object> receiver,
1153 Handle<JSReceiver> getter);
1154 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1155 Handle<Object> receiver,
1156 Handle<JSReceiver> setter,
1157 Handle<Object> value);
1159 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1160 Isolate* isolate, Handle<Object> object, uint32_t index,
1161 LanguageMode language_mode = SLOPPY);
1163 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1164 Isolate* isolate, Handle<Object> object, uint32_t index,
1165 Handle<Object> value, LanguageMode language_mode);
1167 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1168 Isolate* isolate, Handle<Object> receiver);
1170 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1172 // Returns the permanent hash code associated with this object. May return
1173 // undefined if not yet created.
1176 // Returns undefined for JSObjects, but returns the hash code for simple
1177 // objects. This avoids a double lookup in the cases where we know we will
1178 // add the hash to the JSObject if it does not already exist.
1179 Object* GetSimpleHash();
1181 // Returns the permanent hash code associated with this object depending on
1182 // the actual object type. May create and store a hash code if needed and none
1184 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1186 // Checks whether this object has the same value as the given one. This
1187 // function is implemented according to ES5, section 9.12 and can be used
1188 // to implement the Harmony "egal" function.
1189 bool SameValue(Object* other);
1191 // Checks whether this object has the same value as the given one.
1192 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1193 // This function is implemented according to ES6, section 7.2.4 and is used
1194 // by ES6 Map and Set.
1195 bool SameValueZero(Object* other);
1197 // Tries to convert an object to an array length. Returns true and sets the
1198 // output parameter if it succeeds.
1199 inline bool ToArrayLength(uint32_t* index);
1201 // Tries to convert an object to an array index. Returns true and sets the
1202 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1203 // allow kMaxUInt32.
1204 inline bool ToArrayIndex(uint32_t* index);
1206 // Returns true if this is a JSValue containing a string and the index is
1207 // < the length of the string. Used to implement [] on strings.
1208 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1210 DECLARE_VERIFIER(Object)
1212 // Verify a pointer is a valid object pointer.
1213 static void VerifyPointer(Object* p);
1216 inline void VerifyApiCallResultType();
1218 // Prints this object without details.
1219 void ShortPrint(FILE* out = stdout);
1221 // Prints this object without details to a message accumulator.
1222 void ShortPrint(StringStream* accumulator);
1224 void ShortPrint(std::ostream& os); // NOLINT
1226 DECLARE_CAST(Object)
1228 // Layout description.
1229 static const int kHeaderSize = 0; // Object does not take up any space.
1232 // For our gdb macros, we should perhaps change these in the future.
1235 // Prints this object with details.
1236 void Print(std::ostream& os); // NOLINT
1238 void Print() { ShortPrint(); }
1239 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1243 friend class LookupIterator;
1244 friend class PrototypeIterator;
1246 // Return the map of the root of object's prototype chain.
1247 Map* GetRootMap(Isolate* isolate);
1249 // Helper for SetProperty and SetSuperProperty.
1250 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1251 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1252 StoreFromKeyed store_mode, bool* found);
1254 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1258 // In objects.h to be usable without objects-inl.h inclusion.
1259 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1260 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1264 explicit Brief(const Object* const v) : value(v) {}
1265 const Object* value;
1269 std::ostream& operator<<(std::ostream& os, const Brief& v);
1272 // Smi represents integer Numbers that can be stored in 31 bits.
1273 // Smis are immediate which means they are NOT allocated in the heap.
1274 // The this pointer has the following format: [31 bit signed int] 0
1275 // For long smis it has the following format:
1276 // [32 bit signed int] [31 bits zero padding] 0
1277 // Smi stands for small integer.
1278 class Smi: public Object {
1280 // Returns the integer value.
1281 inline int value() const { return Internals::SmiValue(this); }
1283 // Convert a value to a Smi object.
1284 static inline Smi* FromInt(int value) {
1285 DCHECK(Smi::IsValid(value));
1286 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1289 static inline Smi* FromIntptr(intptr_t value) {
1290 DCHECK(Smi::IsValid(value));
1291 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1292 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1295 // Returns whether value can be represented in a Smi.
1296 static inline bool IsValid(intptr_t value) {
1297 bool result = Internals::IsValidSmi(value);
1298 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1304 // Dispatched behavior.
1305 void SmiPrint(std::ostream& os) const; // NOLINT
1306 DECLARE_VERIFIER(Smi)
1308 static const int kMinValue =
1309 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1310 static const int kMaxValue = -(kMinValue + 1);
1313 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1317 // Heap objects typically have a map pointer in their first word. However,
1318 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1319 // encoded in the first word. The class MapWord is an abstraction of the
1320 // value in a heap object's first word.
1321 class MapWord BASE_EMBEDDED {
1323 // Normal state: the map word contains a map pointer.
1325 // Create a map word from a map pointer.
1326 static inline MapWord FromMap(const Map* map);
1328 // View this map word as a map pointer.
1329 inline Map* ToMap();
1332 // Scavenge collection: the map word of live objects in the from space
1333 // contains a forwarding address (a heap object pointer in the to space).
1335 // True if this map word is a forwarding address for a scavenge
1336 // collection. Only valid during a scavenge collection (specifically,
1337 // when all map words are heap object pointers, i.e. not during a full GC).
1338 inline bool IsForwardingAddress();
1340 // Create a map word from a forwarding address.
1341 static inline MapWord FromForwardingAddress(HeapObject* object);
1343 // View this map word as a forwarding address.
1344 inline HeapObject* ToForwardingAddress();
1346 static inline MapWord FromRawValue(uintptr_t value) {
1347 return MapWord(value);
1350 inline uintptr_t ToRawValue() {
1355 // HeapObject calls the private constructor and directly reads the value.
1356 friend class HeapObject;
1358 explicit MapWord(uintptr_t value) : value_(value) {}
1364 // The content of an heap object (except for the map pointer). kTaggedValues
1365 // objects can contain both heap pointers and Smis, kMixedValues can contain
1366 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1367 // objects can contain raw values and Smis.
1368 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1371 // HeapObject is the superclass for all classes describing heap allocated
1373 class HeapObject: public Object {
1375 // [map]: Contains a map which contains the object's reflective
1377 inline Map* map() const;
1378 inline void set_map(Map* value);
1379 // The no-write-barrier version. This is OK if the object is white and in
1380 // new space, or if the value is an immortal immutable object, like the maps
1381 // of primitive (non-JS) objects like strings, heap numbers etc.
1382 inline void set_map_no_write_barrier(Map* value);
1384 // Get the map using acquire load.
1385 inline Map* synchronized_map();
1386 inline MapWord synchronized_map_word() const;
1388 // Set the map using release store
1389 inline void synchronized_set_map(Map* value);
1390 inline void synchronized_set_map_no_write_barrier(Map* value);
1391 inline void synchronized_set_map_word(MapWord map_word);
1393 // During garbage collection, the map word of a heap object does not
1394 // necessarily contain a map pointer.
1395 inline MapWord map_word() const;
1396 inline void set_map_word(MapWord map_word);
1398 // The Heap the object was allocated in. Used also to access Isolate.
1399 inline Heap* GetHeap() const;
1401 // Convenience method to get current isolate.
1402 inline Isolate* GetIsolate() const;
1404 // Converts an address to a HeapObject pointer.
1405 static inline HeapObject* FromAddress(Address address) {
1406 DCHECK_TAG_ALIGNED(address);
1407 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1410 // Returns the address of this HeapObject.
1411 inline Address address() {
1412 return reinterpret_cast<Address>(this) - kHeapObjectTag;
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 // Equality operations.
1599 inline bool Equals(Simd128Value* that);
1601 // Checks that another instance is bit-wise equal.
1602 bool BitwiseEquals(const Simd128Value* other) const;
1603 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1604 uint32_t Hash() const;
1605 // Copies the 16 bytes of SIMD data to the destination address.
1606 void CopyBits(void* destination) const;
1608 // Layout description.
1609 static const int kValueOffset = HeapObject::kHeaderSize;
1610 static const int kSize = kValueOffset + kSimd128Size;
1613 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1617 // V has parameters (TYPE, Type, type, lane count, lane type)
1618 #define SIMD128_TYPES(V) \
1619 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1620 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1621 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1622 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1623 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1624 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1625 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1627 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1628 class Type final : public Simd128Value { \
1630 inline lane_type get_lane(int lane) const; \
1631 inline void set_lane(int lane, lane_type value); \
1633 DECLARE_CAST(Type) \
1635 DECLARE_PRINTER(Type) \
1637 inline bool Equals(Type* that); \
1640 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1642 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1643 #undef SIMD128_VALUE_CLASS
1646 enum EnsureElementsMode {
1647 DONT_ALLOW_DOUBLE_ELEMENTS,
1648 ALLOW_COPIED_DOUBLE_ELEMENTS,
1649 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1653 // Indicator for one component of an AccessorPair.
1654 enum AccessorComponent {
1660 // JSReceiver includes types on which properties can be defined, i.e.,
1661 // JSObject and JSProxy.
1662 class JSReceiver: public HeapObject {
1664 DECLARE_CAST(JSReceiver)
1666 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1667 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1668 Handle<JSReceiver> object, Handle<Name> name);
1669 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1671 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1672 Handle<JSReceiver> object, uint32_t index);
1673 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1674 Handle<JSReceiver> object, uint32_t index);
1676 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1677 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1678 Handle<JSReceiver> object, Handle<Name> name,
1679 LanguageMode language_mode = SLOPPY);
1680 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1681 Handle<JSReceiver> object, Handle<Name> name,
1682 LanguageMode language_mode = SLOPPY);
1683 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1684 LookupIterator* it, LanguageMode language_mode);
1685 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1686 Handle<JSReceiver> object, uint32_t index,
1687 LanguageMode language_mode = SLOPPY);
1689 // Tests for the fast common case for property enumeration.
1690 bool IsSimpleEnum();
1692 // Returns the class name ([[Class]] property in the specification).
1693 String* class_name();
1695 // Returns the constructor name (the name (possibly, inferred name) of the
1696 // function that was used to instantiate the object).
1697 String* constructor_name();
1699 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1700 Handle<JSReceiver> object, Handle<Name> name);
1701 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1702 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1704 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1705 Handle<JSReceiver> object, uint32_t index);
1706 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1707 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1709 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1710 LookupIterator* it);
1713 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1715 static Handle<Object> GetDataProperty(LookupIterator* it);
1718 // Retrieves a permanent object identity hash code. The undefined value might
1719 // be returned in case no hash was created yet.
1720 inline Object* GetIdentityHash();
1722 // Retrieves a permanent object identity hash code. May create and store a
1723 // hash code if needed and none exists.
1724 inline static Handle<Smi> GetOrCreateIdentityHash(
1725 Handle<JSReceiver> object);
1727 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1729 // Computes the enumerable keys for a JSObject. Used for implementing
1730 // "for (n in object) { }".
1731 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1732 Handle<JSReceiver> object,
1733 KeyCollectionType type);
1736 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1740 // The JSObject describes real heap allocated JavaScript objects with
1742 // Note that the map of JSObject changes during execution to enable inline
1744 class JSObject: public JSReceiver {
1746 // [properties]: Backing storage for properties.
1747 // properties is a FixedArray in the fast case and a Dictionary in the
1749 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1750 inline void initialize_properties();
1751 inline bool HasFastProperties();
1752 // Gets slow properties for non-global objects.
1753 inline NameDictionary* property_dictionary();
1754 // Gets global object properties.
1755 inline GlobalDictionary* global_dictionary();
1757 // [elements]: The elements (properties with names that are integers).
1759 // Elements can be in two general modes: fast and slow. Each mode
1760 // corrensponds to a set of object representations of elements that
1761 // have something in common.
1763 // In the fast mode elements is a FixedArray and so each element can
1764 // be quickly accessed. This fact is used in the generated code. The
1765 // elements array can have one of three maps in this mode:
1766 // fixed_array_map, sloppy_arguments_elements_map or
1767 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1768 // the elements array may be shared by a few objects and so before
1769 // writing to any element the array must be copied. Use
1770 // EnsureWritableFastElements in this case.
1772 // In the slow mode the elements is either a NumberDictionary, a
1773 // FixedArray parameter map for a (sloppy) arguments object.
1774 DECL_ACCESSORS(elements, FixedArrayBase)
1775 inline void initialize_elements();
1776 static void ResetElements(Handle<JSObject> object);
1777 static inline void SetMapAndElements(Handle<JSObject> object,
1779 Handle<FixedArrayBase> elements);
1780 inline ElementsKind GetElementsKind();
1781 ElementsAccessor* GetElementsAccessor();
1782 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1783 inline bool HasFastSmiElements();
1784 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1785 inline bool HasFastObjectElements();
1786 // Returns true if an object has elements of FAST_ELEMENTS or
1787 // FAST_SMI_ONLY_ELEMENTS.
1788 inline bool HasFastSmiOrObjectElements();
1789 // Returns true if an object has any of the fast elements kinds.
1790 inline bool HasFastElements();
1791 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1793 inline bool HasFastDoubleElements();
1794 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1796 inline bool HasFastHoleyElements();
1797 inline bool HasSloppyArgumentsElements();
1798 inline bool HasDictionaryElements();
1800 inline bool HasFixedTypedArrayElements();
1802 inline bool HasFixedUint8ClampedElements();
1803 inline bool HasFixedArrayElements();
1804 inline bool HasFixedInt8Elements();
1805 inline bool HasFixedUint8Elements();
1806 inline bool HasFixedInt16Elements();
1807 inline bool HasFixedUint16Elements();
1808 inline bool HasFixedInt32Elements();
1809 inline bool HasFixedUint32Elements();
1810 inline bool HasFixedFloat32Elements();
1811 inline bool HasFixedFloat64Elements();
1813 inline bool HasFastArgumentsElements();
1814 inline bool HasSlowArgumentsElements();
1815 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1817 // Requires: HasFastElements().
1818 static Handle<FixedArray> EnsureWritableFastElements(
1819 Handle<JSObject> object);
1821 // Collects elements starting at index 0.
1822 // Undefined values are placed after non-undefined values.
1823 // Returns the number of non-undefined values.
1824 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1826 // As PrepareElementsForSort, but only on objects where elements is
1827 // a dictionary, and it will stay a dictionary. Collates undefined and
1828 // unexisting elements below limit from position zero of the elements.
1829 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1832 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1833 LookupIterator* it, Handle<Object> value);
1835 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1836 // grant an exemption to ExecutableAccessor callbacks in some cases.
1837 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1839 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1840 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1841 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1843 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1844 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1845 PropertyAttributes attributes,
1846 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1848 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1849 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1850 PropertyAttributes attributes,
1851 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1853 // Equivalent to one of the above depending on whether |name| can be converted
1854 // to an array index.
1855 MUST_USE_RESULT static MaybeHandle<Object>
1856 DefinePropertyOrElementIgnoreAttributes(
1857 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1858 PropertyAttributes attributes = NONE,
1859 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1861 // Adds or reconfigures a property to attributes NONE. It will fail when it
1863 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1864 Handle<Object> value);
1866 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1867 Handle<Object> value, PropertyAttributes attributes);
1869 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1870 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1871 PropertyAttributes attributes);
1873 // Extend the receiver with a single fast property appeared first in the
1874 // passed map. This also extends the property backing store if necessary.
1875 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1877 // Migrates the given object to a map whose field representations are the
1878 // lowest upper bound of all known representations for that field.
1879 static void MigrateInstance(Handle<JSObject> instance);
1881 // Migrates the given object only if the target map is already available,
1882 // or returns false if such a map is not yet available.
1883 static bool TryMigrateInstance(Handle<JSObject> instance);
1885 // Sets the property value in a normalized object given (key, value, details).
1886 // Handles the special representation of JS global objects.
1887 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1888 Handle<Object> value,
1889 PropertyDetails details);
1890 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1891 Handle<Object> value,
1892 PropertyAttributes attributes);
1893 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1895 Handle<Object> value,
1896 PropertyAttributes attributes);
1898 static void OptimizeAsPrototype(Handle<JSObject> object,
1899 PrototypeOptimizationMode mode);
1900 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1901 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1902 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1903 static void InvalidatePrototypeChains(Map* map);
1905 // Alternative implementation of WeakFixedArray::NullCallback.
1906 class PrototypeRegistryCompactionCallback {
1908 static void Callback(Object* value, int old_index, int new_index);
1911 // Retrieve interceptors.
1912 InterceptorInfo* GetNamedInterceptor();
1913 InterceptorInfo* GetIndexedInterceptor();
1915 // Used from JSReceiver.
1916 MUST_USE_RESULT static Maybe<PropertyAttributes>
1917 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1918 MUST_USE_RESULT static Maybe<PropertyAttributes>
1919 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1921 // Retrieves an AccessorPair property from the given object. Might return
1922 // undefined if the property doesn't exist or is of a different kind.
1923 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1924 Handle<JSObject> object,
1926 AccessorComponent component);
1928 // Defines an AccessorPair property on the given object.
1929 // TODO(mstarzinger): Rename to SetAccessor().
1930 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1932 Handle<Object> getter,
1933 Handle<Object> setter,
1934 PropertyAttributes attributes);
1936 // Defines an AccessorInfo property on the given object.
1937 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1938 Handle<JSObject> object,
1939 Handle<AccessorInfo> info);
1941 // The result must be checked first for exceptions. If there's no exception,
1942 // the output parameter |done| indicates whether the interceptor has a result
1944 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1945 LookupIterator* it, bool* done);
1947 // Accessors for hidden properties object.
1949 // Hidden properties are not own properties of the object itself.
1950 // Instead they are stored in an auxiliary structure kept as an own
1951 // property with a special name Heap::hidden_string(). But if the
1952 // receiver is a JSGlobalProxy then the auxiliary object is a property
1953 // of its prototype, and if it's a detached proxy, then you can't have
1954 // hidden properties.
1956 // Sets a hidden property on this object. Returns this object if successful,
1957 // undefined if called on a detached proxy.
1958 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1960 Handle<Object> value);
1961 // Gets the value of a hidden property with the given key. Returns the hole
1962 // if the property doesn't exist (or if called on a detached proxy),
1963 // otherwise returns the value set for the key.
1964 Object* GetHiddenProperty(Handle<Name> key);
1965 // Deletes a hidden property. Deleting a non-existing property is
1966 // considered successful.
1967 static void DeleteHiddenProperty(Handle<JSObject> object,
1969 // Returns true if the object has a property with the hidden string as name.
1970 static bool HasHiddenProperties(Handle<JSObject> object);
1972 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1974 static void ValidateElements(Handle<JSObject> object);
1976 // Makes sure that this object can contain HeapObject as elements.
1977 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1979 // Makes sure that this object can contain the specified elements.
1980 static inline void EnsureCanContainElements(
1981 Handle<JSObject> object,
1984 EnsureElementsMode mode);
1985 static inline void EnsureCanContainElements(
1986 Handle<JSObject> object,
1987 Handle<FixedArrayBase> elements,
1989 EnsureElementsMode mode);
1990 static void EnsureCanContainElements(
1991 Handle<JSObject> object,
1992 Arguments* arguments,
1995 EnsureElementsMode mode);
1997 // Would we convert a fast elements array to dictionary mode given
1998 // an access at key?
1999 bool WouldConvertToSlowElements(uint32_t index);
2001 // Computes the new capacity when expanding the elements of a JSObject.
2002 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2003 // (old_capacity + 50%) + 16
2004 return old_capacity + (old_capacity >> 1) + 16;
2007 // These methods do not perform access checks!
2008 static void UpdateAllocationSite(Handle<JSObject> object,
2009 ElementsKind to_kind);
2011 // Lookup interceptors are used for handling properties controlled by host
2013 inline bool HasNamedInterceptor();
2014 inline bool HasIndexedInterceptor();
2016 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2017 // by JSReceiver::GetKeys.
2018 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2019 Handle<JSObject> object,
2020 Handle<JSReceiver> receiver);
2021 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2022 Handle<JSObject> object,
2023 Handle<JSReceiver> receiver);
2025 // Support functions for v8 api (needed for correct interceptor behavior).
2026 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2027 Handle<JSObject> object, Handle<Name> name);
2028 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2029 Handle<JSObject> object, uint32_t index);
2030 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2031 Handle<JSObject> object, Handle<Name> name);
2033 // Get the header size for a JSObject. Used to compute the index of
2034 // internal fields as well as the number of internal fields.
2035 inline int GetHeaderSize();
2037 inline int GetInternalFieldCount();
2038 inline int GetInternalFieldOffset(int index);
2039 inline Object* GetInternalField(int index);
2040 inline void SetInternalField(int index, Object* value);
2041 inline void SetInternalField(int index, Smi* value);
2043 // Returns the number of properties on this object filtering out properties
2044 // with the specified attributes (ignoring interceptors).
2045 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2046 // Fill in details for properties into storage starting at the specified
2047 // index. Returns the number of properties added.
2048 int GetOwnPropertyNames(FixedArray* storage, int index,
2049 PropertyAttributes filter = NONE);
2051 // Returns the number of properties on this object filtering out properties
2052 // with the specified attributes (ignoring interceptors).
2053 int NumberOfOwnElements(PropertyAttributes filter);
2054 // Returns the number of enumerable elements (ignoring interceptors).
2055 int NumberOfEnumElements();
2056 // Returns the number of elements on this object filtering out elements
2057 // with the specified attributes (ignoring interceptors).
2058 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2059 // Count and fill in the enumerable elements into storage.
2060 // (storage->length() == NumberOfEnumElements()).
2061 // If storage is NULL, will count the elements without adding
2062 // them to any storage.
2063 // Returns the number of enumerable elements.
2064 int GetEnumElementKeys(FixedArray* storage);
2066 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2069 // Returns a new map with all transitions dropped from the object's current
2070 // map and the ElementsKind set.
2071 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2072 ElementsKind to_kind);
2073 static void TransitionElementsKind(Handle<JSObject> object,
2074 ElementsKind to_kind);
2076 // Always use this to migrate an object to a new map.
2077 // |expected_additional_properties| is only used for fast-to-slow transitions
2078 // and ignored otherwise.
2079 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2080 int expected_additional_properties = 0);
2082 // Convert the object to use the canonical dictionary
2083 // representation. If the object is expected to have additional properties
2084 // added this number can be indicated to have the backing store allocated to
2085 // an initial capacity for holding these properties.
2086 static void NormalizeProperties(Handle<JSObject> object,
2087 PropertyNormalizationMode mode,
2088 int expected_additional_properties,
2089 const char* reason);
2091 // Convert and update the elements backing store to be a
2092 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2093 static Handle<SeededNumberDictionary> NormalizeElements(
2094 Handle<JSObject> object);
2096 void RequireSlowElements(SeededNumberDictionary* dictionary);
2098 // Transform slow named properties to fast variants.
2099 static void MigrateSlowToFast(Handle<JSObject> object,
2100 int unused_property_fields, const char* reason);
2102 inline bool IsUnboxedDoubleField(FieldIndex index);
2104 // Access fast-case object properties at index.
2105 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2106 Representation representation,
2108 inline Object* RawFastPropertyAt(FieldIndex index);
2109 inline double RawFastDoublePropertyAt(FieldIndex index);
2111 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2112 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2113 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2114 inline void WriteToField(int descriptor, Object* value);
2116 // Access to in object properties.
2117 inline int GetInObjectPropertyOffset(int index);
2118 inline Object* InObjectPropertyAt(int index);
2119 inline Object* InObjectPropertyAtPut(int index,
2121 WriteBarrierMode mode
2122 = UPDATE_WRITE_BARRIER);
2124 // Set the object's prototype (only JSReceiver and null are allowed values).
2125 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2126 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2128 // Initializes the body after properties slot, properties slot is
2129 // initialized by set_properties. Fill the pre-allocated fields with
2130 // pre_allocated_value and the rest with filler_value.
2131 // Note: this call does not update write barrier, the caller is responsible
2132 // to ensure that |filler_value| can be collected without WB here.
2133 inline void InitializeBody(Map* map,
2134 Object* pre_allocated_value,
2135 Object* filler_value);
2137 // Check whether this object references another object
2138 bool ReferencesObject(Object* obj);
2140 // Disalow further properties to be added to the oject.
2141 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2142 Handle<JSObject> object);
2144 bool IsExtensible();
2147 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2149 // ES5 Object.freeze
2150 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2152 // Called the first time an object is observed with ES7 Object.observe.
2153 static void SetObserved(Handle<JSObject> object);
2156 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2158 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2159 Handle<JSObject> object,
2160 AllocationSiteUsageContext* site_context,
2161 DeepCopyHints hints = kNoHints);
2162 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2163 Handle<JSObject> object,
2164 AllocationSiteCreationContext* site_context);
2166 DECLARE_CAST(JSObject)
2168 // Dispatched behavior.
2169 void JSObjectShortPrint(StringStream* accumulator);
2170 DECLARE_PRINTER(JSObject)
2171 DECLARE_VERIFIER(JSObject)
2173 void PrintProperties(std::ostream& os); // NOLINT
2174 void PrintElements(std::ostream& os); // NOLINT
2176 #if defined(DEBUG) || defined(OBJECT_PRINT)
2177 void PrintTransitions(std::ostream& os); // NOLINT
2180 static void PrintElementsTransition(
2181 FILE* file, Handle<JSObject> object,
2182 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2183 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2185 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2188 // Structure for collecting spill information about JSObjects.
2189 class SpillInformation {
2193 int number_of_objects_;
2194 int number_of_objects_with_fast_properties_;
2195 int number_of_objects_with_fast_elements_;
2196 int number_of_fast_used_fields_;
2197 int number_of_fast_unused_fields_;
2198 int number_of_slow_used_properties_;
2199 int number_of_slow_unused_properties_;
2200 int number_of_fast_used_elements_;
2201 int number_of_fast_unused_elements_;
2202 int number_of_slow_used_elements_;
2203 int number_of_slow_unused_elements_;
2206 void IncrementSpillStatistics(SpillInformation* info);
2210 // If a GC was caused while constructing this object, the elements pointer
2211 // may point to a one pointer filler map. The object won't be rooted, but
2212 // our heap verification code could stumble across it.
2213 bool ElementsAreSafeToExamine();
2216 Object* SlowReverseLookup(Object* value);
2218 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2219 // Also maximal value of JSArray's length property.
2220 static const uint32_t kMaxElementCount = 0xffffffffu;
2222 // Constants for heuristics controlling conversion of fast elements
2223 // to slow elements.
2225 // Maximal gap that can be introduced by adding an element beyond
2226 // the current elements length.
2227 static const uint32_t kMaxGap = 1024;
2229 // Maximal length of fast elements array that won't be checked for
2230 // being dense enough on expansion.
2231 static const int kMaxUncheckedFastElementsLength = 5000;
2233 // Same as above but for old arrays. This limit is more strict. We
2234 // don't want to be wasteful with long lived objects.
2235 static const int kMaxUncheckedOldFastElementsLength = 500;
2237 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2238 // permissible values (see the DCHECK in heap.cc).
2239 static const int kInitialMaxFastElementArray = 100000;
2241 // This constant applies only to the initial map of "global.Object" and
2242 // not to arbitrary other JSObject maps.
2243 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2245 static const int kMaxInstanceSize = 255 * kPointerSize;
2246 // When extending the backing storage for property values, we increase
2247 // its size by more than the 1 entry necessary, so sequentially adding fields
2248 // to the same object requires fewer allocations and copies.
2249 static const int kFieldsAdded = 3;
2251 // Layout description.
2252 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2253 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2254 static const int kHeaderSize = kElementsOffset + kPointerSize;
2256 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2258 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2260 static inline int SizeOf(Map* map, HeapObject* object);
2263 Context* GetCreationContext();
2265 // Enqueue change record for Object.observe. May cause GC.
2266 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2267 Handle<JSObject> object, const char* type, Handle<Name> name,
2268 Handle<Object> old_value);
2270 // Gets the number of currently used elements.
2271 int GetFastElementsUsage();
2273 // Deletes an existing named property in a normalized object.
2274 static void DeleteNormalizedProperty(Handle<JSObject> object,
2275 Handle<Name> name, int entry);
2277 static bool AllCanRead(LookupIterator* it);
2278 static bool AllCanWrite(LookupIterator* it);
2281 friend class JSReceiver;
2282 friend class Object;
2284 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2285 static void MigrateFastToSlow(Handle<JSObject> object,
2286 Handle<Map> new_map,
2287 int expected_additional_properties);
2289 // Used from Object::GetProperty().
2290 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2291 LookupIterator* it);
2293 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2294 LookupIterator* it, Handle<Object> value);
2296 // Add a property to a slow-case object.
2297 static void AddSlowProperty(Handle<JSObject> object,
2299 Handle<Object> value,
2300 PropertyAttributes attributes);
2302 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2303 LookupIterator* it);
2305 bool ReferencesObjectFromElements(FixedArray* elements,
2309 // Return the hash table backing store or the inline stored identity hash,
2310 // whatever is found.
2311 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2313 // Return the hash table backing store for hidden properties. If there is no
2314 // backing store, allocate one.
2315 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2316 Handle<JSObject> object);
2318 // Set the hidden property backing store to either a hash table or
2319 // the inline-stored identity hash.
2320 static Handle<Object> SetHiddenPropertiesHashTable(
2321 Handle<JSObject> object,
2322 Handle<Object> value);
2324 MUST_USE_RESULT Object* GetIdentityHash();
2326 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2328 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2329 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2331 // Helper for fast versions of preventExtensions, seal, and freeze.
2332 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2333 template <PropertyAttributes attrs>
2334 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2335 Handle<JSObject> object);
2337 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2341 // Common superclass for FixedArrays that allow implementations to share
2342 // common accessors and some code paths.
2343 class FixedArrayBase: public HeapObject {
2345 // [length]: length of the array.
2346 inline int length() const;
2347 inline void set_length(int value);
2349 // Get and set the length using acquire loads and release stores.
2350 inline int synchronized_length() const;
2351 inline void synchronized_set_length(int value);
2353 DECLARE_CAST(FixedArrayBase)
2355 // Layout description.
2356 // Length is smi tagged when it is stored.
2357 static const int kLengthOffset = HeapObject::kHeaderSize;
2358 static const int kHeaderSize = kLengthOffset + kPointerSize;
2362 class FixedDoubleArray;
2363 class IncrementalMarking;
2366 // FixedArray describes fixed-sized arrays with element type Object*.
2367 class FixedArray: public FixedArrayBase {
2369 // Setter and getter for elements.
2370 inline Object* get(int index) const;
2371 void SetValue(uint32_t index, Object* value);
2372 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2373 // Setter that uses write barrier.
2374 inline void set(int index, Object* value);
2375 inline bool is_the_hole(int index);
2377 // Setter that doesn't need write barrier.
2378 inline void set(int index, Smi* value);
2379 // Setter with explicit barrier mode.
2380 inline void set(int index, Object* value, WriteBarrierMode mode);
2382 // Setters for frequently used oddballs located in old space.
2383 inline void set_undefined(int index);
2384 inline void set_null(int index);
2385 inline void set_the_hole(int index);
2387 inline Object** GetFirstElementAddress();
2388 inline bool ContainsOnlySmisOrHoles();
2390 // Gives access to raw memory which stores the array's data.
2391 inline Object** data_start();
2393 inline void FillWithHoles(int from, int to);
2395 // Shrink length and insert filler objects.
2396 void Shrink(int length);
2398 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2400 // Add the elements of a JSArray to this FixedArray.
2401 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2402 Handle<FixedArray> content, Handle<JSObject> array,
2403 KeyFilter filter = ALL_KEYS);
2405 // Computes the union of keys and return the result.
2406 // Used for implementing "for (n in object) { }"
2407 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2408 Handle<FixedArray> first,
2409 Handle<FixedArray> second);
2411 // Copy a sub array from the receiver to dest.
2412 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2414 // Garbage collection support.
2415 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2417 // Code Generation support.
2418 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2420 // Garbage collection support.
2421 inline Object** RawFieldOfElementAt(int index);
2423 DECLARE_CAST(FixedArray)
2425 // Maximal allowed size, in bytes, of a single FixedArray.
2426 // Prevents overflowing size computations, as well as extreme memory
2428 static const int kMaxSize = 128 * MB * kPointerSize;
2429 // Maximally allowed length of a FixedArray.
2430 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2432 // Dispatched behavior.
2433 DECLARE_PRINTER(FixedArray)
2434 DECLARE_VERIFIER(FixedArray)
2436 // Checks if two FixedArrays have identical contents.
2437 bool IsEqualTo(FixedArray* other);
2440 // Swap two elements in a pair of arrays. If this array and the
2441 // numbers array are the same object, the elements are only swapped
2443 void SwapPairs(FixedArray* numbers, int i, int j);
2445 // Sort prefix of this array and the numbers array as pairs wrt. the
2446 // numbers. If the numbers array and the this array are the same
2447 // object, the prefix of this array is sorted.
2448 void SortPairs(FixedArray* numbers, uint32_t len);
2450 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2452 static inline int SizeOf(Map* map, HeapObject* object);
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 inline int number_of_descriptors();
2619 inline int number_of_descriptors_storage();
2621 inline int NumberOfSlackDescriptors();
2623 inline void SetNumberOfDescriptors(int number_of_descriptors);
2624 inline int number_of_entries();
2626 inline bool HasEnumCache();
2628 inline void CopyEnumCacheFrom(DescriptorArray* array);
2630 inline FixedArray* GetEnumCache();
2632 inline bool HasEnumIndicesCache();
2634 inline FixedArray* GetEnumIndicesCache();
2636 inline Object** GetEnumCacheSlot();
2638 void ClearEnumCache();
2640 // Initialize or change the enum cache,
2641 // using the supplied storage for the small "bridge".
2642 void SetEnumCache(FixedArray* bridge_storage,
2643 FixedArray* new_cache,
2644 Object* new_index_cache);
2646 bool CanHoldValue(int descriptor, Object* value);
2648 // Accessors for fetching instance descriptor at descriptor number.
2649 inline Name* GetKey(int descriptor_number);
2650 inline Object** GetKeySlot(int descriptor_number);
2651 inline Object* GetValue(int descriptor_number);
2652 inline void SetValue(int descriptor_number, Object* value);
2653 inline Object** GetValueSlot(int descriptor_number);
2654 static inline int GetValueOffset(int descriptor_number);
2655 inline Object** GetDescriptorStartSlot(int descriptor_number);
2656 inline Object** GetDescriptorEndSlot(int descriptor_number);
2657 inline PropertyDetails GetDetails(int descriptor_number);
2658 inline PropertyType GetType(int descriptor_number);
2659 inline int GetFieldIndex(int descriptor_number);
2660 inline HeapType* GetFieldType(int descriptor_number);
2661 inline Object* GetConstant(int descriptor_number);
2662 inline Object* GetCallbacksObject(int descriptor_number);
2663 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2665 inline Name* GetSortedKey(int descriptor_number);
2666 inline int GetSortedKeyIndex(int descriptor_number);
2667 inline void SetSortedKey(int pointer, int descriptor_number);
2668 inline void SetRepresentation(int descriptor_number,
2669 Representation representation);
2671 // Accessor for complete descriptor.
2672 inline void Get(int descriptor_number, Descriptor* desc);
2673 inline void Set(int descriptor_number, Descriptor* desc);
2674 void Replace(int descriptor_number, Descriptor* descriptor);
2676 // Append automatically sets the enumeration index. This should only be used
2677 // to add descriptors in bulk at the end, followed by sorting the descriptor
2679 inline void Append(Descriptor* desc);
2681 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2682 int enumeration_index,
2685 static Handle<DescriptorArray> CopyUpToAddAttributes(
2686 Handle<DescriptorArray> desc,
2687 int enumeration_index,
2688 PropertyAttributes attributes,
2691 // Sort the instance descriptors by the hash codes of their keys.
2694 // Search the instance descriptors for given name.
2695 INLINE(int Search(Name* name, int number_of_own_descriptors));
2697 // As the above, but uses DescriptorLookupCache and updates it when
2699 INLINE(int SearchWithCache(Name* name, Map* map));
2701 // Allocates a DescriptorArray, but returns the singleton
2702 // empty descriptor array object if number_of_descriptors is 0.
2703 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2704 int number_of_descriptors,
2707 DECLARE_CAST(DescriptorArray)
2709 // Constant for denoting key was not found.
2710 static const int kNotFound = -1;
2712 static const int kDescriptorLengthIndex = 0;
2713 static const int kEnumCacheIndex = 1;
2714 static const int kFirstIndex = 2;
2716 // The length of the "bridge" to the enum cache.
2717 static const int kEnumCacheBridgeLength = 2;
2718 static const int kEnumCacheBridgeCacheIndex = 0;
2719 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2721 // Layout description.
2722 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2723 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2724 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2726 // Layout description for the bridge array.
2727 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2729 // Layout of descriptor.
2730 static const int kDescriptorKey = 0;
2731 static const int kDescriptorDetails = 1;
2732 static const int kDescriptorValue = 2;
2733 static const int kDescriptorSize = 3;
2735 #if defined(DEBUG) || defined(OBJECT_PRINT)
2736 // For our gdb macros, we should perhaps change these in the future.
2739 // Print all the descriptors.
2740 void PrintDescriptors(std::ostream& os); // NOLINT
2744 // Is the descriptor array sorted and without duplicates?
2745 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2747 // Is the descriptor array consistent with the back pointers in targets?
2748 bool IsConsistentWithBackPointers(Map* current_map);
2750 // Are two DescriptorArrays equal?
2751 bool IsEqualTo(DescriptorArray* other);
2754 // Returns the fixed array length required to hold number_of_descriptors
2756 static int LengthFor(int number_of_descriptors) {
2757 return ToKeyIndex(number_of_descriptors);
2761 // WhitenessWitness is used to prove that a descriptor array is white
2762 // (unmarked), so incremental write barriers can be skipped because the
2763 // marking invariant cannot be broken and slots pointing into evacuation
2764 // candidates will be discovered when the object is scanned. A witness is
2765 // always stack-allocated right after creating an array. By allocating a
2766 // witness, incremental marking is globally disabled. The witness is then
2767 // passed along wherever needed to statically prove that the array is known to
2769 class WhitenessWitness {
2771 inline explicit WhitenessWitness(DescriptorArray* array);
2772 inline ~WhitenessWitness();
2775 IncrementalMarking* marking_;
2778 // An entry in a DescriptorArray, represented as an (array, index) pair.
2781 inline explicit Entry(DescriptorArray* descs, int index) :
2782 descs_(descs), index_(index) { }
2784 inline PropertyType type();
2785 inline Object* GetCallbackObject();
2788 DescriptorArray* descs_;
2792 // Conversion from descriptor number to array indices.
2793 static int ToKeyIndex(int descriptor_number) {
2794 return kFirstIndex +
2795 (descriptor_number * kDescriptorSize) +
2799 static int ToDetailsIndex(int descriptor_number) {
2800 return kFirstIndex +
2801 (descriptor_number * kDescriptorSize) +
2805 static int ToValueIndex(int descriptor_number) {
2806 return kFirstIndex +
2807 (descriptor_number * kDescriptorSize) +
2811 // Transfer a complete descriptor from the src descriptor array to this
2812 // descriptor array.
2813 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2815 inline void Set(int descriptor_number,
2817 const WhitenessWitness&);
2819 // Swap first and second descriptor.
2820 inline void SwapSortedKeys(int first, int second);
2822 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2826 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2828 template <SearchMode search_mode, typename T>
2829 inline int Search(T* array, Name* name, int valid_entries = 0,
2830 int* out_insertion_index = NULL);
2833 // HashTable is a subclass of FixedArray that implements a hash table
2834 // that uses open addressing and quadratic probing.
2836 // In order for the quadratic probing to work, elements that have not
2837 // yet been used and elements that have been deleted are
2838 // distinguished. Probing continues when deleted elements are
2839 // encountered and stops when unused elements are encountered.
2841 // - Elements with key == undefined have not been used yet.
2842 // - Elements with key == the_hole have been deleted.
2844 // The hash table class is parameterized with a Shape and a Key.
2845 // Shape must be a class with the following interface:
2846 // class ExampleShape {
2848 // // Tells whether key matches other.
2849 // static bool IsMatch(Key key, Object* other);
2850 // // Returns the hash value for key.
2851 // static uint32_t Hash(Key key);
2852 // // Returns the hash value for object.
2853 // static uint32_t HashForObject(Key key, Object* object);
2854 // // Convert key to an object.
2855 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2856 // // The prefix size indicates number of elements in the beginning
2857 // // of the backing storage.
2858 // static const int kPrefixSize = ..;
2859 // // The Element size indicates number of elements per entry.
2860 // static const int kEntrySize = ..;
2862 // The prefix size indicates an amount of memory in the
2863 // beginning of the backing storage that can be used for non-element
2864 // information by subclasses.
2866 template<typename Key>
2869 static const bool UsesSeed = false;
2870 static uint32_t Hash(Key key) { return 0; }
2871 static uint32_t SeededHash(Key key, uint32_t seed) {
2875 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2876 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2878 return HashForObject(key, object);
2883 class HashTableBase : public FixedArray {
2885 // Returns the number of elements in the hash table.
2886 inline int NumberOfElements();
2888 // Returns the number of deleted elements in the hash table.
2889 inline int NumberOfDeletedElements();
2891 // Returns the capacity of the hash table.
2892 inline int Capacity();
2894 // ElementAdded should be called whenever an element is added to a
2896 inline void ElementAdded();
2898 // ElementRemoved should be called whenever an element is removed from
2900 inline void ElementRemoved();
2901 inline void ElementsRemoved(int n);
2903 // Computes the required capacity for a table holding the given
2904 // number of elements. May be more than HashTable::kMaxCapacity.
2905 static inline int ComputeCapacity(int at_least_space_for);
2907 // Tells whether k is a real key. The hole and undefined are not allowed
2908 // as keys and can be used to indicate missing or deleted elements.
2909 inline bool IsKey(Object* k);
2911 // Compute the probe offset (quadratic probing).
2912 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2913 return (n + n * n) >> 1;
2916 static const int kNumberOfElementsIndex = 0;
2917 static const int kNumberOfDeletedElementsIndex = 1;
2918 static const int kCapacityIndex = 2;
2919 static const int kPrefixStartIndex = 3;
2921 // Constant used for denoting a absent entry.
2922 static const int kNotFound = -1;
2925 // Update the number of elements in the hash table.
2926 inline void SetNumberOfElements(int nof);
2928 // Update the number of deleted elements in the hash table.
2929 inline void SetNumberOfDeletedElements(int nod);
2931 // Returns probe entry.
2932 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2933 DCHECK(base::bits::IsPowerOfTwo32(size));
2934 return (hash + GetProbeOffset(number)) & (size - 1);
2937 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2938 return hash & (size - 1);
2941 inline static uint32_t NextProbe(
2942 uint32_t last, uint32_t number, uint32_t size) {
2943 return (last + number) & (size - 1);
2948 template <typename Derived, typename Shape, typename Key>
2949 class HashTable : public HashTableBase {
2952 inline uint32_t Hash(Key key) {
2953 if (Shape::UsesSeed) {
2954 return Shape::SeededHash(key, GetHeap()->HashSeed());
2956 return Shape::Hash(key);
2960 inline uint32_t HashForObject(Key key, Object* object) {
2961 if (Shape::UsesSeed) {
2962 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2964 return Shape::HashForObject(key, object);
2968 // Returns a new HashTable object.
2969 MUST_USE_RESULT static Handle<Derived> New(
2970 Isolate* isolate, int at_least_space_for,
2971 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2972 PretenureFlag pretenure = NOT_TENURED);
2974 DECLARE_CAST(HashTable)
2976 // Garbage collection support.
2977 void IteratePrefix(ObjectVisitor* visitor);
2978 void IterateElements(ObjectVisitor* visitor);
2980 // Find entry for key otherwise return kNotFound.
2981 inline int FindEntry(Key key);
2982 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2983 int FindEntry(Isolate* isolate, Key key);
2985 // Rehashes the table in-place.
2986 void Rehash(Key key);
2988 // Returns the key at entry.
2989 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2991 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
2992 static const int kEntrySize = Shape::kEntrySize;
2993 static const int kElementsStartOffset =
2994 kHeaderSize + kElementsStartIndex * kPointerSize;
2995 static const int kCapacityOffset =
2996 kHeaderSize + kCapacityIndex * kPointerSize;
2998 // Returns the index for an entry (of the key)
2999 static inline int EntryToIndex(int entry) {
3000 return (entry * kEntrySize) + kElementsStartIndex;
3004 friend class ObjectHashTable;
3006 // Find the entry at which to insert element with the given key that
3007 // has the given hash value.
3008 uint32_t FindInsertionEntry(uint32_t hash);
3010 // Attempt to shrink hash table after removal of key.
3011 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3013 // Ensure enough space for n additional elements.
3014 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3015 Handle<Derived> table,
3018 PretenureFlag pretenure = NOT_TENURED);
3020 // Sets the capacity of the hash table.
3021 void SetCapacity(int capacity) {
3022 // To scale a computed hash code to fit within the hash table, we
3023 // use bit-wise AND with a mask, so the capacity must be positive
3025 DCHECK(capacity > 0);
3026 DCHECK(capacity <= kMaxCapacity);
3027 set(kCapacityIndex, Smi::FromInt(capacity));
3030 // Maximal capacity of HashTable. Based on maximal length of underlying
3031 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3033 static const int kMaxCapacity =
3034 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3037 // Returns _expected_ if one of entries given by the first _probe_ probes is
3038 // equal to _expected_. Otherwise, returns the entry given by the probe
3040 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3042 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3044 // Rehashes this hash-table into the new table.
3045 void Rehash(Handle<Derived> new_table, Key key);
3049 // HashTableKey is an abstract superclass for virtual key behavior.
3050 class HashTableKey {
3052 // Returns whether the other object matches this key.
3053 virtual bool IsMatch(Object* other) = 0;
3054 // Returns the hash value for this key.
3055 virtual uint32_t Hash() = 0;
3056 // Returns the hash value for object.
3057 virtual uint32_t HashForObject(Object* key) = 0;
3058 // Returns the key object for storing into the hash table.
3059 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3061 virtual ~HashTableKey() {}
3065 class StringTableShape : public BaseShape<HashTableKey*> {
3067 static inline bool IsMatch(HashTableKey* key, Object* value) {
3068 return key->IsMatch(value);
3071 static inline uint32_t Hash(HashTableKey* key) {
3075 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3076 return key->HashForObject(object);
3079 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3081 static const int kPrefixSize = 0;
3082 static const int kEntrySize = 1;
3085 class SeqOneByteString;
3089 // No special elements in the prefix and the element size is 1
3090 // because only the string itself (the key) needs to be stored.
3091 class StringTable: public HashTable<StringTable,
3095 // Find string in the string table. If it is not there yet, it is
3096 // added. The return value is the string found.
3097 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3098 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3099 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3101 // Tries to internalize given string and returns string handle on success
3102 // or an empty handle otherwise.
3103 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3105 Handle<String> string);
3107 // Looks up a string that is equal to the given string and returns
3108 // string handle if it is found, or an empty handle otherwise.
3109 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3111 Handle<String> str);
3112 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3117 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3119 DECLARE_CAST(StringTable)
3122 template <bool seq_one_byte>
3123 friend class JsonParser;
3125 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3129 template <typename Derived, typename Shape, typename Key>
3130 class Dictionary: public HashTable<Derived, Shape, Key> {
3131 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3134 // Returns the value at entry.
3135 Object* ValueAt(int entry) {
3136 return this->get(Derived::EntryToIndex(entry) + 1);
3139 // Set the value for entry.
3140 void ValueAtPut(int entry, Object* value) {
3141 this->set(Derived::EntryToIndex(entry) + 1, value);
3144 // Returns the property details for the property at entry.
3145 PropertyDetails DetailsAt(int entry) {
3146 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3149 // Set the details for entry.
3150 void DetailsAtPut(int entry, PropertyDetails value) {
3151 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3154 // Returns true if property at given entry is deleted.
3155 bool IsDeleted(int entry) {
3156 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3159 // Delete a property from the dictionary.
3160 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3162 // Attempt to shrink the dictionary after deletion of key.
3163 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3164 Handle<Derived> dictionary,
3166 return DerivedHashTable::Shrink(dictionary, key);
3170 // TODO(dcarney): templatize or move to SeededNumberDictionary
3171 void CopyValuesTo(FixedArray* elements);
3173 // Returns the number of elements in the dictionary filtering out properties
3174 // with the specified attributes.
3175 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3177 // Returns the number of enumerable elements in the dictionary.
3178 int NumberOfEnumElements() {
3179 return NumberOfElementsFilterAttributes(
3180 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3183 // Returns true if the dictionary contains any elements that are non-writable,
3184 // non-configurable, non-enumerable, or have getters/setters.
3185 bool HasComplexElements();
3187 enum SortMode { UNSORTED, SORTED };
3189 // Fill in details for properties into storage.
3190 // Returns the number of properties added.
3191 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3192 SortMode sort_mode);
3194 // Copies enumerable keys to preallocated fixed array.
3195 void CopyEnumKeysTo(FixedArray* storage);
3197 // Accessors for next enumeration index.
3198 void SetNextEnumerationIndex(int index) {
3200 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3203 int NextEnumerationIndex() {
3204 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3207 // Creates a new dictionary.
3208 MUST_USE_RESULT static Handle<Derived> New(
3210 int at_least_space_for,
3211 PretenureFlag pretenure = NOT_TENURED);
3213 // Ensure enough space for n additional elements.
3214 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3217 void Print(std::ostream& os); // NOLINT
3219 // Returns the key (slow).
3220 Object* SlowReverseLookup(Object* value);
3222 // Sets the entry to (key, value) pair.
3223 inline void SetEntry(int entry,
3225 Handle<Object> value);
3226 inline void SetEntry(int entry,
3228 Handle<Object> value,
3229 PropertyDetails details);
3231 MUST_USE_RESULT static Handle<Derived> Add(
3232 Handle<Derived> dictionary,
3234 Handle<Object> value,
3235 PropertyDetails details);
3237 // Returns iteration indices array for the |dictionary|.
3238 // Values are direct indices in the |HashTable| array.
3239 static Handle<FixedArray> BuildIterationIndicesArray(
3240 Handle<Derived> dictionary);
3243 // Generic at put operation.
3244 MUST_USE_RESULT static Handle<Derived> AtPut(
3245 Handle<Derived> dictionary,
3247 Handle<Object> value);
3249 // Add entry to dictionary.
3250 static void AddEntry(
3251 Handle<Derived> dictionary,
3253 Handle<Object> value,
3254 PropertyDetails details,
3257 // Generate new enumeration indices to avoid enumeration index overflow.
3258 // Returns iteration indices array for the |dictionary|.
3259 static Handle<FixedArray> GenerateNewEnumerationIndices(
3260 Handle<Derived> dictionary);
3261 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3262 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3266 template <typename Derived, typename Shape>
3267 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3268 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3271 // Find entry for key, otherwise return kNotFound. Optimized version of
3272 // HashTable::FindEntry.
3273 int FindEntry(Handle<Name> key);
3277 template <typename Key>
3278 class BaseDictionaryShape : public BaseShape<Key> {
3280 template <typename Dictionary>
3281 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3282 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3283 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3284 return PropertyDetails(
3285 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3288 template <typename Dictionary>
3289 static inline void DetailsAtPut(Dictionary* dict, int entry,
3290 PropertyDetails value) {
3291 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3292 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3295 template <typename Dictionary>
3296 static bool IsDeleted(Dictionary* dict, int entry) {
3300 template <typename Dictionary>
3301 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3302 Handle<Object> value, PropertyDetails details);
3306 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3308 static inline bool IsMatch(Handle<Name> key, Object* other);
3309 static inline uint32_t Hash(Handle<Name> key);
3310 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3311 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3312 static const int kPrefixSize = 2;
3313 static const int kEntrySize = 3;
3314 static const bool kIsEnumerable = true;
3318 class NameDictionary
3319 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3320 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3324 DECLARE_CAST(NameDictionary)
3326 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3327 Handle<NameDictionary> dictionary);
3331 class GlobalDictionaryShape : public NameDictionaryShape {
3333 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3335 template <typename Dictionary>
3336 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3338 template <typename Dictionary>
3339 static inline void DetailsAtPut(Dictionary* dict, int entry,
3340 PropertyDetails value);
3342 template <typename Dictionary>
3343 static bool IsDeleted(Dictionary* dict, int entry);
3345 template <typename Dictionary>
3346 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3347 Handle<Object> value, PropertyDetails details);
3351 class GlobalDictionary
3352 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3354 DECLARE_CAST(GlobalDictionary)
3358 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3360 static inline bool IsMatch(uint32_t key, Object* other);
3361 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3362 static const int kEntrySize = 3;
3363 static const bool kIsEnumerable = false;
3367 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3369 static const bool UsesSeed = true;
3370 static const int kPrefixSize = 2;
3372 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3373 static inline uint32_t SeededHashForObject(uint32_t key,
3379 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3381 static const int kPrefixSize = 0;
3383 static inline uint32_t Hash(uint32_t key);
3384 static inline uint32_t HashForObject(uint32_t key, Object* object);
3388 class SeededNumberDictionary
3389 : public Dictionary<SeededNumberDictionary,
3390 SeededNumberDictionaryShape,
3393 DECLARE_CAST(SeededNumberDictionary)
3395 // Type specific at put (default NONE attributes is used when adding).
3396 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3397 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3398 Handle<Object> value, bool used_as_prototype);
3399 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3400 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3401 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3403 // Set an existing entry or add a new one if needed.
3404 // Return the updated dictionary.
3405 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3406 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3407 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3409 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3411 // If slow elements are required we will never go back to fast-case
3412 // for the elements kept in this dictionary. We require slow
3413 // elements if an element has been added at an index larger than
3414 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3415 // when defining a getter or setter with a number key.
3416 inline bool requires_slow_elements();
3417 inline void set_requires_slow_elements();
3419 // Get the value of the max number key that has been added to this
3420 // dictionary. max_number_key can only be called if
3421 // requires_slow_elements returns false.
3422 inline uint32_t max_number_key();
3425 static const int kRequiresSlowElementsMask = 1;
3426 static const int kRequiresSlowElementsTagSize = 1;
3427 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3431 class UnseededNumberDictionary
3432 : public Dictionary<UnseededNumberDictionary,
3433 UnseededNumberDictionaryShape,
3436 DECLARE_CAST(UnseededNumberDictionary)
3438 // Type specific at put (default NONE attributes is used when adding).
3439 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3440 Handle<UnseededNumberDictionary> dictionary,
3442 Handle<Object> value);
3443 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3444 Handle<UnseededNumberDictionary> dictionary,
3446 Handle<Object> value);
3448 // Set an existing entry or add a new one if needed.
3449 // Return the updated dictionary.
3450 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3451 Handle<UnseededNumberDictionary> dictionary,
3453 Handle<Object> value);
3457 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3459 static inline bool IsMatch(Handle<Object> key, Object* other);
3460 static inline uint32_t Hash(Handle<Object> key);
3461 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3462 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3463 static const int kPrefixSize = 0;
3464 static const int kEntrySize = 2;
3468 // ObjectHashTable maps keys that are arbitrary objects to object values by
3469 // using the identity hash of the key for hashing purposes.
3470 class ObjectHashTable: public HashTable<ObjectHashTable,
3471 ObjectHashTableShape,
3474 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3476 DECLARE_CAST(ObjectHashTable)
3478 // Attempt to shrink hash table after removal of key.
3479 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3480 Handle<ObjectHashTable> table,
3481 Handle<Object> key);
3483 // Looks up the value associated with the given key. The hole value is
3484 // returned in case the key is not present.
3485 Object* Lookup(Handle<Object> key);
3486 Object* Lookup(Handle<Object> key, int32_t hash);
3487 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3489 // Adds (or overwrites) the value associated with the given key.
3490 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3492 Handle<Object> value);
3493 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3494 Handle<Object> key, Handle<Object> value,
3497 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3498 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3501 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3502 Handle<Object> key, bool* was_present,
3506 friend class MarkCompactCollector;
3508 void AddEntry(int entry, Object* key, Object* value);
3509 void RemoveEntry(int entry);
3511 // Returns the index to the value of an entry.
3512 static inline int EntryToValueIndex(int entry) {
3513 return EntryToIndex(entry) + 1;
3518 // OrderedHashTable is a HashTable with Object keys that preserves
3519 // insertion order. There are Map and Set interfaces (OrderedHashMap
3520 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3522 // Only Object* keys are supported, with Object::SameValueZero() used as the
3523 // equality operator and Object::GetHash() for the hash function.
3525 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3526 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3527 // Originally attributed to Tyler Close.
3530 // [0]: bucket count
3531 // [1]: element count
3532 // [2]: deleted element count
3533 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3534 // offset into the data table (see below) where the
3535 // first item in this bucket is stored.
3536 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3537 // Capacity() * kEntrySize, where the first entrysize
3538 // items are handled by the derived class and the
3539 // item at kChainOffset is another entry into the
3540 // data table indicating the next entry in this hash
3543 // When we transition the table to a new version we obsolete it and reuse parts
3544 // of the memory to store information how to transition an iterator to the new
3547 // Memory layout for obsolete table:
3548 // [0]: bucket count
3549 // [1]: Next newer table
3550 // [2]: Number of removed holes or -1 when the table was cleared.
3551 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3552 // [3 + NumberOfRemovedHoles()..length]: Not used
3554 template<class Derived, class Iterator, int entrysize>
3555 class OrderedHashTable: public FixedArray {
3557 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3558 static Handle<Derived> Allocate(
3559 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3561 // Returns an OrderedHashTable (possibly |table|) with enough space
3562 // to add at least one new element.
3563 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3565 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3567 static Handle<Derived> Shrink(Handle<Derived> table);
3569 // Returns a new empty OrderedHashTable and records the clearing so that
3570 // exisiting iterators can be updated.
3571 static Handle<Derived> Clear(Handle<Derived> table);
3573 int NumberOfElements() {
3574 return Smi::cast(get(kNumberOfElementsIndex))->value();
3577 int NumberOfDeletedElements() {
3578 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3581 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3583 int NumberOfBuckets() {
3584 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3587 // Returns an index into |this| for the given entry.
3588 int EntryToIndex(int entry) {
3589 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3592 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3595 return !get(kNextTableIndex)->IsSmi();
3598 // The next newer table. This is only valid if the table is obsolete.
3599 Derived* NextTable() {
3600 return Derived::cast(get(kNextTableIndex));
3603 // When the table is obsolete we store the indexes of the removed holes.
3604 int RemovedIndexAt(int index) {
3605 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3608 static const int kNotFound = -1;
3609 static const int kMinCapacity = 4;
3611 static const int kNumberOfBucketsIndex = 0;
3612 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3613 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3614 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3615 static const int kNextTableIndex = kNumberOfElementsIndex;
3617 static const int kNumberOfBucketsOffset =
3618 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3619 static const int kNumberOfElementsOffset =
3620 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3621 static const int kNumberOfDeletedElementsOffset =
3622 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3623 static const int kHashTableStartOffset =
3624 kHeaderSize + kHashTableStartIndex * kPointerSize;
3625 static const int kNextTableOffset =
3626 kHeaderSize + kNextTableIndex * kPointerSize;
3628 static const int kEntrySize = entrysize + 1;
3629 static const int kChainOffset = entrysize;
3631 static const int kLoadFactor = 2;
3633 // NumberOfDeletedElements is set to kClearedTableSentinel when
3634 // the table is cleared, which allows iterator transitions to
3635 // optimize that case.
3636 static const int kClearedTableSentinel = -1;
3639 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3641 void SetNumberOfBuckets(int num) {
3642 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3645 void SetNumberOfElements(int num) {
3646 set(kNumberOfElementsIndex, Smi::FromInt(num));
3649 void SetNumberOfDeletedElements(int num) {
3650 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3654 return NumberOfBuckets() * kLoadFactor;
3657 void SetNextTable(Derived* next_table) {
3658 set(kNextTableIndex, next_table);
3661 void SetRemovedIndexAt(int index, int removed_index) {
3662 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3665 static const int kRemovedHolesIndex = kHashTableStartIndex;
3667 static const int kMaxCapacity =
3668 (FixedArray::kMaxLength - kHashTableStartIndex)
3669 / (1 + (kEntrySize * kLoadFactor));
3673 class JSSetIterator;
3676 class OrderedHashSet: public OrderedHashTable<
3677 OrderedHashSet, JSSetIterator, 1> {
3679 DECLARE_CAST(OrderedHashSet)
3683 class JSMapIterator;
3686 class OrderedHashMap
3687 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3689 DECLARE_CAST(OrderedHashMap)
3691 inline Object* ValueAt(int entry);
3693 static const int kValueOffset = 1;
3697 template <int entrysize>
3698 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3700 static inline bool IsMatch(Handle<Object> key, Object* other);
3701 static inline uint32_t Hash(Handle<Object> key);
3702 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3703 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3704 static const int kPrefixSize = 0;
3705 static const int kEntrySize = entrysize;
3709 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3710 // values. The table wraps the keys in weak cells and store values directly.
3711 // Thus it references keys weakly and values strongly.
3712 class WeakHashTable: public HashTable<WeakHashTable,
3713 WeakHashTableShape<2>,
3716 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3718 DECLARE_CAST(WeakHashTable)
3720 // Looks up the value associated with the given key. The hole value is
3721 // returned in case the key is not present.
3722 Object* Lookup(Handle<HeapObject> key);
3724 // Adds (or overwrites) the value associated with the given key. Mapping a
3725 // key to the hole value causes removal of the whole entry.
3726 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3727 Handle<HeapObject> key,
3728 Handle<HeapObject> value);
3730 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3733 friend class MarkCompactCollector;
3735 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3737 // Returns the index to the value of an entry.
3738 static inline int EntryToValueIndex(int entry) {
3739 return EntryToIndex(entry) + 1;
3744 // ScopeInfo represents information about different scopes of a source
3745 // program and the allocation of the scope's variables. Scope information
3746 // is stored in a compressed form in ScopeInfo objects and is used
3747 // at runtime (stack dumps, deoptimization, etc.).
3749 // This object provides quick access to scope info details for runtime
3751 class ScopeInfo : public FixedArray {
3753 DECLARE_CAST(ScopeInfo)
3755 // Return the type of this scope.
3756 ScopeType scope_type();
3758 // Does this scope call eval?
3761 // Return the language mode of this scope.
3762 LanguageMode language_mode();
3764 // Does this scope make a sloppy eval call?
3765 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3767 // Return the total number of locals allocated on the stack and in the
3768 // context. This includes the parameters that are allocated in the context.
3771 // Return the number of stack slots for code. This number consists of two
3773 // 1. One stack slot per stack allocated local.
3774 // 2. One stack slot for the function name if it is stack allocated.
3775 int StackSlotCount();
3777 // Return the number of context slots for code if a context is allocated. This
3778 // number consists of three parts:
3779 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3780 // 2. One context slot per context allocated local.
3781 // 3. One context slot for the function name if it is context allocated.
3782 // Parameters allocated in the context count as context allocated locals. If
3783 // no contexts are allocated for this scope ContextLength returns 0.
3784 int ContextLength();
3786 // Does this scope declare a "this" binding?
3789 // Does this scope declare a "this" binding, and the "this" binding is stack-
3790 // or context-allocated?
3791 bool HasAllocatedReceiver();
3793 // Is this scope the scope of a named function expression?
3794 bool HasFunctionName();
3796 // Return if this has context allocated locals.
3797 bool HasHeapAllocatedLocals();
3799 // Return if contexts are allocated for this scope.
3802 // Return if this is a function scope with "use asm".
3803 inline bool IsAsmModule();
3805 // Return if this is a nested function within an asm module scope.
3806 inline bool IsAsmFunction();
3808 inline bool HasSimpleParameters();
3810 // Return the function_name if present.
3811 String* FunctionName();
3813 // Return the name of the given parameter.
3814 String* ParameterName(int var);
3816 // Return the name of the given local.
3817 String* LocalName(int var);
3819 // Return the name of the given stack local.
3820 String* StackLocalName(int var);
3822 // Return the name of the given stack local.
3823 int StackLocalIndex(int var);
3825 // Return the name of the given context local.
3826 String* ContextLocalName(int var);
3828 // Return the mode of the given context local.
3829 VariableMode ContextLocalMode(int var);
3831 // Return the initialization flag of the given context local.
3832 InitializationFlag ContextLocalInitFlag(int var);
3834 // Return the initialization flag of the given context local.
3835 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3837 // Return true if this local was introduced by the compiler, and should not be
3838 // exposed to the user in a debugger.
3839 bool LocalIsSynthetic(int var);
3841 String* StrongModeFreeVariableName(int var);
3842 int StrongModeFreeVariableStartPosition(int var);
3843 int StrongModeFreeVariableEndPosition(int var);
3845 // Lookup support for serialized scope info. Returns the
3846 // the stack slot index for a given slot name if the slot is
3847 // present; otherwise returns a value < 0. The name must be an internalized
3849 int StackSlotIndex(String* name);
3851 // Lookup support for serialized scope info. Returns the
3852 // context slot index for a given slot name if the slot is present; otherwise
3853 // returns a value < 0. The name must be an internalized string.
3854 // If the slot is present and mode != NULL, sets *mode to the corresponding
3855 // mode for that variable.
3856 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3857 VariableMode* mode, VariableLocation* location,
3858 InitializationFlag* init_flag,
3859 MaybeAssignedFlag* maybe_assigned_flag);
3861 // Lookup the name of a certain context slot by its index.
3862 String* ContextSlotName(int slot_index);
3864 // Lookup support for serialized scope info. Returns the
3865 // parameter index for a given parameter name if the parameter is present;
3866 // otherwise returns a value < 0. The name must be an internalized string.
3867 int ParameterIndex(String* name);
3869 // Lookup support for serialized scope info. Returns the function context
3870 // slot index if the function name is present and context-allocated (named
3871 // function expressions, only), otherwise returns a value < 0. The name
3872 // must be an internalized string.
3873 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3875 // Lookup support for serialized scope info. Returns the receiver context
3876 // slot index if scope has a "this" binding, and the binding is
3877 // context-allocated. Otherwise returns a value < 0.
3878 int ReceiverContextSlotIndex();
3880 FunctionKind function_kind();
3882 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3883 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3885 // Serializes empty scope info.
3886 static ScopeInfo* Empty(Isolate* isolate);
3892 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3893 // numeric and occupies one array slot.
3894 // 1. A set of properties of the scope
3895 // 2. The number of parameters. This only applies to function scopes. For
3896 // non-function scopes this is 0.
3897 // 3. The number of non-parameter variables allocated on the stack.
3898 // 4. The number of non-parameter and parameter variables allocated in the
3900 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3903 V(StackLocalCount) \
3904 V(ContextLocalCount) \
3905 V(ContextGlobalCount) \
3906 V(StrongModeFreeVariableCount)
3908 #define FIELD_ACCESSORS(name) \
3909 inline void Set##name(int value); \
3911 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3912 #undef FIELD_ACCESSORS
3916 #define DECL_INDEX(name) k##name,
3917 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3922 // The layout of the variable part of a ScopeInfo is as follows:
3923 // 1. ParameterEntries:
3924 // This part stores the names of the parameters for function scopes. One
3925 // slot is used per parameter, so in total this part occupies
3926 // ParameterCount() slots in the array. For other scopes than function
3927 // scopes ParameterCount() is 0.
3928 // 2. StackLocalFirstSlot:
3929 // Index of a first stack slot for stack local. Stack locals belonging to
3930 // this scope are located on a stack at slots starting from this index.
3931 // 3. StackLocalEntries:
3932 // Contains the names of local variables that are allocated on the stack,
3933 // in increasing order of the stack slot index. First local variable has
3934 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3935 // One slot is used per stack local, so in total this part occupies
3936 // StackLocalCount() slots in the array.
3937 // 4. ContextLocalNameEntries:
3938 // Contains the names of local variables and parameters that are allocated
3939 // in the context. They are stored in increasing order of the context slot
3940 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3941 // context local, so in total this part occupies ContextLocalCount() slots
3943 // 5. ContextLocalInfoEntries:
3944 // Contains the variable modes and initialization flags corresponding to
3945 // the context locals in ContextLocalNameEntries. One slot is used per
3946 // context local, so in total this part occupies ContextLocalCount()
3947 // slots in the array.
3948 // 6. StrongModeFreeVariableNameEntries:
3949 // Stores the names of strong mode free variables.
3950 // 7. StrongModeFreeVariablePositionEntries:
3951 // Stores the locations (start and end position) of strong mode free
3953 // 8. RecieverEntryIndex:
3954 // If the scope binds a "this" value, one slot is reserved to hold the
3955 // context or stack slot index for the variable.
3956 // 9. FunctionNameEntryIndex:
3957 // If the scope belongs to a named function expression this part contains
3958 // information about the function variable. It always occupies two array
3959 // slots: a. The name of the function variable.
3960 // b. The context or stack slot index for the variable.
3961 int ParameterEntriesIndex();
3962 int StackLocalFirstSlotIndex();
3963 int StackLocalEntriesIndex();
3964 int ContextLocalNameEntriesIndex();
3965 int ContextGlobalNameEntriesIndex();
3966 int ContextLocalInfoEntriesIndex();
3967 int ContextGlobalInfoEntriesIndex();
3968 int StrongModeFreeVariableNameEntriesIndex();
3969 int StrongModeFreeVariablePositionEntriesIndex();
3970 int ReceiverEntryIndex();
3971 int FunctionNameEntryIndex();
3973 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
3974 VariableLocation* location, InitializationFlag* init_flag,
3975 MaybeAssignedFlag* maybe_assigned_flag);
3977 // Used for the function name variable for named function expressions, and for
3979 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
3981 // Properties of scopes.
3982 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
3983 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
3984 STATIC_ASSERT(LANGUAGE_END == 3);
3985 class LanguageModeField
3986 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
3987 class ReceiverVariableField
3988 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
3989 class FunctionVariableField
3990 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
3992 class FunctionVariableMode
3993 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
3994 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
3996 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
3997 class HasSimpleParametersField
3998 : public BitField<bool, AsmFunctionField::kNext, 1> {};
3999 class FunctionKindField
4000 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4002 // BitFields representing the encoded information for context locals in the
4003 // ContextLocalInfoEntries part.
4004 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4005 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4006 class ContextLocalMaybeAssignedFlag
4007 : public BitField<MaybeAssignedFlag, 4, 1> {};
4009 friend class ScopeIterator;
4013 // The cache for maps used by normalized (dictionary mode) objects.
4014 // Such maps do not have property descriptors, so a typical program
4015 // needs very limited number of distinct normalized maps.
4016 class NormalizedMapCache: public FixedArray {
4018 static Handle<NormalizedMapCache> New(Isolate* isolate);
4020 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4021 PropertyNormalizationMode mode);
4022 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4026 DECLARE_CAST(NormalizedMapCache)
4028 static inline bool IsNormalizedMapCache(const Object* obj);
4030 DECLARE_VERIFIER(NormalizedMapCache)
4032 static const int kEntries = 64;
4034 static inline int GetIndex(Handle<Map> map);
4036 // The following declarations hide base class methods.
4037 Object* get(int index);
4038 void set(int index, Object* value);
4042 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4043 // that is attached to code objects.
4044 class ByteArray: public FixedArrayBase {
4048 // Setter and getter.
4049 inline byte get(int index);
4050 inline void set(int index, byte value);
4052 // Treat contents as an int array.
4053 inline int get_int(int index);
4055 static int SizeFor(int length) {
4056 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4058 // We use byte arrays for free blocks in the heap. Given a desired size in
4059 // bytes that is a multiple of the word size and big enough to hold a byte
4060 // array, this function returns the number of elements a byte array should
4062 static int LengthFor(int size_in_bytes) {
4063 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4064 DCHECK(size_in_bytes >= kHeaderSize);
4065 return size_in_bytes - kHeaderSize;
4068 // Returns data start address.
4069 inline Address GetDataStartAddress();
4071 // Returns a pointer to the ByteArray object for a given data start address.
4072 static inline ByteArray* FromDataStartAddress(Address address);
4074 DECLARE_CAST(ByteArray)
4076 // Dispatched behavior.
4077 inline int ByteArraySize();
4078 DECLARE_PRINTER(ByteArray)
4079 DECLARE_VERIFIER(ByteArray)
4081 // Layout description.
4082 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4084 // Maximal memory consumption for a single ByteArray.
4085 static const int kMaxSize = 512 * MB;
4086 // Maximal length of a single ByteArray.
4087 static const int kMaxLength = kMaxSize - kHeaderSize;
4090 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4094 // BytecodeArray represents a sequence of interpreter bytecodes.
4095 class BytecodeArray : public FixedArrayBase {
4097 static int SizeFor(int length) {
4098 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4101 // Setter and getter
4102 inline byte get(int index);
4103 inline void set(int index, byte value);
4105 // Returns data start address.
4106 inline Address GetFirstBytecodeAddress();
4108 // Accessors for frame size and the number of locals
4109 inline int frame_size() const;
4110 inline void set_frame_size(int value);
4112 DECLARE_CAST(BytecodeArray)
4114 // Dispatched behavior.
4115 inline int BytecodeArraySize();
4117 DECLARE_PRINTER(BytecodeArray)
4118 DECLARE_VERIFIER(BytecodeArray)
4120 void Disassemble(std::ostream& os);
4122 // Layout description.
4123 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4124 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4126 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4128 // Maximal memory consumption for a single BytecodeArray.
4129 static const int kMaxSize = 512 * MB;
4130 // Maximal length of a single BytecodeArray.
4131 static const int kMaxLength = kMaxSize - kHeaderSize;
4134 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4138 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4139 // They look like heap objects (are heap object tagged and have a map) so that
4140 // the heap remains iterable. They have a size and a next pointer.
4141 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4142 // in the free list.
4143 class FreeSpace: public HeapObject {
4145 // [size]: size of the free space including the header.
4146 inline int size() const;
4147 inline void set_size(int value);
4149 inline int nobarrier_size() const;
4150 inline void nobarrier_set_size(int value);
4154 // Accessors for the next field.
4155 inline FreeSpace* next();
4156 inline FreeSpace** next_address();
4157 inline void set_next(FreeSpace* next);
4159 inline static FreeSpace* cast(HeapObject* obj);
4161 // Dispatched behavior.
4162 DECLARE_PRINTER(FreeSpace)
4163 DECLARE_VERIFIER(FreeSpace)
4165 // Layout description.
4166 // Size is smi tagged when it is stored.
4167 static const int kSizeOffset = HeapObject::kHeaderSize;
4168 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4171 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4175 // V has parameters (Type, type, TYPE, C type, element_size)
4176 #define TYPED_ARRAYS(V) \
4177 V(Uint8, uint8, UINT8, uint8_t, 1) \
4178 V(Int8, int8, INT8, int8_t, 1) \
4179 V(Uint16, uint16, UINT16, uint16_t, 2) \
4180 V(Int16, int16, INT16, int16_t, 2) \
4181 V(Uint32, uint32, UINT32, uint32_t, 4) \
4182 V(Int32, int32, INT32, int32_t, 4) \
4183 V(Float32, float32, FLOAT32, float, 4) \
4184 V(Float64, float64, FLOAT64, double, 8) \
4185 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4188 class FixedTypedArrayBase: public FixedArrayBase {
4190 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4191 DECL_ACCESSORS(base_pointer, Object)
4193 // [external_pointer]: Contains the offset between base_pointer and the start
4194 // of the data. If the base_pointer is a nullptr, the external_pointer
4195 // therefore points to the actual backing store.
4196 DECL_ACCESSORS(external_pointer, void)
4198 // Dispatched behavior.
4199 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4201 template <typename StaticVisitor>
4202 inline void FixedTypedArrayBaseIterateBody();
4204 DECLARE_CAST(FixedTypedArrayBase)
4206 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4207 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4208 static const int kHeaderSize =
4209 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4211 static const int kDataOffset = kHeaderSize;
4215 static inline int TypedArraySize(InstanceType type, int length);
4216 inline int TypedArraySize(InstanceType type);
4218 // Use with care: returns raw pointer into heap.
4219 inline void* DataPtr();
4221 inline int DataSize();
4224 static inline int ElementSize(InstanceType type);
4226 inline int DataSize(InstanceType type);
4228 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4232 template <class Traits>
4233 class FixedTypedArray: public FixedTypedArrayBase {
4235 typedef typename Traits::ElementType ElementType;
4236 static const InstanceType kInstanceType = Traits::kInstanceType;
4238 DECLARE_CAST(FixedTypedArray<Traits>)
4240 inline ElementType get_scalar(int index);
4241 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4242 inline void set(int index, ElementType value);
4244 static inline ElementType from_int(int value);
4245 static inline ElementType from_double(double value);
4247 // This accessor applies the correct conversion from Smi, HeapNumber
4249 void SetValue(uint32_t index, Object* value);
4251 DECLARE_PRINTER(FixedTypedArray)
4252 DECLARE_VERIFIER(FixedTypedArray)
4255 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4258 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4259 class Type##ArrayTraits { \
4260 public: /* NOLINT */ \
4261 typedef elementType ElementType; \
4262 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4263 static const char* Designator() { return #type " array"; } \
4264 static inline Handle<Object> ToHandle(Isolate* isolate, \
4265 elementType scalar); \
4266 static inline elementType defaultValue(); \
4269 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4271 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4273 #undef FIXED_TYPED_ARRAY_TRAITS
4276 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4277 // data for code generated by the Hydrogen/Lithium compiler. It also
4278 // contains information about functions that were inlined. If N different
4279 // functions were inlined then first N elements of the literal array will
4280 // contain these functions.
4283 class DeoptimizationInputData: public FixedArray {
4285 // Layout description. Indices in the array.
4286 static const int kTranslationByteArrayIndex = 0;
4287 static const int kInlinedFunctionCountIndex = 1;
4288 static const int kLiteralArrayIndex = 2;
4289 static const int kOsrAstIdIndex = 3;
4290 static const int kOsrPcOffsetIndex = 4;
4291 static const int kOptimizationIdIndex = 5;
4292 static const int kSharedFunctionInfoIndex = 6;
4293 static const int kWeakCellCacheIndex = 7;
4294 static const int kFirstDeoptEntryIndex = 8;
4296 // Offsets of deopt entry elements relative to the start of the entry.
4297 static const int kAstIdRawOffset = 0;
4298 static const int kTranslationIndexOffset = 1;
4299 static const int kArgumentsStackHeightOffset = 2;
4300 static const int kPcOffset = 3;
4301 static const int kDeoptEntrySize = 4;
4303 // Simple element accessors.
4304 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4305 inline type* name(); \
4306 inline void Set##name(type* value);
4308 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4309 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4310 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4311 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4312 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4313 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4314 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4315 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4317 #undef DECLARE_ELEMENT_ACCESSORS
4319 // Accessors for elements of the ith deoptimization entry.
4320 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4321 inline type* name(int i); \
4322 inline void Set##name(int i, type* value);
4324 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4325 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4326 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4327 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4329 #undef DECLARE_ENTRY_ACCESSORS
4331 inline BailoutId AstId(int i);
4333 inline void SetAstId(int i, BailoutId value);
4335 inline int DeoptCount();
4337 // Allocates a DeoptimizationInputData.
4338 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4339 int deopt_entry_count,
4340 PretenureFlag pretenure);
4342 DECLARE_CAST(DeoptimizationInputData)
4344 #ifdef ENABLE_DISASSEMBLER
4345 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4349 static int IndexForEntry(int i) {
4350 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4354 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4358 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4359 // data for code generated by the full compiler.
4360 // The format of the these objects is
4361 // [i * 2]: Ast ID for ith deoptimization.
4362 // [i * 2 + 1]: PC and state of ith deoptimization
4363 class DeoptimizationOutputData: public FixedArray {
4365 inline int DeoptPoints();
4367 inline BailoutId AstId(int index);
4369 inline void SetAstId(int index, BailoutId id);
4371 inline Smi* PcAndState(int index);
4372 inline void SetPcAndState(int index, Smi* offset);
4374 static int LengthOfFixedArray(int deopt_points) {
4375 return deopt_points * 2;
4378 // Allocates a DeoptimizationOutputData.
4379 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4380 int number_of_deopt_points,
4381 PretenureFlag pretenure);
4383 DECLARE_CAST(DeoptimizationOutputData)
4385 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4386 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4391 // HandlerTable is a fixed array containing entries for exception handlers in
4392 // the code object it is associated with. The tables comes in two flavors:
4393 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4394 // exception handler and a range representing the try-block covered by that
4395 // handler. Layout looks as follows:
4396 // [ range-start , range-end , handler-offset , stack-depth ]
4397 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4398 // per call-site that could throw an exception. Layout looks as follows:
4399 // [ return-address-offset , handler-offset ]
4400 class HandlerTable : public FixedArray {
4402 // Conservative prediction whether a given handler will locally catch an
4403 // exception or cause a re-throw to outside the code boundary. Since this is
4404 // undecidable it is merely an approximation (e.g. useful for debugger).
4405 enum CatchPrediction { UNCAUGHT, CAUGHT };
4407 // Accessors for handler table based on ranges.
4408 inline void SetRangeStart(int index, int value);
4409 inline void SetRangeEnd(int index, int value);
4410 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4411 inline void SetRangeDepth(int index, int value);
4413 // Accessors for handler table based on return addresses.
4414 inline void SetReturnOffset(int index, int value);
4415 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4417 // Lookup handler in a table based on ranges.
4418 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4420 // Lookup handler in a table based on return addresses.
4421 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4423 // Returns the required length of the underlying fixed array.
4424 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4425 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4427 DECLARE_CAST(HandlerTable)
4429 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4430 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4431 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4435 // Layout description for handler table based on ranges.
4436 static const int kRangeStartIndex = 0;
4437 static const int kRangeEndIndex = 1;
4438 static const int kRangeHandlerIndex = 2;
4439 static const int kRangeDepthIndex = 3;
4440 static const int kRangeEntrySize = 4;
4442 // Layout description for handler table based on return addresses.
4443 static const int kReturnOffsetIndex = 0;
4444 static const int kReturnHandlerIndex = 1;
4445 static const int kReturnEntrySize = 2;
4447 // Encoding of the {handler} field.
4448 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4449 class HandlerOffsetField : public BitField<int, 1, 30> {};
4453 // Code describes objects with on-the-fly generated machine code.
4454 class Code: public HeapObject {
4456 // Opaque data type for encapsulating code flags like kind, inline
4457 // cache state, and arguments count.
4458 typedef uint32_t Flags;
4460 #define NON_IC_KIND_LIST(V) \
4462 V(OPTIMIZED_FUNCTION) \
4468 #define IC_KIND_LIST(V) \
4479 #define CODE_KIND_LIST(V) \
4480 NON_IC_KIND_LIST(V) \
4484 #define DEFINE_CODE_KIND_ENUM(name) name,
4485 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4486 #undef DEFINE_CODE_KIND_ENUM
4490 // No more than 16 kinds. The value is currently encoded in four bits in
4492 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4494 static const char* Kind2String(Kind kind);
4502 static const int kPrologueOffsetNotSet = -1;
4504 #ifdef ENABLE_DISASSEMBLER
4506 static const char* ICState2String(InlineCacheState state);
4507 static const char* StubType2String(StubType type);
4508 static void PrintExtraICState(std::ostream& os, // NOLINT
4509 Kind kind, ExtraICState extra);
4510 void Disassemble(const char* name, std::ostream& os); // NOLINT
4511 #endif // ENABLE_DISASSEMBLER
4513 // [instruction_size]: Size of the native instructions
4514 inline int instruction_size() const;
4515 inline void set_instruction_size(int value);
4517 // [relocation_info]: Code relocation information
4518 DECL_ACCESSORS(relocation_info, ByteArray)
4519 void InvalidateRelocation();
4520 void InvalidateEmbeddedObjects();
4522 // [handler_table]: Fixed array containing offsets of exception handlers.
4523 DECL_ACCESSORS(handler_table, FixedArray)
4525 // [deoptimization_data]: Array containing data for deopt.
4526 DECL_ACCESSORS(deoptimization_data, FixedArray)
4528 // [raw_type_feedback_info]: This field stores various things, depending on
4529 // the kind of the code object.
4530 // FUNCTION => type feedback information.
4531 // STUB and ICs => major/minor key as Smi.
4532 DECL_ACCESSORS(raw_type_feedback_info, Object)
4533 inline Object* type_feedback_info();
4534 inline void set_type_feedback_info(
4535 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4536 inline uint32_t stub_key();
4537 inline void set_stub_key(uint32_t key);
4539 // [next_code_link]: Link for lists of optimized or deoptimized code.
4540 // Note that storage for this field is overlapped with typefeedback_info.
4541 DECL_ACCESSORS(next_code_link, Object)
4543 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4544 // field does not have to be traced during garbage collection since
4545 // it is only used by the garbage collector itself.
4546 DECL_ACCESSORS(gc_metadata, Object)
4548 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4549 // at the moment when this object was created.
4550 inline void set_ic_age(int count);
4551 inline int ic_age() const;
4553 // [prologue_offset]: Offset of the function prologue, used for aging
4554 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4555 inline int prologue_offset() const;
4556 inline void set_prologue_offset(int offset);
4558 // [constant_pool offset]: Offset of the constant pool.
4559 // Valid for FLAG_enable_embedded_constant_pool only
4560 inline int constant_pool_offset() const;
4561 inline void set_constant_pool_offset(int offset);
4563 // Unchecked accessors to be used during GC.
4564 inline ByteArray* unchecked_relocation_info();
4566 inline int relocation_size();
4568 // [flags]: Various code flags.
4569 inline Flags flags();
4570 inline void set_flags(Flags flags);
4572 // [flags]: Access to specific code flags.
4574 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4575 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4577 inline StubType type(); // Only valid for monomorphic IC stubs.
4579 // Testers for IC stub kinds.
4580 inline bool is_inline_cache_stub();
4581 inline bool is_debug_stub();
4582 inline bool is_handler();
4583 inline bool is_load_stub();
4584 inline bool is_keyed_load_stub();
4585 inline bool is_store_stub();
4586 inline bool is_keyed_store_stub();
4587 inline bool is_call_stub();
4588 inline bool is_binary_op_stub();
4589 inline bool is_compare_ic_stub();
4590 inline bool is_compare_nil_ic_stub();
4591 inline bool is_to_boolean_ic_stub();
4592 inline bool is_keyed_stub();
4593 inline bool is_optimized_code();
4594 inline bool embeds_maps_weakly();
4596 inline bool IsCodeStubOrIC();
4597 inline bool IsJavaScriptCode();
4599 inline void set_raw_kind_specific_flags1(int value);
4600 inline void set_raw_kind_specific_flags2(int value);
4602 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4603 // object was generated by either the hydrogen or the TurboFan optimizing
4604 // compiler (but it may not be an optimized function).
4605 inline bool is_crankshafted();
4606 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4607 inline void set_is_crankshafted(bool value);
4609 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4610 // code object was generated by the TurboFan optimizing compiler.
4611 inline bool is_turbofanned();
4612 inline void set_is_turbofanned(bool value);
4614 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4615 // embedded objects in code should be treated weakly.
4616 inline bool can_have_weak_objects();
4617 inline void set_can_have_weak_objects(bool value);
4619 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4620 // deoptimization support.
4621 inline bool has_deoptimization_support();
4622 inline void set_has_deoptimization_support(bool value);
4624 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4625 // been compiled with debug break slots.
4626 inline bool has_debug_break_slots();
4627 inline void set_has_debug_break_slots(bool value);
4629 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4630 // reloc info includes runtime and external references to support
4631 // serialization/deserialization.
4632 inline bool has_reloc_info_for_serialization();
4633 inline void set_has_reloc_info_for_serialization(bool value);
4635 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4636 // how long the function has been marked for OSR and therefore which
4637 // level of loop nesting we are willing to do on-stack replacement
4639 inline void set_allow_osr_at_loop_nesting_level(int level);
4640 inline int allow_osr_at_loop_nesting_level();
4642 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4643 // the code object was seen on the stack with no IC patching going on.
4644 inline int profiler_ticks();
4645 inline void set_profiler_ticks(int ticks);
4647 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4648 // For builtins, tells which builtin index it has.
4649 // Note that builtins can have a code kind other than BUILTIN, which means
4650 // that for arbitrary code objects, this index value may be random garbage.
4651 // To verify in that case, compare the code object to the indexed builtin.
4652 inline int builtin_index();
4653 inline void set_builtin_index(int id);
4655 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4656 // reserved in the code prologue.
4657 inline unsigned stack_slots();
4658 inline void set_stack_slots(unsigned slots);
4660 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4661 // the instruction stream where the safepoint table starts.
4662 inline unsigned safepoint_table_offset();
4663 inline void set_safepoint_table_offset(unsigned offset);
4665 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4666 // instruction stream where the back edge table starts.
4667 inline unsigned back_edge_table_offset();
4668 inline void set_back_edge_table_offset(unsigned offset);
4670 inline bool back_edges_patched_for_osr();
4672 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4673 inline uint16_t to_boolean_state();
4675 // [has_function_cache]: For kind STUB tells whether there is a function
4676 // cache is passed to the stub.
4677 inline bool has_function_cache();
4678 inline void set_has_function_cache(bool flag);
4681 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4682 // the code is going to be deoptimized because of dead embedded maps.
4683 inline bool marked_for_deoptimization();
4684 inline void set_marked_for_deoptimization(bool flag);
4686 // [constant_pool]: The constant pool for this function.
4687 inline Address constant_pool();
4689 // Get the safepoint entry for the given pc.
4690 SafepointEntry GetSafepointEntry(Address pc);
4692 // Find an object in a stub with a specified map
4693 Object* FindNthObject(int n, Map* match_map);
4695 // Find the first allocation site in an IC stub.
4696 AllocationSite* FindFirstAllocationSite();
4698 // Find the first map in an IC stub.
4699 Map* FindFirstMap();
4700 void FindAllMaps(MapHandleList* maps);
4702 // Find the first handler in an IC stub.
4703 Code* FindFirstHandler();
4705 // Find |length| handlers and put them into |code_list|. Returns false if not
4706 // enough handlers can be found.
4707 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4709 // Find the handler for |map|.
4710 MaybeHandle<Code> FindHandlerForMap(Map* map);
4712 // Find the first name in an IC stub.
4713 Name* FindFirstName();
4715 class FindAndReplacePattern;
4716 // For each (map-to-find, object-to-replace) pair in the pattern, this
4717 // function replaces the corresponding placeholder in the code with the
4718 // object-to-replace. The function assumes that pairs in the pattern come in
4719 // the same order as the placeholders in the code.
4720 // If the placeholder is a weak cell, then the value of weak cell is matched
4721 // against the map-to-find.
4722 void FindAndReplace(const FindAndReplacePattern& pattern);
4724 // The entire code object including its header is copied verbatim to the
4725 // snapshot so that it can be written in one, fast, memcpy during
4726 // deserialization. The deserializer will overwrite some pointers, rather
4727 // like a runtime linker, but the random allocation addresses used in the
4728 // mksnapshot process would still be present in the unlinked snapshot data,
4729 // which would make snapshot production non-reproducible. This method wipes
4730 // out the to-be-overwritten header data for reproducible snapshots.
4731 inline void WipeOutHeader();
4733 // Flags operations.
4734 static inline Flags ComputeFlags(
4735 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4736 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4737 CacheHolderFlag holder = kCacheOnReceiver);
4739 static inline Flags ComputeMonomorphicFlags(
4740 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4741 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4743 static inline Flags ComputeHandlerFlags(
4744 Kind handler_kind, StubType type = NORMAL,
4745 CacheHolderFlag holder = kCacheOnReceiver);
4747 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4748 static inline StubType ExtractTypeFromFlags(Flags flags);
4749 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4750 static inline Kind ExtractKindFromFlags(Flags flags);
4751 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4753 static inline Flags RemoveTypeFromFlags(Flags flags);
4754 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4756 // Convert a target address into a code object.
4757 static inline Code* GetCodeFromTargetAddress(Address address);
4759 // Convert an entry address into an object.
4760 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4762 // Returns the address of the first instruction.
4763 inline byte* instruction_start();
4765 // Returns the address right after the last instruction.
4766 inline byte* instruction_end();
4768 // Returns the size of the instructions, padding, and relocation information.
4769 inline int body_size();
4771 // Returns the address of the first relocation info (read backwards!).
4772 inline byte* relocation_start();
4774 // Code entry point.
4775 inline byte* entry();
4777 // Returns true if pc is inside this object's instructions.
4778 inline bool contains(byte* pc);
4780 // Relocate the code by delta bytes. Called to signal that this code
4781 // object has been moved by delta bytes.
4782 void Relocate(intptr_t delta);
4784 // Migrate code described by desc.
4785 void CopyFrom(const CodeDesc& desc);
4787 // Returns the object size for a given body (used for allocation).
4788 static int SizeFor(int body_size) {
4789 DCHECK_SIZE_TAG_ALIGNED(body_size);
4790 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4793 // Calculate the size of the code object to report for log events. This takes
4794 // the layout of the code object into account.
4795 inline int ExecutableSize();
4797 // Locating source position.
4798 int SourcePosition(Address pc);
4799 int SourceStatementPosition(Address pc);
4803 // Dispatched behavior.
4804 inline int CodeSize();
4805 inline void CodeIterateBody(ObjectVisitor* v);
4807 template<typename StaticVisitor>
4808 inline void CodeIterateBody(Heap* heap);
4810 DECLARE_PRINTER(Code)
4811 DECLARE_VERIFIER(Code)
4813 void ClearInlineCaches();
4814 void ClearInlineCaches(Kind kind);
4816 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4817 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4819 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4821 kToBeExecutedOnceCodeAge = -3,
4822 kNotExecutedCodeAge = -2,
4823 kExecutedOnceCodeAge = -1,
4825 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4827 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4828 kLastCodeAge = kAfterLastCodeAge - 1,
4829 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4830 kIsOldCodeAge = kSexagenarianCodeAge,
4831 kPreAgedCodeAge = kIsOldCodeAge - 1
4833 #undef DECLARE_CODE_AGE_ENUM
4835 // Code aging. Indicates how many full GCs this code has survived without
4836 // being entered through the prologue. Used to determine when it is
4837 // relatively safe to flush this code object and replace it with the lazy
4838 // compilation stub.
4839 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4840 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4841 void MakeYoung(Isolate* isolate);
4842 void MarkToBeExecutedOnce(Isolate* isolate);
4843 void MakeOlder(MarkingParity);
4844 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4847 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4848 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4851 void PrintDeoptLocation(FILE* out, Address pc);
4852 bool CanDeoptAt(Address pc);
4855 void VerifyEmbeddedObjectsDependency();
4859 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4860 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4861 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4864 inline bool CanContainWeakObjects();
4866 inline bool IsWeakObject(Object* object);
4868 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4870 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4871 WeakCell* CachedWeakCell();
4873 // Max loop nesting marker used to postpose OSR. We don't take loop
4874 // nesting that is deeper than 5 levels into account.
4875 static const int kMaxLoopNestingMarker = 6;
4877 static const int kConstantPoolSize =
4878 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4880 // Layout description.
4881 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4882 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4883 static const int kDeoptimizationDataOffset =
4884 kHandlerTableOffset + kPointerSize;
4885 // For FUNCTION kind, we store the type feedback info here.
4886 static const int kTypeFeedbackInfoOffset =
4887 kDeoptimizationDataOffset + kPointerSize;
4888 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4889 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4890 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4891 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4892 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4893 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4894 static const int kKindSpecificFlags2Offset =
4895 kKindSpecificFlags1Offset + kIntSize;
4896 // Note: We might be able to squeeze this into the flags above.
4897 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4898 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4899 static const int kHeaderPaddingStart =
4900 kConstantPoolOffset + kConstantPoolSize;
4902 // Add padding to align the instruction start following right after
4903 // the Code object header.
4904 static const int kHeaderSize =
4905 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4907 // Byte offsets within kKindSpecificFlags1Offset.
4908 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4909 class FullCodeFlagsHasDeoptimizationSupportField:
4910 public BitField<bool, 0, 1> {}; // NOLINT
4911 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4912 class FullCodeFlagsHasRelocInfoForSerialization
4913 : public BitField<bool, 2, 1> {};
4914 // Bit 3 in this bitfield is unused.
4915 class ProfilerTicksField : public BitField<int, 4, 28> {};
4917 // Flags layout. BitField<type, shift, size>.
4918 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4919 class TypeField : public BitField<StubType, 4, 1> {};
4920 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4921 class KindField : public BitField<Kind, 7, 4> {};
4922 class ExtraICStateField: public BitField<ExtraICState, 11,
4923 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4925 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4926 static const int kStackSlotsFirstBit = 0;
4927 static const int kStackSlotsBitCount = 24;
4928 static const int kHasFunctionCacheBit =
4929 kStackSlotsFirstBit + kStackSlotsBitCount;
4930 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4931 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4932 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4934 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4935 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4937 class StackSlotsField: public BitField<int,
4938 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4939 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4941 class MarkedForDeoptimizationField
4942 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
4943 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
4945 class CanHaveWeakObjectsField
4946 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
4948 // KindSpecificFlags2 layout (ALL)
4949 static const int kIsCrankshaftedBit = 0;
4950 class IsCrankshaftedField: public BitField<bool,
4951 kIsCrankshaftedBit, 1> {}; // NOLINT
4953 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
4954 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
4955 static const int kSafepointTableOffsetBitCount = 30;
4957 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
4958 kSafepointTableOffsetBitCount <= 32);
4959 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
4961 class SafepointTableOffsetField: public BitField<int,
4962 kSafepointTableOffsetFirstBit,
4963 kSafepointTableOffsetBitCount> {}; // NOLINT
4965 // KindSpecificFlags2 layout (FUNCTION)
4966 class BackEdgeTableOffsetField: public BitField<int,
4967 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
4968 class AllowOSRAtLoopNestingLevelField: public BitField<int,
4969 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
4970 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
4972 static const int kArgumentsBits = 16;
4973 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
4975 // This constant should be encodable in an ARM instruction.
4976 static const int kFlagsNotUsedInLookup =
4977 TypeField::kMask | CacheHolderField::kMask;
4980 friend class RelocIterator;
4981 friend class Deoptimizer; // For FindCodeAgeSequence.
4983 void ClearInlineCaches(Kind* kind);
4986 byte* FindCodeAgeSequence();
4987 static void GetCodeAgeAndParity(Code* code, Age* age,
4988 MarkingParity* parity);
4989 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
4990 MarkingParity* parity);
4991 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
4993 // Code aging -- platform-specific
4994 static void PatchPlatformCodeAge(Isolate* isolate,
4995 byte* sequence, Age age,
4996 MarkingParity parity);
4998 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5002 // This class describes the layout of dependent codes array of a map. The
5003 // array is partitioned into several groups of dependent codes. Each group
5004 // contains codes with the same dependency on the map. The array has the
5005 // following layout for n dependency groups:
5007 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5008 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5009 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5011 // The first n elements are Smis, each of them specifies the number of codes
5012 // in the corresponding group. The subsequent elements contain grouped code
5013 // objects in weak cells. The suffix of the array can be filled with the
5014 // undefined value if the number of codes is less than the length of the
5015 // array. The order of the code objects within a group is not preserved.
5017 // All code indexes used in the class are counted starting from the first
5018 // code object of the first group. In other words, code index 0 corresponds
5019 // to array index n = kCodesStartIndex.
5021 class DependentCode: public FixedArray {
5023 enum DependencyGroup {
5024 // Group of code that weakly embed this map and depend on being
5025 // deoptimized when the map is garbage collected.
5027 // Group of code that embed a transition to this map, and depend on being
5028 // deoptimized when the transition is replaced by a new version.
5030 // Group of code that omit run-time prototype checks for prototypes
5031 // described by this map. The group is deoptimized whenever an object
5032 // described by this map changes shape (and transitions to a new map),
5033 // possibly invalidating the assumptions embedded in the code.
5034 kPrototypeCheckGroup,
5035 // Group of code that depends on global property values in property cells
5036 // not being changed.
5037 kPropertyCellChangedGroup,
5038 // Group of code that omit run-time type checks for the field(s) introduced
5041 // Group of code that omit run-time type checks for initial maps of
5043 kInitialMapChangedGroup,
5044 // Group of code that depends on tenuring information in AllocationSites
5045 // not being changed.
5046 kAllocationSiteTenuringChangedGroup,
5047 // Group of code that depends on element transition information in
5048 // AllocationSites not being changed.
5049 kAllocationSiteTransitionChangedGroup
5052 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5054 // Array for holding the index of the first code object of each group.
5055 // The last element stores the total number of code objects.
5056 class GroupStartIndexes {
5058 explicit GroupStartIndexes(DependentCode* entries);
5059 void Recompute(DependentCode* entries);
5060 int at(int i) { return start_indexes_[i]; }
5061 int number_of_entries() { return start_indexes_[kGroupCount]; }
5063 int start_indexes_[kGroupCount + 1];
5066 bool Contains(DependencyGroup group, WeakCell* code_cell);
5068 static Handle<DependentCode> InsertCompilationDependencies(
5069 Handle<DependentCode> entries, DependencyGroup group,
5070 Handle<Foreign> info);
5072 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5073 DependencyGroup group,
5074 Handle<WeakCell> code_cell);
5076 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5077 WeakCell* code_cell);
5079 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5082 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5083 DependentCode::DependencyGroup group);
5085 bool MarkCodeForDeoptimization(Isolate* isolate,
5086 DependentCode::DependencyGroup group);
5088 // The following low-level accessors should only be used by this class
5089 // and the mark compact collector.
5090 inline int number_of_entries(DependencyGroup group);
5091 inline void set_number_of_entries(DependencyGroup group, int value);
5092 inline Object* object_at(int i);
5093 inline void set_object_at(int i, Object* object);
5094 inline void clear_at(int i);
5095 inline void copy(int from, int to);
5096 DECLARE_CAST(DependentCode)
5098 static const char* DependencyGroupName(DependencyGroup group);
5099 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5102 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5103 DependencyGroup group,
5104 Handle<Object> object);
5105 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5106 // Make a room at the end of the given group by moving out the first
5107 // code objects of the subsequent groups.
5108 inline void ExtendGroup(DependencyGroup group);
5109 // Compact by removing cleared weak cells and return true if there was
5110 // any cleared weak cell.
5112 static int Grow(int number_of_entries) {
5113 if (number_of_entries < 5) return number_of_entries + 1;
5114 return number_of_entries * 5 / 4;
5116 static const int kCodesStartIndex = kGroupCount;
5120 class PrototypeInfo;
5123 // All heap objects have a Map that describes their structure.
5124 // A Map contains information about:
5125 // - Size information about the object
5126 // - How to iterate over an object (for garbage collection)
5127 class Map: public HeapObject {
5130 // Size in bytes or kVariableSizeSentinel if instances do not have
5132 inline int instance_size();
5133 inline void set_instance_size(int value);
5135 // Only to clear an unused byte, remove once byte is used.
5136 inline void clear_unused();
5138 // [inobject_properties_or_constructor_function_index]: Provides access
5139 // to the inobject properties in case of JSObject maps, or the constructor
5140 // function index in case of primitive maps.
5141 inline int inobject_properties_or_constructor_function_index();
5142 inline void set_inobject_properties_or_constructor_function_index(int value);
5143 // Count of properties allocated in the object (JSObject only).
5144 inline int GetInObjectProperties();
5145 inline void SetInObjectProperties(int value);
5146 // Index of the constructor function in the native context (primitives only),
5147 // or the special sentinel value to indicate that there is no object wrapper
5148 // for the primitive (i.e. in case of null or undefined).
5149 static const int kNoConstructorFunctionIndex = 0;
5150 inline int GetConstructorFunctionIndex();
5151 inline void SetConstructorFunctionIndex(int value);
5154 inline InstanceType instance_type();
5155 inline void set_instance_type(InstanceType value);
5157 // Tells how many unused property fields are available in the
5158 // instance (only used for JSObject in fast mode).
5159 inline int unused_property_fields();
5160 inline void set_unused_property_fields(int value);
5163 inline byte bit_field() const;
5164 inline void set_bit_field(byte value);
5167 inline byte bit_field2() const;
5168 inline void set_bit_field2(byte value);
5171 inline uint32_t bit_field3() const;
5172 inline void set_bit_field3(uint32_t bits);
5174 class EnumLengthBits: public BitField<int,
5175 0, kDescriptorIndexBitCount> {}; // NOLINT
5176 class NumberOfOwnDescriptorsBits: public BitField<int,
5177 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5178 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5179 class DictionaryMap : public BitField<bool, 20, 1> {};
5180 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5181 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5182 class Deprecated : public BitField<bool, 23, 1> {};
5183 class IsUnstable : public BitField<bool, 24, 1> {};
5184 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5185 class IsStrong : public BitField<bool, 26, 1> {};
5188 // Keep this bit field at the very end for better code in
5189 // Builtins::kJSConstructStubGeneric stub.
5190 // This counter is used for in-object slack tracking and for map aging.
5191 // The in-object slack tracking is considered enabled when the counter is
5192 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5193 class Counter : public BitField<int, 28, 4> {};
5194 static const int kSlackTrackingCounterStart = 14;
5195 static const int kSlackTrackingCounterEnd = 8;
5196 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5197 static const int kRetainingCounterEnd = 0;
5199 // Tells whether the object in the prototype property will be used
5200 // for instances created from this function. If the prototype
5201 // property is set to a value that is not a JSObject, the prototype
5202 // property will not be used to create instances of the function.
5203 // See ECMA-262, 13.2.2.
5204 inline void set_non_instance_prototype(bool value);
5205 inline bool has_non_instance_prototype();
5207 // Tells whether function has special prototype property. If not, prototype
5208 // property will not be created when accessed (will return undefined),
5209 // and construction from this function will not be allowed.
5210 inline void set_function_with_prototype(bool value);
5211 inline bool function_with_prototype();
5213 // Tells whether the instance with this map should be ignored by the
5214 // Object.getPrototypeOf() function and the __proto__ accessor.
5215 inline void set_is_hidden_prototype();
5216 inline bool is_hidden_prototype();
5218 // Records and queries whether the instance has a named interceptor.
5219 inline void set_has_named_interceptor();
5220 inline bool has_named_interceptor();
5222 // Records and queries whether the instance has an indexed interceptor.
5223 inline void set_has_indexed_interceptor();
5224 inline bool has_indexed_interceptor();
5226 // Tells whether the instance is undetectable.
5227 // An undetectable object is a special class of JSObject: 'typeof' operator
5228 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5229 // a normal JS object. It is useful for implementing undetectable
5230 // document.all in Firefox & Safari.
5231 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5232 inline void set_is_undetectable();
5233 inline bool is_undetectable();
5235 // Tells whether the instance has a call-as-function handler.
5236 inline void set_is_observed();
5237 inline bool is_observed();
5239 inline void set_is_strong();
5240 inline bool is_strong();
5241 inline void set_is_extensible(bool value);
5242 inline bool is_extensible();
5243 inline void set_is_prototype_map(bool value);
5244 inline bool is_prototype_map() const;
5246 inline void set_elements_kind(ElementsKind elements_kind);
5247 inline ElementsKind elements_kind();
5249 // Tells whether the instance has fast elements that are only Smis.
5250 inline bool has_fast_smi_elements();
5252 // Tells whether the instance has fast elements.
5253 inline bool has_fast_object_elements();
5254 inline bool has_fast_smi_or_object_elements();
5255 inline bool has_fast_double_elements();
5256 inline bool has_fast_elements();
5257 inline bool has_sloppy_arguments_elements();
5258 inline bool has_fixed_typed_array_elements();
5259 inline bool has_dictionary_elements();
5261 static bool IsValidElementsTransition(ElementsKind from_kind,
5262 ElementsKind to_kind);
5264 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5265 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5266 bool DictionaryElementsInPrototypeChainOnly();
5268 inline Map* ElementsTransitionMap();
5270 inline FixedArrayBase* GetInitialElements();
5272 // [raw_transitions]: Provides access to the transitions storage field.
5273 // Don't call set_raw_transitions() directly to overwrite transitions, use
5274 // the TransitionArray::ReplaceTransitions() wrapper instead!
5275 DECL_ACCESSORS(raw_transitions, Object)
5276 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5277 // (which prototype maps don't have).
5278 DECL_ACCESSORS(prototype_info, Object)
5279 // PrototypeInfo is created lazily using this helper (which installs it on
5280 // the given prototype's map).
5281 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5282 Handle<JSObject> prototype, Isolate* isolate);
5283 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5284 Handle<Map> prototype_map, Isolate* isolate);
5286 // [prototype chain validity cell]: Associated with a prototype object,
5287 // stored in that object's map's PrototypeInfo, indicates that prototype
5288 // chains through this object are currently valid. The cell will be
5289 // invalidated and replaced when the prototype chain changes.
5290 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5292 static const int kPrototypeChainValid = 0;
5293 static const int kPrototypeChainInvalid = 1;
5296 Map* FindFieldOwner(int descriptor);
5298 inline int GetInObjectPropertyOffset(int index);
5300 int NumberOfFields();
5302 // TODO(ishell): candidate with JSObject::MigrateToMap().
5303 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5304 int target_inobject, int target_unused,
5305 int* old_number_of_fields);
5306 // TODO(ishell): moveit!
5307 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5308 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5309 Handle<HeapType> type1,
5310 Handle<HeapType> type2,
5312 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5313 Representation new_representation,
5314 Handle<HeapType> new_field_type);
5315 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5316 PropertyKind new_kind,
5317 PropertyAttributes new_attributes,
5318 Representation new_representation,
5319 Handle<HeapType> new_field_type,
5320 StoreMode store_mode);
5321 static Handle<Map> CopyGeneralizeAllRepresentations(
5322 Handle<Map> map, int modify_index, StoreMode store_mode,
5323 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5325 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5326 int descriptor_number,
5327 Handle<Object> value);
5329 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5330 const char* reason);
5332 // Returns the constructor name (the name (possibly, inferred name) of the
5333 // function that was used to instantiate the object).
5334 String* constructor_name();
5336 // Tells whether the map is used for JSObjects in dictionary mode (ie
5337 // normalized objects, ie objects for which HasFastProperties returns false).
5338 // A map can never be used for both dictionary mode and fast mode JSObjects.
5339 // False by default and for HeapObjects that are not JSObjects.
5340 inline void set_dictionary_map(bool value);
5341 inline bool is_dictionary_map();
5343 // Tells whether the instance needs security checks when accessing its
5345 inline void set_is_access_check_needed(bool access_check_needed);
5346 inline bool is_access_check_needed();
5348 // Returns true if map has a non-empty stub code cache.
5349 inline bool has_code_cache();
5351 // [prototype]: implicit prototype object.
5352 DECL_ACCESSORS(prototype, Object)
5353 // TODO(jkummerow): make set_prototype private.
5354 static void SetPrototype(
5355 Handle<Map> map, Handle<Object> prototype,
5356 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5358 // [constructor]: points back to the function responsible for this map.
5359 // The field overlaps with the back pointer. All maps in a transition tree
5360 // have the same constructor, so maps with back pointers can walk the
5361 // back pointer chain until they find the map holding their constructor.
5362 DECL_ACCESSORS(constructor_or_backpointer, Object)
5363 inline Object* GetConstructor() const;
5364 inline void SetConstructor(Object* constructor,
5365 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5366 // [back pointer]: points back to the parent map from which a transition
5367 // leads to this map. The field overlaps with the constructor (see above).
5368 inline Object* GetBackPointer();
5369 inline void SetBackPointer(Object* value,
5370 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5372 // [instance descriptors]: describes the object.
5373 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5375 // [layout descriptor]: describes the object layout.
5376 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5377 // |layout descriptor| accessor which can be used from GC.
5378 inline LayoutDescriptor* layout_descriptor_gc_safe();
5379 inline bool HasFastPointerLayout() const;
5381 // |layout descriptor| accessor that is safe to call even when
5382 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5383 // |layout_descriptor| field at all).
5384 inline LayoutDescriptor* GetLayoutDescriptor();
5386 inline void UpdateDescriptors(DescriptorArray* descriptors,
5387 LayoutDescriptor* layout_descriptor);
5388 inline void InitializeDescriptors(DescriptorArray* descriptors,
5389 LayoutDescriptor* layout_descriptor);
5391 // [stub cache]: contains stubs compiled for this map.
5392 DECL_ACCESSORS(code_cache, Object)
5394 // [dependent code]: list of optimized codes that weakly embed this map.
5395 DECL_ACCESSORS(dependent_code, DependentCode)
5397 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5398 DECL_ACCESSORS(weak_cell_cache, Object)
5400 inline PropertyDetails GetLastDescriptorDetails();
5402 inline int LastAdded();
5404 inline int NumberOfOwnDescriptors();
5405 inline void SetNumberOfOwnDescriptors(int number);
5407 inline Cell* RetrieveDescriptorsPointer();
5409 inline int EnumLength();
5410 inline void SetEnumLength(int length);
5412 inline bool owns_descriptors();
5413 inline void set_owns_descriptors(bool owns_descriptors);
5414 inline bool has_instance_call_handler();
5415 inline void set_has_instance_call_handler();
5416 inline void mark_unstable();
5417 inline bool is_stable();
5418 inline void set_migration_target(bool value);
5419 inline bool is_migration_target();
5420 inline void set_counter(int value);
5421 inline int counter();
5422 inline void deprecate();
5423 inline bool is_deprecated();
5424 inline bool CanBeDeprecated();
5425 // Returns a non-deprecated version of the input. If the input was not
5426 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5427 // is found by re-transitioning from the root of the transition tree using the
5428 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5430 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5432 // Returns a non-deprecated version of the input. This method may deprecate
5433 // existing maps along the way if encodings conflict. Not for use while
5434 // gathering type feedback. Use TryUpdate in those cases instead.
5435 static Handle<Map> Update(Handle<Map> map);
5437 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5438 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5439 Descriptor* descriptor,
5440 TransitionFlag flag);
5442 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5445 Handle<HeapType> type,
5446 PropertyAttributes attributes,
5447 Representation representation,
5448 TransitionFlag flag);
5450 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5453 Handle<Object> constant,
5454 PropertyAttributes attributes,
5455 TransitionFlag flag);
5457 // Returns a new map with all transitions dropped from the given map and
5458 // the ElementsKind set.
5459 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5460 ElementsKind to_kind);
5462 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5464 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5466 TransitionFlag flag);
5468 static Handle<Map> CopyForObserved(Handle<Map> map);
5470 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5471 PropertyAttributes attrs_to_add,
5472 Handle<Symbol> transition_marker,
5473 const char* reason);
5475 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5478 // Maximal number of fast properties. Used to restrict the number of map
5479 // transitions to avoid an explosion in the number of maps for objects used as
5481 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5482 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5484 Handle<Object> value,
5485 PropertyAttributes attributes,
5486 StoreFromKeyed store_mode);
5487 static Handle<Map> TransitionToAccessorProperty(
5488 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5489 Handle<Object> accessor, PropertyAttributes attributes);
5490 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5493 PropertyAttributes attributes);
5495 inline void AppendDescriptor(Descriptor* desc);
5497 // Returns a copy of the map, prepared for inserting into the transition
5498 // tree (if the |map| owns descriptors then the new one will share
5499 // descriptors with |map|).
5500 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5502 // Returns a copy of the map, with all transitions dropped from the
5503 // instance descriptors.
5504 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5505 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5507 // Returns the next free property index (only valid for FAST MODE).
5508 int NextFreePropertyIndex();
5510 // Returns the number of properties described in instance_descriptors
5511 // filtering out properties with the specified attributes.
5512 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5513 PropertyAttributes filter = NONE);
5517 // Code cache operations.
5519 // Clears the code cache.
5520 inline void ClearCodeCache(Heap* heap);
5522 // Update code cache.
5523 static void UpdateCodeCache(Handle<Map> map,
5527 // Extend the descriptor array of the map with the list of descriptors.
5528 // In case of duplicates, the latest descriptor is used.
5529 static void AppendCallbackDescriptors(Handle<Map> map,
5530 Handle<Object> descriptors);
5532 static inline int SlackForArraySize(int old_size, int size_limit);
5534 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5536 // Returns the found code or undefined if absent.
5537 Object* FindInCodeCache(Name* name, Code::Flags flags);
5539 // Returns the non-negative index of the code object if it is in the
5540 // cache and -1 otherwise.
5541 int IndexInCodeCache(Object* name, Code* code);
5543 // Removes a code object from the code cache at the given index.
5544 void RemoveFromCodeCache(Name* name, Code* code, int index);
5546 // Computes a hash value for this map, to be used in HashTables and such.
5549 // Returns the map that this map transitions to if its elements_kind
5550 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5551 // |safe_to_add_transitions| is set to false if adding transitions is not
5553 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5555 // Returns the transitioned map for this map with the most generic
5556 // elements_kind that's found in |candidates|, or null handle if no match is
5558 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5559 MapHandleList* candidates);
5561 inline bool CanTransition();
5563 inline bool IsPrimitiveMap();
5564 inline bool IsJSObjectMap();
5565 inline bool IsJSArrayMap();
5566 inline bool IsStringMap();
5567 inline bool IsJSProxyMap();
5568 inline bool IsJSGlobalProxyMap();
5569 inline bool IsJSGlobalObjectMap();
5570 inline bool IsGlobalObjectMap();
5572 inline bool CanOmitMapChecks();
5574 static void AddDependentCode(Handle<Map> map,
5575 DependentCode::DependencyGroup group,
5578 bool IsMapInArrayPrototypeChain();
5580 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5582 // Dispatched behavior.
5583 DECLARE_PRINTER(Map)
5584 DECLARE_VERIFIER(Map)
5587 void DictionaryMapVerify();
5588 void VerifyOmittedMapChecks();
5591 inline int visitor_id();
5592 inline void set_visitor_id(int visitor_id);
5594 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5595 Handle<Object> prototype,
5596 PrototypeOptimizationMode mode);
5598 static const int kMaxPreAllocatedPropertyFields = 255;
5600 // Layout description.
5601 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5602 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5603 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5604 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5605 static const int kConstructorOrBackPointerOffset =
5606 kPrototypeOffset + kPointerSize;
5607 // When there is only one transition, it is stored directly in this field;
5608 // otherwise a transition array is used.
5609 // For prototype maps, this slot is used to store this map's PrototypeInfo
5611 static const int kTransitionsOrPrototypeInfoOffset =
5612 kConstructorOrBackPointerOffset + kPointerSize;
5613 static const int kDescriptorsOffset =
5614 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5615 #if V8_DOUBLE_FIELDS_UNBOXING
5616 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5617 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5619 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5620 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5622 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5623 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5624 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5626 // Layout of pointer fields. Heap iteration code relies on them
5627 // being continuously allocated.
5628 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5629 static const int kPointerFieldsEndOffset = kSize;
5631 // Byte offsets within kInstanceSizesOffset.
5632 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5633 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5634 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5635 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5636 // Note there is one byte available for use here.
5637 static const int kUnusedByte = 2;
5638 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5639 static const int kVisitorIdByte = 3;
5640 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5642 // Byte offsets within kInstanceAttributesOffset attributes.
5643 #if V8_TARGET_LITTLE_ENDIAN
5644 // Order instance type and bit field together such that they can be loaded
5645 // together as a 16-bit word with instance type in the lower 8 bits regardless
5646 // of endianess. Also provide endian-independent offset to that 16-bit word.
5647 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5648 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5650 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5651 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5653 static const int kInstanceTypeAndBitFieldOffset =
5654 kInstanceAttributesOffset + 0;
5655 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5656 static const int kUnusedPropertyFieldsByte = 3;
5657 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5659 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5660 Internals::kMapInstanceTypeAndBitFieldOffset);
5662 // Bit positions for bit field.
5663 static const int kHasNonInstancePrototype = 0;
5664 static const int kIsHiddenPrototype = 1;
5665 static const int kHasNamedInterceptor = 2;
5666 static const int kHasIndexedInterceptor = 3;
5667 static const int kIsUndetectable = 4;
5668 static const int kIsObserved = 5;
5669 static const int kIsAccessCheckNeeded = 6;
5670 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5672 // Bit positions for bit field 2
5673 static const int kIsExtensible = 0;
5674 static const int kStringWrapperSafeForDefaultValueOf = 1;
5675 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5676 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5678 // Derived values from bit field 2
5679 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5680 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5681 static const int8_t kMaximumBitField2FastSmiElementValue =
5682 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5683 Map::ElementsKindBits::kShift) - 1;
5684 static const int8_t kMaximumBitField2FastHoleyElementValue =
5685 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5686 Map::ElementsKindBits::kShift) - 1;
5687 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5688 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5689 Map::ElementsKindBits::kShift) - 1;
5691 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5692 kPointerFieldsEndOffset,
5693 kSize> BodyDescriptor;
5695 // Compares this map to another to see if they describe equivalent objects.
5696 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5697 // it had exactly zero inobject properties.
5698 // The "shared" flags of both this map and |other| are ignored.
5699 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5701 // Returns true if given field is unboxed double.
5702 inline bool IsUnboxedDoubleField(FieldIndex index);
5705 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5706 static void TraceAllTransitions(Map* map);
5709 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5710 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5711 Handle<LayoutDescriptor> layout_descriptor);
5714 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5715 Handle<Name> name, SimpleTransitionFlag flag);
5717 bool EquivalentToForTransition(Map* other);
5718 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5719 static Handle<Map> ShareDescriptor(Handle<Map> map,
5720 Handle<DescriptorArray> descriptors,
5721 Descriptor* descriptor);
5722 static Handle<Map> CopyInstallDescriptors(
5723 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5724 Handle<LayoutDescriptor> layout_descriptor);
5725 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5726 Descriptor* descriptor,
5727 TransitionFlag flag);
5728 static Handle<Map> CopyReplaceDescriptors(
5729 Handle<Map> map, Handle<DescriptorArray> descriptors,
5730 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5731 MaybeHandle<Name> maybe_name, const char* reason,
5732 SimpleTransitionFlag simple_flag);
5734 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5735 Handle<DescriptorArray> descriptors,
5736 Descriptor* descriptor,
5738 TransitionFlag flag);
5739 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5740 Handle<Map> map, int descriptor, PropertyKind kind,
5741 PropertyAttributes attributes, const char** reason);
5743 static Handle<Map> CopyNormalized(Handle<Map> map,
5744 PropertyNormalizationMode mode);
5746 // Fires when the layout of an object with a leaf map changes.
5747 // This includes adding transitions to the leaf map or changing
5748 // the descriptor array.
5749 inline void NotifyLeafMapLayoutChange();
5751 void DeprecateTransitionTree();
5752 bool DeprecateTarget(PropertyKind kind, Name* key,
5753 PropertyAttributes attributes,
5754 DescriptorArray* new_descriptors,
5755 LayoutDescriptor* new_layout_descriptor);
5757 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5759 // Update field type of the given descriptor to new representation and new
5760 // type. The type must be prepared for storing in descriptor array:
5761 // it must be either a simple type or a map wrapped in a weak cell.
5762 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5763 Representation new_representation,
5764 Handle<Object> new_wrapped_type);
5766 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5767 PropertyAttributes attributes);
5768 void PrintGeneralization(FILE* file,
5773 bool constant_to_field,
5774 Representation old_representation,
5775 Representation new_representation,
5776 HeapType* old_field_type,
5777 HeapType* new_field_type);
5779 static const int kFastPropertiesSoftLimit = 12;
5780 static const int kMaxFastProperties = 128;
5782 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5786 // An abstract superclass, a marker class really, for simple structure classes.
5787 // It doesn't carry much functionality but allows struct classes to be
5788 // identified in the type system.
5789 class Struct: public HeapObject {
5791 inline void InitializeBody(int object_size);
5792 DECLARE_CAST(Struct)
5796 // A simple one-element struct, useful where smis need to be boxed.
5797 class Box : public Struct {
5799 // [value]: the boxed contents.
5800 DECL_ACCESSORS(value, Object)
5804 // Dispatched behavior.
5805 DECLARE_PRINTER(Box)
5806 DECLARE_VERIFIER(Box)
5808 static const int kValueOffset = HeapObject::kHeaderSize;
5809 static const int kSize = kValueOffset + kPointerSize;
5812 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5816 // Container for metadata stored on each prototype map.
5817 class PrototypeInfo : public Struct {
5819 static const int UNREGISTERED = -1;
5821 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5822 // or Smi(0) if uninitialized.
5823 DECL_ACCESSORS(prototype_users, Object)
5824 // [registry_slot]: Slot in prototype's user registry where this user
5825 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5826 inline int registry_slot() const;
5827 inline void set_registry_slot(int slot);
5828 // [validity_cell]: Cell containing the validity bit for prototype chains
5829 // going through this object, or Smi(0) if uninitialized.
5830 DECL_ACCESSORS(validity_cell, Object)
5831 // [constructor_name]: User-friendly name of the original constructor.
5832 DECL_ACCESSORS(constructor_name, Object)
5834 DECLARE_CAST(PrototypeInfo)
5836 // Dispatched behavior.
5837 DECLARE_PRINTER(PrototypeInfo)
5838 DECLARE_VERIFIER(PrototypeInfo)
5840 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5841 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5842 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5843 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5844 static const int kSize = kConstructorNameOffset + kPointerSize;
5847 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5851 // Script describes a script which has been added to the VM.
5852 class Script: public Struct {
5861 // Script compilation types.
5862 enum CompilationType {
5863 COMPILATION_TYPE_HOST = 0,
5864 COMPILATION_TYPE_EVAL = 1
5867 // Script compilation state.
5868 enum CompilationState {
5869 COMPILATION_STATE_INITIAL = 0,
5870 COMPILATION_STATE_COMPILED = 1
5873 // [source]: the script source.
5874 DECL_ACCESSORS(source, Object)
5876 // [name]: the script name.
5877 DECL_ACCESSORS(name, Object)
5879 // [id]: the script id.
5880 DECL_ACCESSORS(id, Smi)
5882 // [line_offset]: script line offset in resource from where it was extracted.
5883 DECL_ACCESSORS(line_offset, Smi)
5885 // [column_offset]: script column offset in resource from where it was
5887 DECL_ACCESSORS(column_offset, Smi)
5889 // [context_data]: context data for the context this script was compiled in.
5890 DECL_ACCESSORS(context_data, Object)
5892 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5893 DECL_ACCESSORS(wrapper, HeapObject)
5895 // [type]: the script type.
5896 DECL_ACCESSORS(type, Smi)
5898 // [line_ends]: FixedArray of line ends positions.
5899 DECL_ACCESSORS(line_ends, Object)
5901 // [eval_from_shared]: for eval scripts the shared funcion info for the
5902 // function from which eval was called.
5903 DECL_ACCESSORS(eval_from_shared, Object)
5905 // [eval_from_instructions_offset]: the instruction offset in the code for the
5906 // function from which eval was called where eval was called.
5907 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5909 // [shared_function_infos]: weak fixed array containing all shared
5910 // function infos created from this script.
5911 DECL_ACCESSORS(shared_function_infos, Object)
5913 // [flags]: Holds an exciting bitfield.
5914 DECL_ACCESSORS(flags, Smi)
5916 // [source_url]: sourceURL from magic comment
5917 DECL_ACCESSORS(source_url, Object)
5919 // [source_url]: sourceMappingURL magic comment
5920 DECL_ACCESSORS(source_mapping_url, Object)
5922 // [compilation_type]: how the the script was compiled. Encoded in the
5924 inline CompilationType compilation_type();
5925 inline void set_compilation_type(CompilationType type);
5927 // [compilation_state]: determines whether the script has already been
5928 // compiled. Encoded in the 'flags' field.
5929 inline CompilationState compilation_state();
5930 inline void set_compilation_state(CompilationState state);
5932 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
5933 // and used by the embedder to make decisions about the script. V8 just passes
5934 // this through. Encoded in the 'flags' field.
5935 inline v8::ScriptOriginOptions origin_options();
5936 inline void set_origin_options(ScriptOriginOptions origin_options);
5938 DECLARE_CAST(Script)
5940 // If script source is an external string, check that the underlying
5941 // resource is accessible. Otherwise, always return true.
5942 inline bool HasValidSource();
5944 // Convert code position into column number.
5945 static int GetColumnNumber(Handle<Script> script, int code_pos);
5947 // Convert code position into (zero-based) line number.
5948 // The non-handlified version does not allocate, but may be much slower.
5949 static int GetLineNumber(Handle<Script> script, int code_pos);
5950 int GetLineNumber(int code_pos);
5952 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
5954 // Init line_ends array with code positions of line ends inside script source.
5955 static void InitLineEnds(Handle<Script> script);
5957 // Get the JS object wrapping the given script; create it if none exists.
5958 static Handle<JSObject> GetWrapper(Handle<Script> script);
5960 // Look through the list of existing shared function infos to find one
5961 // that matches the function literal. Return empty handle if not found.
5962 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
5964 // Dispatched behavior.
5965 DECLARE_PRINTER(Script)
5966 DECLARE_VERIFIER(Script)
5968 static const int kSourceOffset = HeapObject::kHeaderSize;
5969 static const int kNameOffset = kSourceOffset + kPointerSize;
5970 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
5971 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
5972 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
5973 static const int kWrapperOffset = kContextOffset + kPointerSize;
5974 static const int kTypeOffset = kWrapperOffset + kPointerSize;
5975 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
5976 static const int kIdOffset = kLineEndsOffset + kPointerSize;
5977 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
5978 static const int kEvalFrominstructionsOffsetOffset =
5979 kEvalFromSharedOffset + kPointerSize;
5980 static const int kSharedFunctionInfosOffset =
5981 kEvalFrominstructionsOffsetOffset + kPointerSize;
5982 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
5983 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
5984 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
5985 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
5988 int GetLineNumberWithArray(int code_pos);
5990 // Bit positions in the flags field.
5991 static const int kCompilationTypeBit = 0;
5992 static const int kCompilationStateBit = 1;
5993 static const int kOriginOptionsShift = 2;
5994 static const int kOriginOptionsSize = 3;
5995 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
5996 << kOriginOptionsShift;
5998 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6002 // List of builtin functions we want to identify to improve code
6005 // Each entry has a name of a global object property holding an object
6006 // optionally followed by ".prototype", a name of a builtin function
6007 // on the object (the one the id is set for), and a label.
6009 // Installation of ids for the selected builtin functions is handled
6010 // by the bootstrapper.
6011 #define FUNCTIONS_WITH_ID_LIST(V) \
6012 V(Array.prototype, indexOf, ArrayIndexOf) \
6013 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6014 V(Array.prototype, push, ArrayPush) \
6015 V(Array.prototype, pop, ArrayPop) \
6016 V(Array.prototype, shift, ArrayShift) \
6017 V(Function.prototype, apply, FunctionApply) \
6018 V(Function.prototype, call, FunctionCall) \
6019 V(String.prototype, charCodeAt, StringCharCodeAt) \
6020 V(String.prototype, charAt, StringCharAt) \
6021 V(String, fromCharCode, StringFromCharCode) \
6022 V(Math, random, MathRandom) \
6023 V(Math, floor, MathFloor) \
6024 V(Math, round, MathRound) \
6025 V(Math, ceil, MathCeil) \
6026 V(Math, abs, MathAbs) \
6027 V(Math, log, MathLog) \
6028 V(Math, exp, MathExp) \
6029 V(Math, sqrt, MathSqrt) \
6030 V(Math, pow, MathPow) \
6031 V(Math, max, MathMax) \
6032 V(Math, min, MathMin) \
6033 V(Math, cos, MathCos) \
6034 V(Math, sin, MathSin) \
6035 V(Math, tan, MathTan) \
6036 V(Math, acos, MathAcos) \
6037 V(Math, asin, MathAsin) \
6038 V(Math, atan, MathAtan) \
6039 V(Math, atan2, MathAtan2) \
6040 V(Math, imul, MathImul) \
6041 V(Math, clz32, MathClz32) \
6042 V(Math, fround, MathFround)
6044 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6045 V(Atomics, load, AtomicsLoad) \
6046 V(Atomics, store, AtomicsStore)
6048 enum BuiltinFunctionId {
6050 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6052 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6053 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6054 #undef DECLARE_FUNCTION_ID
6055 // Fake id for a special case of Math.pow. Note, it continues the
6056 // list of math functions.
6061 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6062 // that both {code} and {literals} can be NULL to pass search result status.
6063 struct CodeAndLiterals {
6064 Code* code; // Cached optimized code.
6065 FixedArray* literals; // Cached literals array.
6069 // SharedFunctionInfo describes the JSFunction information that can be
6070 // shared by multiple instances of the function.
6071 class SharedFunctionInfo: public HeapObject {
6073 // [name]: Function name.
6074 DECL_ACCESSORS(name, Object)
6076 // [code]: Function code.
6077 DECL_ACCESSORS(code, Code)
6078 inline void ReplaceCode(Code* code);
6080 // [optimized_code_map]: Map from native context to optimized code
6081 // and a shared literals array or Smi(0) if none.
6082 DECL_ACCESSORS(optimized_code_map, Object)
6084 // Returns entry from optimized code map for specified context and OSR entry.
6085 // Note that {code == nullptr} indicates no matching entry has been found,
6086 // whereas {literals == nullptr} indicates the code is context-independent.
6087 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6088 BailoutId osr_ast_id);
6090 // Clear optimized code map.
6091 void ClearOptimizedCodeMap();
6093 // Removed a specific optimized code object from the optimized code map.
6094 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6096 // Trims the optimized code map after entries have been removed.
6097 void TrimOptimizedCodeMap(int shrink_by);
6099 // Add a new entry to the optimized code map for context-independent code.
6100 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6103 // Add a new entry to the optimized code map for context-dependent code.
6104 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6105 Handle<Context> native_context,
6107 Handle<FixedArray> literals,
6108 BailoutId osr_ast_id);
6110 // Set up the link between shared function info and the script. The shared
6111 // function info is added to the list on the script.
6112 static void SetScript(Handle<SharedFunctionInfo> shared,
6113 Handle<Object> script_object);
6115 // Layout description of the optimized code map.
6116 static const int kNextMapIndex = 0;
6117 static const int kSharedCodeIndex = 1;
6118 static const int kEntriesStart = 2;
6119 static const int kContextOffset = 0;
6120 static const int kCachedCodeOffset = 1;
6121 static const int kLiteralsOffset = 2;
6122 static const int kOsrAstIdOffset = 3;
6123 static const int kEntryLength = 4;
6124 static const int kInitialLength = kEntriesStart + kEntryLength;
6126 // [scope_info]: Scope info.
6127 DECL_ACCESSORS(scope_info, ScopeInfo)
6129 // [construct stub]: Code stub for constructing instances of this function.
6130 DECL_ACCESSORS(construct_stub, Code)
6132 // Returns if this function has been compiled to native code yet.
6133 inline bool is_compiled();
6135 // [length]: The function length - usually the number of declared parameters.
6136 // Use up to 2^30 parameters.
6137 inline int length() const;
6138 inline void set_length(int value);
6140 // [internal formal parameter count]: The declared number of parameters.
6141 // For subclass constructors, also includes new.target.
6142 // The size of function's frame is internal_formal_parameter_count + 1.
6143 inline int internal_formal_parameter_count() const;
6144 inline void set_internal_formal_parameter_count(int value);
6146 // Set the formal parameter count so the function code will be
6147 // called without using argument adaptor frames.
6148 inline void DontAdaptArguments();
6150 // [expected_nof_properties]: Expected number of properties for the function.
6151 inline int expected_nof_properties() const;
6152 inline void set_expected_nof_properties(int value);
6154 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6155 // (increasingly) from crankshafted code where sufficient feedback isn't
6157 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6159 // Unconditionally clear the type feedback vector (including vector ICs).
6160 void ClearTypeFeedbackInfo();
6162 // Clear the type feedback vector with a more subtle policy at GC time.
6163 void ClearTypeFeedbackInfoAtGCTime();
6166 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6167 // even if the GC moves this SharedFunctionInfo.
6168 inline int unique_id() const;
6169 inline void set_unique_id(int value);
6172 // [instance class name]: class name for instances.
6173 DECL_ACCESSORS(instance_class_name, Object)
6175 // [function data]: This field holds some additional data for function.
6176 // Currently it has one of:
6177 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6178 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6179 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6180 // In the long run we don't want all functions to have this field but
6181 // we can fix that when we have a better model for storing hidden data
6183 DECL_ACCESSORS(function_data, Object)
6185 inline bool IsApiFunction();
6186 inline FunctionTemplateInfo* get_api_func_data();
6187 inline bool HasBuiltinFunctionId();
6188 inline BuiltinFunctionId builtin_function_id();
6189 inline bool HasBytecodeArray();
6190 inline BytecodeArray* bytecode_array();
6192 // [script info]: Script from which the function originates.
6193 DECL_ACCESSORS(script, Object)
6195 // [num_literals]: Number of literals used by this function.
6196 inline int num_literals() const;
6197 inline void set_num_literals(int value);
6199 // [start_position_and_type]: Field used to store both the source code
6200 // position, whether or not the function is a function expression,
6201 // and whether or not the function is a toplevel function. The two
6202 // least significants bit indicates whether the function is an
6203 // expression and the rest contains the source code position.
6204 inline int start_position_and_type() const;
6205 inline void set_start_position_and_type(int value);
6207 // The function is subject to debugging if a debug info is attached.
6208 inline bool HasDebugInfo();
6209 inline DebugInfo* GetDebugInfo();
6211 // A function has debug code if the compiled code has debug break slots.
6212 inline bool HasDebugCode();
6214 // [debug info]: Debug information.
6215 DECL_ACCESSORS(debug_info, Object)
6217 // [inferred name]: Name inferred from variable or property
6218 // assignment of this function. Used to facilitate debugging and
6219 // profiling of JavaScript code written in OO style, where almost
6220 // all functions are anonymous but are assigned to object
6222 DECL_ACCESSORS(inferred_name, String)
6224 // The function's name if it is non-empty, otherwise the inferred name.
6225 String* DebugName();
6227 // Position of the 'function' token in the script source.
6228 inline int function_token_position() const;
6229 inline void set_function_token_position(int function_token_position);
6231 // Position of this function in the script source.
6232 inline int start_position() const;
6233 inline void set_start_position(int start_position);
6235 // End position of this function in the script source.
6236 inline int end_position() const;
6237 inline void set_end_position(int end_position);
6239 // Is this function a function expression in the source code.
6240 DECL_BOOLEAN_ACCESSORS(is_expression)
6242 // Is this function a top-level function (scripts, evals).
6243 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6245 // Bit field containing various information collected by the compiler to
6246 // drive optimization.
6247 inline int compiler_hints() const;
6248 inline void set_compiler_hints(int value);
6250 inline int ast_node_count() const;
6251 inline void set_ast_node_count(int count);
6253 inline int profiler_ticks() const;
6254 inline void set_profiler_ticks(int ticks);
6256 // Inline cache age is used to infer whether the function survived a context
6257 // disposal or not. In the former case we reset the opt_count.
6258 inline int ic_age();
6259 inline void set_ic_age(int age);
6261 // Indicates if this function can be lazy compiled.
6262 // This is used to determine if we can safely flush code from a function
6263 // when doing GC if we expect that the function will no longer be used.
6264 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6266 // Indicates if this function can be lazy compiled without a context.
6267 // This is used to determine if we can force compilation without reaching
6268 // the function through program execution but through other means (e.g. heap
6269 // iteration by the debugger).
6270 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6272 // Indicates whether optimizations have been disabled for this
6273 // shared function info. If a function is repeatedly optimized or if
6274 // we cannot optimize the function we disable optimization to avoid
6275 // spending time attempting to optimize it again.
6276 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6278 // Indicates the language mode.
6279 inline LanguageMode language_mode();
6280 inline void set_language_mode(LanguageMode language_mode);
6282 // False if the function definitely does not allocate an arguments object.
6283 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6285 // Indicates that this function uses a super property (or an eval that may
6286 // use a super property).
6287 // This is needed to set up the [[HomeObject]] on the function instance.
6288 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6290 // True if the function has any duplicated parameter names.
6291 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6293 // Indicates whether the function is a native function.
6294 // These needs special treatment in .call and .apply since
6295 // null passed as the receiver should not be translated to the
6297 DECL_BOOLEAN_ACCESSORS(native)
6299 // Indicate that this function should always be inlined in optimized code.
6300 DECL_BOOLEAN_ACCESSORS(force_inline)
6302 // Indicates that the function was created by the Function function.
6303 // Though it's anonymous, toString should treat it as if it had the name
6304 // "anonymous". We don't set the name itself so that the system does not
6305 // see a binding for it.
6306 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6308 // Indicates whether the function is a bound function created using
6309 // the bind function.
6310 DECL_BOOLEAN_ACCESSORS(bound)
6312 // Indicates that the function is anonymous (the name field can be set
6313 // through the API, which does not change this flag).
6314 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6316 // Is this a function or top-level/eval code.
6317 DECL_BOOLEAN_ACCESSORS(is_function)
6319 // Indicates that code for this function cannot be compiled with Crankshaft.
6320 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6322 // Indicates that code for this function cannot be flushed.
6323 DECL_BOOLEAN_ACCESSORS(dont_flush)
6325 // Indicates that this function is a generator.
6326 DECL_BOOLEAN_ACCESSORS(is_generator)
6328 // Indicates that this function is an arrow function.
6329 DECL_BOOLEAN_ACCESSORS(is_arrow)
6331 // Indicates that this function is a concise method.
6332 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6334 // Indicates that this function is an accessor (getter or setter).
6335 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6337 // Indicates that this function is a default constructor.
6338 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6340 // Indicates that this function is an asm function.
6341 DECL_BOOLEAN_ACCESSORS(asm_function)
6343 // Indicates that the the shared function info is deserialized from cache.
6344 DECL_BOOLEAN_ACCESSORS(deserialized)
6346 // Indicates that the the shared function info has never been compiled before.
6347 DECL_BOOLEAN_ACCESSORS(never_compiled)
6349 inline FunctionKind kind();
6350 inline void set_kind(FunctionKind kind);
6352 // Indicates whether or not the code in the shared function support
6354 inline bool has_deoptimization_support();
6356 // Enable deoptimization support through recompiled code.
6357 void EnableDeoptimizationSupport(Code* recompiled);
6359 // Disable (further) attempted optimization of all functions sharing this
6360 // shared function info.
6361 void DisableOptimization(BailoutReason reason);
6363 inline BailoutReason disable_optimization_reason();
6365 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6366 // code, returns whether it asserted (i.e., always true if assertions are
6368 bool VerifyBailoutId(BailoutId id);
6370 // [source code]: Source code for the function.
6371 bool HasSourceCode() const;
6372 Handle<Object> GetSourceCode();
6374 // Number of times the function was optimized.
6375 inline int opt_count();
6376 inline void set_opt_count(int opt_count);
6378 // Number of times the function was deoptimized.
6379 inline void set_deopt_count(int value);
6380 inline int deopt_count();
6381 inline void increment_deopt_count();
6383 // Number of time we tried to re-enable optimization after it
6384 // was disabled due to high number of deoptimizations.
6385 inline void set_opt_reenable_tries(int value);
6386 inline int opt_reenable_tries();
6388 inline void TryReenableOptimization();
6390 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6391 inline void set_counters(int value);
6392 inline int counters() const;
6394 // Stores opt_count and bailout_reason as bit-fields.
6395 inline void set_opt_count_and_bailout_reason(int value);
6396 inline int opt_count_and_bailout_reason() const;
6398 inline void set_disable_optimization_reason(BailoutReason reason);
6400 // Tells whether this function should be subject to debugging.
6401 inline bool IsSubjectToDebugging();
6403 // Check whether or not this function is inlineable.
6404 bool IsInlineable();
6406 // Source size of this function.
6409 // Calculate the instance size.
6410 int CalculateInstanceSize();
6412 // Calculate the number of in-object properties.
6413 int CalculateInObjectProperties();
6415 inline bool has_simple_parameters();
6417 // Initialize a SharedFunctionInfo from a parsed function literal.
6418 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6419 FunctionLiteral* lit);
6421 // Dispatched behavior.
6422 DECLARE_PRINTER(SharedFunctionInfo)
6423 DECLARE_VERIFIER(SharedFunctionInfo)
6425 void ResetForNewContext(int new_ic_age);
6427 DECLARE_CAST(SharedFunctionInfo)
6430 static const int kDontAdaptArgumentsSentinel = -1;
6432 // Layout description.
6434 static const int kNameOffset = HeapObject::kHeaderSize;
6435 static const int kCodeOffset = kNameOffset + kPointerSize;
6436 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6437 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6438 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6439 static const int kInstanceClassNameOffset =
6440 kConstructStubOffset + kPointerSize;
6441 static const int kFunctionDataOffset =
6442 kInstanceClassNameOffset + kPointerSize;
6443 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6444 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6445 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6446 static const int kFeedbackVectorOffset =
6447 kInferredNameOffset + kPointerSize;
6449 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6450 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6452 // Just to not break the postmortrem support with conditional offsets
6453 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6454 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6457 #if V8_HOST_ARCH_32_BIT
6459 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6460 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6461 static const int kExpectedNofPropertiesOffset =
6462 kFormalParameterCountOffset + kPointerSize;
6463 static const int kNumLiteralsOffset =
6464 kExpectedNofPropertiesOffset + kPointerSize;
6465 static const int kStartPositionAndTypeOffset =
6466 kNumLiteralsOffset + kPointerSize;
6467 static const int kEndPositionOffset =
6468 kStartPositionAndTypeOffset + kPointerSize;
6469 static const int kFunctionTokenPositionOffset =
6470 kEndPositionOffset + kPointerSize;
6471 static const int kCompilerHintsOffset =
6472 kFunctionTokenPositionOffset + kPointerSize;
6473 static const int kOptCountAndBailoutReasonOffset =
6474 kCompilerHintsOffset + kPointerSize;
6475 static const int kCountersOffset =
6476 kOptCountAndBailoutReasonOffset + kPointerSize;
6477 static const int kAstNodeCountOffset =
6478 kCountersOffset + kPointerSize;
6479 static const int kProfilerTicksOffset =
6480 kAstNodeCountOffset + kPointerSize;
6483 static const int kSize = kProfilerTicksOffset + kPointerSize;
6485 // The only reason to use smi fields instead of int fields
6486 // is to allow iteration without maps decoding during
6487 // garbage collections.
6488 // To avoid wasting space on 64-bit architectures we use
6489 // the following trick: we group integer fields into pairs
6490 // The least significant integer in each pair is shifted left by 1.
6491 // By doing this we guarantee that LSB of each kPointerSize aligned
6492 // word is not set and thus this word cannot be treated as pointer
6493 // to HeapObject during old space traversal.
6494 #if V8_TARGET_LITTLE_ENDIAN
6495 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6496 static const int kFormalParameterCountOffset =
6497 kLengthOffset + kIntSize;
6499 static const int kExpectedNofPropertiesOffset =
6500 kFormalParameterCountOffset + kIntSize;
6501 static const int kNumLiteralsOffset =
6502 kExpectedNofPropertiesOffset + kIntSize;
6504 static const int kEndPositionOffset =
6505 kNumLiteralsOffset + kIntSize;
6506 static const int kStartPositionAndTypeOffset =
6507 kEndPositionOffset + kIntSize;
6509 static const int kFunctionTokenPositionOffset =
6510 kStartPositionAndTypeOffset + kIntSize;
6511 static const int kCompilerHintsOffset =
6512 kFunctionTokenPositionOffset + kIntSize;
6514 static const int kOptCountAndBailoutReasonOffset =
6515 kCompilerHintsOffset + kIntSize;
6516 static const int kCountersOffset =
6517 kOptCountAndBailoutReasonOffset + kIntSize;
6519 static const int kAstNodeCountOffset =
6520 kCountersOffset + kIntSize;
6521 static const int kProfilerTicksOffset =
6522 kAstNodeCountOffset + kIntSize;
6525 static const int kSize = kProfilerTicksOffset + kIntSize;
6527 #elif V8_TARGET_BIG_ENDIAN
6528 static const int kFormalParameterCountOffset =
6529 kLastPointerFieldOffset + kPointerSize;
6530 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6532 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6533 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6535 static const int kStartPositionAndTypeOffset =
6536 kExpectedNofPropertiesOffset + kIntSize;
6537 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6539 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6540 static const int kFunctionTokenPositionOffset =
6541 kCompilerHintsOffset + kIntSize;
6543 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6544 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6546 static const int kProfilerTicksOffset =
6547 kOptCountAndBailoutReasonOffset + kIntSize;
6548 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6551 static const int kSize = kAstNodeCountOffset + kIntSize;
6554 #error Unknown byte ordering
6555 #endif // Big endian
6559 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6561 typedef FixedBodyDescriptor<kNameOffset,
6562 kLastPointerFieldOffset + kPointerSize,
6563 kSize> BodyDescriptor;
6565 // Bit positions in start_position_and_type.
6566 // The source code start position is in the 30 most significant bits of
6567 // the start_position_and_type field.
6568 static const int kIsExpressionBit = 0;
6569 static const int kIsTopLevelBit = 1;
6570 static const int kStartPositionShift = 2;
6571 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6573 // Bit positions in compiler_hints.
6574 enum CompilerHints {
6575 kAllowLazyCompilation,
6576 kAllowLazyCompilationWithoutContext,
6577 kOptimizationDisabled,
6578 kStrictModeFunction,
6579 kStrongModeFunction,
6582 kHasDuplicateParameters,
6587 kNameShouldPrintAsAnonymous,
6594 kIsAccessorFunction,
6595 kIsDefaultConstructor,
6596 kIsSubclassConstructor,
6602 kCompilerHintsCount // Pseudo entry
6604 // Add hints for other modes when they're added.
6605 STATIC_ASSERT(LANGUAGE_END == 3);
6607 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6609 class DeoptCountBits : public BitField<int, 0, 4> {};
6610 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6611 class ICAgeBits : public BitField<int, 22, 8> {};
6613 class OptCountBits : public BitField<int, 0, 22> {};
6614 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6617 #if V8_HOST_ARCH_32_BIT
6618 // On 32 bit platforms, compiler hints is a smi.
6619 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6620 static const int kCompilerHintsSize = kPointerSize;
6622 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6623 static const int kCompilerHintsSmiTagSize = 0;
6624 static const int kCompilerHintsSize = kIntSize;
6627 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6628 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6631 // Constants for optimizing codegen for strict mode function and
6633 // Allows to use byte-width instructions.
6634 static const int kStrictModeBitWithinByte =
6635 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6636 static const int kStrongModeBitWithinByte =
6637 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6639 static const int kNativeBitWithinByte =
6640 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6642 #if defined(V8_TARGET_LITTLE_ENDIAN)
6643 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6644 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6645 static const int kStrongModeByteOffset =
6646 kCompilerHintsOffset +
6647 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6648 static const int kNativeByteOffset = kCompilerHintsOffset +
6649 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6650 #elif defined(V8_TARGET_BIG_ENDIAN)
6651 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6652 (kCompilerHintsSize - 1) -
6653 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6654 static const int kStrongModeByteOffset =
6655 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6656 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6657 static const int kNativeByteOffset = kCompilerHintsOffset +
6658 (kCompilerHintsSize - 1) -
6659 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6661 #error Unknown byte ordering
6665 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6669 // Printing support.
6670 struct SourceCodeOf {
6671 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6672 : value(v), max_length(max) {}
6673 const SharedFunctionInfo* value;
6678 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6681 class JSGeneratorObject: public JSObject {
6683 // [function]: The function corresponding to this generator object.
6684 DECL_ACCESSORS(function, JSFunction)
6686 // [context]: The context of the suspended computation.
6687 DECL_ACCESSORS(context, Context)
6689 // [receiver]: The receiver of the suspended computation.
6690 DECL_ACCESSORS(receiver, Object)
6692 // [continuation]: Offset into code of continuation.
6694 // A positive offset indicates a suspended generator. The special
6695 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6696 // cannot be resumed.
6697 inline int continuation() const;
6698 inline void set_continuation(int continuation);
6699 inline bool is_closed();
6700 inline bool is_executing();
6701 inline bool is_suspended();
6703 // [operand_stack]: Saved operand stack.
6704 DECL_ACCESSORS(operand_stack, FixedArray)
6706 DECLARE_CAST(JSGeneratorObject)
6708 // Dispatched behavior.
6709 DECLARE_PRINTER(JSGeneratorObject)
6710 DECLARE_VERIFIER(JSGeneratorObject)
6712 // Magic sentinel values for the continuation.
6713 static const int kGeneratorExecuting = -1;
6714 static const int kGeneratorClosed = 0;
6716 // Layout description.
6717 static const int kFunctionOffset = JSObject::kHeaderSize;
6718 static const int kContextOffset = kFunctionOffset + kPointerSize;
6719 static const int kReceiverOffset = kContextOffset + kPointerSize;
6720 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6721 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6722 static const int kSize = kOperandStackOffset + kPointerSize;
6724 // Resume mode, for use by runtime functions.
6725 enum ResumeMode { NEXT, THROW };
6727 // Yielding from a generator returns an object with the following inobject
6728 // properties. See Context::iterator_result_map() for the map.
6729 static const int kResultValuePropertyIndex = 0;
6730 static const int kResultDonePropertyIndex = 1;
6731 static const int kResultPropertyCount = 2;
6733 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6734 static const int kResultDonePropertyOffset =
6735 kResultValuePropertyOffset + kPointerSize;
6736 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6739 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6743 // Representation for module instance objects.
6744 class JSModule: public JSObject {
6746 // [context]: the context holding the module's locals, or undefined if none.
6747 DECL_ACCESSORS(context, Object)
6749 // [scope_info]: Scope info.
6750 DECL_ACCESSORS(scope_info, ScopeInfo)
6752 DECLARE_CAST(JSModule)
6754 // Dispatched behavior.
6755 DECLARE_PRINTER(JSModule)
6756 DECLARE_VERIFIER(JSModule)
6758 // Layout description.
6759 static const int kContextOffset = JSObject::kHeaderSize;
6760 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6761 static const int kSize = kScopeInfoOffset + kPointerSize;
6764 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6768 // JSFunction describes JavaScript functions.
6769 class JSFunction: public JSObject {
6771 // [prototype_or_initial_map]:
6772 DECL_ACCESSORS(prototype_or_initial_map, Object)
6774 // [shared]: The information about the function that
6775 // can be shared by instances.
6776 DECL_ACCESSORS(shared, SharedFunctionInfo)
6778 // [context]: The context for this function.
6779 inline Context* context();
6780 inline void set_context(Object* context);
6781 inline JSObject* global_proxy();
6783 // [code]: The generated code object for this function. Executed
6784 // when the function is invoked, e.g. foo() or new foo(). See
6785 // [[Call]] and [[Construct]] description in ECMA-262, section
6787 inline Code* code();
6788 inline void set_code(Code* code);
6789 inline void set_code_no_write_barrier(Code* code);
6790 inline void ReplaceCode(Code* code);
6792 // Tells whether this function is builtin.
6793 inline bool IsBuiltin();
6795 // Tells whether this function inlines the given shared function info.
6796 bool Inlines(SharedFunctionInfo* candidate);
6798 // Tells whether this function should be subject to debugging.
6799 inline bool IsSubjectToDebugging();
6801 // Tells whether or not the function needs arguments adaption.
6802 inline bool NeedsArgumentsAdaption();
6804 // Tells whether or not this function has been optimized.
6805 inline bool IsOptimized();
6807 // Mark this function for lazy recompilation. The function will be
6808 // recompiled the next time it is executed.
6809 void MarkForOptimization();
6810 void AttemptConcurrentOptimization();
6812 // Tells whether or not the function is already marked for lazy
6814 inline bool IsMarkedForOptimization();
6815 inline bool IsMarkedForConcurrentOptimization();
6817 // Tells whether or not the function is on the concurrent recompilation queue.
6818 inline bool IsInOptimizationQueue();
6820 // Inobject slack tracking is the way to reclaim unused inobject space.
6822 // The instance size is initially determined by adding some slack to
6823 // expected_nof_properties (to allow for a few extra properties added
6824 // after the constructor). There is no guarantee that the extra space
6825 // will not be wasted.
6827 // Here is the algorithm to reclaim the unused inobject space:
6828 // - Detect the first constructor call for this JSFunction.
6829 // When it happens enter the "in progress" state: initialize construction
6830 // counter in the initial_map.
6831 // - While the tracking is in progress create objects filled with
6832 // one_pointer_filler_map instead of undefined_value. This way they can be
6833 // resized quickly and safely.
6834 // - Once enough objects have been created compute the 'slack'
6835 // (traverse the map transition tree starting from the
6836 // initial_map and find the lowest value of unused_property_fields).
6837 // - Traverse the transition tree again and decrease the instance size
6838 // of every map. Existing objects will resize automatically (they are
6839 // filled with one_pointer_filler_map). All further allocations will
6840 // use the adjusted instance size.
6841 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6842 // allocations made using different closures could actually create different
6843 // kind of objects (see prototype inheritance pattern).
6845 // Important: inobject slack tracking is not attempted during the snapshot
6848 // True if the initial_map is set and the object constructions countdown
6849 // counter is not zero.
6850 static const int kGenerousAllocationCount =
6851 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6852 inline bool IsInobjectSlackTrackingInProgress();
6854 // Starts the tracking.
6855 // Initializes object constructions countdown counter in the initial map.
6856 void StartInobjectSlackTracking();
6858 // Completes the tracking.
6859 void CompleteInobjectSlackTracking();
6861 // [literals_or_bindings]: Fixed array holding either
6862 // the materialized literals or the bindings of a bound function.
6864 // If the function contains object, regexp or array literals, the
6865 // literals array prefix contains the object, regexp, and array
6866 // function to be used when creating these literals. This is
6867 // necessary so that we do not dynamically lookup the object, regexp
6868 // or array functions. Performing a dynamic lookup, we might end up
6869 // using the functions from a new context that we should not have
6872 // On bound functions, the array is a (copy-on-write) fixed-array containing
6873 // the function that was bound, bound this-value and any bound
6874 // arguments. Bound functions never contain literals.
6875 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6877 inline FixedArray* literals();
6878 inline void set_literals(FixedArray* literals);
6880 inline FixedArray* function_bindings();
6881 inline void set_function_bindings(FixedArray* bindings);
6883 // The initial map for an object created by this constructor.
6884 inline Map* initial_map();
6885 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
6886 Handle<Object> prototype);
6887 inline bool has_initial_map();
6888 static void EnsureHasInitialMap(Handle<JSFunction> function);
6890 // Get and set the prototype property on a JSFunction. If the
6891 // function has an initial map the prototype is set on the initial
6892 // map. Otherwise, the prototype is put in the initial map field
6893 // until an initial map is needed.
6894 inline bool has_prototype();
6895 inline bool has_instance_prototype();
6896 inline Object* prototype();
6897 inline Object* instance_prototype();
6898 static void SetPrototype(Handle<JSFunction> function,
6899 Handle<Object> value);
6900 static void SetInstancePrototype(Handle<JSFunction> function,
6901 Handle<Object> value);
6903 // Creates a new closure for the fucntion with the same bindings,
6904 // bound values, and prototype. An equivalent of spec operations
6905 // ``CloneMethod`` and ``CloneBoundFunction``.
6906 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
6908 // After prototype is removed, it will not be created when accessed, and
6909 // [[Construct]] from this function will not be allowed.
6910 bool RemovePrototype();
6911 inline bool should_have_prototype();
6913 // Accessor for this function's initial map's [[class]]
6914 // property. This is primarily used by ECMA native functions. This
6915 // method sets the class_name field of this function's initial map
6916 // to a given value. It creates an initial map if this function does
6917 // not have one. Note that this method does not copy the initial map
6918 // if it has one already, but simply replaces it with the new value.
6919 // Instances created afterwards will have a map whose [[class]] is
6920 // set to 'value', but there is no guarantees on instances created
6922 void SetInstanceClassName(String* name);
6924 // Returns if this function has been compiled to native code yet.
6925 inline bool is_compiled();
6927 // Returns `false` if formal parameters include rest parameters, optional
6928 // parameters, or destructuring parameters.
6929 // TODO(caitp): make this a flag set during parsing
6930 inline bool has_simple_parameters();
6932 // [next_function_link]: Links functions into various lists, e.g. the list
6933 // of optimized functions hanging off the native_context. The CodeFlusher
6934 // uses this link to chain together flushing candidates. Treated weakly
6935 // by the garbage collector.
6936 DECL_ACCESSORS(next_function_link, Object)
6938 // Prints the name of the function using PrintF.
6939 void PrintName(FILE* out = stdout);
6941 DECLARE_CAST(JSFunction)
6943 // Iterates the objects, including code objects indirectly referenced
6944 // through pointers to the first instruction in the code object.
6945 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
6947 // Dispatched behavior.
6948 DECLARE_PRINTER(JSFunction)
6949 DECLARE_VERIFIER(JSFunction)
6951 // Returns the number of allocated literals.
6952 inline int NumberOfLiterals();
6954 // Used for flags such as --hydrogen-filter.
6955 bool PassesFilter(const char* raw_filter);
6957 // The function's name if it is configured, otherwise shared function info
6959 static Handle<String> GetDebugName(Handle<JSFunction> function);
6961 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
6962 // kSize) is weak and has special handling during garbage collection.
6963 static const int kCodeEntryOffset = JSObject::kHeaderSize;
6964 static const int kPrototypeOrInitialMapOffset =
6965 kCodeEntryOffset + kPointerSize;
6966 static const int kSharedFunctionInfoOffset =
6967 kPrototypeOrInitialMapOffset + kPointerSize;
6968 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
6969 static const int kLiteralsOffset = kContextOffset + kPointerSize;
6970 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
6971 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
6972 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
6974 // Layout of the bound-function binding array.
6975 static const int kBoundFunctionIndex = 0;
6976 static const int kBoundThisIndex = 1;
6977 static const int kBoundArgumentsStartIndex = 2;
6980 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
6984 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
6985 // and the prototype is hidden. JSGlobalProxy always delegates
6986 // property accesses to its prototype if the prototype is not null.
6988 // A JSGlobalProxy can be reinitialized which will preserve its identity.
6990 // Accessing a JSGlobalProxy requires security check.
6992 class JSGlobalProxy : public JSObject {
6994 // [native_context]: the owner native context of this global proxy object.
6995 // It is null value if this object is not used by any context.
6996 DECL_ACCESSORS(native_context, Object)
6998 // [hash]: The hash code property (undefined if not initialized yet).
6999 DECL_ACCESSORS(hash, Object)
7001 DECLARE_CAST(JSGlobalProxy)
7003 inline bool IsDetachedFrom(GlobalObject* global) const;
7005 // Dispatched behavior.
7006 DECLARE_PRINTER(JSGlobalProxy)
7007 DECLARE_VERIFIER(JSGlobalProxy)
7009 // Layout description.
7010 static const int kNativeContextOffset = JSObject::kHeaderSize;
7011 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7012 static const int kSize = kHashOffset + kPointerSize;
7015 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7019 // Common super class for JavaScript global objects and the special
7020 // builtins global objects.
7021 class GlobalObject: public JSObject {
7023 // [builtins]: the object holding the runtime routines written in JS.
7024 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7026 // [native context]: the natives corresponding to this global object.
7027 DECL_ACCESSORS(native_context, Context)
7029 // [global proxy]: the global proxy object of the context
7030 DECL_ACCESSORS(global_proxy, JSObject)
7032 DECLARE_CAST(GlobalObject)
7034 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7036 // Ensure that the global object has a cell for the given property name.
7037 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7040 // Layout description.
7041 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7042 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7043 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7044 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7047 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7051 // JavaScript global object.
7052 class JSGlobalObject: public GlobalObject {
7054 DECLARE_CAST(JSGlobalObject)
7056 inline bool IsDetached();
7058 // Dispatched behavior.
7059 DECLARE_PRINTER(JSGlobalObject)
7060 DECLARE_VERIFIER(JSGlobalObject)
7062 // Layout description.
7063 static const int kSize = GlobalObject::kHeaderSize;
7066 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7070 // Builtins global object which holds the runtime routines written in
7072 class JSBuiltinsObject: public GlobalObject {
7074 // Accessors for the runtime routines written in JavaScript.
7075 inline Object* javascript_builtin(Builtins::JavaScript id);
7076 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7078 DECLARE_CAST(JSBuiltinsObject)
7080 // Dispatched behavior.
7081 DECLARE_PRINTER(JSBuiltinsObject)
7082 DECLARE_VERIFIER(JSBuiltinsObject)
7084 // Layout description. The size of the builtins object includes
7085 // room for two pointers per runtime routine written in javascript
7086 // (function and code object).
7087 static const int kJSBuiltinsCount = Builtins::id_count;
7088 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7089 static const int kSize =
7090 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7092 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7093 return kJSBuiltinsOffset + id * kPointerSize;
7097 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7101 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7102 class JSValue: public JSObject {
7104 // [value]: the object being wrapped.
7105 DECL_ACCESSORS(value, Object)
7107 DECLARE_CAST(JSValue)
7109 // Dispatched behavior.
7110 DECLARE_PRINTER(JSValue)
7111 DECLARE_VERIFIER(JSValue)
7113 // Layout description.
7114 static const int kValueOffset = JSObject::kHeaderSize;
7115 static const int kSize = kValueOffset + kPointerSize;
7118 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7124 // Representation for JS date objects.
7125 class JSDate: public JSObject {
7127 // If one component is NaN, all of them are, indicating a NaN time value.
7128 // [value]: the time value.
7129 DECL_ACCESSORS(value, Object)
7130 // [year]: caches year. Either undefined, smi, or NaN.
7131 DECL_ACCESSORS(year, Object)
7132 // [month]: caches month. Either undefined, smi, or NaN.
7133 DECL_ACCESSORS(month, Object)
7134 // [day]: caches day. Either undefined, smi, or NaN.
7135 DECL_ACCESSORS(day, Object)
7136 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7137 DECL_ACCESSORS(weekday, Object)
7138 // [hour]: caches hours. Either undefined, smi, or NaN.
7139 DECL_ACCESSORS(hour, Object)
7140 // [min]: caches minutes. Either undefined, smi, or NaN.
7141 DECL_ACCESSORS(min, Object)
7142 // [sec]: caches seconds. Either undefined, smi, or NaN.
7143 DECL_ACCESSORS(sec, Object)
7144 // [cache stamp]: sample of the date cache stamp at the
7145 // moment when chached fields were cached.
7146 DECL_ACCESSORS(cache_stamp, Object)
7148 DECLARE_CAST(JSDate)
7150 // Returns the date field with the specified index.
7151 // See FieldIndex for the list of date fields.
7152 static Object* GetField(Object* date, Smi* index);
7154 void SetValue(Object* value, bool is_value_nan);
7157 // Dispatched behavior.
7158 DECLARE_PRINTER(JSDate)
7159 DECLARE_VERIFIER(JSDate)
7161 // The order is important. It must be kept in sync with date macros
7172 kFirstUncachedField,
7173 kMillisecond = kFirstUncachedField,
7177 kYearUTC = kFirstUTCField,
7190 // Layout description.
7191 static const int kValueOffset = JSObject::kHeaderSize;
7192 static const int kYearOffset = kValueOffset + kPointerSize;
7193 static const int kMonthOffset = kYearOffset + kPointerSize;
7194 static const int kDayOffset = kMonthOffset + kPointerSize;
7195 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7196 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7197 static const int kMinOffset = kHourOffset + kPointerSize;
7198 static const int kSecOffset = kMinOffset + kPointerSize;
7199 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7200 static const int kSize = kCacheStampOffset + kPointerSize;
7203 inline Object* DoGetField(FieldIndex index);
7205 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7207 // Computes and caches the cacheable fields of the date.
7208 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7211 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7215 // Representation of message objects used for error reporting through
7216 // the API. The messages are formatted in JavaScript so this object is
7217 // a real JavaScript object. The information used for formatting the
7218 // error messages are not directly accessible from JavaScript to
7219 // prevent leaking information to user code called during error
7221 class JSMessageObject: public JSObject {
7223 // [type]: the type of error message.
7224 inline int type() const;
7225 inline void set_type(int value);
7227 // [arguments]: the arguments for formatting the error message.
7228 DECL_ACCESSORS(argument, Object)
7230 // [script]: the script from which the error message originated.
7231 DECL_ACCESSORS(script, Object)
7233 // [stack_frames]: an array of stack frames for this error object.
7234 DECL_ACCESSORS(stack_frames, Object)
7236 // [start_position]: the start position in the script for the error message.
7237 inline int start_position() const;
7238 inline void set_start_position(int value);
7240 // [end_position]: the end position in the script for the error message.
7241 inline int end_position() const;
7242 inline void set_end_position(int value);
7244 DECLARE_CAST(JSMessageObject)
7246 // Dispatched behavior.
7247 DECLARE_PRINTER(JSMessageObject)
7248 DECLARE_VERIFIER(JSMessageObject)
7250 // Layout description.
7251 static const int kTypeOffset = JSObject::kHeaderSize;
7252 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7253 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7254 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7255 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7256 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7257 static const int kSize = kEndPositionOffset + kPointerSize;
7259 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7260 kStackFramesOffset + kPointerSize,
7261 kSize> BodyDescriptor;
7265 // Regular expressions
7266 // The regular expression holds a single reference to a FixedArray in
7267 // the kDataOffset field.
7268 // The FixedArray contains the following data:
7269 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7270 // - reference to the original source string
7271 // - reference to the original flag string
7272 // If it is an atom regexp
7273 // - a reference to a literal string to search for
7274 // If it is an irregexp regexp:
7275 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7276 // used for tracking the last usage (used for code flushing).
7277 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7278 // used for tracking the last usage (used for code flushing)..
7279 // - max number of registers used by irregexp implementations.
7280 // - number of capture registers (output values) of the regexp.
7281 class JSRegExp: public JSObject {
7284 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7285 // ATOM: A simple string to match against using an indexOf operation.
7286 // IRREGEXP: Compiled with Irregexp.
7287 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7288 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7295 UNICODE_ESCAPES = 16
7300 explicit Flags(uint32_t value) : value_(value) { }
7301 bool is_global() { return (value_ & GLOBAL) != 0; }
7302 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7303 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7304 bool is_sticky() { return (value_ & STICKY) != 0; }
7305 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7306 uint32_t value() { return value_; }
7311 DECL_ACCESSORS(data, Object)
7313 inline Type TypeTag();
7314 inline int CaptureCount();
7315 inline Flags GetFlags();
7316 inline String* Pattern();
7317 inline Object* DataAt(int index);
7318 // Set implementation data after the object has been prepared.
7319 inline void SetDataAt(int index, Object* value);
7321 static int code_index(bool is_latin1) {
7323 return kIrregexpLatin1CodeIndex;
7325 return kIrregexpUC16CodeIndex;
7329 static int saved_code_index(bool is_latin1) {
7331 return kIrregexpLatin1CodeSavedIndex;
7333 return kIrregexpUC16CodeSavedIndex;
7337 DECLARE_CAST(JSRegExp)
7339 // Dispatched behavior.
7340 DECLARE_VERIFIER(JSRegExp)
7342 static const int kDataOffset = JSObject::kHeaderSize;
7343 static const int kSize = kDataOffset + kPointerSize;
7345 // Indices in the data array.
7346 static const int kTagIndex = 0;
7347 static const int kSourceIndex = kTagIndex + 1;
7348 static const int kFlagsIndex = kSourceIndex + 1;
7349 static const int kDataIndex = kFlagsIndex + 1;
7350 // The data fields are used in different ways depending on the
7351 // value of the tag.
7352 // Atom regexps (literal strings).
7353 static const int kAtomPatternIndex = kDataIndex;
7355 static const int kAtomDataSize = kAtomPatternIndex + 1;
7357 // Irregexp compiled code or bytecode for Latin1. If compilation
7358 // fails, this fields hold an exception object that should be
7359 // thrown if the regexp is used again.
7360 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7361 // Irregexp compiled code or bytecode for UC16. If compilation
7362 // fails, this fields hold an exception object that should be
7363 // thrown if the regexp is used again.
7364 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7366 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7367 // is a potential candidate for flushing.
7368 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7369 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7370 // a potential candidate for flushing.
7371 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7373 // Maximal number of registers used by either Latin1 or UC16.
7374 // Only used to check that there is enough stack space
7375 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7376 // Number of captures in the compiled regexp.
7377 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7379 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7381 // Offsets directly into the data fixed array.
7382 static const int kDataTagOffset =
7383 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7384 static const int kDataOneByteCodeOffset =
7385 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7386 static const int kDataUC16CodeOffset =
7387 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7388 static const int kIrregexpCaptureCountOffset =
7389 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7391 // In-object fields.
7392 static const int kSourceFieldIndex = 0;
7393 static const int kGlobalFieldIndex = 1;
7394 static const int kIgnoreCaseFieldIndex = 2;
7395 static const int kMultilineFieldIndex = 3;
7396 static const int kLastIndexFieldIndex = 4;
7397 static const int kInObjectFieldCount = 5;
7399 // The uninitialized value for a regexp code object.
7400 static const int kUninitializedValue = -1;
7402 // The compilation error value for the regexp code object. The real error
7403 // object is in the saved code field.
7404 static const int kCompilationErrorValue = -2;
7406 // When we store the sweep generation at which we moved the code from the
7407 // code index to the saved code index we mask it of to be in the [0:255]
7409 static const int kCodeAgeMask = 0xff;
7413 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7415 static inline bool IsMatch(HashTableKey* key, Object* value) {
7416 return key->IsMatch(value);
7419 static inline uint32_t Hash(HashTableKey* key) {
7423 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7424 return key->HashForObject(object);
7427 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7429 static const int kPrefixSize = 0;
7430 static const int kEntrySize = 2;
7434 // This cache is used in two different variants. For regexp caching, it simply
7435 // maps identifying info of the regexp to the cached regexp object. Scripts and
7436 // eval code only gets cached after a second probe for the code object. To do
7437 // so, on first "put" only a hash identifying the source is entered into the
7438 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7439 // such lifetimes get reduced, and removed once they reach zero. If a second put
7440 // is called while such a hash is live in the cache, the hash gets replaced by
7441 // an actual cache entry. Age also removes stale live entries from the cache.
7442 // Such entries are identified by SharedFunctionInfos pointing to either the
7443 // recompilation stub, or to "old" code. This avoids memory leaks due to
7444 // premature caching of scripts and eval strings that are never needed later.
7445 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7446 CompilationCacheShape,
7449 // Find cached value for a string key, otherwise return null.
7450 Handle<Object> Lookup(
7451 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7452 Handle<Object> LookupEval(
7453 Handle<String> src, Handle<SharedFunctionInfo> shared,
7454 LanguageMode language_mode, int scope_position);
7455 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7456 static Handle<CompilationCacheTable> Put(
7457 Handle<CompilationCacheTable> cache, Handle<String> src,
7458 Handle<Context> context, LanguageMode language_mode,
7459 Handle<Object> value);
7460 static Handle<CompilationCacheTable> PutEval(
7461 Handle<CompilationCacheTable> cache, Handle<String> src,
7462 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7463 int scope_position);
7464 static Handle<CompilationCacheTable> PutRegExp(
7465 Handle<CompilationCacheTable> cache, Handle<String> src,
7466 JSRegExp::Flags flags, Handle<FixedArray> value);
7467 void Remove(Object* value);
7469 static const int kHashGenerations = 10;
7471 DECLARE_CAST(CompilationCacheTable)
7474 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7478 class CodeCache: public Struct {
7480 DECL_ACCESSORS(default_cache, FixedArray)
7481 DECL_ACCESSORS(normal_type_cache, Object)
7483 // Add the code object to the cache.
7485 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7487 // Lookup code object in the cache. Returns code object if found and undefined
7489 Object* Lookup(Name* name, Code::Flags flags);
7491 // Get the internal index of a code object in the cache. Returns -1 if the
7492 // code object is not in that cache. This index can be used to later call
7493 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7495 int GetIndex(Object* name, Code* code);
7497 // Remove an object from the cache with the provided internal index.
7498 void RemoveByIndex(Object* name, Code* code, int index);
7500 DECLARE_CAST(CodeCache)
7502 // Dispatched behavior.
7503 DECLARE_PRINTER(CodeCache)
7504 DECLARE_VERIFIER(CodeCache)
7506 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7507 static const int kNormalTypeCacheOffset =
7508 kDefaultCacheOffset + kPointerSize;
7509 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7512 static void UpdateDefaultCache(
7513 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7514 static void UpdateNormalTypeCache(
7515 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7516 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7517 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7519 // Code cache layout of the default cache. Elements are alternating name and
7520 // code objects for non normal load/store/call IC's.
7521 static const int kCodeCacheEntrySize = 2;
7522 static const int kCodeCacheEntryNameOffset = 0;
7523 static const int kCodeCacheEntryCodeOffset = 1;
7525 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7529 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7531 static inline bool IsMatch(HashTableKey* key, Object* value) {
7532 return key->IsMatch(value);
7535 static inline uint32_t Hash(HashTableKey* key) {
7539 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7540 return key->HashForObject(object);
7543 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7545 static const int kPrefixSize = 0;
7546 static const int kEntrySize = 2;
7550 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7551 CodeCacheHashTableShape,
7554 Object* Lookup(Name* name, Code::Flags flags);
7555 static Handle<CodeCacheHashTable> Put(
7556 Handle<CodeCacheHashTable> table,
7560 int GetIndex(Name* name, Code::Flags flags);
7561 void RemoveByIndex(int index);
7563 DECLARE_CAST(CodeCacheHashTable)
7565 // Initial size of the fixed array backing the hash table.
7566 static const int kInitialSize = 64;
7569 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7573 class PolymorphicCodeCache: public Struct {
7575 DECL_ACCESSORS(cache, Object)
7577 static void Update(Handle<PolymorphicCodeCache> cache,
7578 MapHandleList* maps,
7583 // Returns an undefined value if the entry is not found.
7584 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7586 DECLARE_CAST(PolymorphicCodeCache)
7588 // Dispatched behavior.
7589 DECLARE_PRINTER(PolymorphicCodeCache)
7590 DECLARE_VERIFIER(PolymorphicCodeCache)
7592 static const int kCacheOffset = HeapObject::kHeaderSize;
7593 static const int kSize = kCacheOffset + kPointerSize;
7596 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7600 class PolymorphicCodeCacheHashTable
7601 : public HashTable<PolymorphicCodeCacheHashTable,
7602 CodeCacheHashTableShape,
7605 Object* Lookup(MapHandleList* maps, int code_kind);
7607 static Handle<PolymorphicCodeCacheHashTable> Put(
7608 Handle<PolymorphicCodeCacheHashTable> hash_table,
7609 MapHandleList* maps,
7613 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7615 static const int kInitialSize = 64;
7617 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7621 class TypeFeedbackInfo: public Struct {
7623 inline int ic_total_count();
7624 inline void set_ic_total_count(int count);
7626 inline int ic_with_type_info_count();
7627 inline void change_ic_with_type_info_count(int delta);
7629 inline int ic_generic_count();
7630 inline void change_ic_generic_count(int delta);
7632 inline void initialize_storage();
7634 inline void change_own_type_change_checksum();
7635 inline int own_type_change_checksum();
7637 inline void set_inlined_type_change_checksum(int checksum);
7638 inline bool matches_inlined_type_change_checksum(int checksum);
7640 DECLARE_CAST(TypeFeedbackInfo)
7642 // Dispatched behavior.
7643 DECLARE_PRINTER(TypeFeedbackInfo)
7644 DECLARE_VERIFIER(TypeFeedbackInfo)
7646 static const int kStorage1Offset = HeapObject::kHeaderSize;
7647 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7648 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7649 static const int kSize = kStorage3Offset + kPointerSize;
7652 static const int kTypeChangeChecksumBits = 7;
7654 class ICTotalCountField: public BitField<int, 0,
7655 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7656 class OwnTypeChangeChecksum: public BitField<int,
7657 kSmiValueSize - kTypeChangeChecksumBits,
7658 kTypeChangeChecksumBits> {}; // NOLINT
7659 class ICsWithTypeInfoCountField: public BitField<int, 0,
7660 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7661 class InlinedTypeChangeChecksum: public BitField<int,
7662 kSmiValueSize - kTypeChangeChecksumBits,
7663 kTypeChangeChecksumBits> {}; // NOLINT
7665 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7669 enum AllocationSiteMode {
7670 DONT_TRACK_ALLOCATION_SITE,
7671 TRACK_ALLOCATION_SITE,
7672 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7676 class AllocationSite: public Struct {
7678 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7679 static const double kPretenureRatio;
7680 static const int kPretenureMinimumCreated = 100;
7682 // Values for pretenure decision field.
7683 enum PretenureDecision {
7689 kLastPretenureDecisionValue = kZombie
7692 const char* PretenureDecisionName(PretenureDecision decision);
7694 DECL_ACCESSORS(transition_info, Object)
7695 // nested_site threads a list of sites that represent nested literals
7696 // walked in a particular order. So [[1, 2], 1, 2] will have one
7697 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7698 DECL_ACCESSORS(nested_site, Object)
7699 DECL_ACCESSORS(pretenure_data, Smi)
7700 DECL_ACCESSORS(pretenure_create_count, Smi)
7701 DECL_ACCESSORS(dependent_code, DependentCode)
7702 DECL_ACCESSORS(weak_next, Object)
7704 inline void Initialize();
7706 // This method is expensive, it should only be called for reporting.
7707 bool IsNestedSite();
7709 // transition_info bitfields, for constructed array transition info.
7710 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7711 class UnusedBits: public BitField<int, 15, 14> {};
7712 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7714 // Bitfields for pretenure_data
7715 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7716 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7717 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7718 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7720 // Increments the mementos found counter and returns true when the first
7721 // memento was found for a given allocation site.
7722 inline bool IncrementMementoFoundCount();
7724 inline void IncrementMementoCreateCount();
7726 PretenureFlag GetPretenureMode();
7728 void ResetPretenureDecision();
7730 inline PretenureDecision pretenure_decision();
7731 inline void set_pretenure_decision(PretenureDecision decision);
7733 inline bool deopt_dependent_code();
7734 inline void set_deopt_dependent_code(bool deopt);
7736 inline int memento_found_count();
7737 inline void set_memento_found_count(int count);
7739 inline int memento_create_count();
7740 inline void set_memento_create_count(int count);
7742 // The pretenuring decision is made during gc, and the zombie state allows
7743 // us to recognize when an allocation site is just being kept alive because
7744 // a later traversal of new space may discover AllocationMementos that point
7745 // to this AllocationSite.
7746 inline bool IsZombie();
7748 inline bool IsMaybeTenure();
7750 inline void MarkZombie();
7752 inline bool MakePretenureDecision(PretenureDecision current_decision,
7754 bool maximum_size_scavenge);
7756 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7758 inline ElementsKind GetElementsKind();
7759 inline void SetElementsKind(ElementsKind kind);
7761 inline bool CanInlineCall();
7762 inline void SetDoNotInlineCall();
7764 inline bool SitePointsToLiteral();
7766 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7767 ElementsKind to_kind);
7769 DECLARE_PRINTER(AllocationSite)
7770 DECLARE_VERIFIER(AllocationSite)
7772 DECLARE_CAST(AllocationSite)
7773 static inline AllocationSiteMode GetMode(
7774 ElementsKind boilerplate_elements_kind);
7775 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7776 static inline bool CanTrack(InstanceType type);
7778 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7779 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7780 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7781 static const int kPretenureCreateCountOffset =
7782 kPretenureDataOffset + kPointerSize;
7783 static const int kDependentCodeOffset =
7784 kPretenureCreateCountOffset + kPointerSize;
7785 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7786 static const int kSize = kWeakNextOffset + kPointerSize;
7788 // During mark compact we need to take special care for the dependent code
7790 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7791 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7793 // For other visitors, use the fixed body descriptor below.
7794 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7795 kDependentCodeOffset + kPointerSize,
7796 kSize> BodyDescriptor;
7799 inline bool PretenuringDecisionMade();
7801 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7805 class AllocationMemento: public Struct {
7807 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7808 static const int kSize = kAllocationSiteOffset + kPointerSize;
7810 DECL_ACCESSORS(allocation_site, Object)
7812 inline bool IsValid();
7813 inline AllocationSite* GetAllocationSite();
7815 DECLARE_PRINTER(AllocationMemento)
7816 DECLARE_VERIFIER(AllocationMemento)
7818 DECLARE_CAST(AllocationMemento)
7821 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7825 // Representation of a slow alias as part of a sloppy arguments objects.
7826 // For fast aliases (if HasSloppyArgumentsElements()):
7827 // - the parameter map contains an index into the context
7828 // - all attributes of the element have default values
7829 // For slow aliases (if HasDictionaryArgumentsElements()):
7830 // - the parameter map contains no fast alias mapping (i.e. the hole)
7831 // - this struct (in the slow backing store) contains an index into the context
7832 // - all attributes are available as part if the property details
7833 class AliasedArgumentsEntry: public Struct {
7835 inline int aliased_context_slot() const;
7836 inline void set_aliased_context_slot(int count);
7838 DECLARE_CAST(AliasedArgumentsEntry)
7840 // Dispatched behavior.
7841 DECLARE_PRINTER(AliasedArgumentsEntry)
7842 DECLARE_VERIFIER(AliasedArgumentsEntry)
7844 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7845 static const int kSize = kAliasedContextSlot + kPointerSize;
7848 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7852 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7853 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7856 class StringHasher {
7858 explicit inline StringHasher(int length, uint32_t seed);
7860 template <typename schar>
7861 static inline uint32_t HashSequentialString(const schar* chars,
7865 // Reads all the data, even for long strings and computes the utf16 length.
7866 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7868 int* utf16_length_out);
7870 // Calculated hash value for a string consisting of 1 to
7871 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7872 // value is represented decimal value.
7873 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7875 // No string is allowed to have a hash of zero. That value is reserved
7876 // for internal properties. If the hash calculation yields zero then we
7878 static const int kZeroHash = 27;
7880 // Reusable parts of the hashing algorithm.
7881 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7882 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7883 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7884 const uc16* chars, int length));
7885 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
7890 // Returns the value to store in the hash field of a string with
7891 // the given length and contents.
7892 uint32_t GetHashField();
7893 // Returns true if the hash of this string can be computed without
7894 // looking at the contents.
7895 inline bool has_trivial_hash();
7896 // Adds a block of characters to the hash.
7897 template<typename Char>
7898 inline void AddCharacters(const Char* chars, int len);
7901 // Add a character to the hash.
7902 inline void AddCharacter(uint16_t c);
7903 // Update index. Returns true if string is still an index.
7904 inline bool UpdateIndex(uint16_t c);
7907 uint32_t raw_running_hash_;
7908 uint32_t array_index_;
7909 bool is_array_index_;
7910 bool is_first_char_;
7911 DISALLOW_COPY_AND_ASSIGN(StringHasher);
7915 class IteratingStringHasher : public StringHasher {
7917 static inline uint32_t Hash(String* string, uint32_t seed);
7918 inline void VisitOneByteString(const uint8_t* chars, int length);
7919 inline void VisitTwoByteString(const uint16_t* chars, int length);
7922 inline IteratingStringHasher(int len, uint32_t seed);
7923 void VisitConsString(ConsString* cons_string);
7924 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
7928 // The characteristics of a string are stored in its map. Retrieving these
7929 // few bits of information is moderately expensive, involving two memory
7930 // loads where the second is dependent on the first. To improve efficiency
7931 // the shape of the string is given its own class so that it can be retrieved
7932 // once and used for several string operations. A StringShape is small enough
7933 // to be passed by value and is immutable, but be aware that flattening a
7934 // string can potentially alter its shape. Also be aware that a GC caused by
7935 // something else can alter the shape of a string due to ConsString
7936 // shortcutting. Keeping these restrictions in mind has proven to be error-
7937 // prone and so we no longer put StringShapes in variables unless there is a
7938 // concrete performance benefit at that particular point in the code.
7939 class StringShape BASE_EMBEDDED {
7941 inline explicit StringShape(const String* s);
7942 inline explicit StringShape(Map* s);
7943 inline explicit StringShape(InstanceType t);
7944 inline bool IsSequential();
7945 inline bool IsExternal();
7946 inline bool IsCons();
7947 inline bool IsSliced();
7948 inline bool IsIndirect();
7949 inline bool IsExternalOneByte();
7950 inline bool IsExternalTwoByte();
7951 inline bool IsSequentialOneByte();
7952 inline bool IsSequentialTwoByte();
7953 inline bool IsInternalized();
7954 inline StringRepresentationTag representation_tag();
7955 inline uint32_t encoding_tag();
7956 inline uint32_t full_representation_tag();
7957 inline uint32_t size_tag();
7959 inline uint32_t type() { return type_; }
7960 inline void invalidate() { valid_ = false; }
7961 inline bool valid() { return valid_; }
7963 inline void invalidate() { }
7969 inline void set_valid() { valid_ = true; }
7972 inline void set_valid() { }
7977 // The Name abstract class captures anything that can be used as a property
7978 // name, i.e., strings and symbols. All names store a hash value.
7979 class Name: public HeapObject {
7981 // Get and set the hash field of the name.
7982 inline uint32_t hash_field();
7983 inline void set_hash_field(uint32_t value);
7985 // Tells whether the hash code has been computed.
7986 inline bool HasHashCode();
7988 // Returns a hash value used for the property table
7989 inline uint32_t Hash();
7991 // Equality operations.
7992 inline bool Equals(Name* other);
7993 inline static bool Equals(Handle<Name> one, Handle<Name> two);
7996 inline bool AsArrayIndex(uint32_t* index);
7998 // If the name is private, it can only name own properties.
7999 inline bool IsPrivate();
8001 // If the name is a non-flat string, this method returns a flat version of the
8002 // string. Otherwise it'll just return the input.
8003 static inline Handle<Name> Flatten(Handle<Name> name,
8004 PretenureFlag pretenure = NOT_TENURED);
8008 DECLARE_PRINTER(Name)
8010 void NameShortPrint();
8011 int NameShortPrint(Vector<char> str);
8014 // Layout description.
8015 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8016 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8017 static const int kHashFieldOffset = kHashFieldSlot;
8019 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8021 static const int kSize = kHashFieldSlot + kPointerSize;
8023 // Mask constant for checking if a name has a computed hash code
8024 // and if it is a string that is an array index. The least significant bit
8025 // indicates whether a hash code has been computed. If the hash code has
8026 // been computed the 2nd bit tells whether the string can be used as an
8028 static const int kHashNotComputedMask = 1;
8029 static const int kIsNotArrayIndexMask = 1 << 1;
8030 static const int kNofHashBitFields = 2;
8032 // Shift constant retrieving hash code from hash field.
8033 static const int kHashShift = kNofHashBitFields;
8035 // Only these bits are relevant in the hash, since the top two are shifted
8037 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8039 // Array index strings this short can keep their index in the hash field.
8040 static const int kMaxCachedArrayIndexLength = 7;
8042 // For strings which are array indexes the hash value has the string length
8043 // mixed into the hash, mainly to avoid a hash value of zero which would be
8044 // the case for the string '0'. 24 bits are used for the array index value.
8045 static const int kArrayIndexValueBits = 24;
8046 static const int kArrayIndexLengthBits =
8047 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8049 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8051 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8052 kArrayIndexValueBits> {}; // NOLINT
8053 class ArrayIndexLengthBits : public BitField<unsigned int,
8054 kNofHashBitFields + kArrayIndexValueBits,
8055 kArrayIndexLengthBits> {}; // NOLINT
8057 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8058 // could use a mask to test if the length of string is less than or equal to
8059 // kMaxCachedArrayIndexLength.
8060 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8062 static const unsigned int kContainsCachedArrayIndexMask =
8063 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8064 << ArrayIndexLengthBits::kShift) |
8065 kIsNotArrayIndexMask;
8067 // Value of empty hash field indicating that the hash is not computed.
8068 static const int kEmptyHashField =
8069 kIsNotArrayIndexMask | kHashNotComputedMask;
8072 static inline bool IsHashFieldComputed(uint32_t field);
8075 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8080 class Symbol: public Name {
8082 // [name]: The print name of a symbol, or undefined if none.
8083 DECL_ACCESSORS(name, Object)
8085 DECL_ACCESSORS(flags, Smi)
8087 // [is_private]: Whether this is a private symbol. Private symbols can only
8088 // be used to designate own properties of objects.
8089 DECL_BOOLEAN_ACCESSORS(is_private)
8091 DECLARE_CAST(Symbol)
8093 // Dispatched behavior.
8094 DECLARE_PRINTER(Symbol)
8095 DECLARE_VERIFIER(Symbol)
8097 // Layout description.
8098 static const int kNameOffset = Name::kSize;
8099 static const int kFlagsOffset = kNameOffset + kPointerSize;
8100 static const int kSize = kFlagsOffset + kPointerSize;
8102 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8104 void SymbolShortPrint(std::ostream& os);
8107 static const int kPrivateBit = 0;
8109 const char* PrivateSymbolToName() const;
8112 friend class Name; // For PrivateSymbolToName.
8115 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8121 // The String abstract class captures JavaScript string values:
8124 // 4.3.16 String Value
8125 // A string value is a member of the type String and is a finite
8126 // ordered sequence of zero or more 16-bit unsigned integer values.
8128 // All string values have a length field.
8129 class String: public Name {
8131 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8133 // Array index strings this short can keep their index in the hash field.
8134 static const int kMaxCachedArrayIndexLength = 7;
8136 // For strings which are array indexes the hash value has the string length
8137 // mixed into the hash, mainly to avoid a hash value of zero which would be
8138 // the case for the string '0'. 24 bits are used for the array index value.
8139 static const int kArrayIndexValueBits = 24;
8140 static const int kArrayIndexLengthBits =
8141 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8143 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8145 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8146 kArrayIndexValueBits> {}; // NOLINT
8147 class ArrayIndexLengthBits : public BitField<unsigned int,
8148 kNofHashBitFields + kArrayIndexValueBits,
8149 kArrayIndexLengthBits> {}; // NOLINT
8151 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8152 // could use a mask to test if the length of string is less than or equal to
8153 // kMaxCachedArrayIndexLength.
8154 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8156 static const unsigned int kContainsCachedArrayIndexMask =
8157 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8158 << ArrayIndexLengthBits::kShift) |
8159 kIsNotArrayIndexMask;
8161 class SubStringRange {
8163 explicit inline SubStringRange(String* string, int first = 0,
8166 inline iterator begin();
8167 inline iterator end();
8175 // Representation of the flat content of a String.
8176 // A non-flat string doesn't have flat content.
8177 // A flat string has content that's encoded as a sequence of either
8178 // one-byte chars or two-byte UC16.
8179 // Returned by String::GetFlatContent().
8182 // Returns true if the string is flat and this structure contains content.
8183 bool IsFlat() { return state_ != NON_FLAT; }
8184 // Returns true if the structure contains one-byte content.
8185 bool IsOneByte() { return state_ == ONE_BYTE; }
8186 // Returns true if the structure contains two-byte content.
8187 bool IsTwoByte() { return state_ == TWO_BYTE; }
8189 // Return the one byte content of the string. Only use if IsOneByte()
8191 Vector<const uint8_t> ToOneByteVector() {
8192 DCHECK_EQ(ONE_BYTE, state_);
8193 return Vector<const uint8_t>(onebyte_start, length_);
8195 // Return the two-byte content of the string. Only use if IsTwoByte()
8197 Vector<const uc16> ToUC16Vector() {
8198 DCHECK_EQ(TWO_BYTE, state_);
8199 return Vector<const uc16>(twobyte_start, length_);
8203 DCHECK(i < length_);
8204 DCHECK(state_ != NON_FLAT);
8205 if (state_ == ONE_BYTE) return onebyte_start[i];
8206 return twobyte_start[i];
8209 bool UsesSameString(const FlatContent& other) const {
8210 return onebyte_start == other.onebyte_start;
8214 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8216 // Constructors only used by String::GetFlatContent().
8217 explicit FlatContent(const uint8_t* start, int length)
8218 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8219 explicit FlatContent(const uc16* start, int length)
8220 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8221 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8224 const uint8_t* onebyte_start;
8225 const uc16* twobyte_start;
8230 friend class String;
8231 friend class IterableSubString;
8234 template <typename Char>
8235 INLINE(Vector<const Char> GetCharVector());
8237 // Get and set the length of the string.
8238 inline int length() const;
8239 inline void set_length(int value);
8241 // Get and set the length of the string using acquire loads and release
8243 inline int synchronized_length() const;
8244 inline void synchronized_set_length(int value);
8246 // Returns whether this string has only one-byte chars, i.e. all of them can
8247 // be one-byte encoded. This might be the case even if the string is
8248 // two-byte. Such strings may appear when the embedder prefers
8249 // two-byte external representations even for one-byte data.
8250 inline bool IsOneByteRepresentation() const;
8251 inline bool IsTwoByteRepresentation() const;
8253 // Cons and slices have an encoding flag that may not represent the actual
8254 // encoding of the underlying string. This is taken into account here.
8255 // Requires: this->IsFlat()
8256 inline bool IsOneByteRepresentationUnderneath();
8257 inline bool IsTwoByteRepresentationUnderneath();
8259 // NOTE: this should be considered only a hint. False negatives are
8261 inline bool HasOnlyOneByteChars();
8263 // Get and set individual two byte chars in the string.
8264 inline void Set(int index, uint16_t value);
8265 // Get individual two byte char in the string. Repeated calls
8266 // to this method are not efficient unless the string is flat.
8267 INLINE(uint16_t Get(int index));
8269 // Flattens the string. Checks first inline to see if it is
8270 // necessary. Does nothing if the string is not a cons string.
8271 // Flattening allocates a sequential string with the same data as
8272 // the given string and mutates the cons string to a degenerate
8273 // form, where the first component is the new sequential string and
8274 // the second component is the empty string. If allocation fails,
8275 // this function returns a failure. If flattening succeeds, this
8276 // function returns the sequential string that is now the first
8277 // component of the cons string.
8279 // Degenerate cons strings are handled specially by the garbage
8280 // collector (see IsShortcutCandidate).
8282 static inline Handle<String> Flatten(Handle<String> string,
8283 PretenureFlag pretenure = NOT_TENURED);
8285 // Tries to return the content of a flat string as a structure holding either
8286 // a flat vector of char or of uc16.
8287 // If the string isn't flat, and therefore doesn't have flat content, the
8288 // returned structure will report so, and can't provide a vector of either
8290 FlatContent GetFlatContent();
8292 // Returns the parent of a sliced string or first part of a flat cons string.
8293 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8294 inline String* GetUnderlying();
8296 // String equality operations.
8297 inline bool Equals(String* other);
8298 inline static bool Equals(Handle<String> one, Handle<String> two);
8299 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8300 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8301 bool IsTwoByteEqualTo(Vector<const uc16> str);
8303 // Return a UTF8 representation of the string. The string is null
8304 // terminated but may optionally contain nulls. Length is returned
8305 // in length_output if length_output is not a null pointer The string
8306 // should be nearly flat, otherwise the performance of this method may
8307 // be very slow (quadratic in the length). Setting robustness_flag to
8308 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8309 // handles unexpected data without causing assert failures and it does not
8310 // do any heap allocations. This is useful when printing stack traces.
8311 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8312 RobustnessFlag robustness_flag,
8313 int offset, int length,
8314 int* length_output = 0);
8315 base::SmartArrayPointer<char> ToCString(
8316 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8317 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8318 int* length_output = 0);
8320 // Return a 16 bit Unicode representation of the string.
8321 // The string should be nearly flat, otherwise the performance of
8322 // of this method may be very bad. Setting robustness_flag to
8323 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8324 // handles unexpected data without causing assert failures and it does not
8325 // do any heap allocations. This is useful when printing stack traces.
8326 base::SmartArrayPointer<uc16> ToWideCString(
8327 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8329 bool ComputeArrayIndex(uint32_t* index);
8332 bool MakeExternal(v8::String::ExternalStringResource* resource);
8333 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8336 inline bool AsArrayIndex(uint32_t* index);
8338 DECLARE_CAST(String)
8340 void PrintOn(FILE* out);
8342 // For use during stack traces. Performs rudimentary sanity check.
8345 // Dispatched behavior.
8346 void StringShortPrint(StringStream* accumulator);
8347 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8348 #if defined(DEBUG) || defined(OBJECT_PRINT)
8349 char* ToAsciiArray();
8351 DECLARE_PRINTER(String)
8352 DECLARE_VERIFIER(String)
8354 inline bool IsFlat();
8356 // Layout description.
8357 static const int kLengthOffset = Name::kSize;
8358 static const int kSize = kLengthOffset + kPointerSize;
8360 // Maximum number of characters to consider when trying to convert a string
8361 // value into an array index.
8362 static const int kMaxArrayIndexSize = 10;
8363 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8366 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8367 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8368 static const int kMaxUtf16CodeUnit = 0xffff;
8369 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8371 // Value of hash field containing computed hash equal to zero.
8372 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8374 // Maximal string length.
8375 static const int kMaxLength = (1 << 28) - 16;
8377 // Max length for computing hash. For strings longer than this limit the
8378 // string length is used as the hash value.
8379 static const int kMaxHashCalcLength = 16383;
8381 // Limit for truncation in short printing.
8382 static const int kMaxShortPrintLength = 1024;
8384 // Support for regular expressions.
8385 const uc16* GetTwoByteData(unsigned start);
8387 // Helper function for flattening strings.
8388 template <typename sinkchar>
8389 static void WriteToFlat(String* source,
8394 // The return value may point to the first aligned word containing the first
8395 // non-one-byte character, rather than directly to the non-one-byte character.
8396 // If the return value is >= the passed length, the entire string was
8398 static inline int NonAsciiStart(const char* chars, int length) {
8399 const char* start = chars;
8400 const char* limit = chars + length;
8402 if (length >= kIntptrSize) {
8403 // Check unaligned bytes.
8404 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8405 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8406 return static_cast<int>(chars - start);
8410 // Check aligned words.
8411 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8412 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8413 while (chars + sizeof(uintptr_t) <= limit) {
8414 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8415 return static_cast<int>(chars - start);
8417 chars += sizeof(uintptr_t);
8420 // Check remaining unaligned bytes.
8421 while (chars < limit) {
8422 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8423 return static_cast<int>(chars - start);
8428 return static_cast<int>(chars - start);
8431 static inline bool IsAscii(const char* chars, int length) {
8432 return NonAsciiStart(chars, length) >= length;
8435 static inline bool IsAscii(const uint8_t* chars, int length) {
8437 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8440 static inline int NonOneByteStart(const uc16* chars, int length) {
8441 const uc16* limit = chars + length;
8442 const uc16* start = chars;
8443 while (chars < limit) {
8444 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8447 return static_cast<int>(chars - start);
8450 static inline bool IsOneByte(const uc16* chars, int length) {
8451 return NonOneByteStart(chars, length) >= length;
8454 template<class Visitor>
8455 static inline ConsString* VisitFlat(Visitor* visitor,
8459 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8460 bool include_ending_line);
8462 // Use the hash field to forward to the canonical internalized string
8463 // when deserializing an internalized string.
8464 inline void SetForwardedInternalizedString(String* string);
8465 inline String* GetForwardedInternalizedString();
8469 friend class StringTableInsertionKey;
8471 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8472 PretenureFlag tenure);
8474 // Slow case of String::Equals. This implementation works on any strings
8475 // but it is most efficient on strings that are almost flat.
8476 bool SlowEquals(String* other);
8478 static bool SlowEquals(Handle<String> one, Handle<String> two);
8480 // Slow case of AsArrayIndex.
8481 bool SlowAsArrayIndex(uint32_t* index);
8483 // Compute and set the hash code.
8484 uint32_t ComputeAndSetHash();
8486 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8490 // The SeqString abstract class captures sequential string values.
8491 class SeqString: public String {
8493 DECLARE_CAST(SeqString)
8495 // Layout description.
8496 static const int kHeaderSize = String::kSize;
8498 // Truncate the string in-place if possible and return the result.
8499 // In case of new_length == 0, the empty string is returned without
8500 // truncating the original string.
8501 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8504 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8508 // The OneByteString class captures sequential one-byte string objects.
8509 // Each character in the OneByteString is an one-byte character.
8510 class SeqOneByteString: public SeqString {
8512 static const bool kHasOneByteEncoding = true;
8514 // Dispatched behavior.
8515 inline uint16_t SeqOneByteStringGet(int index);
8516 inline void SeqOneByteStringSet(int index, uint16_t value);
8518 // Get the address of the characters in this string.
8519 inline Address GetCharsAddress();
8521 inline uint8_t* GetChars();
8523 DECLARE_CAST(SeqOneByteString)
8525 // Garbage collection support. This method is called by the
8526 // garbage collector to compute the actual size of an OneByteString
8528 inline int SeqOneByteStringSize(InstanceType instance_type);
8530 // Computes the size for an OneByteString instance of a given length.
8531 static int SizeFor(int length) {
8532 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8535 // Maximal memory usage for a single sequential one-byte string.
8536 static const int kMaxSize = 512 * MB - 1;
8537 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8540 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8544 // The TwoByteString class captures sequential unicode string objects.
8545 // Each character in the TwoByteString is a two-byte uint16_t.
8546 class SeqTwoByteString: public SeqString {
8548 static const bool kHasOneByteEncoding = false;
8550 // Dispatched behavior.
8551 inline uint16_t SeqTwoByteStringGet(int index);
8552 inline void SeqTwoByteStringSet(int index, uint16_t value);
8554 // Get the address of the characters in this string.
8555 inline Address GetCharsAddress();
8557 inline uc16* GetChars();
8560 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8562 DECLARE_CAST(SeqTwoByteString)
8564 // Garbage collection support. This method is called by the
8565 // garbage collector to compute the actual size of a TwoByteString
8567 inline int SeqTwoByteStringSize(InstanceType instance_type);
8569 // Computes the size for a TwoByteString instance of a given length.
8570 static int SizeFor(int length) {
8571 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8574 // Maximal memory usage for a single sequential two-byte string.
8575 static const int kMaxSize = 512 * MB - 1;
8576 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8577 String::kMaxLength);
8580 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8584 // The ConsString class describes string values built by using the
8585 // addition operator on strings. A ConsString is a pair where the
8586 // first and second components are pointers to other string values.
8587 // One or both components of a ConsString can be pointers to other
8588 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8589 // are non-ConsString string values. The string value represented by
8590 // a ConsString can be obtained by concatenating the leaf string
8591 // values in a left-to-right depth-first traversal of the tree.
8592 class ConsString: public String {
8594 // First string of the cons cell.
8595 inline String* first();
8596 // Doesn't check that the result is a string, even in debug mode. This is
8597 // useful during GC where the mark bits confuse the checks.
8598 inline Object* unchecked_first();
8599 inline void set_first(String* first,
8600 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8602 // Second string of the cons cell.
8603 inline String* second();
8604 // Doesn't check that the result is a string, even in debug mode. This is
8605 // useful during GC where the mark bits confuse the checks.
8606 inline Object* unchecked_second();
8607 inline void set_second(String* second,
8608 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8610 // Dispatched behavior.
8611 uint16_t ConsStringGet(int index);
8613 DECLARE_CAST(ConsString)
8615 // Layout description.
8616 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8617 static const int kSecondOffset = kFirstOffset + kPointerSize;
8618 static const int kSize = kSecondOffset + kPointerSize;
8620 // Minimum length for a cons string.
8621 static const int kMinLength = 13;
8623 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8626 DECLARE_VERIFIER(ConsString)
8629 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8633 // The Sliced String class describes strings that are substrings of another
8634 // sequential string. The motivation is to save time and memory when creating
8635 // a substring. A Sliced String is described as a pointer to the parent,
8636 // the offset from the start of the parent string and the length. Using
8637 // a Sliced String therefore requires unpacking of the parent string and
8638 // adding the offset to the start address. A substring of a Sliced String
8639 // are not nested since the double indirection is simplified when creating
8640 // such a substring.
8641 // Currently missing features are:
8642 // - handling externalized parent strings
8643 // - external strings as parent
8644 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8645 class SlicedString: public String {
8647 inline String* parent();
8648 inline void set_parent(String* parent,
8649 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8650 inline int offset() const;
8651 inline void set_offset(int offset);
8653 // Dispatched behavior.
8654 uint16_t SlicedStringGet(int index);
8656 DECLARE_CAST(SlicedString)
8658 // Layout description.
8659 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8660 static const int kOffsetOffset = kParentOffset + kPointerSize;
8661 static const int kSize = kOffsetOffset + kPointerSize;
8663 // Minimum length for a sliced string.
8664 static const int kMinLength = 13;
8666 typedef FixedBodyDescriptor<kParentOffset,
8667 kOffsetOffset + kPointerSize, kSize>
8670 DECLARE_VERIFIER(SlicedString)
8673 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8677 // The ExternalString class describes string values that are backed by
8678 // a string resource that lies outside the V8 heap. ExternalStrings
8679 // consist of the length field common to all strings, a pointer to the
8680 // external resource. It is important to ensure (externally) that the
8681 // resource is not deallocated while the ExternalString is live in the
8684 // The API expects that all ExternalStrings are created through the
8685 // API. Therefore, ExternalStrings should not be used internally.
8686 class ExternalString: public String {
8688 DECLARE_CAST(ExternalString)
8690 // Layout description.
8691 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8692 static const int kShortSize = kResourceOffset + kPointerSize;
8693 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8694 static const int kSize = kResourceDataOffset + kPointerSize;
8696 static const int kMaxShortLength =
8697 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8699 // Return whether external string is short (data pointer is not cached).
8700 inline bool is_short();
8702 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8705 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8709 // The ExternalOneByteString class is an external string backed by an
8711 class ExternalOneByteString : public ExternalString {
8713 static const bool kHasOneByteEncoding = true;
8715 typedef v8::String::ExternalOneByteStringResource Resource;
8717 // The underlying resource.
8718 inline const Resource* resource();
8719 inline void set_resource(const Resource* buffer);
8721 // Update the pointer cache to the external character array.
8722 // The cached pointer is always valid, as the external character array does =
8723 // not move during lifetime. Deserialization is the only exception, after
8724 // which the pointer cache has to be refreshed.
8725 inline void update_data_cache();
8727 inline const uint8_t* GetChars();
8729 // Dispatched behavior.
8730 inline uint16_t ExternalOneByteStringGet(int index);
8732 DECLARE_CAST(ExternalOneByteString)
8734 // Garbage collection support.
8735 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8737 template <typename StaticVisitor>
8738 inline void ExternalOneByteStringIterateBody();
8741 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8745 // The ExternalTwoByteString class is an external string backed by a UTF-16
8747 class ExternalTwoByteString: public ExternalString {
8749 static const bool kHasOneByteEncoding = false;
8751 typedef v8::String::ExternalStringResource Resource;
8753 // The underlying string resource.
8754 inline const Resource* resource();
8755 inline void set_resource(const Resource* buffer);
8757 // Update the pointer cache to the external character array.
8758 // The cached pointer is always valid, as the external character array does =
8759 // not move during lifetime. Deserialization is the only exception, after
8760 // which the pointer cache has to be refreshed.
8761 inline void update_data_cache();
8763 inline const uint16_t* GetChars();
8765 // Dispatched behavior.
8766 inline uint16_t ExternalTwoByteStringGet(int index);
8769 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8771 DECLARE_CAST(ExternalTwoByteString)
8773 // Garbage collection support.
8774 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8776 template<typename StaticVisitor>
8777 inline void ExternalTwoByteStringIterateBody();
8780 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8784 // Utility superclass for stack-allocated objects that must be updated
8785 // on gc. It provides two ways for the gc to update instances, either
8786 // iterating or updating after gc.
8787 class Relocatable BASE_EMBEDDED {
8789 explicit inline Relocatable(Isolate* isolate);
8790 inline virtual ~Relocatable();
8791 virtual void IterateInstance(ObjectVisitor* v) { }
8792 virtual void PostGarbageCollection() { }
8794 static void PostGarbageCollectionProcessing(Isolate* isolate);
8795 static int ArchiveSpacePerThread();
8796 static char* ArchiveState(Isolate* isolate, char* to);
8797 static char* RestoreState(Isolate* isolate, char* from);
8798 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8799 static void Iterate(ObjectVisitor* v, Relocatable* top);
8800 static char* Iterate(ObjectVisitor* v, char* t);
8808 // A flat string reader provides random access to the contents of a
8809 // string independent of the character width of the string. The handle
8810 // must be valid as long as the reader is being used.
8811 class FlatStringReader : public Relocatable {
8813 FlatStringReader(Isolate* isolate, Handle<String> str);
8814 FlatStringReader(Isolate* isolate, Vector<const char> input);
8815 void PostGarbageCollection();
8816 inline uc32 Get(int index);
8817 template <typename Char>
8818 inline Char Get(int index);
8819 int length() { return length_; }
8828 // This maintains an off-stack representation of the stack frames required
8829 // to traverse a ConsString, allowing an entirely iterative and restartable
8830 // traversal of the entire string
8831 class ConsStringIterator {
8833 inline ConsStringIterator() {}
8834 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8835 Reset(cons_string, offset);
8837 inline void Reset(ConsString* cons_string, int offset = 0) {
8839 // Next will always return NULL.
8840 if (cons_string == NULL) return;
8841 Initialize(cons_string, offset);
8843 // Returns NULL when complete.
8844 inline String* Next(int* offset_out) {
8846 if (depth_ == 0) return NULL;
8847 return Continue(offset_out);
8851 static const int kStackSize = 32;
8852 // Use a mask instead of doing modulo operations for stack wrapping.
8853 static const int kDepthMask = kStackSize-1;
8854 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8855 static inline int OffsetForDepth(int depth);
8857 inline void PushLeft(ConsString* string);
8858 inline void PushRight(ConsString* string);
8859 inline void AdjustMaximumDepth();
8861 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8862 void Initialize(ConsString* cons_string, int offset);
8863 String* Continue(int* offset_out);
8864 String* NextLeaf(bool* blew_stack);
8865 String* Search(int* offset_out);
8867 // Stack must always contain only frames for which right traversal
8868 // has not yet been performed.
8869 ConsString* frames_[kStackSize];
8874 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8878 class StringCharacterStream {
8880 inline StringCharacterStream(String* string,
8882 inline uint16_t GetNext();
8883 inline bool HasMore();
8884 inline void Reset(String* string, int offset = 0);
8885 inline void VisitOneByteString(const uint8_t* chars, int length);
8886 inline void VisitTwoByteString(const uint16_t* chars, int length);
8889 ConsStringIterator iter_;
8892 const uint8_t* buffer8_;
8893 const uint16_t* buffer16_;
8895 const uint8_t* end_;
8896 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
8900 template <typename T>
8901 class VectorIterator {
8903 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
8904 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
8905 T GetNext() { return data_[index_++]; }
8906 bool has_more() { return index_ < data_.length(); }
8908 Vector<const T> data_;
8913 // The Oddball describes objects null, undefined, true, and false.
8914 class Oddball: public HeapObject {
8916 // [to_string]: Cached to_string computed at startup.
8917 DECL_ACCESSORS(to_string, String)
8919 // [to_number]: Cached to_number computed at startup.
8920 DECL_ACCESSORS(to_number, Object)
8922 // [typeof]: Cached type_of computed at startup.
8923 DECL_ACCESSORS(type_of, String)
8925 inline byte kind() const;
8926 inline void set_kind(byte kind);
8928 DECLARE_CAST(Oddball)
8930 // Dispatched behavior.
8931 DECLARE_VERIFIER(Oddball)
8933 // Initialize the fields.
8934 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
8935 const char* to_string, Handle<Object> to_number,
8936 const char* type_of, byte kind);
8938 // Layout description.
8939 static const int kToStringOffset = HeapObject::kHeaderSize;
8940 static const int kToNumberOffset = kToStringOffset + kPointerSize;
8941 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
8942 static const int kKindOffset = kTypeOfOffset + kPointerSize;
8943 static const int kSize = kKindOffset + kPointerSize;
8945 static const byte kFalse = 0;
8946 static const byte kTrue = 1;
8947 static const byte kNotBooleanMask = ~1;
8948 static const byte kTheHole = 2;
8949 static const byte kNull = 3;
8950 static const byte kArgumentMarker = 4;
8951 static const byte kUndefined = 5;
8952 static const byte kUninitialized = 6;
8953 static const byte kOther = 7;
8954 static const byte kException = 8;
8956 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
8957 kSize> BodyDescriptor;
8959 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
8960 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
8961 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
8964 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
8968 class Cell: public HeapObject {
8970 // [value]: value of the cell.
8971 DECL_ACCESSORS(value, Object)
8975 static inline Cell* FromValueAddress(Address value) {
8976 Object* result = FromAddress(value - kValueOffset);
8977 return static_cast<Cell*>(result);
8980 inline Address ValueAddress() {
8981 return address() + kValueOffset;
8984 // Dispatched behavior.
8985 DECLARE_PRINTER(Cell)
8986 DECLARE_VERIFIER(Cell)
8988 // Layout description.
8989 static const int kValueOffset = HeapObject::kHeaderSize;
8990 static const int kSize = kValueOffset + kPointerSize;
8992 typedef FixedBodyDescriptor<kValueOffset,
8993 kValueOffset + kPointerSize,
8994 kSize> BodyDescriptor;
8997 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9001 class PropertyCell : public HeapObject {
9003 // [property_details]: details of the global property.
9004 DECL_ACCESSORS(property_details_raw, Object)
9005 // [value]: value of the global property.
9006 DECL_ACCESSORS(value, Object)
9007 // [dependent_code]: dependent code that depends on the type of the global
9009 DECL_ACCESSORS(dependent_code, DependentCode)
9011 inline PropertyDetails property_details();
9012 inline void set_property_details(PropertyDetails details);
9014 PropertyCellConstantType GetConstantType();
9016 // Computes the new type of the cell's contents for the given value, but
9017 // without actually modifying the details.
9018 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9019 Handle<Object> value,
9020 PropertyDetails details);
9021 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9022 Handle<Object> value, PropertyDetails details);
9024 static Handle<PropertyCell> InvalidateEntry(
9025 Handle<GlobalDictionary> dictionary, int entry);
9027 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9028 Handle<Object> new_value);
9030 DECLARE_CAST(PropertyCell)
9032 // Dispatched behavior.
9033 DECLARE_PRINTER(PropertyCell)
9034 DECLARE_VERIFIER(PropertyCell)
9036 // Layout description.
9037 static const int kDetailsOffset = HeapObject::kHeaderSize;
9038 static const int kValueOffset = kDetailsOffset + kPointerSize;
9039 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9040 static const int kSize = kDependentCodeOffset + kPointerSize;
9042 static const int kPointerFieldsBeginOffset = kValueOffset;
9043 static const int kPointerFieldsEndOffset = kSize;
9045 typedef FixedBodyDescriptor<kValueOffset,
9047 kSize> BodyDescriptor;
9050 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9054 class WeakCell : public HeapObject {
9056 inline Object* value() const;
9058 // This should not be called by anyone except GC.
9059 inline void clear();
9061 // This should not be called by anyone except allocator.
9062 inline void initialize(HeapObject* value);
9064 inline bool cleared() const;
9066 DECL_ACCESSORS(next, Object)
9068 inline void clear_next(Heap* heap);
9070 inline bool next_cleared();
9072 DECLARE_CAST(WeakCell)
9074 DECLARE_PRINTER(WeakCell)
9075 DECLARE_VERIFIER(WeakCell)
9077 // Layout description.
9078 static const int kValueOffset = HeapObject::kHeaderSize;
9079 static const int kNextOffset = kValueOffset + kPointerSize;
9080 static const int kSize = kNextOffset + kPointerSize;
9082 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9085 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9089 // The JSProxy describes EcmaScript Harmony proxies
9090 class JSProxy: public JSReceiver {
9092 // [handler]: The handler property.
9093 DECL_ACCESSORS(handler, Object)
9095 // [hash]: The hash code property (undefined if not initialized yet).
9096 DECL_ACCESSORS(hash, Object)
9098 DECLARE_CAST(JSProxy)
9100 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9101 Handle<JSProxy> proxy,
9102 Handle<Object> receiver,
9105 // If the handler defines an accessor property with a setter, invoke it.
9106 // If it defines an accessor property without a setter, or a data property
9107 // that is read-only, throw. In all these cases set '*done' to true,
9108 // otherwise set it to false.
9110 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9111 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9112 Handle<Object> value, LanguageMode language_mode, bool* done);
9114 MUST_USE_RESULT static Maybe<PropertyAttributes>
9115 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9116 Handle<Object> receiver,
9118 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9119 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9120 Handle<Object> value, LanguageMode language_mode);
9122 // Turn the proxy into an (empty) JSObject.
9123 static void Fix(Handle<JSProxy> proxy);
9125 // Initializes the body after the handler slot.
9126 inline void InitializeBody(int object_size, Object* value);
9128 // Invoke a trap by name. If the trap does not exist on this's handler,
9129 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9130 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9131 Handle<JSProxy> proxy,
9133 Handle<Object> derived_trap,
9135 Handle<Object> args[]);
9137 // Dispatched behavior.
9138 DECLARE_PRINTER(JSProxy)
9139 DECLARE_VERIFIER(JSProxy)
9141 // Layout description. We add padding so that a proxy has the same
9142 // size as a virgin JSObject. This is essential for becoming a JSObject
9144 static const int kHandlerOffset = HeapObject::kHeaderSize;
9145 static const int kHashOffset = kHandlerOffset + kPointerSize;
9146 static const int kPaddingOffset = kHashOffset + kPointerSize;
9147 static const int kSize = JSObject::kHeaderSize;
9148 static const int kHeaderSize = kPaddingOffset;
9149 static const int kPaddingSize = kSize - kPaddingOffset;
9151 STATIC_ASSERT(kPaddingSize >= 0);
9153 typedef FixedBodyDescriptor<kHandlerOffset,
9155 kSize> BodyDescriptor;
9158 friend class JSReceiver;
9160 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9161 Handle<JSProxy> proxy, Handle<Name> name);
9163 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9164 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9166 MUST_USE_RESULT Object* GetIdentityHash();
9168 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9170 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9174 class JSFunctionProxy: public JSProxy {
9176 // [call_trap]: The call trap.
9177 DECL_ACCESSORS(call_trap, Object)
9179 // [construct_trap]: The construct trap.
9180 DECL_ACCESSORS(construct_trap, Object)
9182 DECLARE_CAST(JSFunctionProxy)
9184 // Dispatched behavior.
9185 DECLARE_PRINTER(JSFunctionProxy)
9186 DECLARE_VERIFIER(JSFunctionProxy)
9188 // Layout description.
9189 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9190 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9191 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9192 static const int kSize = JSFunction::kSize;
9193 static const int kPaddingSize = kSize - kPaddingOffset;
9195 STATIC_ASSERT(kPaddingSize >= 0);
9197 typedef FixedBodyDescriptor<kHandlerOffset,
9198 kConstructTrapOffset + kPointerSize,
9199 kSize> BodyDescriptor;
9202 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9206 class JSCollection : public JSObject {
9208 // [table]: the backing hash table
9209 DECL_ACCESSORS(table, Object)
9211 static const int kTableOffset = JSObject::kHeaderSize;
9212 static const int kSize = kTableOffset + kPointerSize;
9215 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9219 // The JSSet describes EcmaScript Harmony sets
9220 class JSSet : public JSCollection {
9224 // Dispatched behavior.
9225 DECLARE_PRINTER(JSSet)
9226 DECLARE_VERIFIER(JSSet)
9229 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9233 // The JSMap describes EcmaScript Harmony maps
9234 class JSMap : public JSCollection {
9238 // Dispatched behavior.
9239 DECLARE_PRINTER(JSMap)
9240 DECLARE_VERIFIER(JSMap)
9243 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9247 // OrderedHashTableIterator is an iterator that iterates over the keys and
9248 // values of an OrderedHashTable.
9250 // The iterator has a reference to the underlying OrderedHashTable data,
9251 // [table], as well as the current [index] the iterator is at.
9253 // When the OrderedHashTable is rehashed it adds a reference from the old table
9254 // to the new table as well as storing enough data about the changes so that the
9255 // iterator [index] can be adjusted accordingly.
9257 // When the [Next] result from the iterator is requested, the iterator checks if
9258 // there is a newer table that it needs to transition to.
9259 template<class Derived, class TableType>
9260 class OrderedHashTableIterator: public JSObject {
9262 // [table]: the backing hash table mapping keys to values.
9263 DECL_ACCESSORS(table, Object)
9265 // [index]: The index into the data table.
9266 DECL_ACCESSORS(index, Object)
9268 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9269 DECL_ACCESSORS(kind, Object)
9272 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9275 static const int kTableOffset = JSObject::kHeaderSize;
9276 static const int kIndexOffset = kTableOffset + kPointerSize;
9277 static const int kKindOffset = kIndexOffset + kPointerSize;
9278 static const int kSize = kKindOffset + kPointerSize;
9286 // Whether the iterator has more elements. This needs to be called before
9287 // calling |CurrentKey| and/or |CurrentValue|.
9290 // Move the index forward one.
9292 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9295 // Populates the array with the next key and value and then moves the iterator
9297 // This returns the |kind| or 0 if the iterator is already at the end.
9298 Smi* Next(JSArray* value_array);
9300 // Returns the current key of the iterator. This should only be called when
9301 // |HasMore| returns true.
9302 inline Object* CurrentKey();
9305 // Transitions the iterator to the non obsolete backing store. This is a NOP
9306 // if the [table] is not obsolete.
9309 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9313 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9316 // Dispatched behavior.
9317 DECLARE_PRINTER(JSSetIterator)
9318 DECLARE_VERIFIER(JSSetIterator)
9320 DECLARE_CAST(JSSetIterator)
9322 // Called by |Next| to populate the array. This allows the subclasses to
9323 // populate the array differently.
9324 inline void PopulateValueArray(FixedArray* array);
9327 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9331 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9334 // Dispatched behavior.
9335 DECLARE_PRINTER(JSMapIterator)
9336 DECLARE_VERIFIER(JSMapIterator)
9338 DECLARE_CAST(JSMapIterator)
9340 // Called by |Next| to populate the array. This allows the subclasses to
9341 // populate the array differently.
9342 inline void PopulateValueArray(FixedArray* array);
9345 // Returns the current value of the iterator. This should only be called when
9346 // |HasMore| returns true.
9347 inline Object* CurrentValue();
9349 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9353 // Base class for both JSWeakMap and JSWeakSet
9354 class JSWeakCollection: public JSObject {
9356 // [table]: the backing hash table mapping keys to values.
9357 DECL_ACCESSORS(table, Object)
9359 // [next]: linked list of encountered weak maps during GC.
9360 DECL_ACCESSORS(next, Object)
9362 static const int kTableOffset = JSObject::kHeaderSize;
9363 static const int kNextOffset = kTableOffset + kPointerSize;
9364 static const int kSize = kNextOffset + kPointerSize;
9367 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9371 // The JSWeakMap describes EcmaScript Harmony weak maps
9372 class JSWeakMap: public JSWeakCollection {
9374 DECLARE_CAST(JSWeakMap)
9376 // Dispatched behavior.
9377 DECLARE_PRINTER(JSWeakMap)
9378 DECLARE_VERIFIER(JSWeakMap)
9381 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9385 // The JSWeakSet describes EcmaScript Harmony weak sets
9386 class JSWeakSet: public JSWeakCollection {
9388 DECLARE_CAST(JSWeakSet)
9390 // Dispatched behavior.
9391 DECLARE_PRINTER(JSWeakSet)
9392 DECLARE_VERIFIER(JSWeakSet)
9395 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9399 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9400 enum class SharedFlag { kNotShared, kShared };
9403 class JSArrayBuffer: public JSObject {
9405 // [backing_store]: backing memory for this array
9406 DECL_ACCESSORS(backing_store, void)
9408 // [byte_length]: length in bytes
9409 DECL_ACCESSORS(byte_length, Object)
9411 inline uint32_t bit_field() const;
9412 inline void set_bit_field(uint32_t bits);
9414 inline bool is_external();
9415 inline void set_is_external(bool value);
9417 inline bool is_neuterable();
9418 inline void set_is_neuterable(bool value);
9420 inline bool was_neutered();
9421 inline void set_was_neutered(bool value);
9423 inline bool is_shared();
9424 inline void set_is_shared(bool value);
9426 DECLARE_CAST(JSArrayBuffer)
9430 // Dispatched behavior.
9431 DECLARE_PRINTER(JSArrayBuffer)
9432 DECLARE_VERIFIER(JSArrayBuffer)
9434 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9435 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9436 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9437 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9438 static const int kBitFieldOffset = kBitFieldSlot;
9440 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9442 static const int kSize = kBitFieldSlot + kPointerSize;
9444 static const int kSizeWithInternalFields =
9445 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9447 class IsExternal : public BitField<bool, 1, 1> {};
9448 class IsNeuterable : public BitField<bool, 2, 1> {};
9449 class WasNeutered : public BitField<bool, 3, 1> {};
9450 class IsShared : public BitField<bool, 4, 1> {};
9453 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9457 class JSArrayBufferView: public JSObject {
9459 // [buffer]: ArrayBuffer that this typed array views.
9460 DECL_ACCESSORS(buffer, Object)
9462 // [byte_offset]: offset of typed array in bytes.
9463 DECL_ACCESSORS(byte_offset, Object)
9465 // [byte_length]: length of typed array in bytes.
9466 DECL_ACCESSORS(byte_length, Object)
9468 DECLARE_CAST(JSArrayBufferView)
9470 DECLARE_VERIFIER(JSArrayBufferView)
9472 inline bool WasNeutered() const;
9474 static const int kBufferOffset = JSObject::kHeaderSize;
9475 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9476 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9477 static const int kViewSize = kByteLengthOffset + kPointerSize;
9481 DECL_ACCESSORS(raw_byte_offset, Object)
9482 DECL_ACCESSORS(raw_byte_length, Object)
9485 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9489 class JSTypedArray: public JSArrayBufferView {
9491 // [length]: length of typed array in elements.
9492 DECL_ACCESSORS(length, Object)
9493 inline uint32_t length_value() const;
9495 DECLARE_CAST(JSTypedArray)
9497 ExternalArrayType type();
9498 size_t element_size();
9500 Handle<JSArrayBuffer> GetBuffer();
9502 // Dispatched behavior.
9503 DECLARE_PRINTER(JSTypedArray)
9504 DECLARE_VERIFIER(JSTypedArray)
9506 static const int kLengthOffset = kViewSize + kPointerSize;
9507 static const int kSize = kLengthOffset + kPointerSize;
9509 static const int kSizeWithInternalFields =
9510 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9513 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9514 Handle<JSTypedArray> typed_array);
9516 DECL_ACCESSORS(raw_length, Object)
9519 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9523 class JSDataView: public JSArrayBufferView {
9525 DECLARE_CAST(JSDataView)
9527 // Dispatched behavior.
9528 DECLARE_PRINTER(JSDataView)
9529 DECLARE_VERIFIER(JSDataView)
9531 static const int kSize = kViewSize;
9533 static const int kSizeWithInternalFields =
9534 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9537 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9541 // Foreign describes objects pointing from JavaScript to C structures.
9542 class Foreign: public HeapObject {
9544 // [address]: field containing the address.
9545 inline Address foreign_address();
9546 inline void set_foreign_address(Address value);
9548 DECLARE_CAST(Foreign)
9550 // Dispatched behavior.
9551 inline void ForeignIterateBody(ObjectVisitor* v);
9553 template<typename StaticVisitor>
9554 inline void ForeignIterateBody();
9556 // Dispatched behavior.
9557 DECLARE_PRINTER(Foreign)
9558 DECLARE_VERIFIER(Foreign)
9560 // Layout description.
9562 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9563 static const int kSize = kForeignAddressOffset + kPointerSize;
9565 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9568 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9572 // The JSArray describes JavaScript Arrays
9573 // Such an array can be in one of two modes:
9574 // - fast, backing storage is a FixedArray and length <= elements.length();
9575 // Please note: push and pop can be used to grow and shrink the array.
9576 // - slow, backing storage is a HashTable with numbers as keys.
9577 class JSArray: public JSObject {
9579 // [length]: The length property.
9580 DECL_ACCESSORS(length, Object)
9582 // Overload the length setter to skip write barrier when the length
9583 // is set to a smi. This matches the set function on FixedArray.
9584 inline void set_length(Smi* length);
9586 static bool HasReadOnlyLength(Handle<JSArray> array);
9587 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9588 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9590 // Initialize the array with the given capacity. The function may
9591 // fail due to out-of-memory situations, but only if the requested
9592 // capacity is non-zero.
9593 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9595 // If the JSArray has fast elements, and new_length would result in
9596 // normalization, returns true.
9597 bool SetLengthWouldNormalize(uint32_t new_length);
9598 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9600 // Initializes the array to a certain length.
9601 inline bool AllowsSetLength();
9603 static void SetLength(Handle<JSArray> array, uint32_t length);
9604 // Same as above but will also queue splice records if |array| is observed.
9605 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9608 // Set the content of the array to the content of storage.
9609 static inline void SetContent(Handle<JSArray> array,
9610 Handle<FixedArrayBase> storage);
9612 DECLARE_CAST(JSArray)
9614 // Dispatched behavior.
9615 DECLARE_PRINTER(JSArray)
9616 DECLARE_VERIFIER(JSArray)
9618 // Number of element slots to pre-allocate for an empty array.
9619 static const int kPreallocatedArrayElements = 4;
9621 // Layout description.
9622 static const int kLengthOffset = JSObject::kHeaderSize;
9623 static const int kSize = kLengthOffset + kPointerSize;
9626 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9630 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9631 Handle<Map> initial_map);
9634 // JSRegExpResult is just a JSArray with a specific initial map.
9635 // This initial map adds in-object properties for "index" and "input"
9636 // properties, as assigned by RegExp.prototype.exec, which allows
9637 // faster creation of RegExp exec results.
9638 // This class just holds constants used when creating the result.
9639 // After creation the result must be treated as a JSArray in all regards.
9640 class JSRegExpResult: public JSArray {
9642 // Offsets of object fields.
9643 static const int kIndexOffset = JSArray::kSize;
9644 static const int kInputOffset = kIndexOffset + kPointerSize;
9645 static const int kSize = kInputOffset + kPointerSize;
9646 // Indices of in-object properties.
9647 static const int kIndexIndex = 0;
9648 static const int kInputIndex = 1;
9650 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9654 class AccessorInfo: public Struct {
9656 DECL_ACCESSORS(name, Object)
9657 DECL_ACCESSORS(flag, Smi)
9658 DECL_ACCESSORS(expected_receiver_type, Object)
9660 inline bool all_can_read();
9661 inline void set_all_can_read(bool value);
9663 inline bool all_can_write();
9664 inline void set_all_can_write(bool value);
9666 inline bool is_special_data_property();
9667 inline void set_is_special_data_property(bool value);
9669 inline PropertyAttributes property_attributes();
9670 inline void set_property_attributes(PropertyAttributes attributes);
9672 // Checks whether the given receiver is compatible with this accessor.
9673 static bool IsCompatibleReceiverMap(Isolate* isolate,
9674 Handle<AccessorInfo> info,
9676 inline bool IsCompatibleReceiver(Object* receiver);
9678 DECLARE_CAST(AccessorInfo)
9680 // Dispatched behavior.
9681 DECLARE_VERIFIER(AccessorInfo)
9683 // Append all descriptors to the array that are not already there.
9684 // Return number added.
9685 static int AppendUnique(Handle<Object> descriptors,
9686 Handle<FixedArray> array,
9687 int valid_descriptors);
9689 static const int kNameOffset = HeapObject::kHeaderSize;
9690 static const int kFlagOffset = kNameOffset + kPointerSize;
9691 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9692 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9695 inline bool HasExpectedReceiverType();
9697 // Bit positions in flag.
9698 static const int kAllCanReadBit = 0;
9699 static const int kAllCanWriteBit = 1;
9700 static const int kSpecialDataProperty = 2;
9701 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9703 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9707 // An accessor must have a getter, but can have no setter.
9709 // When setting a property, V8 searches accessors in prototypes.
9710 // If an accessor was found and it does not have a setter,
9711 // the request is ignored.
9713 // If the accessor in the prototype has the READ_ONLY property attribute, then
9714 // a new value is added to the derived object when the property is set.
9715 // This shadows the accessor in the prototype.
9716 class ExecutableAccessorInfo: public AccessorInfo {
9718 DECL_ACCESSORS(getter, Object)
9719 DECL_ACCESSORS(setter, Object)
9720 DECL_ACCESSORS(data, Object)
9722 DECLARE_CAST(ExecutableAccessorInfo)
9724 // Dispatched behavior.
9725 DECLARE_PRINTER(ExecutableAccessorInfo)
9726 DECLARE_VERIFIER(ExecutableAccessorInfo)
9728 static const int kGetterOffset = AccessorInfo::kSize;
9729 static const int kSetterOffset = kGetterOffset + kPointerSize;
9730 static const int kDataOffset = kSetterOffset + kPointerSize;
9731 static const int kSize = kDataOffset + kPointerSize;
9733 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9736 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9740 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9741 // accessor can either be
9742 // * a pointer to a JavaScript function or proxy: a real accessor
9743 // * undefined: considered an accessor by the spec, too, strangely enough
9744 // * the hole: an accessor which has not been set
9745 // * a pointer to a map: a transition used to ensure map sharing
9746 class AccessorPair: public Struct {
9748 DECL_ACCESSORS(getter, Object)
9749 DECL_ACCESSORS(setter, Object)
9751 DECLARE_CAST(AccessorPair)
9753 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9755 inline Object* get(AccessorComponent component);
9756 inline void set(AccessorComponent component, Object* value);
9758 // Note: Returns undefined instead in case of a hole.
9759 Object* GetComponent(AccessorComponent component);
9761 // Set both components, skipping arguments which are a JavaScript null.
9762 inline void SetComponents(Object* getter, Object* setter);
9764 inline bool Equals(AccessorPair* pair);
9765 inline bool Equals(Object* getter_value, Object* setter_value);
9767 inline bool ContainsAccessor();
9769 // Dispatched behavior.
9770 DECLARE_PRINTER(AccessorPair)
9771 DECLARE_VERIFIER(AccessorPair)
9773 static const int kGetterOffset = HeapObject::kHeaderSize;
9774 static const int kSetterOffset = kGetterOffset + kPointerSize;
9775 static const int kSize = kSetterOffset + kPointerSize;
9778 // Strangely enough, in addition to functions and harmony proxies, the spec
9779 // requires us to consider undefined as a kind of accessor, too:
9781 // Object.defineProperty(obj, "foo", {get: undefined});
9782 // assertTrue("foo" in obj);
9783 inline bool IsJSAccessor(Object* obj);
9785 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9789 class AccessCheckInfo: public Struct {
9791 DECL_ACCESSORS(named_callback, Object)
9792 DECL_ACCESSORS(indexed_callback, Object)
9793 DECL_ACCESSORS(data, Object)
9795 DECLARE_CAST(AccessCheckInfo)
9797 // Dispatched behavior.
9798 DECLARE_PRINTER(AccessCheckInfo)
9799 DECLARE_VERIFIER(AccessCheckInfo)
9801 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9802 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9803 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9804 static const int kSize = kDataOffset + kPointerSize;
9807 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9811 class InterceptorInfo: public Struct {
9813 DECL_ACCESSORS(getter, Object)
9814 DECL_ACCESSORS(setter, Object)
9815 DECL_ACCESSORS(query, Object)
9816 DECL_ACCESSORS(deleter, Object)
9817 DECL_ACCESSORS(enumerator, Object)
9818 DECL_ACCESSORS(data, Object)
9819 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9820 DECL_BOOLEAN_ACCESSORS(all_can_read)
9821 DECL_BOOLEAN_ACCESSORS(non_masking)
9823 inline int flags() const;
9824 inline void set_flags(int flags);
9826 DECLARE_CAST(InterceptorInfo)
9828 // Dispatched behavior.
9829 DECLARE_PRINTER(InterceptorInfo)
9830 DECLARE_VERIFIER(InterceptorInfo)
9832 static const int kGetterOffset = HeapObject::kHeaderSize;
9833 static const int kSetterOffset = kGetterOffset + kPointerSize;
9834 static const int kQueryOffset = kSetterOffset + kPointerSize;
9835 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9836 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9837 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9838 static const int kFlagsOffset = kDataOffset + kPointerSize;
9839 static const int kSize = kFlagsOffset + kPointerSize;
9841 static const int kCanInterceptSymbolsBit = 0;
9842 static const int kAllCanReadBit = 1;
9843 static const int kNonMasking = 2;
9846 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9850 class CallHandlerInfo: public Struct {
9852 DECL_ACCESSORS(callback, Object)
9853 DECL_ACCESSORS(data, Object)
9855 DECLARE_CAST(CallHandlerInfo)
9857 // Dispatched behavior.
9858 DECLARE_PRINTER(CallHandlerInfo)
9859 DECLARE_VERIFIER(CallHandlerInfo)
9861 static const int kCallbackOffset = HeapObject::kHeaderSize;
9862 static const int kDataOffset = kCallbackOffset + kPointerSize;
9863 static const int kSize = kDataOffset + kPointerSize;
9866 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
9870 class TemplateInfo: public Struct {
9872 DECL_ACCESSORS(tag, Object)
9873 inline int number_of_properties() const;
9874 inline void set_number_of_properties(int value);
9875 DECL_ACCESSORS(property_list, Object)
9876 DECL_ACCESSORS(property_accessors, Object)
9878 DECLARE_VERIFIER(TemplateInfo)
9880 static const int kTagOffset = HeapObject::kHeaderSize;
9881 static const int kNumberOfProperties = kTagOffset + kPointerSize;
9882 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
9883 static const int kPropertyAccessorsOffset =
9884 kPropertyListOffset + kPointerSize;
9885 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
9888 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
9892 class FunctionTemplateInfo: public TemplateInfo {
9894 DECL_ACCESSORS(serial_number, Object)
9895 DECL_ACCESSORS(call_code, Object)
9896 DECL_ACCESSORS(prototype_template, Object)
9897 DECL_ACCESSORS(parent_template, Object)
9898 DECL_ACCESSORS(named_property_handler, Object)
9899 DECL_ACCESSORS(indexed_property_handler, Object)
9900 DECL_ACCESSORS(instance_template, Object)
9901 DECL_ACCESSORS(class_name, Object)
9902 DECL_ACCESSORS(signature, Object)
9903 DECL_ACCESSORS(instance_call_handler, Object)
9904 DECL_ACCESSORS(access_check_info, Object)
9905 DECL_ACCESSORS(flag, Smi)
9907 inline int length() const;
9908 inline void set_length(int value);
9910 // Following properties use flag bits.
9911 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
9912 DECL_BOOLEAN_ACCESSORS(undetectable)
9913 // If the bit is set, object instances created by this function
9914 // requires access check.
9915 DECL_BOOLEAN_ACCESSORS(needs_access_check)
9916 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
9917 DECL_BOOLEAN_ACCESSORS(remove_prototype)
9918 DECL_BOOLEAN_ACCESSORS(do_not_cache)
9919 DECL_BOOLEAN_ACCESSORS(instantiated)
9920 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
9922 DECLARE_CAST(FunctionTemplateInfo)
9924 // Dispatched behavior.
9925 DECLARE_PRINTER(FunctionTemplateInfo)
9926 DECLARE_VERIFIER(FunctionTemplateInfo)
9928 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
9929 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
9930 static const int kPrototypeTemplateOffset =
9931 kCallCodeOffset + kPointerSize;
9932 static const int kParentTemplateOffset =
9933 kPrototypeTemplateOffset + kPointerSize;
9934 static const int kNamedPropertyHandlerOffset =
9935 kParentTemplateOffset + kPointerSize;
9936 static const int kIndexedPropertyHandlerOffset =
9937 kNamedPropertyHandlerOffset + kPointerSize;
9938 static const int kInstanceTemplateOffset =
9939 kIndexedPropertyHandlerOffset + kPointerSize;
9940 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
9941 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
9942 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
9943 static const int kAccessCheckInfoOffset =
9944 kInstanceCallHandlerOffset + kPointerSize;
9945 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
9946 static const int kLengthOffset = kFlagOffset + kPointerSize;
9947 static const int kSize = kLengthOffset + kPointerSize;
9949 // Returns true if |object| is an instance of this function template.
9950 bool IsTemplateFor(Object* object);
9951 bool IsTemplateFor(Map* map);
9953 // Returns the holder JSObject if the function can legally be called with this
9954 // receiver. Returns Heap::null_value() if the call is illegal.
9955 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
9958 // Bit position in the flag, from least significant bit position.
9959 static const int kHiddenPrototypeBit = 0;
9960 static const int kUndetectableBit = 1;
9961 static const int kNeedsAccessCheckBit = 2;
9962 static const int kReadOnlyPrototypeBit = 3;
9963 static const int kRemovePrototypeBit = 4;
9964 static const int kDoNotCacheBit = 5;
9965 static const int kInstantiatedBit = 6;
9966 static const int kAcceptAnyReceiver = 7;
9968 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
9972 class ObjectTemplateInfo: public TemplateInfo {
9974 DECL_ACCESSORS(constructor, Object)
9975 DECL_ACCESSORS(internal_field_count, Object)
9977 DECLARE_CAST(ObjectTemplateInfo)
9979 // Dispatched behavior.
9980 DECLARE_PRINTER(ObjectTemplateInfo)
9981 DECLARE_VERIFIER(ObjectTemplateInfo)
9983 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
9984 static const int kInternalFieldCountOffset =
9985 kConstructorOffset + kPointerSize;
9986 static const int kSize = kInternalFieldCountOffset + kPointerSize;
9990 class TypeSwitchInfo: public Struct {
9992 DECL_ACCESSORS(types, Object)
9994 DECLARE_CAST(TypeSwitchInfo)
9996 // Dispatched behavior.
9997 DECLARE_PRINTER(TypeSwitchInfo)
9998 DECLARE_VERIFIER(TypeSwitchInfo)
10000 static const int kTypesOffset = Struct::kHeaderSize;
10001 static const int kSize = kTypesOffset + kPointerSize;
10005 // The DebugInfo class holds additional information for a function being
10007 class DebugInfo: public Struct {
10009 // The shared function info for the source being debugged.
10010 DECL_ACCESSORS(shared, SharedFunctionInfo)
10011 // Code object for the patched code. This code object is the code object
10012 // currently active for the function.
10013 DECL_ACCESSORS(code, Code)
10014 // Fixed array holding status information for each active break point.
10015 DECL_ACCESSORS(break_points, FixedArray)
10017 // Check if there is a break point at a code position.
10018 bool HasBreakPoint(int code_position);
10019 // Get the break point info object for a code position.
10020 Object* GetBreakPointInfo(int code_position);
10021 // Clear a break point.
10022 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10024 Handle<Object> break_point_object);
10025 // Set a break point.
10026 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10027 int source_position, int statement_position,
10028 Handle<Object> break_point_object);
10029 // Get the break point objects for a code position.
10030 Handle<Object> GetBreakPointObjects(int code_position);
10031 // Find the break point info holding this break point object.
10032 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10033 Handle<Object> break_point_object);
10034 // Get the number of break points for this function.
10035 int GetBreakPointCount();
10037 DECLARE_CAST(DebugInfo)
10039 // Dispatched behavior.
10040 DECLARE_PRINTER(DebugInfo)
10041 DECLARE_VERIFIER(DebugInfo)
10043 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10044 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10045 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10046 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10048 static const int kEstimatedNofBreakPointsInFunction = 16;
10051 static const int kNoBreakPointInfo = -1;
10053 // Lookup the index in the break_points array for a code position.
10054 int GetBreakPointInfoIndex(int code_position);
10056 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10060 // The BreakPointInfo class holds information for break points set in a
10061 // function. The DebugInfo object holds a BreakPointInfo object for each code
10062 // position with one or more break points.
10063 class BreakPointInfo: public Struct {
10065 // The position in the code for the break point.
10066 DECL_ACCESSORS(code_position, Smi)
10067 // The position in the source for the break position.
10068 DECL_ACCESSORS(source_position, Smi)
10069 // The position in the source for the last statement before this break
10071 DECL_ACCESSORS(statement_position, Smi)
10072 // List of related JavaScript break points.
10073 DECL_ACCESSORS(break_point_objects, Object)
10075 // Removes a break point.
10076 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10077 Handle<Object> break_point_object);
10078 // Set a break point.
10079 static void SetBreakPoint(Handle<BreakPointInfo> info,
10080 Handle<Object> break_point_object);
10081 // Check if break point info has this break point object.
10082 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10083 Handle<Object> break_point_object);
10084 // Get the number of break points for this code position.
10085 int GetBreakPointCount();
10087 DECLARE_CAST(BreakPointInfo)
10089 // Dispatched behavior.
10090 DECLARE_PRINTER(BreakPointInfo)
10091 DECLARE_VERIFIER(BreakPointInfo)
10093 static const int kCodePositionIndex = Struct::kHeaderSize;
10094 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10095 static const int kStatementPositionIndex =
10096 kSourcePositionIndex + kPointerSize;
10097 static const int kBreakPointObjectsIndex =
10098 kStatementPositionIndex + kPointerSize;
10099 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10102 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10106 #undef DECL_BOOLEAN_ACCESSORS
10107 #undef DECL_ACCESSORS
10108 #undef DECLARE_CAST
10109 #undef DECLARE_VERIFIER
10111 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10112 V(kStringTable, "string_table", "(Internalized strings)") \
10113 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10114 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10115 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10116 V(kInternalizedString, "internalized_string", "(Internal string)") \
10117 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10118 V(kTop, "top", "(Isolate)") \
10119 V(kRelocatable, "relocatable", "(Relocatable)") \
10120 V(kDebug, "debug", "(Debugger)") \
10121 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10122 V(kHandleScope, "handlescope", "(Handle scope)") \
10123 V(kBuiltins, "builtins", "(Builtins)") \
10124 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10125 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10126 V(kThreadManager, "threadmanager", "(Thread manager)") \
10127 V(kStrongRoots, "strong roots", "(Strong roots)") \
10128 V(kExtensions, "Extensions", "(Extensions)")
10130 class VisitorSynchronization : public AllStatic {
10132 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10134 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10137 #undef DECLARE_ENUM
10139 static const char* const kTags[kNumberOfSyncTags];
10140 static const char* const kTagNames[kNumberOfSyncTags];
10143 // Abstract base class for visiting, and optionally modifying, the
10144 // pointers contained in Objects. Used in GC and serialization/deserialization.
10145 class ObjectVisitor BASE_EMBEDDED {
10147 virtual ~ObjectVisitor() {}
10149 // Visits a contiguous arrays of pointers in the half-open range
10150 // [start, end). Any or all of the values may be modified on return.
10151 virtual void VisitPointers(Object** start, Object** end) = 0;
10153 // Handy shorthand for visiting a single pointer.
10154 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10156 // Visit weak next_code_link in Code object.
10157 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10159 // To allow lazy clearing of inline caches the visitor has
10160 // a rich interface for iterating over Code objects..
10162 // Visits a code target in the instruction stream.
10163 virtual void VisitCodeTarget(RelocInfo* rinfo);
10165 // Visits a code entry in a JS function.
10166 virtual void VisitCodeEntry(Address entry_address);
10168 // Visits a global property cell reference in the instruction stream.
10169 virtual void VisitCell(RelocInfo* rinfo);
10171 // Visits a runtime entry in the instruction stream.
10172 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10174 // Visits the resource of an one-byte or two-byte string.
10175 virtual void VisitExternalOneByteString(
10176 v8::String::ExternalOneByteStringResource** resource) {}
10177 virtual void VisitExternalTwoByteString(
10178 v8::String::ExternalStringResource** resource) {}
10180 // Visits a debug call target in the instruction stream.
10181 virtual void VisitDebugTarget(RelocInfo* rinfo);
10183 // Visits the byte sequence in a function's prologue that contains information
10184 // about the code's age.
10185 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10187 // Visit pointer embedded into a code object.
10188 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10190 // Visits an external reference embedded into a code object.
10191 virtual void VisitExternalReference(RelocInfo* rinfo);
10193 // Visits an external reference.
10194 virtual void VisitExternalReference(Address* p) {}
10196 // Visits an (encoded) internal reference.
10197 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10199 // Visits a handle that has an embedder-assigned class ID.
10200 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10202 // Intended for serialization/deserialization checking: insert, or
10203 // check for the presence of, a tag at this position in the stream.
10204 // Also used for marking up GC roots in heap snapshots.
10205 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10209 class StructBodyDescriptor : public
10210 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10212 static inline int SizeOf(Map* map, HeapObject* object);
10216 // BooleanBit is a helper class for setting and getting a bit in an
10218 class BooleanBit : public AllStatic {
10220 static inline bool get(Smi* smi, int bit_position) {
10221 return get(smi->value(), bit_position);
10224 static inline bool get(int value, int bit_position) {
10225 return (value & (1 << bit_position)) != 0;
10228 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10229 return Smi::FromInt(set(smi->value(), bit_position, v));
10232 static inline int set(int value, int bit_position, bool v) {
10234 value |= (1 << bit_position);
10236 value &= ~(1 << bit_position);
10242 } } // namespace v8::internal
10244 #endif // V8_OBJECTS_H_