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) \
994 V(WeakValueHashTable) \
997 // Object is the abstract superclass for all classes in the
999 // Object does not use any virtual functions to avoid the
1000 // allocation of the C++ vtable.
1001 // Since both Smi and HeapObject are subclasses of Object no
1002 // data members can be present in Object.
1006 bool IsObject() const { return true; }
1008 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1009 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1010 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1011 #undef IS_TYPE_FUNCTION_DECL
1013 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1014 // a keyed store is of the form a[expression] = foo.
1015 enum StoreFromKeyed {
1016 MAY_BE_STORE_FROM_KEYED,
1017 CERTAINLY_NOT_STORE_FROM_KEYED
1020 INLINE(bool IsFixedArrayBase() const);
1021 INLINE(bool IsExternal() const);
1022 INLINE(bool IsAccessorInfo() const);
1024 INLINE(bool IsStruct() const);
1025 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1026 INLINE(bool Is##Name() const);
1027 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1028 #undef DECLARE_STRUCT_PREDICATE
1030 INLINE(bool IsSpecObject()) const;
1031 INLINE(bool IsSpecFunction()) const;
1032 INLINE(bool IsTemplateInfo()) const;
1033 INLINE(bool IsNameDictionary() const);
1034 INLINE(bool IsGlobalDictionary() const);
1035 INLINE(bool IsSeededNumberDictionary() const);
1036 INLINE(bool IsUnseededNumberDictionary() const);
1037 INLINE(bool IsOrderedHashSet() const);
1038 INLINE(bool IsOrderedHashMap() const);
1039 bool IsCallable() const;
1040 static bool IsPromise(Handle<Object> object);
1043 INLINE(bool IsUndefined() const);
1044 INLINE(bool IsNull() const);
1045 INLINE(bool IsTheHole() const);
1046 INLINE(bool IsException() const);
1047 INLINE(bool IsUninitialized() const);
1048 INLINE(bool IsTrue() const);
1049 INLINE(bool IsFalse() const);
1050 INLINE(bool IsArgumentsMarker() const);
1052 // Filler objects (fillers and free space objects).
1053 INLINE(bool IsFiller() const);
1055 // Extract the number.
1056 inline double Number();
1057 INLINE(bool IsNaN() const);
1058 INLINE(bool IsMinusZero() const);
1059 bool ToInt32(int32_t* value);
1060 bool ToUint32(uint32_t* value);
1062 inline Representation OptimalRepresentation();
1064 inline ElementsKind OptimalElementsKind();
1066 inline bool FitsRepresentation(Representation representation);
1068 // Checks whether two valid primitive encodings of a property name resolve to
1069 // the same logical property. E.g., the smi 1, the string "1" and the double
1070 // 1 all refer to the same property, so this helper will return true.
1071 inline bool KeyEquals(Object* other);
1073 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1075 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1076 Handle<Object> object,
1077 Representation representation);
1079 inline static Handle<Object> WrapForRead(Isolate* isolate,
1080 Handle<Object> object,
1081 Representation representation);
1083 // Returns true if the object is of the correct type to be used as a
1084 // implementation of a JSObject's elements.
1085 inline bool HasValidElements();
1087 inline bool HasSpecificClassOf(String* name);
1089 bool BooleanValue(); // ECMA-262 9.2.
1091 // ES6 section 7.2.13 Strict Equality Comparison
1092 bool StrictEquals(Object* that);
1094 // Convert to a JSObject if needed.
1095 // native_context is used when creating wrapper object.
1096 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1097 Handle<Object> object);
1098 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1099 Handle<Object> object,
1100 Handle<Context> context);
1102 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1103 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1105 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1106 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1107 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1108 LanguageMode language_mode,
1109 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1111 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1112 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1113 StoreFromKeyed store_mode);
1115 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1116 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1117 StoreFromKeyed store_mode);
1119 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1120 LookupIterator* it, LanguageMode language_mode);
1121 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1122 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1123 LanguageMode language_mode);
1124 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1125 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1126 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1127 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1128 Handle<Object> value, LanguageMode language_mode);
1129 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1130 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1131 LanguageMode language_mode);
1132 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1133 LookupIterator* it, Handle<Object> value);
1134 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1135 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1136 LanguageMode language_mode, StoreFromKeyed store_mode);
1137 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1138 Handle<Object> object, Handle<Name> name,
1139 LanguageMode language_mode = SLOPPY);
1140 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1141 Isolate* isolate, Handle<Object> object, const char* key,
1142 LanguageMode language_mode = SLOPPY);
1143 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1144 Handle<Object> object, Handle<Name> name,
1145 LanguageMode language_mode = SLOPPY);
1147 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1148 LookupIterator* it, LanguageMode language_mode);
1149 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1150 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1152 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1153 Handle<Object> receiver,
1154 Handle<JSReceiver> getter);
1155 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1156 Handle<Object> receiver,
1157 Handle<JSReceiver> setter,
1158 Handle<Object> value);
1160 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1161 Isolate* isolate, Handle<Object> object, uint32_t index,
1162 LanguageMode language_mode = SLOPPY);
1164 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1165 Isolate* isolate, Handle<Object> object, uint32_t index,
1166 Handle<Object> value, LanguageMode language_mode);
1168 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1169 Isolate* isolate, Handle<Object> receiver);
1171 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1173 // Returns the permanent hash code associated with this object. May return
1174 // undefined if not yet created.
1177 // Returns undefined for JSObjects, but returns the hash code for simple
1178 // objects. This avoids a double lookup in the cases where we know we will
1179 // add the hash to the JSObject if it does not already exist.
1180 Object* GetSimpleHash();
1182 // Returns the permanent hash code associated with this object depending on
1183 // the actual object type. May create and store a hash code if needed and none
1185 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1187 // Checks whether this object has the same value as the given one. This
1188 // function is implemented according to ES5, section 9.12 and can be used
1189 // to implement the Harmony "egal" function.
1190 bool SameValue(Object* other);
1192 // Checks whether this object has the same value as the given one.
1193 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1194 // This function is implemented according to ES6, section 7.2.4 and is used
1195 // by ES6 Map and Set.
1196 bool SameValueZero(Object* other);
1198 // Tries to convert an object to an array length. Returns true and sets the
1199 // output parameter if it succeeds.
1200 inline bool ToArrayLength(uint32_t* index);
1202 // Tries to convert an object to an array index. Returns true and sets the
1203 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1204 // allow kMaxUInt32.
1205 inline bool ToArrayIndex(uint32_t* index);
1207 // Returns true if this is a JSValue containing a string and the index is
1208 // < the length of the string. Used to implement [] on strings.
1209 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1211 DECLARE_VERIFIER(Object)
1213 // Verify a pointer is a valid object pointer.
1214 static void VerifyPointer(Object* p);
1217 inline void VerifyApiCallResultType();
1219 // Prints this object without details.
1220 void ShortPrint(FILE* out = stdout);
1222 // Prints this object without details to a message accumulator.
1223 void ShortPrint(StringStream* accumulator);
1225 void ShortPrint(std::ostream& os); // NOLINT
1227 DECLARE_CAST(Object)
1229 // Layout description.
1230 static const int kHeaderSize = 0; // Object does not take up any space.
1233 // For our gdb macros, we should perhaps change these in the future.
1236 // Prints this object with details.
1237 void Print(std::ostream& os); // NOLINT
1239 void Print() { ShortPrint(); }
1240 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1244 friend class LookupIterator;
1245 friend class PrototypeIterator;
1247 // Return the map of the root of object's prototype chain.
1248 Map* GetRootMap(Isolate* isolate);
1250 // Helper for SetProperty and SetSuperProperty.
1251 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1252 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1253 StoreFromKeyed store_mode, bool* found);
1255 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1259 // In objects.h to be usable without objects-inl.h inclusion.
1260 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1261 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1265 explicit Brief(const Object* const v) : value(v) {}
1266 const Object* value;
1270 std::ostream& operator<<(std::ostream& os, const Brief& v);
1273 // Smi represents integer Numbers that can be stored in 31 bits.
1274 // Smis are immediate which means they are NOT allocated in the heap.
1275 // The this pointer has the following format: [31 bit signed int] 0
1276 // For long smis it has the following format:
1277 // [32 bit signed int] [31 bits zero padding] 0
1278 // Smi stands for small integer.
1279 class Smi: public Object {
1281 // Returns the integer value.
1282 inline int value() const { return Internals::SmiValue(this); }
1284 // Convert a value to a Smi object.
1285 static inline Smi* FromInt(int value) {
1286 DCHECK(Smi::IsValid(value));
1287 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1290 static inline Smi* FromIntptr(intptr_t value) {
1291 DCHECK(Smi::IsValid(value));
1292 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1293 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1296 // Returns whether value can be represented in a Smi.
1297 static inline bool IsValid(intptr_t value) {
1298 bool result = Internals::IsValidSmi(value);
1299 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1305 // Dispatched behavior.
1306 void SmiPrint(std::ostream& os) const; // NOLINT
1307 DECLARE_VERIFIER(Smi)
1309 static const int kMinValue =
1310 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1311 static const int kMaxValue = -(kMinValue + 1);
1314 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1318 // Heap objects typically have a map pointer in their first word. However,
1319 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1320 // encoded in the first word. The class MapWord is an abstraction of the
1321 // value in a heap object's first word.
1322 class MapWord BASE_EMBEDDED {
1324 // Normal state: the map word contains a map pointer.
1326 // Create a map word from a map pointer.
1327 static inline MapWord FromMap(const Map* map);
1329 // View this map word as a map pointer.
1330 inline Map* ToMap();
1333 // Scavenge collection: the map word of live objects in the from space
1334 // contains a forwarding address (a heap object pointer in the to space).
1336 // True if this map word is a forwarding address for a scavenge
1337 // collection. Only valid during a scavenge collection (specifically,
1338 // when all map words are heap object pointers, i.e. not during a full GC).
1339 inline bool IsForwardingAddress();
1341 // Create a map word from a forwarding address.
1342 static inline MapWord FromForwardingAddress(HeapObject* object);
1344 // View this map word as a forwarding address.
1345 inline HeapObject* ToForwardingAddress();
1347 static inline MapWord FromRawValue(uintptr_t value) {
1348 return MapWord(value);
1351 inline uintptr_t ToRawValue() {
1356 // HeapObject calls the private constructor and directly reads the value.
1357 friend class HeapObject;
1359 explicit MapWord(uintptr_t value) : value_(value) {}
1365 // The content of an heap object (except for the map pointer). kTaggedValues
1366 // objects can contain both heap pointers and Smis, kMixedValues can contain
1367 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1368 // objects can contain raw values and Smis.
1369 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1372 // HeapObject is the superclass for all classes describing heap allocated
1374 class HeapObject: public Object {
1376 // [map]: Contains a map which contains the object's reflective
1378 inline Map* map() const;
1379 inline void set_map(Map* value);
1380 // The no-write-barrier version. This is OK if the object is white and in
1381 // new space, or if the value is an immortal immutable object, like the maps
1382 // of primitive (non-JS) objects like strings, heap numbers etc.
1383 inline void set_map_no_write_barrier(Map* value);
1385 // Get the map using acquire load.
1386 inline Map* synchronized_map();
1387 inline MapWord synchronized_map_word() const;
1389 // Set the map using release store
1390 inline void synchronized_set_map(Map* value);
1391 inline void synchronized_set_map_no_write_barrier(Map* value);
1392 inline void synchronized_set_map_word(MapWord map_word);
1394 // During garbage collection, the map word of a heap object does not
1395 // necessarily contain a map pointer.
1396 inline MapWord map_word() const;
1397 inline void set_map_word(MapWord map_word);
1399 // The Heap the object was allocated in. Used also to access Isolate.
1400 inline Heap* GetHeap() const;
1402 // Convenience method to get current isolate.
1403 inline Isolate* GetIsolate() const;
1405 // Converts an address to a HeapObject pointer.
1406 static inline HeapObject* FromAddress(Address address) {
1407 DCHECK_TAG_ALIGNED(address);
1408 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1411 // Returns the address of this HeapObject.
1412 inline Address address() {
1413 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1416 // Iterates over pointers contained in the object (including the Map)
1417 void Iterate(ObjectVisitor* v);
1419 // Iterates over all pointers contained in the object except the
1420 // first map pointer. The object type is given in the first
1421 // parameter. This function does not access the map pointer in the
1422 // object, and so is safe to call while the map pointer is modified.
1423 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1425 // Returns the heap object's size in bytes
1428 // Indicates what type of values this heap object may contain.
1429 inline HeapObjectContents ContentType();
1431 // Given a heap object's map pointer, returns the heap size in bytes
1432 // Useful when the map pointer field is used for other purposes.
1434 inline int SizeFromMap(Map* map);
1436 // Returns the field at offset in obj, as a read/write Object* reference.
1437 // Does no checking, and is safe to use during GC, while maps are invalid.
1438 // Does not invoke write barrier, so should only be assigned to
1439 // during marking GC.
1440 static inline Object** RawField(HeapObject* obj, int offset);
1442 // Adds the |code| object related to |name| to the code cache of this map. If
1443 // this map is a dictionary map that is shared, the map copied and installed
1445 static void UpdateMapCodeCache(Handle<HeapObject> object,
1449 DECLARE_CAST(HeapObject)
1451 // Return the write barrier mode for this. Callers of this function
1452 // must be able to present a reference to an DisallowHeapAllocation
1453 // object as a sign that they are not going to use this function
1454 // from code that allocates and thus invalidates the returned write
1456 inline WriteBarrierMode GetWriteBarrierMode(
1457 const DisallowHeapAllocation& promise);
1459 // Dispatched behavior.
1460 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1462 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1464 DECLARE_PRINTER(HeapObject)
1465 DECLARE_VERIFIER(HeapObject)
1467 inline void VerifyObjectField(int offset);
1468 inline void VerifySmiField(int offset);
1470 // Verify a pointer is a valid HeapObject pointer that points to object
1471 // areas in the heap.
1472 static void VerifyHeapPointer(Object* p);
1475 inline AllocationAlignment RequiredAlignment();
1477 // Layout description.
1478 // First field in a heap object is map.
1479 static const int kMapOffset = Object::kHeaderSize;
1480 static const int kHeaderSize = kMapOffset + kPointerSize;
1482 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1485 // helpers for calling an ObjectVisitor to iterate over pointers in the
1486 // half-open range [start, end) specified as integer offsets
1487 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1488 // as above, for the single element at "offset"
1489 inline void IteratePointer(ObjectVisitor* v, int offset);
1490 // as above, for the next code link of a code object.
1491 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1494 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1498 // This class describes a body of an object of a fixed size
1499 // in which all pointer fields are located in the [start_offset, end_offset)
1501 template<int start_offset, int end_offset, int size>
1502 class FixedBodyDescriptor {
1504 static const int kStartOffset = start_offset;
1505 static const int kEndOffset = end_offset;
1506 static const int kSize = size;
1508 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1510 template<typename StaticVisitor>
1511 static inline void IterateBody(HeapObject* obj) {
1512 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1513 HeapObject::RawField(obj, end_offset));
1518 // This class describes a body of an object of a variable size
1519 // in which all pointer fields are located in the [start_offset, object_size)
1521 template<int start_offset>
1522 class FlexibleBodyDescriptor {
1524 static const int kStartOffset = start_offset;
1526 static inline void IterateBody(HeapObject* obj,
1530 template<typename StaticVisitor>
1531 static inline void IterateBody(HeapObject* obj, int object_size) {
1532 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1533 HeapObject::RawField(obj, object_size));
1538 // The HeapNumber class describes heap allocated numbers that cannot be
1539 // represented in a Smi (small integer)
1540 class HeapNumber: public HeapObject {
1542 // [value]: number value.
1543 inline double value() const;
1544 inline void set_value(double value);
1546 DECLARE_CAST(HeapNumber)
1548 // Dispatched behavior.
1549 bool HeapNumberBooleanValue();
1551 void HeapNumberPrint(std::ostream& os); // NOLINT
1552 DECLARE_VERIFIER(HeapNumber)
1554 inline int get_exponent();
1555 inline int get_sign();
1557 // Layout description.
1558 static const int kValueOffset = HeapObject::kHeaderSize;
1559 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1560 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1561 // words within double numbers are endian dependent and they are set
1563 #if defined(V8_TARGET_LITTLE_ENDIAN)
1564 static const int kMantissaOffset = kValueOffset;
1565 static const int kExponentOffset = kValueOffset + 4;
1566 #elif defined(V8_TARGET_BIG_ENDIAN)
1567 static const int kMantissaOffset = kValueOffset + 4;
1568 static const int kExponentOffset = kValueOffset;
1570 #error Unknown byte ordering
1573 static const int kSize = kValueOffset + kDoubleSize;
1574 static const uint32_t kSignMask = 0x80000000u;
1575 static const uint32_t kExponentMask = 0x7ff00000u;
1576 static const uint32_t kMantissaMask = 0xfffffu;
1577 static const int kMantissaBits = 52;
1578 static const int kExponentBits = 11;
1579 static const int kExponentBias = 1023;
1580 static const int kExponentShift = 20;
1581 static const int kInfinityOrNanExponent =
1582 (kExponentMask >> kExponentShift) - kExponentBias;
1583 static const int kMantissaBitsInTopWord = 20;
1584 static const int kNonMantissaBitsInTopWord = 12;
1587 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1591 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1592 class Simd128Value : public HeapObject {
1594 DECLARE_CAST(Simd128Value)
1596 DECLARE_PRINTER(Simd128Value)
1597 DECLARE_VERIFIER(Simd128Value)
1599 // Equality operations.
1600 inline bool Equals(Simd128Value* that);
1602 // Checks that another instance is bit-wise equal.
1603 bool BitwiseEquals(const Simd128Value* other) const;
1604 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1605 uint32_t Hash() const;
1606 // Copies the 16 bytes of SIMD data to the destination address.
1607 void CopyBits(void* destination) const;
1609 // Layout description.
1610 static const int kValueOffset = HeapObject::kHeaderSize;
1611 static const int kSize = kValueOffset + kSimd128Size;
1614 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1618 // V has parameters (TYPE, Type, type, lane count, lane type)
1619 #define SIMD128_TYPES(V) \
1620 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1621 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1622 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1623 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1624 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1625 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1626 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1628 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1629 class Type final : public Simd128Value { \
1631 inline lane_type get_lane(int lane) const; \
1632 inline void set_lane(int lane, lane_type value); \
1634 DECLARE_CAST(Type) \
1636 DECLARE_PRINTER(Type) \
1638 inline bool Equals(Type* that); \
1641 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1643 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1644 #undef SIMD128_VALUE_CLASS
1647 enum EnsureElementsMode {
1648 DONT_ALLOW_DOUBLE_ELEMENTS,
1649 ALLOW_COPIED_DOUBLE_ELEMENTS,
1650 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1654 // Indicator for one component of an AccessorPair.
1655 enum AccessorComponent {
1661 // JSReceiver includes types on which properties can be defined, i.e.,
1662 // JSObject and JSProxy.
1663 class JSReceiver: public HeapObject {
1665 DECLARE_CAST(JSReceiver)
1667 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1668 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1669 Handle<JSReceiver> object, Handle<Name> name);
1670 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1672 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1673 Handle<JSReceiver> object, uint32_t index);
1674 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1675 Handle<JSReceiver> object, uint32_t index);
1677 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1678 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1679 Handle<JSReceiver> object, Handle<Name> name,
1680 LanguageMode language_mode = SLOPPY);
1681 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1682 Handle<JSReceiver> object, Handle<Name> name,
1683 LanguageMode language_mode = SLOPPY);
1684 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1685 LookupIterator* it, LanguageMode language_mode);
1686 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1687 Handle<JSReceiver> object, uint32_t index,
1688 LanguageMode language_mode = SLOPPY);
1690 // Tests for the fast common case for property enumeration.
1691 bool IsSimpleEnum();
1693 // Returns the class name ([[Class]] property in the specification).
1694 String* class_name();
1696 // Returns the constructor name (the name (possibly, inferred name) of the
1697 // function that was used to instantiate the object).
1698 String* constructor_name();
1700 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1701 Handle<JSReceiver> object, Handle<Name> name);
1702 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1703 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1705 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1706 Handle<JSReceiver> object, uint32_t index);
1707 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1708 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1710 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1711 LookupIterator* it);
1714 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1716 static Handle<Object> GetDataProperty(LookupIterator* it);
1719 // Retrieves a permanent object identity hash code. The undefined value might
1720 // be returned in case no hash was created yet.
1721 inline Object* GetIdentityHash();
1723 // Retrieves a permanent object identity hash code. May create and store a
1724 // hash code if needed and none exists.
1725 inline static Handle<Smi> GetOrCreateIdentityHash(
1726 Handle<JSReceiver> object);
1728 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1730 // Computes the enumerable keys for a JSObject. Used for implementing
1731 // "for (n in object) { }".
1732 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1733 Handle<JSReceiver> object,
1734 KeyCollectionType type);
1737 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1741 // The JSObject describes real heap allocated JavaScript objects with
1743 // Note that the map of JSObject changes during execution to enable inline
1745 class JSObject: public JSReceiver {
1747 // [properties]: Backing storage for properties.
1748 // properties is a FixedArray in the fast case and a Dictionary in the
1750 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1751 inline void initialize_properties();
1752 inline bool HasFastProperties();
1753 // Gets slow properties for non-global objects.
1754 inline NameDictionary* property_dictionary();
1755 // Gets global object properties.
1756 inline GlobalDictionary* global_dictionary();
1758 // [elements]: The elements (properties with names that are integers).
1760 // Elements can be in two general modes: fast and slow. Each mode
1761 // corrensponds to a set of object representations of elements that
1762 // have something in common.
1764 // In the fast mode elements is a FixedArray and so each element can
1765 // be quickly accessed. This fact is used in the generated code. The
1766 // elements array can have one of three maps in this mode:
1767 // fixed_array_map, sloppy_arguments_elements_map or
1768 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1769 // the elements array may be shared by a few objects and so before
1770 // writing to any element the array must be copied. Use
1771 // EnsureWritableFastElements in this case.
1773 // In the slow mode the elements is either a NumberDictionary, a
1774 // FixedArray parameter map for a (sloppy) arguments object.
1775 DECL_ACCESSORS(elements, FixedArrayBase)
1776 inline void initialize_elements();
1777 static void ResetElements(Handle<JSObject> object);
1778 static inline void SetMapAndElements(Handle<JSObject> object,
1780 Handle<FixedArrayBase> elements);
1781 inline ElementsKind GetElementsKind();
1782 ElementsAccessor* GetElementsAccessor();
1783 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1784 inline bool HasFastSmiElements();
1785 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1786 inline bool HasFastObjectElements();
1787 // Returns true if an object has elements of FAST_ELEMENTS or
1788 // FAST_SMI_ONLY_ELEMENTS.
1789 inline bool HasFastSmiOrObjectElements();
1790 // Returns true if an object has any of the fast elements kinds.
1791 inline bool HasFastElements();
1792 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1794 inline bool HasFastDoubleElements();
1795 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1797 inline bool HasFastHoleyElements();
1798 inline bool HasSloppyArgumentsElements();
1799 inline bool HasDictionaryElements();
1801 inline bool HasFixedTypedArrayElements();
1803 inline bool HasFixedUint8ClampedElements();
1804 inline bool HasFixedArrayElements();
1805 inline bool HasFixedInt8Elements();
1806 inline bool HasFixedUint8Elements();
1807 inline bool HasFixedInt16Elements();
1808 inline bool HasFixedUint16Elements();
1809 inline bool HasFixedInt32Elements();
1810 inline bool HasFixedUint32Elements();
1811 inline bool HasFixedFloat32Elements();
1812 inline bool HasFixedFloat64Elements();
1814 inline bool HasFastArgumentsElements();
1815 inline bool HasSlowArgumentsElements();
1816 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1818 // Requires: HasFastElements().
1819 static Handle<FixedArray> EnsureWritableFastElements(
1820 Handle<JSObject> object);
1822 // Collects elements starting at index 0.
1823 // Undefined values are placed after non-undefined values.
1824 // Returns the number of non-undefined values.
1825 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1827 // As PrepareElementsForSort, but only on objects where elements is
1828 // a dictionary, and it will stay a dictionary. Collates undefined and
1829 // unexisting elements below limit from position zero of the elements.
1830 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1833 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1834 LookupIterator* it, Handle<Object> value);
1836 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1837 // grant an exemption to ExecutableAccessor callbacks in some cases.
1838 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1840 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1841 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1842 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1844 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1845 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1846 PropertyAttributes attributes,
1847 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1849 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1850 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1851 PropertyAttributes attributes,
1852 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1854 // Equivalent to one of the above depending on whether |name| can be converted
1855 // to an array index.
1856 MUST_USE_RESULT static MaybeHandle<Object>
1857 DefinePropertyOrElementIgnoreAttributes(
1858 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1859 PropertyAttributes attributes = NONE,
1860 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1862 // Adds or reconfigures a property to attributes NONE. It will fail when it
1864 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1865 Handle<Object> value);
1867 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1868 Handle<Object> value, PropertyAttributes attributes);
1870 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1871 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1872 PropertyAttributes attributes);
1874 // Extend the receiver with a single fast property appeared first in the
1875 // passed map. This also extends the property backing store if necessary.
1876 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1878 // Migrates the given object to a map whose field representations are the
1879 // lowest upper bound of all known representations for that field.
1880 static void MigrateInstance(Handle<JSObject> instance);
1882 // Migrates the given object only if the target map is already available,
1883 // or returns false if such a map is not yet available.
1884 static bool TryMigrateInstance(Handle<JSObject> instance);
1886 // Sets the property value in a normalized object given (key, value, details).
1887 // Handles the special representation of JS global objects.
1888 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1889 Handle<Object> value,
1890 PropertyDetails details);
1891 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1892 Handle<Object> value,
1893 PropertyAttributes attributes);
1894 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1896 Handle<Object> value,
1897 PropertyAttributes attributes);
1899 static void OptimizeAsPrototype(Handle<JSObject> object,
1900 PrototypeOptimizationMode mode);
1901 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1902 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1903 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1904 static void InvalidatePrototypeChains(Map* map);
1906 // Alternative implementation of WeakFixedArray::NullCallback.
1907 class PrototypeRegistryCompactionCallback {
1909 static void Callback(Object* value, int old_index, int new_index);
1912 // Retrieve interceptors.
1913 InterceptorInfo* GetNamedInterceptor();
1914 InterceptorInfo* GetIndexedInterceptor();
1916 // Used from JSReceiver.
1917 MUST_USE_RESULT static Maybe<PropertyAttributes>
1918 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1919 MUST_USE_RESULT static Maybe<PropertyAttributes>
1920 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1922 // Retrieves an AccessorPair property from the given object. Might return
1923 // undefined if the property doesn't exist or is of a different kind.
1924 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1925 Handle<JSObject> object,
1927 AccessorComponent component);
1929 // Defines an AccessorPair property on the given object.
1930 // TODO(mstarzinger): Rename to SetAccessor().
1931 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1933 Handle<Object> getter,
1934 Handle<Object> setter,
1935 PropertyAttributes attributes);
1937 // Defines an AccessorInfo property on the given object.
1938 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1939 Handle<JSObject> object,
1940 Handle<AccessorInfo> info);
1942 // The result must be checked first for exceptions. If there's no exception,
1943 // the output parameter |done| indicates whether the interceptor has a result
1945 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1946 LookupIterator* it, bool* done);
1948 // Accessors for hidden properties object.
1950 // Hidden properties are not own properties of the object itself.
1951 // Instead they are stored in an auxiliary structure kept as an own
1952 // property with a special name Heap::hidden_string(). But if the
1953 // receiver is a JSGlobalProxy then the auxiliary object is a property
1954 // of its prototype, and if it's a detached proxy, then you can't have
1955 // hidden properties.
1957 // Sets a hidden property on this object. Returns this object if successful,
1958 // undefined if called on a detached proxy.
1959 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1961 Handle<Object> value);
1962 // Gets the value of a hidden property with the given key. Returns the hole
1963 // if the property doesn't exist (or if called on a detached proxy),
1964 // otherwise returns the value set for the key.
1965 Object* GetHiddenProperty(Handle<Name> key);
1966 // Deletes a hidden property. Deleting a non-existing property is
1967 // considered successful.
1968 static void DeleteHiddenProperty(Handle<JSObject> object,
1970 // Returns true if the object has a property with the hidden string as name.
1971 static bool HasHiddenProperties(Handle<JSObject> object);
1973 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1975 static void ValidateElements(Handle<JSObject> object);
1977 // Makes sure that this object can contain HeapObject as elements.
1978 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1980 // Makes sure that this object can contain the specified elements.
1981 static inline void EnsureCanContainElements(
1982 Handle<JSObject> object,
1985 EnsureElementsMode mode);
1986 static inline void EnsureCanContainElements(
1987 Handle<JSObject> object,
1988 Handle<FixedArrayBase> elements,
1990 EnsureElementsMode mode);
1991 static void EnsureCanContainElements(
1992 Handle<JSObject> object,
1993 Arguments* arguments,
1996 EnsureElementsMode mode);
1998 // Would we convert a fast elements array to dictionary mode given
1999 // an access at key?
2000 bool WouldConvertToSlowElements(uint32_t index);
2002 // Computes the new capacity when expanding the elements of a JSObject.
2003 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2004 // (old_capacity + 50%) + 16
2005 return old_capacity + (old_capacity >> 1) + 16;
2008 // These methods do not perform access checks!
2009 static void UpdateAllocationSite(Handle<JSObject> object,
2010 ElementsKind to_kind);
2012 // Lookup interceptors are used for handling properties controlled by host
2014 inline bool HasNamedInterceptor();
2015 inline bool HasIndexedInterceptor();
2017 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2018 // by JSReceiver::GetKeys.
2019 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2020 Handle<JSObject> object,
2021 Handle<JSReceiver> receiver);
2022 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2023 Handle<JSObject> object,
2024 Handle<JSReceiver> receiver);
2026 // Support functions for v8 api (needed for correct interceptor behavior).
2027 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2028 Handle<JSObject> object, Handle<Name> name);
2029 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2030 Handle<JSObject> object, uint32_t index);
2031 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2032 Handle<JSObject> object, Handle<Name> name);
2034 // Get the header size for a JSObject. Used to compute the index of
2035 // internal fields as well as the number of internal fields.
2036 inline int GetHeaderSize();
2038 inline int GetInternalFieldCount();
2039 inline int GetInternalFieldOffset(int index);
2040 inline Object* GetInternalField(int index);
2041 inline void SetInternalField(int index, Object* value);
2042 inline void SetInternalField(int index, Smi* value);
2044 // Returns the number of properties on this object filtering out properties
2045 // with the specified attributes (ignoring interceptors).
2046 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2047 // Fill in details for properties into storage starting at the specified
2048 // index. Returns the number of properties added.
2049 int GetOwnPropertyNames(FixedArray* storage, int index,
2050 PropertyAttributes filter = NONE);
2052 // Returns the number of properties on this object filtering out properties
2053 // with the specified attributes (ignoring interceptors).
2054 int NumberOfOwnElements(PropertyAttributes filter);
2055 // Returns the number of enumerable elements (ignoring interceptors).
2056 int NumberOfEnumElements();
2057 // Returns the number of elements on this object filtering out elements
2058 // with the specified attributes (ignoring interceptors).
2059 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2060 // Count and fill in the enumerable elements into storage.
2061 // (storage->length() == NumberOfEnumElements()).
2062 // If storage is NULL, will count the elements without adding
2063 // them to any storage.
2064 // Returns the number of enumerable elements.
2065 int GetEnumElementKeys(FixedArray* storage);
2067 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2070 // Returns a new map with all transitions dropped from the object's current
2071 // map and the ElementsKind set.
2072 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2073 ElementsKind to_kind);
2074 static void TransitionElementsKind(Handle<JSObject> object,
2075 ElementsKind to_kind);
2077 // Always use this to migrate an object to a new map.
2078 // |expected_additional_properties| is only used for fast-to-slow transitions
2079 // and ignored otherwise.
2080 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2081 int expected_additional_properties = 0);
2083 // Convert the object to use the canonical dictionary
2084 // representation. If the object is expected to have additional properties
2085 // added this number can be indicated to have the backing store allocated to
2086 // an initial capacity for holding these properties.
2087 static void NormalizeProperties(Handle<JSObject> object,
2088 PropertyNormalizationMode mode,
2089 int expected_additional_properties,
2090 const char* reason);
2092 // Convert and update the elements backing store to be a
2093 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2094 static Handle<SeededNumberDictionary> NormalizeElements(
2095 Handle<JSObject> object);
2097 void RequireSlowElements(SeededNumberDictionary* dictionary);
2099 // Transform slow named properties to fast variants.
2100 static void MigrateSlowToFast(Handle<JSObject> object,
2101 int unused_property_fields, const char* reason);
2103 inline bool IsUnboxedDoubleField(FieldIndex index);
2105 // Access fast-case object properties at index.
2106 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2107 Representation representation,
2109 inline Object* RawFastPropertyAt(FieldIndex index);
2110 inline double RawFastDoublePropertyAt(FieldIndex index);
2112 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2113 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2114 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2115 inline void WriteToField(int descriptor, Object* value);
2117 // Access to in object properties.
2118 inline int GetInObjectPropertyOffset(int index);
2119 inline Object* InObjectPropertyAt(int index);
2120 inline Object* InObjectPropertyAtPut(int index,
2122 WriteBarrierMode mode
2123 = UPDATE_WRITE_BARRIER);
2125 // Set the object's prototype (only JSReceiver and null are allowed values).
2126 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2127 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2129 // Initializes the body after properties slot, properties slot is
2130 // initialized by set_properties. Fill the pre-allocated fields with
2131 // pre_allocated_value and the rest with filler_value.
2132 // Note: this call does not update write barrier, the caller is responsible
2133 // to ensure that |filler_value| can be collected without WB here.
2134 inline void InitializeBody(Map* map,
2135 Object* pre_allocated_value,
2136 Object* filler_value);
2138 // Check whether this object references another object
2139 bool ReferencesObject(Object* obj);
2141 // Disalow further properties to be added to the oject.
2142 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2143 Handle<JSObject> object);
2145 bool IsExtensible();
2148 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2150 // ES5 Object.freeze
2151 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2153 // Called the first time an object is observed with ES7 Object.observe.
2154 static void SetObserved(Handle<JSObject> object);
2157 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2159 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2160 Handle<JSObject> object,
2161 AllocationSiteUsageContext* site_context,
2162 DeepCopyHints hints = kNoHints);
2163 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2164 Handle<JSObject> object,
2165 AllocationSiteCreationContext* site_context);
2167 DECLARE_CAST(JSObject)
2169 // Dispatched behavior.
2170 void JSObjectShortPrint(StringStream* accumulator);
2171 DECLARE_PRINTER(JSObject)
2172 DECLARE_VERIFIER(JSObject)
2174 void PrintProperties(std::ostream& os); // NOLINT
2175 void PrintElements(std::ostream& os); // NOLINT
2177 #if defined(DEBUG) || defined(OBJECT_PRINT)
2178 void PrintTransitions(std::ostream& os); // NOLINT
2181 static void PrintElementsTransition(
2182 FILE* file, Handle<JSObject> object,
2183 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2184 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2186 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2189 // Structure for collecting spill information about JSObjects.
2190 class SpillInformation {
2194 int number_of_objects_;
2195 int number_of_objects_with_fast_properties_;
2196 int number_of_objects_with_fast_elements_;
2197 int number_of_fast_used_fields_;
2198 int number_of_fast_unused_fields_;
2199 int number_of_slow_used_properties_;
2200 int number_of_slow_unused_properties_;
2201 int number_of_fast_used_elements_;
2202 int number_of_fast_unused_elements_;
2203 int number_of_slow_used_elements_;
2204 int number_of_slow_unused_elements_;
2207 void IncrementSpillStatistics(SpillInformation* info);
2211 // If a GC was caused while constructing this object, the elements pointer
2212 // may point to a one pointer filler map. The object won't be rooted, but
2213 // our heap verification code could stumble across it.
2214 bool ElementsAreSafeToExamine();
2217 Object* SlowReverseLookup(Object* value);
2219 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2220 // Also maximal value of JSArray's length property.
2221 static const uint32_t kMaxElementCount = 0xffffffffu;
2223 // Constants for heuristics controlling conversion of fast elements
2224 // to slow elements.
2226 // Maximal gap that can be introduced by adding an element beyond
2227 // the current elements length.
2228 static const uint32_t kMaxGap = 1024;
2230 // Maximal length of fast elements array that won't be checked for
2231 // being dense enough on expansion.
2232 static const int kMaxUncheckedFastElementsLength = 5000;
2234 // Same as above but for old arrays. This limit is more strict. We
2235 // don't want to be wasteful with long lived objects.
2236 static const int kMaxUncheckedOldFastElementsLength = 500;
2238 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2239 // permissible values (see the DCHECK in heap.cc).
2240 static const int kInitialMaxFastElementArray = 100000;
2242 // This constant applies only to the initial map of "global.Object" and
2243 // not to arbitrary other JSObject maps.
2244 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2246 static const int kMaxInstanceSize = 255 * kPointerSize;
2247 // When extending the backing storage for property values, we increase
2248 // its size by more than the 1 entry necessary, so sequentially adding fields
2249 // to the same object requires fewer allocations and copies.
2250 static const int kFieldsAdded = 3;
2252 // Layout description.
2253 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2254 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2255 static const int kHeaderSize = kElementsOffset + kPointerSize;
2257 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2259 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2261 static inline int SizeOf(Map* map, HeapObject* object);
2264 Context* GetCreationContext();
2266 // Enqueue change record for Object.observe. May cause GC.
2267 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2268 Handle<JSObject> object, const char* type, Handle<Name> name,
2269 Handle<Object> old_value);
2271 // Gets the number of currently used elements.
2272 int GetFastElementsUsage();
2274 // Deletes an existing named property in a normalized object.
2275 static void DeleteNormalizedProperty(Handle<JSObject> object,
2276 Handle<Name> name, int entry);
2278 static bool AllCanRead(LookupIterator* it);
2279 static bool AllCanWrite(LookupIterator* it);
2282 friend class JSReceiver;
2283 friend class Object;
2285 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2286 static void MigrateFastToSlow(Handle<JSObject> object,
2287 Handle<Map> new_map,
2288 int expected_additional_properties);
2290 // Used from Object::GetProperty().
2291 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2292 LookupIterator* it);
2294 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2295 LookupIterator* it, Handle<Object> value);
2297 // Add a property to a slow-case object.
2298 static void AddSlowProperty(Handle<JSObject> object,
2300 Handle<Object> value,
2301 PropertyAttributes attributes);
2303 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2304 LookupIterator* it);
2306 bool ReferencesObjectFromElements(FixedArray* elements,
2310 // Return the hash table backing store or the inline stored identity hash,
2311 // whatever is found.
2312 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2314 // Return the hash table backing store for hidden properties. If there is no
2315 // backing store, allocate one.
2316 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2317 Handle<JSObject> object);
2319 // Set the hidden property backing store to either a hash table or
2320 // the inline-stored identity hash.
2321 static Handle<Object> SetHiddenPropertiesHashTable(
2322 Handle<JSObject> object,
2323 Handle<Object> value);
2325 MUST_USE_RESULT Object* GetIdentityHash();
2327 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2329 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2330 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2332 // Helper for fast versions of preventExtensions, seal, and freeze.
2333 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2334 template <PropertyAttributes attrs>
2335 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2336 Handle<JSObject> object);
2338 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2342 // Common superclass for FixedArrays that allow implementations to share
2343 // common accessors and some code paths.
2344 class FixedArrayBase: public HeapObject {
2346 // [length]: length of the array.
2347 inline int length() const;
2348 inline void set_length(int value);
2350 // Get and set the length using acquire loads and release stores.
2351 inline int synchronized_length() const;
2352 inline void synchronized_set_length(int value);
2354 DECLARE_CAST(FixedArrayBase)
2356 // Layout description.
2357 // Length is smi tagged when it is stored.
2358 static const int kLengthOffset = HeapObject::kHeaderSize;
2359 static const int kHeaderSize = kLengthOffset + kPointerSize;
2363 class FixedDoubleArray;
2364 class IncrementalMarking;
2367 // FixedArray describes fixed-sized arrays with element type Object*.
2368 class FixedArray: public FixedArrayBase {
2370 // Setter and getter for elements.
2371 inline Object* get(int index) const;
2372 void SetValue(uint32_t index, Object* value);
2373 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2374 // Setter that uses write barrier.
2375 inline void set(int index, Object* value);
2376 inline bool is_the_hole(int index);
2378 // Setter that doesn't need write barrier.
2379 inline void set(int index, Smi* value);
2380 // Setter with explicit barrier mode.
2381 inline void set(int index, Object* value, WriteBarrierMode mode);
2383 // Setters for frequently used oddballs located in old space.
2384 inline void set_undefined(int index);
2385 inline void set_null(int index);
2386 inline void set_the_hole(int index);
2388 inline Object** GetFirstElementAddress();
2389 inline bool ContainsOnlySmisOrHoles();
2391 // Gives access to raw memory which stores the array's data.
2392 inline Object** data_start();
2394 inline void FillWithHoles(int from, int to);
2396 // Shrink length and insert filler objects.
2397 void Shrink(int length);
2399 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2401 // Add the elements of a JSArray to this FixedArray.
2402 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2403 Handle<FixedArray> content, Handle<JSObject> array,
2404 KeyFilter filter = ALL_KEYS);
2406 // Computes the union of keys and return the result.
2407 // Used for implementing "for (n in object) { }"
2408 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2409 Handle<FixedArray> first,
2410 Handle<FixedArray> second);
2412 // Copy a sub array from the receiver to dest.
2413 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2415 // Garbage collection support.
2416 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2418 // Code Generation support.
2419 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2421 // Garbage collection support.
2422 inline Object** RawFieldOfElementAt(int index);
2424 DECLARE_CAST(FixedArray)
2426 // Maximal allowed size, in bytes, of a single FixedArray.
2427 // Prevents overflowing size computations, as well as extreme memory
2429 static const int kMaxSize = 128 * MB * kPointerSize;
2430 // Maximally allowed length of a FixedArray.
2431 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2433 // Dispatched behavior.
2434 DECLARE_PRINTER(FixedArray)
2435 DECLARE_VERIFIER(FixedArray)
2437 // Checks if two FixedArrays have identical contents.
2438 bool IsEqualTo(FixedArray* other);
2441 // Swap two elements in a pair of arrays. If this array and the
2442 // numbers array are the same object, the elements are only swapped
2444 void SwapPairs(FixedArray* numbers, int i, int j);
2446 // Sort prefix of this array and the numbers array as pairs wrt. the
2447 // numbers. If the numbers array and the this array are the same
2448 // object, the prefix of this array is sorted.
2449 void SortPairs(FixedArray* numbers, uint32_t len);
2451 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2453 static inline int SizeOf(Map* map, HeapObject* object);
2457 // Set operation on FixedArray without using write barriers. Can
2458 // only be used for storing old space objects or smis.
2459 static inline void NoWriteBarrierSet(FixedArray* array,
2463 // Set operation on FixedArray without incremental write barrier. Can
2464 // only be used if the object is guaranteed to be white (whiteness witness
2466 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2471 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2473 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2477 // FixedDoubleArray describes fixed-sized arrays with element type double.
2478 class FixedDoubleArray: public FixedArrayBase {
2480 // Setter and getter for elements.
2481 inline double get_scalar(int index);
2482 inline uint64_t get_representation(int index);
2483 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2484 // This accessor has to get a Number as |value|.
2485 void SetValue(uint32_t index, Object* value);
2486 inline void set(int index, double value);
2487 inline void set_the_hole(int index);
2489 // Checking for the hole.
2490 inline bool is_the_hole(int index);
2492 // Garbage collection support.
2493 inline static int SizeFor(int length) {
2494 return kHeaderSize + length * kDoubleSize;
2497 // Gives access to raw memory which stores the array's data.
2498 inline double* data_start();
2500 inline void FillWithHoles(int from, int to);
2502 // Code Generation support.
2503 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2505 DECLARE_CAST(FixedDoubleArray)
2507 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2508 // Prevents overflowing size computations, as well as extreme memory
2510 static const int kMaxSize = 512 * MB;
2511 // Maximally allowed length of a FixedArray.
2512 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2514 // Dispatched behavior.
2515 DECLARE_PRINTER(FixedDoubleArray)
2516 DECLARE_VERIFIER(FixedDoubleArray)
2519 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2523 class WeakFixedArray : public FixedArray {
2525 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2526 // This function does not check if the value exists already, callers must
2527 // ensure this themselves if necessary.
2528 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2529 Handle<HeapObject> value,
2530 int* assigned_index = NULL);
2532 // Returns true if an entry was found and removed.
2533 bool Remove(Handle<HeapObject> value);
2535 class NullCallback {
2537 static void Callback(Object* value, int old_index, int new_index) {}
2540 template <class CompactionCallback>
2543 inline Object* Get(int index) const;
2544 inline void Clear(int index);
2545 inline int Length() const;
2547 inline bool IsEmptySlot(int index) const;
2548 static Object* Empty() { return Smi::FromInt(0); }
2550 DECLARE_CAST(WeakFixedArray)
2553 static const int kLastUsedIndexIndex = 0;
2554 static const int kFirstIndex = 1;
2556 static Handle<WeakFixedArray> Allocate(
2557 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2559 static void Set(Handle<WeakFixedArray> array, int index,
2560 Handle<HeapObject> value);
2561 inline void clear(int index);
2563 inline int last_used_index() const;
2564 inline void set_last_used_index(int index);
2566 // Disallow inherited setters.
2567 void set(int index, Smi* value);
2568 void set(int index, Object* value);
2569 void set(int index, Object* value, WriteBarrierMode mode);
2570 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2574 // Generic array grows dynamically with O(1) amortized insertion.
2575 class ArrayList : public FixedArray {
2579 // Use this if GC can delete elements from the array.
2580 kReloadLengthAfterAllocation,
2582 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2583 AddMode mode = kNone);
2584 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2585 Handle<Object> obj2, AddMode = kNone);
2586 inline int Length();
2587 inline void SetLength(int length);
2588 inline Object* Get(int index);
2589 inline Object** Slot(int index);
2590 inline void Set(int index, Object* obj);
2591 inline void Clear(int index, Object* undefined);
2592 DECLARE_CAST(ArrayList)
2595 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2596 static const int kLengthIndex = 0;
2597 static const int kFirstIndex = 1;
2598 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2602 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2603 // The format of the these objects is:
2604 // [0]: Number of descriptors
2605 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2606 // [0]: pointer to fixed array with enum cache
2607 // [1]: either Smi(0) or pointer to fixed array with indices
2609 // [2 + number of descriptors * kDescriptorSize]: start of slack
2610 class DescriptorArray: public FixedArray {
2612 // Returns true for both shared empty_descriptor_array and for smis, which the
2613 // map uses to encode additional bit fields when the descriptor array is not
2615 inline bool IsEmpty();
2617 // Returns the number of descriptors in the array.
2618 inline int number_of_descriptors();
2620 inline int number_of_descriptors_storage();
2622 inline int NumberOfSlackDescriptors();
2624 inline void SetNumberOfDescriptors(int number_of_descriptors);
2625 inline int number_of_entries();
2627 inline bool HasEnumCache();
2629 inline void CopyEnumCacheFrom(DescriptorArray* array);
2631 inline FixedArray* GetEnumCache();
2633 inline bool HasEnumIndicesCache();
2635 inline FixedArray* GetEnumIndicesCache();
2637 inline Object** GetEnumCacheSlot();
2639 void ClearEnumCache();
2641 // Initialize or change the enum cache,
2642 // using the supplied storage for the small "bridge".
2643 void SetEnumCache(FixedArray* bridge_storage,
2644 FixedArray* new_cache,
2645 Object* new_index_cache);
2647 bool CanHoldValue(int descriptor, Object* value);
2649 // Accessors for fetching instance descriptor at descriptor number.
2650 inline Name* GetKey(int descriptor_number);
2651 inline Object** GetKeySlot(int descriptor_number);
2652 inline Object* GetValue(int descriptor_number);
2653 inline void SetValue(int descriptor_number, Object* value);
2654 inline Object** GetValueSlot(int descriptor_number);
2655 static inline int GetValueOffset(int descriptor_number);
2656 inline Object** GetDescriptorStartSlot(int descriptor_number);
2657 inline Object** GetDescriptorEndSlot(int descriptor_number);
2658 inline PropertyDetails GetDetails(int descriptor_number);
2659 inline PropertyType GetType(int descriptor_number);
2660 inline int GetFieldIndex(int descriptor_number);
2661 inline HeapType* GetFieldType(int descriptor_number);
2662 inline Object* GetConstant(int descriptor_number);
2663 inline Object* GetCallbacksObject(int descriptor_number);
2664 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2666 inline Name* GetSortedKey(int descriptor_number);
2667 inline int GetSortedKeyIndex(int descriptor_number);
2668 inline void SetSortedKey(int pointer, int descriptor_number);
2669 inline void SetRepresentation(int descriptor_number,
2670 Representation representation);
2672 // Accessor for complete descriptor.
2673 inline void Get(int descriptor_number, Descriptor* desc);
2674 inline void Set(int descriptor_number, Descriptor* desc);
2675 void Replace(int descriptor_number, Descriptor* descriptor);
2677 // Append automatically sets the enumeration index. This should only be used
2678 // to add descriptors in bulk at the end, followed by sorting the descriptor
2680 inline void Append(Descriptor* desc);
2682 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2683 int enumeration_index,
2686 static Handle<DescriptorArray> CopyUpToAddAttributes(
2687 Handle<DescriptorArray> desc,
2688 int enumeration_index,
2689 PropertyAttributes attributes,
2692 // Sort the instance descriptors by the hash codes of their keys.
2695 // Search the instance descriptors for given name.
2696 INLINE(int Search(Name* name, int number_of_own_descriptors));
2698 // As the above, but uses DescriptorLookupCache and updates it when
2700 INLINE(int SearchWithCache(Name* name, Map* map));
2702 // Allocates a DescriptorArray, but returns the singleton
2703 // empty descriptor array object if number_of_descriptors is 0.
2704 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2705 int number_of_descriptors,
2708 DECLARE_CAST(DescriptorArray)
2710 // Constant for denoting key was not found.
2711 static const int kNotFound = -1;
2713 static const int kDescriptorLengthIndex = 0;
2714 static const int kEnumCacheIndex = 1;
2715 static const int kFirstIndex = 2;
2717 // The length of the "bridge" to the enum cache.
2718 static const int kEnumCacheBridgeLength = 2;
2719 static const int kEnumCacheBridgeCacheIndex = 0;
2720 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2722 // Layout description.
2723 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2724 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2725 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2727 // Layout description for the bridge array.
2728 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2730 // Layout of descriptor.
2731 static const int kDescriptorKey = 0;
2732 static const int kDescriptorDetails = 1;
2733 static const int kDescriptorValue = 2;
2734 static const int kDescriptorSize = 3;
2736 #if defined(DEBUG) || defined(OBJECT_PRINT)
2737 // For our gdb macros, we should perhaps change these in the future.
2740 // Print all the descriptors.
2741 void PrintDescriptors(std::ostream& os); // NOLINT
2745 // Is the descriptor array sorted and without duplicates?
2746 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2748 // Is the descriptor array consistent with the back pointers in targets?
2749 bool IsConsistentWithBackPointers(Map* current_map);
2751 // Are two DescriptorArrays equal?
2752 bool IsEqualTo(DescriptorArray* other);
2755 // Returns the fixed array length required to hold number_of_descriptors
2757 static int LengthFor(int number_of_descriptors) {
2758 return ToKeyIndex(number_of_descriptors);
2762 // WhitenessWitness is used to prove that a descriptor array is white
2763 // (unmarked), so incremental write barriers can be skipped because the
2764 // marking invariant cannot be broken and slots pointing into evacuation
2765 // candidates will be discovered when the object is scanned. A witness is
2766 // always stack-allocated right after creating an array. By allocating a
2767 // witness, incremental marking is globally disabled. The witness is then
2768 // passed along wherever needed to statically prove that the array is known to
2770 class WhitenessWitness {
2772 inline explicit WhitenessWitness(DescriptorArray* array);
2773 inline ~WhitenessWitness();
2776 IncrementalMarking* marking_;
2779 // An entry in a DescriptorArray, represented as an (array, index) pair.
2782 inline explicit Entry(DescriptorArray* descs, int index) :
2783 descs_(descs), index_(index) { }
2785 inline PropertyType type();
2786 inline Object* GetCallbackObject();
2789 DescriptorArray* descs_;
2793 // Conversion from descriptor number to array indices.
2794 static int ToKeyIndex(int descriptor_number) {
2795 return kFirstIndex +
2796 (descriptor_number * kDescriptorSize) +
2800 static int ToDetailsIndex(int descriptor_number) {
2801 return kFirstIndex +
2802 (descriptor_number * kDescriptorSize) +
2806 static int ToValueIndex(int descriptor_number) {
2807 return kFirstIndex +
2808 (descriptor_number * kDescriptorSize) +
2812 // Transfer a complete descriptor from the src descriptor array to this
2813 // descriptor array.
2814 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2816 inline void Set(int descriptor_number,
2818 const WhitenessWitness&);
2820 // Swap first and second descriptor.
2821 inline void SwapSortedKeys(int first, int second);
2823 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2827 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2829 template <SearchMode search_mode, typename T>
2830 inline int Search(T* array, Name* name, int valid_entries = 0,
2831 int* out_insertion_index = NULL);
2834 // HashTable is a subclass of FixedArray that implements a hash table
2835 // that uses open addressing and quadratic probing.
2837 // In order for the quadratic probing to work, elements that have not
2838 // yet been used and elements that have been deleted are
2839 // distinguished. Probing continues when deleted elements are
2840 // encountered and stops when unused elements are encountered.
2842 // - Elements with key == undefined have not been used yet.
2843 // - Elements with key == the_hole have been deleted.
2845 // The hash table class is parameterized with a Shape and a Key.
2846 // Shape must be a class with the following interface:
2847 // class ExampleShape {
2849 // // Tells whether key matches other.
2850 // static bool IsMatch(Key key, Object* other);
2851 // // Returns the hash value for key.
2852 // static uint32_t Hash(Key key);
2853 // // Returns the hash value for object.
2854 // static uint32_t HashForObject(Key key, Object* object);
2855 // // Convert key to an object.
2856 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2857 // // The prefix size indicates number of elements in the beginning
2858 // // of the backing storage.
2859 // static const int kPrefixSize = ..;
2860 // // The Element size indicates number of elements per entry.
2861 // static const int kEntrySize = ..;
2863 // The prefix size indicates an amount of memory in the
2864 // beginning of the backing storage that can be used for non-element
2865 // information by subclasses.
2867 template<typename Key>
2870 static const bool UsesSeed = false;
2871 static uint32_t Hash(Key key) { return 0; }
2872 static uint32_t SeededHash(Key key, uint32_t seed) {
2876 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2877 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2879 return HashForObject(key, object);
2884 class HashTableBase : public FixedArray {
2886 // Returns the number of elements in the hash table.
2887 inline int NumberOfElements();
2889 // Returns the number of deleted elements in the hash table.
2890 inline int NumberOfDeletedElements();
2892 // Returns the capacity of the hash table.
2893 inline int Capacity();
2895 // ElementAdded should be called whenever an element is added to a
2897 inline void ElementAdded();
2899 // ElementRemoved should be called whenever an element is removed from
2901 inline void ElementRemoved();
2902 inline void ElementsRemoved(int n);
2904 // Computes the required capacity for a table holding the given
2905 // number of elements. May be more than HashTable::kMaxCapacity.
2906 static inline int ComputeCapacity(int at_least_space_for);
2908 // Tells whether k is a real key. The hole and undefined are not allowed
2909 // as keys and can be used to indicate missing or deleted elements.
2910 inline bool IsKey(Object* k);
2912 // Compute the probe offset (quadratic probing).
2913 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2914 return (n + n * n) >> 1;
2917 static const int kNumberOfElementsIndex = 0;
2918 static const int kNumberOfDeletedElementsIndex = 1;
2919 static const int kCapacityIndex = 2;
2920 static const int kPrefixStartIndex = 3;
2922 // Constant used for denoting a absent entry.
2923 static const int kNotFound = -1;
2926 // Update the number of elements in the hash table.
2927 inline void SetNumberOfElements(int nof);
2929 // Update the number of deleted elements in the hash table.
2930 inline void SetNumberOfDeletedElements(int nod);
2932 // Returns probe entry.
2933 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2934 DCHECK(base::bits::IsPowerOfTwo32(size));
2935 return (hash + GetProbeOffset(number)) & (size - 1);
2938 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2939 return hash & (size - 1);
2942 inline static uint32_t NextProbe(
2943 uint32_t last, uint32_t number, uint32_t size) {
2944 return (last + number) & (size - 1);
2949 template <typename Derived, typename Shape, typename Key>
2950 class HashTable : public HashTableBase {
2953 inline uint32_t Hash(Key key) {
2954 if (Shape::UsesSeed) {
2955 return Shape::SeededHash(key, GetHeap()->HashSeed());
2957 return Shape::Hash(key);
2961 inline uint32_t HashForObject(Key key, Object* object) {
2962 if (Shape::UsesSeed) {
2963 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2965 return Shape::HashForObject(key, object);
2969 // Returns a new HashTable object.
2970 MUST_USE_RESULT static Handle<Derived> New(
2971 Isolate* isolate, int at_least_space_for,
2972 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2973 PretenureFlag pretenure = NOT_TENURED);
2975 DECLARE_CAST(HashTable)
2977 // Garbage collection support.
2978 void IteratePrefix(ObjectVisitor* visitor);
2979 void IterateElements(ObjectVisitor* visitor);
2981 // Find entry for key otherwise return kNotFound.
2982 inline int FindEntry(Key key);
2983 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2984 int FindEntry(Isolate* isolate, Key key);
2986 // Rehashes the table in-place.
2987 void Rehash(Key key);
2989 // Returns the key at entry.
2990 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2992 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
2993 static const int kEntrySize = Shape::kEntrySize;
2994 static const int kElementsStartOffset =
2995 kHeaderSize + kElementsStartIndex * kPointerSize;
2996 static const int kCapacityOffset =
2997 kHeaderSize + kCapacityIndex * kPointerSize;
2999 // Returns the index for an entry (of the key)
3000 static inline int EntryToIndex(int entry) {
3001 return (entry * kEntrySize) + kElementsStartIndex;
3005 friend class ObjectHashTable;
3007 // Find the entry at which to insert element with the given key that
3008 // has the given hash value.
3009 uint32_t FindInsertionEntry(uint32_t hash);
3011 // Attempt to shrink hash table after removal of key.
3012 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3014 // Ensure enough space for n additional elements.
3015 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3016 Handle<Derived> table,
3019 PretenureFlag pretenure = NOT_TENURED);
3021 // Sets the capacity of the hash table.
3022 void SetCapacity(int capacity) {
3023 // To scale a computed hash code to fit within the hash table, we
3024 // use bit-wise AND with a mask, so the capacity must be positive
3026 DCHECK(capacity > 0);
3027 DCHECK(capacity <= kMaxCapacity);
3028 set(kCapacityIndex, Smi::FromInt(capacity));
3031 // Maximal capacity of HashTable. Based on maximal length of underlying
3032 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3034 static const int kMaxCapacity =
3035 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3038 // Returns _expected_ if one of entries given by the first _probe_ probes is
3039 // equal to _expected_. Otherwise, returns the entry given by the probe
3041 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3043 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3045 // Rehashes this hash-table into the new table.
3046 void Rehash(Handle<Derived> new_table, Key key);
3050 // HashTableKey is an abstract superclass for virtual key behavior.
3051 class HashTableKey {
3053 // Returns whether the other object matches this key.
3054 virtual bool IsMatch(Object* other) = 0;
3055 // Returns the hash value for this key.
3056 virtual uint32_t Hash() = 0;
3057 // Returns the hash value for object.
3058 virtual uint32_t HashForObject(Object* key) = 0;
3059 // Returns the key object for storing into the hash table.
3060 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3062 virtual ~HashTableKey() {}
3066 class StringTableShape : public BaseShape<HashTableKey*> {
3068 static inline bool IsMatch(HashTableKey* key, Object* value) {
3069 return key->IsMatch(value);
3072 static inline uint32_t Hash(HashTableKey* key) {
3076 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3077 return key->HashForObject(object);
3080 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3082 static const int kPrefixSize = 0;
3083 static const int kEntrySize = 1;
3086 class SeqOneByteString;
3090 // No special elements in the prefix and the element size is 1
3091 // because only the string itself (the key) needs to be stored.
3092 class StringTable: public HashTable<StringTable,
3096 // Find string in the string table. If it is not there yet, it is
3097 // added. The return value is the string found.
3098 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3099 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3100 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3102 // Tries to internalize given string and returns string handle on success
3103 // or an empty handle otherwise.
3104 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3106 Handle<String> string);
3108 // Looks up a string that is equal to the given string and returns
3109 // string handle if it is found, or an empty handle otherwise.
3110 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3112 Handle<String> str);
3113 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3118 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3120 DECLARE_CAST(StringTable)
3123 template <bool seq_one_byte>
3124 friend class JsonParser;
3126 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3130 template <typename Derived, typename Shape, typename Key>
3131 class Dictionary: public HashTable<Derived, Shape, Key> {
3132 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3135 // Returns the value at entry.
3136 Object* ValueAt(int entry) {
3137 return this->get(Derived::EntryToIndex(entry) + 1);
3140 // Set the value for entry.
3141 void ValueAtPut(int entry, Object* value) {
3142 this->set(Derived::EntryToIndex(entry) + 1, value);
3145 // Returns the property details for the property at entry.
3146 PropertyDetails DetailsAt(int entry) {
3147 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3150 // Set the details for entry.
3151 void DetailsAtPut(int entry, PropertyDetails value) {
3152 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3155 // Returns true if property at given entry is deleted.
3156 bool IsDeleted(int entry) {
3157 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3160 // Delete a property from the dictionary.
3161 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3163 // Attempt to shrink the dictionary after deletion of key.
3164 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3165 Handle<Derived> dictionary,
3167 return DerivedHashTable::Shrink(dictionary, key);
3171 // TODO(dcarney): templatize or move to SeededNumberDictionary
3172 void CopyValuesTo(FixedArray* elements);
3174 // Returns the number of elements in the dictionary filtering out properties
3175 // with the specified attributes.
3176 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3178 // Returns the number of enumerable elements in the dictionary.
3179 int NumberOfEnumElements() {
3180 return NumberOfElementsFilterAttributes(
3181 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3184 // Returns true if the dictionary contains any elements that are non-writable,
3185 // non-configurable, non-enumerable, or have getters/setters.
3186 bool HasComplexElements();
3188 enum SortMode { UNSORTED, SORTED };
3190 // Fill in details for properties into storage.
3191 // Returns the number of properties added.
3192 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3193 SortMode sort_mode);
3195 // Copies enumerable keys to preallocated fixed array.
3196 void CopyEnumKeysTo(FixedArray* storage);
3198 // Accessors for next enumeration index.
3199 void SetNextEnumerationIndex(int index) {
3201 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3204 int NextEnumerationIndex() {
3205 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3208 // Creates a new dictionary.
3209 MUST_USE_RESULT static Handle<Derived> New(
3211 int at_least_space_for,
3212 PretenureFlag pretenure = NOT_TENURED);
3214 // Ensure enough space for n additional elements.
3215 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3218 void Print(std::ostream& os); // NOLINT
3220 // Returns the key (slow).
3221 Object* SlowReverseLookup(Object* value);
3223 // Sets the entry to (key, value) pair.
3224 inline void SetEntry(int entry,
3226 Handle<Object> value);
3227 inline void SetEntry(int entry,
3229 Handle<Object> value,
3230 PropertyDetails details);
3232 MUST_USE_RESULT static Handle<Derived> Add(
3233 Handle<Derived> dictionary,
3235 Handle<Object> value,
3236 PropertyDetails details);
3238 // Returns iteration indices array for the |dictionary|.
3239 // Values are direct indices in the |HashTable| array.
3240 static Handle<FixedArray> BuildIterationIndicesArray(
3241 Handle<Derived> dictionary);
3244 // Generic at put operation.
3245 MUST_USE_RESULT static Handle<Derived> AtPut(
3246 Handle<Derived> dictionary,
3248 Handle<Object> value);
3250 // Add entry to dictionary.
3251 static void AddEntry(
3252 Handle<Derived> dictionary,
3254 Handle<Object> value,
3255 PropertyDetails details,
3258 // Generate new enumeration indices to avoid enumeration index overflow.
3259 // Returns iteration indices array for the |dictionary|.
3260 static Handle<FixedArray> GenerateNewEnumerationIndices(
3261 Handle<Derived> dictionary);
3262 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3263 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3267 template <typename Derived, typename Shape>
3268 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3269 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3272 // Find entry for key, otherwise return kNotFound. Optimized version of
3273 // HashTable::FindEntry.
3274 int FindEntry(Handle<Name> key);
3278 template <typename Key>
3279 class BaseDictionaryShape : public BaseShape<Key> {
3281 template <typename Dictionary>
3282 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3283 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3284 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3285 return PropertyDetails(
3286 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3289 template <typename Dictionary>
3290 static inline void DetailsAtPut(Dictionary* dict, int entry,
3291 PropertyDetails value) {
3292 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3293 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3296 template <typename Dictionary>
3297 static bool IsDeleted(Dictionary* dict, int entry) {
3301 template <typename Dictionary>
3302 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3303 Handle<Object> value, PropertyDetails details);
3307 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3309 static inline bool IsMatch(Handle<Name> key, Object* other);
3310 static inline uint32_t Hash(Handle<Name> key);
3311 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3312 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3313 static const int kPrefixSize = 2;
3314 static const int kEntrySize = 3;
3315 static const bool kIsEnumerable = true;
3319 class NameDictionary
3320 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3321 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3325 DECLARE_CAST(NameDictionary)
3327 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3328 Handle<NameDictionary> dictionary);
3332 class GlobalDictionaryShape : public NameDictionaryShape {
3334 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3336 template <typename Dictionary>
3337 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3339 template <typename Dictionary>
3340 static inline void DetailsAtPut(Dictionary* dict, int entry,
3341 PropertyDetails value);
3343 template <typename Dictionary>
3344 static bool IsDeleted(Dictionary* dict, int entry);
3346 template <typename Dictionary>
3347 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3348 Handle<Object> value, PropertyDetails details);
3352 class GlobalDictionary
3353 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3355 DECLARE_CAST(GlobalDictionary)
3359 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3361 static inline bool IsMatch(uint32_t key, Object* other);
3362 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3363 static const int kEntrySize = 3;
3364 static const bool kIsEnumerable = false;
3368 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3370 static const bool UsesSeed = true;
3371 static const int kPrefixSize = 2;
3373 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3374 static inline uint32_t SeededHashForObject(uint32_t key,
3380 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3382 static const int kPrefixSize = 0;
3384 static inline uint32_t Hash(uint32_t key);
3385 static inline uint32_t HashForObject(uint32_t key, Object* object);
3389 class SeededNumberDictionary
3390 : public Dictionary<SeededNumberDictionary,
3391 SeededNumberDictionaryShape,
3394 DECLARE_CAST(SeededNumberDictionary)
3396 // Type specific at put (default NONE attributes is used when adding).
3397 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3398 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3399 Handle<Object> value, bool used_as_prototype);
3400 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3401 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3402 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3404 // Set an existing entry or add a new one if needed.
3405 // Return the updated dictionary.
3406 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3407 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3408 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3410 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3412 // If slow elements are required we will never go back to fast-case
3413 // for the elements kept in this dictionary. We require slow
3414 // elements if an element has been added at an index larger than
3415 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3416 // when defining a getter or setter with a number key.
3417 inline bool requires_slow_elements();
3418 inline void set_requires_slow_elements();
3420 // Get the value of the max number key that has been added to this
3421 // dictionary. max_number_key can only be called if
3422 // requires_slow_elements returns false.
3423 inline uint32_t max_number_key();
3426 static const int kRequiresSlowElementsMask = 1;
3427 static const int kRequiresSlowElementsTagSize = 1;
3428 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3432 class UnseededNumberDictionary
3433 : public Dictionary<UnseededNumberDictionary,
3434 UnseededNumberDictionaryShape,
3437 DECLARE_CAST(UnseededNumberDictionary)
3439 // Type specific at put (default NONE attributes is used when adding).
3440 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3441 Handle<UnseededNumberDictionary> dictionary,
3443 Handle<Object> value);
3444 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3445 Handle<UnseededNumberDictionary> dictionary,
3447 Handle<Object> value);
3449 // Set an existing entry or add a new one if needed.
3450 // Return the updated dictionary.
3451 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3452 Handle<UnseededNumberDictionary> dictionary,
3454 Handle<Object> value);
3458 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3460 static inline bool IsMatch(Handle<Object> key, Object* other);
3461 static inline uint32_t Hash(Handle<Object> key);
3462 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3463 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3464 static const int kPrefixSize = 0;
3465 static const int kEntrySize = 2;
3469 // ObjectHashTable maps keys that are arbitrary objects to object values by
3470 // using the identity hash of the key for hashing purposes.
3471 class ObjectHashTable: public HashTable<ObjectHashTable,
3472 ObjectHashTableShape,
3475 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3477 DECLARE_CAST(ObjectHashTable)
3479 // Attempt to shrink hash table after removal of key.
3480 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3481 Handle<ObjectHashTable> table,
3482 Handle<Object> key);
3484 // Looks up the value associated with the given key. The hole value is
3485 // returned in case the key is not present.
3486 Object* Lookup(Handle<Object> key);
3487 Object* Lookup(Handle<Object> key, int32_t hash);
3488 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3490 // Adds (or overwrites) the value associated with the given key.
3491 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3493 Handle<Object> value);
3494 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3495 Handle<Object> key, Handle<Object> value,
3498 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3499 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3502 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3503 Handle<Object> key, bool* was_present,
3507 friend class MarkCompactCollector;
3509 void AddEntry(int entry, Object* key, Object* value);
3510 void RemoveEntry(int entry);
3512 // Returns the index to the value of an entry.
3513 static inline int EntryToValueIndex(int entry) {
3514 return EntryToIndex(entry) + 1;
3519 // OrderedHashTable is a HashTable with Object keys that preserves
3520 // insertion order. There are Map and Set interfaces (OrderedHashMap
3521 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3523 // Only Object* keys are supported, with Object::SameValueZero() used as the
3524 // equality operator and Object::GetHash() for the hash function.
3526 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3527 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3528 // Originally attributed to Tyler Close.
3531 // [0]: bucket count
3532 // [1]: element count
3533 // [2]: deleted element count
3534 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3535 // offset into the data table (see below) where the
3536 // first item in this bucket is stored.
3537 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3538 // Capacity() * kEntrySize, where the first entrysize
3539 // items are handled by the derived class and the
3540 // item at kChainOffset is another entry into the
3541 // data table indicating the next entry in this hash
3544 // When we transition the table to a new version we obsolete it and reuse parts
3545 // of the memory to store information how to transition an iterator to the new
3548 // Memory layout for obsolete table:
3549 // [0]: bucket count
3550 // [1]: Next newer table
3551 // [2]: Number of removed holes or -1 when the table was cleared.
3552 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3553 // [3 + NumberOfRemovedHoles()..length]: Not used
3555 template<class Derived, class Iterator, int entrysize>
3556 class OrderedHashTable: public FixedArray {
3558 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3559 static Handle<Derived> Allocate(
3560 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3562 // Returns an OrderedHashTable (possibly |table|) with enough space
3563 // to add at least one new element.
3564 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3566 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3568 static Handle<Derived> Shrink(Handle<Derived> table);
3570 // Returns a new empty OrderedHashTable and records the clearing so that
3571 // exisiting iterators can be updated.
3572 static Handle<Derived> Clear(Handle<Derived> table);
3574 int NumberOfElements() {
3575 return Smi::cast(get(kNumberOfElementsIndex))->value();
3578 int NumberOfDeletedElements() {
3579 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3582 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3584 int NumberOfBuckets() {
3585 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3588 // Returns an index into |this| for the given entry.
3589 int EntryToIndex(int entry) {
3590 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3593 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3596 return !get(kNextTableIndex)->IsSmi();
3599 // The next newer table. This is only valid if the table is obsolete.
3600 Derived* NextTable() {
3601 return Derived::cast(get(kNextTableIndex));
3604 // When the table is obsolete we store the indexes of the removed holes.
3605 int RemovedIndexAt(int index) {
3606 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3609 static const int kNotFound = -1;
3610 static const int kMinCapacity = 4;
3612 static const int kNumberOfBucketsIndex = 0;
3613 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3614 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3615 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3616 static const int kNextTableIndex = kNumberOfElementsIndex;
3618 static const int kNumberOfBucketsOffset =
3619 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3620 static const int kNumberOfElementsOffset =
3621 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3622 static const int kNumberOfDeletedElementsOffset =
3623 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3624 static const int kHashTableStartOffset =
3625 kHeaderSize + kHashTableStartIndex * kPointerSize;
3626 static const int kNextTableOffset =
3627 kHeaderSize + kNextTableIndex * kPointerSize;
3629 static const int kEntrySize = entrysize + 1;
3630 static const int kChainOffset = entrysize;
3632 static const int kLoadFactor = 2;
3634 // NumberOfDeletedElements is set to kClearedTableSentinel when
3635 // the table is cleared, which allows iterator transitions to
3636 // optimize that case.
3637 static const int kClearedTableSentinel = -1;
3640 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3642 void SetNumberOfBuckets(int num) {
3643 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3646 void SetNumberOfElements(int num) {
3647 set(kNumberOfElementsIndex, Smi::FromInt(num));
3650 void SetNumberOfDeletedElements(int num) {
3651 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3655 return NumberOfBuckets() * kLoadFactor;
3658 void SetNextTable(Derived* next_table) {
3659 set(kNextTableIndex, next_table);
3662 void SetRemovedIndexAt(int index, int removed_index) {
3663 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3666 static const int kRemovedHolesIndex = kHashTableStartIndex;
3668 static const int kMaxCapacity =
3669 (FixedArray::kMaxLength - kHashTableStartIndex)
3670 / (1 + (kEntrySize * kLoadFactor));
3674 class JSSetIterator;
3677 class OrderedHashSet: public OrderedHashTable<
3678 OrderedHashSet, JSSetIterator, 1> {
3680 DECLARE_CAST(OrderedHashSet)
3684 class JSMapIterator;
3687 class OrderedHashMap
3688 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3690 DECLARE_CAST(OrderedHashMap)
3692 inline Object* ValueAt(int entry);
3694 static const int kValueOffset = 1;
3698 template <int entrysize>
3699 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3701 static inline bool IsMatch(Handle<Object> key, Object* other);
3702 static inline uint32_t Hash(Handle<Object> key);
3703 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3704 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3705 static const int kPrefixSize = 0;
3706 static const int kEntrySize = entrysize;
3710 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3711 // values. The table wraps the keys in weak cells and store values directly.
3712 // Thus it references keys weakly and values strongly.
3713 class WeakHashTable: public HashTable<WeakHashTable,
3714 WeakHashTableShape<2>,
3717 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3719 DECLARE_CAST(WeakHashTable)
3721 // Looks up the value associated with the given key. The hole value is
3722 // returned in case the key is not present.
3723 Object* Lookup(Handle<HeapObject> key);
3725 // Adds (or overwrites) the value associated with the given key. Mapping a
3726 // key to the hole value causes removal of the whole entry.
3727 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3728 Handle<HeapObject> key,
3729 Handle<HeapObject> value);
3731 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3734 friend class MarkCompactCollector;
3736 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3738 // Returns the index to the value of an entry.
3739 static inline int EntryToValueIndex(int entry) {
3740 return EntryToIndex(entry) + 1;
3745 class WeakValueHashTable : public ObjectHashTable {
3747 DECLARE_CAST(WeakValueHashTable)
3750 // Looks up the value associated with the given key. The hole value is
3751 // returned in case the key is not present.
3752 Object* LookupWeak(Handle<Object> key);
3755 // Adds (or overwrites) the value associated with the given key. Mapping a
3756 // key to the hole value causes removal of the whole entry.
3757 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3758 Handle<WeakValueHashTable> table, Handle<Object> key,
3759 Handle<HeapObject> value);
3761 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3765 // ScopeInfo represents information about different scopes of a source
3766 // program and the allocation of the scope's variables. Scope information
3767 // is stored in a compressed form in ScopeInfo objects and is used
3768 // at runtime (stack dumps, deoptimization, etc.).
3770 // This object provides quick access to scope info details for runtime
3772 class ScopeInfo : public FixedArray {
3774 DECLARE_CAST(ScopeInfo)
3776 // Return the type of this scope.
3777 ScopeType scope_type();
3779 // Does this scope call eval?
3782 // Return the language mode of this scope.
3783 LanguageMode language_mode();
3785 // Does this scope make a sloppy eval call?
3786 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3788 // Return the total number of locals allocated on the stack and in the
3789 // context. This includes the parameters that are allocated in the context.
3792 // Return the number of stack slots for code. This number consists of two
3794 // 1. One stack slot per stack allocated local.
3795 // 2. One stack slot for the function name if it is stack allocated.
3796 int StackSlotCount();
3798 // Return the number of context slots for code if a context is allocated. This
3799 // number consists of three parts:
3800 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3801 // 2. One context slot per context allocated local.
3802 // 3. One context slot for the function name if it is context allocated.
3803 // Parameters allocated in the context count as context allocated locals. If
3804 // no contexts are allocated for this scope ContextLength returns 0.
3805 int ContextLength();
3807 // Does this scope declare a "this" binding?
3810 // Does this scope declare a "this" binding, and the "this" binding is stack-
3811 // or context-allocated?
3812 bool HasAllocatedReceiver();
3814 // Is this scope the scope of a named function expression?
3815 bool HasFunctionName();
3817 // Return if this has context allocated locals.
3818 bool HasHeapAllocatedLocals();
3820 // Return if contexts are allocated for this scope.
3823 // Return if this is a function scope with "use asm".
3824 inline bool IsAsmModule();
3826 // Return if this is a nested function within an asm module scope.
3827 inline bool IsAsmFunction();
3829 inline bool HasSimpleParameters();
3831 // Return the function_name if present.
3832 String* FunctionName();
3834 // Return the name of the given parameter.
3835 String* ParameterName(int var);
3837 // Return the name of the given local.
3838 String* LocalName(int var);
3840 // Return the name of the given stack local.
3841 String* StackLocalName(int var);
3843 // Return the name of the given stack local.
3844 int StackLocalIndex(int var);
3846 // Return the name of the given context local.
3847 String* ContextLocalName(int var);
3849 // Return the mode of the given context local.
3850 VariableMode ContextLocalMode(int var);
3852 // Return the initialization flag of the given context local.
3853 InitializationFlag ContextLocalInitFlag(int var);
3855 // Return the initialization flag of the given context local.
3856 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3858 // Return true if this local was introduced by the compiler, and should not be
3859 // exposed to the user in a debugger.
3860 bool LocalIsSynthetic(int var);
3862 String* StrongModeFreeVariableName(int var);
3863 int StrongModeFreeVariableStartPosition(int var);
3864 int StrongModeFreeVariableEndPosition(int var);
3866 // Lookup support for serialized scope info. Returns the
3867 // the stack slot index for a given slot name if the slot is
3868 // present; otherwise returns a value < 0. The name must be an internalized
3870 int StackSlotIndex(String* name);
3872 // Lookup support for serialized scope info. Returns the
3873 // context slot index for a given slot name if the slot is present; otherwise
3874 // returns a value < 0. The name must be an internalized string.
3875 // If the slot is present and mode != NULL, sets *mode to the corresponding
3876 // mode for that variable.
3877 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3878 VariableMode* mode, VariableLocation* location,
3879 InitializationFlag* init_flag,
3880 MaybeAssignedFlag* maybe_assigned_flag);
3882 // Lookup the name of a certain context slot by its index.
3883 String* ContextSlotName(int slot_index);
3885 // Lookup support for serialized scope info. Returns the
3886 // parameter index for a given parameter name if the parameter is present;
3887 // otherwise returns a value < 0. The name must be an internalized string.
3888 int ParameterIndex(String* name);
3890 // Lookup support for serialized scope info. Returns the function context
3891 // slot index if the function name is present and context-allocated (named
3892 // function expressions, only), otherwise returns a value < 0. The name
3893 // must be an internalized string.
3894 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3896 // Lookup support for serialized scope info. Returns the receiver context
3897 // slot index if scope has a "this" binding, and the binding is
3898 // context-allocated. Otherwise returns a value < 0.
3899 int ReceiverContextSlotIndex();
3901 FunctionKind function_kind();
3903 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3904 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3906 // Serializes empty scope info.
3907 static ScopeInfo* Empty(Isolate* isolate);
3913 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3914 // numeric and occupies one array slot.
3915 // 1. A set of properties of the scope
3916 // 2. The number of parameters. This only applies to function scopes. For
3917 // non-function scopes this is 0.
3918 // 3. The number of non-parameter variables allocated on the stack.
3919 // 4. The number of non-parameter and parameter variables allocated in the
3921 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3924 V(StackLocalCount) \
3925 V(ContextLocalCount) \
3926 V(ContextGlobalCount) \
3927 V(StrongModeFreeVariableCount)
3929 #define FIELD_ACCESSORS(name) \
3930 inline void Set##name(int value); \
3932 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3933 #undef FIELD_ACCESSORS
3937 #define DECL_INDEX(name) k##name,
3938 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3943 // The layout of the variable part of a ScopeInfo is as follows:
3944 // 1. ParameterEntries:
3945 // This part stores the names of the parameters for function scopes. One
3946 // slot is used per parameter, so in total this part occupies
3947 // ParameterCount() slots in the array. For other scopes than function
3948 // scopes ParameterCount() is 0.
3949 // 2. StackLocalFirstSlot:
3950 // Index of a first stack slot for stack local. Stack locals belonging to
3951 // this scope are located on a stack at slots starting from this index.
3952 // 3. StackLocalEntries:
3953 // Contains the names of local variables that are allocated on the stack,
3954 // in increasing order of the stack slot index. First local variable has
3955 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3956 // One slot is used per stack local, so in total this part occupies
3957 // StackLocalCount() slots in the array.
3958 // 4. ContextLocalNameEntries:
3959 // Contains the names of local variables and parameters that are allocated
3960 // in the context. They are stored in increasing order of the context slot
3961 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3962 // context local, so in total this part occupies ContextLocalCount() slots
3964 // 5. ContextLocalInfoEntries:
3965 // Contains the variable modes and initialization flags corresponding to
3966 // the context locals in ContextLocalNameEntries. One slot is used per
3967 // context local, so in total this part occupies ContextLocalCount()
3968 // slots in the array.
3969 // 6. StrongModeFreeVariableNameEntries:
3970 // Stores the names of strong mode free variables.
3971 // 7. StrongModeFreeVariablePositionEntries:
3972 // Stores the locations (start and end position) of strong mode free
3974 // 8. RecieverEntryIndex:
3975 // If the scope binds a "this" value, one slot is reserved to hold the
3976 // context or stack slot index for the variable.
3977 // 9. FunctionNameEntryIndex:
3978 // If the scope belongs to a named function expression this part contains
3979 // information about the function variable. It always occupies two array
3980 // slots: a. The name of the function variable.
3981 // b. The context or stack slot index for the variable.
3982 int ParameterEntriesIndex();
3983 int StackLocalFirstSlotIndex();
3984 int StackLocalEntriesIndex();
3985 int ContextLocalNameEntriesIndex();
3986 int ContextGlobalNameEntriesIndex();
3987 int ContextLocalInfoEntriesIndex();
3988 int ContextGlobalInfoEntriesIndex();
3989 int StrongModeFreeVariableNameEntriesIndex();
3990 int StrongModeFreeVariablePositionEntriesIndex();
3991 int ReceiverEntryIndex();
3992 int FunctionNameEntryIndex();
3994 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
3995 VariableLocation* location, InitializationFlag* init_flag,
3996 MaybeAssignedFlag* maybe_assigned_flag);
3998 // Used for the function name variable for named function expressions, and for
4000 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4002 // Properties of scopes.
4003 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4004 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4005 STATIC_ASSERT(LANGUAGE_END == 3);
4006 class LanguageModeField
4007 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4008 class ReceiverVariableField
4009 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4010 class FunctionVariableField
4011 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4013 class FunctionVariableMode
4014 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4015 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4017 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4018 class HasSimpleParametersField
4019 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4020 class FunctionKindField
4021 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4023 // BitFields representing the encoded information for context locals in the
4024 // ContextLocalInfoEntries part.
4025 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4026 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4027 class ContextLocalMaybeAssignedFlag
4028 : public BitField<MaybeAssignedFlag, 4, 1> {};
4030 friend class ScopeIterator;
4034 // The cache for maps used by normalized (dictionary mode) objects.
4035 // Such maps do not have property descriptors, so a typical program
4036 // needs very limited number of distinct normalized maps.
4037 class NormalizedMapCache: public FixedArray {
4039 static Handle<NormalizedMapCache> New(Isolate* isolate);
4041 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4042 PropertyNormalizationMode mode);
4043 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4047 DECLARE_CAST(NormalizedMapCache)
4049 static inline bool IsNormalizedMapCache(const Object* obj);
4051 DECLARE_VERIFIER(NormalizedMapCache)
4053 static const int kEntries = 64;
4055 static inline int GetIndex(Handle<Map> map);
4057 // The following declarations hide base class methods.
4058 Object* get(int index);
4059 void set(int index, Object* value);
4063 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4064 // that is attached to code objects.
4065 class ByteArray: public FixedArrayBase {
4069 // Setter and getter.
4070 inline byte get(int index);
4071 inline void set(int index, byte value);
4073 // Treat contents as an int array.
4074 inline int get_int(int index);
4076 static int SizeFor(int length) {
4077 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4079 // We use byte arrays for free blocks in the heap. Given a desired size in
4080 // bytes that is a multiple of the word size and big enough to hold a byte
4081 // array, this function returns the number of elements a byte array should
4083 static int LengthFor(int size_in_bytes) {
4084 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4085 DCHECK(size_in_bytes >= kHeaderSize);
4086 return size_in_bytes - kHeaderSize;
4089 // Returns data start address.
4090 inline Address GetDataStartAddress();
4092 // Returns a pointer to the ByteArray object for a given data start address.
4093 static inline ByteArray* FromDataStartAddress(Address address);
4095 DECLARE_CAST(ByteArray)
4097 // Dispatched behavior.
4098 inline int ByteArraySize();
4099 DECLARE_PRINTER(ByteArray)
4100 DECLARE_VERIFIER(ByteArray)
4102 // Layout description.
4103 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4105 // Maximal memory consumption for a single ByteArray.
4106 static const int kMaxSize = 512 * MB;
4107 // Maximal length of a single ByteArray.
4108 static const int kMaxLength = kMaxSize - kHeaderSize;
4111 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4115 // BytecodeArray represents a sequence of interpreter bytecodes.
4116 class BytecodeArray : public FixedArrayBase {
4118 static int SizeFor(int length) {
4119 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4122 // Setter and getter
4123 inline byte get(int index);
4124 inline void set(int index, byte value);
4126 // Returns data start address.
4127 inline Address GetFirstBytecodeAddress();
4129 // Accessors for frame size and the number of locals
4130 inline int frame_size() const;
4131 inline void set_frame_size(int value);
4133 DECLARE_CAST(BytecodeArray)
4135 // Dispatched behavior.
4136 inline int BytecodeArraySize();
4138 DECLARE_PRINTER(BytecodeArray)
4139 DECLARE_VERIFIER(BytecodeArray)
4141 void Disassemble(std::ostream& os);
4143 // Layout description.
4144 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4145 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4147 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4149 // Maximal memory consumption for a single BytecodeArray.
4150 static const int kMaxSize = 512 * MB;
4151 // Maximal length of a single BytecodeArray.
4152 static const int kMaxLength = kMaxSize - kHeaderSize;
4155 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4159 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4160 // They look like heap objects (are heap object tagged and have a map) so that
4161 // the heap remains iterable. They have a size and a next pointer.
4162 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4163 // in the free list.
4164 class FreeSpace: public HeapObject {
4166 // [size]: size of the free space including the header.
4167 inline int size() const;
4168 inline void set_size(int value);
4170 inline int nobarrier_size() const;
4171 inline void nobarrier_set_size(int value);
4175 // Accessors for the next field.
4176 inline FreeSpace* next();
4177 inline FreeSpace** next_address();
4178 inline void set_next(FreeSpace* next);
4180 inline static FreeSpace* cast(HeapObject* obj);
4182 // Dispatched behavior.
4183 DECLARE_PRINTER(FreeSpace)
4184 DECLARE_VERIFIER(FreeSpace)
4186 // Layout description.
4187 // Size is smi tagged when it is stored.
4188 static const int kSizeOffset = HeapObject::kHeaderSize;
4189 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4192 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4196 // V has parameters (Type, type, TYPE, C type, element_size)
4197 #define TYPED_ARRAYS(V) \
4198 V(Uint8, uint8, UINT8, uint8_t, 1) \
4199 V(Int8, int8, INT8, int8_t, 1) \
4200 V(Uint16, uint16, UINT16, uint16_t, 2) \
4201 V(Int16, int16, INT16, int16_t, 2) \
4202 V(Uint32, uint32, UINT32, uint32_t, 4) \
4203 V(Int32, int32, INT32, int32_t, 4) \
4204 V(Float32, float32, FLOAT32, float, 4) \
4205 V(Float64, float64, FLOAT64, double, 8) \
4206 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4209 class FixedTypedArrayBase: public FixedArrayBase {
4211 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4212 DECL_ACCESSORS(base_pointer, Object)
4214 // [external_pointer]: Contains the offset between base_pointer and the start
4215 // of the data. If the base_pointer is a nullptr, the external_pointer
4216 // therefore points to the actual backing store.
4217 DECL_ACCESSORS(external_pointer, void)
4219 // Dispatched behavior.
4220 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4222 template <typename StaticVisitor>
4223 inline void FixedTypedArrayBaseIterateBody();
4225 DECLARE_CAST(FixedTypedArrayBase)
4227 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4228 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4229 static const int kHeaderSize =
4230 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4232 static const int kDataOffset = kHeaderSize;
4236 static inline int TypedArraySize(InstanceType type, int length);
4237 inline int TypedArraySize(InstanceType type);
4239 // Use with care: returns raw pointer into heap.
4240 inline void* DataPtr();
4242 inline int DataSize();
4245 static inline int ElementSize(InstanceType type);
4247 inline int DataSize(InstanceType type);
4249 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4253 template <class Traits>
4254 class FixedTypedArray: public FixedTypedArrayBase {
4256 typedef typename Traits::ElementType ElementType;
4257 static const InstanceType kInstanceType = Traits::kInstanceType;
4259 DECLARE_CAST(FixedTypedArray<Traits>)
4261 inline ElementType get_scalar(int index);
4262 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4263 inline void set(int index, ElementType value);
4265 static inline ElementType from_int(int value);
4266 static inline ElementType from_double(double value);
4268 // This accessor applies the correct conversion from Smi, HeapNumber
4270 void SetValue(uint32_t index, Object* value);
4272 DECLARE_PRINTER(FixedTypedArray)
4273 DECLARE_VERIFIER(FixedTypedArray)
4276 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4279 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4280 class Type##ArrayTraits { \
4281 public: /* NOLINT */ \
4282 typedef elementType ElementType; \
4283 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4284 static const char* Designator() { return #type " array"; } \
4285 static inline Handle<Object> ToHandle(Isolate* isolate, \
4286 elementType scalar); \
4287 static inline elementType defaultValue(); \
4290 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4292 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4294 #undef FIXED_TYPED_ARRAY_TRAITS
4297 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4298 // data for code generated by the Hydrogen/Lithium compiler. It also
4299 // contains information about functions that were inlined. If N different
4300 // functions were inlined then first N elements of the literal array will
4301 // contain these functions.
4304 class DeoptimizationInputData: public FixedArray {
4306 // Layout description. Indices in the array.
4307 static const int kTranslationByteArrayIndex = 0;
4308 static const int kInlinedFunctionCountIndex = 1;
4309 static const int kLiteralArrayIndex = 2;
4310 static const int kOsrAstIdIndex = 3;
4311 static const int kOsrPcOffsetIndex = 4;
4312 static const int kOptimizationIdIndex = 5;
4313 static const int kSharedFunctionInfoIndex = 6;
4314 static const int kWeakCellCacheIndex = 7;
4315 static const int kFirstDeoptEntryIndex = 8;
4317 // Offsets of deopt entry elements relative to the start of the entry.
4318 static const int kAstIdRawOffset = 0;
4319 static const int kTranslationIndexOffset = 1;
4320 static const int kArgumentsStackHeightOffset = 2;
4321 static const int kPcOffset = 3;
4322 static const int kDeoptEntrySize = 4;
4324 // Simple element accessors.
4325 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4326 inline type* name(); \
4327 inline void Set##name(type* value);
4329 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4330 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4331 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4332 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4333 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4334 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4335 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4336 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4338 #undef DECLARE_ELEMENT_ACCESSORS
4340 // Accessors for elements of the ith deoptimization entry.
4341 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4342 inline type* name(int i); \
4343 inline void Set##name(int i, type* value);
4345 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4346 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4347 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4348 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4350 #undef DECLARE_ENTRY_ACCESSORS
4352 inline BailoutId AstId(int i);
4354 inline void SetAstId(int i, BailoutId value);
4356 inline int DeoptCount();
4358 // Allocates a DeoptimizationInputData.
4359 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4360 int deopt_entry_count,
4361 PretenureFlag pretenure);
4363 DECLARE_CAST(DeoptimizationInputData)
4365 #ifdef ENABLE_DISASSEMBLER
4366 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4370 static int IndexForEntry(int i) {
4371 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4375 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4379 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4380 // data for code generated by the full compiler.
4381 // The format of the these objects is
4382 // [i * 2]: Ast ID for ith deoptimization.
4383 // [i * 2 + 1]: PC and state of ith deoptimization
4384 class DeoptimizationOutputData: public FixedArray {
4386 inline int DeoptPoints();
4388 inline BailoutId AstId(int index);
4390 inline void SetAstId(int index, BailoutId id);
4392 inline Smi* PcAndState(int index);
4393 inline void SetPcAndState(int index, Smi* offset);
4395 static int LengthOfFixedArray(int deopt_points) {
4396 return deopt_points * 2;
4399 // Allocates a DeoptimizationOutputData.
4400 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4401 int number_of_deopt_points,
4402 PretenureFlag pretenure);
4404 DECLARE_CAST(DeoptimizationOutputData)
4406 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4407 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4412 // HandlerTable is a fixed array containing entries for exception handlers in
4413 // the code object it is associated with. The tables comes in two flavors:
4414 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4415 // exception handler and a range representing the try-block covered by that
4416 // handler. Layout looks as follows:
4417 // [ range-start , range-end , handler-offset , stack-depth ]
4418 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4419 // per call-site that could throw an exception. Layout looks as follows:
4420 // [ return-address-offset , handler-offset ]
4421 class HandlerTable : public FixedArray {
4423 // Conservative prediction whether a given handler will locally catch an
4424 // exception or cause a re-throw to outside the code boundary. Since this is
4425 // undecidable it is merely an approximation (e.g. useful for debugger).
4426 enum CatchPrediction { UNCAUGHT, CAUGHT };
4428 // Accessors for handler table based on ranges.
4429 inline void SetRangeStart(int index, int value);
4430 inline void SetRangeEnd(int index, int value);
4431 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4432 inline void SetRangeDepth(int index, int value);
4434 // Accessors for handler table based on return addresses.
4435 inline void SetReturnOffset(int index, int value);
4436 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4438 // Lookup handler in a table based on ranges.
4439 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4441 // Lookup handler in a table based on return addresses.
4442 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4444 // Returns the required length of the underlying fixed array.
4445 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4446 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4448 DECLARE_CAST(HandlerTable)
4450 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4451 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4452 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4456 // Layout description for handler table based on ranges.
4457 static const int kRangeStartIndex = 0;
4458 static const int kRangeEndIndex = 1;
4459 static const int kRangeHandlerIndex = 2;
4460 static const int kRangeDepthIndex = 3;
4461 static const int kRangeEntrySize = 4;
4463 // Layout description for handler table based on return addresses.
4464 static const int kReturnOffsetIndex = 0;
4465 static const int kReturnHandlerIndex = 1;
4466 static const int kReturnEntrySize = 2;
4468 // Encoding of the {handler} field.
4469 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4470 class HandlerOffsetField : public BitField<int, 1, 30> {};
4474 // Code describes objects with on-the-fly generated machine code.
4475 class Code: public HeapObject {
4477 // Opaque data type for encapsulating code flags like kind, inline
4478 // cache state, and arguments count.
4479 typedef uint32_t Flags;
4481 #define NON_IC_KIND_LIST(V) \
4483 V(OPTIMIZED_FUNCTION) \
4489 #define IC_KIND_LIST(V) \
4500 #define CODE_KIND_LIST(V) \
4501 NON_IC_KIND_LIST(V) \
4505 #define DEFINE_CODE_KIND_ENUM(name) name,
4506 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4507 #undef DEFINE_CODE_KIND_ENUM
4511 // No more than 16 kinds. The value is currently encoded in four bits in
4513 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4515 static const char* Kind2String(Kind kind);
4523 static const int kPrologueOffsetNotSet = -1;
4525 #ifdef ENABLE_DISASSEMBLER
4527 static const char* ICState2String(InlineCacheState state);
4528 static const char* StubType2String(StubType type);
4529 static void PrintExtraICState(std::ostream& os, // NOLINT
4530 Kind kind, ExtraICState extra);
4531 void Disassemble(const char* name, std::ostream& os); // NOLINT
4532 #endif // ENABLE_DISASSEMBLER
4534 // [instruction_size]: Size of the native instructions
4535 inline int instruction_size() const;
4536 inline void set_instruction_size(int value);
4538 // [relocation_info]: Code relocation information
4539 DECL_ACCESSORS(relocation_info, ByteArray)
4540 void InvalidateRelocation();
4541 void InvalidateEmbeddedObjects();
4543 // [handler_table]: Fixed array containing offsets of exception handlers.
4544 DECL_ACCESSORS(handler_table, FixedArray)
4546 // [deoptimization_data]: Array containing data for deopt.
4547 DECL_ACCESSORS(deoptimization_data, FixedArray)
4549 // [raw_type_feedback_info]: This field stores various things, depending on
4550 // the kind of the code object.
4551 // FUNCTION => type feedback information.
4552 // STUB and ICs => major/minor key as Smi.
4553 DECL_ACCESSORS(raw_type_feedback_info, Object)
4554 inline Object* type_feedback_info();
4555 inline void set_type_feedback_info(
4556 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4557 inline uint32_t stub_key();
4558 inline void set_stub_key(uint32_t key);
4560 // [next_code_link]: Link for lists of optimized or deoptimized code.
4561 // Note that storage for this field is overlapped with typefeedback_info.
4562 DECL_ACCESSORS(next_code_link, Object)
4564 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4565 // field does not have to be traced during garbage collection since
4566 // it is only used by the garbage collector itself.
4567 DECL_ACCESSORS(gc_metadata, Object)
4569 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4570 // at the moment when this object was created.
4571 inline void set_ic_age(int count);
4572 inline int ic_age() const;
4574 // [prologue_offset]: Offset of the function prologue, used for aging
4575 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4576 inline int prologue_offset() const;
4577 inline void set_prologue_offset(int offset);
4579 // [constant_pool offset]: Offset of the constant pool.
4580 // Valid for FLAG_enable_embedded_constant_pool only
4581 inline int constant_pool_offset() const;
4582 inline void set_constant_pool_offset(int offset);
4584 // Unchecked accessors to be used during GC.
4585 inline ByteArray* unchecked_relocation_info();
4587 inline int relocation_size();
4589 // [flags]: Various code flags.
4590 inline Flags flags();
4591 inline void set_flags(Flags flags);
4593 // [flags]: Access to specific code flags.
4595 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4596 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4598 inline StubType type(); // Only valid for monomorphic IC stubs.
4600 // Testers for IC stub kinds.
4601 inline bool is_inline_cache_stub();
4602 inline bool is_debug_stub();
4603 inline bool is_handler();
4604 inline bool is_load_stub();
4605 inline bool is_keyed_load_stub();
4606 inline bool is_store_stub();
4607 inline bool is_keyed_store_stub();
4608 inline bool is_call_stub();
4609 inline bool is_binary_op_stub();
4610 inline bool is_compare_ic_stub();
4611 inline bool is_compare_nil_ic_stub();
4612 inline bool is_to_boolean_ic_stub();
4613 inline bool is_keyed_stub();
4614 inline bool is_optimized_code();
4615 inline bool embeds_maps_weakly();
4617 inline bool IsCodeStubOrIC();
4618 inline bool IsJavaScriptCode();
4620 inline void set_raw_kind_specific_flags1(int value);
4621 inline void set_raw_kind_specific_flags2(int value);
4623 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4624 // object was generated by either the hydrogen or the TurboFan optimizing
4625 // compiler (but it may not be an optimized function).
4626 inline bool is_crankshafted();
4627 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4628 inline void set_is_crankshafted(bool value);
4630 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4631 // code object was generated by the TurboFan optimizing compiler.
4632 inline bool is_turbofanned();
4633 inline void set_is_turbofanned(bool value);
4635 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4636 // embedded objects in code should be treated weakly.
4637 inline bool can_have_weak_objects();
4638 inline void set_can_have_weak_objects(bool value);
4640 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4641 // deoptimization support.
4642 inline bool has_deoptimization_support();
4643 inline void set_has_deoptimization_support(bool value);
4645 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4646 // been compiled with debug break slots.
4647 inline bool has_debug_break_slots();
4648 inline void set_has_debug_break_slots(bool value);
4650 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4651 // reloc info includes runtime and external references to support
4652 // serialization/deserialization.
4653 inline bool has_reloc_info_for_serialization();
4654 inline void set_has_reloc_info_for_serialization(bool value);
4656 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4657 // how long the function has been marked for OSR and therefore which
4658 // level of loop nesting we are willing to do on-stack replacement
4660 inline void set_allow_osr_at_loop_nesting_level(int level);
4661 inline int allow_osr_at_loop_nesting_level();
4663 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4664 // the code object was seen on the stack with no IC patching going on.
4665 inline int profiler_ticks();
4666 inline void set_profiler_ticks(int ticks);
4668 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4669 // For builtins, tells which builtin index it has.
4670 // Note that builtins can have a code kind other than BUILTIN, which means
4671 // that for arbitrary code objects, this index value may be random garbage.
4672 // To verify in that case, compare the code object to the indexed builtin.
4673 inline int builtin_index();
4674 inline void set_builtin_index(int id);
4676 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4677 // reserved in the code prologue.
4678 inline unsigned stack_slots();
4679 inline void set_stack_slots(unsigned slots);
4681 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4682 // the instruction stream where the safepoint table starts.
4683 inline unsigned safepoint_table_offset();
4684 inline void set_safepoint_table_offset(unsigned offset);
4686 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4687 // instruction stream where the back edge table starts.
4688 inline unsigned back_edge_table_offset();
4689 inline void set_back_edge_table_offset(unsigned offset);
4691 inline bool back_edges_patched_for_osr();
4693 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4694 inline uint16_t to_boolean_state();
4696 // [has_function_cache]: For kind STUB tells whether there is a function
4697 // cache is passed to the stub.
4698 inline bool has_function_cache();
4699 inline void set_has_function_cache(bool flag);
4702 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4703 // the code is going to be deoptimized because of dead embedded maps.
4704 inline bool marked_for_deoptimization();
4705 inline void set_marked_for_deoptimization(bool flag);
4707 // [constant_pool]: The constant pool for this function.
4708 inline Address constant_pool();
4710 // Get the safepoint entry for the given pc.
4711 SafepointEntry GetSafepointEntry(Address pc);
4713 // Find an object in a stub with a specified map
4714 Object* FindNthObject(int n, Map* match_map);
4716 // Find the first allocation site in an IC stub.
4717 AllocationSite* FindFirstAllocationSite();
4719 // Find the first map in an IC stub.
4720 Map* FindFirstMap();
4721 void FindAllMaps(MapHandleList* maps);
4723 // Find the first handler in an IC stub.
4724 Code* FindFirstHandler();
4726 // Find |length| handlers and put them into |code_list|. Returns false if not
4727 // enough handlers can be found.
4728 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4730 // Find the handler for |map|.
4731 MaybeHandle<Code> FindHandlerForMap(Map* map);
4733 // Find the first name in an IC stub.
4734 Name* FindFirstName();
4736 class FindAndReplacePattern;
4737 // For each (map-to-find, object-to-replace) pair in the pattern, this
4738 // function replaces the corresponding placeholder in the code with the
4739 // object-to-replace. The function assumes that pairs in the pattern come in
4740 // the same order as the placeholders in the code.
4741 // If the placeholder is a weak cell, then the value of weak cell is matched
4742 // against the map-to-find.
4743 void FindAndReplace(const FindAndReplacePattern& pattern);
4745 // The entire code object including its header is copied verbatim to the
4746 // snapshot so that it can be written in one, fast, memcpy during
4747 // deserialization. The deserializer will overwrite some pointers, rather
4748 // like a runtime linker, but the random allocation addresses used in the
4749 // mksnapshot process would still be present in the unlinked snapshot data,
4750 // which would make snapshot production non-reproducible. This method wipes
4751 // out the to-be-overwritten header data for reproducible snapshots.
4752 inline void WipeOutHeader();
4754 // Flags operations.
4755 static inline Flags ComputeFlags(
4756 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4757 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4758 CacheHolderFlag holder = kCacheOnReceiver);
4760 static inline Flags ComputeMonomorphicFlags(
4761 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4762 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4764 static inline Flags ComputeHandlerFlags(
4765 Kind handler_kind, StubType type = NORMAL,
4766 CacheHolderFlag holder = kCacheOnReceiver);
4768 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4769 static inline StubType ExtractTypeFromFlags(Flags flags);
4770 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4771 static inline Kind ExtractKindFromFlags(Flags flags);
4772 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4774 static inline Flags RemoveTypeFromFlags(Flags flags);
4775 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4777 // Convert a target address into a code object.
4778 static inline Code* GetCodeFromTargetAddress(Address address);
4780 // Convert an entry address into an object.
4781 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4783 // Returns the address of the first instruction.
4784 inline byte* instruction_start();
4786 // Returns the address right after the last instruction.
4787 inline byte* instruction_end();
4789 // Returns the size of the instructions, padding, and relocation information.
4790 inline int body_size();
4792 // Returns the address of the first relocation info (read backwards!).
4793 inline byte* relocation_start();
4795 // Code entry point.
4796 inline byte* entry();
4798 // Returns true if pc is inside this object's instructions.
4799 inline bool contains(byte* pc);
4801 // Relocate the code by delta bytes. Called to signal that this code
4802 // object has been moved by delta bytes.
4803 void Relocate(intptr_t delta);
4805 // Migrate code described by desc.
4806 void CopyFrom(const CodeDesc& desc);
4808 // Returns the object size for a given body (used for allocation).
4809 static int SizeFor(int body_size) {
4810 DCHECK_SIZE_TAG_ALIGNED(body_size);
4811 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4814 // Calculate the size of the code object to report for log events. This takes
4815 // the layout of the code object into account.
4816 inline int ExecutableSize();
4818 // Locating source position.
4819 int SourcePosition(Address pc);
4820 int SourceStatementPosition(Address pc);
4824 // Dispatched behavior.
4825 inline int CodeSize();
4826 inline void CodeIterateBody(ObjectVisitor* v);
4828 template<typename StaticVisitor>
4829 inline void CodeIterateBody(Heap* heap);
4831 DECLARE_PRINTER(Code)
4832 DECLARE_VERIFIER(Code)
4834 void ClearInlineCaches();
4835 void ClearInlineCaches(Kind kind);
4837 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4838 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4840 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4842 kToBeExecutedOnceCodeAge = -3,
4843 kNotExecutedCodeAge = -2,
4844 kExecutedOnceCodeAge = -1,
4846 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4848 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4849 kLastCodeAge = kAfterLastCodeAge - 1,
4850 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4851 kIsOldCodeAge = kSexagenarianCodeAge,
4852 kPreAgedCodeAge = kIsOldCodeAge - 1
4854 #undef DECLARE_CODE_AGE_ENUM
4856 // Code aging. Indicates how many full GCs this code has survived without
4857 // being entered through the prologue. Used to determine when it is
4858 // relatively safe to flush this code object and replace it with the lazy
4859 // compilation stub.
4860 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4861 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4862 void MakeYoung(Isolate* isolate);
4863 void MarkToBeExecutedOnce(Isolate* isolate);
4864 void MakeOlder(MarkingParity);
4865 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4868 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4869 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4872 void PrintDeoptLocation(FILE* out, Address pc);
4873 bool CanDeoptAt(Address pc);
4876 void VerifyEmbeddedObjectsDependency();
4880 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4881 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4882 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4885 inline bool CanContainWeakObjects();
4887 inline bool IsWeakObject(Object* object);
4889 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4891 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4892 WeakCell* CachedWeakCell();
4894 // Max loop nesting marker used to postpose OSR. We don't take loop
4895 // nesting that is deeper than 5 levels into account.
4896 static const int kMaxLoopNestingMarker = 6;
4898 static const int kConstantPoolSize =
4899 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4901 // Layout description.
4902 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4903 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4904 static const int kDeoptimizationDataOffset =
4905 kHandlerTableOffset + kPointerSize;
4906 // For FUNCTION kind, we store the type feedback info here.
4907 static const int kTypeFeedbackInfoOffset =
4908 kDeoptimizationDataOffset + kPointerSize;
4909 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4910 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4911 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4912 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4913 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4914 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4915 static const int kKindSpecificFlags2Offset =
4916 kKindSpecificFlags1Offset + kIntSize;
4917 // Note: We might be able to squeeze this into the flags above.
4918 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4919 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4920 static const int kHeaderPaddingStart =
4921 kConstantPoolOffset + kConstantPoolSize;
4923 // Add padding to align the instruction start following right after
4924 // the Code object header.
4925 static const int kHeaderSize =
4926 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4928 // Byte offsets within kKindSpecificFlags1Offset.
4929 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4930 class FullCodeFlagsHasDeoptimizationSupportField:
4931 public BitField<bool, 0, 1> {}; // NOLINT
4932 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4933 class FullCodeFlagsHasRelocInfoForSerialization
4934 : public BitField<bool, 2, 1> {};
4935 // Bit 3 in this bitfield is unused.
4936 class ProfilerTicksField : public BitField<int, 4, 28> {};
4938 // Flags layout. BitField<type, shift, size>.
4939 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4940 class TypeField : public BitField<StubType, 4, 1> {};
4941 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4942 class KindField : public BitField<Kind, 7, 4> {};
4943 class ExtraICStateField: public BitField<ExtraICState, 11,
4944 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4946 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4947 static const int kStackSlotsFirstBit = 0;
4948 static const int kStackSlotsBitCount = 24;
4949 static const int kHasFunctionCacheBit =
4950 kStackSlotsFirstBit + kStackSlotsBitCount;
4951 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4952 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4953 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4955 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4956 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4958 class StackSlotsField: public BitField<int,
4959 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4960 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4962 class MarkedForDeoptimizationField
4963 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
4964 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
4966 class CanHaveWeakObjectsField
4967 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
4969 // KindSpecificFlags2 layout (ALL)
4970 static const int kIsCrankshaftedBit = 0;
4971 class IsCrankshaftedField: public BitField<bool,
4972 kIsCrankshaftedBit, 1> {}; // NOLINT
4974 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
4975 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
4976 static const int kSafepointTableOffsetBitCount = 30;
4978 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
4979 kSafepointTableOffsetBitCount <= 32);
4980 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
4982 class SafepointTableOffsetField: public BitField<int,
4983 kSafepointTableOffsetFirstBit,
4984 kSafepointTableOffsetBitCount> {}; // NOLINT
4986 // KindSpecificFlags2 layout (FUNCTION)
4987 class BackEdgeTableOffsetField: public BitField<int,
4988 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
4989 class AllowOSRAtLoopNestingLevelField: public BitField<int,
4990 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
4991 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
4993 static const int kArgumentsBits = 16;
4994 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
4996 // This constant should be encodable in an ARM instruction.
4997 static const int kFlagsNotUsedInLookup =
4998 TypeField::kMask | CacheHolderField::kMask;
5001 friend class RelocIterator;
5002 friend class Deoptimizer; // For FindCodeAgeSequence.
5004 void ClearInlineCaches(Kind* kind);
5007 byte* FindCodeAgeSequence();
5008 static void GetCodeAgeAndParity(Code* code, Age* age,
5009 MarkingParity* parity);
5010 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5011 MarkingParity* parity);
5012 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5014 // Code aging -- platform-specific
5015 static void PatchPlatformCodeAge(Isolate* isolate,
5016 byte* sequence, Age age,
5017 MarkingParity parity);
5019 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5023 // This class describes the layout of dependent codes array of a map. The
5024 // array is partitioned into several groups of dependent codes. Each group
5025 // contains codes with the same dependency on the map. The array has the
5026 // following layout for n dependency groups:
5028 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5029 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5030 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5032 // The first n elements are Smis, each of them specifies the number of codes
5033 // in the corresponding group. The subsequent elements contain grouped code
5034 // objects in weak cells. The suffix of the array can be filled with the
5035 // undefined value if the number of codes is less than the length of the
5036 // array. The order of the code objects within a group is not preserved.
5038 // All code indexes used in the class are counted starting from the first
5039 // code object of the first group. In other words, code index 0 corresponds
5040 // to array index n = kCodesStartIndex.
5042 class DependentCode: public FixedArray {
5044 enum DependencyGroup {
5045 // Group of code that weakly embed this map and depend on being
5046 // deoptimized when the map is garbage collected.
5048 // Group of code that embed a transition to this map, and depend on being
5049 // deoptimized when the transition is replaced by a new version.
5051 // Group of code that omit run-time prototype checks for prototypes
5052 // described by this map. The group is deoptimized whenever an object
5053 // described by this map changes shape (and transitions to a new map),
5054 // possibly invalidating the assumptions embedded in the code.
5055 kPrototypeCheckGroup,
5056 // Group of code that depends on global property values in property cells
5057 // not being changed.
5058 kPropertyCellChangedGroup,
5059 // Group of code that omit run-time type checks for the field(s) introduced
5062 // Group of code that omit run-time type checks for initial maps of
5064 kInitialMapChangedGroup,
5065 // Group of code that depends on tenuring information in AllocationSites
5066 // not being changed.
5067 kAllocationSiteTenuringChangedGroup,
5068 // Group of code that depends on element transition information in
5069 // AllocationSites not being changed.
5070 kAllocationSiteTransitionChangedGroup
5073 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5075 // Array for holding the index of the first code object of each group.
5076 // The last element stores the total number of code objects.
5077 class GroupStartIndexes {
5079 explicit GroupStartIndexes(DependentCode* entries);
5080 void Recompute(DependentCode* entries);
5081 int at(int i) { return start_indexes_[i]; }
5082 int number_of_entries() { return start_indexes_[kGroupCount]; }
5084 int start_indexes_[kGroupCount + 1];
5087 bool Contains(DependencyGroup group, WeakCell* code_cell);
5089 static Handle<DependentCode> InsertCompilationDependencies(
5090 Handle<DependentCode> entries, DependencyGroup group,
5091 Handle<Foreign> info);
5093 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5094 DependencyGroup group,
5095 Handle<WeakCell> code_cell);
5097 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5098 WeakCell* code_cell);
5100 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5103 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5104 DependentCode::DependencyGroup group);
5106 bool MarkCodeForDeoptimization(Isolate* isolate,
5107 DependentCode::DependencyGroup group);
5109 // The following low-level accessors should only be used by this class
5110 // and the mark compact collector.
5111 inline int number_of_entries(DependencyGroup group);
5112 inline void set_number_of_entries(DependencyGroup group, int value);
5113 inline Object* object_at(int i);
5114 inline void set_object_at(int i, Object* object);
5115 inline void clear_at(int i);
5116 inline void copy(int from, int to);
5117 DECLARE_CAST(DependentCode)
5119 static const char* DependencyGroupName(DependencyGroup group);
5120 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5123 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5124 DependencyGroup group,
5125 Handle<Object> object);
5126 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5127 // Make a room at the end of the given group by moving out the first
5128 // code objects of the subsequent groups.
5129 inline void ExtendGroup(DependencyGroup group);
5130 // Compact by removing cleared weak cells and return true if there was
5131 // any cleared weak cell.
5133 static int Grow(int number_of_entries) {
5134 if (number_of_entries < 5) return number_of_entries + 1;
5135 return number_of_entries * 5 / 4;
5137 static const int kCodesStartIndex = kGroupCount;
5141 class PrototypeInfo;
5144 // All heap objects have a Map that describes their structure.
5145 // A Map contains information about:
5146 // - Size information about the object
5147 // - How to iterate over an object (for garbage collection)
5148 class Map: public HeapObject {
5151 // Size in bytes or kVariableSizeSentinel if instances do not have
5153 inline int instance_size();
5154 inline void set_instance_size(int value);
5156 // Only to clear an unused byte, remove once byte is used.
5157 inline void clear_unused();
5159 // [inobject_properties_or_constructor_function_index]: Provides access
5160 // to the inobject properties in case of JSObject maps, or the constructor
5161 // function index in case of primitive maps.
5162 inline int inobject_properties_or_constructor_function_index();
5163 inline void set_inobject_properties_or_constructor_function_index(int value);
5164 // Count of properties allocated in the object (JSObject only).
5165 inline int GetInObjectProperties();
5166 inline void SetInObjectProperties(int value);
5167 // Index of the constructor function in the native context (primitives only),
5168 // or the special sentinel value to indicate that there is no object wrapper
5169 // for the primitive (i.e. in case of null or undefined).
5170 static const int kNoConstructorFunctionIndex = 0;
5171 inline int GetConstructorFunctionIndex();
5172 inline void SetConstructorFunctionIndex(int value);
5175 inline InstanceType instance_type();
5176 inline void set_instance_type(InstanceType value);
5178 // Tells how many unused property fields are available in the
5179 // instance (only used for JSObject in fast mode).
5180 inline int unused_property_fields();
5181 inline void set_unused_property_fields(int value);
5184 inline byte bit_field() const;
5185 inline void set_bit_field(byte value);
5188 inline byte bit_field2() const;
5189 inline void set_bit_field2(byte value);
5192 inline uint32_t bit_field3() const;
5193 inline void set_bit_field3(uint32_t bits);
5195 class EnumLengthBits: public BitField<int,
5196 0, kDescriptorIndexBitCount> {}; // NOLINT
5197 class NumberOfOwnDescriptorsBits: public BitField<int,
5198 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5199 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5200 class DictionaryMap : public BitField<bool, 20, 1> {};
5201 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5202 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5203 class Deprecated : public BitField<bool, 23, 1> {};
5204 class IsUnstable : public BitField<bool, 24, 1> {};
5205 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5206 class IsStrong : public BitField<bool, 26, 1> {};
5209 // Keep this bit field at the very end for better code in
5210 // Builtins::kJSConstructStubGeneric stub.
5211 // This counter is used for in-object slack tracking and for map aging.
5212 // The in-object slack tracking is considered enabled when the counter is
5213 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5214 class Counter : public BitField<int, 28, 4> {};
5215 static const int kSlackTrackingCounterStart = 14;
5216 static const int kSlackTrackingCounterEnd = 8;
5217 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5218 static const int kRetainingCounterEnd = 0;
5220 // Tells whether the object in the prototype property will be used
5221 // for instances created from this function. If the prototype
5222 // property is set to a value that is not a JSObject, the prototype
5223 // property will not be used to create instances of the function.
5224 // See ECMA-262, 13.2.2.
5225 inline void set_non_instance_prototype(bool value);
5226 inline bool has_non_instance_prototype();
5228 // Tells whether function has special prototype property. If not, prototype
5229 // property will not be created when accessed (will return undefined),
5230 // and construction from this function will not be allowed.
5231 inline void set_function_with_prototype(bool value);
5232 inline bool function_with_prototype();
5234 // Tells whether the instance with this map should be ignored by the
5235 // Object.getPrototypeOf() function and the __proto__ accessor.
5236 inline void set_is_hidden_prototype();
5237 inline bool is_hidden_prototype();
5239 // Records and queries whether the instance has a named interceptor.
5240 inline void set_has_named_interceptor();
5241 inline bool has_named_interceptor();
5243 // Records and queries whether the instance has an indexed interceptor.
5244 inline void set_has_indexed_interceptor();
5245 inline bool has_indexed_interceptor();
5247 // Tells whether the instance is undetectable.
5248 // An undetectable object is a special class of JSObject: 'typeof' operator
5249 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5250 // a normal JS object. It is useful for implementing undetectable
5251 // document.all in Firefox & Safari.
5252 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5253 inline void set_is_undetectable();
5254 inline bool is_undetectable();
5256 // Tells whether the instance has a call-as-function handler.
5257 inline void set_is_observed();
5258 inline bool is_observed();
5260 inline void set_is_strong();
5261 inline bool is_strong();
5262 inline void set_is_extensible(bool value);
5263 inline bool is_extensible();
5264 inline void set_is_prototype_map(bool value);
5265 inline bool is_prototype_map() const;
5267 inline void set_elements_kind(ElementsKind elements_kind);
5268 inline ElementsKind elements_kind();
5270 // Tells whether the instance has fast elements that are only Smis.
5271 inline bool has_fast_smi_elements();
5273 // Tells whether the instance has fast elements.
5274 inline bool has_fast_object_elements();
5275 inline bool has_fast_smi_or_object_elements();
5276 inline bool has_fast_double_elements();
5277 inline bool has_fast_elements();
5278 inline bool has_sloppy_arguments_elements();
5279 inline bool has_fixed_typed_array_elements();
5280 inline bool has_dictionary_elements();
5282 static bool IsValidElementsTransition(ElementsKind from_kind,
5283 ElementsKind to_kind);
5285 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5286 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5287 bool DictionaryElementsInPrototypeChainOnly();
5289 inline Map* ElementsTransitionMap();
5291 inline FixedArrayBase* GetInitialElements();
5293 // [raw_transitions]: Provides access to the transitions storage field.
5294 // Don't call set_raw_transitions() directly to overwrite transitions, use
5295 // the TransitionArray::ReplaceTransitions() wrapper instead!
5296 DECL_ACCESSORS(raw_transitions, Object)
5297 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5298 // (which prototype maps don't have).
5299 DECL_ACCESSORS(prototype_info, Object)
5300 // PrototypeInfo is created lazily using this helper (which installs it on
5301 // the given prototype's map).
5302 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5303 Handle<JSObject> prototype, Isolate* isolate);
5304 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5305 Handle<Map> prototype_map, Isolate* isolate);
5307 // [prototype chain validity cell]: Associated with a prototype object,
5308 // stored in that object's map's PrototypeInfo, indicates that prototype
5309 // chains through this object are currently valid. The cell will be
5310 // invalidated and replaced when the prototype chain changes.
5311 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5313 static const int kPrototypeChainValid = 0;
5314 static const int kPrototypeChainInvalid = 1;
5317 Map* FindFieldOwner(int descriptor);
5319 inline int GetInObjectPropertyOffset(int index);
5321 int NumberOfFields();
5323 // TODO(ishell): candidate with JSObject::MigrateToMap().
5324 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5325 int target_inobject, int target_unused,
5326 int* old_number_of_fields);
5327 // TODO(ishell): moveit!
5328 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5329 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5330 Handle<HeapType> type1,
5331 Handle<HeapType> type2,
5333 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5334 Representation new_representation,
5335 Handle<HeapType> new_field_type);
5336 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5337 PropertyKind new_kind,
5338 PropertyAttributes new_attributes,
5339 Representation new_representation,
5340 Handle<HeapType> new_field_type,
5341 StoreMode store_mode);
5342 static Handle<Map> CopyGeneralizeAllRepresentations(
5343 Handle<Map> map, int modify_index, StoreMode store_mode,
5344 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5346 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5347 int descriptor_number,
5348 Handle<Object> value);
5350 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5351 const char* reason);
5353 // Returns the constructor name (the name (possibly, inferred name) of the
5354 // function that was used to instantiate the object).
5355 String* constructor_name();
5357 // Tells whether the map is used for JSObjects in dictionary mode (ie
5358 // normalized objects, ie objects for which HasFastProperties returns false).
5359 // A map can never be used for both dictionary mode and fast mode JSObjects.
5360 // False by default and for HeapObjects that are not JSObjects.
5361 inline void set_dictionary_map(bool value);
5362 inline bool is_dictionary_map();
5364 // Tells whether the instance needs security checks when accessing its
5366 inline void set_is_access_check_needed(bool access_check_needed);
5367 inline bool is_access_check_needed();
5369 // Returns true if map has a non-empty stub code cache.
5370 inline bool has_code_cache();
5372 // [prototype]: implicit prototype object.
5373 DECL_ACCESSORS(prototype, Object)
5374 // TODO(jkummerow): make set_prototype private.
5375 static void SetPrototype(
5376 Handle<Map> map, Handle<Object> prototype,
5377 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5379 // [constructor]: points back to the function responsible for this map.
5380 // The field overlaps with the back pointer. All maps in a transition tree
5381 // have the same constructor, so maps with back pointers can walk the
5382 // back pointer chain until they find the map holding their constructor.
5383 DECL_ACCESSORS(constructor_or_backpointer, Object)
5384 inline Object* GetConstructor() const;
5385 inline void SetConstructor(Object* constructor,
5386 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5387 // [back pointer]: points back to the parent map from which a transition
5388 // leads to this map. The field overlaps with the constructor (see above).
5389 inline Object* GetBackPointer();
5390 inline void SetBackPointer(Object* value,
5391 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5393 // [instance descriptors]: describes the object.
5394 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5396 // [layout descriptor]: describes the object layout.
5397 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5398 // |layout descriptor| accessor which can be used from GC.
5399 inline LayoutDescriptor* layout_descriptor_gc_safe();
5400 inline bool HasFastPointerLayout() const;
5402 // |layout descriptor| accessor that is safe to call even when
5403 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5404 // |layout_descriptor| field at all).
5405 inline LayoutDescriptor* GetLayoutDescriptor();
5407 inline void UpdateDescriptors(DescriptorArray* descriptors,
5408 LayoutDescriptor* layout_descriptor);
5409 inline void InitializeDescriptors(DescriptorArray* descriptors,
5410 LayoutDescriptor* layout_descriptor);
5412 // [stub cache]: contains stubs compiled for this map.
5413 DECL_ACCESSORS(code_cache, Object)
5415 // [dependent code]: list of optimized codes that weakly embed this map.
5416 DECL_ACCESSORS(dependent_code, DependentCode)
5418 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5419 DECL_ACCESSORS(weak_cell_cache, Object)
5421 inline PropertyDetails GetLastDescriptorDetails();
5423 inline int LastAdded();
5425 inline int NumberOfOwnDescriptors();
5426 inline void SetNumberOfOwnDescriptors(int number);
5428 inline Cell* RetrieveDescriptorsPointer();
5430 inline int EnumLength();
5431 inline void SetEnumLength(int length);
5433 inline bool owns_descriptors();
5434 inline void set_owns_descriptors(bool owns_descriptors);
5435 inline bool has_instance_call_handler();
5436 inline void set_has_instance_call_handler();
5437 inline void mark_unstable();
5438 inline bool is_stable();
5439 inline void set_migration_target(bool value);
5440 inline bool is_migration_target();
5441 inline void set_counter(int value);
5442 inline int counter();
5443 inline void deprecate();
5444 inline bool is_deprecated();
5445 inline bool CanBeDeprecated();
5446 // Returns a non-deprecated version of the input. If the input was not
5447 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5448 // is found by re-transitioning from the root of the transition tree using the
5449 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5451 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5453 // Returns a non-deprecated version of the input. This method may deprecate
5454 // existing maps along the way if encodings conflict. Not for use while
5455 // gathering type feedback. Use TryUpdate in those cases instead.
5456 static Handle<Map> Update(Handle<Map> map);
5458 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5459 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5460 Descriptor* descriptor,
5461 TransitionFlag flag);
5463 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5466 Handle<HeapType> type,
5467 PropertyAttributes attributes,
5468 Representation representation,
5469 TransitionFlag flag);
5471 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5474 Handle<Object> constant,
5475 PropertyAttributes attributes,
5476 TransitionFlag flag);
5478 // Returns a new map with all transitions dropped from the given map and
5479 // the ElementsKind set.
5480 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5481 ElementsKind to_kind);
5483 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5485 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5487 TransitionFlag flag);
5489 static Handle<Map> CopyForObserved(Handle<Map> map);
5491 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5492 PropertyAttributes attrs_to_add,
5493 Handle<Symbol> transition_marker,
5494 const char* reason);
5496 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5499 // Maximal number of fast properties. Used to restrict the number of map
5500 // transitions to avoid an explosion in the number of maps for objects used as
5502 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5503 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5505 Handle<Object> value,
5506 PropertyAttributes attributes,
5507 StoreFromKeyed store_mode);
5508 static Handle<Map> TransitionToAccessorProperty(
5509 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5510 Handle<Object> accessor, PropertyAttributes attributes);
5511 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5514 PropertyAttributes attributes);
5516 inline void AppendDescriptor(Descriptor* desc);
5518 // Returns a copy of the map, prepared for inserting into the transition
5519 // tree (if the |map| owns descriptors then the new one will share
5520 // descriptors with |map|).
5521 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5523 // Returns a copy of the map, with all transitions dropped from the
5524 // instance descriptors.
5525 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5526 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5528 // Returns the next free property index (only valid for FAST MODE).
5529 int NextFreePropertyIndex();
5531 // Returns the number of properties described in instance_descriptors
5532 // filtering out properties with the specified attributes.
5533 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5534 PropertyAttributes filter = NONE);
5538 // Code cache operations.
5540 // Clears the code cache.
5541 inline void ClearCodeCache(Heap* heap);
5543 // Update code cache.
5544 static void UpdateCodeCache(Handle<Map> map,
5548 // Extend the descriptor array of the map with the list of descriptors.
5549 // In case of duplicates, the latest descriptor is used.
5550 static void AppendCallbackDescriptors(Handle<Map> map,
5551 Handle<Object> descriptors);
5553 static inline int SlackForArraySize(int old_size, int size_limit);
5555 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5557 // Returns the found code or undefined if absent.
5558 Object* FindInCodeCache(Name* name, Code::Flags flags);
5560 // Returns the non-negative index of the code object if it is in the
5561 // cache and -1 otherwise.
5562 int IndexInCodeCache(Object* name, Code* code);
5564 // Removes a code object from the code cache at the given index.
5565 void RemoveFromCodeCache(Name* name, Code* code, int index);
5567 // Computes a hash value for this map, to be used in HashTables and such.
5570 // Returns the map that this map transitions to if its elements_kind
5571 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5572 // |safe_to_add_transitions| is set to false if adding transitions is not
5574 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5576 // Returns the transitioned map for this map with the most generic
5577 // elements_kind that's found in |candidates|, or null handle if no match is
5579 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5580 MapHandleList* candidates);
5582 inline bool CanTransition();
5584 inline bool IsPrimitiveMap();
5585 inline bool IsJSObjectMap();
5586 inline bool IsJSArrayMap();
5587 inline bool IsStringMap();
5588 inline bool IsJSProxyMap();
5589 inline bool IsJSGlobalProxyMap();
5590 inline bool IsJSGlobalObjectMap();
5591 inline bool IsGlobalObjectMap();
5593 inline bool CanOmitMapChecks();
5595 static void AddDependentCode(Handle<Map> map,
5596 DependentCode::DependencyGroup group,
5599 bool IsMapInArrayPrototypeChain();
5601 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5603 // Dispatched behavior.
5604 DECLARE_PRINTER(Map)
5605 DECLARE_VERIFIER(Map)
5608 void DictionaryMapVerify();
5609 void VerifyOmittedMapChecks();
5612 inline int visitor_id();
5613 inline void set_visitor_id(int visitor_id);
5615 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5616 Handle<Object> prototype,
5617 PrototypeOptimizationMode mode);
5619 static const int kMaxPreAllocatedPropertyFields = 255;
5621 // Layout description.
5622 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5623 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5624 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5625 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5626 static const int kConstructorOrBackPointerOffset =
5627 kPrototypeOffset + kPointerSize;
5628 // When there is only one transition, it is stored directly in this field;
5629 // otherwise a transition array is used.
5630 // For prototype maps, this slot is used to store this map's PrototypeInfo
5632 static const int kTransitionsOrPrototypeInfoOffset =
5633 kConstructorOrBackPointerOffset + kPointerSize;
5634 static const int kDescriptorsOffset =
5635 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5636 #if V8_DOUBLE_FIELDS_UNBOXING
5637 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5638 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5640 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5641 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5643 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5644 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5645 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5647 // Layout of pointer fields. Heap iteration code relies on them
5648 // being continuously allocated.
5649 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5650 static const int kPointerFieldsEndOffset = kSize;
5652 // Byte offsets within kInstanceSizesOffset.
5653 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5654 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5655 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5656 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5657 // Note there is one byte available for use here.
5658 static const int kUnusedByte = 2;
5659 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5660 static const int kVisitorIdByte = 3;
5661 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5663 // Byte offsets within kInstanceAttributesOffset attributes.
5664 #if V8_TARGET_LITTLE_ENDIAN
5665 // Order instance type and bit field together such that they can be loaded
5666 // together as a 16-bit word with instance type in the lower 8 bits regardless
5667 // of endianess. Also provide endian-independent offset to that 16-bit word.
5668 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5669 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5671 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5672 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5674 static const int kInstanceTypeAndBitFieldOffset =
5675 kInstanceAttributesOffset + 0;
5676 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5677 static const int kUnusedPropertyFieldsByte = 3;
5678 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5680 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5681 Internals::kMapInstanceTypeAndBitFieldOffset);
5683 // Bit positions for bit field.
5684 static const int kHasNonInstancePrototype = 0;
5685 static const int kIsHiddenPrototype = 1;
5686 static const int kHasNamedInterceptor = 2;
5687 static const int kHasIndexedInterceptor = 3;
5688 static const int kIsUndetectable = 4;
5689 static const int kIsObserved = 5;
5690 static const int kIsAccessCheckNeeded = 6;
5691 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5693 // Bit positions for bit field 2
5694 static const int kIsExtensible = 0;
5695 static const int kStringWrapperSafeForDefaultValueOf = 1;
5696 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5697 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5699 // Derived values from bit field 2
5700 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5701 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5702 static const int8_t kMaximumBitField2FastSmiElementValue =
5703 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5704 Map::ElementsKindBits::kShift) - 1;
5705 static const int8_t kMaximumBitField2FastHoleyElementValue =
5706 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5707 Map::ElementsKindBits::kShift) - 1;
5708 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5709 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5710 Map::ElementsKindBits::kShift) - 1;
5712 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5713 kPointerFieldsEndOffset,
5714 kSize> BodyDescriptor;
5716 // Compares this map to another to see if they describe equivalent objects.
5717 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5718 // it had exactly zero inobject properties.
5719 // The "shared" flags of both this map and |other| are ignored.
5720 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5722 // Returns true if given field is unboxed double.
5723 inline bool IsUnboxedDoubleField(FieldIndex index);
5726 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5727 static void TraceAllTransitions(Map* map);
5730 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5731 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5732 Handle<LayoutDescriptor> layout_descriptor);
5735 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5736 Handle<Name> name, SimpleTransitionFlag flag);
5738 bool EquivalentToForTransition(Map* other);
5739 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5740 static Handle<Map> ShareDescriptor(Handle<Map> map,
5741 Handle<DescriptorArray> descriptors,
5742 Descriptor* descriptor);
5743 static Handle<Map> CopyInstallDescriptors(
5744 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5745 Handle<LayoutDescriptor> layout_descriptor);
5746 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5747 Descriptor* descriptor,
5748 TransitionFlag flag);
5749 static Handle<Map> CopyReplaceDescriptors(
5750 Handle<Map> map, Handle<DescriptorArray> descriptors,
5751 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5752 MaybeHandle<Name> maybe_name, const char* reason,
5753 SimpleTransitionFlag simple_flag);
5755 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5756 Handle<DescriptorArray> descriptors,
5757 Descriptor* descriptor,
5759 TransitionFlag flag);
5760 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5761 Handle<Map> map, int descriptor, PropertyKind kind,
5762 PropertyAttributes attributes, const char** reason);
5764 static Handle<Map> CopyNormalized(Handle<Map> map,
5765 PropertyNormalizationMode mode);
5767 // Fires when the layout of an object with a leaf map changes.
5768 // This includes adding transitions to the leaf map or changing
5769 // the descriptor array.
5770 inline void NotifyLeafMapLayoutChange();
5772 void DeprecateTransitionTree();
5773 bool DeprecateTarget(PropertyKind kind, Name* key,
5774 PropertyAttributes attributes,
5775 DescriptorArray* new_descriptors,
5776 LayoutDescriptor* new_layout_descriptor);
5778 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5780 // Update field type of the given descriptor to new representation and new
5781 // type. The type must be prepared for storing in descriptor array:
5782 // it must be either a simple type or a map wrapped in a weak cell.
5783 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5784 Representation new_representation,
5785 Handle<Object> new_wrapped_type);
5787 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5788 PropertyAttributes attributes);
5789 void PrintGeneralization(FILE* file,
5794 bool constant_to_field,
5795 Representation old_representation,
5796 Representation new_representation,
5797 HeapType* old_field_type,
5798 HeapType* new_field_type);
5800 static const int kFastPropertiesSoftLimit = 12;
5801 static const int kMaxFastProperties = 128;
5803 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5807 // An abstract superclass, a marker class really, for simple structure classes.
5808 // It doesn't carry much functionality but allows struct classes to be
5809 // identified in the type system.
5810 class Struct: public HeapObject {
5812 inline void InitializeBody(int object_size);
5813 DECLARE_CAST(Struct)
5817 // A simple one-element struct, useful where smis need to be boxed.
5818 class Box : public Struct {
5820 // [value]: the boxed contents.
5821 DECL_ACCESSORS(value, Object)
5825 // Dispatched behavior.
5826 DECLARE_PRINTER(Box)
5827 DECLARE_VERIFIER(Box)
5829 static const int kValueOffset = HeapObject::kHeaderSize;
5830 static const int kSize = kValueOffset + kPointerSize;
5833 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5837 // Container for metadata stored on each prototype map.
5838 class PrototypeInfo : public Struct {
5840 static const int UNREGISTERED = -1;
5842 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5843 // or Smi(0) if uninitialized.
5844 DECL_ACCESSORS(prototype_users, Object)
5845 // [registry_slot]: Slot in prototype's user registry where this user
5846 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5847 inline int registry_slot() const;
5848 inline void set_registry_slot(int slot);
5849 // [validity_cell]: Cell containing the validity bit for prototype chains
5850 // going through this object, or Smi(0) if uninitialized.
5851 DECL_ACCESSORS(validity_cell, Object)
5852 // [constructor_name]: User-friendly name of the original constructor.
5853 DECL_ACCESSORS(constructor_name, Object)
5855 DECLARE_CAST(PrototypeInfo)
5857 // Dispatched behavior.
5858 DECLARE_PRINTER(PrototypeInfo)
5859 DECLARE_VERIFIER(PrototypeInfo)
5861 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5862 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5863 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5864 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5865 static const int kSize = kConstructorNameOffset + kPointerSize;
5868 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5872 // Script describes a script which has been added to the VM.
5873 class Script: public Struct {
5882 // Script compilation types.
5883 enum CompilationType {
5884 COMPILATION_TYPE_HOST = 0,
5885 COMPILATION_TYPE_EVAL = 1
5888 // Script compilation state.
5889 enum CompilationState {
5890 COMPILATION_STATE_INITIAL = 0,
5891 COMPILATION_STATE_COMPILED = 1
5894 // [source]: the script source.
5895 DECL_ACCESSORS(source, Object)
5897 // [name]: the script name.
5898 DECL_ACCESSORS(name, Object)
5900 // [id]: the script id.
5901 DECL_ACCESSORS(id, Smi)
5903 // [line_offset]: script line offset in resource from where it was extracted.
5904 DECL_ACCESSORS(line_offset, Smi)
5906 // [column_offset]: script column offset in resource from where it was
5908 DECL_ACCESSORS(column_offset, Smi)
5910 // [context_data]: context data for the context this script was compiled in.
5911 DECL_ACCESSORS(context_data, Object)
5913 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5914 DECL_ACCESSORS(wrapper, HeapObject)
5916 // [type]: the script type.
5917 DECL_ACCESSORS(type, Smi)
5919 // [line_ends]: FixedArray of line ends positions.
5920 DECL_ACCESSORS(line_ends, Object)
5922 // [eval_from_shared]: for eval scripts the shared funcion info for the
5923 // function from which eval was called.
5924 DECL_ACCESSORS(eval_from_shared, Object)
5926 // [eval_from_instructions_offset]: the instruction offset in the code for the
5927 // function from which eval was called where eval was called.
5928 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5930 // [shared_function_infos]: weak fixed array containing all shared
5931 // function infos created from this script.
5932 DECL_ACCESSORS(shared_function_infos, Object)
5934 // [flags]: Holds an exciting bitfield.
5935 DECL_ACCESSORS(flags, Smi)
5937 // [source_url]: sourceURL from magic comment
5938 DECL_ACCESSORS(source_url, Object)
5940 // [source_url]: sourceMappingURL magic comment
5941 DECL_ACCESSORS(source_mapping_url, Object)
5943 // [compilation_type]: how the the script was compiled. Encoded in the
5945 inline CompilationType compilation_type();
5946 inline void set_compilation_type(CompilationType type);
5948 // [compilation_state]: determines whether the script has already been
5949 // compiled. Encoded in the 'flags' field.
5950 inline CompilationState compilation_state();
5951 inline void set_compilation_state(CompilationState state);
5953 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
5954 // and used by the embedder to make decisions about the script. V8 just passes
5955 // this through. Encoded in the 'flags' field.
5956 inline v8::ScriptOriginOptions origin_options();
5957 inline void set_origin_options(ScriptOriginOptions origin_options);
5959 DECLARE_CAST(Script)
5961 // If script source is an external string, check that the underlying
5962 // resource is accessible. Otherwise, always return true.
5963 inline bool HasValidSource();
5965 // Convert code position into column number.
5966 static int GetColumnNumber(Handle<Script> script, int code_pos);
5968 // Convert code position into (zero-based) line number.
5969 // The non-handlified version does not allocate, but may be much slower.
5970 static int GetLineNumber(Handle<Script> script, int code_pos);
5971 int GetLineNumber(int code_pos);
5973 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
5975 // Init line_ends array with code positions of line ends inside script source.
5976 static void InitLineEnds(Handle<Script> script);
5978 // Get the JS object wrapping the given script; create it if none exists.
5979 static Handle<JSObject> GetWrapper(Handle<Script> script);
5981 // Look through the list of existing shared function infos to find one
5982 // that matches the function literal. Return empty handle if not found.
5983 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
5985 // Dispatched behavior.
5986 DECLARE_PRINTER(Script)
5987 DECLARE_VERIFIER(Script)
5989 static const int kSourceOffset = HeapObject::kHeaderSize;
5990 static const int kNameOffset = kSourceOffset + kPointerSize;
5991 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
5992 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
5993 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
5994 static const int kWrapperOffset = kContextOffset + kPointerSize;
5995 static const int kTypeOffset = kWrapperOffset + kPointerSize;
5996 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
5997 static const int kIdOffset = kLineEndsOffset + kPointerSize;
5998 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
5999 static const int kEvalFrominstructionsOffsetOffset =
6000 kEvalFromSharedOffset + kPointerSize;
6001 static const int kSharedFunctionInfosOffset =
6002 kEvalFrominstructionsOffsetOffset + kPointerSize;
6003 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6004 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6005 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6006 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6009 int GetLineNumberWithArray(int code_pos);
6011 // Bit positions in the flags field.
6012 static const int kCompilationTypeBit = 0;
6013 static const int kCompilationStateBit = 1;
6014 static const int kOriginOptionsShift = 2;
6015 static const int kOriginOptionsSize = 3;
6016 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6017 << kOriginOptionsShift;
6019 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6023 // List of builtin functions we want to identify to improve code
6026 // Each entry has a name of a global object property holding an object
6027 // optionally followed by ".prototype", a name of a builtin function
6028 // on the object (the one the id is set for), and a label.
6030 // Installation of ids for the selected builtin functions is handled
6031 // by the bootstrapper.
6032 #define FUNCTIONS_WITH_ID_LIST(V) \
6033 V(Array.prototype, indexOf, ArrayIndexOf) \
6034 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6035 V(Array.prototype, push, ArrayPush) \
6036 V(Array.prototype, pop, ArrayPop) \
6037 V(Array.prototype, shift, ArrayShift) \
6038 V(Function.prototype, apply, FunctionApply) \
6039 V(Function.prototype, call, FunctionCall) \
6040 V(String.prototype, charCodeAt, StringCharCodeAt) \
6041 V(String.prototype, charAt, StringCharAt) \
6042 V(String, fromCharCode, StringFromCharCode) \
6043 V(Math, random, MathRandom) \
6044 V(Math, floor, MathFloor) \
6045 V(Math, round, MathRound) \
6046 V(Math, ceil, MathCeil) \
6047 V(Math, abs, MathAbs) \
6048 V(Math, log, MathLog) \
6049 V(Math, exp, MathExp) \
6050 V(Math, sqrt, MathSqrt) \
6051 V(Math, pow, MathPow) \
6052 V(Math, max, MathMax) \
6053 V(Math, min, MathMin) \
6054 V(Math, cos, MathCos) \
6055 V(Math, sin, MathSin) \
6056 V(Math, tan, MathTan) \
6057 V(Math, acos, MathAcos) \
6058 V(Math, asin, MathAsin) \
6059 V(Math, atan, MathAtan) \
6060 V(Math, atan2, MathAtan2) \
6061 V(Math, imul, MathImul) \
6062 V(Math, clz32, MathClz32) \
6063 V(Math, fround, MathFround)
6065 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6066 V(Atomics, load, AtomicsLoad) \
6067 V(Atomics, store, AtomicsStore)
6069 enum BuiltinFunctionId {
6071 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6073 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6074 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6075 #undef DECLARE_FUNCTION_ID
6076 // Fake id for a special case of Math.pow. Note, it continues the
6077 // list of math functions.
6082 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6083 // that both {code} and {literals} can be NULL to pass search result status.
6084 struct CodeAndLiterals {
6085 Code* code; // Cached optimized code.
6086 FixedArray* literals; // Cached literals array.
6090 // SharedFunctionInfo describes the JSFunction information that can be
6091 // shared by multiple instances of the function.
6092 class SharedFunctionInfo: public HeapObject {
6094 // [name]: Function name.
6095 DECL_ACCESSORS(name, Object)
6097 // [code]: Function code.
6098 DECL_ACCESSORS(code, Code)
6099 inline void ReplaceCode(Code* code);
6101 // [optimized_code_map]: Map from native context to optimized code
6102 // and a shared literals array or Smi(0) if none.
6103 DECL_ACCESSORS(optimized_code_map, Object)
6105 // Returns entry from optimized code map for specified context and OSR entry.
6106 // Note that {code == nullptr} indicates no matching entry has been found,
6107 // whereas {literals == nullptr} indicates the code is context-independent.
6108 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6109 BailoutId osr_ast_id);
6111 // Clear optimized code map.
6112 void ClearOptimizedCodeMap();
6114 // Removed a specific optimized code object from the optimized code map.
6115 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6117 // Trims the optimized code map after entries have been removed.
6118 void TrimOptimizedCodeMap(int shrink_by);
6120 // Add a new entry to the optimized code map for context-independent code.
6121 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6124 // Add a new entry to the optimized code map for context-dependent code.
6125 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6126 Handle<Context> native_context,
6128 Handle<FixedArray> literals,
6129 BailoutId osr_ast_id);
6131 // Set up the link between shared function info and the script. The shared
6132 // function info is added to the list on the script.
6133 static void SetScript(Handle<SharedFunctionInfo> shared,
6134 Handle<Object> script_object);
6136 // Layout description of the optimized code map.
6137 static const int kNextMapIndex = 0;
6138 static const int kSharedCodeIndex = 1;
6139 static const int kEntriesStart = 2;
6140 static const int kContextOffset = 0;
6141 static const int kCachedCodeOffset = 1;
6142 static const int kLiteralsOffset = 2;
6143 static const int kOsrAstIdOffset = 3;
6144 static const int kEntryLength = 4;
6145 static const int kInitialLength = kEntriesStart + kEntryLength;
6147 // [scope_info]: Scope info.
6148 DECL_ACCESSORS(scope_info, ScopeInfo)
6150 // [construct stub]: Code stub for constructing instances of this function.
6151 DECL_ACCESSORS(construct_stub, Code)
6153 // Returns if this function has been compiled to native code yet.
6154 inline bool is_compiled();
6156 // [length]: The function length - usually the number of declared parameters.
6157 // Use up to 2^30 parameters.
6158 inline int length() const;
6159 inline void set_length(int value);
6161 // [internal formal parameter count]: The declared number of parameters.
6162 // For subclass constructors, also includes new.target.
6163 // The size of function's frame is internal_formal_parameter_count + 1.
6164 inline int internal_formal_parameter_count() const;
6165 inline void set_internal_formal_parameter_count(int value);
6167 // Set the formal parameter count so the function code will be
6168 // called without using argument adaptor frames.
6169 inline void DontAdaptArguments();
6171 // [expected_nof_properties]: Expected number of properties for the function.
6172 inline int expected_nof_properties() const;
6173 inline void set_expected_nof_properties(int value);
6175 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6176 // (increasingly) from crankshafted code where sufficient feedback isn't
6178 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6180 // Unconditionally clear the type feedback vector (including vector ICs).
6181 void ClearTypeFeedbackInfo();
6183 // Clear the type feedback vector with a more subtle policy at GC time.
6184 void ClearTypeFeedbackInfoAtGCTime();
6187 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6188 // even if the GC moves this SharedFunctionInfo.
6189 inline int unique_id() const;
6190 inline void set_unique_id(int value);
6193 // [instance class name]: class name for instances.
6194 DECL_ACCESSORS(instance_class_name, Object)
6196 // [function data]: This field holds some additional data for function.
6197 // Currently it has one of:
6198 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6199 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6200 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6201 // In the long run we don't want all functions to have this field but
6202 // we can fix that when we have a better model for storing hidden data
6204 DECL_ACCESSORS(function_data, Object)
6206 inline bool IsApiFunction();
6207 inline FunctionTemplateInfo* get_api_func_data();
6208 inline bool HasBuiltinFunctionId();
6209 inline BuiltinFunctionId builtin_function_id();
6210 inline bool HasBytecodeArray();
6211 inline BytecodeArray* bytecode_array();
6213 // [script info]: Script from which the function originates.
6214 DECL_ACCESSORS(script, Object)
6216 // [num_literals]: Number of literals used by this function.
6217 inline int num_literals() const;
6218 inline void set_num_literals(int value);
6220 // [start_position_and_type]: Field used to store both the source code
6221 // position, whether or not the function is a function expression,
6222 // and whether or not the function is a toplevel function. The two
6223 // least significants bit indicates whether the function is an
6224 // expression and the rest contains the source code position.
6225 inline int start_position_and_type() const;
6226 inline void set_start_position_and_type(int value);
6228 // The function is subject to debugging if a debug info is attached.
6229 inline bool HasDebugInfo();
6230 inline DebugInfo* GetDebugInfo();
6232 // A function has debug code if the compiled code has debug break slots.
6233 inline bool HasDebugCode();
6235 // [debug info]: Debug information.
6236 DECL_ACCESSORS(debug_info, Object)
6238 // [inferred name]: Name inferred from variable or property
6239 // assignment of this function. Used to facilitate debugging and
6240 // profiling of JavaScript code written in OO style, where almost
6241 // all functions are anonymous but are assigned to object
6243 DECL_ACCESSORS(inferred_name, String)
6245 // The function's name if it is non-empty, otherwise the inferred name.
6246 String* DebugName();
6248 // Position of the 'function' token in the script source.
6249 inline int function_token_position() const;
6250 inline void set_function_token_position(int function_token_position);
6252 // Position of this function in the script source.
6253 inline int start_position() const;
6254 inline void set_start_position(int start_position);
6256 // End position of this function in the script source.
6257 inline int end_position() const;
6258 inline void set_end_position(int end_position);
6260 // Is this function a function expression in the source code.
6261 DECL_BOOLEAN_ACCESSORS(is_expression)
6263 // Is this function a top-level function (scripts, evals).
6264 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6266 // Bit field containing various information collected by the compiler to
6267 // drive optimization.
6268 inline int compiler_hints() const;
6269 inline void set_compiler_hints(int value);
6271 inline int ast_node_count() const;
6272 inline void set_ast_node_count(int count);
6274 inline int profiler_ticks() const;
6275 inline void set_profiler_ticks(int ticks);
6277 // Inline cache age is used to infer whether the function survived a context
6278 // disposal or not. In the former case we reset the opt_count.
6279 inline int ic_age();
6280 inline void set_ic_age(int age);
6282 // Indicates if this function can be lazy compiled.
6283 // This is used to determine if we can safely flush code from a function
6284 // when doing GC if we expect that the function will no longer be used.
6285 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6287 // Indicates if this function can be lazy compiled without a context.
6288 // This is used to determine if we can force compilation without reaching
6289 // the function through program execution but through other means (e.g. heap
6290 // iteration by the debugger).
6291 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6293 // Indicates whether optimizations have been disabled for this
6294 // shared function info. If a function is repeatedly optimized or if
6295 // we cannot optimize the function we disable optimization to avoid
6296 // spending time attempting to optimize it again.
6297 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6299 // Indicates the language mode.
6300 inline LanguageMode language_mode();
6301 inline void set_language_mode(LanguageMode language_mode);
6303 // False if the function definitely does not allocate an arguments object.
6304 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6306 // Indicates that this function uses a super property (or an eval that may
6307 // use a super property).
6308 // This is needed to set up the [[HomeObject]] on the function instance.
6309 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6311 // True if the function has any duplicated parameter names.
6312 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6314 // Indicates whether the function is a native function.
6315 // These needs special treatment in .call and .apply since
6316 // null passed as the receiver should not be translated to the
6318 DECL_BOOLEAN_ACCESSORS(native)
6320 // Indicate that this function should always be inlined in optimized code.
6321 DECL_BOOLEAN_ACCESSORS(force_inline)
6323 // Indicates that the function was created by the Function function.
6324 // Though it's anonymous, toString should treat it as if it had the name
6325 // "anonymous". We don't set the name itself so that the system does not
6326 // see a binding for it.
6327 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6329 // Indicates whether the function is a bound function created using
6330 // the bind function.
6331 DECL_BOOLEAN_ACCESSORS(bound)
6333 // Indicates that the function is anonymous (the name field can be set
6334 // through the API, which does not change this flag).
6335 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6337 // Is this a function or top-level/eval code.
6338 DECL_BOOLEAN_ACCESSORS(is_function)
6340 // Indicates that code for this function cannot be compiled with Crankshaft.
6341 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6343 // Indicates that code for this function cannot be flushed.
6344 DECL_BOOLEAN_ACCESSORS(dont_flush)
6346 // Indicates that this function is a generator.
6347 DECL_BOOLEAN_ACCESSORS(is_generator)
6349 // Indicates that this function is an arrow function.
6350 DECL_BOOLEAN_ACCESSORS(is_arrow)
6352 // Indicates that this function is a concise method.
6353 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6355 // Indicates that this function is an accessor (getter or setter).
6356 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6358 // Indicates that this function is a default constructor.
6359 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6361 // Indicates that this function is an asm function.
6362 DECL_BOOLEAN_ACCESSORS(asm_function)
6364 // Indicates that the the shared function info is deserialized from cache.
6365 DECL_BOOLEAN_ACCESSORS(deserialized)
6367 // Indicates that the the shared function info has never been compiled before.
6368 DECL_BOOLEAN_ACCESSORS(never_compiled)
6370 inline FunctionKind kind();
6371 inline void set_kind(FunctionKind kind);
6373 // Indicates whether or not the code in the shared function support
6375 inline bool has_deoptimization_support();
6377 // Enable deoptimization support through recompiled code.
6378 void EnableDeoptimizationSupport(Code* recompiled);
6380 // Disable (further) attempted optimization of all functions sharing this
6381 // shared function info.
6382 void DisableOptimization(BailoutReason reason);
6384 inline BailoutReason disable_optimization_reason();
6386 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6387 // code, returns whether it asserted (i.e., always true if assertions are
6389 bool VerifyBailoutId(BailoutId id);
6391 // [source code]: Source code for the function.
6392 bool HasSourceCode() const;
6393 Handle<Object> GetSourceCode();
6395 // Number of times the function was optimized.
6396 inline int opt_count();
6397 inline void set_opt_count(int opt_count);
6399 // Number of times the function was deoptimized.
6400 inline void set_deopt_count(int value);
6401 inline int deopt_count();
6402 inline void increment_deopt_count();
6404 // Number of time we tried to re-enable optimization after it
6405 // was disabled due to high number of deoptimizations.
6406 inline void set_opt_reenable_tries(int value);
6407 inline int opt_reenable_tries();
6409 inline void TryReenableOptimization();
6411 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6412 inline void set_counters(int value);
6413 inline int counters() const;
6415 // Stores opt_count and bailout_reason as bit-fields.
6416 inline void set_opt_count_and_bailout_reason(int value);
6417 inline int opt_count_and_bailout_reason() const;
6419 inline void set_disable_optimization_reason(BailoutReason reason);
6421 // Tells whether this function should be subject to debugging.
6422 inline bool IsSubjectToDebugging();
6424 // Check whether or not this function is inlineable.
6425 bool IsInlineable();
6427 // Source size of this function.
6430 // Calculate the instance size.
6431 int CalculateInstanceSize();
6433 // Calculate the number of in-object properties.
6434 int CalculateInObjectProperties();
6436 inline bool has_simple_parameters();
6438 // Initialize a SharedFunctionInfo from a parsed function literal.
6439 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6440 FunctionLiteral* lit);
6442 // Dispatched behavior.
6443 DECLARE_PRINTER(SharedFunctionInfo)
6444 DECLARE_VERIFIER(SharedFunctionInfo)
6446 void ResetForNewContext(int new_ic_age);
6448 DECLARE_CAST(SharedFunctionInfo)
6451 static const int kDontAdaptArgumentsSentinel = -1;
6453 // Layout description.
6455 static const int kNameOffset = HeapObject::kHeaderSize;
6456 static const int kCodeOffset = kNameOffset + kPointerSize;
6457 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6458 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6459 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6460 static const int kInstanceClassNameOffset =
6461 kConstructStubOffset + kPointerSize;
6462 static const int kFunctionDataOffset =
6463 kInstanceClassNameOffset + kPointerSize;
6464 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6465 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6466 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6467 static const int kFeedbackVectorOffset =
6468 kInferredNameOffset + kPointerSize;
6470 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6471 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6473 // Just to not break the postmortrem support with conditional offsets
6474 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6475 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6478 #if V8_HOST_ARCH_32_BIT
6480 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6481 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6482 static const int kExpectedNofPropertiesOffset =
6483 kFormalParameterCountOffset + kPointerSize;
6484 static const int kNumLiteralsOffset =
6485 kExpectedNofPropertiesOffset + kPointerSize;
6486 static const int kStartPositionAndTypeOffset =
6487 kNumLiteralsOffset + kPointerSize;
6488 static const int kEndPositionOffset =
6489 kStartPositionAndTypeOffset + kPointerSize;
6490 static const int kFunctionTokenPositionOffset =
6491 kEndPositionOffset + kPointerSize;
6492 static const int kCompilerHintsOffset =
6493 kFunctionTokenPositionOffset + kPointerSize;
6494 static const int kOptCountAndBailoutReasonOffset =
6495 kCompilerHintsOffset + kPointerSize;
6496 static const int kCountersOffset =
6497 kOptCountAndBailoutReasonOffset + kPointerSize;
6498 static const int kAstNodeCountOffset =
6499 kCountersOffset + kPointerSize;
6500 static const int kProfilerTicksOffset =
6501 kAstNodeCountOffset + kPointerSize;
6504 static const int kSize = kProfilerTicksOffset + kPointerSize;
6506 // The only reason to use smi fields instead of int fields
6507 // is to allow iteration without maps decoding during
6508 // garbage collections.
6509 // To avoid wasting space on 64-bit architectures we use
6510 // the following trick: we group integer fields into pairs
6511 // The least significant integer in each pair is shifted left by 1.
6512 // By doing this we guarantee that LSB of each kPointerSize aligned
6513 // word is not set and thus this word cannot be treated as pointer
6514 // to HeapObject during old space traversal.
6515 #if V8_TARGET_LITTLE_ENDIAN
6516 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6517 static const int kFormalParameterCountOffset =
6518 kLengthOffset + kIntSize;
6520 static const int kExpectedNofPropertiesOffset =
6521 kFormalParameterCountOffset + kIntSize;
6522 static const int kNumLiteralsOffset =
6523 kExpectedNofPropertiesOffset + kIntSize;
6525 static const int kEndPositionOffset =
6526 kNumLiteralsOffset + kIntSize;
6527 static const int kStartPositionAndTypeOffset =
6528 kEndPositionOffset + kIntSize;
6530 static const int kFunctionTokenPositionOffset =
6531 kStartPositionAndTypeOffset + kIntSize;
6532 static const int kCompilerHintsOffset =
6533 kFunctionTokenPositionOffset + kIntSize;
6535 static const int kOptCountAndBailoutReasonOffset =
6536 kCompilerHintsOffset + kIntSize;
6537 static const int kCountersOffset =
6538 kOptCountAndBailoutReasonOffset + kIntSize;
6540 static const int kAstNodeCountOffset =
6541 kCountersOffset + kIntSize;
6542 static const int kProfilerTicksOffset =
6543 kAstNodeCountOffset + kIntSize;
6546 static const int kSize = kProfilerTicksOffset + kIntSize;
6548 #elif V8_TARGET_BIG_ENDIAN
6549 static const int kFormalParameterCountOffset =
6550 kLastPointerFieldOffset + kPointerSize;
6551 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6553 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6554 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6556 static const int kStartPositionAndTypeOffset =
6557 kExpectedNofPropertiesOffset + kIntSize;
6558 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6560 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6561 static const int kFunctionTokenPositionOffset =
6562 kCompilerHintsOffset + kIntSize;
6564 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6565 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6567 static const int kProfilerTicksOffset =
6568 kOptCountAndBailoutReasonOffset + kIntSize;
6569 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6572 static const int kSize = kAstNodeCountOffset + kIntSize;
6575 #error Unknown byte ordering
6576 #endif // Big endian
6580 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6582 typedef FixedBodyDescriptor<kNameOffset,
6583 kLastPointerFieldOffset + kPointerSize,
6584 kSize> BodyDescriptor;
6586 // Bit positions in start_position_and_type.
6587 // The source code start position is in the 30 most significant bits of
6588 // the start_position_and_type field.
6589 static const int kIsExpressionBit = 0;
6590 static const int kIsTopLevelBit = 1;
6591 static const int kStartPositionShift = 2;
6592 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6594 // Bit positions in compiler_hints.
6595 enum CompilerHints {
6596 kAllowLazyCompilation,
6597 kAllowLazyCompilationWithoutContext,
6598 kOptimizationDisabled,
6599 kStrictModeFunction,
6600 kStrongModeFunction,
6603 kHasDuplicateParameters,
6608 kNameShouldPrintAsAnonymous,
6615 kIsAccessorFunction,
6616 kIsDefaultConstructor,
6617 kIsSubclassConstructor,
6623 kCompilerHintsCount // Pseudo entry
6625 // Add hints for other modes when they're added.
6626 STATIC_ASSERT(LANGUAGE_END == 3);
6628 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6630 class DeoptCountBits : public BitField<int, 0, 4> {};
6631 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6632 class ICAgeBits : public BitField<int, 22, 8> {};
6634 class OptCountBits : public BitField<int, 0, 22> {};
6635 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6638 #if V8_HOST_ARCH_32_BIT
6639 // On 32 bit platforms, compiler hints is a smi.
6640 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6641 static const int kCompilerHintsSize = kPointerSize;
6643 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6644 static const int kCompilerHintsSmiTagSize = 0;
6645 static const int kCompilerHintsSize = kIntSize;
6648 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6649 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6652 // Constants for optimizing codegen for strict mode function and
6654 // Allows to use byte-width instructions.
6655 static const int kStrictModeBitWithinByte =
6656 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6657 static const int kStrongModeBitWithinByte =
6658 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6660 static const int kNativeBitWithinByte =
6661 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6663 #if defined(V8_TARGET_LITTLE_ENDIAN)
6664 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6665 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6666 static const int kStrongModeByteOffset =
6667 kCompilerHintsOffset +
6668 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6669 static const int kNativeByteOffset = kCompilerHintsOffset +
6670 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6671 #elif defined(V8_TARGET_BIG_ENDIAN)
6672 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6673 (kCompilerHintsSize - 1) -
6674 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6675 static const int kStrongModeByteOffset =
6676 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6677 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6678 static const int kNativeByteOffset = kCompilerHintsOffset +
6679 (kCompilerHintsSize - 1) -
6680 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6682 #error Unknown byte ordering
6686 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6690 // Printing support.
6691 struct SourceCodeOf {
6692 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6693 : value(v), max_length(max) {}
6694 const SharedFunctionInfo* value;
6699 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6702 class JSGeneratorObject: public JSObject {
6704 // [function]: The function corresponding to this generator object.
6705 DECL_ACCESSORS(function, JSFunction)
6707 // [context]: The context of the suspended computation.
6708 DECL_ACCESSORS(context, Context)
6710 // [receiver]: The receiver of the suspended computation.
6711 DECL_ACCESSORS(receiver, Object)
6713 // [continuation]: Offset into code of continuation.
6715 // A positive offset indicates a suspended generator. The special
6716 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6717 // cannot be resumed.
6718 inline int continuation() const;
6719 inline void set_continuation(int continuation);
6720 inline bool is_closed();
6721 inline bool is_executing();
6722 inline bool is_suspended();
6724 // [operand_stack]: Saved operand stack.
6725 DECL_ACCESSORS(operand_stack, FixedArray)
6727 DECLARE_CAST(JSGeneratorObject)
6729 // Dispatched behavior.
6730 DECLARE_PRINTER(JSGeneratorObject)
6731 DECLARE_VERIFIER(JSGeneratorObject)
6733 // Magic sentinel values for the continuation.
6734 static const int kGeneratorExecuting = -1;
6735 static const int kGeneratorClosed = 0;
6737 // Layout description.
6738 static const int kFunctionOffset = JSObject::kHeaderSize;
6739 static const int kContextOffset = kFunctionOffset + kPointerSize;
6740 static const int kReceiverOffset = kContextOffset + kPointerSize;
6741 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6742 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6743 static const int kSize = kOperandStackOffset + kPointerSize;
6745 // Resume mode, for use by runtime functions.
6746 enum ResumeMode { NEXT, THROW };
6748 // Yielding from a generator returns an object with the following inobject
6749 // properties. See Context::iterator_result_map() for the map.
6750 static const int kResultValuePropertyIndex = 0;
6751 static const int kResultDonePropertyIndex = 1;
6752 static const int kResultPropertyCount = 2;
6754 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6755 static const int kResultDonePropertyOffset =
6756 kResultValuePropertyOffset + kPointerSize;
6757 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6760 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6764 // Representation for module instance objects.
6765 class JSModule: public JSObject {
6767 // [context]: the context holding the module's locals, or undefined if none.
6768 DECL_ACCESSORS(context, Object)
6770 // [scope_info]: Scope info.
6771 DECL_ACCESSORS(scope_info, ScopeInfo)
6773 DECLARE_CAST(JSModule)
6775 // Dispatched behavior.
6776 DECLARE_PRINTER(JSModule)
6777 DECLARE_VERIFIER(JSModule)
6779 // Layout description.
6780 static const int kContextOffset = JSObject::kHeaderSize;
6781 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6782 static const int kSize = kScopeInfoOffset + kPointerSize;
6785 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6789 // JSFunction describes JavaScript functions.
6790 class JSFunction: public JSObject {
6792 // [prototype_or_initial_map]:
6793 DECL_ACCESSORS(prototype_or_initial_map, Object)
6795 // [shared]: The information about the function that
6796 // can be shared by instances.
6797 DECL_ACCESSORS(shared, SharedFunctionInfo)
6799 // [context]: The context for this function.
6800 inline Context* context();
6801 inline void set_context(Object* context);
6802 inline JSObject* global_proxy();
6804 // [code]: The generated code object for this function. Executed
6805 // when the function is invoked, e.g. foo() or new foo(). See
6806 // [[Call]] and [[Construct]] description in ECMA-262, section
6808 inline Code* code();
6809 inline void set_code(Code* code);
6810 inline void set_code_no_write_barrier(Code* code);
6811 inline void ReplaceCode(Code* code);
6813 // Tells whether this function is builtin.
6814 inline bool IsBuiltin();
6816 // Tells whether this function inlines the given shared function info.
6817 bool Inlines(SharedFunctionInfo* candidate);
6819 // Tells whether this function should be subject to debugging.
6820 inline bool IsSubjectToDebugging();
6822 // Tells whether or not the function needs arguments adaption.
6823 inline bool NeedsArgumentsAdaption();
6825 // Tells whether or not this function has been optimized.
6826 inline bool IsOptimized();
6828 // Mark this function for lazy recompilation. The function will be
6829 // recompiled the next time it is executed.
6830 void MarkForOptimization();
6831 void AttemptConcurrentOptimization();
6833 // Tells whether or not the function is already marked for lazy
6835 inline bool IsMarkedForOptimization();
6836 inline bool IsMarkedForConcurrentOptimization();
6838 // Tells whether or not the function is on the concurrent recompilation queue.
6839 inline bool IsInOptimizationQueue();
6841 // Inobject slack tracking is the way to reclaim unused inobject space.
6843 // The instance size is initially determined by adding some slack to
6844 // expected_nof_properties (to allow for a few extra properties added
6845 // after the constructor). There is no guarantee that the extra space
6846 // will not be wasted.
6848 // Here is the algorithm to reclaim the unused inobject space:
6849 // - Detect the first constructor call for this JSFunction.
6850 // When it happens enter the "in progress" state: initialize construction
6851 // counter in the initial_map.
6852 // - While the tracking is in progress create objects filled with
6853 // one_pointer_filler_map instead of undefined_value. This way they can be
6854 // resized quickly and safely.
6855 // - Once enough objects have been created compute the 'slack'
6856 // (traverse the map transition tree starting from the
6857 // initial_map and find the lowest value of unused_property_fields).
6858 // - Traverse the transition tree again and decrease the instance size
6859 // of every map. Existing objects will resize automatically (they are
6860 // filled with one_pointer_filler_map). All further allocations will
6861 // use the adjusted instance size.
6862 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6863 // allocations made using different closures could actually create different
6864 // kind of objects (see prototype inheritance pattern).
6866 // Important: inobject slack tracking is not attempted during the snapshot
6869 // True if the initial_map is set and the object constructions countdown
6870 // counter is not zero.
6871 static const int kGenerousAllocationCount =
6872 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6873 inline bool IsInobjectSlackTrackingInProgress();
6875 // Starts the tracking.
6876 // Initializes object constructions countdown counter in the initial map.
6877 void StartInobjectSlackTracking();
6879 // Completes the tracking.
6880 void CompleteInobjectSlackTracking();
6882 // [literals_or_bindings]: Fixed array holding either
6883 // the materialized literals or the bindings of a bound function.
6885 // If the function contains object, regexp or array literals, the
6886 // literals array prefix contains the object, regexp, and array
6887 // function to be used when creating these literals. This is
6888 // necessary so that we do not dynamically lookup the object, regexp
6889 // or array functions. Performing a dynamic lookup, we might end up
6890 // using the functions from a new context that we should not have
6893 // On bound functions, the array is a (copy-on-write) fixed-array containing
6894 // the function that was bound, bound this-value and any bound
6895 // arguments. Bound functions never contain literals.
6896 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6898 inline FixedArray* literals();
6899 inline void set_literals(FixedArray* literals);
6901 inline FixedArray* function_bindings();
6902 inline void set_function_bindings(FixedArray* bindings);
6904 // The initial map for an object created by this constructor.
6905 inline Map* initial_map();
6906 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
6907 Handle<Object> prototype);
6908 inline bool has_initial_map();
6909 static void EnsureHasInitialMap(Handle<JSFunction> function);
6911 // Get and set the prototype property on a JSFunction. If the
6912 // function has an initial map the prototype is set on the initial
6913 // map. Otherwise, the prototype is put in the initial map field
6914 // until an initial map is needed.
6915 inline bool has_prototype();
6916 inline bool has_instance_prototype();
6917 inline Object* prototype();
6918 inline Object* instance_prototype();
6919 static void SetPrototype(Handle<JSFunction> function,
6920 Handle<Object> value);
6921 static void SetInstancePrototype(Handle<JSFunction> function,
6922 Handle<Object> value);
6924 // Creates a new closure for the fucntion with the same bindings,
6925 // bound values, and prototype. An equivalent of spec operations
6926 // ``CloneMethod`` and ``CloneBoundFunction``.
6927 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
6929 // After prototype is removed, it will not be created when accessed, and
6930 // [[Construct]] from this function will not be allowed.
6931 bool RemovePrototype();
6932 inline bool should_have_prototype();
6934 // Accessor for this function's initial map's [[class]]
6935 // property. This is primarily used by ECMA native functions. This
6936 // method sets the class_name field of this function's initial map
6937 // to a given value. It creates an initial map if this function does
6938 // not have one. Note that this method does not copy the initial map
6939 // if it has one already, but simply replaces it with the new value.
6940 // Instances created afterwards will have a map whose [[class]] is
6941 // set to 'value', but there is no guarantees on instances created
6943 void SetInstanceClassName(String* name);
6945 // Returns if this function has been compiled to native code yet.
6946 inline bool is_compiled();
6948 // Returns `false` if formal parameters include rest parameters, optional
6949 // parameters, or destructuring parameters.
6950 // TODO(caitp): make this a flag set during parsing
6951 inline bool has_simple_parameters();
6953 // [next_function_link]: Links functions into various lists, e.g. the list
6954 // of optimized functions hanging off the native_context. The CodeFlusher
6955 // uses this link to chain together flushing candidates. Treated weakly
6956 // by the garbage collector.
6957 DECL_ACCESSORS(next_function_link, Object)
6959 // Prints the name of the function using PrintF.
6960 void PrintName(FILE* out = stdout);
6962 DECLARE_CAST(JSFunction)
6964 // Iterates the objects, including code objects indirectly referenced
6965 // through pointers to the first instruction in the code object.
6966 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
6968 // Dispatched behavior.
6969 DECLARE_PRINTER(JSFunction)
6970 DECLARE_VERIFIER(JSFunction)
6972 // Returns the number of allocated literals.
6973 inline int NumberOfLiterals();
6975 // Used for flags such as --hydrogen-filter.
6976 bool PassesFilter(const char* raw_filter);
6978 // The function's name if it is configured, otherwise shared function info
6980 static Handle<String> GetDebugName(Handle<JSFunction> function);
6982 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
6983 // kSize) is weak and has special handling during garbage collection.
6984 static const int kCodeEntryOffset = JSObject::kHeaderSize;
6985 static const int kPrototypeOrInitialMapOffset =
6986 kCodeEntryOffset + kPointerSize;
6987 static const int kSharedFunctionInfoOffset =
6988 kPrototypeOrInitialMapOffset + kPointerSize;
6989 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
6990 static const int kLiteralsOffset = kContextOffset + kPointerSize;
6991 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
6992 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
6993 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
6995 // Layout of the bound-function binding array.
6996 static const int kBoundFunctionIndex = 0;
6997 static const int kBoundThisIndex = 1;
6998 static const int kBoundArgumentsStartIndex = 2;
7001 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7005 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7006 // and the prototype is hidden. JSGlobalProxy always delegates
7007 // property accesses to its prototype if the prototype is not null.
7009 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7011 // Accessing a JSGlobalProxy requires security check.
7013 class JSGlobalProxy : public JSObject {
7015 // [native_context]: the owner native context of this global proxy object.
7016 // It is null value if this object is not used by any context.
7017 DECL_ACCESSORS(native_context, Object)
7019 // [hash]: The hash code property (undefined if not initialized yet).
7020 DECL_ACCESSORS(hash, Object)
7022 DECLARE_CAST(JSGlobalProxy)
7024 inline bool IsDetachedFrom(GlobalObject* global) const;
7026 // Dispatched behavior.
7027 DECLARE_PRINTER(JSGlobalProxy)
7028 DECLARE_VERIFIER(JSGlobalProxy)
7030 // Layout description.
7031 static const int kNativeContextOffset = JSObject::kHeaderSize;
7032 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7033 static const int kSize = kHashOffset + kPointerSize;
7036 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7040 // Common super class for JavaScript global objects and the special
7041 // builtins global objects.
7042 class GlobalObject: public JSObject {
7044 // [builtins]: the object holding the runtime routines written in JS.
7045 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7047 // [native context]: the natives corresponding to this global object.
7048 DECL_ACCESSORS(native_context, Context)
7050 // [global proxy]: the global proxy object of the context
7051 DECL_ACCESSORS(global_proxy, JSObject)
7053 DECLARE_CAST(GlobalObject)
7055 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7057 // Ensure that the global object has a cell for the given property name.
7058 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7061 // Layout description.
7062 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7063 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7064 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7065 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7068 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7072 // JavaScript global object.
7073 class JSGlobalObject: public GlobalObject {
7075 DECLARE_CAST(JSGlobalObject)
7077 inline bool IsDetached();
7079 // Dispatched behavior.
7080 DECLARE_PRINTER(JSGlobalObject)
7081 DECLARE_VERIFIER(JSGlobalObject)
7083 // Layout description.
7084 static const int kSize = GlobalObject::kHeaderSize;
7087 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7091 // Builtins global object which holds the runtime routines written in
7093 class JSBuiltinsObject: public GlobalObject {
7095 // Accessors for the runtime routines written in JavaScript.
7096 inline Object* javascript_builtin(Builtins::JavaScript id);
7097 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7099 DECLARE_CAST(JSBuiltinsObject)
7101 // Dispatched behavior.
7102 DECLARE_PRINTER(JSBuiltinsObject)
7103 DECLARE_VERIFIER(JSBuiltinsObject)
7105 // Layout description. The size of the builtins object includes
7106 // room for two pointers per runtime routine written in javascript
7107 // (function and code object).
7108 static const int kJSBuiltinsCount = Builtins::id_count;
7109 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7110 static const int kSize =
7111 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7113 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7114 return kJSBuiltinsOffset + id * kPointerSize;
7118 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7122 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7123 class JSValue: public JSObject {
7125 // [value]: the object being wrapped.
7126 DECL_ACCESSORS(value, Object)
7128 DECLARE_CAST(JSValue)
7130 // Dispatched behavior.
7131 DECLARE_PRINTER(JSValue)
7132 DECLARE_VERIFIER(JSValue)
7134 // Layout description.
7135 static const int kValueOffset = JSObject::kHeaderSize;
7136 static const int kSize = kValueOffset + kPointerSize;
7139 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7145 // Representation for JS date objects.
7146 class JSDate: public JSObject {
7148 // If one component is NaN, all of them are, indicating a NaN time value.
7149 // [value]: the time value.
7150 DECL_ACCESSORS(value, Object)
7151 // [year]: caches year. Either undefined, smi, or NaN.
7152 DECL_ACCESSORS(year, Object)
7153 // [month]: caches month. Either undefined, smi, or NaN.
7154 DECL_ACCESSORS(month, Object)
7155 // [day]: caches day. Either undefined, smi, or NaN.
7156 DECL_ACCESSORS(day, Object)
7157 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7158 DECL_ACCESSORS(weekday, Object)
7159 // [hour]: caches hours. Either undefined, smi, or NaN.
7160 DECL_ACCESSORS(hour, Object)
7161 // [min]: caches minutes. Either undefined, smi, or NaN.
7162 DECL_ACCESSORS(min, Object)
7163 // [sec]: caches seconds. Either undefined, smi, or NaN.
7164 DECL_ACCESSORS(sec, Object)
7165 // [cache stamp]: sample of the date cache stamp at the
7166 // moment when chached fields were cached.
7167 DECL_ACCESSORS(cache_stamp, Object)
7169 DECLARE_CAST(JSDate)
7171 // Returns the date field with the specified index.
7172 // See FieldIndex for the list of date fields.
7173 static Object* GetField(Object* date, Smi* index);
7175 void SetValue(Object* value, bool is_value_nan);
7178 // Dispatched behavior.
7179 DECLARE_PRINTER(JSDate)
7180 DECLARE_VERIFIER(JSDate)
7182 // The order is important. It must be kept in sync with date macros
7193 kFirstUncachedField,
7194 kMillisecond = kFirstUncachedField,
7198 kYearUTC = kFirstUTCField,
7211 // Layout description.
7212 static const int kValueOffset = JSObject::kHeaderSize;
7213 static const int kYearOffset = kValueOffset + kPointerSize;
7214 static const int kMonthOffset = kYearOffset + kPointerSize;
7215 static const int kDayOffset = kMonthOffset + kPointerSize;
7216 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7217 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7218 static const int kMinOffset = kHourOffset + kPointerSize;
7219 static const int kSecOffset = kMinOffset + kPointerSize;
7220 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7221 static const int kSize = kCacheStampOffset + kPointerSize;
7224 inline Object* DoGetField(FieldIndex index);
7226 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7228 // Computes and caches the cacheable fields of the date.
7229 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7232 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7236 // Representation of message objects used for error reporting through
7237 // the API. The messages are formatted in JavaScript so this object is
7238 // a real JavaScript object. The information used for formatting the
7239 // error messages are not directly accessible from JavaScript to
7240 // prevent leaking information to user code called during error
7242 class JSMessageObject: public JSObject {
7244 // [type]: the type of error message.
7245 inline int type() const;
7246 inline void set_type(int value);
7248 // [arguments]: the arguments for formatting the error message.
7249 DECL_ACCESSORS(argument, Object)
7251 // [script]: the script from which the error message originated.
7252 DECL_ACCESSORS(script, Object)
7254 // [stack_frames]: an array of stack frames for this error object.
7255 DECL_ACCESSORS(stack_frames, Object)
7257 // [start_position]: the start position in the script for the error message.
7258 inline int start_position() const;
7259 inline void set_start_position(int value);
7261 // [end_position]: the end position in the script for the error message.
7262 inline int end_position() const;
7263 inline void set_end_position(int value);
7265 DECLARE_CAST(JSMessageObject)
7267 // Dispatched behavior.
7268 DECLARE_PRINTER(JSMessageObject)
7269 DECLARE_VERIFIER(JSMessageObject)
7271 // Layout description.
7272 static const int kTypeOffset = JSObject::kHeaderSize;
7273 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7274 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7275 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7276 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7277 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7278 static const int kSize = kEndPositionOffset + kPointerSize;
7280 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7281 kStackFramesOffset + kPointerSize,
7282 kSize> BodyDescriptor;
7286 // Regular expressions
7287 // The regular expression holds a single reference to a FixedArray in
7288 // the kDataOffset field.
7289 // The FixedArray contains the following data:
7290 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7291 // - reference to the original source string
7292 // - reference to the original flag string
7293 // If it is an atom regexp
7294 // - a reference to a literal string to search for
7295 // If it is an irregexp regexp:
7296 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7297 // used for tracking the last usage (used for code flushing).
7298 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7299 // used for tracking the last usage (used for code flushing)..
7300 // - max number of registers used by irregexp implementations.
7301 // - number of capture registers (output values) of the regexp.
7302 class JSRegExp: public JSObject {
7305 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7306 // ATOM: A simple string to match against using an indexOf operation.
7307 // IRREGEXP: Compiled with Irregexp.
7308 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7309 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7316 UNICODE_ESCAPES = 16
7321 explicit Flags(uint32_t value) : value_(value) { }
7322 bool is_global() { return (value_ & GLOBAL) != 0; }
7323 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7324 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7325 bool is_sticky() { return (value_ & STICKY) != 0; }
7326 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7327 uint32_t value() { return value_; }
7332 DECL_ACCESSORS(data, Object)
7334 inline Type TypeTag();
7335 inline int CaptureCount();
7336 inline Flags GetFlags();
7337 inline String* Pattern();
7338 inline Object* DataAt(int index);
7339 // Set implementation data after the object has been prepared.
7340 inline void SetDataAt(int index, Object* value);
7342 static int code_index(bool is_latin1) {
7344 return kIrregexpLatin1CodeIndex;
7346 return kIrregexpUC16CodeIndex;
7350 static int saved_code_index(bool is_latin1) {
7352 return kIrregexpLatin1CodeSavedIndex;
7354 return kIrregexpUC16CodeSavedIndex;
7358 DECLARE_CAST(JSRegExp)
7360 // Dispatched behavior.
7361 DECLARE_VERIFIER(JSRegExp)
7363 static const int kDataOffset = JSObject::kHeaderSize;
7364 static const int kSize = kDataOffset + kPointerSize;
7366 // Indices in the data array.
7367 static const int kTagIndex = 0;
7368 static const int kSourceIndex = kTagIndex + 1;
7369 static const int kFlagsIndex = kSourceIndex + 1;
7370 static const int kDataIndex = kFlagsIndex + 1;
7371 // The data fields are used in different ways depending on the
7372 // value of the tag.
7373 // Atom regexps (literal strings).
7374 static const int kAtomPatternIndex = kDataIndex;
7376 static const int kAtomDataSize = kAtomPatternIndex + 1;
7378 // Irregexp compiled code or bytecode for Latin1. If compilation
7379 // fails, this fields hold an exception object that should be
7380 // thrown if the regexp is used again.
7381 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7382 // Irregexp compiled code or bytecode for UC16. If compilation
7383 // fails, this fields hold an exception object that should be
7384 // thrown if the regexp is used again.
7385 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7387 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7388 // is a potential candidate for flushing.
7389 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7390 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7391 // a potential candidate for flushing.
7392 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7394 // Maximal number of registers used by either Latin1 or UC16.
7395 // Only used to check that there is enough stack space
7396 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7397 // Number of captures in the compiled regexp.
7398 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7400 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7402 // Offsets directly into the data fixed array.
7403 static const int kDataTagOffset =
7404 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7405 static const int kDataOneByteCodeOffset =
7406 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7407 static const int kDataUC16CodeOffset =
7408 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7409 static const int kIrregexpCaptureCountOffset =
7410 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7412 // In-object fields.
7413 static const int kSourceFieldIndex = 0;
7414 static const int kGlobalFieldIndex = 1;
7415 static const int kIgnoreCaseFieldIndex = 2;
7416 static const int kMultilineFieldIndex = 3;
7417 static const int kLastIndexFieldIndex = 4;
7418 static const int kInObjectFieldCount = 5;
7420 // The uninitialized value for a regexp code object.
7421 static const int kUninitializedValue = -1;
7423 // The compilation error value for the regexp code object. The real error
7424 // object is in the saved code field.
7425 static const int kCompilationErrorValue = -2;
7427 // When we store the sweep generation at which we moved the code from the
7428 // code index to the saved code index we mask it of to be in the [0:255]
7430 static const int kCodeAgeMask = 0xff;
7434 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7436 static inline bool IsMatch(HashTableKey* key, Object* value) {
7437 return key->IsMatch(value);
7440 static inline uint32_t Hash(HashTableKey* key) {
7444 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7445 return key->HashForObject(object);
7448 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7450 static const int kPrefixSize = 0;
7451 static const int kEntrySize = 2;
7455 // This cache is used in two different variants. For regexp caching, it simply
7456 // maps identifying info of the regexp to the cached regexp object. Scripts and
7457 // eval code only gets cached after a second probe for the code object. To do
7458 // so, on first "put" only a hash identifying the source is entered into the
7459 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7460 // such lifetimes get reduced, and removed once they reach zero. If a second put
7461 // is called while such a hash is live in the cache, the hash gets replaced by
7462 // an actual cache entry. Age also removes stale live entries from the cache.
7463 // Such entries are identified by SharedFunctionInfos pointing to either the
7464 // recompilation stub, or to "old" code. This avoids memory leaks due to
7465 // premature caching of scripts and eval strings that are never needed later.
7466 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7467 CompilationCacheShape,
7470 // Find cached value for a string key, otherwise return null.
7471 Handle<Object> Lookup(
7472 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7473 Handle<Object> LookupEval(
7474 Handle<String> src, Handle<SharedFunctionInfo> shared,
7475 LanguageMode language_mode, int scope_position);
7476 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7477 static Handle<CompilationCacheTable> Put(
7478 Handle<CompilationCacheTable> cache, Handle<String> src,
7479 Handle<Context> context, LanguageMode language_mode,
7480 Handle<Object> value);
7481 static Handle<CompilationCacheTable> PutEval(
7482 Handle<CompilationCacheTable> cache, Handle<String> src,
7483 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7484 int scope_position);
7485 static Handle<CompilationCacheTable> PutRegExp(
7486 Handle<CompilationCacheTable> cache, Handle<String> src,
7487 JSRegExp::Flags flags, Handle<FixedArray> value);
7488 void Remove(Object* value);
7490 static const int kHashGenerations = 10;
7492 DECLARE_CAST(CompilationCacheTable)
7495 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7499 class CodeCache: public Struct {
7501 DECL_ACCESSORS(default_cache, FixedArray)
7502 DECL_ACCESSORS(normal_type_cache, Object)
7504 // Add the code object to the cache.
7506 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7508 // Lookup code object in the cache. Returns code object if found and undefined
7510 Object* Lookup(Name* name, Code::Flags flags);
7512 // Get the internal index of a code object in the cache. Returns -1 if the
7513 // code object is not in that cache. This index can be used to later call
7514 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7516 int GetIndex(Object* name, Code* code);
7518 // Remove an object from the cache with the provided internal index.
7519 void RemoveByIndex(Object* name, Code* code, int index);
7521 DECLARE_CAST(CodeCache)
7523 // Dispatched behavior.
7524 DECLARE_PRINTER(CodeCache)
7525 DECLARE_VERIFIER(CodeCache)
7527 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7528 static const int kNormalTypeCacheOffset =
7529 kDefaultCacheOffset + kPointerSize;
7530 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7533 static void UpdateDefaultCache(
7534 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7535 static void UpdateNormalTypeCache(
7536 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7537 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7538 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7540 // Code cache layout of the default cache. Elements are alternating name and
7541 // code objects for non normal load/store/call IC's.
7542 static const int kCodeCacheEntrySize = 2;
7543 static const int kCodeCacheEntryNameOffset = 0;
7544 static const int kCodeCacheEntryCodeOffset = 1;
7546 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7550 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7552 static inline bool IsMatch(HashTableKey* key, Object* value) {
7553 return key->IsMatch(value);
7556 static inline uint32_t Hash(HashTableKey* key) {
7560 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7561 return key->HashForObject(object);
7564 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7566 static const int kPrefixSize = 0;
7567 static const int kEntrySize = 2;
7571 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7572 CodeCacheHashTableShape,
7575 Object* Lookup(Name* name, Code::Flags flags);
7576 static Handle<CodeCacheHashTable> Put(
7577 Handle<CodeCacheHashTable> table,
7581 int GetIndex(Name* name, Code::Flags flags);
7582 void RemoveByIndex(int index);
7584 DECLARE_CAST(CodeCacheHashTable)
7586 // Initial size of the fixed array backing the hash table.
7587 static const int kInitialSize = 64;
7590 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7594 class PolymorphicCodeCache: public Struct {
7596 DECL_ACCESSORS(cache, Object)
7598 static void Update(Handle<PolymorphicCodeCache> cache,
7599 MapHandleList* maps,
7604 // Returns an undefined value if the entry is not found.
7605 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7607 DECLARE_CAST(PolymorphicCodeCache)
7609 // Dispatched behavior.
7610 DECLARE_PRINTER(PolymorphicCodeCache)
7611 DECLARE_VERIFIER(PolymorphicCodeCache)
7613 static const int kCacheOffset = HeapObject::kHeaderSize;
7614 static const int kSize = kCacheOffset + kPointerSize;
7617 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7621 class PolymorphicCodeCacheHashTable
7622 : public HashTable<PolymorphicCodeCacheHashTable,
7623 CodeCacheHashTableShape,
7626 Object* Lookup(MapHandleList* maps, int code_kind);
7628 static Handle<PolymorphicCodeCacheHashTable> Put(
7629 Handle<PolymorphicCodeCacheHashTable> hash_table,
7630 MapHandleList* maps,
7634 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7636 static const int kInitialSize = 64;
7638 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7642 class TypeFeedbackInfo: public Struct {
7644 inline int ic_total_count();
7645 inline void set_ic_total_count(int count);
7647 inline int ic_with_type_info_count();
7648 inline void change_ic_with_type_info_count(int delta);
7650 inline int ic_generic_count();
7651 inline void change_ic_generic_count(int delta);
7653 inline void initialize_storage();
7655 inline void change_own_type_change_checksum();
7656 inline int own_type_change_checksum();
7658 inline void set_inlined_type_change_checksum(int checksum);
7659 inline bool matches_inlined_type_change_checksum(int checksum);
7661 DECLARE_CAST(TypeFeedbackInfo)
7663 // Dispatched behavior.
7664 DECLARE_PRINTER(TypeFeedbackInfo)
7665 DECLARE_VERIFIER(TypeFeedbackInfo)
7667 static const int kStorage1Offset = HeapObject::kHeaderSize;
7668 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7669 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7670 static const int kSize = kStorage3Offset + kPointerSize;
7673 static const int kTypeChangeChecksumBits = 7;
7675 class ICTotalCountField: public BitField<int, 0,
7676 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7677 class OwnTypeChangeChecksum: public BitField<int,
7678 kSmiValueSize - kTypeChangeChecksumBits,
7679 kTypeChangeChecksumBits> {}; // NOLINT
7680 class ICsWithTypeInfoCountField: public BitField<int, 0,
7681 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7682 class InlinedTypeChangeChecksum: public BitField<int,
7683 kSmiValueSize - kTypeChangeChecksumBits,
7684 kTypeChangeChecksumBits> {}; // NOLINT
7686 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7690 enum AllocationSiteMode {
7691 DONT_TRACK_ALLOCATION_SITE,
7692 TRACK_ALLOCATION_SITE,
7693 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7697 class AllocationSite: public Struct {
7699 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7700 static const double kPretenureRatio;
7701 static const int kPretenureMinimumCreated = 100;
7703 // Values for pretenure decision field.
7704 enum PretenureDecision {
7710 kLastPretenureDecisionValue = kZombie
7713 const char* PretenureDecisionName(PretenureDecision decision);
7715 DECL_ACCESSORS(transition_info, Object)
7716 // nested_site threads a list of sites that represent nested literals
7717 // walked in a particular order. So [[1, 2], 1, 2] will have one
7718 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7719 DECL_ACCESSORS(nested_site, Object)
7720 DECL_ACCESSORS(pretenure_data, Smi)
7721 DECL_ACCESSORS(pretenure_create_count, Smi)
7722 DECL_ACCESSORS(dependent_code, DependentCode)
7723 DECL_ACCESSORS(weak_next, Object)
7725 inline void Initialize();
7727 // This method is expensive, it should only be called for reporting.
7728 bool IsNestedSite();
7730 // transition_info bitfields, for constructed array transition info.
7731 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7732 class UnusedBits: public BitField<int, 15, 14> {};
7733 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7735 // Bitfields for pretenure_data
7736 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7737 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7738 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7739 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7741 // Increments the mementos found counter and returns true when the first
7742 // memento was found for a given allocation site.
7743 inline bool IncrementMementoFoundCount();
7745 inline void IncrementMementoCreateCount();
7747 PretenureFlag GetPretenureMode();
7749 void ResetPretenureDecision();
7751 inline PretenureDecision pretenure_decision();
7752 inline void set_pretenure_decision(PretenureDecision decision);
7754 inline bool deopt_dependent_code();
7755 inline void set_deopt_dependent_code(bool deopt);
7757 inline int memento_found_count();
7758 inline void set_memento_found_count(int count);
7760 inline int memento_create_count();
7761 inline void set_memento_create_count(int count);
7763 // The pretenuring decision is made during gc, and the zombie state allows
7764 // us to recognize when an allocation site is just being kept alive because
7765 // a later traversal of new space may discover AllocationMementos that point
7766 // to this AllocationSite.
7767 inline bool IsZombie();
7769 inline bool IsMaybeTenure();
7771 inline void MarkZombie();
7773 inline bool MakePretenureDecision(PretenureDecision current_decision,
7775 bool maximum_size_scavenge);
7777 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7779 inline ElementsKind GetElementsKind();
7780 inline void SetElementsKind(ElementsKind kind);
7782 inline bool CanInlineCall();
7783 inline void SetDoNotInlineCall();
7785 inline bool SitePointsToLiteral();
7787 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7788 ElementsKind to_kind);
7790 DECLARE_PRINTER(AllocationSite)
7791 DECLARE_VERIFIER(AllocationSite)
7793 DECLARE_CAST(AllocationSite)
7794 static inline AllocationSiteMode GetMode(
7795 ElementsKind boilerplate_elements_kind);
7796 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7797 static inline bool CanTrack(InstanceType type);
7799 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7800 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7801 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7802 static const int kPretenureCreateCountOffset =
7803 kPretenureDataOffset + kPointerSize;
7804 static const int kDependentCodeOffset =
7805 kPretenureCreateCountOffset + kPointerSize;
7806 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7807 static const int kSize = kWeakNextOffset + kPointerSize;
7809 // During mark compact we need to take special care for the dependent code
7811 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7812 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7814 // For other visitors, use the fixed body descriptor below.
7815 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7816 kDependentCodeOffset + kPointerSize,
7817 kSize> BodyDescriptor;
7820 inline bool PretenuringDecisionMade();
7822 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7826 class AllocationMemento: public Struct {
7828 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7829 static const int kSize = kAllocationSiteOffset + kPointerSize;
7831 DECL_ACCESSORS(allocation_site, Object)
7833 inline bool IsValid();
7834 inline AllocationSite* GetAllocationSite();
7836 DECLARE_PRINTER(AllocationMemento)
7837 DECLARE_VERIFIER(AllocationMemento)
7839 DECLARE_CAST(AllocationMemento)
7842 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7846 // Representation of a slow alias as part of a sloppy arguments objects.
7847 // For fast aliases (if HasSloppyArgumentsElements()):
7848 // - the parameter map contains an index into the context
7849 // - all attributes of the element have default values
7850 // For slow aliases (if HasDictionaryArgumentsElements()):
7851 // - the parameter map contains no fast alias mapping (i.e. the hole)
7852 // - this struct (in the slow backing store) contains an index into the context
7853 // - all attributes are available as part if the property details
7854 class AliasedArgumentsEntry: public Struct {
7856 inline int aliased_context_slot() const;
7857 inline void set_aliased_context_slot(int count);
7859 DECLARE_CAST(AliasedArgumentsEntry)
7861 // Dispatched behavior.
7862 DECLARE_PRINTER(AliasedArgumentsEntry)
7863 DECLARE_VERIFIER(AliasedArgumentsEntry)
7865 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7866 static const int kSize = kAliasedContextSlot + kPointerSize;
7869 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7873 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7874 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7877 class StringHasher {
7879 explicit inline StringHasher(int length, uint32_t seed);
7881 template <typename schar>
7882 static inline uint32_t HashSequentialString(const schar* chars,
7886 // Reads all the data, even for long strings and computes the utf16 length.
7887 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7889 int* utf16_length_out);
7891 // Calculated hash value for a string consisting of 1 to
7892 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7893 // value is represented decimal value.
7894 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7896 // No string is allowed to have a hash of zero. That value is reserved
7897 // for internal properties. If the hash calculation yields zero then we
7899 static const int kZeroHash = 27;
7901 // Reusable parts of the hashing algorithm.
7902 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7903 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7904 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7905 const uc16* chars, int length));
7906 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
7911 // Returns the value to store in the hash field of a string with
7912 // the given length and contents.
7913 uint32_t GetHashField();
7914 // Returns true if the hash of this string can be computed without
7915 // looking at the contents.
7916 inline bool has_trivial_hash();
7917 // Adds a block of characters to the hash.
7918 template<typename Char>
7919 inline void AddCharacters(const Char* chars, int len);
7922 // Add a character to the hash.
7923 inline void AddCharacter(uint16_t c);
7924 // Update index. Returns true if string is still an index.
7925 inline bool UpdateIndex(uint16_t c);
7928 uint32_t raw_running_hash_;
7929 uint32_t array_index_;
7930 bool is_array_index_;
7931 bool is_first_char_;
7932 DISALLOW_COPY_AND_ASSIGN(StringHasher);
7936 class IteratingStringHasher : public StringHasher {
7938 static inline uint32_t Hash(String* string, uint32_t seed);
7939 inline void VisitOneByteString(const uint8_t* chars, int length);
7940 inline void VisitTwoByteString(const uint16_t* chars, int length);
7943 inline IteratingStringHasher(int len, uint32_t seed);
7944 void VisitConsString(ConsString* cons_string);
7945 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
7949 // The characteristics of a string are stored in its map. Retrieving these
7950 // few bits of information is moderately expensive, involving two memory
7951 // loads where the second is dependent on the first. To improve efficiency
7952 // the shape of the string is given its own class so that it can be retrieved
7953 // once and used for several string operations. A StringShape is small enough
7954 // to be passed by value and is immutable, but be aware that flattening a
7955 // string can potentially alter its shape. Also be aware that a GC caused by
7956 // something else can alter the shape of a string due to ConsString
7957 // shortcutting. Keeping these restrictions in mind has proven to be error-
7958 // prone and so we no longer put StringShapes in variables unless there is a
7959 // concrete performance benefit at that particular point in the code.
7960 class StringShape BASE_EMBEDDED {
7962 inline explicit StringShape(const String* s);
7963 inline explicit StringShape(Map* s);
7964 inline explicit StringShape(InstanceType t);
7965 inline bool IsSequential();
7966 inline bool IsExternal();
7967 inline bool IsCons();
7968 inline bool IsSliced();
7969 inline bool IsIndirect();
7970 inline bool IsExternalOneByte();
7971 inline bool IsExternalTwoByte();
7972 inline bool IsSequentialOneByte();
7973 inline bool IsSequentialTwoByte();
7974 inline bool IsInternalized();
7975 inline StringRepresentationTag representation_tag();
7976 inline uint32_t encoding_tag();
7977 inline uint32_t full_representation_tag();
7978 inline uint32_t size_tag();
7980 inline uint32_t type() { return type_; }
7981 inline void invalidate() { valid_ = false; }
7982 inline bool valid() { return valid_; }
7984 inline void invalidate() { }
7990 inline void set_valid() { valid_ = true; }
7993 inline void set_valid() { }
7998 // The Name abstract class captures anything that can be used as a property
7999 // name, i.e., strings and symbols. All names store a hash value.
8000 class Name: public HeapObject {
8002 // Get and set the hash field of the name.
8003 inline uint32_t hash_field();
8004 inline void set_hash_field(uint32_t value);
8006 // Tells whether the hash code has been computed.
8007 inline bool HasHashCode();
8009 // Returns a hash value used for the property table
8010 inline uint32_t Hash();
8012 // Equality operations.
8013 inline bool Equals(Name* other);
8014 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8017 inline bool AsArrayIndex(uint32_t* index);
8019 // If the name is private, it can only name own properties.
8020 inline bool IsPrivate();
8022 // If the name is a non-flat string, this method returns a flat version of the
8023 // string. Otherwise it'll just return the input.
8024 static inline Handle<Name> Flatten(Handle<Name> name,
8025 PretenureFlag pretenure = NOT_TENURED);
8029 DECLARE_PRINTER(Name)
8031 void NameShortPrint();
8032 int NameShortPrint(Vector<char> str);
8035 // Layout description.
8036 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8037 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8038 static const int kHashFieldOffset = kHashFieldSlot;
8040 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8042 static const int kSize = kHashFieldSlot + kPointerSize;
8044 // Mask constant for checking if a name has a computed hash code
8045 // and if it is a string that is an array index. The least significant bit
8046 // indicates whether a hash code has been computed. If the hash code has
8047 // been computed the 2nd bit tells whether the string can be used as an
8049 static const int kHashNotComputedMask = 1;
8050 static const int kIsNotArrayIndexMask = 1 << 1;
8051 static const int kNofHashBitFields = 2;
8053 // Shift constant retrieving hash code from hash field.
8054 static const int kHashShift = kNofHashBitFields;
8056 // Only these bits are relevant in the hash, since the top two are shifted
8058 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8060 // Array index strings this short can keep their index in the hash field.
8061 static const int kMaxCachedArrayIndexLength = 7;
8063 // For strings which are array indexes the hash value has the string length
8064 // mixed into the hash, mainly to avoid a hash value of zero which would be
8065 // the case for the string '0'. 24 bits are used for the array index value.
8066 static const int kArrayIndexValueBits = 24;
8067 static const int kArrayIndexLengthBits =
8068 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8070 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8072 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8073 kArrayIndexValueBits> {}; // NOLINT
8074 class ArrayIndexLengthBits : public BitField<unsigned int,
8075 kNofHashBitFields + kArrayIndexValueBits,
8076 kArrayIndexLengthBits> {}; // NOLINT
8078 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8079 // could use a mask to test if the length of string is less than or equal to
8080 // kMaxCachedArrayIndexLength.
8081 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8083 static const unsigned int kContainsCachedArrayIndexMask =
8084 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8085 << ArrayIndexLengthBits::kShift) |
8086 kIsNotArrayIndexMask;
8088 // Value of empty hash field indicating that the hash is not computed.
8089 static const int kEmptyHashField =
8090 kIsNotArrayIndexMask | kHashNotComputedMask;
8093 static inline bool IsHashFieldComputed(uint32_t field);
8096 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8101 class Symbol: public Name {
8103 // [name]: The print name of a symbol, or undefined if none.
8104 DECL_ACCESSORS(name, Object)
8106 DECL_ACCESSORS(flags, Smi)
8108 // [is_private]: Whether this is a private symbol. Private symbols can only
8109 // be used to designate own properties of objects.
8110 DECL_BOOLEAN_ACCESSORS(is_private)
8112 DECLARE_CAST(Symbol)
8114 // Dispatched behavior.
8115 DECLARE_PRINTER(Symbol)
8116 DECLARE_VERIFIER(Symbol)
8118 // Layout description.
8119 static const int kNameOffset = Name::kSize;
8120 static const int kFlagsOffset = kNameOffset + kPointerSize;
8121 static const int kSize = kFlagsOffset + kPointerSize;
8123 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8125 void SymbolShortPrint(std::ostream& os);
8128 static const int kPrivateBit = 0;
8130 const char* PrivateSymbolToName() const;
8133 friend class Name; // For PrivateSymbolToName.
8136 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8142 // The String abstract class captures JavaScript string values:
8145 // 4.3.16 String Value
8146 // A string value is a member of the type String and is a finite
8147 // ordered sequence of zero or more 16-bit unsigned integer values.
8149 // All string values have a length field.
8150 class String: public Name {
8152 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8154 // Array index strings this short can keep their index in the hash field.
8155 static const int kMaxCachedArrayIndexLength = 7;
8157 // For strings which are array indexes the hash value has the string length
8158 // mixed into the hash, mainly to avoid a hash value of zero which would be
8159 // the case for the string '0'. 24 bits are used for the array index value.
8160 static const int kArrayIndexValueBits = 24;
8161 static const int kArrayIndexLengthBits =
8162 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8164 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8166 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8167 kArrayIndexValueBits> {}; // NOLINT
8168 class ArrayIndexLengthBits : public BitField<unsigned int,
8169 kNofHashBitFields + kArrayIndexValueBits,
8170 kArrayIndexLengthBits> {}; // NOLINT
8172 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8173 // could use a mask to test if the length of string is less than or equal to
8174 // kMaxCachedArrayIndexLength.
8175 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8177 static const unsigned int kContainsCachedArrayIndexMask =
8178 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8179 << ArrayIndexLengthBits::kShift) |
8180 kIsNotArrayIndexMask;
8182 class SubStringRange {
8184 explicit inline SubStringRange(String* string, int first = 0,
8187 inline iterator begin();
8188 inline iterator end();
8196 // Representation of the flat content of a String.
8197 // A non-flat string doesn't have flat content.
8198 // A flat string has content that's encoded as a sequence of either
8199 // one-byte chars or two-byte UC16.
8200 // Returned by String::GetFlatContent().
8203 // Returns true if the string is flat and this structure contains content.
8204 bool IsFlat() { return state_ != NON_FLAT; }
8205 // Returns true if the structure contains one-byte content.
8206 bool IsOneByte() { return state_ == ONE_BYTE; }
8207 // Returns true if the structure contains two-byte content.
8208 bool IsTwoByte() { return state_ == TWO_BYTE; }
8210 // Return the one byte content of the string. Only use if IsOneByte()
8212 Vector<const uint8_t> ToOneByteVector() {
8213 DCHECK_EQ(ONE_BYTE, state_);
8214 return Vector<const uint8_t>(onebyte_start, length_);
8216 // Return the two-byte content of the string. Only use if IsTwoByte()
8218 Vector<const uc16> ToUC16Vector() {
8219 DCHECK_EQ(TWO_BYTE, state_);
8220 return Vector<const uc16>(twobyte_start, length_);
8224 DCHECK(i < length_);
8225 DCHECK(state_ != NON_FLAT);
8226 if (state_ == ONE_BYTE) return onebyte_start[i];
8227 return twobyte_start[i];
8230 bool UsesSameString(const FlatContent& other) const {
8231 return onebyte_start == other.onebyte_start;
8235 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8237 // Constructors only used by String::GetFlatContent().
8238 explicit FlatContent(const uint8_t* start, int length)
8239 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8240 explicit FlatContent(const uc16* start, int length)
8241 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8242 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8245 const uint8_t* onebyte_start;
8246 const uc16* twobyte_start;
8251 friend class String;
8252 friend class IterableSubString;
8255 template <typename Char>
8256 INLINE(Vector<const Char> GetCharVector());
8258 // Get and set the length of the string.
8259 inline int length() const;
8260 inline void set_length(int value);
8262 // Get and set the length of the string using acquire loads and release
8264 inline int synchronized_length() const;
8265 inline void synchronized_set_length(int value);
8267 // Returns whether this string has only one-byte chars, i.e. all of them can
8268 // be one-byte encoded. This might be the case even if the string is
8269 // two-byte. Such strings may appear when the embedder prefers
8270 // two-byte external representations even for one-byte data.
8271 inline bool IsOneByteRepresentation() const;
8272 inline bool IsTwoByteRepresentation() const;
8274 // Cons and slices have an encoding flag that may not represent the actual
8275 // encoding of the underlying string. This is taken into account here.
8276 // Requires: this->IsFlat()
8277 inline bool IsOneByteRepresentationUnderneath();
8278 inline bool IsTwoByteRepresentationUnderneath();
8280 // NOTE: this should be considered only a hint. False negatives are
8282 inline bool HasOnlyOneByteChars();
8284 // Get and set individual two byte chars in the string.
8285 inline void Set(int index, uint16_t value);
8286 // Get individual two byte char in the string. Repeated calls
8287 // to this method are not efficient unless the string is flat.
8288 INLINE(uint16_t Get(int index));
8290 // Flattens the string. Checks first inline to see if it is
8291 // necessary. Does nothing if the string is not a cons string.
8292 // Flattening allocates a sequential string with the same data as
8293 // the given string and mutates the cons string to a degenerate
8294 // form, where the first component is the new sequential string and
8295 // the second component is the empty string. If allocation fails,
8296 // this function returns a failure. If flattening succeeds, this
8297 // function returns the sequential string that is now the first
8298 // component of the cons string.
8300 // Degenerate cons strings are handled specially by the garbage
8301 // collector (see IsShortcutCandidate).
8303 static inline Handle<String> Flatten(Handle<String> string,
8304 PretenureFlag pretenure = NOT_TENURED);
8306 // Tries to return the content of a flat string as a structure holding either
8307 // a flat vector of char or of uc16.
8308 // If the string isn't flat, and therefore doesn't have flat content, the
8309 // returned structure will report so, and can't provide a vector of either
8311 FlatContent GetFlatContent();
8313 // Returns the parent of a sliced string or first part of a flat cons string.
8314 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8315 inline String* GetUnderlying();
8317 // String equality operations.
8318 inline bool Equals(String* other);
8319 inline static bool Equals(Handle<String> one, Handle<String> two);
8320 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8321 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8322 bool IsTwoByteEqualTo(Vector<const uc16> str);
8324 // Return a UTF8 representation of the string. The string is null
8325 // terminated but may optionally contain nulls. Length is returned
8326 // in length_output if length_output is not a null pointer The string
8327 // should be nearly flat, otherwise the performance of this method may
8328 // be very slow (quadratic in the length). Setting robustness_flag to
8329 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8330 // handles unexpected data without causing assert failures and it does not
8331 // do any heap allocations. This is useful when printing stack traces.
8332 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8333 RobustnessFlag robustness_flag,
8334 int offset, int length,
8335 int* length_output = 0);
8336 base::SmartArrayPointer<char> ToCString(
8337 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8338 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8339 int* length_output = 0);
8341 // Return a 16 bit Unicode representation of the string.
8342 // The string should be nearly flat, otherwise the performance of
8343 // of this method may be very bad. Setting robustness_flag to
8344 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8345 // handles unexpected data without causing assert failures and it does not
8346 // do any heap allocations. This is useful when printing stack traces.
8347 base::SmartArrayPointer<uc16> ToWideCString(
8348 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8350 bool ComputeArrayIndex(uint32_t* index);
8353 bool MakeExternal(v8::String::ExternalStringResource* resource);
8354 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8357 inline bool AsArrayIndex(uint32_t* index);
8359 DECLARE_CAST(String)
8361 void PrintOn(FILE* out);
8363 // For use during stack traces. Performs rudimentary sanity check.
8366 // Dispatched behavior.
8367 void StringShortPrint(StringStream* accumulator);
8368 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8369 #if defined(DEBUG) || defined(OBJECT_PRINT)
8370 char* ToAsciiArray();
8372 DECLARE_PRINTER(String)
8373 DECLARE_VERIFIER(String)
8375 inline bool IsFlat();
8377 // Layout description.
8378 static const int kLengthOffset = Name::kSize;
8379 static const int kSize = kLengthOffset + kPointerSize;
8381 // Maximum number of characters to consider when trying to convert a string
8382 // value into an array index.
8383 static const int kMaxArrayIndexSize = 10;
8384 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8387 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8388 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8389 static const int kMaxUtf16CodeUnit = 0xffff;
8390 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8392 // Value of hash field containing computed hash equal to zero.
8393 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8395 // Maximal string length.
8396 static const int kMaxLength = (1 << 28) - 16;
8398 // Max length for computing hash. For strings longer than this limit the
8399 // string length is used as the hash value.
8400 static const int kMaxHashCalcLength = 16383;
8402 // Limit for truncation in short printing.
8403 static const int kMaxShortPrintLength = 1024;
8405 // Support for regular expressions.
8406 const uc16* GetTwoByteData(unsigned start);
8408 // Helper function for flattening strings.
8409 template <typename sinkchar>
8410 static void WriteToFlat(String* source,
8415 // The return value may point to the first aligned word containing the first
8416 // non-one-byte character, rather than directly to the non-one-byte character.
8417 // If the return value is >= the passed length, the entire string was
8419 static inline int NonAsciiStart(const char* chars, int length) {
8420 const char* start = chars;
8421 const char* limit = chars + length;
8423 if (length >= kIntptrSize) {
8424 // Check unaligned bytes.
8425 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8426 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8427 return static_cast<int>(chars - start);
8431 // Check aligned words.
8432 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8433 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8434 while (chars + sizeof(uintptr_t) <= limit) {
8435 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8436 return static_cast<int>(chars - start);
8438 chars += sizeof(uintptr_t);
8441 // Check remaining unaligned bytes.
8442 while (chars < limit) {
8443 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8444 return static_cast<int>(chars - start);
8449 return static_cast<int>(chars - start);
8452 static inline bool IsAscii(const char* chars, int length) {
8453 return NonAsciiStart(chars, length) >= length;
8456 static inline bool IsAscii(const uint8_t* chars, int length) {
8458 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8461 static inline int NonOneByteStart(const uc16* chars, int length) {
8462 const uc16* limit = chars + length;
8463 const uc16* start = chars;
8464 while (chars < limit) {
8465 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8468 return static_cast<int>(chars - start);
8471 static inline bool IsOneByte(const uc16* chars, int length) {
8472 return NonOneByteStart(chars, length) >= length;
8475 template<class Visitor>
8476 static inline ConsString* VisitFlat(Visitor* visitor,
8480 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8481 bool include_ending_line);
8483 // Use the hash field to forward to the canonical internalized string
8484 // when deserializing an internalized string.
8485 inline void SetForwardedInternalizedString(String* string);
8486 inline String* GetForwardedInternalizedString();
8490 friend class StringTableInsertionKey;
8492 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8493 PretenureFlag tenure);
8495 // Slow case of String::Equals. This implementation works on any strings
8496 // but it is most efficient on strings that are almost flat.
8497 bool SlowEquals(String* other);
8499 static bool SlowEquals(Handle<String> one, Handle<String> two);
8501 // Slow case of AsArrayIndex.
8502 bool SlowAsArrayIndex(uint32_t* index);
8504 // Compute and set the hash code.
8505 uint32_t ComputeAndSetHash();
8507 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8511 // The SeqString abstract class captures sequential string values.
8512 class SeqString: public String {
8514 DECLARE_CAST(SeqString)
8516 // Layout description.
8517 static const int kHeaderSize = String::kSize;
8519 // Truncate the string in-place if possible and return the result.
8520 // In case of new_length == 0, the empty string is returned without
8521 // truncating the original string.
8522 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8525 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8529 // The OneByteString class captures sequential one-byte string objects.
8530 // Each character in the OneByteString is an one-byte character.
8531 class SeqOneByteString: public SeqString {
8533 static const bool kHasOneByteEncoding = true;
8535 // Dispatched behavior.
8536 inline uint16_t SeqOneByteStringGet(int index);
8537 inline void SeqOneByteStringSet(int index, uint16_t value);
8539 // Get the address of the characters in this string.
8540 inline Address GetCharsAddress();
8542 inline uint8_t* GetChars();
8544 DECLARE_CAST(SeqOneByteString)
8546 // Garbage collection support. This method is called by the
8547 // garbage collector to compute the actual size of an OneByteString
8549 inline int SeqOneByteStringSize(InstanceType instance_type);
8551 // Computes the size for an OneByteString instance of a given length.
8552 static int SizeFor(int length) {
8553 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8556 // Maximal memory usage for a single sequential one-byte string.
8557 static const int kMaxSize = 512 * MB - 1;
8558 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8561 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8565 // The TwoByteString class captures sequential unicode string objects.
8566 // Each character in the TwoByteString is a two-byte uint16_t.
8567 class SeqTwoByteString: public SeqString {
8569 static const bool kHasOneByteEncoding = false;
8571 // Dispatched behavior.
8572 inline uint16_t SeqTwoByteStringGet(int index);
8573 inline void SeqTwoByteStringSet(int index, uint16_t value);
8575 // Get the address of the characters in this string.
8576 inline Address GetCharsAddress();
8578 inline uc16* GetChars();
8581 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8583 DECLARE_CAST(SeqTwoByteString)
8585 // Garbage collection support. This method is called by the
8586 // garbage collector to compute the actual size of a TwoByteString
8588 inline int SeqTwoByteStringSize(InstanceType instance_type);
8590 // Computes the size for a TwoByteString instance of a given length.
8591 static int SizeFor(int length) {
8592 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8595 // Maximal memory usage for a single sequential two-byte string.
8596 static const int kMaxSize = 512 * MB - 1;
8597 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8598 String::kMaxLength);
8601 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8605 // The ConsString class describes string values built by using the
8606 // addition operator on strings. A ConsString is a pair where the
8607 // first and second components are pointers to other string values.
8608 // One or both components of a ConsString can be pointers to other
8609 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8610 // are non-ConsString string values. The string value represented by
8611 // a ConsString can be obtained by concatenating the leaf string
8612 // values in a left-to-right depth-first traversal of the tree.
8613 class ConsString: public String {
8615 // First string of the cons cell.
8616 inline String* first();
8617 // Doesn't check that the result is a string, even in debug mode. This is
8618 // useful during GC where the mark bits confuse the checks.
8619 inline Object* unchecked_first();
8620 inline void set_first(String* first,
8621 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8623 // Second string of the cons cell.
8624 inline String* second();
8625 // Doesn't check that the result is a string, even in debug mode. This is
8626 // useful during GC where the mark bits confuse the checks.
8627 inline Object* unchecked_second();
8628 inline void set_second(String* second,
8629 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8631 // Dispatched behavior.
8632 uint16_t ConsStringGet(int index);
8634 DECLARE_CAST(ConsString)
8636 // Layout description.
8637 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8638 static const int kSecondOffset = kFirstOffset + kPointerSize;
8639 static const int kSize = kSecondOffset + kPointerSize;
8641 // Minimum length for a cons string.
8642 static const int kMinLength = 13;
8644 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8647 DECLARE_VERIFIER(ConsString)
8650 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8654 // The Sliced String class describes strings that are substrings of another
8655 // sequential string. The motivation is to save time and memory when creating
8656 // a substring. A Sliced String is described as a pointer to the parent,
8657 // the offset from the start of the parent string and the length. Using
8658 // a Sliced String therefore requires unpacking of the parent string and
8659 // adding the offset to the start address. A substring of a Sliced String
8660 // are not nested since the double indirection is simplified when creating
8661 // such a substring.
8662 // Currently missing features are:
8663 // - handling externalized parent strings
8664 // - external strings as parent
8665 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8666 class SlicedString: public String {
8668 inline String* parent();
8669 inline void set_parent(String* parent,
8670 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8671 inline int offset() const;
8672 inline void set_offset(int offset);
8674 // Dispatched behavior.
8675 uint16_t SlicedStringGet(int index);
8677 DECLARE_CAST(SlicedString)
8679 // Layout description.
8680 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8681 static const int kOffsetOffset = kParentOffset + kPointerSize;
8682 static const int kSize = kOffsetOffset + kPointerSize;
8684 // Minimum length for a sliced string.
8685 static const int kMinLength = 13;
8687 typedef FixedBodyDescriptor<kParentOffset,
8688 kOffsetOffset + kPointerSize, kSize>
8691 DECLARE_VERIFIER(SlicedString)
8694 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8698 // The ExternalString class describes string values that are backed by
8699 // a string resource that lies outside the V8 heap. ExternalStrings
8700 // consist of the length field common to all strings, a pointer to the
8701 // external resource. It is important to ensure (externally) that the
8702 // resource is not deallocated while the ExternalString is live in the
8705 // The API expects that all ExternalStrings are created through the
8706 // API. Therefore, ExternalStrings should not be used internally.
8707 class ExternalString: public String {
8709 DECLARE_CAST(ExternalString)
8711 // Layout description.
8712 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8713 static const int kShortSize = kResourceOffset + kPointerSize;
8714 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8715 static const int kSize = kResourceDataOffset + kPointerSize;
8717 static const int kMaxShortLength =
8718 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8720 // Return whether external string is short (data pointer is not cached).
8721 inline bool is_short();
8723 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8726 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8730 // The ExternalOneByteString class is an external string backed by an
8732 class ExternalOneByteString : public ExternalString {
8734 static const bool kHasOneByteEncoding = true;
8736 typedef v8::String::ExternalOneByteStringResource Resource;
8738 // The underlying resource.
8739 inline const Resource* resource();
8740 inline void set_resource(const Resource* buffer);
8742 // Update the pointer cache to the external character array.
8743 // The cached pointer is always valid, as the external character array does =
8744 // not move during lifetime. Deserialization is the only exception, after
8745 // which the pointer cache has to be refreshed.
8746 inline void update_data_cache();
8748 inline const uint8_t* GetChars();
8750 // Dispatched behavior.
8751 inline uint16_t ExternalOneByteStringGet(int index);
8753 DECLARE_CAST(ExternalOneByteString)
8755 // Garbage collection support.
8756 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8758 template <typename StaticVisitor>
8759 inline void ExternalOneByteStringIterateBody();
8762 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8766 // The ExternalTwoByteString class is an external string backed by a UTF-16
8768 class ExternalTwoByteString: public ExternalString {
8770 static const bool kHasOneByteEncoding = false;
8772 typedef v8::String::ExternalStringResource Resource;
8774 // The underlying string resource.
8775 inline const Resource* resource();
8776 inline void set_resource(const Resource* buffer);
8778 // Update the pointer cache to the external character array.
8779 // The cached pointer is always valid, as the external character array does =
8780 // not move during lifetime. Deserialization is the only exception, after
8781 // which the pointer cache has to be refreshed.
8782 inline void update_data_cache();
8784 inline const uint16_t* GetChars();
8786 // Dispatched behavior.
8787 inline uint16_t ExternalTwoByteStringGet(int index);
8790 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8792 DECLARE_CAST(ExternalTwoByteString)
8794 // Garbage collection support.
8795 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8797 template<typename StaticVisitor>
8798 inline void ExternalTwoByteStringIterateBody();
8801 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8805 // Utility superclass for stack-allocated objects that must be updated
8806 // on gc. It provides two ways for the gc to update instances, either
8807 // iterating or updating after gc.
8808 class Relocatable BASE_EMBEDDED {
8810 explicit inline Relocatable(Isolate* isolate);
8811 inline virtual ~Relocatable();
8812 virtual void IterateInstance(ObjectVisitor* v) { }
8813 virtual void PostGarbageCollection() { }
8815 static void PostGarbageCollectionProcessing(Isolate* isolate);
8816 static int ArchiveSpacePerThread();
8817 static char* ArchiveState(Isolate* isolate, char* to);
8818 static char* RestoreState(Isolate* isolate, char* from);
8819 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8820 static void Iterate(ObjectVisitor* v, Relocatable* top);
8821 static char* Iterate(ObjectVisitor* v, char* t);
8829 // A flat string reader provides random access to the contents of a
8830 // string independent of the character width of the string. The handle
8831 // must be valid as long as the reader is being used.
8832 class FlatStringReader : public Relocatable {
8834 FlatStringReader(Isolate* isolate, Handle<String> str);
8835 FlatStringReader(Isolate* isolate, Vector<const char> input);
8836 void PostGarbageCollection();
8837 inline uc32 Get(int index);
8838 template <typename Char>
8839 inline Char Get(int index);
8840 int length() { return length_; }
8849 // This maintains an off-stack representation of the stack frames required
8850 // to traverse a ConsString, allowing an entirely iterative and restartable
8851 // traversal of the entire string
8852 class ConsStringIterator {
8854 inline ConsStringIterator() {}
8855 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8856 Reset(cons_string, offset);
8858 inline void Reset(ConsString* cons_string, int offset = 0) {
8860 // Next will always return NULL.
8861 if (cons_string == NULL) return;
8862 Initialize(cons_string, offset);
8864 // Returns NULL when complete.
8865 inline String* Next(int* offset_out) {
8867 if (depth_ == 0) return NULL;
8868 return Continue(offset_out);
8872 static const int kStackSize = 32;
8873 // Use a mask instead of doing modulo operations for stack wrapping.
8874 static const int kDepthMask = kStackSize-1;
8875 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8876 static inline int OffsetForDepth(int depth);
8878 inline void PushLeft(ConsString* string);
8879 inline void PushRight(ConsString* string);
8880 inline void AdjustMaximumDepth();
8882 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8883 void Initialize(ConsString* cons_string, int offset);
8884 String* Continue(int* offset_out);
8885 String* NextLeaf(bool* blew_stack);
8886 String* Search(int* offset_out);
8888 // Stack must always contain only frames for which right traversal
8889 // has not yet been performed.
8890 ConsString* frames_[kStackSize];
8895 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8899 class StringCharacterStream {
8901 inline StringCharacterStream(String* string,
8903 inline uint16_t GetNext();
8904 inline bool HasMore();
8905 inline void Reset(String* string, int offset = 0);
8906 inline void VisitOneByteString(const uint8_t* chars, int length);
8907 inline void VisitTwoByteString(const uint16_t* chars, int length);
8910 ConsStringIterator iter_;
8913 const uint8_t* buffer8_;
8914 const uint16_t* buffer16_;
8916 const uint8_t* end_;
8917 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
8921 template <typename T>
8922 class VectorIterator {
8924 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
8925 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
8926 T GetNext() { return data_[index_++]; }
8927 bool has_more() { return index_ < data_.length(); }
8929 Vector<const T> data_;
8934 // The Oddball describes objects null, undefined, true, and false.
8935 class Oddball: public HeapObject {
8937 // [to_string]: Cached to_string computed at startup.
8938 DECL_ACCESSORS(to_string, String)
8940 // [to_number]: Cached to_number computed at startup.
8941 DECL_ACCESSORS(to_number, Object)
8943 // [typeof]: Cached type_of computed at startup.
8944 DECL_ACCESSORS(type_of, String)
8946 inline byte kind() const;
8947 inline void set_kind(byte kind);
8949 DECLARE_CAST(Oddball)
8951 // Dispatched behavior.
8952 DECLARE_VERIFIER(Oddball)
8954 // Initialize the fields.
8955 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
8956 const char* to_string, Handle<Object> to_number,
8957 const char* type_of, byte kind);
8959 // Layout description.
8960 static const int kToStringOffset = HeapObject::kHeaderSize;
8961 static const int kToNumberOffset = kToStringOffset + kPointerSize;
8962 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
8963 static const int kKindOffset = kTypeOfOffset + kPointerSize;
8964 static const int kSize = kKindOffset + kPointerSize;
8966 static const byte kFalse = 0;
8967 static const byte kTrue = 1;
8968 static const byte kNotBooleanMask = ~1;
8969 static const byte kTheHole = 2;
8970 static const byte kNull = 3;
8971 static const byte kArgumentMarker = 4;
8972 static const byte kUndefined = 5;
8973 static const byte kUninitialized = 6;
8974 static const byte kOther = 7;
8975 static const byte kException = 8;
8977 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
8978 kSize> BodyDescriptor;
8980 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
8981 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
8982 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
8985 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
8989 class Cell: public HeapObject {
8991 // [value]: value of the cell.
8992 DECL_ACCESSORS(value, Object)
8996 static inline Cell* FromValueAddress(Address value) {
8997 Object* result = FromAddress(value - kValueOffset);
8998 return static_cast<Cell*>(result);
9001 inline Address ValueAddress() {
9002 return address() + kValueOffset;
9005 // Dispatched behavior.
9006 DECLARE_PRINTER(Cell)
9007 DECLARE_VERIFIER(Cell)
9009 // Layout description.
9010 static const int kValueOffset = HeapObject::kHeaderSize;
9011 static const int kSize = kValueOffset + kPointerSize;
9013 typedef FixedBodyDescriptor<kValueOffset,
9014 kValueOffset + kPointerSize,
9015 kSize> BodyDescriptor;
9018 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9022 class PropertyCell : public HeapObject {
9024 // [property_details]: details of the global property.
9025 DECL_ACCESSORS(property_details_raw, Object)
9026 // [value]: value of the global property.
9027 DECL_ACCESSORS(value, Object)
9028 // [dependent_code]: dependent code that depends on the type of the global
9030 DECL_ACCESSORS(dependent_code, DependentCode)
9032 inline PropertyDetails property_details();
9033 inline void set_property_details(PropertyDetails details);
9035 PropertyCellConstantType GetConstantType();
9037 // Computes the new type of the cell's contents for the given value, but
9038 // without actually modifying the details.
9039 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9040 Handle<Object> value,
9041 PropertyDetails details);
9042 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9043 Handle<Object> value, PropertyDetails details);
9045 static Handle<PropertyCell> InvalidateEntry(
9046 Handle<GlobalDictionary> dictionary, int entry);
9048 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9049 Handle<Object> new_value);
9051 DECLARE_CAST(PropertyCell)
9053 // Dispatched behavior.
9054 DECLARE_PRINTER(PropertyCell)
9055 DECLARE_VERIFIER(PropertyCell)
9057 // Layout description.
9058 static const int kDetailsOffset = HeapObject::kHeaderSize;
9059 static const int kValueOffset = kDetailsOffset + kPointerSize;
9060 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9061 static const int kSize = kDependentCodeOffset + kPointerSize;
9063 static const int kPointerFieldsBeginOffset = kValueOffset;
9064 static const int kPointerFieldsEndOffset = kSize;
9066 typedef FixedBodyDescriptor<kValueOffset,
9068 kSize> BodyDescriptor;
9071 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9075 class WeakCell : public HeapObject {
9077 inline Object* value() const;
9079 // This should not be called by anyone except GC.
9080 inline void clear();
9082 // This should not be called by anyone except allocator.
9083 inline void initialize(HeapObject* value);
9085 inline bool cleared() const;
9087 DECL_ACCESSORS(next, Object)
9089 inline void clear_next(Heap* heap);
9091 inline bool next_cleared();
9093 DECLARE_CAST(WeakCell)
9095 DECLARE_PRINTER(WeakCell)
9096 DECLARE_VERIFIER(WeakCell)
9098 // Layout description.
9099 static const int kValueOffset = HeapObject::kHeaderSize;
9100 static const int kNextOffset = kValueOffset + kPointerSize;
9101 static const int kSize = kNextOffset + kPointerSize;
9103 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9106 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9110 // The JSProxy describes EcmaScript Harmony proxies
9111 class JSProxy: public JSReceiver {
9113 // [handler]: The handler property.
9114 DECL_ACCESSORS(handler, Object)
9116 // [hash]: The hash code property (undefined if not initialized yet).
9117 DECL_ACCESSORS(hash, Object)
9119 DECLARE_CAST(JSProxy)
9121 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9122 Handle<JSProxy> proxy,
9123 Handle<Object> receiver,
9126 // If the handler defines an accessor property with a setter, invoke it.
9127 // If it defines an accessor property without a setter, or a data property
9128 // that is read-only, throw. In all these cases set '*done' to true,
9129 // otherwise set it to false.
9131 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9132 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9133 Handle<Object> value, LanguageMode language_mode, bool* done);
9135 MUST_USE_RESULT static Maybe<PropertyAttributes>
9136 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9137 Handle<Object> receiver,
9139 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9140 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9141 Handle<Object> value, LanguageMode language_mode);
9143 // Turn the proxy into an (empty) JSObject.
9144 static void Fix(Handle<JSProxy> proxy);
9146 // Initializes the body after the handler slot.
9147 inline void InitializeBody(int object_size, Object* value);
9149 // Invoke a trap by name. If the trap does not exist on this's handler,
9150 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9151 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9152 Handle<JSProxy> proxy,
9154 Handle<Object> derived_trap,
9156 Handle<Object> args[]);
9158 // Dispatched behavior.
9159 DECLARE_PRINTER(JSProxy)
9160 DECLARE_VERIFIER(JSProxy)
9162 // Layout description. We add padding so that a proxy has the same
9163 // size as a virgin JSObject. This is essential for becoming a JSObject
9165 static const int kHandlerOffset = HeapObject::kHeaderSize;
9166 static const int kHashOffset = kHandlerOffset + kPointerSize;
9167 static const int kPaddingOffset = kHashOffset + kPointerSize;
9168 static const int kSize = JSObject::kHeaderSize;
9169 static const int kHeaderSize = kPaddingOffset;
9170 static const int kPaddingSize = kSize - kPaddingOffset;
9172 STATIC_ASSERT(kPaddingSize >= 0);
9174 typedef FixedBodyDescriptor<kHandlerOffset,
9176 kSize> BodyDescriptor;
9179 friend class JSReceiver;
9181 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9182 Handle<JSProxy> proxy, Handle<Name> name);
9184 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9185 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9187 MUST_USE_RESULT Object* GetIdentityHash();
9189 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9191 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9195 class JSFunctionProxy: public JSProxy {
9197 // [call_trap]: The call trap.
9198 DECL_ACCESSORS(call_trap, Object)
9200 // [construct_trap]: The construct trap.
9201 DECL_ACCESSORS(construct_trap, Object)
9203 DECLARE_CAST(JSFunctionProxy)
9205 // Dispatched behavior.
9206 DECLARE_PRINTER(JSFunctionProxy)
9207 DECLARE_VERIFIER(JSFunctionProxy)
9209 // Layout description.
9210 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9211 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9212 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9213 static const int kSize = JSFunction::kSize;
9214 static const int kPaddingSize = kSize - kPaddingOffset;
9216 STATIC_ASSERT(kPaddingSize >= 0);
9218 typedef FixedBodyDescriptor<kHandlerOffset,
9219 kConstructTrapOffset + kPointerSize,
9220 kSize> BodyDescriptor;
9223 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9227 class JSCollection : public JSObject {
9229 // [table]: the backing hash table
9230 DECL_ACCESSORS(table, Object)
9232 static const int kTableOffset = JSObject::kHeaderSize;
9233 static const int kSize = kTableOffset + kPointerSize;
9236 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9240 // The JSSet describes EcmaScript Harmony sets
9241 class JSSet : public JSCollection {
9245 // Dispatched behavior.
9246 DECLARE_PRINTER(JSSet)
9247 DECLARE_VERIFIER(JSSet)
9250 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9254 // The JSMap describes EcmaScript Harmony maps
9255 class JSMap : public JSCollection {
9259 // Dispatched behavior.
9260 DECLARE_PRINTER(JSMap)
9261 DECLARE_VERIFIER(JSMap)
9264 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9268 // OrderedHashTableIterator is an iterator that iterates over the keys and
9269 // values of an OrderedHashTable.
9271 // The iterator has a reference to the underlying OrderedHashTable data,
9272 // [table], as well as the current [index] the iterator is at.
9274 // When the OrderedHashTable is rehashed it adds a reference from the old table
9275 // to the new table as well as storing enough data about the changes so that the
9276 // iterator [index] can be adjusted accordingly.
9278 // When the [Next] result from the iterator is requested, the iterator checks if
9279 // there is a newer table that it needs to transition to.
9280 template<class Derived, class TableType>
9281 class OrderedHashTableIterator: public JSObject {
9283 // [table]: the backing hash table mapping keys to values.
9284 DECL_ACCESSORS(table, Object)
9286 // [index]: The index into the data table.
9287 DECL_ACCESSORS(index, Object)
9289 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9290 DECL_ACCESSORS(kind, Object)
9293 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9296 static const int kTableOffset = JSObject::kHeaderSize;
9297 static const int kIndexOffset = kTableOffset + kPointerSize;
9298 static const int kKindOffset = kIndexOffset + kPointerSize;
9299 static const int kSize = kKindOffset + kPointerSize;
9307 // Whether the iterator has more elements. This needs to be called before
9308 // calling |CurrentKey| and/or |CurrentValue|.
9311 // Move the index forward one.
9313 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9316 // Populates the array with the next key and value and then moves the iterator
9318 // This returns the |kind| or 0 if the iterator is already at the end.
9319 Smi* Next(JSArray* value_array);
9321 // Returns the current key of the iterator. This should only be called when
9322 // |HasMore| returns true.
9323 inline Object* CurrentKey();
9326 // Transitions the iterator to the non obsolete backing store. This is a NOP
9327 // if the [table] is not obsolete.
9330 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9334 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9337 // Dispatched behavior.
9338 DECLARE_PRINTER(JSSetIterator)
9339 DECLARE_VERIFIER(JSSetIterator)
9341 DECLARE_CAST(JSSetIterator)
9343 // Called by |Next| to populate the array. This allows the subclasses to
9344 // populate the array differently.
9345 inline void PopulateValueArray(FixedArray* array);
9348 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9352 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9355 // Dispatched behavior.
9356 DECLARE_PRINTER(JSMapIterator)
9357 DECLARE_VERIFIER(JSMapIterator)
9359 DECLARE_CAST(JSMapIterator)
9361 // Called by |Next| to populate the array. This allows the subclasses to
9362 // populate the array differently.
9363 inline void PopulateValueArray(FixedArray* array);
9366 // Returns the current value of the iterator. This should only be called when
9367 // |HasMore| returns true.
9368 inline Object* CurrentValue();
9370 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9374 // Base class for both JSWeakMap and JSWeakSet
9375 class JSWeakCollection: public JSObject {
9377 // [table]: the backing hash table mapping keys to values.
9378 DECL_ACCESSORS(table, Object)
9380 // [next]: linked list of encountered weak maps during GC.
9381 DECL_ACCESSORS(next, Object)
9383 static const int kTableOffset = JSObject::kHeaderSize;
9384 static const int kNextOffset = kTableOffset + kPointerSize;
9385 static const int kSize = kNextOffset + kPointerSize;
9388 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9392 // The JSWeakMap describes EcmaScript Harmony weak maps
9393 class JSWeakMap: public JSWeakCollection {
9395 DECLARE_CAST(JSWeakMap)
9397 // Dispatched behavior.
9398 DECLARE_PRINTER(JSWeakMap)
9399 DECLARE_VERIFIER(JSWeakMap)
9402 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9406 // The JSWeakSet describes EcmaScript Harmony weak sets
9407 class JSWeakSet: public JSWeakCollection {
9409 DECLARE_CAST(JSWeakSet)
9411 // Dispatched behavior.
9412 DECLARE_PRINTER(JSWeakSet)
9413 DECLARE_VERIFIER(JSWeakSet)
9416 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9420 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9421 enum class SharedFlag { kNotShared, kShared };
9424 class JSArrayBuffer: public JSObject {
9426 // [backing_store]: backing memory for this array
9427 DECL_ACCESSORS(backing_store, void)
9429 // [byte_length]: length in bytes
9430 DECL_ACCESSORS(byte_length, Object)
9432 inline uint32_t bit_field() const;
9433 inline void set_bit_field(uint32_t bits);
9435 inline bool is_external();
9436 inline void set_is_external(bool value);
9438 inline bool is_neuterable();
9439 inline void set_is_neuterable(bool value);
9441 inline bool was_neutered();
9442 inline void set_was_neutered(bool value);
9444 inline bool is_shared();
9445 inline void set_is_shared(bool value);
9447 DECLARE_CAST(JSArrayBuffer)
9451 // Dispatched behavior.
9452 DECLARE_PRINTER(JSArrayBuffer)
9453 DECLARE_VERIFIER(JSArrayBuffer)
9455 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9456 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9457 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9458 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9459 static const int kBitFieldOffset = kBitFieldSlot;
9461 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9463 static const int kSize = kBitFieldSlot + kPointerSize;
9465 static const int kSizeWithInternalFields =
9466 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9468 class IsExternal : public BitField<bool, 1, 1> {};
9469 class IsNeuterable : public BitField<bool, 2, 1> {};
9470 class WasNeutered : public BitField<bool, 3, 1> {};
9471 class IsShared : public BitField<bool, 4, 1> {};
9474 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9478 class JSArrayBufferView: public JSObject {
9480 // [buffer]: ArrayBuffer that this typed array views.
9481 DECL_ACCESSORS(buffer, Object)
9483 // [byte_offset]: offset of typed array in bytes.
9484 DECL_ACCESSORS(byte_offset, Object)
9486 // [byte_length]: length of typed array in bytes.
9487 DECL_ACCESSORS(byte_length, Object)
9489 DECLARE_CAST(JSArrayBufferView)
9491 DECLARE_VERIFIER(JSArrayBufferView)
9493 inline bool WasNeutered() const;
9495 static const int kBufferOffset = JSObject::kHeaderSize;
9496 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9497 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9498 static const int kViewSize = kByteLengthOffset + kPointerSize;
9502 DECL_ACCESSORS(raw_byte_offset, Object)
9503 DECL_ACCESSORS(raw_byte_length, Object)
9506 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9510 class JSTypedArray: public JSArrayBufferView {
9512 // [length]: length of typed array in elements.
9513 DECL_ACCESSORS(length, Object)
9514 inline uint32_t length_value() const;
9516 DECLARE_CAST(JSTypedArray)
9518 ExternalArrayType type();
9519 size_t element_size();
9521 Handle<JSArrayBuffer> GetBuffer();
9523 // Dispatched behavior.
9524 DECLARE_PRINTER(JSTypedArray)
9525 DECLARE_VERIFIER(JSTypedArray)
9527 static const int kLengthOffset = kViewSize + kPointerSize;
9528 static const int kSize = kLengthOffset + kPointerSize;
9530 static const int kSizeWithInternalFields =
9531 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9534 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9535 Handle<JSTypedArray> typed_array);
9537 DECL_ACCESSORS(raw_length, Object)
9540 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9544 class JSDataView: public JSArrayBufferView {
9546 DECLARE_CAST(JSDataView)
9548 // Dispatched behavior.
9549 DECLARE_PRINTER(JSDataView)
9550 DECLARE_VERIFIER(JSDataView)
9552 static const int kSize = kViewSize;
9554 static const int kSizeWithInternalFields =
9555 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9558 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9562 // Foreign describes objects pointing from JavaScript to C structures.
9563 class Foreign: public HeapObject {
9565 // [address]: field containing the address.
9566 inline Address foreign_address();
9567 inline void set_foreign_address(Address value);
9569 DECLARE_CAST(Foreign)
9571 // Dispatched behavior.
9572 inline void ForeignIterateBody(ObjectVisitor* v);
9574 template<typename StaticVisitor>
9575 inline void ForeignIterateBody();
9577 // Dispatched behavior.
9578 DECLARE_PRINTER(Foreign)
9579 DECLARE_VERIFIER(Foreign)
9581 // Layout description.
9583 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9584 static const int kSize = kForeignAddressOffset + kPointerSize;
9586 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9589 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9593 // The JSArray describes JavaScript Arrays
9594 // Such an array can be in one of two modes:
9595 // - fast, backing storage is a FixedArray and length <= elements.length();
9596 // Please note: push and pop can be used to grow and shrink the array.
9597 // - slow, backing storage is a HashTable with numbers as keys.
9598 class JSArray: public JSObject {
9600 // [length]: The length property.
9601 DECL_ACCESSORS(length, Object)
9603 // Overload the length setter to skip write barrier when the length
9604 // is set to a smi. This matches the set function on FixedArray.
9605 inline void set_length(Smi* length);
9607 static bool HasReadOnlyLength(Handle<JSArray> array);
9608 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9609 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9611 // Initialize the array with the given capacity. The function may
9612 // fail due to out-of-memory situations, but only if the requested
9613 // capacity is non-zero.
9614 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9616 // If the JSArray has fast elements, and new_length would result in
9617 // normalization, returns true.
9618 bool SetLengthWouldNormalize(uint32_t new_length);
9619 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9621 // Initializes the array to a certain length.
9622 inline bool AllowsSetLength();
9624 static void SetLength(Handle<JSArray> array, uint32_t length);
9625 // Same as above but will also queue splice records if |array| is observed.
9626 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9629 // Set the content of the array to the content of storage.
9630 static inline void SetContent(Handle<JSArray> array,
9631 Handle<FixedArrayBase> storage);
9633 DECLARE_CAST(JSArray)
9635 // Dispatched behavior.
9636 DECLARE_PRINTER(JSArray)
9637 DECLARE_VERIFIER(JSArray)
9639 // Number of element slots to pre-allocate for an empty array.
9640 static const int kPreallocatedArrayElements = 4;
9642 // Layout description.
9643 static const int kLengthOffset = JSObject::kHeaderSize;
9644 static const int kSize = kLengthOffset + kPointerSize;
9647 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9651 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9652 Handle<Map> initial_map);
9655 // JSRegExpResult is just a JSArray with a specific initial map.
9656 // This initial map adds in-object properties for "index" and "input"
9657 // properties, as assigned by RegExp.prototype.exec, which allows
9658 // faster creation of RegExp exec results.
9659 // This class just holds constants used when creating the result.
9660 // After creation the result must be treated as a JSArray in all regards.
9661 class JSRegExpResult: public JSArray {
9663 // Offsets of object fields.
9664 static const int kIndexOffset = JSArray::kSize;
9665 static const int kInputOffset = kIndexOffset + kPointerSize;
9666 static const int kSize = kInputOffset + kPointerSize;
9667 // Indices of in-object properties.
9668 static const int kIndexIndex = 0;
9669 static const int kInputIndex = 1;
9671 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9675 class AccessorInfo: public Struct {
9677 DECL_ACCESSORS(name, Object)
9678 DECL_ACCESSORS(flag, Smi)
9679 DECL_ACCESSORS(expected_receiver_type, Object)
9681 inline bool all_can_read();
9682 inline void set_all_can_read(bool value);
9684 inline bool all_can_write();
9685 inline void set_all_can_write(bool value);
9687 inline bool is_special_data_property();
9688 inline void set_is_special_data_property(bool value);
9690 inline PropertyAttributes property_attributes();
9691 inline void set_property_attributes(PropertyAttributes attributes);
9693 // Checks whether the given receiver is compatible with this accessor.
9694 static bool IsCompatibleReceiverMap(Isolate* isolate,
9695 Handle<AccessorInfo> info,
9697 inline bool IsCompatibleReceiver(Object* receiver);
9699 DECLARE_CAST(AccessorInfo)
9701 // Dispatched behavior.
9702 DECLARE_VERIFIER(AccessorInfo)
9704 // Append all descriptors to the array that are not already there.
9705 // Return number added.
9706 static int AppendUnique(Handle<Object> descriptors,
9707 Handle<FixedArray> array,
9708 int valid_descriptors);
9710 static const int kNameOffset = HeapObject::kHeaderSize;
9711 static const int kFlagOffset = kNameOffset + kPointerSize;
9712 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9713 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9716 inline bool HasExpectedReceiverType();
9718 // Bit positions in flag.
9719 static const int kAllCanReadBit = 0;
9720 static const int kAllCanWriteBit = 1;
9721 static const int kSpecialDataProperty = 2;
9722 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9724 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9728 // An accessor must have a getter, but can have no setter.
9730 // When setting a property, V8 searches accessors in prototypes.
9731 // If an accessor was found and it does not have a setter,
9732 // the request is ignored.
9734 // If the accessor in the prototype has the READ_ONLY property attribute, then
9735 // a new value is added to the derived object when the property is set.
9736 // This shadows the accessor in the prototype.
9737 class ExecutableAccessorInfo: public AccessorInfo {
9739 DECL_ACCESSORS(getter, Object)
9740 DECL_ACCESSORS(setter, Object)
9741 DECL_ACCESSORS(data, Object)
9743 DECLARE_CAST(ExecutableAccessorInfo)
9745 // Dispatched behavior.
9746 DECLARE_PRINTER(ExecutableAccessorInfo)
9747 DECLARE_VERIFIER(ExecutableAccessorInfo)
9749 static const int kGetterOffset = AccessorInfo::kSize;
9750 static const int kSetterOffset = kGetterOffset + kPointerSize;
9751 static const int kDataOffset = kSetterOffset + kPointerSize;
9752 static const int kSize = kDataOffset + kPointerSize;
9754 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9757 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9761 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9762 // accessor can either be
9763 // * a pointer to a JavaScript function or proxy: a real accessor
9764 // * undefined: considered an accessor by the spec, too, strangely enough
9765 // * the hole: an accessor which has not been set
9766 // * a pointer to a map: a transition used to ensure map sharing
9767 class AccessorPair: public Struct {
9769 DECL_ACCESSORS(getter, Object)
9770 DECL_ACCESSORS(setter, Object)
9772 DECLARE_CAST(AccessorPair)
9774 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9776 inline Object* get(AccessorComponent component);
9777 inline void set(AccessorComponent component, Object* value);
9779 // Note: Returns undefined instead in case of a hole.
9780 Object* GetComponent(AccessorComponent component);
9782 // Set both components, skipping arguments which are a JavaScript null.
9783 inline void SetComponents(Object* getter, Object* setter);
9785 inline bool Equals(AccessorPair* pair);
9786 inline bool Equals(Object* getter_value, Object* setter_value);
9788 inline bool ContainsAccessor();
9790 // Dispatched behavior.
9791 DECLARE_PRINTER(AccessorPair)
9792 DECLARE_VERIFIER(AccessorPair)
9794 static const int kGetterOffset = HeapObject::kHeaderSize;
9795 static const int kSetterOffset = kGetterOffset + kPointerSize;
9796 static const int kSize = kSetterOffset + kPointerSize;
9799 // Strangely enough, in addition to functions and harmony proxies, the spec
9800 // requires us to consider undefined as a kind of accessor, too:
9802 // Object.defineProperty(obj, "foo", {get: undefined});
9803 // assertTrue("foo" in obj);
9804 inline bool IsJSAccessor(Object* obj);
9806 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9810 class AccessCheckInfo: public Struct {
9812 DECL_ACCESSORS(named_callback, Object)
9813 DECL_ACCESSORS(indexed_callback, Object)
9814 DECL_ACCESSORS(data, Object)
9816 DECLARE_CAST(AccessCheckInfo)
9818 // Dispatched behavior.
9819 DECLARE_PRINTER(AccessCheckInfo)
9820 DECLARE_VERIFIER(AccessCheckInfo)
9822 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9823 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9824 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9825 static const int kSize = kDataOffset + kPointerSize;
9828 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9832 class InterceptorInfo: public Struct {
9834 DECL_ACCESSORS(getter, Object)
9835 DECL_ACCESSORS(setter, Object)
9836 DECL_ACCESSORS(query, Object)
9837 DECL_ACCESSORS(deleter, Object)
9838 DECL_ACCESSORS(enumerator, Object)
9839 DECL_ACCESSORS(data, Object)
9840 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9841 DECL_BOOLEAN_ACCESSORS(all_can_read)
9842 DECL_BOOLEAN_ACCESSORS(non_masking)
9844 inline int flags() const;
9845 inline void set_flags(int flags);
9847 DECLARE_CAST(InterceptorInfo)
9849 // Dispatched behavior.
9850 DECLARE_PRINTER(InterceptorInfo)
9851 DECLARE_VERIFIER(InterceptorInfo)
9853 static const int kGetterOffset = HeapObject::kHeaderSize;
9854 static const int kSetterOffset = kGetterOffset + kPointerSize;
9855 static const int kQueryOffset = kSetterOffset + kPointerSize;
9856 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9857 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9858 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9859 static const int kFlagsOffset = kDataOffset + kPointerSize;
9860 static const int kSize = kFlagsOffset + kPointerSize;
9862 static const int kCanInterceptSymbolsBit = 0;
9863 static const int kAllCanReadBit = 1;
9864 static const int kNonMasking = 2;
9867 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9871 class CallHandlerInfo: public Struct {
9873 DECL_ACCESSORS(callback, Object)
9874 DECL_ACCESSORS(data, Object)
9876 DECLARE_CAST(CallHandlerInfo)
9878 // Dispatched behavior.
9879 DECLARE_PRINTER(CallHandlerInfo)
9880 DECLARE_VERIFIER(CallHandlerInfo)
9882 static const int kCallbackOffset = HeapObject::kHeaderSize;
9883 static const int kDataOffset = kCallbackOffset + kPointerSize;
9884 static const int kSize = kDataOffset + kPointerSize;
9887 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
9891 class TemplateInfo: public Struct {
9893 DECL_ACCESSORS(tag, Object)
9894 inline int number_of_properties() const;
9895 inline void set_number_of_properties(int value);
9896 DECL_ACCESSORS(property_list, Object)
9897 DECL_ACCESSORS(property_accessors, Object)
9899 DECLARE_VERIFIER(TemplateInfo)
9901 static const int kTagOffset = HeapObject::kHeaderSize;
9902 static const int kNumberOfProperties = kTagOffset + kPointerSize;
9903 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
9904 static const int kPropertyAccessorsOffset =
9905 kPropertyListOffset + kPointerSize;
9906 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
9909 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
9913 class FunctionTemplateInfo: public TemplateInfo {
9915 DECL_ACCESSORS(serial_number, Object)
9916 DECL_ACCESSORS(call_code, Object)
9917 DECL_ACCESSORS(prototype_template, Object)
9918 DECL_ACCESSORS(parent_template, Object)
9919 DECL_ACCESSORS(named_property_handler, Object)
9920 DECL_ACCESSORS(indexed_property_handler, Object)
9921 DECL_ACCESSORS(instance_template, Object)
9922 DECL_ACCESSORS(class_name, Object)
9923 DECL_ACCESSORS(signature, Object)
9924 DECL_ACCESSORS(instance_call_handler, Object)
9925 DECL_ACCESSORS(access_check_info, Object)
9926 DECL_ACCESSORS(flag, Smi)
9928 inline int length() const;
9929 inline void set_length(int value);
9931 // Following properties use flag bits.
9932 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
9933 DECL_BOOLEAN_ACCESSORS(undetectable)
9934 // If the bit is set, object instances created by this function
9935 // requires access check.
9936 DECL_BOOLEAN_ACCESSORS(needs_access_check)
9937 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
9938 DECL_BOOLEAN_ACCESSORS(remove_prototype)
9939 DECL_BOOLEAN_ACCESSORS(do_not_cache)
9940 DECL_BOOLEAN_ACCESSORS(instantiated)
9941 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
9943 DECLARE_CAST(FunctionTemplateInfo)
9945 // Dispatched behavior.
9946 DECLARE_PRINTER(FunctionTemplateInfo)
9947 DECLARE_VERIFIER(FunctionTemplateInfo)
9949 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
9950 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
9951 static const int kPrototypeTemplateOffset =
9952 kCallCodeOffset + kPointerSize;
9953 static const int kParentTemplateOffset =
9954 kPrototypeTemplateOffset + kPointerSize;
9955 static const int kNamedPropertyHandlerOffset =
9956 kParentTemplateOffset + kPointerSize;
9957 static const int kIndexedPropertyHandlerOffset =
9958 kNamedPropertyHandlerOffset + kPointerSize;
9959 static const int kInstanceTemplateOffset =
9960 kIndexedPropertyHandlerOffset + kPointerSize;
9961 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
9962 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
9963 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
9964 static const int kAccessCheckInfoOffset =
9965 kInstanceCallHandlerOffset + kPointerSize;
9966 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
9967 static const int kLengthOffset = kFlagOffset + kPointerSize;
9968 static const int kSize = kLengthOffset + kPointerSize;
9970 // Returns true if |object| is an instance of this function template.
9971 bool IsTemplateFor(Object* object);
9972 bool IsTemplateFor(Map* map);
9974 // Returns the holder JSObject if the function can legally be called with this
9975 // receiver. Returns Heap::null_value() if the call is illegal.
9976 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
9979 // Bit position in the flag, from least significant bit position.
9980 static const int kHiddenPrototypeBit = 0;
9981 static const int kUndetectableBit = 1;
9982 static const int kNeedsAccessCheckBit = 2;
9983 static const int kReadOnlyPrototypeBit = 3;
9984 static const int kRemovePrototypeBit = 4;
9985 static const int kDoNotCacheBit = 5;
9986 static const int kInstantiatedBit = 6;
9987 static const int kAcceptAnyReceiver = 7;
9989 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
9993 class ObjectTemplateInfo: public TemplateInfo {
9995 DECL_ACCESSORS(constructor, Object)
9996 DECL_ACCESSORS(internal_field_count, Object)
9998 DECLARE_CAST(ObjectTemplateInfo)
10000 // Dispatched behavior.
10001 DECLARE_PRINTER(ObjectTemplateInfo)
10002 DECLARE_VERIFIER(ObjectTemplateInfo)
10004 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10005 static const int kInternalFieldCountOffset =
10006 kConstructorOffset + kPointerSize;
10007 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10011 class TypeSwitchInfo: public Struct {
10013 DECL_ACCESSORS(types, Object)
10015 DECLARE_CAST(TypeSwitchInfo)
10017 // Dispatched behavior.
10018 DECLARE_PRINTER(TypeSwitchInfo)
10019 DECLARE_VERIFIER(TypeSwitchInfo)
10021 static const int kTypesOffset = Struct::kHeaderSize;
10022 static const int kSize = kTypesOffset + kPointerSize;
10026 // The DebugInfo class holds additional information for a function being
10028 class DebugInfo: public Struct {
10030 // The shared function info for the source being debugged.
10031 DECL_ACCESSORS(shared, SharedFunctionInfo)
10032 // Code object for the patched code. This code object is the code object
10033 // currently active for the function.
10034 DECL_ACCESSORS(code, Code)
10035 // Fixed array holding status information for each active break point.
10036 DECL_ACCESSORS(break_points, FixedArray)
10038 // Check if there is a break point at a code position.
10039 bool HasBreakPoint(int code_position);
10040 // Get the break point info object for a code position.
10041 Object* GetBreakPointInfo(int code_position);
10042 // Clear a break point.
10043 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10045 Handle<Object> break_point_object);
10046 // Set a break point.
10047 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10048 int source_position, int statement_position,
10049 Handle<Object> break_point_object);
10050 // Get the break point objects for a code position.
10051 Handle<Object> GetBreakPointObjects(int code_position);
10052 // Find the break point info holding this break point object.
10053 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10054 Handle<Object> break_point_object);
10055 // Get the number of break points for this function.
10056 int GetBreakPointCount();
10058 DECLARE_CAST(DebugInfo)
10060 // Dispatched behavior.
10061 DECLARE_PRINTER(DebugInfo)
10062 DECLARE_VERIFIER(DebugInfo)
10064 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10065 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10066 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10067 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10069 static const int kEstimatedNofBreakPointsInFunction = 16;
10072 static const int kNoBreakPointInfo = -1;
10074 // Lookup the index in the break_points array for a code position.
10075 int GetBreakPointInfoIndex(int code_position);
10077 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10081 // The BreakPointInfo class holds information for break points set in a
10082 // function. The DebugInfo object holds a BreakPointInfo object for each code
10083 // position with one or more break points.
10084 class BreakPointInfo: public Struct {
10086 // The position in the code for the break point.
10087 DECL_ACCESSORS(code_position, Smi)
10088 // The position in the source for the break position.
10089 DECL_ACCESSORS(source_position, Smi)
10090 // The position in the source for the last statement before this break
10092 DECL_ACCESSORS(statement_position, Smi)
10093 // List of related JavaScript break points.
10094 DECL_ACCESSORS(break_point_objects, Object)
10096 // Removes a break point.
10097 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10098 Handle<Object> break_point_object);
10099 // Set a break point.
10100 static void SetBreakPoint(Handle<BreakPointInfo> info,
10101 Handle<Object> break_point_object);
10102 // Check if break point info has this break point object.
10103 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10104 Handle<Object> break_point_object);
10105 // Get the number of break points for this code position.
10106 int GetBreakPointCount();
10108 DECLARE_CAST(BreakPointInfo)
10110 // Dispatched behavior.
10111 DECLARE_PRINTER(BreakPointInfo)
10112 DECLARE_VERIFIER(BreakPointInfo)
10114 static const int kCodePositionIndex = Struct::kHeaderSize;
10115 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10116 static const int kStatementPositionIndex =
10117 kSourcePositionIndex + kPointerSize;
10118 static const int kBreakPointObjectsIndex =
10119 kStatementPositionIndex + kPointerSize;
10120 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10123 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10127 #undef DECL_BOOLEAN_ACCESSORS
10128 #undef DECL_ACCESSORS
10129 #undef DECLARE_CAST
10130 #undef DECLARE_VERIFIER
10132 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10133 V(kStringTable, "string_table", "(Internalized strings)") \
10134 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10135 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10136 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10137 V(kInternalizedString, "internalized_string", "(Internal string)") \
10138 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10139 V(kTop, "top", "(Isolate)") \
10140 V(kRelocatable, "relocatable", "(Relocatable)") \
10141 V(kDebug, "debug", "(Debugger)") \
10142 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10143 V(kHandleScope, "handlescope", "(Handle scope)") \
10144 V(kBuiltins, "builtins", "(Builtins)") \
10145 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10146 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10147 V(kThreadManager, "threadmanager", "(Thread manager)") \
10148 V(kStrongRoots, "strong roots", "(Strong roots)") \
10149 V(kExtensions, "Extensions", "(Extensions)")
10151 class VisitorSynchronization : public AllStatic {
10153 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10155 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10158 #undef DECLARE_ENUM
10160 static const char* const kTags[kNumberOfSyncTags];
10161 static const char* const kTagNames[kNumberOfSyncTags];
10164 // Abstract base class for visiting, and optionally modifying, the
10165 // pointers contained in Objects. Used in GC and serialization/deserialization.
10166 class ObjectVisitor BASE_EMBEDDED {
10168 virtual ~ObjectVisitor() {}
10170 // Visits a contiguous arrays of pointers in the half-open range
10171 // [start, end). Any or all of the values may be modified on return.
10172 virtual void VisitPointers(Object** start, Object** end) = 0;
10174 // Handy shorthand for visiting a single pointer.
10175 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10177 // Visit weak next_code_link in Code object.
10178 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10180 // To allow lazy clearing of inline caches the visitor has
10181 // a rich interface for iterating over Code objects..
10183 // Visits a code target in the instruction stream.
10184 virtual void VisitCodeTarget(RelocInfo* rinfo);
10186 // Visits a code entry in a JS function.
10187 virtual void VisitCodeEntry(Address entry_address);
10189 // Visits a global property cell reference in the instruction stream.
10190 virtual void VisitCell(RelocInfo* rinfo);
10192 // Visits a runtime entry in the instruction stream.
10193 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10195 // Visits the resource of an one-byte or two-byte string.
10196 virtual void VisitExternalOneByteString(
10197 v8::String::ExternalOneByteStringResource** resource) {}
10198 virtual void VisitExternalTwoByteString(
10199 v8::String::ExternalStringResource** resource) {}
10201 // Visits a debug call target in the instruction stream.
10202 virtual void VisitDebugTarget(RelocInfo* rinfo);
10204 // Visits the byte sequence in a function's prologue that contains information
10205 // about the code's age.
10206 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10208 // Visit pointer embedded into a code object.
10209 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10211 // Visits an external reference embedded into a code object.
10212 virtual void VisitExternalReference(RelocInfo* rinfo);
10214 // Visits an external reference.
10215 virtual void VisitExternalReference(Address* p) {}
10217 // Visits an (encoded) internal reference.
10218 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10220 // Visits a handle that has an embedder-assigned class ID.
10221 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10223 // Intended for serialization/deserialization checking: insert, or
10224 // check for the presence of, a tag at this position in the stream.
10225 // Also used for marking up GC roots in heap snapshots.
10226 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10230 class StructBodyDescriptor : public
10231 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10233 static inline int SizeOf(Map* map, HeapObject* object);
10237 // BooleanBit is a helper class for setting and getting a bit in an
10239 class BooleanBit : public AllStatic {
10241 static inline bool get(Smi* smi, int bit_position) {
10242 return get(smi->value(), bit_position);
10245 static inline bool get(int value, int bit_position) {
10246 return (value & (1 << bit_position)) != 0;
10249 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10250 return Smi::FromInt(set(smi->value(), bit_position, v));
10253 static inline int set(int value, int bit_position, bool v) {
10255 value |= (1 << bit_position);
10257 value &= ~(1 << bit_position);
10263 } } // namespace v8::internal
10265 #endif // V8_OBJECTS_H_