1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
83 // - CompilationCacheTable
84 // - CodeCacheHashTable
90 // - TypeFeedbackVector
93 // - ScriptContextTable
100 // - SeqTwoByteString
104 // - ExternalOneByteString
105 // - ExternalTwoByteString
106 // - InternalizedString
107 // - SeqInternalizedString
108 // - SeqOneByteInternalizedString
109 // - SeqTwoByteInternalizedString
110 // - ConsInternalizedString
111 // - ExternalInternalizedString
112 // - ExternalOneByteInternalizedString
113 // - ExternalTwoByteInternalizedString
133 // - SharedFunctionInfo
137 // - ExecutableAccessorInfo
143 // - FunctionTemplateInfo
144 // - ObjectTemplateInfo
153 // Formats of Object*:
154 // Smi: [31 bit signed int] 0
155 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
160 enum KeyedAccessStoreMode {
162 STORE_TRANSITION_TO_OBJECT,
163 STORE_TRANSITION_TO_DOUBLE,
164 STORE_AND_GROW_NO_TRANSITION,
165 STORE_AND_GROW_TRANSITION_TO_OBJECT,
166 STORE_AND_GROW_TRANSITION_TO_DOUBLE,
167 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
168 STORE_NO_TRANSITION_HANDLE_COW
172 // Valid hints for the abstract operation ToPrimitive,
173 // implemented according to ES6, section 7.1.1.
174 enum class ToPrimitiveHint { kDefault, kNumber, kString };
177 // Valid hints for the abstract operation OrdinaryToPrimitive,
178 // implemented according to ES6, section 7.1.1.
179 enum class OrdinaryToPrimitiveHint { kNumber, kString };
182 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
191 enum ExternalArrayType {
192 kExternalInt8Array = 1,
195 kExternalUint16Array,
197 kExternalUint32Array,
198 kExternalFloat32Array,
199 kExternalFloat64Array,
200 kExternalUint8ClampedArray,
204 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
205 return store_mode == STORE_TRANSITION_TO_OBJECT ||
206 store_mode == STORE_TRANSITION_TO_DOUBLE ||
207 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
208 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
212 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
213 KeyedAccessStoreMode store_mode) {
214 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
217 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
218 return STORE_AND_GROW_NO_TRANSITION;
220 return STANDARD_STORE;
224 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
225 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
226 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
230 enum IcCheckType { ELEMENT, PROPERTY };
233 // SKIP_WRITE_BARRIER skips the write barrier.
234 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
235 // only performs the generational part.
236 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
237 enum WriteBarrierMode {
239 UPDATE_WEAK_WRITE_BARRIER,
244 // Indicates whether a value can be loaded as a constant.
245 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
248 // PropertyNormalizationMode is used to specify whether to keep
249 // inobject properties when normalizing properties of a JSObject.
250 enum PropertyNormalizationMode {
251 CLEAR_INOBJECT_PROPERTIES,
252 KEEP_INOBJECT_PROPERTIES
256 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
257 // will give the fastest result by tailoring the map to the prototype, but that
258 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
259 // (at least for now) when dynamically modifying the prototype chain of an
260 // object using __proto__ or Object.setPrototypeOf.
261 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
264 // Indicates whether transitions can be added to a source map or not.
265 enum TransitionFlag {
271 // Indicates whether the transition is simple: the target map of the transition
272 // either extends the current map with a new property, or it modifies the
273 // property that was added last to the current map.
274 enum SimpleTransitionFlag {
275 SIMPLE_PROPERTY_TRANSITION,
281 // Indicates whether we are only interested in the descriptors of a particular
282 // map, or in all descriptors in the descriptor array.
283 enum DescriptorFlag {
288 // The GC maintains a bit of information, the MarkingParity, which toggles
289 // from odd to even and back every time marking is completed. Incremental
290 // marking can visit an object twice during a marking phase, so algorithms that
291 // that piggy-back on marking can use the parity to ensure that they only
292 // perform an operation on an object once per marking phase: they record the
293 // MarkingParity when they visit an object, and only re-visit the object when it
294 // is marked again and the MarkingParity changes.
301 // ICs store extra state in a Code object. The default extra state is
303 typedef int ExtraICState;
304 static const ExtraICState kNoExtraICState = 0;
306 // Instance size sentinel for objects of variable size.
307 const int kVariableSizeSentinel = 0;
309 // We may store the unsigned bit field as signed Smi value and do not
311 const int kStubMajorKeyBits = 7;
312 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
314 // All Maps have a field instance_type containing a InstanceType.
315 // It describes the type of the instances.
317 // As an example, a JavaScript object is a heap object and its map
318 // instance_type is JS_OBJECT_TYPE.
320 // The names of the string instance types are intended to systematically
321 // mirror their encoding in the instance_type field of the map. The default
322 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
323 // encoding is mentioned explicitly in the name. Likewise, the default
324 // representation is considered sequential. It is not mentioned in the
325 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
326 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
327 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
329 // NOTE: The following things are some that depend on the string types having
330 // instance_types that are less than those of all other types:
331 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
334 // NOTE: Everything following JS_VALUE_TYPE is considered a
335 // JSObject for GC purposes. The first four entries here have typeof
336 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
337 #define INSTANCE_TYPE_LIST(V) \
339 V(ONE_BYTE_STRING_TYPE) \
340 V(CONS_STRING_TYPE) \
341 V(CONS_ONE_BYTE_STRING_TYPE) \
342 V(SLICED_STRING_TYPE) \
343 V(SLICED_ONE_BYTE_STRING_TYPE) \
344 V(EXTERNAL_STRING_TYPE) \
345 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
346 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
347 V(SHORT_EXTERNAL_STRING_TYPE) \
348 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
349 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
351 V(INTERNALIZED_STRING_TYPE) \
352 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
353 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
354 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
355 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
356 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
357 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
358 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
361 V(SIMD128_VALUE_TYPE) \
367 V(PROPERTY_CELL_TYPE) \
369 V(HEAP_NUMBER_TYPE) \
370 V(MUTABLE_HEAP_NUMBER_TYPE) \
373 V(BYTECODE_ARRAY_TYPE) \
376 V(FIXED_INT8_ARRAY_TYPE) \
377 V(FIXED_UINT8_ARRAY_TYPE) \
378 V(FIXED_INT16_ARRAY_TYPE) \
379 V(FIXED_UINT16_ARRAY_TYPE) \
380 V(FIXED_INT32_ARRAY_TYPE) \
381 V(FIXED_UINT32_ARRAY_TYPE) \
382 V(FIXED_FLOAT32_ARRAY_TYPE) \
383 V(FIXED_FLOAT64_ARRAY_TYPE) \
384 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
388 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
389 V(DECLARED_ACCESSOR_INFO_TYPE) \
390 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
391 V(ACCESSOR_PAIR_TYPE) \
392 V(ACCESS_CHECK_INFO_TYPE) \
393 V(INTERCEPTOR_INFO_TYPE) \
394 V(CALL_HANDLER_INFO_TYPE) \
395 V(FUNCTION_TEMPLATE_INFO_TYPE) \
396 V(OBJECT_TEMPLATE_INFO_TYPE) \
397 V(SIGNATURE_INFO_TYPE) \
398 V(TYPE_SWITCH_INFO_TYPE) \
399 V(ALLOCATION_MEMENTO_TYPE) \
400 V(ALLOCATION_SITE_TYPE) \
403 V(POLYMORPHIC_CODE_CACHE_TYPE) \
404 V(TYPE_FEEDBACK_INFO_TYPE) \
405 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
407 V(PROTOTYPE_INFO_TYPE) \
408 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
410 V(FIXED_ARRAY_TYPE) \
411 V(FIXED_DOUBLE_ARRAY_TYPE) \
412 V(SHARED_FUNCTION_INFO_TYPE) \
415 V(JS_MESSAGE_OBJECT_TYPE) \
420 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
421 V(JS_GENERATOR_OBJECT_TYPE) \
423 V(JS_GLOBAL_OBJECT_TYPE) \
424 V(JS_BUILTINS_OBJECT_TYPE) \
425 V(JS_GLOBAL_PROXY_TYPE) \
427 V(JS_ARRAY_BUFFER_TYPE) \
428 V(JS_TYPED_ARRAY_TYPE) \
429 V(JS_DATA_VIEW_TYPE) \
433 V(JS_SET_ITERATOR_TYPE) \
434 V(JS_MAP_ITERATOR_TYPE) \
435 V(JS_ITERATOR_RESULT_TYPE) \
436 V(JS_WEAK_MAP_TYPE) \
437 V(JS_WEAK_SET_TYPE) \
440 V(JS_FUNCTION_TYPE) \
441 V(JS_FUNCTION_PROXY_TYPE) \
443 V(BREAK_POINT_INFO_TYPE)
446 // Since string types are not consecutive, this macro is used to
447 // iterate over them.
448 #define STRING_TYPE_LIST(V) \
449 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
450 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
452 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
453 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
455 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
456 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
457 SlicedOneByteString) \
458 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
460 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
461 external_one_byte_string, ExternalOneByteString) \
462 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
463 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
464 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
465 short_external_string, ShortExternalString) \
466 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
467 short_external_one_byte_string, ShortExternalOneByteString) \
468 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
469 ExternalTwoByteString::kShortSize, \
470 short_external_string_with_one_byte_data, \
471 ShortExternalStringWithOneByteData) \
473 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
474 InternalizedString) \
475 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
476 one_byte_internalized_string, OneByteInternalizedString) \
477 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
478 external_internalized_string, ExternalInternalizedString) \
479 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
480 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
481 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
482 ExternalTwoByteString::kSize, \
483 external_internalized_string_with_one_byte_data, \
484 ExternalInternalizedStringWithOneByteData) \
485 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
486 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
487 ShortExternalInternalizedString) \
488 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
489 ExternalOneByteString::kShortSize, \
490 short_external_one_byte_internalized_string, \
491 ShortExternalOneByteInternalizedString) \
492 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
493 ExternalTwoByteString::kShortSize, \
494 short_external_internalized_string_with_one_byte_data, \
495 ShortExternalInternalizedStringWithOneByteData)
497 // A struct is a simple object a set of object-valued fields. Including an
498 // object type in this causes the compiler to generate most of the boilerplate
499 // code for the class including allocation and garbage collection routines,
500 // casts and predicates. All you need to define is the class, methods and
501 // object verification routines. Easy, no?
503 // Note that for subtle reasons related to the ordering or numerical values of
504 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
506 #define STRUCT_LIST(V) \
508 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
509 executable_accessor_info) \
510 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
511 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
512 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
513 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
514 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
515 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
516 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
517 V(SCRIPT, Script, script) \
518 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
519 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
520 V(CODE_CACHE, CodeCache, code_cache) \
521 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
522 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
523 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
524 V(DEBUG_INFO, DebugInfo, debug_info) \
525 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
526 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
527 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
528 SloppyBlockWithEvalContextExtension, \
529 sloppy_block_with_eval_context_extension)
531 // We use the full 8 bits of the instance_type field to encode heap object
532 // instance types. The high-order bit (bit 7) is set if the object is not a
533 // string, and cleared if it is a string.
534 const uint32_t kIsNotStringMask = 0x80;
535 const uint32_t kStringTag = 0x0;
536 const uint32_t kNotStringTag = 0x80;
538 // Bit 6 indicates that the object is an internalized string (if set) or not.
539 // Bit 7 has to be clear as well.
540 const uint32_t kIsNotInternalizedMask = 0x40;
541 const uint32_t kNotInternalizedTag = 0x40;
542 const uint32_t kInternalizedTag = 0x0;
544 // If bit 7 is clear then bit 2 indicates whether the string consists of
545 // two-byte characters or one-byte characters.
546 const uint32_t kStringEncodingMask = 0x4;
547 const uint32_t kTwoByteStringTag = 0x0;
548 const uint32_t kOneByteStringTag = 0x4;
550 // If bit 7 is clear, the low-order 2 bits indicate the representation
552 const uint32_t kStringRepresentationMask = 0x03;
553 enum StringRepresentationTag {
555 kConsStringTag = 0x1,
556 kExternalStringTag = 0x2,
557 kSlicedStringTag = 0x3
559 const uint32_t kIsIndirectStringMask = 0x1;
560 const uint32_t kIsIndirectStringTag = 0x1;
561 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
562 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
563 STATIC_ASSERT((kConsStringTag &
564 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
565 STATIC_ASSERT((kSlicedStringTag &
566 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
568 // Use this mask to distinguish between cons and slice only after making
569 // sure that the string is one of the two (an indirect string).
570 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
571 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
573 // If bit 7 is clear, then bit 3 indicates whether this two-byte
574 // string actually contains one byte data.
575 const uint32_t kOneByteDataHintMask = 0x08;
576 const uint32_t kOneByteDataHintTag = 0x08;
578 // If bit 7 is clear and string representation indicates an external string,
579 // then bit 4 indicates whether the data pointer is cached.
580 const uint32_t kShortExternalStringMask = 0x10;
581 const uint32_t kShortExternalStringTag = 0x10;
584 // A ConsString with an empty string as the right side is a candidate
585 // for being shortcut by the garbage collector. We don't allocate any
586 // non-flat internalized strings, so we do not shortcut them thereby
587 // avoiding turning internalized strings into strings. The bit-masks
588 // below contain the internalized bit as additional safety.
589 // See heap.cc, mark-compact.cc and objects-visiting.cc.
590 const uint32_t kShortcutTypeMask =
592 kIsNotInternalizedMask |
593 kStringRepresentationMask;
594 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
596 static inline bool IsShortcutCandidate(int type) {
597 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
603 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
604 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
605 ONE_BYTE_INTERNALIZED_STRING_TYPE =
606 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
607 EXTERNAL_INTERNALIZED_STRING_TYPE =
608 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
609 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
610 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
611 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
612 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
614 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
615 kShortExternalStringTag |
617 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
618 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
620 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
621 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
622 kShortExternalStringTag | kInternalizedTag,
623 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
624 ONE_BYTE_STRING_TYPE =
625 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
626 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
627 CONS_ONE_BYTE_STRING_TYPE =
628 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
630 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
631 SLICED_ONE_BYTE_STRING_TYPE =
632 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
633 EXTERNAL_STRING_TYPE =
634 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
635 EXTERNAL_ONE_BYTE_STRING_TYPE =
636 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
637 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
638 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
640 SHORT_EXTERNAL_STRING_TYPE =
641 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
642 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
643 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
644 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
645 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
649 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
651 // Other primitives (cannot contain non-map-word pointers to heap objects).
654 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
656 // Objects allocated in their own spaces (never in new space).
660 // "Data", objects that cannot contain non-map-word pointers to heap
662 MUTABLE_HEAP_NUMBER_TYPE,
667 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
668 FIXED_UINT8_ARRAY_TYPE,
669 FIXED_INT16_ARRAY_TYPE,
670 FIXED_UINT16_ARRAY_TYPE,
671 FIXED_INT32_ARRAY_TYPE,
672 FIXED_UINT32_ARRAY_TYPE,
673 FIXED_FLOAT32_ARRAY_TYPE,
674 FIXED_FLOAT64_ARRAY_TYPE,
675 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
676 FIXED_DOUBLE_ARRAY_TYPE,
677 FILLER_TYPE, // LAST_DATA_TYPE
680 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
681 DECLARED_ACCESSOR_INFO_TYPE,
682 EXECUTABLE_ACCESSOR_INFO_TYPE,
684 ACCESS_CHECK_INFO_TYPE,
685 INTERCEPTOR_INFO_TYPE,
686 CALL_HANDLER_INFO_TYPE,
687 FUNCTION_TEMPLATE_INFO_TYPE,
688 OBJECT_TEMPLATE_INFO_TYPE,
690 TYPE_SWITCH_INFO_TYPE,
691 ALLOCATION_SITE_TYPE,
692 ALLOCATION_MEMENTO_TYPE,
695 POLYMORPHIC_CODE_CACHE_TYPE,
696 TYPE_FEEDBACK_INFO_TYPE,
697 ALIASED_ARGUMENTS_ENTRY_TYPE,
700 BREAK_POINT_INFO_TYPE,
702 SHARED_FUNCTION_INFO_TYPE,
707 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
709 // All the following types are subtypes of JSReceiver, which corresponds to
710 // objects in the JS sense. The first and the last type in this range are
711 // the two forms of function. This organization enables using the same
712 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
713 // NONCALLABLE_JS_OBJECT range.
714 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
715 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
716 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
717 JS_MESSAGE_OBJECT_TYPE,
720 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
721 JS_GENERATOR_OBJECT_TYPE,
723 JS_GLOBAL_OBJECT_TYPE,
724 JS_BUILTINS_OBJECT_TYPE,
725 JS_GLOBAL_PROXY_TYPE,
727 JS_ARRAY_BUFFER_TYPE,
732 JS_SET_ITERATOR_TYPE,
733 JS_MAP_ITERATOR_TYPE,
734 JS_ITERATOR_RESULT_TYPE,
738 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
742 LAST_TYPE = JS_FUNCTION_TYPE,
743 FIRST_NAME_TYPE = FIRST_TYPE,
744 LAST_NAME_TYPE = SYMBOL_TYPE,
745 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
746 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
747 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
748 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
749 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
750 // Boundaries for testing for a fixed typed array.
751 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
752 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
753 // Boundary for promotion to old space.
754 LAST_DATA_TYPE = FILLER_TYPE,
755 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
756 // Note that there is no range for JSObject or JSProxy, since their subtypes
757 // are not continuous in this enum! The enum ranges instead reflect the
758 // external class names, where proxies are treated as either ordinary objects,
760 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
761 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
762 // Boundaries for testing the types represented as JSObject
763 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
764 LAST_JS_OBJECT_TYPE = LAST_TYPE,
765 // Boundaries for testing the types represented as JSProxy
766 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
767 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
768 // Boundaries for testing whether the type is a JavaScript object.
769 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
770 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
771 // Boundaries for testing the types for which typeof is "object".
772 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
773 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
774 // Note that the types for which typeof is "function" are not continuous.
775 // Define this so that we can put assertions on discrete checks.
776 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
779 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
780 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
781 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
782 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
785 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
786 V(FAST_ELEMENTS_SUB_TYPE) \
787 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
788 V(FAST_PROPERTIES_SUB_TYPE) \
789 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
790 V(MAP_CODE_CACHE_SUB_TYPE) \
791 V(SCOPE_INFO_SUB_TYPE) \
792 V(STRING_TABLE_SUB_TYPE) \
793 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
794 V(TRANSITION_ARRAY_SUB_TYPE)
796 enum FixedArraySubInstanceType {
797 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
798 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
799 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
800 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
804 // TODO(bmeurer): Remove this in favor of the ComparisonResult below.
814 // Result of an abstract relational comparison of x and y, implemented according
815 // to ES6 section 7.2.11 Abstract Relational Comparison.
816 enum class ComparisonResult {
819 kGreaterThan, // x > y
820 kUndefined // at least one of x or y was undefined or NaN
824 #define DECL_BOOLEAN_ACCESSORS(name) \
825 inline bool name() const; \
826 inline void set_##name(bool value);
828 #define DECL_INT_ACCESSORS(name) \
829 inline int name() const; \
830 inline void set_##name(int value);
833 #define DECL_ACCESSORS(name, type) \
834 inline type* name() const; \
835 inline void set_##name(type* value, \
836 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
839 #define DECLARE_CAST(type) \
840 INLINE(static type* cast(Object* object)); \
841 INLINE(static const type* cast(const Object* object));
845 class AllocationSite;
846 class AllocationSiteCreationContext;
847 class AllocationSiteUsageContext;
850 class ElementsAccessor;
851 class FixedArrayBase;
852 class FunctionLiteral;
854 class JSBuiltinsObject;
855 class LayoutDescriptor;
857 class LookupIterator;
858 class ObjectHashTable;
861 class SafepointEntry;
862 class SharedFunctionInfo;
864 class TypeFeedbackInfo;
865 class TypeFeedbackVector;
868 // We cannot just say "class HeapType;" if it is created from a template... =8-?
869 template<class> class TypeImpl;
870 struct HeapTypeConfig;
871 typedef TypeImpl<HeapTypeConfig> HeapType;
874 // A template-ized version of the IsXXX functions.
875 template <class C> inline bool Is(Object* obj);
878 #define DECLARE_VERIFIER(Name) void Name##Verify();
880 #define DECLARE_VERIFIER(Name)
884 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
886 #define DECLARE_PRINTER(Name)
890 #define OBJECT_TYPE_LIST(V) \
895 #define HEAP_OBJECT_TYPE_LIST(V) \
897 V(MutableHeapNumber) \
916 V(ExternalTwoByteString) \
917 V(ExternalOneByteString) \
918 V(SeqTwoByteString) \
919 V(SeqOneByteString) \
920 V(InternalizedString) \
923 V(FixedTypedArrayBase) \
926 V(FixedUint16Array) \
928 V(FixedUint32Array) \
930 V(FixedFloat32Array) \
931 V(FixedFloat64Array) \
932 V(FixedUint8ClampedArray) \
938 V(JSContextExtensionObject) \
939 V(JSGeneratorObject) \
941 V(LayoutDescriptor) \
946 V(TypeFeedbackVector) \
947 V(DeoptimizationInputData) \
948 V(DeoptimizationOutputData) \
952 V(FixedDoubleArray) \
956 V(ScriptContextTable) \
962 V(SharedFunctionInfo) \
971 V(JSArrayBufferView) \
980 V(JSIteratorResult) \
981 V(JSWeakCollection) \
988 V(NormalizedMapCache) \
989 V(CompilationCacheTable) \
990 V(CodeCacheHashTable) \
991 V(PolymorphicCodeCacheHashTable) \
996 V(JSBuiltinsObject) \
998 V(UndetectableObject) \
999 V(AccessCheckNeeded) \
1003 V(ObjectHashTable) \
1007 // Object is the abstract superclass for all classes in the
1008 // object hierarchy.
1009 // Object does not use any virtual functions to avoid the
1010 // allocation of the C++ vtable.
1011 // Since both Smi and HeapObject are subclasses of Object no
1012 // data members can be present in Object.
1016 bool IsObject() const { return true; }
1018 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1019 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1020 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1021 #undef IS_TYPE_FUNCTION_DECL
1023 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1024 // a keyed store is of the form a[expression] = foo.
1025 enum StoreFromKeyed {
1026 MAY_BE_STORE_FROM_KEYED,
1027 CERTAINLY_NOT_STORE_FROM_KEYED
1030 INLINE(bool IsFixedArrayBase() const);
1031 INLINE(bool IsExternal() const);
1032 INLINE(bool IsAccessorInfo() const);
1034 INLINE(bool IsStruct() const);
1035 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1036 INLINE(bool Is##Name() const);
1037 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1038 #undef DECLARE_STRUCT_PREDICATE
1040 // ES6, section 7.2.3 IsCallable.
1041 INLINE(bool IsCallable() const);
1043 // ES6, section 7.2.4 IsConstructor.
1044 INLINE(bool IsConstructor() const);
1046 INLINE(bool IsSpecObject()) const;
1047 INLINE(bool IsTemplateInfo()) const;
1048 INLINE(bool IsNameDictionary() const);
1049 INLINE(bool IsGlobalDictionary() const);
1050 INLINE(bool IsSeededNumberDictionary() const);
1051 INLINE(bool IsUnseededNumberDictionary() const);
1052 INLINE(bool IsOrderedHashSet() const);
1053 INLINE(bool IsOrderedHashMap() const);
1054 static bool IsPromise(Handle<Object> object);
1057 INLINE(bool IsUndefined() const);
1058 INLINE(bool IsNull() const);
1059 INLINE(bool IsTheHole() const);
1060 INLINE(bool IsException() const);
1061 INLINE(bool IsUninitialized() const);
1062 INLINE(bool IsTrue() const);
1063 INLINE(bool IsFalse() const);
1064 INLINE(bool IsArgumentsMarker() const);
1066 // Filler objects (fillers and free space objects).
1067 INLINE(bool IsFiller() const);
1069 // Extract the number.
1070 inline double Number() const;
1071 INLINE(bool IsNaN() const);
1072 INLINE(bool IsMinusZero() const);
1073 bool ToInt32(int32_t* value);
1074 bool ToUint32(uint32_t* value);
1076 inline Representation OptimalRepresentation();
1078 inline ElementsKind OptimalElementsKind();
1080 inline bool FitsRepresentation(Representation representation);
1082 // Checks whether two valid primitive encodings of a property name resolve to
1083 // the same logical property. E.g., the smi 1, the string "1" and the double
1084 // 1 all refer to the same property, so this helper will return true.
1085 inline bool KeyEquals(Object* other);
1087 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1089 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1090 Handle<Object> object,
1091 Representation representation);
1093 inline static Handle<Object> WrapForRead(Isolate* isolate,
1094 Handle<Object> object,
1095 Representation representation);
1097 // Returns true if the object is of the correct type to be used as a
1098 // implementation of a JSObject's elements.
1099 inline bool HasValidElements();
1101 inline bool HasSpecificClassOf(String* name);
1103 bool BooleanValue(); // ECMA-262 9.2.
1105 // ES6 section 7.2.11 Abstract Relational Comparison
1106 MUST_USE_RESULT static Maybe<ComparisonResult> Compare(
1107 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1109 // ES6 section 7.2.12 Abstract Equality Comparison
1110 MUST_USE_RESULT static Maybe<bool> Equals(Handle<Object> x, Handle<Object> y);
1112 // ES6 section 7.2.13 Strict Equality Comparison
1113 bool StrictEquals(Object* that);
1115 // Convert to a JSObject if needed.
1116 // native_context is used when creating wrapper object.
1117 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1118 Handle<Object> object);
1119 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1120 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1122 // ES6 section 7.1.14 ToPropertyKey
1123 MUST_USE_RESULT static MaybeHandle<Name> ToName(Isolate* isolate,
1124 Handle<Object> input);
1126 // ES6 section 7.1.1 ToPrimitive
1127 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1128 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1130 // ES6 section 7.1.3 ToNumber
1131 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Handle<Object> input);
1133 // ES6 section 7.1.4 ToInteger
1134 MUST_USE_RESULT static MaybeHandle<Object> ToInteger(Isolate* isolate,
1135 Handle<Object> input);
1137 // ES6 section 7.1.5 ToInt32
1138 MUST_USE_RESULT static MaybeHandle<Object> ToInt32(Isolate* isolate,
1139 Handle<Object> input);
1141 // ES6 section 7.1.6 ToUint32
1142 MUST_USE_RESULT static MaybeHandle<Object> ToUint32(Isolate* isolate,
1143 Handle<Object> input);
1145 // ES6 section 7.1.12 ToString
1146 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1147 Handle<Object> input);
1149 // ES6 section 7.1.15 ToLength
1150 MUST_USE_RESULT static MaybeHandle<Object> ToLength(Isolate* isolate,
1151 Handle<Object> input);
1153 // ES6 section 7.3.9 GetMethod
1154 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1155 Handle<JSReceiver> receiver, Handle<Name> name);
1157 // ES6 section 12.5.6 The typeof Operator
1158 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1160 // ES6 section 12.6 Multiplicative Operators
1161 MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1162 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1163 Strength strength = Strength::WEAK);
1164 MUST_USE_RESULT static MaybeHandle<Object> Divide(
1165 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1166 Strength strength = Strength::WEAK);
1167 MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1168 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1169 Strength strength = Strength::WEAK);
1171 // ES6 section 12.7 Additive Operators
1172 MUST_USE_RESULT static MaybeHandle<Object> Add(
1173 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1174 Strength strength = Strength::WEAK);
1175 MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1176 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1177 Strength strength = Strength::WEAK);
1179 // ES6 section 12.8 Bitwise Shift Operators
1180 MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1181 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1182 Strength strength = Strength::WEAK);
1183 MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1184 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1185 Strength strength = Strength::WEAK);
1186 MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1187 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1188 Strength strength = Strength::WEAK);
1190 // ES6 section 12.9 Relational Operators
1191 MUST_USE_RESULT static inline Maybe<bool> GreaterThan(
1192 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1193 MUST_USE_RESULT static inline Maybe<bool> GreaterThanOrEqual(
1194 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1195 MUST_USE_RESULT static inline Maybe<bool> LessThan(
1196 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1197 MUST_USE_RESULT static inline Maybe<bool> LessThanOrEqual(
1198 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1200 // ES6 section 12.11 Binary Bitwise Operators
1201 MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1202 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1203 Strength strength = Strength::WEAK);
1204 MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1205 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1206 Strength strength = Strength::WEAK);
1207 MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1208 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1209 Strength strength = Strength::WEAK);
1211 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1212 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1214 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1215 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1216 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1217 LanguageMode language_mode,
1218 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1220 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1221 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1222 StoreFromKeyed store_mode);
1224 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1225 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1226 StoreFromKeyed store_mode);
1228 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1229 LookupIterator* it, LanguageMode language_mode);
1230 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1231 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1232 LanguageMode language_mode);
1233 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1234 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1235 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1236 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1237 Handle<Object> value, LanguageMode language_mode);
1238 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1239 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1240 LanguageMode language_mode);
1241 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1242 LookupIterator* it, Handle<Object> value);
1243 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1244 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1245 LanguageMode language_mode, StoreFromKeyed store_mode);
1246 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1247 Handle<Object> object, Handle<Name> name,
1248 LanguageMode language_mode = SLOPPY);
1249 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1250 Isolate* isolate, Handle<Object> object, const char* key,
1251 LanguageMode language_mode = SLOPPY);
1252 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1253 Handle<Object> object, Handle<Name> name,
1254 LanguageMode language_mode = SLOPPY);
1256 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1257 LookupIterator* it, LanguageMode language_mode);
1258 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1259 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1261 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1262 Handle<Object> receiver,
1263 Handle<JSReceiver> getter);
1264 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1265 Handle<Object> receiver,
1266 Handle<JSReceiver> setter,
1267 Handle<Object> value);
1269 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1270 Isolate* isolate, Handle<Object> object, uint32_t index,
1271 LanguageMode language_mode = SLOPPY);
1273 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1274 Isolate* isolate, Handle<Object> object, uint32_t index,
1275 Handle<Object> value, LanguageMode language_mode);
1277 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1278 Isolate* isolate, Handle<Object> receiver);
1280 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1282 // Returns the permanent hash code associated with this object. May return
1283 // undefined if not yet created.
1286 // Returns undefined for JSObjects, but returns the hash code for simple
1287 // objects. This avoids a double lookup in the cases where we know we will
1288 // add the hash to the JSObject if it does not already exist.
1289 Object* GetSimpleHash();
1291 // Returns the permanent hash code associated with this object depending on
1292 // the actual object type. May create and store a hash code if needed and none
1294 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1296 // Checks whether this object has the same value as the given one. This
1297 // function is implemented according to ES5, section 9.12 and can be used
1298 // to implement the Harmony "egal" function.
1299 bool SameValue(Object* other);
1301 // Checks whether this object has the same value as the given one.
1302 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1303 // This function is implemented according to ES6, section 7.2.4 and is used
1304 // by ES6 Map and Set.
1305 bool SameValueZero(Object* other);
1307 // Tries to convert an object to an array length. Returns true and sets the
1308 // output parameter if it succeeds.
1309 inline bool ToArrayLength(uint32_t* index);
1311 // Tries to convert an object to an array index. Returns true and sets the
1312 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1313 // allow kMaxUInt32.
1314 inline bool ToArrayIndex(uint32_t* index);
1316 // Returns true if this is a JSValue containing a string and the index is
1317 // < the length of the string. Used to implement [] on strings.
1318 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1320 DECLARE_VERIFIER(Object)
1322 // Verify a pointer is a valid object pointer.
1323 static void VerifyPointer(Object* p);
1326 inline void VerifyApiCallResultType();
1328 // Prints this object without details.
1329 void ShortPrint(FILE* out = stdout);
1331 // Prints this object without details to a message accumulator.
1332 void ShortPrint(StringStream* accumulator);
1334 void ShortPrint(std::ostream& os); // NOLINT
1336 DECLARE_CAST(Object)
1338 // Layout description.
1339 static const int kHeaderSize = 0; // Object does not take up any space.
1342 // For our gdb macros, we should perhaps change these in the future.
1345 // Prints this object with details.
1346 void Print(std::ostream& os); // NOLINT
1348 void Print() { ShortPrint(); }
1349 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1353 friend class LookupIterator;
1354 friend class PrototypeIterator;
1356 // Return the map of the root of object's prototype chain.
1357 Map* GetRootMap(Isolate* isolate);
1359 // Helper for SetProperty and SetSuperProperty.
1360 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1361 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1362 StoreFromKeyed store_mode, bool* found);
1364 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1368 // In objects.h to be usable without objects-inl.h inclusion.
1369 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1370 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1374 explicit Brief(const Object* const v) : value(v) {}
1375 const Object* value;
1379 std::ostream& operator<<(std::ostream& os, const Brief& v);
1382 // Smi represents integer Numbers that can be stored in 31 bits.
1383 // Smis are immediate which means they are NOT allocated in the heap.
1384 // The this pointer has the following format: [31 bit signed int] 0
1385 // For long smis it has the following format:
1386 // [32 bit signed int] [31 bits zero padding] 0
1387 // Smi stands for small integer.
1388 class Smi: public Object {
1390 // Returns the integer value.
1391 inline int value() const { return Internals::SmiValue(this); }
1393 // Convert a value to a Smi object.
1394 static inline Smi* FromInt(int value) {
1395 DCHECK(Smi::IsValid(value));
1396 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1399 static inline Smi* FromIntptr(intptr_t value) {
1400 DCHECK(Smi::IsValid(value));
1401 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1402 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1405 // Returns whether value can be represented in a Smi.
1406 static inline bool IsValid(intptr_t value) {
1407 bool result = Internals::IsValidSmi(value);
1408 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1414 // Dispatched behavior.
1415 void SmiPrint(std::ostream& os) const; // NOLINT
1416 DECLARE_VERIFIER(Smi)
1418 static const int kMinValue =
1419 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1420 static const int kMaxValue = -(kMinValue + 1);
1423 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1427 // Heap objects typically have a map pointer in their first word. However,
1428 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1429 // encoded in the first word. The class MapWord is an abstraction of the
1430 // value in a heap object's first word.
1431 class MapWord BASE_EMBEDDED {
1433 // Normal state: the map word contains a map pointer.
1435 // Create a map word from a map pointer.
1436 static inline MapWord FromMap(const Map* map);
1438 // View this map word as a map pointer.
1439 inline Map* ToMap();
1442 // Scavenge collection: the map word of live objects in the from space
1443 // contains a forwarding address (a heap object pointer in the to space).
1445 // True if this map word is a forwarding address for a scavenge
1446 // collection. Only valid during a scavenge collection (specifically,
1447 // when all map words are heap object pointers, i.e. not during a full GC).
1448 inline bool IsForwardingAddress();
1450 // Create a map word from a forwarding address.
1451 static inline MapWord FromForwardingAddress(HeapObject* object);
1453 // View this map word as a forwarding address.
1454 inline HeapObject* ToForwardingAddress();
1456 static inline MapWord FromRawValue(uintptr_t value) {
1457 return MapWord(value);
1460 inline uintptr_t ToRawValue() {
1465 // HeapObject calls the private constructor and directly reads the value.
1466 friend class HeapObject;
1468 explicit MapWord(uintptr_t value) : value_(value) {}
1474 // The content of an heap object (except for the map pointer). kTaggedValues
1475 // objects can contain both heap pointers and Smis, kMixedValues can contain
1476 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1477 // objects can contain raw values and Smis.
1478 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1481 // HeapObject is the superclass for all classes describing heap allocated
1483 class HeapObject: public Object {
1485 // [map]: Contains a map which contains the object's reflective
1487 inline Map* map() const;
1488 inline void set_map(Map* value);
1489 // The no-write-barrier version. This is OK if the object is white and in
1490 // new space, or if the value is an immortal immutable object, like the maps
1491 // of primitive (non-JS) objects like strings, heap numbers etc.
1492 inline void set_map_no_write_barrier(Map* value);
1494 // Get the map using acquire load.
1495 inline Map* synchronized_map();
1496 inline MapWord synchronized_map_word() const;
1498 // Set the map using release store
1499 inline void synchronized_set_map(Map* value);
1500 inline void synchronized_set_map_no_write_barrier(Map* value);
1501 inline void synchronized_set_map_word(MapWord map_word);
1503 // During garbage collection, the map word of a heap object does not
1504 // necessarily contain a map pointer.
1505 inline MapWord map_word() const;
1506 inline void set_map_word(MapWord map_word);
1508 // The Heap the object was allocated in. Used also to access Isolate.
1509 inline Heap* GetHeap() const;
1511 // Convenience method to get current isolate.
1512 inline Isolate* GetIsolate() const;
1514 // Converts an address to a HeapObject pointer.
1515 static inline HeapObject* FromAddress(Address address) {
1516 DCHECK_TAG_ALIGNED(address);
1517 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1520 // Returns the address of this HeapObject.
1521 inline Address address() {
1522 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1525 // Iterates over pointers contained in the object (including the Map)
1526 void Iterate(ObjectVisitor* v);
1528 // Iterates over all pointers contained in the object except the
1529 // first map pointer. The object type is given in the first
1530 // parameter. This function does not access the map pointer in the
1531 // object, and so is safe to call while the map pointer is modified.
1532 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1534 // Returns the heap object's size in bytes
1537 // Indicates what type of values this heap object may contain.
1538 inline HeapObjectContents ContentType();
1540 // Given a heap object's map pointer, returns the heap size in bytes
1541 // Useful when the map pointer field is used for other purposes.
1543 inline int SizeFromMap(Map* map);
1545 // Returns the field at offset in obj, as a read/write Object* reference.
1546 // Does no checking, and is safe to use during GC, while maps are invalid.
1547 // Does not invoke write barrier, so should only be assigned to
1548 // during marking GC.
1549 static inline Object** RawField(HeapObject* obj, int offset);
1551 // Adds the |code| object related to |name| to the code cache of this map. If
1552 // this map is a dictionary map that is shared, the map copied and installed
1554 static void UpdateMapCodeCache(Handle<HeapObject> object,
1558 DECLARE_CAST(HeapObject)
1560 // Return the write barrier mode for this. Callers of this function
1561 // must be able to present a reference to an DisallowHeapAllocation
1562 // object as a sign that they are not going to use this function
1563 // from code that allocates and thus invalidates the returned write
1565 inline WriteBarrierMode GetWriteBarrierMode(
1566 const DisallowHeapAllocation& promise);
1568 // Dispatched behavior.
1569 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1571 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1573 DECLARE_PRINTER(HeapObject)
1574 DECLARE_VERIFIER(HeapObject)
1576 inline void VerifyObjectField(int offset);
1577 inline void VerifySmiField(int offset);
1579 // Verify a pointer is a valid HeapObject pointer that points to object
1580 // areas in the heap.
1581 static void VerifyHeapPointer(Object* p);
1584 inline AllocationAlignment RequiredAlignment();
1586 // Layout description.
1587 // First field in a heap object is map.
1588 static const int kMapOffset = Object::kHeaderSize;
1589 static const int kHeaderSize = kMapOffset + kPointerSize;
1591 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1594 // helpers for calling an ObjectVisitor to iterate over pointers in the
1595 // half-open range [start, end) specified as integer offsets
1596 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1597 // as above, for the single element at "offset"
1598 inline void IteratePointer(ObjectVisitor* v, int offset);
1599 // as above, for the next code link of a code object.
1600 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1603 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1607 // This class describes a body of an object of a fixed size
1608 // in which all pointer fields are located in the [start_offset, end_offset)
1610 template<int start_offset, int end_offset, int size>
1611 class FixedBodyDescriptor {
1613 static const int kStartOffset = start_offset;
1614 static const int kEndOffset = end_offset;
1615 static const int kSize = size;
1617 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1619 template<typename StaticVisitor>
1620 static inline void IterateBody(HeapObject* obj) {
1621 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1622 HeapObject::RawField(obj, end_offset));
1627 // This class describes a body of an object of a variable size
1628 // in which all pointer fields are located in the [start_offset, object_size)
1630 template<int start_offset>
1631 class FlexibleBodyDescriptor {
1633 static const int kStartOffset = start_offset;
1635 static inline void IterateBody(HeapObject* obj,
1639 template<typename StaticVisitor>
1640 static inline void IterateBody(HeapObject* obj, int object_size) {
1641 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1642 HeapObject::RawField(obj, object_size));
1647 // The HeapNumber class describes heap allocated numbers that cannot be
1648 // represented in a Smi (small integer)
1649 class HeapNumber: public HeapObject {
1651 // [value]: number value.
1652 inline double value() const;
1653 inline void set_value(double value);
1655 DECLARE_CAST(HeapNumber)
1657 // Dispatched behavior.
1658 bool HeapNumberBooleanValue();
1660 void HeapNumberPrint(std::ostream& os); // NOLINT
1661 DECLARE_VERIFIER(HeapNumber)
1663 inline int get_exponent();
1664 inline int get_sign();
1666 // Layout description.
1667 static const int kValueOffset = HeapObject::kHeaderSize;
1668 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1669 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1670 // words within double numbers are endian dependent and they are set
1672 #if defined(V8_TARGET_LITTLE_ENDIAN)
1673 static const int kMantissaOffset = kValueOffset;
1674 static const int kExponentOffset = kValueOffset + 4;
1675 #elif defined(V8_TARGET_BIG_ENDIAN)
1676 static const int kMantissaOffset = kValueOffset + 4;
1677 static const int kExponentOffset = kValueOffset;
1679 #error Unknown byte ordering
1682 static const int kSize = kValueOffset + kDoubleSize;
1683 static const uint32_t kSignMask = 0x80000000u;
1684 static const uint32_t kExponentMask = 0x7ff00000u;
1685 static const uint32_t kMantissaMask = 0xfffffu;
1686 static const int kMantissaBits = 52;
1687 static const int kExponentBits = 11;
1688 static const int kExponentBias = 1023;
1689 static const int kExponentShift = 20;
1690 static const int kInfinityOrNanExponent =
1691 (kExponentMask >> kExponentShift) - kExponentBias;
1692 static const int kMantissaBitsInTopWord = 20;
1693 static const int kNonMantissaBitsInTopWord = 12;
1696 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1700 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1701 class Simd128Value : public HeapObject {
1703 DECLARE_CAST(Simd128Value)
1705 DECLARE_PRINTER(Simd128Value)
1706 DECLARE_VERIFIER(Simd128Value)
1708 static Handle<String> ToString(Handle<Simd128Value> input);
1710 // Equality operations.
1711 inline bool Equals(Simd128Value* that);
1712 static inline bool Equals(Handle<Simd128Value> one, Handle<Simd128Value> two);
1714 // Checks that another instance is bit-wise equal.
1715 bool BitwiseEquals(const Simd128Value* other) const;
1716 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1717 uint32_t Hash() const;
1718 // Copies the 16 bytes of SIMD data to the destination address.
1719 void CopyBits(void* destination) const;
1721 // Layout description.
1722 static const int kValueOffset = HeapObject::kHeaderSize;
1723 static const int kSize = kValueOffset + kSimd128Size;
1726 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1730 // V has parameters (TYPE, Type, type, lane count, lane type)
1731 #define SIMD128_TYPES(V) \
1732 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1733 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1734 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1735 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1736 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1737 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1738 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1739 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1740 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1741 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1743 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1744 class Type final : public Simd128Value { \
1746 inline lane_type get_lane(int lane) const; \
1747 inline void set_lane(int lane, lane_type value); \
1749 DECLARE_CAST(Type) \
1751 DECLARE_PRINTER(Type) \
1753 static Handle<String> ToString(Handle<Type> input); \
1755 inline bool Equals(Type* that); \
1758 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1760 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1761 #undef SIMD128_VALUE_CLASS
1764 enum EnsureElementsMode {
1765 DONT_ALLOW_DOUBLE_ELEMENTS,
1766 ALLOW_COPIED_DOUBLE_ELEMENTS,
1767 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1771 // Indicator for one component of an AccessorPair.
1772 enum AccessorComponent {
1778 // JSReceiver includes types on which properties can be defined, i.e.,
1779 // JSObject and JSProxy.
1780 class JSReceiver: public HeapObject {
1782 DECLARE_CAST(JSReceiver)
1784 // ES6 section 7.1.1 ToPrimitive
1785 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1786 Handle<JSReceiver> receiver,
1787 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1788 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1789 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1791 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1792 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1793 Handle<JSReceiver> object, Handle<Name> name);
1794 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1796 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1797 Handle<JSReceiver> object, uint32_t index);
1798 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1799 Handle<JSReceiver> object, uint32_t index);
1801 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1802 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1803 Handle<JSReceiver> object, Handle<Name> name,
1804 LanguageMode language_mode = SLOPPY);
1805 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1806 Handle<JSReceiver> object, Handle<Name> name,
1807 LanguageMode language_mode = SLOPPY);
1808 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1809 LookupIterator* it, LanguageMode language_mode);
1810 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1811 Handle<JSReceiver> object, uint32_t index,
1812 LanguageMode language_mode = SLOPPY);
1814 // Tests for the fast common case for property enumeration.
1815 bool IsSimpleEnum();
1817 // Returns the class name ([[Class]] property in the specification).
1818 String* class_name();
1820 // Returns the constructor name (the name (possibly, inferred name) of the
1821 // function that was used to instantiate the object).
1822 String* constructor_name();
1824 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1825 Handle<JSReceiver> object, Handle<Name> name);
1826 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1827 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1829 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1830 Handle<JSReceiver> object, uint32_t index);
1831 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1832 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1834 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1835 LookupIterator* it);
1838 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1840 static Handle<Object> GetDataProperty(LookupIterator* it);
1843 // Retrieves a permanent object identity hash code. The undefined value might
1844 // be returned in case no hash was created yet.
1845 inline Object* GetIdentityHash();
1847 // Retrieves a permanent object identity hash code. May create and store a
1848 // hash code if needed and none exists.
1849 inline static Handle<Smi> GetOrCreateIdentityHash(
1850 Handle<JSReceiver> object);
1852 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1854 // Computes the enumerable keys for a JSObject. Used for implementing
1855 // "for (n in object) { }".
1856 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1857 Handle<JSReceiver> object,
1858 KeyCollectionType type);
1861 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1865 // The JSObject describes real heap allocated JavaScript objects with
1867 // Note that the map of JSObject changes during execution to enable inline
1869 class JSObject: public JSReceiver {
1871 // [properties]: Backing storage for properties.
1872 // properties is a FixedArray in the fast case and a Dictionary in the
1874 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1875 inline void initialize_properties();
1876 inline bool HasFastProperties();
1877 // Gets slow properties for non-global objects.
1878 inline NameDictionary* property_dictionary();
1879 // Gets global object properties.
1880 inline GlobalDictionary* global_dictionary();
1882 // [elements]: The elements (properties with names that are integers).
1884 // Elements can be in two general modes: fast and slow. Each mode
1885 // corrensponds to a set of object representations of elements that
1886 // have something in common.
1888 // In the fast mode elements is a FixedArray and so each element can
1889 // be quickly accessed. This fact is used in the generated code. The
1890 // elements array can have one of three maps in this mode:
1891 // fixed_array_map, sloppy_arguments_elements_map or
1892 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1893 // the elements array may be shared by a few objects and so before
1894 // writing to any element the array must be copied. Use
1895 // EnsureWritableFastElements in this case.
1897 // In the slow mode the elements is either a NumberDictionary, a
1898 // FixedArray parameter map for a (sloppy) arguments object.
1899 DECL_ACCESSORS(elements, FixedArrayBase)
1900 inline void initialize_elements();
1901 static void ResetElements(Handle<JSObject> object);
1902 static inline void SetMapAndElements(Handle<JSObject> object,
1904 Handle<FixedArrayBase> elements);
1905 inline ElementsKind GetElementsKind();
1906 ElementsAccessor* GetElementsAccessor();
1907 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1908 inline bool HasFastSmiElements();
1909 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1910 inline bool HasFastObjectElements();
1911 // Returns true if an object has elements of FAST_ELEMENTS or
1912 // FAST_SMI_ONLY_ELEMENTS.
1913 inline bool HasFastSmiOrObjectElements();
1914 // Returns true if an object has any of the fast elements kinds.
1915 inline bool HasFastElements();
1916 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1918 inline bool HasFastDoubleElements();
1919 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1921 inline bool HasFastHoleyElements();
1922 inline bool HasSloppyArgumentsElements();
1923 inline bool HasDictionaryElements();
1925 inline bool HasFixedTypedArrayElements();
1927 inline bool HasFixedUint8ClampedElements();
1928 inline bool HasFixedArrayElements();
1929 inline bool HasFixedInt8Elements();
1930 inline bool HasFixedUint8Elements();
1931 inline bool HasFixedInt16Elements();
1932 inline bool HasFixedUint16Elements();
1933 inline bool HasFixedInt32Elements();
1934 inline bool HasFixedUint32Elements();
1935 inline bool HasFixedFloat32Elements();
1936 inline bool HasFixedFloat64Elements();
1938 inline bool HasFastArgumentsElements();
1939 inline bool HasSlowArgumentsElements();
1940 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1942 // Requires: HasFastElements().
1943 static Handle<FixedArray> EnsureWritableFastElements(
1944 Handle<JSObject> object);
1946 // Collects elements starting at index 0.
1947 // Undefined values are placed after non-undefined values.
1948 // Returns the number of non-undefined values.
1949 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1951 // As PrepareElementsForSort, but only on objects where elements is
1952 // a dictionary, and it will stay a dictionary. Collates undefined and
1953 // unexisting elements below limit from position zero of the elements.
1954 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1957 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1958 LookupIterator* it, Handle<Object> value);
1960 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1961 // grant an exemption to ExecutableAccessor callbacks in some cases.
1962 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1964 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1965 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1966 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1968 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1969 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1970 PropertyAttributes attributes,
1971 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1973 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1974 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1975 PropertyAttributes attributes,
1976 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1978 // Equivalent to one of the above depending on whether |name| can be converted
1979 // to an array index.
1980 MUST_USE_RESULT static MaybeHandle<Object>
1981 DefinePropertyOrElementIgnoreAttributes(
1982 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1983 PropertyAttributes attributes = NONE,
1984 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1986 // Adds or reconfigures a property to attributes NONE. It will fail when it
1988 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1989 Handle<Object> value);
1991 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1992 Handle<Object> value, PropertyAttributes attributes);
1994 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1995 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1996 PropertyAttributes attributes);
1998 // Extend the receiver with a single fast property appeared first in the
1999 // passed map. This also extends the property backing store if necessary.
2000 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
2002 // Migrates the given object to a map whose field representations are the
2003 // lowest upper bound of all known representations for that field.
2004 static void MigrateInstance(Handle<JSObject> instance);
2006 // Migrates the given object only if the target map is already available,
2007 // or returns false if such a map is not yet available.
2008 static bool TryMigrateInstance(Handle<JSObject> instance);
2010 // Sets the property value in a normalized object given (key, value, details).
2011 // Handles the special representation of JS global objects.
2012 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
2013 Handle<Object> value,
2014 PropertyDetails details);
2015 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
2016 Handle<Object> value,
2017 PropertyAttributes attributes);
2018 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
2020 Handle<Object> value,
2021 PropertyAttributes attributes);
2023 static void OptimizeAsPrototype(Handle<JSObject> object,
2024 PrototypeOptimizationMode mode);
2025 static void ReoptimizeIfPrototype(Handle<JSObject> object);
2026 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2027 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2028 static void InvalidatePrototypeChains(Map* map);
2030 // Alternative implementation of WeakFixedArray::NullCallback.
2031 class PrototypeRegistryCompactionCallback {
2033 static void Callback(Object* value, int old_index, int new_index);
2036 // Retrieve interceptors.
2037 InterceptorInfo* GetNamedInterceptor();
2038 InterceptorInfo* GetIndexedInterceptor();
2040 // Used from JSReceiver.
2041 MUST_USE_RESULT static Maybe<PropertyAttributes>
2042 GetPropertyAttributesWithInterceptor(LookupIterator* it);
2043 MUST_USE_RESULT static Maybe<PropertyAttributes>
2044 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
2046 // Retrieves an AccessorPair property from the given object. Might return
2047 // undefined if the property doesn't exist or is of a different kind.
2048 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
2049 Handle<JSObject> object,
2051 AccessorComponent component);
2053 // Defines an AccessorPair property on the given object.
2054 // TODO(mstarzinger): Rename to SetAccessor().
2055 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2057 Handle<Object> getter,
2058 Handle<Object> setter,
2059 PropertyAttributes attributes);
2061 // Defines an AccessorInfo property on the given object.
2062 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2063 Handle<JSObject> object,
2064 Handle<AccessorInfo> info);
2066 // The result must be checked first for exceptions. If there's no exception,
2067 // the output parameter |done| indicates whether the interceptor has a result
2069 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2070 LookupIterator* it, bool* done);
2072 // Accessors for hidden properties object.
2074 // Hidden properties are not own properties of the object itself.
2075 // Instead they are stored in an auxiliary structure kept as an own
2076 // property with a special name Heap::hidden_string(). But if the
2077 // receiver is a JSGlobalProxy then the auxiliary object is a property
2078 // of its prototype, and if it's a detached proxy, then you can't have
2079 // hidden properties.
2081 // Sets a hidden property on this object. Returns this object if successful,
2082 // undefined if called on a detached proxy.
2083 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2085 Handle<Object> value);
2086 // Gets the value of a hidden property with the given key. Returns the hole
2087 // if the property doesn't exist (or if called on a detached proxy),
2088 // otherwise returns the value set for the key.
2089 Object* GetHiddenProperty(Handle<Name> key);
2090 // Deletes a hidden property. Deleting a non-existing property is
2091 // considered successful.
2092 static void DeleteHiddenProperty(Handle<JSObject> object,
2094 // Returns true if the object has a property with the hidden string as name.
2095 static bool HasHiddenProperties(Handle<JSObject> object);
2097 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2099 static void ValidateElements(Handle<JSObject> object);
2101 // Makes sure that this object can contain HeapObject as elements.
2102 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2104 // Makes sure that this object can contain the specified elements.
2105 static inline void EnsureCanContainElements(
2106 Handle<JSObject> object,
2109 EnsureElementsMode mode);
2110 static inline void EnsureCanContainElements(
2111 Handle<JSObject> object,
2112 Handle<FixedArrayBase> elements,
2114 EnsureElementsMode mode);
2115 static void EnsureCanContainElements(
2116 Handle<JSObject> object,
2117 Arguments* arguments,
2120 EnsureElementsMode mode);
2122 // Would we convert a fast elements array to dictionary mode given
2123 // an access at key?
2124 bool WouldConvertToSlowElements(uint32_t index);
2126 // Computes the new capacity when expanding the elements of a JSObject.
2127 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2128 // (old_capacity + 50%) + 16
2129 return old_capacity + (old_capacity >> 1) + 16;
2132 // These methods do not perform access checks!
2133 static void UpdateAllocationSite(Handle<JSObject> object,
2134 ElementsKind to_kind);
2136 // Lookup interceptors are used for handling properties controlled by host
2138 inline bool HasNamedInterceptor();
2139 inline bool HasIndexedInterceptor();
2141 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2142 // by JSReceiver::GetKeys.
2143 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2144 Handle<JSObject> object,
2145 Handle<JSReceiver> receiver);
2146 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2147 Handle<JSObject> object,
2148 Handle<JSReceiver> receiver);
2150 // Support functions for v8 api (needed for correct interceptor behavior).
2151 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2152 Handle<JSObject> object, Handle<Name> name);
2153 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2154 Handle<JSObject> object, uint32_t index);
2155 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2156 Handle<JSObject> object, Handle<Name> name);
2158 // Get the header size for a JSObject. Used to compute the index of
2159 // internal fields as well as the number of internal fields.
2160 inline int GetHeaderSize();
2162 inline int GetInternalFieldCount();
2163 inline int GetInternalFieldOffset(int index);
2164 inline Object* GetInternalField(int index);
2165 inline void SetInternalField(int index, Object* value);
2166 inline void SetInternalField(int index, Smi* value);
2168 // Returns the number of properties on this object filtering out properties
2169 // with the specified attributes (ignoring interceptors).
2170 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2171 // Fill in details for properties into storage starting at the specified
2172 // index. Returns the number of properties added.
2173 int GetOwnPropertyNames(FixedArray* storage, int index,
2174 PropertyAttributes filter = NONE);
2176 // Returns the number of properties on this object filtering out properties
2177 // with the specified attributes (ignoring interceptors).
2178 int NumberOfOwnElements(PropertyAttributes filter);
2179 // Returns the number of enumerable elements (ignoring interceptors).
2180 int NumberOfEnumElements();
2181 // Returns the number of elements on this object filtering out elements
2182 // with the specified attributes (ignoring interceptors).
2183 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2184 // Count and fill in the enumerable elements into storage.
2185 // (storage->length() == NumberOfEnumElements()).
2186 // If storage is NULL, will count the elements without adding
2187 // them to any storage.
2188 // Returns the number of enumerable elements.
2189 int GetEnumElementKeys(FixedArray* storage);
2191 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2194 // Returns a new map with all transitions dropped from the object's current
2195 // map and the ElementsKind set.
2196 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2197 ElementsKind to_kind);
2198 static void TransitionElementsKind(Handle<JSObject> object,
2199 ElementsKind to_kind);
2201 // Always use this to migrate an object to a new map.
2202 // |expected_additional_properties| is only used for fast-to-slow transitions
2203 // and ignored otherwise.
2204 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2205 int expected_additional_properties = 0);
2207 // Convert the object to use the canonical dictionary
2208 // representation. If the object is expected to have additional properties
2209 // added this number can be indicated to have the backing store allocated to
2210 // an initial capacity for holding these properties.
2211 static void NormalizeProperties(Handle<JSObject> object,
2212 PropertyNormalizationMode mode,
2213 int expected_additional_properties,
2214 const char* reason);
2216 // Convert and update the elements backing store to be a
2217 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2218 static Handle<SeededNumberDictionary> NormalizeElements(
2219 Handle<JSObject> object);
2221 void RequireSlowElements(SeededNumberDictionary* dictionary);
2223 // Transform slow named properties to fast variants.
2224 static void MigrateSlowToFast(Handle<JSObject> object,
2225 int unused_property_fields, const char* reason);
2227 inline bool IsUnboxedDoubleField(FieldIndex index);
2229 // Access fast-case object properties at index.
2230 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2231 Representation representation,
2233 inline Object* RawFastPropertyAt(FieldIndex index);
2234 inline double RawFastDoublePropertyAt(FieldIndex index);
2236 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2237 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2238 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2239 inline void WriteToField(int descriptor, Object* value);
2241 // Access to in object properties.
2242 inline int GetInObjectPropertyOffset(int index);
2243 inline Object* InObjectPropertyAt(int index);
2244 inline Object* InObjectPropertyAtPut(int index,
2246 WriteBarrierMode mode
2247 = UPDATE_WRITE_BARRIER);
2249 // Set the object's prototype (only JSReceiver and null are allowed values).
2250 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2251 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2253 // Initializes the body after properties slot, properties slot is
2254 // initialized by set_properties. Fill the pre-allocated fields with
2255 // pre_allocated_value and the rest with filler_value.
2256 // Note: this call does not update write barrier, the caller is responsible
2257 // to ensure that |filler_value| can be collected without WB here.
2258 inline void InitializeBody(Map* map,
2259 Object* pre_allocated_value,
2260 Object* filler_value);
2262 // Check whether this object references another object
2263 bool ReferencesObject(Object* obj);
2265 // Disalow further properties to be added to the oject.
2266 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2267 Handle<JSObject> object);
2269 bool IsExtensible();
2272 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2274 // ES5 Object.freeze
2275 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2277 // Called the first time an object is observed with ES7 Object.observe.
2278 static void SetObserved(Handle<JSObject> object);
2281 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2283 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2284 Handle<JSObject> object,
2285 AllocationSiteUsageContext* site_context,
2286 DeepCopyHints hints = kNoHints);
2287 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2288 Handle<JSObject> object,
2289 AllocationSiteCreationContext* site_context);
2291 DECLARE_CAST(JSObject)
2293 // Dispatched behavior.
2294 void JSObjectShortPrint(StringStream* accumulator);
2295 DECLARE_PRINTER(JSObject)
2296 DECLARE_VERIFIER(JSObject)
2298 void PrintProperties(std::ostream& os); // NOLINT
2299 void PrintElements(std::ostream& os); // NOLINT
2301 #if defined(DEBUG) || defined(OBJECT_PRINT)
2302 void PrintTransitions(std::ostream& os); // NOLINT
2305 static void PrintElementsTransition(
2306 FILE* file, Handle<JSObject> object,
2307 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2308 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2310 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2313 // Structure for collecting spill information about JSObjects.
2314 class SpillInformation {
2318 int number_of_objects_;
2319 int number_of_objects_with_fast_properties_;
2320 int number_of_objects_with_fast_elements_;
2321 int number_of_fast_used_fields_;
2322 int number_of_fast_unused_fields_;
2323 int number_of_slow_used_properties_;
2324 int number_of_slow_unused_properties_;
2325 int number_of_fast_used_elements_;
2326 int number_of_fast_unused_elements_;
2327 int number_of_slow_used_elements_;
2328 int number_of_slow_unused_elements_;
2331 void IncrementSpillStatistics(SpillInformation* info);
2335 // If a GC was caused while constructing this object, the elements pointer
2336 // may point to a one pointer filler map. The object won't be rooted, but
2337 // our heap verification code could stumble across it.
2338 bool ElementsAreSafeToExamine();
2341 Object* SlowReverseLookup(Object* value);
2343 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2344 // Also maximal value of JSArray's length property.
2345 static const uint32_t kMaxElementCount = 0xffffffffu;
2347 // Constants for heuristics controlling conversion of fast elements
2348 // to slow elements.
2350 // Maximal gap that can be introduced by adding an element beyond
2351 // the current elements length.
2352 static const uint32_t kMaxGap = 1024;
2354 // Maximal length of fast elements array that won't be checked for
2355 // being dense enough on expansion.
2356 static const int kMaxUncheckedFastElementsLength = 5000;
2358 // Same as above but for old arrays. This limit is more strict. We
2359 // don't want to be wasteful with long lived objects.
2360 static const int kMaxUncheckedOldFastElementsLength = 500;
2362 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2363 // permissible values (see the DCHECK in heap.cc).
2364 static const int kInitialMaxFastElementArray = 100000;
2366 // This constant applies only to the initial map of "global.Object" and
2367 // not to arbitrary other JSObject maps.
2368 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2370 static const int kMaxInstanceSize = 255 * kPointerSize;
2371 // When extending the backing storage for property values, we increase
2372 // its size by more than the 1 entry necessary, so sequentially adding fields
2373 // to the same object requires fewer allocations and copies.
2374 static const int kFieldsAdded = 3;
2376 // Layout description.
2377 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2378 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2379 static const int kHeaderSize = kElementsOffset + kPointerSize;
2381 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2383 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2385 static inline int SizeOf(Map* map, HeapObject* object);
2388 Context* GetCreationContext();
2390 // Enqueue change record for Object.observe. May cause GC.
2391 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2392 Handle<JSObject> object, const char* type, Handle<Name> name,
2393 Handle<Object> old_value);
2395 // Gets the number of currently used elements.
2396 int GetFastElementsUsage();
2398 // Deletes an existing named property in a normalized object.
2399 static void DeleteNormalizedProperty(Handle<JSObject> object,
2400 Handle<Name> name, int entry);
2402 static bool AllCanRead(LookupIterator* it);
2403 static bool AllCanWrite(LookupIterator* it);
2406 friend class JSReceiver;
2407 friend class Object;
2409 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2410 static void MigrateFastToSlow(Handle<JSObject> object,
2411 Handle<Map> new_map,
2412 int expected_additional_properties);
2414 // Used from Object::GetProperty().
2415 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2416 LookupIterator* it);
2418 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2419 LookupIterator* it, Handle<Object> value);
2421 // Add a property to a slow-case object.
2422 static void AddSlowProperty(Handle<JSObject> object,
2424 Handle<Object> value,
2425 PropertyAttributes attributes);
2427 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2428 LookupIterator* it);
2430 bool ReferencesObjectFromElements(FixedArray* elements,
2434 // Return the hash table backing store or the inline stored identity hash,
2435 // whatever is found.
2436 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2438 // Return the hash table backing store for hidden properties. If there is no
2439 // backing store, allocate one.
2440 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2441 Handle<JSObject> object);
2443 // Set the hidden property backing store to either a hash table or
2444 // the inline-stored identity hash.
2445 static Handle<Object> SetHiddenPropertiesHashTable(
2446 Handle<JSObject> object,
2447 Handle<Object> value);
2449 MUST_USE_RESULT Object* GetIdentityHash();
2451 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2453 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2454 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2456 // Helper for fast versions of preventExtensions, seal, and freeze.
2457 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2458 template <PropertyAttributes attrs>
2459 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2460 Handle<JSObject> object);
2462 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2466 // Common superclass for FixedArrays that allow implementations to share
2467 // common accessors and some code paths.
2468 class FixedArrayBase: public HeapObject {
2470 // [length]: length of the array.
2471 inline int length() const;
2472 inline void set_length(int value);
2474 // Get and set the length using acquire loads and release stores.
2475 inline int synchronized_length() const;
2476 inline void synchronized_set_length(int value);
2478 DECLARE_CAST(FixedArrayBase)
2480 // Layout description.
2481 // Length is smi tagged when it is stored.
2482 static const int kLengthOffset = HeapObject::kHeaderSize;
2483 static const int kHeaderSize = kLengthOffset + kPointerSize;
2487 class FixedDoubleArray;
2488 class IncrementalMarking;
2491 // FixedArray describes fixed-sized arrays with element type Object*.
2492 class FixedArray: public FixedArrayBase {
2494 // Setter and getter for elements.
2495 inline Object* get(int index) const;
2496 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2497 // Setter that uses write barrier.
2498 inline void set(int index, Object* value);
2499 inline bool is_the_hole(int index);
2501 // Setter that doesn't need write barrier.
2502 inline void set(int index, Smi* value);
2503 // Setter with explicit barrier mode.
2504 inline void set(int index, Object* value, WriteBarrierMode mode);
2506 // Setters for frequently used oddballs located in old space.
2507 inline void set_undefined(int index);
2508 inline void set_null(int index);
2509 inline void set_the_hole(int index);
2511 inline Object** GetFirstElementAddress();
2512 inline bool ContainsOnlySmisOrHoles();
2514 // Gives access to raw memory which stores the array's data.
2515 inline Object** data_start();
2517 inline void FillWithHoles(int from, int to);
2519 // Shrink length and insert filler objects.
2520 void Shrink(int length);
2522 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2524 // Copy a sub array from the receiver to dest.
2525 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2527 // Garbage collection support.
2528 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2530 // Code Generation support.
2531 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2533 // Garbage collection support.
2534 inline Object** RawFieldOfElementAt(int index);
2536 DECLARE_CAST(FixedArray)
2538 // Maximal allowed size, in bytes, of a single FixedArray.
2539 // Prevents overflowing size computations, as well as extreme memory
2541 static const int kMaxSize = 128 * MB * kPointerSize;
2542 // Maximally allowed length of a FixedArray.
2543 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2545 // Dispatched behavior.
2546 DECLARE_PRINTER(FixedArray)
2547 DECLARE_VERIFIER(FixedArray)
2549 // Checks if two FixedArrays have identical contents.
2550 bool IsEqualTo(FixedArray* other);
2553 // Swap two elements in a pair of arrays. If this array and the
2554 // numbers array are the same object, the elements are only swapped
2556 void SwapPairs(FixedArray* numbers, int i, int j);
2558 // Sort prefix of this array and the numbers array as pairs wrt. the
2559 // numbers. If the numbers array and the this array are the same
2560 // object, the prefix of this array is sorted.
2561 void SortPairs(FixedArray* numbers, uint32_t len);
2563 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2565 static inline int SizeOf(Map* map, HeapObject* object);
2569 // Set operation on FixedArray without using write barriers. Can
2570 // only be used for storing old space objects or smis.
2571 static inline void NoWriteBarrierSet(FixedArray* array,
2575 // Set operation on FixedArray without incremental write barrier. Can
2576 // only be used if the object is guaranteed to be white (whiteness witness
2578 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2583 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2585 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2589 // FixedDoubleArray describes fixed-sized arrays with element type double.
2590 class FixedDoubleArray: public FixedArrayBase {
2592 // Setter and getter for elements.
2593 inline double get_scalar(int index);
2594 inline uint64_t get_representation(int index);
2595 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2596 inline void set(int index, double value);
2597 inline void set_the_hole(int index);
2599 // Checking for the hole.
2600 inline bool is_the_hole(int index);
2602 // Garbage collection support.
2603 inline static int SizeFor(int length) {
2604 return kHeaderSize + length * kDoubleSize;
2607 // Gives access to raw memory which stores the array's data.
2608 inline double* data_start();
2610 inline void FillWithHoles(int from, int to);
2612 // Code Generation support.
2613 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2615 DECLARE_CAST(FixedDoubleArray)
2617 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2618 // Prevents overflowing size computations, as well as extreme memory
2620 static const int kMaxSize = 512 * MB;
2621 // Maximally allowed length of a FixedArray.
2622 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2624 // Dispatched behavior.
2625 DECLARE_PRINTER(FixedDoubleArray)
2626 DECLARE_VERIFIER(FixedDoubleArray)
2629 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2633 class WeakFixedArray : public FixedArray {
2635 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2636 // This function does not check if the value exists already, callers must
2637 // ensure this themselves if necessary.
2638 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2639 Handle<HeapObject> value,
2640 int* assigned_index = NULL);
2642 // Returns true if an entry was found and removed.
2643 bool Remove(Handle<HeapObject> value);
2645 class NullCallback {
2647 static void Callback(Object* value, int old_index, int new_index) {}
2650 template <class CompactionCallback>
2653 inline Object* Get(int index) const;
2654 inline void Clear(int index);
2655 inline int Length() const;
2657 inline bool IsEmptySlot(int index) const;
2658 static Object* Empty() { return Smi::FromInt(0); }
2662 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2663 void Reset(Object* maybe_array);
2670 WeakFixedArray* list_;
2672 int last_used_index_;
2673 DisallowHeapAllocation no_gc_;
2675 DISALLOW_COPY_AND_ASSIGN(Iterator);
2678 DECLARE_CAST(WeakFixedArray)
2681 static const int kLastUsedIndexIndex = 0;
2682 static const int kFirstIndex = 1;
2684 static Handle<WeakFixedArray> Allocate(
2685 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2687 static void Set(Handle<WeakFixedArray> array, int index,
2688 Handle<HeapObject> value);
2689 inline void clear(int index);
2691 inline int last_used_index() const;
2692 inline void set_last_used_index(int index);
2694 // Disallow inherited setters.
2695 void set(int index, Smi* value);
2696 void set(int index, Object* value);
2697 void set(int index, Object* value, WriteBarrierMode mode);
2698 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2702 // Generic array grows dynamically with O(1) amortized insertion.
2703 class ArrayList : public FixedArray {
2707 // Use this if GC can delete elements from the array.
2708 kReloadLengthAfterAllocation,
2710 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2711 AddMode mode = kNone);
2712 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2713 Handle<Object> obj2, AddMode = kNone);
2714 inline int Length();
2715 inline void SetLength(int length);
2716 inline Object* Get(int index);
2717 inline Object** Slot(int index);
2718 inline void Set(int index, Object* obj);
2719 inline void Clear(int index, Object* undefined);
2720 DECLARE_CAST(ArrayList)
2723 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2724 static const int kLengthIndex = 0;
2725 static const int kFirstIndex = 1;
2726 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2730 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2731 // The format of the these objects is:
2732 // [0]: Number of descriptors
2733 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2734 // [0]: pointer to fixed array with enum cache
2735 // [1]: either Smi(0) or pointer to fixed array with indices
2737 // [2 + number of descriptors * kDescriptorSize]: start of slack
2738 class DescriptorArray: public FixedArray {
2740 // Returns true for both shared empty_descriptor_array and for smis, which the
2741 // map uses to encode additional bit fields when the descriptor array is not
2743 inline bool IsEmpty();
2745 // Returns the number of descriptors in the array.
2746 inline int number_of_descriptors();
2748 inline int number_of_descriptors_storage();
2750 inline int NumberOfSlackDescriptors();
2752 inline void SetNumberOfDescriptors(int number_of_descriptors);
2753 inline int number_of_entries();
2755 inline bool HasEnumCache();
2757 inline void CopyEnumCacheFrom(DescriptorArray* array);
2759 inline FixedArray* GetEnumCache();
2761 inline bool HasEnumIndicesCache();
2763 inline FixedArray* GetEnumIndicesCache();
2765 inline Object** GetEnumCacheSlot();
2767 void ClearEnumCache();
2769 // Initialize or change the enum cache,
2770 // using the supplied storage for the small "bridge".
2771 void SetEnumCache(FixedArray* bridge_storage,
2772 FixedArray* new_cache,
2773 Object* new_index_cache);
2775 bool CanHoldValue(int descriptor, Object* value);
2777 // Accessors for fetching instance descriptor at descriptor number.
2778 inline Name* GetKey(int descriptor_number);
2779 inline Object** GetKeySlot(int descriptor_number);
2780 inline Object* GetValue(int descriptor_number);
2781 inline void SetValue(int descriptor_number, Object* value);
2782 inline Object** GetValueSlot(int descriptor_number);
2783 static inline int GetValueOffset(int descriptor_number);
2784 inline Object** GetDescriptorStartSlot(int descriptor_number);
2785 inline Object** GetDescriptorEndSlot(int descriptor_number);
2786 inline PropertyDetails GetDetails(int descriptor_number);
2787 inline PropertyType GetType(int descriptor_number);
2788 inline int GetFieldIndex(int descriptor_number);
2789 inline HeapType* GetFieldType(int descriptor_number);
2790 inline Object* GetConstant(int descriptor_number);
2791 inline Object* GetCallbacksObject(int descriptor_number);
2792 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2794 inline Name* GetSortedKey(int descriptor_number);
2795 inline int GetSortedKeyIndex(int descriptor_number);
2796 inline void SetSortedKey(int pointer, int descriptor_number);
2797 inline void SetRepresentation(int descriptor_number,
2798 Representation representation);
2800 // Accessor for complete descriptor.
2801 inline void Get(int descriptor_number, Descriptor* desc);
2802 inline void Set(int descriptor_number, Descriptor* desc);
2803 void Replace(int descriptor_number, Descriptor* descriptor);
2805 // Append automatically sets the enumeration index. This should only be used
2806 // to add descriptors in bulk at the end, followed by sorting the descriptor
2808 inline void Append(Descriptor* desc);
2810 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2811 int enumeration_index,
2814 static Handle<DescriptorArray> CopyUpToAddAttributes(
2815 Handle<DescriptorArray> desc,
2816 int enumeration_index,
2817 PropertyAttributes attributes,
2820 // Sort the instance descriptors by the hash codes of their keys.
2823 // Search the instance descriptors for given name.
2824 INLINE(int Search(Name* name, int number_of_own_descriptors));
2826 // As the above, but uses DescriptorLookupCache and updates it when
2828 INLINE(int SearchWithCache(Name* name, Map* map));
2830 // Allocates a DescriptorArray, but returns the singleton
2831 // empty descriptor array object if number_of_descriptors is 0.
2832 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2833 int number_of_descriptors,
2836 DECLARE_CAST(DescriptorArray)
2838 // Constant for denoting key was not found.
2839 static const int kNotFound = -1;
2841 static const int kDescriptorLengthIndex = 0;
2842 static const int kEnumCacheIndex = 1;
2843 static const int kFirstIndex = 2;
2845 // The length of the "bridge" to the enum cache.
2846 static const int kEnumCacheBridgeLength = 2;
2847 static const int kEnumCacheBridgeCacheIndex = 0;
2848 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2850 // Layout description.
2851 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2852 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2853 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2855 // Layout description for the bridge array.
2856 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2858 // Layout of descriptor.
2859 static const int kDescriptorKey = 0;
2860 static const int kDescriptorDetails = 1;
2861 static const int kDescriptorValue = 2;
2862 static const int kDescriptorSize = 3;
2864 #if defined(DEBUG) || defined(OBJECT_PRINT)
2865 // For our gdb macros, we should perhaps change these in the future.
2868 // Print all the descriptors.
2869 void PrintDescriptors(std::ostream& os); // NOLINT
2873 // Is the descriptor array sorted and without duplicates?
2874 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2876 // Is the descriptor array consistent with the back pointers in targets?
2877 bool IsConsistentWithBackPointers(Map* current_map);
2879 // Are two DescriptorArrays equal?
2880 bool IsEqualTo(DescriptorArray* other);
2883 // Returns the fixed array length required to hold number_of_descriptors
2885 static int LengthFor(int number_of_descriptors) {
2886 return ToKeyIndex(number_of_descriptors);
2890 // WhitenessWitness is used to prove that a descriptor array is white
2891 // (unmarked), so incremental write barriers can be skipped because the
2892 // marking invariant cannot be broken and slots pointing into evacuation
2893 // candidates will be discovered when the object is scanned. A witness is
2894 // always stack-allocated right after creating an array. By allocating a
2895 // witness, incremental marking is globally disabled. The witness is then
2896 // passed along wherever needed to statically prove that the array is known to
2898 class WhitenessWitness {
2900 inline explicit WhitenessWitness(DescriptorArray* array);
2901 inline ~WhitenessWitness();
2904 IncrementalMarking* marking_;
2907 // An entry in a DescriptorArray, represented as an (array, index) pair.
2910 inline explicit Entry(DescriptorArray* descs, int index) :
2911 descs_(descs), index_(index) { }
2913 inline PropertyType type();
2914 inline Object* GetCallbackObject();
2917 DescriptorArray* descs_;
2921 // Conversion from descriptor number to array indices.
2922 static int ToKeyIndex(int descriptor_number) {
2923 return kFirstIndex +
2924 (descriptor_number * kDescriptorSize) +
2928 static int ToDetailsIndex(int descriptor_number) {
2929 return kFirstIndex +
2930 (descriptor_number * kDescriptorSize) +
2934 static int ToValueIndex(int descriptor_number) {
2935 return kFirstIndex +
2936 (descriptor_number * kDescriptorSize) +
2940 // Transfer a complete descriptor from the src descriptor array to this
2941 // descriptor array.
2942 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2944 inline void Set(int descriptor_number,
2946 const WhitenessWitness&);
2948 // Swap first and second descriptor.
2949 inline void SwapSortedKeys(int first, int second);
2951 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2955 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2957 template <SearchMode search_mode, typename T>
2958 inline int Search(T* array, Name* name, int valid_entries = 0,
2959 int* out_insertion_index = NULL);
2962 // HashTable is a subclass of FixedArray that implements a hash table
2963 // that uses open addressing and quadratic probing.
2965 // In order for the quadratic probing to work, elements that have not
2966 // yet been used and elements that have been deleted are
2967 // distinguished. Probing continues when deleted elements are
2968 // encountered and stops when unused elements are encountered.
2970 // - Elements with key == undefined have not been used yet.
2971 // - Elements with key == the_hole have been deleted.
2973 // The hash table class is parameterized with a Shape and a Key.
2974 // Shape must be a class with the following interface:
2975 // class ExampleShape {
2977 // // Tells whether key matches other.
2978 // static bool IsMatch(Key key, Object* other);
2979 // // Returns the hash value for key.
2980 // static uint32_t Hash(Key key);
2981 // // Returns the hash value for object.
2982 // static uint32_t HashForObject(Key key, Object* object);
2983 // // Convert key to an object.
2984 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2985 // // The prefix size indicates number of elements in the beginning
2986 // // of the backing storage.
2987 // static const int kPrefixSize = ..;
2988 // // The Element size indicates number of elements per entry.
2989 // static const int kEntrySize = ..;
2991 // The prefix size indicates an amount of memory in the
2992 // beginning of the backing storage that can be used for non-element
2993 // information by subclasses.
2995 template<typename Key>
2998 static const bool UsesSeed = false;
2999 static uint32_t Hash(Key key) { return 0; }
3000 static uint32_t SeededHash(Key key, uint32_t seed) {
3004 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3005 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3007 return HashForObject(key, object);
3012 class HashTableBase : public FixedArray {
3014 // Returns the number of elements in the hash table.
3015 inline int NumberOfElements();
3017 // Returns the number of deleted elements in the hash table.
3018 inline int NumberOfDeletedElements();
3020 // Returns the capacity of the hash table.
3021 inline int Capacity();
3023 // ElementAdded should be called whenever an element is added to a
3025 inline void ElementAdded();
3027 // ElementRemoved should be called whenever an element is removed from
3029 inline void ElementRemoved();
3030 inline void ElementsRemoved(int n);
3032 // Computes the required capacity for a table holding the given
3033 // number of elements. May be more than HashTable::kMaxCapacity.
3034 static inline int ComputeCapacity(int at_least_space_for);
3036 // Tells whether k is a real key. The hole and undefined are not allowed
3037 // as keys and can be used to indicate missing or deleted elements.
3038 inline bool IsKey(Object* k);
3040 // Compute the probe offset (quadratic probing).
3041 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3042 return (n + n * n) >> 1;
3045 static const int kNumberOfElementsIndex = 0;
3046 static const int kNumberOfDeletedElementsIndex = 1;
3047 static const int kCapacityIndex = 2;
3048 static const int kPrefixStartIndex = 3;
3050 // Constant used for denoting a absent entry.
3051 static const int kNotFound = -1;
3054 // Update the number of elements in the hash table.
3055 inline void SetNumberOfElements(int nof);
3057 // Update the number of deleted elements in the hash table.
3058 inline void SetNumberOfDeletedElements(int nod);
3060 // Returns probe entry.
3061 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3062 DCHECK(base::bits::IsPowerOfTwo32(size));
3063 return (hash + GetProbeOffset(number)) & (size - 1);
3066 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3067 return hash & (size - 1);
3070 inline static uint32_t NextProbe(
3071 uint32_t last, uint32_t number, uint32_t size) {
3072 return (last + number) & (size - 1);
3077 template <typename Derived, typename Shape, typename Key>
3078 class HashTable : public HashTableBase {
3081 inline uint32_t Hash(Key key) {
3082 if (Shape::UsesSeed) {
3083 return Shape::SeededHash(key, GetHeap()->HashSeed());
3085 return Shape::Hash(key);
3089 inline uint32_t HashForObject(Key key, Object* object) {
3090 if (Shape::UsesSeed) {
3091 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3093 return Shape::HashForObject(key, object);
3097 // Returns a new HashTable object.
3098 MUST_USE_RESULT static Handle<Derived> New(
3099 Isolate* isolate, int at_least_space_for,
3100 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3101 PretenureFlag pretenure = NOT_TENURED);
3103 DECLARE_CAST(HashTable)
3105 // Garbage collection support.
3106 void IteratePrefix(ObjectVisitor* visitor);
3107 void IterateElements(ObjectVisitor* visitor);
3109 // Find entry for key otherwise return kNotFound.
3110 inline int FindEntry(Key key);
3111 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3112 int FindEntry(Isolate* isolate, Key key);
3114 // Rehashes the table in-place.
3115 void Rehash(Key key);
3117 // Returns the key at entry.
3118 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3120 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3121 static const int kEntrySize = Shape::kEntrySize;
3122 static const int kElementsStartOffset =
3123 kHeaderSize + kElementsStartIndex * kPointerSize;
3124 static const int kCapacityOffset =
3125 kHeaderSize + kCapacityIndex * kPointerSize;
3127 // Returns the index for an entry (of the key)
3128 static inline int EntryToIndex(int entry) {
3129 return (entry * kEntrySize) + kElementsStartIndex;
3133 friend class ObjectHashTable;
3135 // Find the entry at which to insert element with the given key that
3136 // has the given hash value.
3137 uint32_t FindInsertionEntry(uint32_t hash);
3139 // Attempt to shrink hash table after removal of key.
3140 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3142 // Ensure enough space for n additional elements.
3143 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3144 Handle<Derived> table,
3147 PretenureFlag pretenure = NOT_TENURED);
3149 // Sets the capacity of the hash table.
3150 void SetCapacity(int capacity) {
3151 // To scale a computed hash code to fit within the hash table, we
3152 // use bit-wise AND with a mask, so the capacity must be positive
3154 DCHECK(capacity > 0);
3155 DCHECK(capacity <= kMaxCapacity);
3156 set(kCapacityIndex, Smi::FromInt(capacity));
3159 // Maximal capacity of HashTable. Based on maximal length of underlying
3160 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3162 static const int kMaxCapacity =
3163 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3166 // Returns _expected_ if one of entries given by the first _probe_ probes is
3167 // equal to _expected_. Otherwise, returns the entry given by the probe
3169 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3171 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3173 // Rehashes this hash-table into the new table.
3174 void Rehash(Handle<Derived> new_table, Key key);
3178 // HashTableKey is an abstract superclass for virtual key behavior.
3179 class HashTableKey {
3181 // Returns whether the other object matches this key.
3182 virtual bool IsMatch(Object* other) = 0;
3183 // Returns the hash value for this key.
3184 virtual uint32_t Hash() = 0;
3185 // Returns the hash value for object.
3186 virtual uint32_t HashForObject(Object* key) = 0;
3187 // Returns the key object for storing into the hash table.
3188 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3190 virtual ~HashTableKey() {}
3194 class StringTableShape : public BaseShape<HashTableKey*> {
3196 static inline bool IsMatch(HashTableKey* key, Object* value) {
3197 return key->IsMatch(value);
3200 static inline uint32_t Hash(HashTableKey* key) {
3204 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3205 return key->HashForObject(object);
3208 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3210 static const int kPrefixSize = 0;
3211 static const int kEntrySize = 1;
3214 class SeqOneByteString;
3218 // No special elements in the prefix and the element size is 1
3219 // because only the string itself (the key) needs to be stored.
3220 class StringTable: public HashTable<StringTable,
3224 // Find string in the string table. If it is not there yet, it is
3225 // added. The return value is the string found.
3226 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3227 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3228 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3230 // Tries to internalize given string and returns string handle on success
3231 // or an empty handle otherwise.
3232 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3234 Handle<String> string);
3236 // Looks up a string that is equal to the given string and returns
3237 // string handle if it is found, or an empty handle otherwise.
3238 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3240 Handle<String> str);
3241 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3246 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3248 DECLARE_CAST(StringTable)
3251 template <bool seq_one_byte>
3252 friend class JsonParser;
3254 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3258 template <typename Derived, typename Shape, typename Key>
3259 class Dictionary: public HashTable<Derived, Shape, Key> {
3260 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3263 // Returns the value at entry.
3264 Object* ValueAt(int entry) {
3265 return this->get(Derived::EntryToIndex(entry) + 1);
3268 // Set the value for entry.
3269 void ValueAtPut(int entry, Object* value) {
3270 this->set(Derived::EntryToIndex(entry) + 1, value);
3273 // Returns the property details for the property at entry.
3274 PropertyDetails DetailsAt(int entry) {
3275 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3278 // Set the details for entry.
3279 void DetailsAtPut(int entry, PropertyDetails value) {
3280 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3283 // Returns true if property at given entry is deleted.
3284 bool IsDeleted(int entry) {
3285 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3288 // Delete a property from the dictionary.
3289 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3291 // Attempt to shrink the dictionary after deletion of key.
3292 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3293 Handle<Derived> dictionary,
3295 return DerivedHashTable::Shrink(dictionary, key);
3299 // TODO(dcarney): templatize or move to SeededNumberDictionary
3300 void CopyValuesTo(FixedArray* elements);
3302 // Returns the number of elements in the dictionary filtering out properties
3303 // with the specified attributes.
3304 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3306 // Returns the number of enumerable elements in the dictionary.
3307 int NumberOfEnumElements() {
3308 return NumberOfElementsFilterAttributes(
3309 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3312 // Returns true if the dictionary contains any elements that are non-writable,
3313 // non-configurable, non-enumerable, or have getters/setters.
3314 bool HasComplexElements();
3316 enum SortMode { UNSORTED, SORTED };
3318 // Fill in details for properties into storage.
3319 // Returns the number of properties added.
3320 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3321 SortMode sort_mode);
3323 // Copies enumerable keys to preallocated fixed array.
3324 void CopyEnumKeysTo(FixedArray* storage);
3326 // Accessors for next enumeration index.
3327 void SetNextEnumerationIndex(int index) {
3329 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3332 int NextEnumerationIndex() {
3333 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3336 // Creates a new dictionary.
3337 MUST_USE_RESULT static Handle<Derived> New(
3339 int at_least_space_for,
3340 PretenureFlag pretenure = NOT_TENURED);
3342 // Ensure enough space for n additional elements.
3343 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3346 void Print(std::ostream& os); // NOLINT
3348 // Returns the key (slow).
3349 Object* SlowReverseLookup(Object* value);
3351 // Sets the entry to (key, value) pair.
3352 inline void SetEntry(int entry,
3354 Handle<Object> value);
3355 inline void SetEntry(int entry,
3357 Handle<Object> value,
3358 PropertyDetails details);
3360 MUST_USE_RESULT static Handle<Derived> Add(
3361 Handle<Derived> dictionary,
3363 Handle<Object> value,
3364 PropertyDetails details);
3366 // Returns iteration indices array for the |dictionary|.
3367 // Values are direct indices in the |HashTable| array.
3368 static Handle<FixedArray> BuildIterationIndicesArray(
3369 Handle<Derived> dictionary);
3372 // Generic at put operation.
3373 MUST_USE_RESULT static Handle<Derived> AtPut(
3374 Handle<Derived> dictionary,
3376 Handle<Object> value);
3378 // Add entry to dictionary.
3379 static void AddEntry(
3380 Handle<Derived> dictionary,
3382 Handle<Object> value,
3383 PropertyDetails details,
3386 // Generate new enumeration indices to avoid enumeration index overflow.
3387 // Returns iteration indices array for the |dictionary|.
3388 static Handle<FixedArray> GenerateNewEnumerationIndices(
3389 Handle<Derived> dictionary);
3390 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3391 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3395 template <typename Derived, typename Shape>
3396 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3397 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3400 // Find entry for key, otherwise return kNotFound. Optimized version of
3401 // HashTable::FindEntry.
3402 int FindEntry(Handle<Name> key);
3406 template <typename Key>
3407 class BaseDictionaryShape : public BaseShape<Key> {
3409 template <typename Dictionary>
3410 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3411 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3412 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3413 return PropertyDetails(
3414 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3417 template <typename Dictionary>
3418 static inline void DetailsAtPut(Dictionary* dict, int entry,
3419 PropertyDetails value) {
3420 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3421 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3424 template <typename Dictionary>
3425 static bool IsDeleted(Dictionary* dict, int entry) {
3429 template <typename Dictionary>
3430 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3431 Handle<Object> value, PropertyDetails details);
3435 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3437 static inline bool IsMatch(Handle<Name> key, Object* other);
3438 static inline uint32_t Hash(Handle<Name> key);
3439 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3440 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3441 static const int kPrefixSize = 2;
3442 static const int kEntrySize = 3;
3443 static const bool kIsEnumerable = true;
3447 class NameDictionary
3448 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3449 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3453 DECLARE_CAST(NameDictionary)
3455 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3456 Handle<NameDictionary> dictionary);
3460 class GlobalDictionaryShape : public NameDictionaryShape {
3462 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3464 template <typename Dictionary>
3465 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3467 template <typename Dictionary>
3468 static inline void DetailsAtPut(Dictionary* dict, int entry,
3469 PropertyDetails value);
3471 template <typename Dictionary>
3472 static bool IsDeleted(Dictionary* dict, int entry);
3474 template <typename Dictionary>
3475 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3476 Handle<Object> value, PropertyDetails details);
3480 class GlobalDictionary
3481 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3483 DECLARE_CAST(GlobalDictionary)
3487 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3489 static inline bool IsMatch(uint32_t key, Object* other);
3490 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3491 static const int kEntrySize = 3;
3492 static const bool kIsEnumerable = false;
3496 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3498 static const bool UsesSeed = true;
3499 static const int kPrefixSize = 2;
3501 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3502 static inline uint32_t SeededHashForObject(uint32_t key,
3508 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3510 static const int kPrefixSize = 0;
3512 static inline uint32_t Hash(uint32_t key);
3513 static inline uint32_t HashForObject(uint32_t key, Object* object);
3517 class SeededNumberDictionary
3518 : public Dictionary<SeededNumberDictionary,
3519 SeededNumberDictionaryShape,
3522 DECLARE_CAST(SeededNumberDictionary)
3524 // Type specific at put (default NONE attributes is used when adding).
3525 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3526 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3527 Handle<Object> value, bool used_as_prototype);
3528 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3529 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3530 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3532 // Set an existing entry or add a new one if needed.
3533 // Return the updated dictionary.
3534 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3535 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3536 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3538 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3540 // If slow elements are required we will never go back to fast-case
3541 // for the elements kept in this dictionary. We require slow
3542 // elements if an element has been added at an index larger than
3543 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3544 // when defining a getter or setter with a number key.
3545 inline bool requires_slow_elements();
3546 inline void set_requires_slow_elements();
3548 // Get the value of the max number key that has been added to this
3549 // dictionary. max_number_key can only be called if
3550 // requires_slow_elements returns false.
3551 inline uint32_t max_number_key();
3554 static const int kRequiresSlowElementsMask = 1;
3555 static const int kRequiresSlowElementsTagSize = 1;
3556 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3560 class UnseededNumberDictionary
3561 : public Dictionary<UnseededNumberDictionary,
3562 UnseededNumberDictionaryShape,
3565 DECLARE_CAST(UnseededNumberDictionary)
3567 // Type specific at put (default NONE attributes is used when adding).
3568 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3569 Handle<UnseededNumberDictionary> dictionary,
3571 Handle<Object> value);
3572 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3573 Handle<UnseededNumberDictionary> dictionary,
3575 Handle<Object> value);
3577 // Set an existing entry or add a new one if needed.
3578 // Return the updated dictionary.
3579 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3580 Handle<UnseededNumberDictionary> dictionary,
3582 Handle<Object> value);
3586 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3588 static inline bool IsMatch(Handle<Object> key, Object* other);
3589 static inline uint32_t Hash(Handle<Object> key);
3590 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3591 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3592 static const int kPrefixSize = 0;
3593 static const int kEntrySize = 2;
3597 // ObjectHashTable maps keys that are arbitrary objects to object values by
3598 // using the identity hash of the key for hashing purposes.
3599 class ObjectHashTable: public HashTable<ObjectHashTable,
3600 ObjectHashTableShape,
3603 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3605 DECLARE_CAST(ObjectHashTable)
3607 // Attempt to shrink hash table after removal of key.
3608 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3609 Handle<ObjectHashTable> table,
3610 Handle<Object> key);
3612 // Looks up the value associated with the given key. The hole value is
3613 // returned in case the key is not present.
3614 Object* Lookup(Handle<Object> key);
3615 Object* Lookup(Handle<Object> key, int32_t hash);
3616 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3618 // Adds (or overwrites) the value associated with the given key.
3619 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3621 Handle<Object> value);
3622 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3623 Handle<Object> key, Handle<Object> value,
3626 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3627 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3630 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3631 Handle<Object> key, bool* was_present,
3635 friend class MarkCompactCollector;
3637 void AddEntry(int entry, Object* key, Object* value);
3638 void RemoveEntry(int entry);
3640 // Returns the index to the value of an entry.
3641 static inline int EntryToValueIndex(int entry) {
3642 return EntryToIndex(entry) + 1;
3647 // OrderedHashTable is a HashTable with Object keys that preserves
3648 // insertion order. There are Map and Set interfaces (OrderedHashMap
3649 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3651 // Only Object* keys are supported, with Object::SameValueZero() used as the
3652 // equality operator and Object::GetHash() for the hash function.
3654 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3655 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3656 // Originally attributed to Tyler Close.
3659 // [0]: bucket count
3660 // [1]: element count
3661 // [2]: deleted element count
3662 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3663 // offset into the data table (see below) where the
3664 // first item in this bucket is stored.
3665 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3666 // Capacity() * kEntrySize, where the first entrysize
3667 // items are handled by the derived class and the
3668 // item at kChainOffset is another entry into the
3669 // data table indicating the next entry in this hash
3672 // When we transition the table to a new version we obsolete it and reuse parts
3673 // of the memory to store information how to transition an iterator to the new
3676 // Memory layout for obsolete table:
3677 // [0]: bucket count
3678 // [1]: Next newer table
3679 // [2]: Number of removed holes or -1 when the table was cleared.
3680 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3681 // [3 + NumberOfRemovedHoles()..length]: Not used
3683 template<class Derived, class Iterator, int entrysize>
3684 class OrderedHashTable: public FixedArray {
3686 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3687 static Handle<Derived> Allocate(
3688 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3690 // Returns an OrderedHashTable (possibly |table|) with enough space
3691 // to add at least one new element.
3692 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3694 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3696 static Handle<Derived> Shrink(Handle<Derived> table);
3698 // Returns a new empty OrderedHashTable and records the clearing so that
3699 // exisiting iterators can be updated.
3700 static Handle<Derived> Clear(Handle<Derived> table);
3702 // Returns a true if the OrderedHashTable contains the key
3703 static bool HasKey(Handle<Derived> table, Handle<Object> key);
3705 int NumberOfElements() {
3706 return Smi::cast(get(kNumberOfElementsIndex))->value();
3709 int NumberOfDeletedElements() {
3710 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3713 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3715 int NumberOfBuckets() {
3716 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3719 // Returns an index into |this| for the given entry.
3720 int EntryToIndex(int entry) {
3721 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3724 int HashToBucket(int hash) { return hash & (NumberOfBuckets() - 1); }
3726 int HashToEntry(int hash) {
3727 int bucket = HashToBucket(hash);
3728 Object* entry = this->get(kHashTableStartIndex + bucket);
3729 return Smi::cast(entry)->value();
3732 int KeyToFirstEntry(Object* key) {
3733 Object* hash = key->GetHash();
3734 // If the object does not have an identity hash, it was never used as a key
3735 if (hash->IsUndefined()) return kNotFound;
3736 return HashToEntry(Smi::cast(hash)->value());
3739 int NextChainEntry(int entry) {
3740 Object* next_entry = get(EntryToIndex(entry) + kChainOffset);
3741 return Smi::cast(next_entry)->value();
3744 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3747 return !get(kNextTableIndex)->IsSmi();
3750 // The next newer table. This is only valid if the table is obsolete.
3751 Derived* NextTable() {
3752 return Derived::cast(get(kNextTableIndex));
3755 // When the table is obsolete we store the indexes of the removed holes.
3756 int RemovedIndexAt(int index) {
3757 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3760 static const int kNotFound = -1;
3761 static const int kMinCapacity = 4;
3763 static const int kNumberOfBucketsIndex = 0;
3764 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3765 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3766 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3767 static const int kNextTableIndex = kNumberOfElementsIndex;
3769 static const int kNumberOfBucketsOffset =
3770 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3771 static const int kNumberOfElementsOffset =
3772 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3773 static const int kNumberOfDeletedElementsOffset =
3774 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3775 static const int kHashTableStartOffset =
3776 kHeaderSize + kHashTableStartIndex * kPointerSize;
3777 static const int kNextTableOffset =
3778 kHeaderSize + kNextTableIndex * kPointerSize;
3780 static const int kEntrySize = entrysize + 1;
3781 static const int kChainOffset = entrysize;
3783 static const int kLoadFactor = 2;
3785 // NumberOfDeletedElements is set to kClearedTableSentinel when
3786 // the table is cleared, which allows iterator transitions to
3787 // optimize that case.
3788 static const int kClearedTableSentinel = -1;
3791 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3793 void SetNumberOfBuckets(int num) {
3794 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3797 void SetNumberOfElements(int num) {
3798 set(kNumberOfElementsIndex, Smi::FromInt(num));
3801 void SetNumberOfDeletedElements(int num) {
3802 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3806 return NumberOfBuckets() * kLoadFactor;
3809 void SetNextTable(Derived* next_table) {
3810 set(kNextTableIndex, next_table);
3813 void SetRemovedIndexAt(int index, int removed_index) {
3814 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3817 static const int kRemovedHolesIndex = kHashTableStartIndex;
3819 static const int kMaxCapacity =
3820 (FixedArray::kMaxLength - kHashTableStartIndex)
3821 / (1 + (kEntrySize * kLoadFactor));
3825 class JSSetIterator;
3828 class OrderedHashSet: public OrderedHashTable<
3829 OrderedHashSet, JSSetIterator, 1> {
3831 DECLARE_CAST(OrderedHashSet)
3833 static Handle<OrderedHashSet> Add(Handle<OrderedHashSet> table,
3834 Handle<Object> value);
3838 class JSMapIterator;
3841 class OrderedHashMap
3842 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3844 DECLARE_CAST(OrderedHashMap)
3846 inline Object* ValueAt(int entry);
3848 static const int kValueOffset = 1;
3852 template <int entrysize>
3853 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3855 static inline bool IsMatch(Handle<Object> key, Object* other);
3856 static inline uint32_t Hash(Handle<Object> key);
3857 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3858 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3859 static const int kPrefixSize = 0;
3860 static const int kEntrySize = entrysize;
3864 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3865 // values. The table wraps the keys in weak cells and store values directly.
3866 // Thus it references keys weakly and values strongly.
3867 class WeakHashTable: public HashTable<WeakHashTable,
3868 WeakHashTableShape<2>,
3871 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3873 DECLARE_CAST(WeakHashTable)
3875 // Looks up the value associated with the given key. The hole value is
3876 // returned in case the key is not present.
3877 Object* Lookup(Handle<HeapObject> key);
3879 // Adds (or overwrites) the value associated with the given key. Mapping a
3880 // key to the hole value causes removal of the whole entry.
3881 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3882 Handle<HeapObject> key,
3883 Handle<HeapObject> value);
3885 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3888 friend class MarkCompactCollector;
3890 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3892 // Returns the index to the value of an entry.
3893 static inline int EntryToValueIndex(int entry) {
3894 return EntryToIndex(entry) + 1;
3899 // ScopeInfo represents information about different scopes of a source
3900 // program and the allocation of the scope's variables. Scope information
3901 // is stored in a compressed form in ScopeInfo objects and is used
3902 // at runtime (stack dumps, deoptimization, etc.).
3904 // This object provides quick access to scope info details for runtime
3906 class ScopeInfo : public FixedArray {
3908 DECLARE_CAST(ScopeInfo)
3910 // Return the type of this scope.
3911 ScopeType scope_type();
3913 // Does this scope call eval?
3916 // Return the language mode of this scope.
3917 LanguageMode language_mode();
3919 // True if this scope is a (var) declaration scope.
3920 bool is_declaration_scope();
3922 // Does this scope make a sloppy eval call?
3923 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3925 // Return the total number of locals allocated on the stack and in the
3926 // context. This includes the parameters that are allocated in the context.
3929 // Return the number of stack slots for code. This number consists of two
3931 // 1. One stack slot per stack allocated local.
3932 // 2. One stack slot for the function name if it is stack allocated.
3933 int StackSlotCount();
3935 // Return the number of context slots for code if a context is allocated. This
3936 // number consists of three parts:
3937 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3938 // 2. One context slot per context allocated local.
3939 // 3. One context slot for the function name if it is context allocated.
3940 // Parameters allocated in the context count as context allocated locals. If
3941 // no contexts are allocated for this scope ContextLength returns 0.
3942 int ContextLength();
3944 // Does this scope declare a "this" binding?
3947 // Does this scope declare a "this" binding, and the "this" binding is stack-
3948 // or context-allocated?
3949 bool HasAllocatedReceiver();
3951 // Is this scope the scope of a named function expression?
3952 bool HasFunctionName();
3954 // Return if this has context allocated locals.
3955 bool HasHeapAllocatedLocals();
3957 // Return if contexts are allocated for this scope.
3960 // Return if this is a function scope with "use asm".
3961 inline bool IsAsmModule();
3963 // Return if this is a nested function within an asm module scope.
3964 inline bool IsAsmFunction();
3966 inline bool HasSimpleParameters();
3968 // Return the function_name if present.
3969 String* FunctionName();
3971 // Return the name of the given parameter.
3972 String* ParameterName(int var);
3974 // Return the name of the given local.
3975 String* LocalName(int var);
3977 // Return the name of the given stack local.
3978 String* StackLocalName(int var);
3980 // Return the name of the given stack local.
3981 int StackLocalIndex(int var);
3983 // Return the name of the given context local.
3984 String* ContextLocalName(int var);
3986 // Return the mode of the given context local.
3987 VariableMode ContextLocalMode(int var);
3989 // Return the initialization flag of the given context local.
3990 InitializationFlag ContextLocalInitFlag(int var);
3992 // Return the initialization flag of the given context local.
3993 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3995 // Return true if this local was introduced by the compiler, and should not be
3996 // exposed to the user in a debugger.
3997 bool LocalIsSynthetic(int var);
3999 String* StrongModeFreeVariableName(int var);
4000 int StrongModeFreeVariableStartPosition(int var);
4001 int StrongModeFreeVariableEndPosition(int var);
4003 // Lookup support for serialized scope info. Returns the
4004 // the stack slot index for a given slot name if the slot is
4005 // present; otherwise returns a value < 0. The name must be an internalized
4007 int StackSlotIndex(String* name);
4009 // Lookup support for serialized scope info. Returns the local context slot
4010 // index for a given slot name if the slot is present; otherwise
4011 // returns a value < 0. The name must be an internalized string.
4012 // If the slot is present and mode != NULL, sets *mode to the corresponding
4013 // mode for that variable.
4014 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
4015 VariableMode* mode, InitializationFlag* init_flag,
4016 MaybeAssignedFlag* maybe_assigned_flag);
4018 // Similar to ContextSlotIndex() but this method searches only among
4019 // global slots of the serialized scope info. Returns the context slot index
4020 // for a given slot name if the slot is present; otherwise returns a
4021 // value < 0. The name must be an internalized string. If the slot is present
4022 // and mode != NULL, sets *mode to the corresponding mode for that variable.
4023 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
4024 Handle<String> name, VariableMode* mode,
4025 InitializationFlag* init_flag,
4026 MaybeAssignedFlag* maybe_assigned_flag);
4028 // Lookup the name of a certain context slot by its index.
4029 String* ContextSlotName(int slot_index);
4031 // Lookup support for serialized scope info. Returns the
4032 // parameter index for a given parameter name if the parameter is present;
4033 // otherwise returns a value < 0. The name must be an internalized string.
4034 int ParameterIndex(String* name);
4036 // Lookup support for serialized scope info. Returns the function context
4037 // slot index if the function name is present and context-allocated (named
4038 // function expressions, only), otherwise returns a value < 0. The name
4039 // must be an internalized string.
4040 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4042 // Lookup support for serialized scope info. Returns the receiver context
4043 // slot index if scope has a "this" binding, and the binding is
4044 // context-allocated. Otherwise returns a value < 0.
4045 int ReceiverContextSlotIndex();
4047 FunctionKind function_kind();
4049 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4050 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4052 // Serializes empty scope info.
4053 static ScopeInfo* Empty(Isolate* isolate);
4059 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4060 // numeric and occupies one array slot.
4061 // 1. A set of properties of the scope
4062 // 2. The number of parameters. This only applies to function scopes. For
4063 // non-function scopes this is 0.
4064 // 3. The number of non-parameter variables allocated on the stack.
4065 // 4. The number of non-parameter and parameter variables allocated in the
4067 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4070 V(StackLocalCount) \
4071 V(ContextLocalCount) \
4072 V(ContextGlobalCount) \
4073 V(StrongModeFreeVariableCount)
4075 #define FIELD_ACCESSORS(name) \
4076 inline void Set##name(int value); \
4078 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4079 #undef FIELD_ACCESSORS
4082 #define DECL_INDEX(name) k##name,
4083 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4089 // The layout of the variable part of a ScopeInfo is as follows:
4090 // 1. ParameterEntries:
4091 // This part stores the names of the parameters for function scopes. One
4092 // slot is used per parameter, so in total this part occupies
4093 // ParameterCount() slots in the array. For other scopes than function
4094 // scopes ParameterCount() is 0.
4095 // 2. StackLocalFirstSlot:
4096 // Index of a first stack slot for stack local. Stack locals belonging to
4097 // this scope are located on a stack at slots starting from this index.
4098 // 3. StackLocalEntries:
4099 // Contains the names of local variables that are allocated on the stack,
4100 // in increasing order of the stack slot index. First local variable has
4101 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4102 // One slot is used per stack local, so in total this part occupies
4103 // StackLocalCount() slots in the array.
4104 // 4. ContextLocalNameEntries:
4105 // Contains the names of local variables and parameters that are allocated
4106 // in the context. They are stored in increasing order of the context slot
4107 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4108 // context local, so in total this part occupies ContextLocalCount() slots
4110 // 5. ContextLocalInfoEntries:
4111 // Contains the variable modes and initialization flags corresponding to
4112 // the context locals in ContextLocalNameEntries. One slot is used per
4113 // context local, so in total this part occupies ContextLocalCount()
4114 // slots in the array.
4115 // 6. StrongModeFreeVariableNameEntries:
4116 // Stores the names of strong mode free variables.
4117 // 7. StrongModeFreeVariablePositionEntries:
4118 // Stores the locations (start and end position) of strong mode free
4120 // 8. RecieverEntryIndex:
4121 // If the scope binds a "this" value, one slot is reserved to hold the
4122 // context or stack slot index for the variable.
4123 // 9. FunctionNameEntryIndex:
4124 // If the scope belongs to a named function expression this part contains
4125 // information about the function variable. It always occupies two array
4126 // slots: a. The name of the function variable.
4127 // b. The context or stack slot index for the variable.
4128 int ParameterEntriesIndex();
4129 int StackLocalFirstSlotIndex();
4130 int StackLocalEntriesIndex();
4131 int ContextLocalNameEntriesIndex();
4132 int ContextGlobalNameEntriesIndex();
4133 int ContextLocalInfoEntriesIndex();
4134 int ContextGlobalInfoEntriesIndex();
4135 int StrongModeFreeVariableNameEntriesIndex();
4136 int StrongModeFreeVariablePositionEntriesIndex();
4137 int ReceiverEntryIndex();
4138 int FunctionNameEntryIndex();
4140 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4141 VariableLocation* location, InitializationFlag* init_flag,
4142 MaybeAssignedFlag* maybe_assigned_flag);
4144 // Used for the function name variable for named function expressions, and for
4146 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4148 // Properties of scopes.
4149 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4150 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4151 STATIC_ASSERT(LANGUAGE_END == 3);
4152 class LanguageModeField
4153 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4154 class DeclarationScopeField
4155 : public BitField<bool, LanguageModeField::kNext, 1> {};
4156 class ReceiverVariableField
4157 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4159 class FunctionVariableField
4160 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4162 class FunctionVariableMode
4163 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4164 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4166 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4167 class HasSimpleParametersField
4168 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4169 class FunctionKindField
4170 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4172 // BitFields representing the encoded information for context locals in the
4173 // ContextLocalInfoEntries part.
4174 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4175 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4176 class ContextLocalMaybeAssignedFlag
4177 : public BitField<MaybeAssignedFlag, 4, 1> {};
4179 friend class ScopeIterator;
4183 // The cache for maps used by normalized (dictionary mode) objects.
4184 // Such maps do not have property descriptors, so a typical program
4185 // needs very limited number of distinct normalized maps.
4186 class NormalizedMapCache: public FixedArray {
4188 static Handle<NormalizedMapCache> New(Isolate* isolate);
4190 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4191 PropertyNormalizationMode mode);
4192 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4196 DECLARE_CAST(NormalizedMapCache)
4198 static inline bool IsNormalizedMapCache(const Object* obj);
4200 DECLARE_VERIFIER(NormalizedMapCache)
4202 static const int kEntries = 64;
4204 static inline int GetIndex(Handle<Map> map);
4206 // The following declarations hide base class methods.
4207 Object* get(int index);
4208 void set(int index, Object* value);
4212 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4213 // that is attached to code objects.
4214 class ByteArray: public FixedArrayBase {
4218 // Setter and getter.
4219 inline byte get(int index);
4220 inline void set(int index, byte value);
4222 // Treat contents as an int array.
4223 inline int get_int(int index);
4225 static int SizeFor(int length) {
4226 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4228 // We use byte arrays for free blocks in the heap. Given a desired size in
4229 // bytes that is a multiple of the word size and big enough to hold a byte
4230 // array, this function returns the number of elements a byte array should
4232 static int LengthFor(int size_in_bytes) {
4233 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4234 DCHECK(size_in_bytes >= kHeaderSize);
4235 return size_in_bytes - kHeaderSize;
4238 // Returns data start address.
4239 inline Address GetDataStartAddress();
4241 // Returns a pointer to the ByteArray object for a given data start address.
4242 static inline ByteArray* FromDataStartAddress(Address address);
4244 DECLARE_CAST(ByteArray)
4246 // Dispatched behavior.
4247 inline int ByteArraySize();
4248 DECLARE_PRINTER(ByteArray)
4249 DECLARE_VERIFIER(ByteArray)
4251 // Layout description.
4252 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4254 // Maximal memory consumption for a single ByteArray.
4255 static const int kMaxSize = 512 * MB;
4256 // Maximal length of a single ByteArray.
4257 static const int kMaxLength = kMaxSize - kHeaderSize;
4260 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4264 // BytecodeArray represents a sequence of interpreter bytecodes.
4265 class BytecodeArray : public FixedArrayBase {
4267 static int SizeFor(int length) {
4268 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4271 // Setter and getter
4272 inline byte get(int index);
4273 inline void set(int index, byte value);
4275 // Returns data start address.
4276 inline Address GetFirstBytecodeAddress();
4278 // Accessors for frame size.
4279 inline int frame_size() const;
4280 inline void set_frame_size(int frame_size);
4282 // Accessor for register count (derived from frame_size).
4283 inline int register_count() const;
4285 // Accessors for parameter count (including implicit 'this' receiver).
4286 inline int parameter_count() const;
4287 inline void set_parameter_count(int number_of_parameters);
4289 // Accessors for the constant pool.
4290 DECL_ACCESSORS(constant_pool, FixedArray)
4292 DECLARE_CAST(BytecodeArray)
4294 // Dispatched behavior.
4295 inline int BytecodeArraySize();
4296 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4298 DECLARE_PRINTER(BytecodeArray)
4299 DECLARE_VERIFIER(BytecodeArray)
4301 void Disassemble(std::ostream& os);
4303 // Layout description.
4304 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4305 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4306 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4307 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4309 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4311 // Maximal memory consumption for a single BytecodeArray.
4312 static const int kMaxSize = 512 * MB;
4313 // Maximal length of a single BytecodeArray.
4314 static const int kMaxLength = kMaxSize - kHeaderSize;
4317 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4321 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4322 // They look like heap objects (are heap object tagged and have a map) so that
4323 // the heap remains iterable. They have a size and a next pointer.
4324 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4325 // in the free list.
4326 class FreeSpace: public HeapObject {
4328 // [size]: size of the free space including the header.
4329 inline int size() const;
4330 inline void set_size(int value);
4332 inline int nobarrier_size() const;
4333 inline void nobarrier_set_size(int value);
4337 // Accessors for the next field.
4338 inline FreeSpace* next();
4339 inline FreeSpace** next_address();
4340 inline void set_next(FreeSpace* next);
4342 inline static FreeSpace* cast(HeapObject* obj);
4344 // Dispatched behavior.
4345 DECLARE_PRINTER(FreeSpace)
4346 DECLARE_VERIFIER(FreeSpace)
4348 // Layout description.
4349 // Size is smi tagged when it is stored.
4350 static const int kSizeOffset = HeapObject::kHeaderSize;
4351 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4354 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4358 // V has parameters (Type, type, TYPE, C type, element_size)
4359 #define TYPED_ARRAYS(V) \
4360 V(Uint8, uint8, UINT8, uint8_t, 1) \
4361 V(Int8, int8, INT8, int8_t, 1) \
4362 V(Uint16, uint16, UINT16, uint16_t, 2) \
4363 V(Int16, int16, INT16, int16_t, 2) \
4364 V(Uint32, uint32, UINT32, uint32_t, 4) \
4365 V(Int32, int32, INT32, int32_t, 4) \
4366 V(Float32, float32, FLOAT32, float, 4) \
4367 V(Float64, float64, FLOAT64, double, 8) \
4368 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4371 class FixedTypedArrayBase: public FixedArrayBase {
4373 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4374 DECL_ACCESSORS(base_pointer, Object)
4376 // [external_pointer]: Contains the offset between base_pointer and the start
4377 // of the data. If the base_pointer is a nullptr, the external_pointer
4378 // therefore points to the actual backing store.
4379 DECL_ACCESSORS(external_pointer, void)
4381 // Dispatched behavior.
4382 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4384 template <typename StaticVisitor>
4385 inline void FixedTypedArrayBaseIterateBody();
4387 DECLARE_CAST(FixedTypedArrayBase)
4389 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4390 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4391 static const int kHeaderSize =
4392 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4394 static const int kDataOffset = kHeaderSize;
4398 static inline int TypedArraySize(InstanceType type, int length);
4399 inline int TypedArraySize(InstanceType type);
4401 // Use with care: returns raw pointer into heap.
4402 inline void* DataPtr();
4404 inline int DataSize();
4407 static inline int ElementSize(InstanceType type);
4409 inline int DataSize(InstanceType type);
4411 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4415 template <class Traits>
4416 class FixedTypedArray: public FixedTypedArrayBase {
4418 typedef typename Traits::ElementType ElementType;
4419 static const InstanceType kInstanceType = Traits::kInstanceType;
4421 DECLARE_CAST(FixedTypedArray<Traits>)
4423 inline ElementType get_scalar(int index);
4424 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4425 inline void set(int index, ElementType value);
4427 static inline ElementType from_int(int value);
4428 static inline ElementType from_double(double value);
4430 // This accessor applies the correct conversion from Smi, HeapNumber
4432 inline void SetValue(uint32_t index, Object* value);
4434 DECLARE_PRINTER(FixedTypedArray)
4435 DECLARE_VERIFIER(FixedTypedArray)
4438 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4441 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4442 class Type##ArrayTraits { \
4443 public: /* NOLINT */ \
4444 typedef elementType ElementType; \
4445 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4446 static const char* Designator() { return #type " array"; } \
4447 static inline Handle<Object> ToHandle(Isolate* isolate, \
4448 elementType scalar); \
4449 static inline elementType defaultValue(); \
4452 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4454 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4456 #undef FIXED_TYPED_ARRAY_TRAITS
4459 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4460 // data for code generated by the Hydrogen/Lithium compiler. It also
4461 // contains information about functions that were inlined. If N different
4462 // functions were inlined then first N elements of the literal array will
4463 // contain these functions.
4466 class DeoptimizationInputData: public FixedArray {
4468 // Layout description. Indices in the array.
4469 static const int kTranslationByteArrayIndex = 0;
4470 static const int kInlinedFunctionCountIndex = 1;
4471 static const int kLiteralArrayIndex = 2;
4472 static const int kOsrAstIdIndex = 3;
4473 static const int kOsrPcOffsetIndex = 4;
4474 static const int kOptimizationIdIndex = 5;
4475 static const int kSharedFunctionInfoIndex = 6;
4476 static const int kWeakCellCacheIndex = 7;
4477 static const int kFirstDeoptEntryIndex = 8;
4479 // Offsets of deopt entry elements relative to the start of the entry.
4480 static const int kAstIdRawOffset = 0;
4481 static const int kTranslationIndexOffset = 1;
4482 static const int kArgumentsStackHeightOffset = 2;
4483 static const int kPcOffset = 3;
4484 static const int kDeoptEntrySize = 4;
4486 // Simple element accessors.
4487 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4488 inline type* name(); \
4489 inline void Set##name(type* value);
4491 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4492 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4493 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4494 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4495 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4496 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4497 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4498 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4500 #undef DECLARE_ELEMENT_ACCESSORS
4502 // Accessors for elements of the ith deoptimization entry.
4503 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4504 inline type* name(int i); \
4505 inline void Set##name(int i, type* value);
4507 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4508 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4509 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4510 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4512 #undef DECLARE_ENTRY_ACCESSORS
4514 inline BailoutId AstId(int i);
4516 inline void SetAstId(int i, BailoutId value);
4518 inline int DeoptCount();
4520 // Allocates a DeoptimizationInputData.
4521 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4522 int deopt_entry_count,
4523 PretenureFlag pretenure);
4525 DECLARE_CAST(DeoptimizationInputData)
4527 #ifdef ENABLE_DISASSEMBLER
4528 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4532 static int IndexForEntry(int i) {
4533 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4537 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4541 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4542 // data for code generated by the full compiler.
4543 // The format of the these objects is
4544 // [i * 2]: Ast ID for ith deoptimization.
4545 // [i * 2 + 1]: PC and state of ith deoptimization
4546 class DeoptimizationOutputData: public FixedArray {
4548 inline int DeoptPoints();
4550 inline BailoutId AstId(int index);
4552 inline void SetAstId(int index, BailoutId id);
4554 inline Smi* PcAndState(int index);
4555 inline void SetPcAndState(int index, Smi* offset);
4557 static int LengthOfFixedArray(int deopt_points) {
4558 return deopt_points * 2;
4561 // Allocates a DeoptimizationOutputData.
4562 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4563 int number_of_deopt_points,
4564 PretenureFlag pretenure);
4566 DECLARE_CAST(DeoptimizationOutputData)
4568 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4569 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4574 // A literals array contains the literals for a JSFunction. It also holds
4575 // the type feedback vector.
4576 class LiteralsArray : public FixedArray {
4578 static const int kVectorIndex = 0;
4579 static const int kFirstLiteralIndex = 1;
4580 static const int kOffsetToFirstLiteral =
4581 FixedArray::kHeaderSize + kPointerSize;
4583 static int OffsetOfLiteralAt(int index) {
4584 return SizeFor(index + kFirstLiteralIndex);
4587 inline TypeFeedbackVector* feedback_vector() const;
4588 inline void set_feedback_vector(TypeFeedbackVector* vector);
4589 inline Object* literal(int literal_index) const;
4590 inline void set_literal(int literal_index, Object* literal);
4591 inline int literals_count() const;
4593 static Handle<LiteralsArray> New(Isolate* isolate,
4594 Handle<TypeFeedbackVector> vector,
4595 int number_of_literals,
4596 PretenureFlag pretenure);
4598 DECLARE_CAST(LiteralsArray)
4601 inline Object* get(int index) const;
4602 inline void set(int index, Object* value);
4603 inline void set(int index, Smi* value);
4604 inline void set(int index, Object* value, WriteBarrierMode mode);
4608 // HandlerTable is a fixed array containing entries for exception handlers in
4609 // the code object it is associated with. The tables comes in two flavors:
4610 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4611 // exception handler and a range representing the try-block covered by that
4612 // handler. Layout looks as follows:
4613 // [ range-start , range-end , handler-offset , stack-depth ]
4614 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4615 // per call-site that could throw an exception. Layout looks as follows:
4616 // [ return-address-offset , handler-offset ]
4617 class HandlerTable : public FixedArray {
4619 // Conservative prediction whether a given handler will locally catch an
4620 // exception or cause a re-throw to outside the code boundary. Since this is
4621 // undecidable it is merely an approximation (e.g. useful for debugger).
4622 enum CatchPrediction { UNCAUGHT, CAUGHT };
4624 // Accessors for handler table based on ranges.
4625 inline void SetRangeStart(int index, int value);
4626 inline void SetRangeEnd(int index, int value);
4627 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4628 inline void SetRangeDepth(int index, int value);
4630 // Accessors for handler table based on return addresses.
4631 inline void SetReturnOffset(int index, int value);
4632 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4634 // Lookup handler in a table based on ranges.
4635 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4637 // Lookup handler in a table based on return addresses.
4638 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4640 // Returns the required length of the underlying fixed array.
4641 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4642 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4644 DECLARE_CAST(HandlerTable)
4646 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4647 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4648 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4652 // Layout description for handler table based on ranges.
4653 static const int kRangeStartIndex = 0;
4654 static const int kRangeEndIndex = 1;
4655 static const int kRangeHandlerIndex = 2;
4656 static const int kRangeDepthIndex = 3;
4657 static const int kRangeEntrySize = 4;
4659 // Layout description for handler table based on return addresses.
4660 static const int kReturnOffsetIndex = 0;
4661 static const int kReturnHandlerIndex = 1;
4662 static const int kReturnEntrySize = 2;
4664 // Encoding of the {handler} field.
4665 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4666 class HandlerOffsetField : public BitField<int, 1, 30> {};
4670 // Code describes objects with on-the-fly generated machine code.
4671 class Code: public HeapObject {
4673 // Opaque data type for encapsulating code flags like kind, inline
4674 // cache state, and arguments count.
4675 typedef uint32_t Flags;
4677 #define NON_IC_KIND_LIST(V) \
4679 V(OPTIMIZED_FUNCTION) \
4686 #define IC_KIND_LIST(V) \
4697 #define CODE_KIND_LIST(V) \
4698 NON_IC_KIND_LIST(V) \
4702 #define DEFINE_CODE_KIND_ENUM(name) name,
4703 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4704 #undef DEFINE_CODE_KIND_ENUM
4708 // No more than 16 kinds. The value is currently encoded in four bits in
4710 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4712 static const char* Kind2String(Kind kind);
4720 static const int kPrologueOffsetNotSet = -1;
4722 #ifdef ENABLE_DISASSEMBLER
4724 static const char* ICState2String(InlineCacheState state);
4725 static const char* StubType2String(StubType type);
4726 static void PrintExtraICState(std::ostream& os, // NOLINT
4727 Kind kind, ExtraICState extra);
4728 void Disassemble(const char* name, std::ostream& os); // NOLINT
4729 #endif // ENABLE_DISASSEMBLER
4731 // [instruction_size]: Size of the native instructions
4732 inline int instruction_size() const;
4733 inline void set_instruction_size(int value);
4735 // [relocation_info]: Code relocation information
4736 DECL_ACCESSORS(relocation_info, ByteArray)
4737 void InvalidateRelocation();
4738 void InvalidateEmbeddedObjects();
4740 // [handler_table]: Fixed array containing offsets of exception handlers.
4741 DECL_ACCESSORS(handler_table, FixedArray)
4743 // [deoptimization_data]: Array containing data for deopt.
4744 DECL_ACCESSORS(deoptimization_data, FixedArray)
4746 // [raw_type_feedback_info]: This field stores various things, depending on
4747 // the kind of the code object.
4748 // FUNCTION => type feedback information.
4749 // STUB and ICs => major/minor key as Smi.
4750 DECL_ACCESSORS(raw_type_feedback_info, Object)
4751 inline Object* type_feedback_info();
4752 inline void set_type_feedback_info(
4753 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4754 inline uint32_t stub_key();
4755 inline void set_stub_key(uint32_t key);
4757 // [next_code_link]: Link for lists of optimized or deoptimized code.
4758 // Note that storage for this field is overlapped with typefeedback_info.
4759 DECL_ACCESSORS(next_code_link, Object)
4761 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4762 // field does not have to be traced during garbage collection since
4763 // it is only used by the garbage collector itself.
4764 DECL_ACCESSORS(gc_metadata, Object)
4766 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4767 // at the moment when this object was created.
4768 inline void set_ic_age(int count);
4769 inline int ic_age() const;
4771 // [prologue_offset]: Offset of the function prologue, used for aging
4772 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4773 inline int prologue_offset() const;
4774 inline void set_prologue_offset(int offset);
4776 // [constant_pool offset]: Offset of the constant pool.
4777 // Valid for FLAG_enable_embedded_constant_pool only
4778 inline int constant_pool_offset() const;
4779 inline void set_constant_pool_offset(int offset);
4781 // Unchecked accessors to be used during GC.
4782 inline ByteArray* unchecked_relocation_info();
4784 inline int relocation_size();
4786 // [flags]: Various code flags.
4787 inline Flags flags();
4788 inline void set_flags(Flags flags);
4790 // [flags]: Access to specific code flags.
4792 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4793 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4795 inline StubType type(); // Only valid for monomorphic IC stubs.
4797 // Testers for IC stub kinds.
4798 inline bool is_inline_cache_stub();
4799 inline bool is_debug_stub();
4800 inline bool is_handler();
4801 inline bool is_load_stub();
4802 inline bool is_keyed_load_stub();
4803 inline bool is_store_stub();
4804 inline bool is_keyed_store_stub();
4805 inline bool is_call_stub();
4806 inline bool is_binary_op_stub();
4807 inline bool is_compare_ic_stub();
4808 inline bool is_compare_nil_ic_stub();
4809 inline bool is_to_boolean_ic_stub();
4810 inline bool is_keyed_stub();
4811 inline bool is_optimized_code();
4812 inline bool embeds_maps_weakly();
4814 inline bool IsCodeStubOrIC();
4815 inline bool IsJavaScriptCode();
4817 inline void set_raw_kind_specific_flags1(int value);
4818 inline void set_raw_kind_specific_flags2(int value);
4820 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4821 // object was generated by either the hydrogen or the TurboFan optimizing
4822 // compiler (but it may not be an optimized function).
4823 inline bool is_crankshafted();
4824 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4825 inline void set_is_crankshafted(bool value);
4827 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4828 // code object was generated by the TurboFan optimizing compiler.
4829 inline bool is_turbofanned();
4830 inline void set_is_turbofanned(bool value);
4832 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4833 // embedded objects in code should be treated weakly.
4834 inline bool can_have_weak_objects();
4835 inline void set_can_have_weak_objects(bool value);
4837 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4838 // deoptimization support.
4839 inline bool has_deoptimization_support();
4840 inline void set_has_deoptimization_support(bool value);
4842 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4843 // been compiled with debug break slots.
4844 inline bool has_debug_break_slots();
4845 inline void set_has_debug_break_slots(bool value);
4847 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4848 // reloc info includes runtime and external references to support
4849 // serialization/deserialization.
4850 inline bool has_reloc_info_for_serialization();
4851 inline void set_has_reloc_info_for_serialization(bool value);
4853 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4854 // how long the function has been marked for OSR and therefore which
4855 // level of loop nesting we are willing to do on-stack replacement
4857 inline void set_allow_osr_at_loop_nesting_level(int level);
4858 inline int allow_osr_at_loop_nesting_level();
4860 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4861 // the code object was seen on the stack with no IC patching going on.
4862 inline int profiler_ticks();
4863 inline void set_profiler_ticks(int ticks);
4865 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4866 // For builtins, tells which builtin index it has.
4867 // Note that builtins can have a code kind other than BUILTIN, which means
4868 // that for arbitrary code objects, this index value may be random garbage.
4869 // To verify in that case, compare the code object to the indexed builtin.
4870 inline int builtin_index();
4871 inline void set_builtin_index(int id);
4873 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4874 // reserved in the code prologue.
4875 inline unsigned stack_slots();
4876 inline void set_stack_slots(unsigned slots);
4878 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4879 // the instruction stream where the safepoint table starts.
4880 inline unsigned safepoint_table_offset();
4881 inline void set_safepoint_table_offset(unsigned offset);
4883 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4884 // instruction stream where the back edge table starts.
4885 inline unsigned back_edge_table_offset();
4886 inline void set_back_edge_table_offset(unsigned offset);
4888 inline bool back_edges_patched_for_osr();
4890 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4891 inline uint16_t to_boolean_state();
4893 // [has_function_cache]: For kind STUB tells whether there is a function
4894 // cache is passed to the stub.
4895 inline bool has_function_cache();
4896 inline void set_has_function_cache(bool flag);
4899 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4900 // the code is going to be deoptimized because of dead embedded maps.
4901 inline bool marked_for_deoptimization();
4902 inline void set_marked_for_deoptimization(bool flag);
4904 // [constant_pool]: The constant pool for this function.
4905 inline Address constant_pool();
4907 // Get the safepoint entry for the given pc.
4908 SafepointEntry GetSafepointEntry(Address pc);
4910 // Find an object in a stub with a specified map
4911 Object* FindNthObject(int n, Map* match_map);
4913 // Find the first allocation site in an IC stub.
4914 AllocationSite* FindFirstAllocationSite();
4916 // Find the first map in an IC stub.
4917 Map* FindFirstMap();
4918 void FindAllMaps(MapHandleList* maps);
4920 // Find the first handler in an IC stub.
4921 Code* FindFirstHandler();
4923 // Find |length| handlers and put them into |code_list|. Returns false if not
4924 // enough handlers can be found.
4925 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4927 // Find the handler for |map|.
4928 MaybeHandle<Code> FindHandlerForMap(Map* map);
4930 // Find the first name in an IC stub.
4931 Name* FindFirstName();
4933 class FindAndReplacePattern;
4934 // For each (map-to-find, object-to-replace) pair in the pattern, this
4935 // function replaces the corresponding placeholder in the code with the
4936 // object-to-replace. The function assumes that pairs in the pattern come in
4937 // the same order as the placeholders in the code.
4938 // If the placeholder is a weak cell, then the value of weak cell is matched
4939 // against the map-to-find.
4940 void FindAndReplace(const FindAndReplacePattern& pattern);
4942 // The entire code object including its header is copied verbatim to the
4943 // snapshot so that it can be written in one, fast, memcpy during
4944 // deserialization. The deserializer will overwrite some pointers, rather
4945 // like a runtime linker, but the random allocation addresses used in the
4946 // mksnapshot process would still be present in the unlinked snapshot data,
4947 // which would make snapshot production non-reproducible. This method wipes
4948 // out the to-be-overwritten header data for reproducible snapshots.
4949 inline void WipeOutHeader();
4951 // Flags operations.
4952 static inline Flags ComputeFlags(
4953 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4954 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4955 CacheHolderFlag holder = kCacheOnReceiver);
4957 static inline Flags ComputeMonomorphicFlags(
4958 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4959 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4961 static inline Flags ComputeHandlerFlags(
4962 Kind handler_kind, StubType type = NORMAL,
4963 CacheHolderFlag holder = kCacheOnReceiver);
4965 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4966 static inline StubType ExtractTypeFromFlags(Flags flags);
4967 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4968 static inline Kind ExtractKindFromFlags(Flags flags);
4969 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4971 static inline Flags RemoveTypeFromFlags(Flags flags);
4972 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4974 // Convert a target address into a code object.
4975 static inline Code* GetCodeFromTargetAddress(Address address);
4977 // Convert an entry address into an object.
4978 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4980 // Returns the address of the first instruction.
4981 inline byte* instruction_start();
4983 // Returns the address right after the last instruction.
4984 inline byte* instruction_end();
4986 // Returns the size of the instructions, padding, and relocation information.
4987 inline int body_size();
4989 // Returns the address of the first relocation info (read backwards!).
4990 inline byte* relocation_start();
4992 // Code entry point.
4993 inline byte* entry();
4995 // Returns true if pc is inside this object's instructions.
4996 inline bool contains(byte* pc);
4998 // Relocate the code by delta bytes. Called to signal that this code
4999 // object has been moved by delta bytes.
5000 void Relocate(intptr_t delta);
5002 // Migrate code described by desc.
5003 void CopyFrom(const CodeDesc& desc);
5005 // Returns the object size for a given body (used for allocation).
5006 static int SizeFor(int body_size) {
5007 DCHECK_SIZE_TAG_ALIGNED(body_size);
5008 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5011 // Calculate the size of the code object to report for log events. This takes
5012 // the layout of the code object into account.
5013 inline int ExecutableSize();
5015 // Locating source position.
5016 int SourcePosition(Address pc);
5017 int SourceStatementPosition(Address pc);
5021 // Dispatched behavior.
5022 inline int CodeSize();
5023 inline void CodeIterateBody(ObjectVisitor* v);
5025 template<typename StaticVisitor>
5026 inline void CodeIterateBody(Heap* heap);
5028 DECLARE_PRINTER(Code)
5029 DECLARE_VERIFIER(Code)
5031 void ClearInlineCaches();
5032 void ClearInlineCaches(Kind kind);
5034 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5035 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5037 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5039 kToBeExecutedOnceCodeAge = -3,
5040 kNotExecutedCodeAge = -2,
5041 kExecutedOnceCodeAge = -1,
5043 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5045 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5046 kLastCodeAge = kAfterLastCodeAge - 1,
5047 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5048 kIsOldCodeAge = kSexagenarianCodeAge,
5049 kPreAgedCodeAge = kIsOldCodeAge - 1
5051 #undef DECLARE_CODE_AGE_ENUM
5053 // Code aging. Indicates how many full GCs this code has survived without
5054 // being entered through the prologue. Used to determine when it is
5055 // relatively safe to flush this code object and replace it with the lazy
5056 // compilation stub.
5057 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5058 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5059 void MakeYoung(Isolate* isolate);
5060 void MarkToBeExecutedOnce(Isolate* isolate);
5061 void MakeOlder(MarkingParity);
5062 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5065 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5066 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5069 void PrintDeoptLocation(FILE* out, Address pc);
5070 bool CanDeoptAt(Address pc);
5073 void VerifyEmbeddedObjectsDependency();
5077 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5078 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5079 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
5082 inline bool CanContainWeakObjects();
5084 inline bool IsWeakObject(Object* object);
5086 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5088 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5089 WeakCell* CachedWeakCell();
5091 // Max loop nesting marker used to postpose OSR. We don't take loop
5092 // nesting that is deeper than 5 levels into account.
5093 static const int kMaxLoopNestingMarker = 6;
5095 static const int kConstantPoolSize =
5096 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5098 // Layout description.
5099 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5100 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5101 static const int kDeoptimizationDataOffset =
5102 kHandlerTableOffset + kPointerSize;
5103 // For FUNCTION kind, we store the type feedback info here.
5104 static const int kTypeFeedbackInfoOffset =
5105 kDeoptimizationDataOffset + kPointerSize;
5106 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5107 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5108 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5109 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5110 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5111 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5112 static const int kKindSpecificFlags2Offset =
5113 kKindSpecificFlags1Offset + kIntSize;
5114 // Note: We might be able to squeeze this into the flags above.
5115 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5116 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5117 static const int kHeaderPaddingStart =
5118 kConstantPoolOffset + kConstantPoolSize;
5120 // Add padding to align the instruction start following right after
5121 // the Code object header.
5122 static const int kHeaderSize =
5123 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5125 // Byte offsets within kKindSpecificFlags1Offset.
5126 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5127 class FullCodeFlagsHasDeoptimizationSupportField:
5128 public BitField<bool, 0, 1> {}; // NOLINT
5129 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5130 class FullCodeFlagsHasRelocInfoForSerialization
5131 : public BitField<bool, 2, 1> {};
5132 // Bit 3 in this bitfield is unused.
5133 class ProfilerTicksField : public BitField<int, 4, 28> {};
5135 // Flags layout. BitField<type, shift, size>.
5136 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5137 class TypeField : public BitField<StubType, 4, 1> {};
5138 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5139 class KindField : public BitField<Kind, 7, 4> {};
5140 class ExtraICStateField: public BitField<ExtraICState, 11,
5141 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5143 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5144 static const int kStackSlotsFirstBit = 0;
5145 static const int kStackSlotsBitCount = 24;
5146 static const int kHasFunctionCacheBit =
5147 kStackSlotsFirstBit + kStackSlotsBitCount;
5148 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5149 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5150 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5152 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5153 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5155 class StackSlotsField: public BitField<int,
5156 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5157 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5159 class MarkedForDeoptimizationField
5160 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5161 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5163 class CanHaveWeakObjectsField
5164 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5166 // KindSpecificFlags2 layout (ALL)
5167 static const int kIsCrankshaftedBit = 0;
5168 class IsCrankshaftedField: public BitField<bool,
5169 kIsCrankshaftedBit, 1> {}; // NOLINT
5171 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5172 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5173 static const int kSafepointTableOffsetBitCount = 30;
5175 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5176 kSafepointTableOffsetBitCount <= 32);
5177 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5179 class SafepointTableOffsetField: public BitField<int,
5180 kSafepointTableOffsetFirstBit,
5181 kSafepointTableOffsetBitCount> {}; // NOLINT
5183 // KindSpecificFlags2 layout (FUNCTION)
5184 class BackEdgeTableOffsetField: public BitField<int,
5185 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5186 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5187 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5188 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5190 static const int kArgumentsBits = 16;
5191 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5193 // This constant should be encodable in an ARM instruction.
5194 static const int kFlagsNotUsedInLookup =
5195 TypeField::kMask | CacheHolderField::kMask;
5198 friend class RelocIterator;
5199 friend class Deoptimizer; // For FindCodeAgeSequence.
5201 void ClearInlineCaches(Kind* kind);
5204 byte* FindCodeAgeSequence();
5205 static void GetCodeAgeAndParity(Code* code, Age* age,
5206 MarkingParity* parity);
5207 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5208 MarkingParity* parity);
5209 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5211 // Code aging -- platform-specific
5212 static void PatchPlatformCodeAge(Isolate* isolate,
5213 byte* sequence, Age age,
5214 MarkingParity parity);
5216 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5220 // This class describes the layout of dependent codes array of a map. The
5221 // array is partitioned into several groups of dependent codes. Each group
5222 // contains codes with the same dependency on the map. The array has the
5223 // following layout for n dependency groups:
5225 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5226 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5227 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5229 // The first n elements are Smis, each of them specifies the number of codes
5230 // in the corresponding group. The subsequent elements contain grouped code
5231 // objects in weak cells. The suffix of the array can be filled with the
5232 // undefined value if the number of codes is less than the length of the
5233 // array. The order of the code objects within a group is not preserved.
5235 // All code indexes used in the class are counted starting from the first
5236 // code object of the first group. In other words, code index 0 corresponds
5237 // to array index n = kCodesStartIndex.
5239 class DependentCode: public FixedArray {
5241 enum DependencyGroup {
5242 // Group of code that weakly embed this map and depend on being
5243 // deoptimized when the map is garbage collected.
5245 // Group of code that embed a transition to this map, and depend on being
5246 // deoptimized when the transition is replaced by a new version.
5248 // Group of code that omit run-time prototype checks for prototypes
5249 // described by this map. The group is deoptimized whenever an object
5250 // described by this map changes shape (and transitions to a new map),
5251 // possibly invalidating the assumptions embedded in the code.
5252 kPrototypeCheckGroup,
5253 // Group of code that depends on global property values in property cells
5254 // not being changed.
5255 kPropertyCellChangedGroup,
5256 // Group of code that omit run-time type checks for the field(s) introduced
5259 // Group of code that omit run-time type checks for initial maps of
5261 kInitialMapChangedGroup,
5262 // Group of code that depends on tenuring information in AllocationSites
5263 // not being changed.
5264 kAllocationSiteTenuringChangedGroup,
5265 // Group of code that depends on element transition information in
5266 // AllocationSites not being changed.
5267 kAllocationSiteTransitionChangedGroup
5270 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5272 // Array for holding the index of the first code object of each group.
5273 // The last element stores the total number of code objects.
5274 class GroupStartIndexes {
5276 explicit GroupStartIndexes(DependentCode* entries);
5277 void Recompute(DependentCode* entries);
5278 int at(int i) { return start_indexes_[i]; }
5279 int number_of_entries() { return start_indexes_[kGroupCount]; }
5281 int start_indexes_[kGroupCount + 1];
5284 bool Contains(DependencyGroup group, WeakCell* code_cell);
5286 static Handle<DependentCode> InsertCompilationDependencies(
5287 Handle<DependentCode> entries, DependencyGroup group,
5288 Handle<Foreign> info);
5290 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5291 DependencyGroup group,
5292 Handle<WeakCell> code_cell);
5294 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5295 WeakCell* code_cell);
5297 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5300 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5301 DependentCode::DependencyGroup group);
5303 bool MarkCodeForDeoptimization(Isolate* isolate,
5304 DependentCode::DependencyGroup group);
5306 // The following low-level accessors should only be used by this class
5307 // and the mark compact collector.
5308 inline int number_of_entries(DependencyGroup group);
5309 inline void set_number_of_entries(DependencyGroup group, int value);
5310 inline Object* object_at(int i);
5311 inline void set_object_at(int i, Object* object);
5312 inline void clear_at(int i);
5313 inline void copy(int from, int to);
5314 DECLARE_CAST(DependentCode)
5316 static const char* DependencyGroupName(DependencyGroup group);
5317 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5320 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5321 DependencyGroup group,
5322 Handle<Object> object);
5323 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5324 // Make a room at the end of the given group by moving out the first
5325 // code objects of the subsequent groups.
5326 inline void ExtendGroup(DependencyGroup group);
5327 // Compact by removing cleared weak cells and return true if there was
5328 // any cleared weak cell.
5330 static int Grow(int number_of_entries) {
5331 if (number_of_entries < 5) return number_of_entries + 1;
5332 return number_of_entries * 5 / 4;
5334 static const int kCodesStartIndex = kGroupCount;
5338 class PrototypeInfo;
5341 // All heap objects have a Map that describes their structure.
5342 // A Map contains information about:
5343 // - Size information about the object
5344 // - How to iterate over an object (for garbage collection)
5345 class Map: public HeapObject {
5348 // Size in bytes or kVariableSizeSentinel if instances do not have
5350 inline int instance_size();
5351 inline void set_instance_size(int value);
5353 // Only to clear an unused byte, remove once byte is used.
5354 inline void clear_unused();
5356 // [inobject_properties_or_constructor_function_index]: Provides access
5357 // to the inobject properties in case of JSObject maps, or the constructor
5358 // function index in case of primitive maps.
5359 inline int inobject_properties_or_constructor_function_index();
5360 inline void set_inobject_properties_or_constructor_function_index(int value);
5361 // Count of properties allocated in the object (JSObject only).
5362 inline int GetInObjectProperties();
5363 inline void SetInObjectProperties(int value);
5364 // Index of the constructor function in the native context (primitives only),
5365 // or the special sentinel value to indicate that there is no object wrapper
5366 // for the primitive (i.e. in case of null or undefined).
5367 static const int kNoConstructorFunctionIndex = 0;
5368 inline int GetConstructorFunctionIndex();
5369 inline void SetConstructorFunctionIndex(int value);
5372 inline InstanceType instance_type();
5373 inline void set_instance_type(InstanceType value);
5375 // Tells how many unused property fields are available in the
5376 // instance (only used for JSObject in fast mode).
5377 inline int unused_property_fields();
5378 inline void set_unused_property_fields(int value);
5381 inline byte bit_field() const;
5382 inline void set_bit_field(byte value);
5385 inline byte bit_field2() const;
5386 inline void set_bit_field2(byte value);
5389 inline uint32_t bit_field3() const;
5390 inline void set_bit_field3(uint32_t bits);
5392 class EnumLengthBits: public BitField<int,
5393 0, kDescriptorIndexBitCount> {}; // NOLINT
5394 class NumberOfOwnDescriptorsBits: public BitField<int,
5395 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5396 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5397 class DictionaryMap : public BitField<bool, 20, 1> {};
5398 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5399 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5400 class Deprecated : public BitField<bool, 23, 1> {};
5401 class IsUnstable : public BitField<bool, 24, 1> {};
5402 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5403 class IsStrong : public BitField<bool, 26, 1> {};
5406 // Keep this bit field at the very end for better code in
5407 // Builtins::kJSConstructStubGeneric stub.
5408 // This counter is used for in-object slack tracking and for map aging.
5409 // The in-object slack tracking is considered enabled when the counter is
5410 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5411 class Counter : public BitField<int, 28, 4> {};
5412 static const int kSlackTrackingCounterStart = 14;
5413 static const int kSlackTrackingCounterEnd = 8;
5414 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5415 static const int kRetainingCounterEnd = 0;
5417 // Tells whether the object in the prototype property will be used
5418 // for instances created from this function. If the prototype
5419 // property is set to a value that is not a JSObject, the prototype
5420 // property will not be used to create instances of the function.
5421 // See ECMA-262, 13.2.2.
5422 inline void set_non_instance_prototype(bool value);
5423 inline bool has_non_instance_prototype();
5425 // Tells whether the instance has a [[Construct]] internal method.
5426 // This property is implemented according to ES6, section 7.2.4.
5427 inline void set_is_constructor(bool value);
5428 inline bool is_constructor() const;
5430 // Tells whether the instance with this map should be ignored by the
5431 // Object.getPrototypeOf() function and the __proto__ accessor.
5432 inline void set_is_hidden_prototype();
5433 inline bool is_hidden_prototype() const;
5435 // Records and queries whether the instance has a named interceptor.
5436 inline void set_has_named_interceptor();
5437 inline bool has_named_interceptor();
5439 // Records and queries whether the instance has an indexed interceptor.
5440 inline void set_has_indexed_interceptor();
5441 inline bool has_indexed_interceptor();
5443 // Tells whether the instance is undetectable.
5444 // An undetectable object is a special class of JSObject: 'typeof' operator
5445 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5446 // a normal JS object. It is useful for implementing undetectable
5447 // document.all in Firefox & Safari.
5448 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5449 inline void set_is_undetectable();
5450 inline bool is_undetectable();
5452 // Tells whether the instance has a call-as-function handler.
5453 inline void set_is_observed();
5454 inline bool is_observed();
5456 // Tells whether the instance has a [[Call]] internal method.
5457 // This property is implemented according to ES6, section 7.2.3.
5458 inline void set_is_callable();
5459 inline bool is_callable() const;
5461 inline void set_is_strong();
5462 inline bool is_strong();
5463 inline void set_is_extensible(bool value);
5464 inline bool is_extensible();
5465 inline void set_is_prototype_map(bool value);
5466 inline bool is_prototype_map() const;
5468 inline void set_elements_kind(ElementsKind elements_kind);
5469 inline ElementsKind elements_kind();
5471 // Tells whether the instance has fast elements that are only Smis.
5472 inline bool has_fast_smi_elements();
5474 // Tells whether the instance has fast elements.
5475 inline bool has_fast_object_elements();
5476 inline bool has_fast_smi_or_object_elements();
5477 inline bool has_fast_double_elements();
5478 inline bool has_fast_elements();
5479 inline bool has_sloppy_arguments_elements();
5480 inline bool has_fixed_typed_array_elements();
5481 inline bool has_dictionary_elements();
5483 static bool IsValidElementsTransition(ElementsKind from_kind,
5484 ElementsKind to_kind);
5486 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5487 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5488 bool DictionaryElementsInPrototypeChainOnly();
5490 inline Map* ElementsTransitionMap();
5492 inline FixedArrayBase* GetInitialElements();
5494 // [raw_transitions]: Provides access to the transitions storage field.
5495 // Don't call set_raw_transitions() directly to overwrite transitions, use
5496 // the TransitionArray::ReplaceTransitions() wrapper instead!
5497 DECL_ACCESSORS(raw_transitions, Object)
5498 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5499 // (which prototype maps don't have).
5500 DECL_ACCESSORS(prototype_info, Object)
5501 // PrototypeInfo is created lazily using this helper (which installs it on
5502 // the given prototype's map).
5503 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5504 Handle<JSObject> prototype, Isolate* isolate);
5505 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5506 Handle<Map> prototype_map, Isolate* isolate);
5508 // [prototype chain validity cell]: Associated with a prototype object,
5509 // stored in that object's map's PrototypeInfo, indicates that prototype
5510 // chains through this object are currently valid. The cell will be
5511 // invalidated and replaced when the prototype chain changes.
5512 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5514 static const int kPrototypeChainValid = 0;
5515 static const int kPrototypeChainInvalid = 1;
5518 Map* FindFieldOwner(int descriptor);
5520 inline int GetInObjectPropertyOffset(int index);
5522 int NumberOfFields();
5524 // TODO(ishell): candidate with JSObject::MigrateToMap().
5525 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5526 int target_inobject, int target_unused,
5527 int* old_number_of_fields);
5528 // TODO(ishell): moveit!
5529 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5530 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5531 Representation rep1, Handle<HeapType> type1, Representation rep2,
5532 Handle<HeapType> type2, Isolate* isolate);
5533 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5534 Representation new_representation,
5535 Handle<HeapType> new_field_type);
5536 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5537 PropertyKind new_kind,
5538 PropertyAttributes new_attributes,
5539 Representation new_representation,
5540 Handle<HeapType> new_field_type,
5541 StoreMode store_mode);
5542 static Handle<Map> CopyGeneralizeAllRepresentations(
5543 Handle<Map> map, int modify_index, StoreMode store_mode,
5544 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5546 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5547 int descriptor_number,
5548 Handle<Object> value);
5550 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5551 const char* reason);
5553 // Returns the constructor name (the name (possibly, inferred name) of the
5554 // function that was used to instantiate the object).
5555 String* constructor_name();
5557 // Tells whether the map is used for JSObjects in dictionary mode (ie
5558 // normalized objects, ie objects for which HasFastProperties returns false).
5559 // A map can never be used for both dictionary mode and fast mode JSObjects.
5560 // False by default and for HeapObjects that are not JSObjects.
5561 inline void set_dictionary_map(bool value);
5562 inline bool is_dictionary_map();
5564 // Tells whether the instance needs security checks when accessing its
5566 inline void set_is_access_check_needed(bool access_check_needed);
5567 inline bool is_access_check_needed();
5569 // Returns true if map has a non-empty stub code cache.
5570 inline bool has_code_cache();
5572 // [prototype]: implicit prototype object.
5573 DECL_ACCESSORS(prototype, Object)
5574 // TODO(jkummerow): make set_prototype private.
5575 static void SetPrototype(
5576 Handle<Map> map, Handle<Object> prototype,
5577 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5579 // [constructor]: points back to the function responsible for this map.
5580 // The field overlaps with the back pointer. All maps in a transition tree
5581 // have the same constructor, so maps with back pointers can walk the
5582 // back pointer chain until they find the map holding their constructor.
5583 DECL_ACCESSORS(constructor_or_backpointer, Object)
5584 inline Object* GetConstructor() const;
5585 inline void SetConstructor(Object* constructor,
5586 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5587 // [back pointer]: points back to the parent map from which a transition
5588 // leads to this map. The field overlaps with the constructor (see above).
5589 inline Object* GetBackPointer();
5590 inline void SetBackPointer(Object* value,
5591 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5593 // [instance descriptors]: describes the object.
5594 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5596 // [layout descriptor]: describes the object layout.
5597 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5598 // |layout descriptor| accessor which can be used from GC.
5599 inline LayoutDescriptor* layout_descriptor_gc_safe();
5600 inline bool HasFastPointerLayout() const;
5602 // |layout descriptor| accessor that is safe to call even when
5603 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5604 // |layout_descriptor| field at all).
5605 inline LayoutDescriptor* GetLayoutDescriptor();
5607 inline void UpdateDescriptors(DescriptorArray* descriptors,
5608 LayoutDescriptor* layout_descriptor);
5609 inline void InitializeDescriptors(DescriptorArray* descriptors,
5610 LayoutDescriptor* layout_descriptor);
5612 // [stub cache]: contains stubs compiled for this map.
5613 DECL_ACCESSORS(code_cache, Object)
5615 // [dependent code]: list of optimized codes that weakly embed this map.
5616 DECL_ACCESSORS(dependent_code, DependentCode)
5618 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5619 DECL_ACCESSORS(weak_cell_cache, Object)
5621 inline PropertyDetails GetLastDescriptorDetails();
5623 inline int LastAdded();
5625 inline int NumberOfOwnDescriptors();
5626 inline void SetNumberOfOwnDescriptors(int number);
5628 inline Cell* RetrieveDescriptorsPointer();
5630 inline int EnumLength();
5631 inline void SetEnumLength(int length);
5633 inline bool owns_descriptors();
5634 inline void set_owns_descriptors(bool owns_descriptors);
5635 inline void mark_unstable();
5636 inline bool is_stable();
5637 inline void set_migration_target(bool value);
5638 inline bool is_migration_target();
5639 inline void set_counter(int value);
5640 inline int counter();
5641 inline void deprecate();
5642 inline bool is_deprecated();
5643 inline bool CanBeDeprecated();
5644 // Returns a non-deprecated version of the input. If the input was not
5645 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5646 // is found by re-transitioning from the root of the transition tree using the
5647 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5649 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5651 // Returns a non-deprecated version of the input. This method may deprecate
5652 // existing maps along the way if encodings conflict. Not for use while
5653 // gathering type feedback. Use TryUpdate in those cases instead.
5654 static Handle<Map> Update(Handle<Map> map);
5656 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5657 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5658 Descriptor* descriptor,
5659 TransitionFlag flag);
5661 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5664 Handle<HeapType> type,
5665 PropertyAttributes attributes,
5666 Representation representation,
5667 TransitionFlag flag);
5669 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5672 Handle<Object> constant,
5673 PropertyAttributes attributes,
5674 TransitionFlag flag);
5676 // Returns a new map with all transitions dropped from the given map and
5677 // the ElementsKind set.
5678 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5679 ElementsKind to_kind);
5681 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5683 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5685 TransitionFlag flag);
5687 static Handle<Map> CopyForObserved(Handle<Map> map);
5689 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5690 PropertyAttributes attrs_to_add,
5691 Handle<Symbol> transition_marker,
5692 const char* reason);
5694 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5697 // Maximal number of fast properties. Used to restrict the number of map
5698 // transitions to avoid an explosion in the number of maps for objects used as
5700 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5701 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5703 Handle<Object> value,
5704 PropertyAttributes attributes,
5705 StoreFromKeyed store_mode);
5706 static Handle<Map> TransitionToAccessorProperty(
5707 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5708 Handle<Object> accessor, PropertyAttributes attributes);
5709 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5712 PropertyAttributes attributes);
5714 inline void AppendDescriptor(Descriptor* desc);
5716 // Returns a copy of the map, prepared for inserting into the transition
5717 // tree (if the |map| owns descriptors then the new one will share
5718 // descriptors with |map|).
5719 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5721 // Returns a copy of the map, with all transitions dropped from the
5722 // instance descriptors.
5723 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5724 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5726 // Returns the next free property index (only valid for FAST MODE).
5727 int NextFreePropertyIndex();
5729 // Returns the number of properties described in instance_descriptors
5730 // filtering out properties with the specified attributes.
5731 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5732 PropertyAttributes filter = NONE);
5736 // Code cache operations.
5738 // Clears the code cache.
5739 inline void ClearCodeCache(Heap* heap);
5741 // Update code cache.
5742 static void UpdateCodeCache(Handle<Map> map,
5746 // Extend the descriptor array of the map with the list of descriptors.
5747 // In case of duplicates, the latest descriptor is used.
5748 static void AppendCallbackDescriptors(Handle<Map> map,
5749 Handle<Object> descriptors);
5751 static inline int SlackForArraySize(int old_size, int size_limit);
5753 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5755 // Returns the found code or undefined if absent.
5756 Object* FindInCodeCache(Name* name, Code::Flags flags);
5758 // Returns the non-negative index of the code object if it is in the
5759 // cache and -1 otherwise.
5760 int IndexInCodeCache(Object* name, Code* code);
5762 // Removes a code object from the code cache at the given index.
5763 void RemoveFromCodeCache(Name* name, Code* code, int index);
5765 // Computes a hash value for this map, to be used in HashTables and such.
5768 // Returns the map that this map transitions to if its elements_kind
5769 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5770 // |safe_to_add_transitions| is set to false if adding transitions is not
5772 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5774 // Returns the transitioned map for this map with the most generic
5775 // elements_kind that's found in |candidates|, or null handle if no match is
5777 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5778 MapHandleList* candidates);
5780 inline bool CanTransition();
5782 inline bool IsPrimitiveMap();
5783 inline bool IsJSObjectMap();
5784 inline bool IsJSArrayMap();
5785 inline bool IsJSFunctionMap();
5786 inline bool IsStringMap();
5787 inline bool IsJSProxyMap();
5788 inline bool IsJSGlobalProxyMap();
5789 inline bool IsJSGlobalObjectMap();
5790 inline bool IsGlobalObjectMap();
5792 inline bool CanOmitMapChecks();
5794 static void AddDependentCode(Handle<Map> map,
5795 DependentCode::DependencyGroup group,
5798 bool IsMapInArrayPrototypeChain();
5800 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5802 // Dispatched behavior.
5803 DECLARE_PRINTER(Map)
5804 DECLARE_VERIFIER(Map)
5807 void DictionaryMapVerify();
5808 void VerifyOmittedMapChecks();
5811 inline int visitor_id();
5812 inline void set_visitor_id(int visitor_id);
5814 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5815 Handle<Object> prototype,
5816 PrototypeOptimizationMode mode);
5818 static const int kMaxPreAllocatedPropertyFields = 255;
5820 // Layout description.
5821 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5822 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5823 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5824 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5825 static const int kConstructorOrBackPointerOffset =
5826 kPrototypeOffset + kPointerSize;
5827 // When there is only one transition, it is stored directly in this field;
5828 // otherwise a transition array is used.
5829 // For prototype maps, this slot is used to store this map's PrototypeInfo
5831 static const int kTransitionsOrPrototypeInfoOffset =
5832 kConstructorOrBackPointerOffset + kPointerSize;
5833 static const int kDescriptorsOffset =
5834 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5835 #if V8_DOUBLE_FIELDS_UNBOXING
5836 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5837 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5839 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5840 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5842 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5843 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5844 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5846 // Layout of pointer fields. Heap iteration code relies on them
5847 // being continuously allocated.
5848 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5849 static const int kPointerFieldsEndOffset = kSize;
5851 // Byte offsets within kInstanceSizesOffset.
5852 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5853 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5854 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5855 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5856 // Note there is one byte available for use here.
5857 static const int kUnusedByte = 2;
5858 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5859 static const int kVisitorIdByte = 3;
5860 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5862 // Byte offsets within kInstanceAttributesOffset attributes.
5863 #if V8_TARGET_LITTLE_ENDIAN
5864 // Order instance type and bit field together such that they can be loaded
5865 // together as a 16-bit word with instance type in the lower 8 bits regardless
5866 // of endianess. Also provide endian-independent offset to that 16-bit word.
5867 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5868 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5870 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5871 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5873 static const int kInstanceTypeAndBitFieldOffset =
5874 kInstanceAttributesOffset + 0;
5875 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5876 static const int kUnusedPropertyFieldsByte = 3;
5877 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5879 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5880 Internals::kMapInstanceTypeAndBitFieldOffset);
5882 // Bit positions for bit field.
5883 static const int kHasNonInstancePrototype = 0;
5884 static const int kIsCallable = 1;
5885 static const int kHasNamedInterceptor = 2;
5886 static const int kHasIndexedInterceptor = 3;
5887 static const int kIsUndetectable = 4;
5888 static const int kIsObserved = 5;
5889 static const int kIsAccessCheckNeeded = 6;
5890 static const int kIsConstructor = 7;
5892 // Bit positions for bit field 2
5893 static const int kIsExtensible = 0;
5895 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5896 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5898 // Derived values from bit field 2
5899 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5900 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5901 static const int8_t kMaximumBitField2FastSmiElementValue =
5902 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5903 Map::ElementsKindBits::kShift) - 1;
5904 static const int8_t kMaximumBitField2FastHoleyElementValue =
5905 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5906 Map::ElementsKindBits::kShift) - 1;
5907 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5908 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5909 Map::ElementsKindBits::kShift) - 1;
5911 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5912 kPointerFieldsEndOffset,
5913 kSize> BodyDescriptor;
5915 // Compares this map to another to see if they describe equivalent objects.
5916 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5917 // it had exactly zero inobject properties.
5918 // The "shared" flags of both this map and |other| are ignored.
5919 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5921 // Returns true if given field is unboxed double.
5922 inline bool IsUnboxedDoubleField(FieldIndex index);
5925 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5926 static void TraceAllTransitions(Map* map);
5929 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5930 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5931 Handle<LayoutDescriptor> layout_descriptor);
5934 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5935 Handle<Name> name, SimpleTransitionFlag flag);
5937 bool EquivalentToForTransition(Map* other);
5938 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5939 static Handle<Map> ShareDescriptor(Handle<Map> map,
5940 Handle<DescriptorArray> descriptors,
5941 Descriptor* descriptor);
5942 static Handle<Map> CopyInstallDescriptors(
5943 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5944 Handle<LayoutDescriptor> layout_descriptor);
5945 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5946 Descriptor* descriptor,
5947 TransitionFlag flag);
5948 static Handle<Map> CopyReplaceDescriptors(
5949 Handle<Map> map, Handle<DescriptorArray> descriptors,
5950 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5951 MaybeHandle<Name> maybe_name, const char* reason,
5952 SimpleTransitionFlag simple_flag);
5954 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5955 Handle<DescriptorArray> descriptors,
5956 Descriptor* descriptor,
5958 TransitionFlag flag);
5959 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5960 Handle<Map> map, int descriptor, PropertyKind kind,
5961 PropertyAttributes attributes, const char** reason);
5963 static Handle<Map> CopyNormalized(Handle<Map> map,
5964 PropertyNormalizationMode mode);
5966 // Fires when the layout of an object with a leaf map changes.
5967 // This includes adding transitions to the leaf map or changing
5968 // the descriptor array.
5969 inline void NotifyLeafMapLayoutChange();
5971 void DeprecateTransitionTree();
5972 bool DeprecateTarget(PropertyKind kind, Name* key,
5973 PropertyAttributes attributes,
5974 DescriptorArray* new_descriptors,
5975 LayoutDescriptor* new_layout_descriptor);
5977 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5979 // Update field type of the given descriptor to new representation and new
5980 // type. The type must be prepared for storing in descriptor array:
5981 // it must be either a simple type or a map wrapped in a weak cell.
5982 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5983 Representation new_representation,
5984 Handle<Object> new_wrapped_type);
5986 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5987 PropertyAttributes attributes);
5988 void PrintGeneralization(FILE* file,
5993 bool constant_to_field,
5994 Representation old_representation,
5995 Representation new_representation,
5996 HeapType* old_field_type,
5997 HeapType* new_field_type);
5999 static const int kFastPropertiesSoftLimit = 12;
6000 static const int kMaxFastProperties = 128;
6002 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6006 // An abstract superclass, a marker class really, for simple structure classes.
6007 // It doesn't carry much functionality but allows struct classes to be
6008 // identified in the type system.
6009 class Struct: public HeapObject {
6011 inline void InitializeBody(int object_size);
6012 DECLARE_CAST(Struct)
6016 // A simple one-element struct, useful where smis need to be boxed.
6017 class Box : public Struct {
6019 // [value]: the boxed contents.
6020 DECL_ACCESSORS(value, Object)
6024 // Dispatched behavior.
6025 DECLARE_PRINTER(Box)
6026 DECLARE_VERIFIER(Box)
6028 static const int kValueOffset = HeapObject::kHeaderSize;
6029 static const int kSize = kValueOffset + kPointerSize;
6032 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6036 // Container for metadata stored on each prototype map.
6037 class PrototypeInfo : public Struct {
6039 static const int UNREGISTERED = -1;
6041 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6042 // or Smi(0) if uninitialized.
6043 DECL_ACCESSORS(prototype_users, Object)
6044 // [registry_slot]: Slot in prototype's user registry where this user
6045 // is stored. Returns UNREGISTERED if this prototype has not been registered.
6046 inline int registry_slot() const;
6047 inline void set_registry_slot(int slot);
6048 // [validity_cell]: Cell containing the validity bit for prototype chains
6049 // going through this object, or Smi(0) if uninitialized.
6050 // When a prototype object changes its map, then both its own validity cell
6051 // and those of all "downstream" prototypes are invalidated; handlers for a
6052 // given receiver embed the currently valid cell for that receiver's prototype
6053 // during their compilation and check it on execution.
6054 DECL_ACCESSORS(validity_cell, Object)
6055 // [constructor_name]: User-friendly name of the original constructor.
6056 DECL_ACCESSORS(constructor_name, Object)
6058 DECLARE_CAST(PrototypeInfo)
6060 // Dispatched behavior.
6061 DECLARE_PRINTER(PrototypeInfo)
6062 DECLARE_VERIFIER(PrototypeInfo)
6064 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6065 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
6066 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
6067 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6068 static const int kSize = kConstructorNameOffset + kPointerSize;
6071 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6075 // Pair used to store both a ScopeInfo and an extension object in the extension
6076 // slot of a block context. Needed in the rare case where a declaration block
6077 // scope (a "varblock" as used to desugar parameter destructuring) also contains
6078 // a sloppy direct eval. (In no other case both are needed at the same time.)
6079 class SloppyBlockWithEvalContextExtension : public Struct {
6081 // [scope_info]: Scope info.
6082 DECL_ACCESSORS(scope_info, ScopeInfo)
6083 // [extension]: Extension object.
6084 DECL_ACCESSORS(extension, JSObject)
6086 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
6088 // Dispatched behavior.
6089 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
6090 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
6092 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
6093 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
6094 static const int kSize = kExtensionOffset + kPointerSize;
6097 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
6101 // Script describes a script which has been added to the VM.
6102 class Script: public Struct {
6111 // Script compilation types.
6112 enum CompilationType {
6113 COMPILATION_TYPE_HOST = 0,
6114 COMPILATION_TYPE_EVAL = 1
6117 // Script compilation state.
6118 enum CompilationState {
6119 COMPILATION_STATE_INITIAL = 0,
6120 COMPILATION_STATE_COMPILED = 1
6123 // [source]: the script source.
6124 DECL_ACCESSORS(source, Object)
6126 // [name]: the script name.
6127 DECL_ACCESSORS(name, Object)
6129 // [id]: the script id.
6130 DECL_INT_ACCESSORS(id)
6132 // [line_offset]: script line offset in resource from where it was extracted.
6133 DECL_INT_ACCESSORS(line_offset)
6135 // [column_offset]: script column offset in resource from where it was
6137 DECL_INT_ACCESSORS(column_offset)
6139 // [context_data]: context data for the context this script was compiled in.
6140 DECL_ACCESSORS(context_data, Object)
6142 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6143 DECL_ACCESSORS(wrapper, HeapObject)
6145 // [type]: the script type.
6146 DECL_INT_ACCESSORS(type)
6148 // [line_ends]: FixedArray of line ends positions.
6149 DECL_ACCESSORS(line_ends, Object)
6151 // [eval_from_shared]: for eval scripts the shared funcion info for the
6152 // function from which eval was called.
6153 DECL_ACCESSORS(eval_from_shared, Object)
6155 // [eval_from_instructions_offset]: the instruction offset in the code for the
6156 // function from which eval was called where eval was called.
6157 DECL_INT_ACCESSORS(eval_from_instructions_offset)
6159 // [shared_function_infos]: weak fixed array containing all shared
6160 // function infos created from this script.
6161 DECL_ACCESSORS(shared_function_infos, Object)
6163 // [flags]: Holds an exciting bitfield.
6164 DECL_INT_ACCESSORS(flags)
6166 // [source_url]: sourceURL from magic comment
6167 DECL_ACCESSORS(source_url, Object)
6169 // [source_url]: sourceMappingURL magic comment
6170 DECL_ACCESSORS(source_mapping_url, Object)
6172 // [compilation_type]: how the the script was compiled. Encoded in the
6174 inline CompilationType compilation_type();
6175 inline void set_compilation_type(CompilationType type);
6177 // [compilation_state]: determines whether the script has already been
6178 // compiled. Encoded in the 'flags' field.
6179 inline CompilationState compilation_state();
6180 inline void set_compilation_state(CompilationState state);
6182 // [hide_source]: determines whether the script source can be exposed as
6183 // function source. Encoded in the 'flags' field.
6184 inline bool hide_source();
6185 inline void set_hide_source(bool value);
6187 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6188 // and used by the embedder to make decisions about the script. V8 just passes
6189 // this through. Encoded in the 'flags' field.
6190 inline v8::ScriptOriginOptions origin_options();
6191 inline void set_origin_options(ScriptOriginOptions origin_options);
6193 DECLARE_CAST(Script)
6195 // If script source is an external string, check that the underlying
6196 // resource is accessible. Otherwise, always return true.
6197 inline bool HasValidSource();
6199 // Convert code position into column number.
6200 static int GetColumnNumber(Handle<Script> script, int code_pos);
6202 // Convert code position into (zero-based) line number.
6203 // The non-handlified version does not allocate, but may be much slower.
6204 static int GetLineNumber(Handle<Script> script, int code_pos);
6205 int GetLineNumber(int code_pos);
6207 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6209 // Init line_ends array with code positions of line ends inside script source.
6210 static void InitLineEnds(Handle<Script> script);
6212 // Get the JS object wrapping the given script; create it if none exists.
6213 static Handle<JSObject> GetWrapper(Handle<Script> script);
6215 // Look through the list of existing shared function infos to find one
6216 // that matches the function literal. Return empty handle if not found.
6217 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6219 // Iterate over all script objects on the heap.
6222 explicit Iterator(Isolate* isolate);
6226 WeakFixedArray::Iterator iterator_;
6227 DISALLOW_COPY_AND_ASSIGN(Iterator);
6230 // Dispatched behavior.
6231 DECLARE_PRINTER(Script)
6232 DECLARE_VERIFIER(Script)
6234 static const int kSourceOffset = HeapObject::kHeaderSize;
6235 static const int kNameOffset = kSourceOffset + kPointerSize;
6236 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6237 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6238 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6239 static const int kWrapperOffset = kContextOffset + kPointerSize;
6240 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6241 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6242 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6243 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6244 static const int kEvalFrominstructionsOffsetOffset =
6245 kEvalFromSharedOffset + kPointerSize;
6246 static const int kSharedFunctionInfosOffset =
6247 kEvalFrominstructionsOffsetOffset + kPointerSize;
6248 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6249 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6250 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6251 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6254 int GetLineNumberWithArray(int code_pos);
6256 // Bit positions in the flags field.
6257 static const int kCompilationTypeBit = 0;
6258 static const int kCompilationStateBit = 1;
6259 static const int kHideSourceBit = 2;
6260 static const int kOriginOptionsShift = 3;
6261 static const int kOriginOptionsSize = 3;
6262 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6263 << kOriginOptionsShift;
6265 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6269 // List of builtin functions we want to identify to improve code
6272 // Each entry has a name of a global object property holding an object
6273 // optionally followed by ".prototype", a name of a builtin function
6274 // on the object (the one the id is set for), and a label.
6276 // Installation of ids for the selected builtin functions is handled
6277 // by the bootstrapper.
6278 #define FUNCTIONS_WITH_ID_LIST(V) \
6279 V(Array.prototype, indexOf, ArrayIndexOf) \
6280 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6281 V(Array.prototype, push, ArrayPush) \
6282 V(Array.prototype, pop, ArrayPop) \
6283 V(Array.prototype, shift, ArrayShift) \
6284 V(Function.prototype, apply, FunctionApply) \
6285 V(Function.prototype, call, FunctionCall) \
6286 V(String.prototype, charCodeAt, StringCharCodeAt) \
6287 V(String.prototype, charAt, StringCharAt) \
6288 V(String, fromCharCode, StringFromCharCode) \
6289 V(Math, random, MathRandom) \
6290 V(Math, floor, MathFloor) \
6291 V(Math, round, MathRound) \
6292 V(Math, ceil, MathCeil) \
6293 V(Math, abs, MathAbs) \
6294 V(Math, log, MathLog) \
6295 V(Math, exp, MathExp) \
6296 V(Math, sqrt, MathSqrt) \
6297 V(Math, pow, MathPow) \
6298 V(Math, max, MathMax) \
6299 V(Math, min, MathMin) \
6300 V(Math, cos, MathCos) \
6301 V(Math, sin, MathSin) \
6302 V(Math, tan, MathTan) \
6303 V(Math, acos, MathAcos) \
6304 V(Math, asin, MathAsin) \
6305 V(Math, atan, MathAtan) \
6306 V(Math, atan2, MathAtan2) \
6307 V(Math, imul, MathImul) \
6308 V(Math, clz32, MathClz32) \
6309 V(Math, fround, MathFround)
6311 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6312 V(Atomics, load, AtomicsLoad) \
6313 V(Atomics, store, AtomicsStore)
6315 enum BuiltinFunctionId {
6317 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6319 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6320 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6321 #undef DECLARE_FUNCTION_ID
6322 // Fake id for a special case of Math.pow. Note, it continues the
6323 // list of math functions.
6328 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6329 // that both {code} and {literals} can be NULL to pass search result status.
6330 struct CodeAndLiterals {
6331 Code* code; // Cached optimized code.
6332 LiteralsArray* literals; // Cached literals array.
6336 // SharedFunctionInfo describes the JSFunction information that can be
6337 // shared by multiple instances of the function.
6338 class SharedFunctionInfo: public HeapObject {
6340 // [name]: Function name.
6341 DECL_ACCESSORS(name, Object)
6343 // [code]: Function code.
6344 DECL_ACCESSORS(code, Code)
6345 inline void ReplaceCode(Code* code);
6347 // [optimized_code_map]: Map from native context to optimized code
6348 // and a shared literals array or Smi(0) if none.
6349 DECL_ACCESSORS(optimized_code_map, Object)
6351 // Returns entry from optimized code map for specified context and OSR entry.
6352 // Note that {code == nullptr, literals == nullptr} indicates no matching
6353 // entry has been found, whereas {code, literals == nullptr} indicates that
6354 // code is context-independent.
6355 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6356 BailoutId osr_ast_id);
6358 // Clear optimized code map.
6359 void ClearOptimizedCodeMap();
6361 // Removes a specific optimized code object from the optimized code map.
6362 // In case of non-OSR the code reference is cleared from the cache entry but
6363 // the entry itself is left in the map in order to proceed sharing literals.
6364 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6366 // Trims the optimized code map after entries have been removed.
6367 void TrimOptimizedCodeMap(int shrink_by);
6369 // Add a new entry to the optimized code map for context-independent code.
6370 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6373 // Add a new entry to the optimized code map for context-dependent code.
6374 // |code| is either a code object or an undefined value. In the latter case
6375 // the entry just maps |native_context, osr_ast_id| pair to |literals| array.
6376 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6377 Handle<Context> native_context,
6378 Handle<HeapObject> code,
6379 Handle<LiteralsArray> literals,
6380 BailoutId osr_ast_id);
6382 // Set up the link between shared function info and the script. The shared
6383 // function info is added to the list on the script.
6384 static void SetScript(Handle<SharedFunctionInfo> shared,
6385 Handle<Object> script_object);
6387 // Layout description of the optimized code map.
6388 static const int kNextMapIndex = 0;
6389 static const int kSharedCodeIndex = 1;
6390 static const int kEntriesStart = 2;
6391 static const int kContextOffset = 0;
6392 static const int kCachedCodeOffset = 1;
6393 static const int kLiteralsOffset = 2;
6394 static const int kOsrAstIdOffset = 3;
6395 static const int kEntryLength = 4;
6396 static const int kInitialLength = kEntriesStart + kEntryLength;
6398 static const int kNotFound = -1;
6400 // [scope_info]: Scope info.
6401 DECL_ACCESSORS(scope_info, ScopeInfo)
6403 // [construct stub]: Code stub for constructing instances of this function.
6404 DECL_ACCESSORS(construct_stub, Code)
6406 // Returns if this function has been compiled to native code yet.
6407 inline bool is_compiled();
6409 // [length]: The function length - usually the number of declared parameters.
6410 // Use up to 2^30 parameters.
6411 inline int length() const;
6412 inline void set_length(int value);
6414 // [internal formal parameter count]: The declared number of parameters.
6415 // For subclass constructors, also includes new.target.
6416 // The size of function's frame is internal_formal_parameter_count + 1.
6417 inline int internal_formal_parameter_count() const;
6418 inline void set_internal_formal_parameter_count(int value);
6420 // Set the formal parameter count so the function code will be
6421 // called without using argument adaptor frames.
6422 inline void DontAdaptArguments();
6424 // [expected_nof_properties]: Expected number of properties for the function.
6425 inline int expected_nof_properties() const;
6426 inline void set_expected_nof_properties(int value);
6428 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6429 // (increasingly) from crankshafted code where sufficient feedback isn't
6431 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6433 // Unconditionally clear the type feedback vector (including vector ICs).
6434 void ClearTypeFeedbackInfo();
6436 // Clear the type feedback vector with a more subtle policy at GC time.
6437 void ClearTypeFeedbackInfoAtGCTime();
6440 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6441 // even if the GC moves this SharedFunctionInfo.
6442 inline int unique_id() const;
6443 inline void set_unique_id(int value);
6446 // [instance class name]: class name for instances.
6447 DECL_ACCESSORS(instance_class_name, Object)
6449 // [function data]: This field holds some additional data for function.
6450 // Currently it has one of:
6451 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6452 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6453 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6454 // In the long run we don't want all functions to have this field but
6455 // we can fix that when we have a better model for storing hidden data
6457 DECL_ACCESSORS(function_data, Object)
6459 inline bool IsApiFunction();
6460 inline FunctionTemplateInfo* get_api_func_data();
6461 inline bool HasBuiltinFunctionId();
6462 inline BuiltinFunctionId builtin_function_id();
6463 inline bool HasBytecodeArray();
6464 inline BytecodeArray* bytecode_array();
6466 // [script info]: Script from which the function originates.
6467 DECL_ACCESSORS(script, Object)
6469 // [num_literals]: Number of literals used by this function.
6470 inline int num_literals() const;
6471 inline void set_num_literals(int value);
6473 // [start_position_and_type]: Field used to store both the source code
6474 // position, whether or not the function is a function expression,
6475 // and whether or not the function is a toplevel function. The two
6476 // least significants bit indicates whether the function is an
6477 // expression and the rest contains the source code position.
6478 inline int start_position_and_type() const;
6479 inline void set_start_position_and_type(int value);
6481 // The function is subject to debugging if a debug info is attached.
6482 inline bool HasDebugInfo();
6483 inline DebugInfo* GetDebugInfo();
6485 // A function has debug code if the compiled code has debug break slots.
6486 inline bool HasDebugCode();
6488 // [debug info]: Debug information.
6489 DECL_ACCESSORS(debug_info, Object)
6491 // [inferred name]: Name inferred from variable or property
6492 // assignment of this function. Used to facilitate debugging and
6493 // profiling of JavaScript code written in OO style, where almost
6494 // all functions are anonymous but are assigned to object
6496 DECL_ACCESSORS(inferred_name, String)
6498 // The function's name if it is non-empty, otherwise the inferred name.
6499 String* DebugName();
6501 // Position of the 'function' token in the script source.
6502 inline int function_token_position() const;
6503 inline void set_function_token_position(int function_token_position);
6505 // Position of this function in the script source.
6506 inline int start_position() const;
6507 inline void set_start_position(int start_position);
6509 // End position of this function in the script source.
6510 inline int end_position() const;
6511 inline void set_end_position(int end_position);
6513 // Is this function a function expression in the source code.
6514 DECL_BOOLEAN_ACCESSORS(is_expression)
6516 // Is this function a top-level function (scripts, evals).
6517 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6519 // Bit field containing various information collected by the compiler to
6520 // drive optimization.
6521 inline int compiler_hints() const;
6522 inline void set_compiler_hints(int value);
6524 inline int ast_node_count() const;
6525 inline void set_ast_node_count(int count);
6527 inline int profiler_ticks() const;
6528 inline void set_profiler_ticks(int ticks);
6530 // Inline cache age is used to infer whether the function survived a context
6531 // disposal or not. In the former case we reset the opt_count.
6532 inline int ic_age();
6533 inline void set_ic_age(int age);
6535 // Indicates if this function can be lazy compiled.
6536 // This is used to determine if we can safely flush code from a function
6537 // when doing GC if we expect that the function will no longer be used.
6538 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6540 // Indicates if this function can be lazy compiled without a context.
6541 // This is used to determine if we can force compilation without reaching
6542 // the function through program execution but through other means (e.g. heap
6543 // iteration by the debugger).
6544 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6546 // Indicates whether optimizations have been disabled for this
6547 // shared function info. If a function is repeatedly optimized or if
6548 // we cannot optimize the function we disable optimization to avoid
6549 // spending time attempting to optimize it again.
6550 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6552 // Indicates the language mode.
6553 inline LanguageMode language_mode();
6554 inline void set_language_mode(LanguageMode language_mode);
6556 // False if the function definitely does not allocate an arguments object.
6557 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6559 // Indicates that this function uses a super property (or an eval that may
6560 // use a super property).
6561 // This is needed to set up the [[HomeObject]] on the function instance.
6562 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6564 // True if the function has any duplicated parameter names.
6565 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6567 // Indicates whether the function is a native function.
6568 // These needs special treatment in .call and .apply since
6569 // null passed as the receiver should not be translated to the
6571 DECL_BOOLEAN_ACCESSORS(native)
6573 // Indicate that this function should always be inlined in optimized code.
6574 DECL_BOOLEAN_ACCESSORS(force_inline)
6576 // Indicates that the function was created by the Function function.
6577 // Though it's anonymous, toString should treat it as if it had the name
6578 // "anonymous". We don't set the name itself so that the system does not
6579 // see a binding for it.
6580 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6582 // Indicates whether the function is a bound function created using
6583 // the bind function.
6584 DECL_BOOLEAN_ACCESSORS(bound)
6586 // Indicates that the function is anonymous (the name field can be set
6587 // through the API, which does not change this flag).
6588 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6590 // Is this a function or top-level/eval code.
6591 DECL_BOOLEAN_ACCESSORS(is_function)
6593 // Indicates that code for this function cannot be compiled with Crankshaft.
6594 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6596 // Indicates that code for this function cannot be flushed.
6597 DECL_BOOLEAN_ACCESSORS(dont_flush)
6599 // Indicates that this function is a generator.
6600 DECL_BOOLEAN_ACCESSORS(is_generator)
6602 // Indicates that this function is an arrow function.
6603 DECL_BOOLEAN_ACCESSORS(is_arrow)
6605 // Indicates that this function is a concise method.
6606 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6608 // Indicates that this function is an accessor (getter or setter).
6609 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6611 // Indicates that this function is a default constructor.
6612 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6614 // Indicates that this function is an asm function.
6615 DECL_BOOLEAN_ACCESSORS(asm_function)
6617 // Indicates that the the shared function info is deserialized from cache.
6618 DECL_BOOLEAN_ACCESSORS(deserialized)
6620 // Indicates that the the shared function info has never been compiled before.
6621 DECL_BOOLEAN_ACCESSORS(never_compiled)
6623 inline FunctionKind kind();
6624 inline void set_kind(FunctionKind kind);
6626 // Indicates whether or not the code in the shared function support
6628 inline bool has_deoptimization_support();
6630 // Enable deoptimization support through recompiled code.
6631 void EnableDeoptimizationSupport(Code* recompiled);
6633 // Disable (further) attempted optimization of all functions sharing this
6634 // shared function info.
6635 void DisableOptimization(BailoutReason reason);
6637 inline BailoutReason disable_optimization_reason();
6639 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6640 // code, returns whether it asserted (i.e., always true if assertions are
6642 bool VerifyBailoutId(BailoutId id);
6644 // [source code]: Source code for the function.
6645 bool HasSourceCode() const;
6646 Handle<Object> GetSourceCode();
6648 // Number of times the function was optimized.
6649 inline int opt_count();
6650 inline void set_opt_count(int opt_count);
6652 // Number of times the function was deoptimized.
6653 inline void set_deopt_count(int value);
6654 inline int deopt_count();
6655 inline void increment_deopt_count();
6657 // Number of time we tried to re-enable optimization after it
6658 // was disabled due to high number of deoptimizations.
6659 inline void set_opt_reenable_tries(int value);
6660 inline int opt_reenable_tries();
6662 inline void TryReenableOptimization();
6664 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6665 inline void set_counters(int value);
6666 inline int counters() const;
6668 // Stores opt_count and bailout_reason as bit-fields.
6669 inline void set_opt_count_and_bailout_reason(int value);
6670 inline int opt_count_and_bailout_reason() const;
6672 inline void set_disable_optimization_reason(BailoutReason reason);
6674 // Tells whether this function should be subject to debugging.
6675 inline bool IsSubjectToDebugging();
6677 // Whether this function is defined in native code or extensions.
6678 inline bool IsBuiltin();
6680 // Check whether or not this function is inlineable.
6681 bool IsInlineable();
6683 // Source size of this function.
6686 // Calculate the instance size.
6687 int CalculateInstanceSize();
6689 // Calculate the number of in-object properties.
6690 int CalculateInObjectProperties();
6692 inline bool has_simple_parameters();
6694 // Initialize a SharedFunctionInfo from a parsed function literal.
6695 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6696 FunctionLiteral* lit);
6698 // Dispatched behavior.
6699 DECLARE_PRINTER(SharedFunctionInfo)
6700 DECLARE_VERIFIER(SharedFunctionInfo)
6702 void ResetForNewContext(int new_ic_age);
6704 // Iterate over all shared function infos that are created from a script.
6705 // That excludes shared function infos created for API functions and C++
6709 explicit Iterator(Isolate* isolate);
6710 SharedFunctionInfo* Next();
6715 Script::Iterator script_iterator_;
6716 WeakFixedArray::Iterator sfi_iterator_;
6717 DisallowHeapAllocation no_gc_;
6718 DISALLOW_COPY_AND_ASSIGN(Iterator);
6721 DECLARE_CAST(SharedFunctionInfo)
6724 static const int kDontAdaptArgumentsSentinel = -1;
6726 // Layout description.
6728 static const int kNameOffset = HeapObject::kHeaderSize;
6729 static const int kCodeOffset = kNameOffset + kPointerSize;
6730 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6731 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6732 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6733 static const int kInstanceClassNameOffset =
6734 kConstructStubOffset + kPointerSize;
6735 static const int kFunctionDataOffset =
6736 kInstanceClassNameOffset + kPointerSize;
6737 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6738 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6739 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6740 static const int kFeedbackVectorOffset =
6741 kInferredNameOffset + kPointerSize;
6743 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6744 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6746 // Just to not break the postmortrem support with conditional offsets
6747 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6748 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6751 #if V8_HOST_ARCH_32_BIT
6753 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6754 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6755 static const int kExpectedNofPropertiesOffset =
6756 kFormalParameterCountOffset + kPointerSize;
6757 static const int kNumLiteralsOffset =
6758 kExpectedNofPropertiesOffset + kPointerSize;
6759 static const int kStartPositionAndTypeOffset =
6760 kNumLiteralsOffset + kPointerSize;
6761 static const int kEndPositionOffset =
6762 kStartPositionAndTypeOffset + kPointerSize;
6763 static const int kFunctionTokenPositionOffset =
6764 kEndPositionOffset + kPointerSize;
6765 static const int kCompilerHintsOffset =
6766 kFunctionTokenPositionOffset + kPointerSize;
6767 static const int kOptCountAndBailoutReasonOffset =
6768 kCompilerHintsOffset + kPointerSize;
6769 static const int kCountersOffset =
6770 kOptCountAndBailoutReasonOffset + kPointerSize;
6771 static const int kAstNodeCountOffset =
6772 kCountersOffset + kPointerSize;
6773 static const int kProfilerTicksOffset =
6774 kAstNodeCountOffset + kPointerSize;
6777 static const int kSize = kProfilerTicksOffset + kPointerSize;
6779 // The only reason to use smi fields instead of int fields
6780 // is to allow iteration without maps decoding during
6781 // garbage collections.
6782 // To avoid wasting space on 64-bit architectures we use
6783 // the following trick: we group integer fields into pairs
6784 // The least significant integer in each pair is shifted left by 1.
6785 // By doing this we guarantee that LSB of each kPointerSize aligned
6786 // word is not set and thus this word cannot be treated as pointer
6787 // to HeapObject during old space traversal.
6788 #if V8_TARGET_LITTLE_ENDIAN
6789 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6790 static const int kFormalParameterCountOffset =
6791 kLengthOffset + kIntSize;
6793 static const int kExpectedNofPropertiesOffset =
6794 kFormalParameterCountOffset + kIntSize;
6795 static const int kNumLiteralsOffset =
6796 kExpectedNofPropertiesOffset + kIntSize;
6798 static const int kEndPositionOffset =
6799 kNumLiteralsOffset + kIntSize;
6800 static const int kStartPositionAndTypeOffset =
6801 kEndPositionOffset + kIntSize;
6803 static const int kFunctionTokenPositionOffset =
6804 kStartPositionAndTypeOffset + kIntSize;
6805 static const int kCompilerHintsOffset =
6806 kFunctionTokenPositionOffset + kIntSize;
6808 static const int kOptCountAndBailoutReasonOffset =
6809 kCompilerHintsOffset + kIntSize;
6810 static const int kCountersOffset =
6811 kOptCountAndBailoutReasonOffset + kIntSize;
6813 static const int kAstNodeCountOffset =
6814 kCountersOffset + kIntSize;
6815 static const int kProfilerTicksOffset =
6816 kAstNodeCountOffset + kIntSize;
6819 static const int kSize = kProfilerTicksOffset + kIntSize;
6821 #elif V8_TARGET_BIG_ENDIAN
6822 static const int kFormalParameterCountOffset =
6823 kLastPointerFieldOffset + kPointerSize;
6824 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6826 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6827 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6829 static const int kStartPositionAndTypeOffset =
6830 kExpectedNofPropertiesOffset + kIntSize;
6831 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6833 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6834 static const int kFunctionTokenPositionOffset =
6835 kCompilerHintsOffset + kIntSize;
6837 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6838 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6840 static const int kProfilerTicksOffset =
6841 kOptCountAndBailoutReasonOffset + kIntSize;
6842 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6845 static const int kSize = kAstNodeCountOffset + kIntSize;
6848 #error Unknown byte ordering
6849 #endif // Big endian
6853 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6855 typedef FixedBodyDescriptor<kNameOffset,
6856 kLastPointerFieldOffset + kPointerSize,
6857 kSize> BodyDescriptor;
6859 // Bit positions in start_position_and_type.
6860 // The source code start position is in the 30 most significant bits of
6861 // the start_position_and_type field.
6862 static const int kIsExpressionBit = 0;
6863 static const int kIsTopLevelBit = 1;
6864 static const int kStartPositionShift = 2;
6865 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6867 // Bit positions in compiler_hints.
6868 enum CompilerHints {
6869 kAllowLazyCompilation,
6870 kAllowLazyCompilationWithoutContext,
6871 kOptimizationDisabled,
6873 kStrictModeFunction,
6874 kStrongModeFunction,
6877 kHasDuplicateParameters,
6881 kNameShouldPrintAsAnonymous,
6888 kIsAccessorFunction,
6889 kIsDefaultConstructor,
6890 kIsSubclassConstructor,
6896 kCompilerHintsCount // Pseudo entry
6898 // Add hints for other modes when they're added.
6899 STATIC_ASSERT(LANGUAGE_END == 3);
6901 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6903 class DeoptCountBits : public BitField<int, 0, 4> {};
6904 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6905 class ICAgeBits : public BitField<int, 22, 8> {};
6907 class OptCountBits : public BitField<int, 0, 22> {};
6908 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6911 #if V8_HOST_ARCH_32_BIT
6912 // On 32 bit platforms, compiler hints is a smi.
6913 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6914 static const int kCompilerHintsSize = kPointerSize;
6916 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6917 static const int kCompilerHintsSmiTagSize = 0;
6918 static const int kCompilerHintsSize = kIntSize;
6921 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6922 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6925 // Constants for optimizing codegen for strict mode function and
6927 // Allows to use byte-width instructions.
6928 static const int kStrictModeBitWithinByte =
6929 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6930 static const int kStrongModeBitWithinByte =
6931 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6933 static const int kNativeBitWithinByte =
6934 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6936 static const int kBoundBitWithinByte =
6937 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6939 #if defined(V8_TARGET_LITTLE_ENDIAN)
6940 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6941 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6942 static const int kStrongModeByteOffset =
6943 kCompilerHintsOffset +
6944 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6945 static const int kNativeByteOffset = kCompilerHintsOffset +
6946 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6947 static const int kBoundByteOffset =
6948 kCompilerHintsOffset +
6949 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6950 #elif defined(V8_TARGET_BIG_ENDIAN)
6951 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6952 (kCompilerHintsSize - 1) -
6953 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6954 static const int kStrongModeByteOffset =
6955 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6956 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6957 static const int kNativeByteOffset = kCompilerHintsOffset +
6958 (kCompilerHintsSize - 1) -
6959 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6960 static const int kBoundByteOffset =
6961 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6962 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6964 #error Unknown byte ordering
6968 // Returns entry from optimized code map for specified context and OSR entry.
6969 // The result is either kNotFound, kSharedCodeIndex for context-independent
6970 // entry or a start index of the context-dependent entry.
6971 int SearchOptimizedCodeMapEntry(Context* native_context,
6972 BailoutId osr_ast_id);
6974 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6978 // Printing support.
6979 struct SourceCodeOf {
6980 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6981 : value(v), max_length(max) {}
6982 const SharedFunctionInfo* value;
6987 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6990 class JSGeneratorObject: public JSObject {
6992 // [function]: The function corresponding to this generator object.
6993 DECL_ACCESSORS(function, JSFunction)
6995 // [context]: The context of the suspended computation.
6996 DECL_ACCESSORS(context, Context)
6998 // [receiver]: The receiver of the suspended computation.
6999 DECL_ACCESSORS(receiver, Object)
7001 // [continuation]: Offset into code of continuation.
7003 // A positive offset indicates a suspended generator. The special
7004 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7005 // cannot be resumed.
7006 inline int continuation() const;
7007 inline void set_continuation(int continuation);
7008 inline bool is_closed();
7009 inline bool is_executing();
7010 inline bool is_suspended();
7012 // [operand_stack]: Saved operand stack.
7013 DECL_ACCESSORS(operand_stack, FixedArray)
7015 DECLARE_CAST(JSGeneratorObject)
7017 // Dispatched behavior.
7018 DECLARE_PRINTER(JSGeneratorObject)
7019 DECLARE_VERIFIER(JSGeneratorObject)
7021 // Magic sentinel values for the continuation.
7022 static const int kGeneratorExecuting = -1;
7023 static const int kGeneratorClosed = 0;
7025 // Layout description.
7026 static const int kFunctionOffset = JSObject::kHeaderSize;
7027 static const int kContextOffset = kFunctionOffset + kPointerSize;
7028 static const int kReceiverOffset = kContextOffset + kPointerSize;
7029 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7030 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7031 static const int kSize = kOperandStackOffset + kPointerSize;
7033 // Resume mode, for use by runtime functions.
7034 enum ResumeMode { NEXT, THROW };
7037 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7041 // Representation for module instance objects.
7042 class JSModule: public JSObject {
7044 // [context]: the context holding the module's locals, or undefined if none.
7045 DECL_ACCESSORS(context, Object)
7047 // [scope_info]: Scope info.
7048 DECL_ACCESSORS(scope_info, ScopeInfo)
7050 DECLARE_CAST(JSModule)
7052 // Dispatched behavior.
7053 DECLARE_PRINTER(JSModule)
7054 DECLARE_VERIFIER(JSModule)
7056 // Layout description.
7057 static const int kContextOffset = JSObject::kHeaderSize;
7058 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7059 static const int kSize = kScopeInfoOffset + kPointerSize;
7062 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7066 // JSFunction describes JavaScript functions.
7067 class JSFunction: public JSObject {
7069 // [prototype_or_initial_map]:
7070 DECL_ACCESSORS(prototype_or_initial_map, Object)
7072 // [shared]: The information about the function that
7073 // can be shared by instances.
7074 DECL_ACCESSORS(shared, SharedFunctionInfo)
7076 // [context]: The context for this function.
7077 inline Context* context();
7078 inline void set_context(Object* context);
7079 inline JSObject* global_proxy();
7081 // [code]: The generated code object for this function. Executed
7082 // when the function is invoked, e.g. foo() or new foo(). See
7083 // [[Call]] and [[Construct]] description in ECMA-262, section
7085 inline Code* code();
7086 inline void set_code(Code* code);
7087 inline void set_code_no_write_barrier(Code* code);
7088 inline void ReplaceCode(Code* code);
7090 // Tells whether this function is builtin.
7091 inline bool IsBuiltin();
7093 // Tells whether this function inlines the given shared function info.
7094 bool Inlines(SharedFunctionInfo* candidate);
7096 // Tells whether this function should be subject to debugging.
7097 inline bool IsSubjectToDebugging();
7099 // Tells whether or not the function needs arguments adaption.
7100 inline bool NeedsArgumentsAdaption();
7102 // Tells whether or not this function has been optimized.
7103 inline bool IsOptimized();
7105 // Mark this function for lazy recompilation. The function will be
7106 // recompiled the next time it is executed.
7107 void MarkForOptimization();
7108 void AttemptConcurrentOptimization();
7110 // Tells whether or not the function is already marked for lazy
7112 inline bool IsMarkedForOptimization();
7113 inline bool IsMarkedForConcurrentOptimization();
7115 // Tells whether or not the function is on the concurrent recompilation queue.
7116 inline bool IsInOptimizationQueue();
7118 // Inobject slack tracking is the way to reclaim unused inobject space.
7120 // The instance size is initially determined by adding some slack to
7121 // expected_nof_properties (to allow for a few extra properties added
7122 // after the constructor). There is no guarantee that the extra space
7123 // will not be wasted.
7125 // Here is the algorithm to reclaim the unused inobject space:
7126 // - Detect the first constructor call for this JSFunction.
7127 // When it happens enter the "in progress" state: initialize construction
7128 // counter in the initial_map.
7129 // - While the tracking is in progress create objects filled with
7130 // one_pointer_filler_map instead of undefined_value. This way they can be
7131 // resized quickly and safely.
7132 // - Once enough objects have been created compute the 'slack'
7133 // (traverse the map transition tree starting from the
7134 // initial_map and find the lowest value of unused_property_fields).
7135 // - Traverse the transition tree again and decrease the instance size
7136 // of every map. Existing objects will resize automatically (they are
7137 // filled with one_pointer_filler_map). All further allocations will
7138 // use the adjusted instance size.
7139 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7140 // allocations made using different closures could actually create different
7141 // kind of objects (see prototype inheritance pattern).
7143 // Important: inobject slack tracking is not attempted during the snapshot
7146 // True if the initial_map is set and the object constructions countdown
7147 // counter is not zero.
7148 static const int kGenerousAllocationCount =
7149 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7150 inline bool IsInobjectSlackTrackingInProgress();
7152 // Starts the tracking.
7153 // Initializes object constructions countdown counter in the initial map.
7154 void StartInobjectSlackTracking();
7156 // Completes the tracking.
7157 void CompleteInobjectSlackTracking();
7159 // [literals_or_bindings]: Fixed array holding either
7160 // the materialized literals or the bindings of a bound function.
7162 // If the function contains object, regexp or array literals, the
7163 // literals array prefix contains the object, regexp, and array
7164 // function to be used when creating these literals. This is
7165 // necessary so that we do not dynamically lookup the object, regexp
7166 // or array functions. Performing a dynamic lookup, we might end up
7167 // using the functions from a new context that we should not have
7170 // On bound functions, the array is a (copy-on-write) fixed-array containing
7171 // the function that was bound, bound this-value and any bound
7172 // arguments. Bound functions never contain literals.
7173 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7175 inline LiteralsArray* literals();
7176 inline void set_literals(LiteralsArray* literals);
7178 inline FixedArray* function_bindings();
7179 inline void set_function_bindings(FixedArray* bindings);
7181 // The initial map for an object created by this constructor.
7182 inline Map* initial_map();
7183 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7184 Handle<Object> prototype);
7185 inline bool has_initial_map();
7186 static void EnsureHasInitialMap(Handle<JSFunction> function);
7188 // Get and set the prototype property on a JSFunction. If the
7189 // function has an initial map the prototype is set on the initial
7190 // map. Otherwise, the prototype is put in the initial map field
7191 // until an initial map is needed.
7192 inline bool has_prototype();
7193 inline bool has_instance_prototype();
7194 inline Object* prototype();
7195 inline Object* instance_prototype();
7196 static void SetPrototype(Handle<JSFunction> function,
7197 Handle<Object> value);
7198 static void SetInstancePrototype(Handle<JSFunction> function,
7199 Handle<Object> value);
7201 // After prototype is removed, it will not be created when accessed, and
7202 // [[Construct]] from this function will not be allowed.
7203 bool RemovePrototype();
7205 // Accessor for this function's initial map's [[class]]
7206 // property. This is primarily used by ECMA native functions. This
7207 // method sets the class_name field of this function's initial map
7208 // to a given value. It creates an initial map if this function does
7209 // not have one. Note that this method does not copy the initial map
7210 // if it has one already, but simply replaces it with the new value.
7211 // Instances created afterwards will have a map whose [[class]] is
7212 // set to 'value', but there is no guarantees on instances created
7214 void SetInstanceClassName(String* name);
7216 // Returns if this function has been compiled to native code yet.
7217 inline bool is_compiled();
7219 // Returns `false` if formal parameters include rest parameters, optional
7220 // parameters, or destructuring parameters.
7221 // TODO(caitp): make this a flag set during parsing
7222 inline bool has_simple_parameters();
7224 // [next_function_link]: Links functions into various lists, e.g. the list
7225 // of optimized functions hanging off the native_context. The CodeFlusher
7226 // uses this link to chain together flushing candidates. Treated weakly
7227 // by the garbage collector.
7228 DECL_ACCESSORS(next_function_link, Object)
7230 // Prints the name of the function using PrintF.
7231 void PrintName(FILE* out = stdout);
7233 DECLARE_CAST(JSFunction)
7235 // Iterates the objects, including code objects indirectly referenced
7236 // through pointers to the first instruction in the code object.
7237 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7239 // Dispatched behavior.
7240 DECLARE_PRINTER(JSFunction)
7241 DECLARE_VERIFIER(JSFunction)
7243 // Returns the number of allocated literals.
7244 inline int NumberOfLiterals();
7246 // Used for flags such as --hydrogen-filter.
7247 bool PassesFilter(const char* raw_filter);
7249 // The function's name if it is configured, otherwise shared function info
7251 static Handle<String> GetDebugName(Handle<JSFunction> function);
7253 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7254 // kSize) is weak and has special handling during garbage collection.
7255 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7256 static const int kPrototypeOrInitialMapOffset =
7257 kCodeEntryOffset + kPointerSize;
7258 static const int kSharedFunctionInfoOffset =
7259 kPrototypeOrInitialMapOffset + kPointerSize;
7260 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7261 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7262 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7263 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7264 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7266 // Layout of the bound-function binding array.
7267 static const int kBoundFunctionIndex = 0;
7268 static const int kBoundThisIndex = 1;
7269 static const int kBoundArgumentsStartIndex = 2;
7272 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7276 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7277 // and the prototype is hidden. JSGlobalProxy always delegates
7278 // property accesses to its prototype if the prototype is not null.
7280 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7282 // Accessing a JSGlobalProxy requires security check.
7284 class JSGlobalProxy : public JSObject {
7286 // [native_context]: the owner native context of this global proxy object.
7287 // It is null value if this object is not used by any context.
7288 DECL_ACCESSORS(native_context, Object)
7290 // [hash]: The hash code property (undefined if not initialized yet).
7291 DECL_ACCESSORS(hash, Object)
7293 DECLARE_CAST(JSGlobalProxy)
7295 inline bool IsDetachedFrom(GlobalObject* global) const;
7297 // Dispatched behavior.
7298 DECLARE_PRINTER(JSGlobalProxy)
7299 DECLARE_VERIFIER(JSGlobalProxy)
7301 // Layout description.
7302 static const int kNativeContextOffset = JSObject::kHeaderSize;
7303 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7304 static const int kSize = kHashOffset + kPointerSize;
7307 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7311 // Common super class for JavaScript global objects and the special
7312 // builtins global objects.
7313 class GlobalObject: public JSObject {
7315 // [builtins]: the object holding the runtime routines written in JS.
7316 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7318 // [native context]: the natives corresponding to this global object.
7319 DECL_ACCESSORS(native_context, Context)
7321 // [global proxy]: the global proxy object of the context
7322 DECL_ACCESSORS(global_proxy, JSObject)
7324 DECLARE_CAST(GlobalObject)
7326 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7328 // Ensure that the global object has a cell for the given property name.
7329 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7332 // Layout description.
7333 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7334 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7335 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7336 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7339 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7343 // JavaScript global object.
7344 class JSGlobalObject: public GlobalObject {
7346 DECLARE_CAST(JSGlobalObject)
7348 inline bool IsDetached();
7350 // Dispatched behavior.
7351 DECLARE_PRINTER(JSGlobalObject)
7352 DECLARE_VERIFIER(JSGlobalObject)
7354 // Layout description.
7355 static const int kSize = GlobalObject::kHeaderSize;
7358 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7362 // Builtins global object which holds the runtime routines written in
7364 class JSBuiltinsObject: public GlobalObject {
7366 DECLARE_CAST(JSBuiltinsObject)
7368 // Dispatched behavior.
7369 DECLARE_PRINTER(JSBuiltinsObject)
7370 DECLARE_VERIFIER(JSBuiltinsObject)
7372 // Layout description.
7373 static const int kSize = GlobalObject::kHeaderSize;
7376 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7380 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7381 class JSValue: public JSObject {
7383 // [value]: the object being wrapped.
7384 DECL_ACCESSORS(value, Object)
7386 DECLARE_CAST(JSValue)
7388 // Dispatched behavior.
7389 DECLARE_PRINTER(JSValue)
7390 DECLARE_VERIFIER(JSValue)
7392 // Layout description.
7393 static const int kValueOffset = JSObject::kHeaderSize;
7394 static const int kSize = kValueOffset + kPointerSize;
7397 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7403 // Representation for JS date objects.
7404 class JSDate: public JSObject {
7406 // If one component is NaN, all of them are, indicating a NaN time value.
7407 // [value]: the time value.
7408 DECL_ACCESSORS(value, Object)
7409 // [year]: caches year. Either undefined, smi, or NaN.
7410 DECL_ACCESSORS(year, Object)
7411 // [month]: caches month. Either undefined, smi, or NaN.
7412 DECL_ACCESSORS(month, Object)
7413 // [day]: caches day. Either undefined, smi, or NaN.
7414 DECL_ACCESSORS(day, Object)
7415 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7416 DECL_ACCESSORS(weekday, Object)
7417 // [hour]: caches hours. Either undefined, smi, or NaN.
7418 DECL_ACCESSORS(hour, Object)
7419 // [min]: caches minutes. Either undefined, smi, or NaN.
7420 DECL_ACCESSORS(min, Object)
7421 // [sec]: caches seconds. Either undefined, smi, or NaN.
7422 DECL_ACCESSORS(sec, Object)
7423 // [cache stamp]: sample of the date cache stamp at the
7424 // moment when chached fields were cached.
7425 DECL_ACCESSORS(cache_stamp, Object)
7427 DECLARE_CAST(JSDate)
7429 // Returns the date field with the specified index.
7430 // See FieldIndex for the list of date fields.
7431 static Object* GetField(Object* date, Smi* index);
7433 void SetValue(Object* value, bool is_value_nan);
7435 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7436 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7437 Handle<JSReceiver> receiver, Handle<Object> hint);
7439 // Dispatched behavior.
7440 DECLARE_PRINTER(JSDate)
7441 DECLARE_VERIFIER(JSDate)
7443 // The order is important. It must be kept in sync with date macros
7454 kFirstUncachedField,
7455 kMillisecond = kFirstUncachedField,
7459 kYearUTC = kFirstUTCField,
7472 // Layout description.
7473 static const int kValueOffset = JSObject::kHeaderSize;
7474 static const int kYearOffset = kValueOffset + kPointerSize;
7475 static const int kMonthOffset = kYearOffset + kPointerSize;
7476 static const int kDayOffset = kMonthOffset + kPointerSize;
7477 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7478 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7479 static const int kMinOffset = kHourOffset + kPointerSize;
7480 static const int kSecOffset = kMinOffset + kPointerSize;
7481 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7482 static const int kSize = kCacheStampOffset + kPointerSize;
7485 inline Object* DoGetField(FieldIndex index);
7487 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7489 // Computes and caches the cacheable fields of the date.
7490 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7493 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7497 // Representation of message objects used for error reporting through
7498 // the API. The messages are formatted in JavaScript so this object is
7499 // a real JavaScript object. The information used for formatting the
7500 // error messages are not directly accessible from JavaScript to
7501 // prevent leaking information to user code called during error
7503 class JSMessageObject: public JSObject {
7505 // [type]: the type of error message.
7506 inline int type() const;
7507 inline void set_type(int value);
7509 // [arguments]: the arguments for formatting the error message.
7510 DECL_ACCESSORS(argument, Object)
7512 // [script]: the script from which the error message originated.
7513 DECL_ACCESSORS(script, Object)
7515 // [stack_frames]: an array of stack frames for this error object.
7516 DECL_ACCESSORS(stack_frames, Object)
7518 // [start_position]: the start position in the script for the error message.
7519 inline int start_position() const;
7520 inline void set_start_position(int value);
7522 // [end_position]: the end position in the script for the error message.
7523 inline int end_position() const;
7524 inline void set_end_position(int value);
7526 DECLARE_CAST(JSMessageObject)
7528 // Dispatched behavior.
7529 DECLARE_PRINTER(JSMessageObject)
7530 DECLARE_VERIFIER(JSMessageObject)
7532 // Layout description.
7533 static const int kTypeOffset = JSObject::kHeaderSize;
7534 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7535 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7536 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7537 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7538 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7539 static const int kSize = kEndPositionOffset + kPointerSize;
7541 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7542 kStackFramesOffset + kPointerSize,
7543 kSize> BodyDescriptor;
7547 // Regular expressions
7548 // The regular expression holds a single reference to a FixedArray in
7549 // the kDataOffset field.
7550 // The FixedArray contains the following data:
7551 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7552 // - reference to the original source string
7553 // - reference to the original flag string
7554 // If it is an atom regexp
7555 // - a reference to a literal string to search for
7556 // If it is an irregexp regexp:
7557 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7558 // used for tracking the last usage (used for code flushing).
7559 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7560 // used for tracking the last usage (used for code flushing)..
7561 // - max number of registers used by irregexp implementations.
7562 // - number of capture registers (output values) of the regexp.
7563 class JSRegExp: public JSObject {
7566 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7567 // ATOM: A simple string to match against using an indexOf operation.
7568 // IRREGEXP: Compiled with Irregexp.
7569 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7570 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7577 UNICODE_ESCAPES = 16
7582 explicit Flags(uint32_t value) : value_(value) { }
7583 bool is_global() { return (value_ & GLOBAL) != 0; }
7584 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7585 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7586 bool is_sticky() { return (value_ & STICKY) != 0; }
7587 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7588 uint32_t value() { return value_; }
7593 DECL_ACCESSORS(data, Object)
7595 inline Type TypeTag();
7596 inline int CaptureCount();
7597 inline Flags GetFlags();
7598 inline String* Pattern();
7599 inline Object* DataAt(int index);
7600 // Set implementation data after the object has been prepared.
7601 inline void SetDataAt(int index, Object* value);
7603 static int code_index(bool is_latin1) {
7605 return kIrregexpLatin1CodeIndex;
7607 return kIrregexpUC16CodeIndex;
7611 static int saved_code_index(bool is_latin1) {
7613 return kIrregexpLatin1CodeSavedIndex;
7615 return kIrregexpUC16CodeSavedIndex;
7619 DECLARE_CAST(JSRegExp)
7621 // Dispatched behavior.
7622 DECLARE_VERIFIER(JSRegExp)
7624 static const int kDataOffset = JSObject::kHeaderSize;
7625 static const int kSize = kDataOffset + kPointerSize;
7627 // Indices in the data array.
7628 static const int kTagIndex = 0;
7629 static const int kSourceIndex = kTagIndex + 1;
7630 static const int kFlagsIndex = kSourceIndex + 1;
7631 static const int kDataIndex = kFlagsIndex + 1;
7632 // The data fields are used in different ways depending on the
7633 // value of the tag.
7634 // Atom regexps (literal strings).
7635 static const int kAtomPatternIndex = kDataIndex;
7637 static const int kAtomDataSize = kAtomPatternIndex + 1;
7639 // Irregexp compiled code or bytecode for Latin1. If compilation
7640 // fails, this fields hold an exception object that should be
7641 // thrown if the regexp is used again.
7642 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7643 // Irregexp compiled code or bytecode for UC16. If compilation
7644 // fails, this fields hold an exception object that should be
7645 // thrown if the regexp is used again.
7646 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7648 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7649 // is a potential candidate for flushing.
7650 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7651 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7652 // a potential candidate for flushing.
7653 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7655 // Maximal number of registers used by either Latin1 or UC16.
7656 // Only used to check that there is enough stack space
7657 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7658 // Number of captures in the compiled regexp.
7659 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7661 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7663 // Offsets directly into the data fixed array.
7664 static const int kDataTagOffset =
7665 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7666 static const int kDataOneByteCodeOffset =
7667 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7668 static const int kDataUC16CodeOffset =
7669 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7670 static const int kIrregexpCaptureCountOffset =
7671 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7673 // In-object fields.
7674 static const int kSourceFieldIndex = 0;
7675 static const int kGlobalFieldIndex = 1;
7676 static const int kIgnoreCaseFieldIndex = 2;
7677 static const int kMultilineFieldIndex = 3;
7678 static const int kLastIndexFieldIndex = 4;
7679 static const int kInObjectFieldCount = 5;
7681 // The uninitialized value for a regexp code object.
7682 static const int kUninitializedValue = -1;
7684 // The compilation error value for the regexp code object. The real error
7685 // object is in the saved code field.
7686 static const int kCompilationErrorValue = -2;
7688 // When we store the sweep generation at which we moved the code from the
7689 // code index to the saved code index we mask it of to be in the [0:255]
7691 static const int kCodeAgeMask = 0xff;
7695 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7697 static inline bool IsMatch(HashTableKey* key, Object* value) {
7698 return key->IsMatch(value);
7701 static inline uint32_t Hash(HashTableKey* key) {
7705 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7706 return key->HashForObject(object);
7709 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7711 static const int kPrefixSize = 0;
7712 static const int kEntrySize = 2;
7716 // This cache is used in two different variants. For regexp caching, it simply
7717 // maps identifying info of the regexp to the cached regexp object. Scripts and
7718 // eval code only gets cached after a second probe for the code object. To do
7719 // so, on first "put" only a hash identifying the source is entered into the
7720 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7721 // such lifetimes get reduced, and removed once they reach zero. If a second put
7722 // is called while such a hash is live in the cache, the hash gets replaced by
7723 // an actual cache entry. Age also removes stale live entries from the cache.
7724 // Such entries are identified by SharedFunctionInfos pointing to either the
7725 // recompilation stub, or to "old" code. This avoids memory leaks due to
7726 // premature caching of scripts and eval strings that are never needed later.
7727 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7728 CompilationCacheShape,
7731 // Find cached value for a string key, otherwise return null.
7732 Handle<Object> Lookup(
7733 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7734 Handle<Object> LookupEval(
7735 Handle<String> src, Handle<SharedFunctionInfo> shared,
7736 LanguageMode language_mode, int scope_position);
7737 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7738 static Handle<CompilationCacheTable> Put(
7739 Handle<CompilationCacheTable> cache, Handle<String> src,
7740 Handle<Context> context, LanguageMode language_mode,
7741 Handle<Object> value);
7742 static Handle<CompilationCacheTable> PutEval(
7743 Handle<CompilationCacheTable> cache, Handle<String> src,
7744 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7745 int scope_position);
7746 static Handle<CompilationCacheTable> PutRegExp(
7747 Handle<CompilationCacheTable> cache, Handle<String> src,
7748 JSRegExp::Flags flags, Handle<FixedArray> value);
7749 void Remove(Object* value);
7751 static const int kHashGenerations = 10;
7753 DECLARE_CAST(CompilationCacheTable)
7756 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7760 class CodeCache: public Struct {
7762 DECL_ACCESSORS(default_cache, FixedArray)
7763 DECL_ACCESSORS(normal_type_cache, Object)
7765 // Add the code object to the cache.
7767 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7769 // Lookup code object in the cache. Returns code object if found and undefined
7771 Object* Lookup(Name* name, Code::Flags flags);
7773 // Get the internal index of a code object in the cache. Returns -1 if the
7774 // code object is not in that cache. This index can be used to later call
7775 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7777 int GetIndex(Object* name, Code* code);
7779 // Remove an object from the cache with the provided internal index.
7780 void RemoveByIndex(Object* name, Code* code, int index);
7782 DECLARE_CAST(CodeCache)
7784 // Dispatched behavior.
7785 DECLARE_PRINTER(CodeCache)
7786 DECLARE_VERIFIER(CodeCache)
7788 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7789 static const int kNormalTypeCacheOffset =
7790 kDefaultCacheOffset + kPointerSize;
7791 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7794 static void UpdateDefaultCache(
7795 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7796 static void UpdateNormalTypeCache(
7797 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7798 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7799 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7801 // Code cache layout of the default cache. Elements are alternating name and
7802 // code objects for non normal load/store/call IC's.
7803 static const int kCodeCacheEntrySize = 2;
7804 static const int kCodeCacheEntryNameOffset = 0;
7805 static const int kCodeCacheEntryCodeOffset = 1;
7807 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7811 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7813 static inline bool IsMatch(HashTableKey* key, Object* value) {
7814 return key->IsMatch(value);
7817 static inline uint32_t Hash(HashTableKey* key) {
7821 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7822 return key->HashForObject(object);
7825 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7827 static const int kPrefixSize = 0;
7828 static const int kEntrySize = 2;
7832 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7833 CodeCacheHashTableShape,
7836 Object* Lookup(Name* name, Code::Flags flags);
7837 static Handle<CodeCacheHashTable> Put(
7838 Handle<CodeCacheHashTable> table,
7842 int GetIndex(Name* name, Code::Flags flags);
7843 void RemoveByIndex(int index);
7845 DECLARE_CAST(CodeCacheHashTable)
7847 // Initial size of the fixed array backing the hash table.
7848 static const int kInitialSize = 64;
7851 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7855 class PolymorphicCodeCache: public Struct {
7857 DECL_ACCESSORS(cache, Object)
7859 static void Update(Handle<PolymorphicCodeCache> cache,
7860 MapHandleList* maps,
7865 // Returns an undefined value if the entry is not found.
7866 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7868 DECLARE_CAST(PolymorphicCodeCache)
7870 // Dispatched behavior.
7871 DECLARE_PRINTER(PolymorphicCodeCache)
7872 DECLARE_VERIFIER(PolymorphicCodeCache)
7874 static const int kCacheOffset = HeapObject::kHeaderSize;
7875 static const int kSize = kCacheOffset + kPointerSize;
7878 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7882 class PolymorphicCodeCacheHashTable
7883 : public HashTable<PolymorphicCodeCacheHashTable,
7884 CodeCacheHashTableShape,
7887 Object* Lookup(MapHandleList* maps, int code_kind);
7889 static Handle<PolymorphicCodeCacheHashTable> Put(
7890 Handle<PolymorphicCodeCacheHashTable> hash_table,
7891 MapHandleList* maps,
7895 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7897 static const int kInitialSize = 64;
7899 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7903 class TypeFeedbackInfo: public Struct {
7905 inline int ic_total_count();
7906 inline void set_ic_total_count(int count);
7908 inline int ic_with_type_info_count();
7909 inline void change_ic_with_type_info_count(int delta);
7911 inline int ic_generic_count();
7912 inline void change_ic_generic_count(int delta);
7914 inline void initialize_storage();
7916 inline void change_own_type_change_checksum();
7917 inline int own_type_change_checksum();
7919 inline void set_inlined_type_change_checksum(int checksum);
7920 inline bool matches_inlined_type_change_checksum(int checksum);
7922 DECLARE_CAST(TypeFeedbackInfo)
7924 // Dispatched behavior.
7925 DECLARE_PRINTER(TypeFeedbackInfo)
7926 DECLARE_VERIFIER(TypeFeedbackInfo)
7928 static const int kStorage1Offset = HeapObject::kHeaderSize;
7929 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7930 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7931 static const int kSize = kStorage3Offset + kPointerSize;
7934 static const int kTypeChangeChecksumBits = 7;
7936 class ICTotalCountField: public BitField<int, 0,
7937 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7938 class OwnTypeChangeChecksum: public BitField<int,
7939 kSmiValueSize - kTypeChangeChecksumBits,
7940 kTypeChangeChecksumBits> {}; // NOLINT
7941 class ICsWithTypeInfoCountField: public BitField<int, 0,
7942 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7943 class InlinedTypeChangeChecksum: public BitField<int,
7944 kSmiValueSize - kTypeChangeChecksumBits,
7945 kTypeChangeChecksumBits> {}; // NOLINT
7947 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7951 enum AllocationSiteMode {
7952 DONT_TRACK_ALLOCATION_SITE,
7953 TRACK_ALLOCATION_SITE,
7954 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7958 class AllocationSite: public Struct {
7960 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7961 static const double kPretenureRatio;
7962 static const int kPretenureMinimumCreated = 100;
7964 // Values for pretenure decision field.
7965 enum PretenureDecision {
7971 kLastPretenureDecisionValue = kZombie
7974 const char* PretenureDecisionName(PretenureDecision decision);
7976 DECL_ACCESSORS(transition_info, Object)
7977 // nested_site threads a list of sites that represent nested literals
7978 // walked in a particular order. So [[1, 2], 1, 2] will have one
7979 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7980 DECL_ACCESSORS(nested_site, Object)
7981 DECL_INT_ACCESSORS(pretenure_data)
7982 DECL_INT_ACCESSORS(pretenure_create_count)
7983 DECL_ACCESSORS(dependent_code, DependentCode)
7984 DECL_ACCESSORS(weak_next, Object)
7986 inline void Initialize();
7988 // This method is expensive, it should only be called for reporting.
7989 bool IsNestedSite();
7991 // transition_info bitfields, for constructed array transition info.
7992 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7993 class UnusedBits: public BitField<int, 15, 14> {};
7994 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7996 // Bitfields for pretenure_data
7997 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7998 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7999 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8000 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8002 // Increments the mementos found counter and returns true when the first
8003 // memento was found for a given allocation site.
8004 inline bool IncrementMementoFoundCount();
8006 inline void IncrementMementoCreateCount();
8008 PretenureFlag GetPretenureMode();
8010 void ResetPretenureDecision();
8012 inline PretenureDecision pretenure_decision();
8013 inline void set_pretenure_decision(PretenureDecision decision);
8015 inline bool deopt_dependent_code();
8016 inline void set_deopt_dependent_code(bool deopt);
8018 inline int memento_found_count();
8019 inline void set_memento_found_count(int count);
8021 inline int memento_create_count();
8022 inline void set_memento_create_count(int count);
8024 // The pretenuring decision is made during gc, and the zombie state allows
8025 // us to recognize when an allocation site is just being kept alive because
8026 // a later traversal of new space may discover AllocationMementos that point
8027 // to this AllocationSite.
8028 inline bool IsZombie();
8030 inline bool IsMaybeTenure();
8032 inline void MarkZombie();
8034 inline bool MakePretenureDecision(PretenureDecision current_decision,
8036 bool maximum_size_scavenge);
8038 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8040 inline ElementsKind GetElementsKind();
8041 inline void SetElementsKind(ElementsKind kind);
8043 inline bool CanInlineCall();
8044 inline void SetDoNotInlineCall();
8046 inline bool SitePointsToLiteral();
8048 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8049 ElementsKind to_kind);
8051 DECLARE_PRINTER(AllocationSite)
8052 DECLARE_VERIFIER(AllocationSite)
8054 DECLARE_CAST(AllocationSite)
8055 static inline AllocationSiteMode GetMode(
8056 ElementsKind boilerplate_elements_kind);
8057 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8058 static inline bool CanTrack(InstanceType type);
8060 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8061 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8062 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8063 static const int kPretenureCreateCountOffset =
8064 kPretenureDataOffset + kPointerSize;
8065 static const int kDependentCodeOffset =
8066 kPretenureCreateCountOffset + kPointerSize;
8067 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8068 static const int kSize = kWeakNextOffset + kPointerSize;
8070 // During mark compact we need to take special care for the dependent code
8072 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8073 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8075 // For other visitors, use the fixed body descriptor below.
8076 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8077 kDependentCodeOffset + kPointerSize,
8078 kSize> BodyDescriptor;
8081 inline bool PretenuringDecisionMade();
8083 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8087 class AllocationMemento: public Struct {
8089 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8090 static const int kSize = kAllocationSiteOffset + kPointerSize;
8092 DECL_ACCESSORS(allocation_site, Object)
8094 inline bool IsValid();
8095 inline AllocationSite* GetAllocationSite();
8097 DECLARE_PRINTER(AllocationMemento)
8098 DECLARE_VERIFIER(AllocationMemento)
8100 DECLARE_CAST(AllocationMemento)
8103 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8107 // Representation of a slow alias as part of a sloppy arguments objects.
8108 // For fast aliases (if HasSloppyArgumentsElements()):
8109 // - the parameter map contains an index into the context
8110 // - all attributes of the element have default values
8111 // For slow aliases (if HasDictionaryArgumentsElements()):
8112 // - the parameter map contains no fast alias mapping (i.e. the hole)
8113 // - this struct (in the slow backing store) contains an index into the context
8114 // - all attributes are available as part if the property details
8115 class AliasedArgumentsEntry: public Struct {
8117 inline int aliased_context_slot() const;
8118 inline void set_aliased_context_slot(int count);
8120 DECLARE_CAST(AliasedArgumentsEntry)
8122 // Dispatched behavior.
8123 DECLARE_PRINTER(AliasedArgumentsEntry)
8124 DECLARE_VERIFIER(AliasedArgumentsEntry)
8126 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8127 static const int kSize = kAliasedContextSlot + kPointerSize;
8130 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8134 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8135 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8138 class StringHasher {
8140 explicit inline StringHasher(int length, uint32_t seed);
8142 template <typename schar>
8143 static inline uint32_t HashSequentialString(const schar* chars,
8147 // Reads all the data, even for long strings and computes the utf16 length.
8148 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8150 int* utf16_length_out);
8152 // Calculated hash value for a string consisting of 1 to
8153 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8154 // value is represented decimal value.
8155 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8157 // No string is allowed to have a hash of zero. That value is reserved
8158 // for internal properties. If the hash calculation yields zero then we
8160 static const int kZeroHash = 27;
8162 // Reusable parts of the hashing algorithm.
8163 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8164 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8165 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8166 const uc16* chars, int length));
8167 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8172 // Returns the value to store in the hash field of a string with
8173 // the given length and contents.
8174 uint32_t GetHashField();
8175 // Returns true if the hash of this string can be computed without
8176 // looking at the contents.
8177 inline bool has_trivial_hash();
8178 // Adds a block of characters to the hash.
8179 template<typename Char>
8180 inline void AddCharacters(const Char* chars, int len);
8183 // Add a character to the hash.
8184 inline void AddCharacter(uint16_t c);
8185 // Update index. Returns true if string is still an index.
8186 inline bool UpdateIndex(uint16_t c);
8189 uint32_t raw_running_hash_;
8190 uint32_t array_index_;
8191 bool is_array_index_;
8192 bool is_first_char_;
8193 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8197 class IteratingStringHasher : public StringHasher {
8199 static inline uint32_t Hash(String* string, uint32_t seed);
8200 inline void VisitOneByteString(const uint8_t* chars, int length);
8201 inline void VisitTwoByteString(const uint16_t* chars, int length);
8204 inline IteratingStringHasher(int len, uint32_t seed);
8205 void VisitConsString(ConsString* cons_string);
8206 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8210 // The characteristics of a string are stored in its map. Retrieving these
8211 // few bits of information is moderately expensive, involving two memory
8212 // loads where the second is dependent on the first. To improve efficiency
8213 // the shape of the string is given its own class so that it can be retrieved
8214 // once and used for several string operations. A StringShape is small enough
8215 // to be passed by value and is immutable, but be aware that flattening a
8216 // string can potentially alter its shape. Also be aware that a GC caused by
8217 // something else can alter the shape of a string due to ConsString
8218 // shortcutting. Keeping these restrictions in mind has proven to be error-
8219 // prone and so we no longer put StringShapes in variables unless there is a
8220 // concrete performance benefit at that particular point in the code.
8221 class StringShape BASE_EMBEDDED {
8223 inline explicit StringShape(const String* s);
8224 inline explicit StringShape(Map* s);
8225 inline explicit StringShape(InstanceType t);
8226 inline bool IsSequential();
8227 inline bool IsExternal();
8228 inline bool IsCons();
8229 inline bool IsSliced();
8230 inline bool IsIndirect();
8231 inline bool IsExternalOneByte();
8232 inline bool IsExternalTwoByte();
8233 inline bool IsSequentialOneByte();
8234 inline bool IsSequentialTwoByte();
8235 inline bool IsInternalized();
8236 inline StringRepresentationTag representation_tag();
8237 inline uint32_t encoding_tag();
8238 inline uint32_t full_representation_tag();
8239 inline uint32_t size_tag();
8241 inline uint32_t type() { return type_; }
8242 inline void invalidate() { valid_ = false; }
8243 inline bool valid() { return valid_; }
8245 inline void invalidate() { }
8251 inline void set_valid() { valid_ = true; }
8254 inline void set_valid() { }
8259 // The Name abstract class captures anything that can be used as a property
8260 // name, i.e., strings and symbols. All names store a hash value.
8261 class Name: public HeapObject {
8263 // Get and set the hash field of the name.
8264 inline uint32_t hash_field();
8265 inline void set_hash_field(uint32_t value);
8267 // Tells whether the hash code has been computed.
8268 inline bool HasHashCode();
8270 // Returns a hash value used for the property table
8271 inline uint32_t Hash();
8273 // Equality operations.
8274 inline bool Equals(Name* other);
8275 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8278 inline bool AsArrayIndex(uint32_t* index);
8280 // If the name is private, it can only name own properties.
8281 inline bool IsPrivate();
8283 // If the name is a non-flat string, this method returns a flat version of the
8284 // string. Otherwise it'll just return the input.
8285 static inline Handle<Name> Flatten(Handle<Name> name,
8286 PretenureFlag pretenure = NOT_TENURED);
8288 // Return a string version of this name that is converted according to the
8289 // rules described in ES6 section 9.2.11.
8290 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8294 DECLARE_PRINTER(Name)
8296 void NameShortPrint();
8297 int NameShortPrint(Vector<char> str);
8300 // Layout description.
8301 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8302 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8303 static const int kHashFieldOffset = kHashFieldSlot;
8305 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8307 static const int kSize = kHashFieldSlot + kPointerSize;
8309 // Mask constant for checking if a name has a computed hash code
8310 // and if it is a string that is an array index. The least significant bit
8311 // indicates whether a hash code has been computed. If the hash code has
8312 // been computed the 2nd bit tells whether the string can be used as an
8314 static const int kHashNotComputedMask = 1;
8315 static const int kIsNotArrayIndexMask = 1 << 1;
8316 static const int kNofHashBitFields = 2;
8318 // Shift constant retrieving hash code from hash field.
8319 static const int kHashShift = kNofHashBitFields;
8321 // Only these bits are relevant in the hash, since the top two are shifted
8323 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8325 // Array index strings this short can keep their index in the hash field.
8326 static const int kMaxCachedArrayIndexLength = 7;
8328 // For strings which are array indexes the hash value has the string length
8329 // mixed into the hash, mainly to avoid a hash value of zero which would be
8330 // the case for the string '0'. 24 bits are used for the array index value.
8331 static const int kArrayIndexValueBits = 24;
8332 static const int kArrayIndexLengthBits =
8333 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8335 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8337 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8338 kArrayIndexValueBits> {}; // NOLINT
8339 class ArrayIndexLengthBits : public BitField<unsigned int,
8340 kNofHashBitFields + kArrayIndexValueBits,
8341 kArrayIndexLengthBits> {}; // NOLINT
8343 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8344 // could use a mask to test if the length of string is less than or equal to
8345 // kMaxCachedArrayIndexLength.
8346 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8348 static const unsigned int kContainsCachedArrayIndexMask =
8349 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8350 << ArrayIndexLengthBits::kShift) |
8351 kIsNotArrayIndexMask;
8353 // Value of empty hash field indicating that the hash is not computed.
8354 static const int kEmptyHashField =
8355 kIsNotArrayIndexMask | kHashNotComputedMask;
8358 static inline bool IsHashFieldComputed(uint32_t field);
8361 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8366 class Symbol: public Name {
8368 // [name]: The print name of a symbol, or undefined if none.
8369 DECL_ACCESSORS(name, Object)
8371 DECL_INT_ACCESSORS(flags)
8373 // [is_private]: Whether this is a private symbol. Private symbols can only
8374 // be used to designate own properties of objects.
8375 DECL_BOOLEAN_ACCESSORS(is_private)
8377 DECLARE_CAST(Symbol)
8379 // Dispatched behavior.
8380 DECLARE_PRINTER(Symbol)
8381 DECLARE_VERIFIER(Symbol)
8383 // Layout description.
8384 static const int kNameOffset = Name::kSize;
8385 static const int kFlagsOffset = kNameOffset + kPointerSize;
8386 static const int kSize = kFlagsOffset + kPointerSize;
8388 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8390 void SymbolShortPrint(std::ostream& os);
8393 static const int kPrivateBit = 0;
8395 const char* PrivateSymbolToName() const;
8398 friend class Name; // For PrivateSymbolToName.
8401 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8407 // The String abstract class captures JavaScript string values:
8410 // 4.3.16 String Value
8411 // A string value is a member of the type String and is a finite
8412 // ordered sequence of zero or more 16-bit unsigned integer values.
8414 // All string values have a length field.
8415 class String: public Name {
8417 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8419 // Array index strings this short can keep their index in the hash field.
8420 static const int kMaxCachedArrayIndexLength = 7;
8422 // For strings which are array indexes the hash value has the string length
8423 // mixed into the hash, mainly to avoid a hash value of zero which would be
8424 // the case for the string '0'. 24 bits are used for the array index value.
8425 static const int kArrayIndexValueBits = 24;
8426 static const int kArrayIndexLengthBits =
8427 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8429 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8431 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8432 kArrayIndexValueBits> {}; // NOLINT
8433 class ArrayIndexLengthBits : public BitField<unsigned int,
8434 kNofHashBitFields + kArrayIndexValueBits,
8435 kArrayIndexLengthBits> {}; // NOLINT
8437 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8438 // could use a mask to test if the length of string is less than or equal to
8439 // kMaxCachedArrayIndexLength.
8440 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8442 static const unsigned int kContainsCachedArrayIndexMask =
8443 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8444 << ArrayIndexLengthBits::kShift) |
8445 kIsNotArrayIndexMask;
8447 class SubStringRange {
8449 explicit inline SubStringRange(String* string, int first = 0,
8452 inline iterator begin();
8453 inline iterator end();
8461 // Representation of the flat content of a String.
8462 // A non-flat string doesn't have flat content.
8463 // A flat string has content that's encoded as a sequence of either
8464 // one-byte chars or two-byte UC16.
8465 // Returned by String::GetFlatContent().
8468 // Returns true if the string is flat and this structure contains content.
8469 bool IsFlat() { return state_ != NON_FLAT; }
8470 // Returns true if the structure contains one-byte content.
8471 bool IsOneByte() { return state_ == ONE_BYTE; }
8472 // Returns true if the structure contains two-byte content.
8473 bool IsTwoByte() { return state_ == TWO_BYTE; }
8475 // Return the one byte content of the string. Only use if IsOneByte()
8477 Vector<const uint8_t> ToOneByteVector() {
8478 DCHECK_EQ(ONE_BYTE, state_);
8479 return Vector<const uint8_t>(onebyte_start, length_);
8481 // Return the two-byte content of the string. Only use if IsTwoByte()
8483 Vector<const uc16> ToUC16Vector() {
8484 DCHECK_EQ(TWO_BYTE, state_);
8485 return Vector<const uc16>(twobyte_start, length_);
8489 DCHECK(i < length_);
8490 DCHECK(state_ != NON_FLAT);
8491 if (state_ == ONE_BYTE) return onebyte_start[i];
8492 return twobyte_start[i];
8495 bool UsesSameString(const FlatContent& other) const {
8496 return onebyte_start == other.onebyte_start;
8500 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8502 // Constructors only used by String::GetFlatContent().
8503 explicit FlatContent(const uint8_t* start, int length)
8504 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8505 explicit FlatContent(const uc16* start, int length)
8506 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8507 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8510 const uint8_t* onebyte_start;
8511 const uc16* twobyte_start;
8516 friend class String;
8517 friend class IterableSubString;
8520 template <typename Char>
8521 INLINE(Vector<const Char> GetCharVector());
8523 // Get and set the length of the string.
8524 inline int length() const;
8525 inline void set_length(int value);
8527 // Get and set the length of the string using acquire loads and release
8529 inline int synchronized_length() const;
8530 inline void synchronized_set_length(int value);
8532 // Returns whether this string has only one-byte chars, i.e. all of them can
8533 // be one-byte encoded. This might be the case even if the string is
8534 // two-byte. Such strings may appear when the embedder prefers
8535 // two-byte external representations even for one-byte data.
8536 inline bool IsOneByteRepresentation() const;
8537 inline bool IsTwoByteRepresentation() const;
8539 // Cons and slices have an encoding flag that may not represent the actual
8540 // encoding of the underlying string. This is taken into account here.
8541 // Requires: this->IsFlat()
8542 inline bool IsOneByteRepresentationUnderneath();
8543 inline bool IsTwoByteRepresentationUnderneath();
8545 // NOTE: this should be considered only a hint. False negatives are
8547 inline bool HasOnlyOneByteChars();
8549 // Get and set individual two byte chars in the string.
8550 inline void Set(int index, uint16_t value);
8551 // Get individual two byte char in the string. Repeated calls
8552 // to this method are not efficient unless the string is flat.
8553 INLINE(uint16_t Get(int index));
8555 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8556 static Handle<Object> ToNumber(Handle<String> subject);
8558 // Flattens the string. Checks first inline to see if it is
8559 // necessary. Does nothing if the string is not a cons string.
8560 // Flattening allocates a sequential string with the same data as
8561 // the given string and mutates the cons string to a degenerate
8562 // form, where the first component is the new sequential string and
8563 // the second component is the empty string. If allocation fails,
8564 // this function returns a failure. If flattening succeeds, this
8565 // function returns the sequential string that is now the first
8566 // component of the cons string.
8568 // Degenerate cons strings are handled specially by the garbage
8569 // collector (see IsShortcutCandidate).
8571 static inline Handle<String> Flatten(Handle<String> string,
8572 PretenureFlag pretenure = NOT_TENURED);
8574 // Tries to return the content of a flat string as a structure holding either
8575 // a flat vector of char or of uc16.
8576 // If the string isn't flat, and therefore doesn't have flat content, the
8577 // returned structure will report so, and can't provide a vector of either
8579 FlatContent GetFlatContent();
8581 // Returns the parent of a sliced string or first part of a flat cons string.
8582 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8583 inline String* GetUnderlying();
8585 // String relational comparison, implemented according to ES6 section 7.2.11
8586 // Abstract Relational Comparison (step 5): The comparison of Strings uses a
8587 // simple lexicographic ordering on sequences of code unit values. There is no
8588 // attempt to use the more complex, semantically oriented definitions of
8589 // character or string equality and collating order defined in the Unicode
8590 // specification. Therefore String values that are canonically equal according
8591 // to the Unicode standard could test as unequal. In effect this algorithm
8592 // assumes that both Strings are already in normalized form. Also, note that
8593 // for strings containing supplementary characters, lexicographic ordering on
8594 // sequences of UTF-16 code unit values differs from that on sequences of code
8596 MUST_USE_RESULT static ComparisonResult Compare(Handle<String> x,
8599 // String equality operations.
8600 inline bool Equals(String* other);
8601 inline static bool Equals(Handle<String> one, Handle<String> two);
8602 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8603 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8604 bool IsTwoByteEqualTo(Vector<const uc16> str);
8606 // Return a UTF8 representation of the string. The string is null
8607 // terminated but may optionally contain nulls. Length is returned
8608 // in length_output if length_output is not a null pointer The string
8609 // should be nearly flat, otherwise the performance of this method may
8610 // be very slow (quadratic in the length). Setting robustness_flag to
8611 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8612 // handles unexpected data without causing assert failures and it does not
8613 // do any heap allocations. This is useful when printing stack traces.
8614 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8615 RobustnessFlag robustness_flag,
8616 int offset, int length,
8617 int* length_output = 0);
8618 base::SmartArrayPointer<char> ToCString(
8619 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8620 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8621 int* length_output = 0);
8623 // Return a 16 bit Unicode representation of the string.
8624 // The string should be nearly flat, otherwise the performance of
8625 // of this method may be very bad. Setting robustness_flag to
8626 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8627 // handles unexpected data without causing assert failures and it does not
8628 // do any heap allocations. This is useful when printing stack traces.
8629 base::SmartArrayPointer<uc16> ToWideCString(
8630 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8632 bool ComputeArrayIndex(uint32_t* index);
8635 bool MakeExternal(v8::String::ExternalStringResource* resource);
8636 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8639 inline bool AsArrayIndex(uint32_t* index);
8641 DECLARE_CAST(String)
8643 void PrintOn(FILE* out);
8645 // For use during stack traces. Performs rudimentary sanity check.
8648 // Dispatched behavior.
8649 void StringShortPrint(StringStream* accumulator);
8650 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8651 #if defined(DEBUG) || defined(OBJECT_PRINT)
8652 char* ToAsciiArray();
8654 DECLARE_PRINTER(String)
8655 DECLARE_VERIFIER(String)
8657 inline bool IsFlat();
8659 // Layout description.
8660 static const int kLengthOffset = Name::kSize;
8661 static const int kSize = kLengthOffset + kPointerSize;
8663 // Maximum number of characters to consider when trying to convert a string
8664 // value into an array index.
8665 static const int kMaxArrayIndexSize = 10;
8666 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8669 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8670 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8671 static const int kMaxUtf16CodeUnit = 0xffff;
8672 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8674 // Value of hash field containing computed hash equal to zero.
8675 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8677 // Maximal string length.
8678 static const int kMaxLength = (1 << 28) - 16;
8680 // Max length for computing hash. For strings longer than this limit the
8681 // string length is used as the hash value.
8682 static const int kMaxHashCalcLength = 16383;
8684 // Limit for truncation in short printing.
8685 static const int kMaxShortPrintLength = 1024;
8687 // Support for regular expressions.
8688 const uc16* GetTwoByteData(unsigned start);
8690 // Helper function for flattening strings.
8691 template <typename sinkchar>
8692 static void WriteToFlat(String* source,
8697 // The return value may point to the first aligned word containing the first
8698 // non-one-byte character, rather than directly to the non-one-byte character.
8699 // If the return value is >= the passed length, the entire string was
8701 static inline int NonAsciiStart(const char* chars, int length) {
8702 const char* start = chars;
8703 const char* limit = chars + length;
8705 if (length >= kIntptrSize) {
8706 // Check unaligned bytes.
8707 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8708 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8709 return static_cast<int>(chars - start);
8713 // Check aligned words.
8714 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8715 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8716 while (chars + sizeof(uintptr_t) <= limit) {
8717 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8718 return static_cast<int>(chars - start);
8720 chars += sizeof(uintptr_t);
8723 // Check remaining unaligned bytes.
8724 while (chars < limit) {
8725 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8726 return static_cast<int>(chars - start);
8731 return static_cast<int>(chars - start);
8734 static inline bool IsAscii(const char* chars, int length) {
8735 return NonAsciiStart(chars, length) >= length;
8738 static inline bool IsAscii(const uint8_t* chars, int length) {
8740 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8743 static inline int NonOneByteStart(const uc16* chars, int length) {
8744 const uc16* limit = chars + length;
8745 const uc16* start = chars;
8746 while (chars < limit) {
8747 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8750 return static_cast<int>(chars - start);
8753 static inline bool IsOneByte(const uc16* chars, int length) {
8754 return NonOneByteStart(chars, length) >= length;
8757 template<class Visitor>
8758 static inline ConsString* VisitFlat(Visitor* visitor,
8762 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8763 bool include_ending_line);
8765 // Use the hash field to forward to the canonical internalized string
8766 // when deserializing an internalized string.
8767 inline void SetForwardedInternalizedString(String* string);
8768 inline String* GetForwardedInternalizedString();
8772 friend class StringTableInsertionKey;
8774 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8775 PretenureFlag tenure);
8777 // Slow case of String::Equals. This implementation works on any strings
8778 // but it is most efficient on strings that are almost flat.
8779 bool SlowEquals(String* other);
8781 static bool SlowEquals(Handle<String> one, Handle<String> two);
8783 // Slow case of AsArrayIndex.
8784 bool SlowAsArrayIndex(uint32_t* index);
8786 // Compute and set the hash code.
8787 uint32_t ComputeAndSetHash();
8789 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8793 // The SeqString abstract class captures sequential string values.
8794 class SeqString: public String {
8796 DECLARE_CAST(SeqString)
8798 // Layout description.
8799 static const int kHeaderSize = String::kSize;
8801 // Truncate the string in-place if possible and return the result.
8802 // In case of new_length == 0, the empty string is returned without
8803 // truncating the original string.
8804 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8807 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8811 // The OneByteString class captures sequential one-byte string objects.
8812 // Each character in the OneByteString is an one-byte character.
8813 class SeqOneByteString: public SeqString {
8815 static const bool kHasOneByteEncoding = true;
8817 // Dispatched behavior.
8818 inline uint16_t SeqOneByteStringGet(int index);
8819 inline void SeqOneByteStringSet(int index, uint16_t value);
8821 // Get the address of the characters in this string.
8822 inline Address GetCharsAddress();
8824 inline uint8_t* GetChars();
8826 DECLARE_CAST(SeqOneByteString)
8828 // Garbage collection support. This method is called by the
8829 // garbage collector to compute the actual size of an OneByteString
8831 inline int SeqOneByteStringSize(InstanceType instance_type);
8833 // Computes the size for an OneByteString instance of a given length.
8834 static int SizeFor(int length) {
8835 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8838 // Maximal memory usage for a single sequential one-byte string.
8839 static const int kMaxSize = 512 * MB - 1;
8840 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8843 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8847 // The TwoByteString class captures sequential unicode string objects.
8848 // Each character in the TwoByteString is a two-byte uint16_t.
8849 class SeqTwoByteString: public SeqString {
8851 static const bool kHasOneByteEncoding = false;
8853 // Dispatched behavior.
8854 inline uint16_t SeqTwoByteStringGet(int index);
8855 inline void SeqTwoByteStringSet(int index, uint16_t value);
8857 // Get the address of the characters in this string.
8858 inline Address GetCharsAddress();
8860 inline uc16* GetChars();
8863 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8865 DECLARE_CAST(SeqTwoByteString)
8867 // Garbage collection support. This method is called by the
8868 // garbage collector to compute the actual size of a TwoByteString
8870 inline int SeqTwoByteStringSize(InstanceType instance_type);
8872 // Computes the size for a TwoByteString instance of a given length.
8873 static int SizeFor(int length) {
8874 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8877 // Maximal memory usage for a single sequential two-byte string.
8878 static const int kMaxSize = 512 * MB - 1;
8879 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8880 String::kMaxLength);
8883 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8887 // The ConsString class describes string values built by using the
8888 // addition operator on strings. A ConsString is a pair where the
8889 // first and second components are pointers to other string values.
8890 // One or both components of a ConsString can be pointers to other
8891 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8892 // are non-ConsString string values. The string value represented by
8893 // a ConsString can be obtained by concatenating the leaf string
8894 // values in a left-to-right depth-first traversal of the tree.
8895 class ConsString: public String {
8897 // First string of the cons cell.
8898 inline String* first();
8899 // Doesn't check that the result is a string, even in debug mode. This is
8900 // useful during GC where the mark bits confuse the checks.
8901 inline Object* unchecked_first();
8902 inline void set_first(String* first,
8903 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8905 // Second string of the cons cell.
8906 inline String* second();
8907 // Doesn't check that the result is a string, even in debug mode. This is
8908 // useful during GC where the mark bits confuse the checks.
8909 inline Object* unchecked_second();
8910 inline void set_second(String* second,
8911 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8913 // Dispatched behavior.
8914 uint16_t ConsStringGet(int index);
8916 DECLARE_CAST(ConsString)
8918 // Layout description.
8919 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8920 static const int kSecondOffset = kFirstOffset + kPointerSize;
8921 static const int kSize = kSecondOffset + kPointerSize;
8923 // Minimum length for a cons string.
8924 static const int kMinLength = 13;
8926 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8929 DECLARE_VERIFIER(ConsString)
8932 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8936 // The Sliced String class describes strings that are substrings of another
8937 // sequential string. The motivation is to save time and memory when creating
8938 // a substring. A Sliced String is described as a pointer to the parent,
8939 // the offset from the start of the parent string and the length. Using
8940 // a Sliced String therefore requires unpacking of the parent string and
8941 // adding the offset to the start address. A substring of a Sliced String
8942 // are not nested since the double indirection is simplified when creating
8943 // such a substring.
8944 // Currently missing features are:
8945 // - handling externalized parent strings
8946 // - external strings as parent
8947 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8948 class SlicedString: public String {
8950 inline String* parent();
8951 inline void set_parent(String* parent,
8952 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8953 inline int offset() const;
8954 inline void set_offset(int offset);
8956 // Dispatched behavior.
8957 uint16_t SlicedStringGet(int index);
8959 DECLARE_CAST(SlicedString)
8961 // Layout description.
8962 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8963 static const int kOffsetOffset = kParentOffset + kPointerSize;
8964 static const int kSize = kOffsetOffset + kPointerSize;
8966 // Minimum length for a sliced string.
8967 static const int kMinLength = 13;
8969 typedef FixedBodyDescriptor<kParentOffset,
8970 kOffsetOffset + kPointerSize, kSize>
8973 DECLARE_VERIFIER(SlicedString)
8976 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8980 // The ExternalString class describes string values that are backed by
8981 // a string resource that lies outside the V8 heap. ExternalStrings
8982 // consist of the length field common to all strings, a pointer to the
8983 // external resource. It is important to ensure (externally) that the
8984 // resource is not deallocated while the ExternalString is live in the
8987 // The API expects that all ExternalStrings are created through the
8988 // API. Therefore, ExternalStrings should not be used internally.
8989 class ExternalString: public String {
8991 DECLARE_CAST(ExternalString)
8993 // Layout description.
8994 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8995 static const int kShortSize = kResourceOffset + kPointerSize;
8996 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8997 static const int kSize = kResourceDataOffset + kPointerSize;
8999 static const int kMaxShortLength =
9000 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9002 // Return whether external string is short (data pointer is not cached).
9003 inline bool is_short();
9005 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9008 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9012 // The ExternalOneByteString class is an external string backed by an
9014 class ExternalOneByteString : public ExternalString {
9016 static const bool kHasOneByteEncoding = true;
9018 typedef v8::String::ExternalOneByteStringResource Resource;
9020 // The underlying resource.
9021 inline const Resource* resource();
9022 inline void set_resource(const Resource* buffer);
9024 // Update the pointer cache to the external character array.
9025 // The cached pointer is always valid, as the external character array does =
9026 // not move during lifetime. Deserialization is the only exception, after
9027 // which the pointer cache has to be refreshed.
9028 inline void update_data_cache();
9030 inline const uint8_t* GetChars();
9032 // Dispatched behavior.
9033 inline uint16_t ExternalOneByteStringGet(int index);
9035 DECLARE_CAST(ExternalOneByteString)
9037 // Garbage collection support.
9038 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9040 template <typename StaticVisitor>
9041 inline void ExternalOneByteStringIterateBody();
9044 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9048 // The ExternalTwoByteString class is an external string backed by a UTF-16
9050 class ExternalTwoByteString: public ExternalString {
9052 static const bool kHasOneByteEncoding = false;
9054 typedef v8::String::ExternalStringResource Resource;
9056 // The underlying string resource.
9057 inline const Resource* resource();
9058 inline void set_resource(const Resource* buffer);
9060 // Update the pointer cache to the external character array.
9061 // The cached pointer is always valid, as the external character array does =
9062 // not move during lifetime. Deserialization is the only exception, after
9063 // which the pointer cache has to be refreshed.
9064 inline void update_data_cache();
9066 inline const uint16_t* GetChars();
9068 // Dispatched behavior.
9069 inline uint16_t ExternalTwoByteStringGet(int index);
9072 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9074 DECLARE_CAST(ExternalTwoByteString)
9076 // Garbage collection support.
9077 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9079 template<typename StaticVisitor>
9080 inline void ExternalTwoByteStringIterateBody();
9083 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9087 // Utility superclass for stack-allocated objects that must be updated
9088 // on gc. It provides two ways for the gc to update instances, either
9089 // iterating or updating after gc.
9090 class Relocatable BASE_EMBEDDED {
9092 explicit inline Relocatable(Isolate* isolate);
9093 inline virtual ~Relocatable();
9094 virtual void IterateInstance(ObjectVisitor* v) { }
9095 virtual void PostGarbageCollection() { }
9097 static void PostGarbageCollectionProcessing(Isolate* isolate);
9098 static int ArchiveSpacePerThread();
9099 static char* ArchiveState(Isolate* isolate, char* to);
9100 static char* RestoreState(Isolate* isolate, char* from);
9101 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9102 static void Iterate(ObjectVisitor* v, Relocatable* top);
9103 static char* Iterate(ObjectVisitor* v, char* t);
9111 // A flat string reader provides random access to the contents of a
9112 // string independent of the character width of the string. The handle
9113 // must be valid as long as the reader is being used.
9114 class FlatStringReader : public Relocatable {
9116 FlatStringReader(Isolate* isolate, Handle<String> str);
9117 FlatStringReader(Isolate* isolate, Vector<const char> input);
9118 void PostGarbageCollection();
9119 inline uc32 Get(int index);
9120 template <typename Char>
9121 inline Char Get(int index);
9122 int length() { return length_; }
9131 // This maintains an off-stack representation of the stack frames required
9132 // to traverse a ConsString, allowing an entirely iterative and restartable
9133 // traversal of the entire string
9134 class ConsStringIterator {
9136 inline ConsStringIterator() {}
9137 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9138 Reset(cons_string, offset);
9140 inline void Reset(ConsString* cons_string, int offset = 0) {
9142 // Next will always return NULL.
9143 if (cons_string == NULL) return;
9144 Initialize(cons_string, offset);
9146 // Returns NULL when complete.
9147 inline String* Next(int* offset_out) {
9149 if (depth_ == 0) return NULL;
9150 return Continue(offset_out);
9154 static const int kStackSize = 32;
9155 // Use a mask instead of doing modulo operations for stack wrapping.
9156 static const int kDepthMask = kStackSize-1;
9157 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9158 static inline int OffsetForDepth(int depth);
9160 inline void PushLeft(ConsString* string);
9161 inline void PushRight(ConsString* string);
9162 inline void AdjustMaximumDepth();
9164 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9165 void Initialize(ConsString* cons_string, int offset);
9166 String* Continue(int* offset_out);
9167 String* NextLeaf(bool* blew_stack);
9168 String* Search(int* offset_out);
9170 // Stack must always contain only frames for which right traversal
9171 // has not yet been performed.
9172 ConsString* frames_[kStackSize];
9177 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9181 class StringCharacterStream {
9183 inline StringCharacterStream(String* string,
9185 inline uint16_t GetNext();
9186 inline bool HasMore();
9187 inline void Reset(String* string, int offset = 0);
9188 inline void VisitOneByteString(const uint8_t* chars, int length);
9189 inline void VisitTwoByteString(const uint16_t* chars, int length);
9192 ConsStringIterator iter_;
9195 const uint8_t* buffer8_;
9196 const uint16_t* buffer16_;
9198 const uint8_t* end_;
9199 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9203 template <typename T>
9204 class VectorIterator {
9206 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9207 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9208 T GetNext() { return data_[index_++]; }
9209 bool has_more() { return index_ < data_.length(); }
9211 Vector<const T> data_;
9216 // The Oddball describes objects null, undefined, true, and false.
9217 class Oddball: public HeapObject {
9219 // [to_string]: Cached to_string computed at startup.
9220 DECL_ACCESSORS(to_string, String)
9222 // [to_number]: Cached to_number computed at startup.
9223 DECL_ACCESSORS(to_number, Object)
9225 // [typeof]: Cached type_of computed at startup.
9226 DECL_ACCESSORS(type_of, String)
9228 inline byte kind() const;
9229 inline void set_kind(byte kind);
9231 // ES6 section 7.1.3 ToNumber for Boolean, Null, Undefined.
9232 MUST_USE_RESULT static inline Handle<Object> ToNumber(Handle<Oddball> input);
9234 DECLARE_CAST(Oddball)
9236 // Dispatched behavior.
9237 DECLARE_VERIFIER(Oddball)
9239 // Initialize the fields.
9240 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9241 const char* to_string, Handle<Object> to_number,
9242 const char* type_of, byte kind);
9244 // Layout description.
9245 static const int kToStringOffset = HeapObject::kHeaderSize;
9246 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9247 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9248 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9249 static const int kSize = kKindOffset + kPointerSize;
9251 static const byte kFalse = 0;
9252 static const byte kTrue = 1;
9253 static const byte kNotBooleanMask = ~1;
9254 static const byte kTheHole = 2;
9255 static const byte kNull = 3;
9256 static const byte kArgumentMarker = 4;
9257 static const byte kUndefined = 5;
9258 static const byte kUninitialized = 6;
9259 static const byte kOther = 7;
9260 static const byte kException = 8;
9262 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9263 kSize> BodyDescriptor;
9265 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9266 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9267 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9270 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9274 class Cell: public HeapObject {
9276 // [value]: value of the cell.
9277 DECL_ACCESSORS(value, Object)
9281 static inline Cell* FromValueAddress(Address value) {
9282 Object* result = FromAddress(value - kValueOffset);
9283 return static_cast<Cell*>(result);
9286 inline Address ValueAddress() {
9287 return address() + kValueOffset;
9290 // Dispatched behavior.
9291 DECLARE_PRINTER(Cell)
9292 DECLARE_VERIFIER(Cell)
9294 // Layout description.
9295 static const int kValueOffset = HeapObject::kHeaderSize;
9296 static const int kSize = kValueOffset + kPointerSize;
9298 typedef FixedBodyDescriptor<kValueOffset,
9299 kValueOffset + kPointerSize,
9300 kSize> BodyDescriptor;
9303 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9307 class PropertyCell : public HeapObject {
9309 // [property_details]: details of the global property.
9310 DECL_ACCESSORS(property_details_raw, Object)
9311 // [value]: value of the global property.
9312 DECL_ACCESSORS(value, Object)
9313 // [dependent_code]: dependent code that depends on the type of the global
9315 DECL_ACCESSORS(dependent_code, DependentCode)
9317 inline PropertyDetails property_details();
9318 inline void set_property_details(PropertyDetails details);
9320 PropertyCellConstantType GetConstantType();
9322 // Computes the new type of the cell's contents for the given value, but
9323 // without actually modifying the details.
9324 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9325 Handle<Object> value,
9326 PropertyDetails details);
9327 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9328 Handle<Object> value, PropertyDetails details);
9330 static Handle<PropertyCell> InvalidateEntry(
9331 Handle<GlobalDictionary> dictionary, int entry);
9333 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9334 Handle<Object> new_value);
9336 DECLARE_CAST(PropertyCell)
9338 // Dispatched behavior.
9339 DECLARE_PRINTER(PropertyCell)
9340 DECLARE_VERIFIER(PropertyCell)
9342 // Layout description.
9343 static const int kDetailsOffset = HeapObject::kHeaderSize;
9344 static const int kValueOffset = kDetailsOffset + kPointerSize;
9345 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9346 static const int kSize = kDependentCodeOffset + kPointerSize;
9348 static const int kPointerFieldsBeginOffset = kValueOffset;
9349 static const int kPointerFieldsEndOffset = kSize;
9351 typedef FixedBodyDescriptor<kValueOffset,
9353 kSize> BodyDescriptor;
9356 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9360 class WeakCell : public HeapObject {
9362 inline Object* value() const;
9364 // This should not be called by anyone except GC.
9365 inline void clear();
9367 // This should not be called by anyone except allocator.
9368 inline void initialize(HeapObject* value);
9370 inline bool cleared() const;
9372 DECL_ACCESSORS(next, Object)
9374 inline void clear_next(Heap* heap);
9376 inline bool next_cleared();
9378 DECLARE_CAST(WeakCell)
9380 DECLARE_PRINTER(WeakCell)
9381 DECLARE_VERIFIER(WeakCell)
9383 // Layout description.
9384 static const int kValueOffset = HeapObject::kHeaderSize;
9385 static const int kNextOffset = kValueOffset + kPointerSize;
9386 static const int kSize = kNextOffset + kPointerSize;
9388 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9391 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9395 // The JSProxy describes EcmaScript Harmony proxies
9396 class JSProxy: public JSReceiver {
9398 // [handler]: The handler property.
9399 DECL_ACCESSORS(handler, Object)
9401 // [hash]: The hash code property (undefined if not initialized yet).
9402 DECL_ACCESSORS(hash, Object)
9404 DECLARE_CAST(JSProxy)
9406 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9407 Handle<JSProxy> proxy,
9408 Handle<Object> receiver,
9411 // If the handler defines an accessor property with a setter, invoke it.
9412 // If it defines an accessor property without a setter, or a data property
9413 // that is read-only, throw. In all these cases set '*done' to true,
9414 // otherwise set it to false.
9416 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9417 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9418 Handle<Object> value, LanguageMode language_mode, bool* done);
9420 MUST_USE_RESULT static Maybe<PropertyAttributes>
9421 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9422 Handle<Object> receiver,
9424 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9425 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9426 Handle<Object> value, LanguageMode language_mode);
9428 // Turn the proxy into an (empty) JSObject.
9429 static void Fix(Handle<JSProxy> proxy);
9431 // Initializes the body after the handler slot.
9432 inline void InitializeBody(int object_size, Object* value);
9434 // Invoke a trap by name. If the trap does not exist on this's handler,
9435 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9436 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9437 Handle<JSProxy> proxy,
9439 Handle<Object> derived_trap,
9441 Handle<Object> args[]);
9443 // Dispatched behavior.
9444 DECLARE_PRINTER(JSProxy)
9445 DECLARE_VERIFIER(JSProxy)
9447 // Layout description. We add padding so that a proxy has the same
9448 // size as a virgin JSObject. This is essential for becoming a JSObject
9450 static const int kHandlerOffset = HeapObject::kHeaderSize;
9451 static const int kHashOffset = kHandlerOffset + kPointerSize;
9452 static const int kPaddingOffset = kHashOffset + kPointerSize;
9453 static const int kSize = JSObject::kHeaderSize;
9454 static const int kHeaderSize = kPaddingOffset;
9455 static const int kPaddingSize = kSize - kPaddingOffset;
9457 STATIC_ASSERT(kPaddingSize >= 0);
9459 typedef FixedBodyDescriptor<kHandlerOffset,
9461 kSize> BodyDescriptor;
9464 friend class JSReceiver;
9466 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9467 Handle<JSProxy> proxy, Handle<Name> name);
9469 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9470 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9472 MUST_USE_RESULT Object* GetIdentityHash();
9474 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9476 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9480 class JSFunctionProxy: public JSProxy {
9482 // [call_trap]: The call trap.
9483 DECL_ACCESSORS(call_trap, JSReceiver)
9485 // [construct_trap]: The construct trap.
9486 DECL_ACCESSORS(construct_trap, Object)
9488 DECLARE_CAST(JSFunctionProxy)
9490 // Dispatched behavior.
9491 DECLARE_PRINTER(JSFunctionProxy)
9492 DECLARE_VERIFIER(JSFunctionProxy)
9494 // Layout description.
9495 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9496 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9497 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9498 static const int kSize = JSFunction::kSize;
9499 static const int kPaddingSize = kSize - kPaddingOffset;
9501 STATIC_ASSERT(kPaddingSize >= 0);
9503 typedef FixedBodyDescriptor<kHandlerOffset,
9504 kConstructTrapOffset + kPointerSize,
9505 kSize> BodyDescriptor;
9508 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9512 class JSCollection : public JSObject {
9514 // [table]: the backing hash table
9515 DECL_ACCESSORS(table, Object)
9517 static const int kTableOffset = JSObject::kHeaderSize;
9518 static const int kSize = kTableOffset + kPointerSize;
9521 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9525 // The JSSet describes EcmaScript Harmony sets
9526 class JSSet : public JSCollection {
9530 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9531 static void Clear(Handle<JSSet> set);
9533 // Dispatched behavior.
9534 DECLARE_PRINTER(JSSet)
9535 DECLARE_VERIFIER(JSSet)
9538 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9542 // The JSMap describes EcmaScript Harmony maps
9543 class JSMap : public JSCollection {
9547 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9548 static void Clear(Handle<JSMap> map);
9550 // Dispatched behavior.
9551 DECLARE_PRINTER(JSMap)
9552 DECLARE_VERIFIER(JSMap)
9555 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9559 // OrderedHashTableIterator is an iterator that iterates over the keys and
9560 // values of an OrderedHashTable.
9562 // The iterator has a reference to the underlying OrderedHashTable data,
9563 // [table], as well as the current [index] the iterator is at.
9565 // When the OrderedHashTable is rehashed it adds a reference from the old table
9566 // to the new table as well as storing enough data about the changes so that the
9567 // iterator [index] can be adjusted accordingly.
9569 // When the [Next] result from the iterator is requested, the iterator checks if
9570 // there is a newer table that it needs to transition to.
9571 template<class Derived, class TableType>
9572 class OrderedHashTableIterator: public JSObject {
9574 // [table]: the backing hash table mapping keys to values.
9575 DECL_ACCESSORS(table, Object)
9577 // [index]: The index into the data table.
9578 DECL_ACCESSORS(index, Object)
9580 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9581 DECL_ACCESSORS(kind, Object)
9584 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9587 static const int kTableOffset = JSObject::kHeaderSize;
9588 static const int kIndexOffset = kTableOffset + kPointerSize;
9589 static const int kKindOffset = kIndexOffset + kPointerSize;
9590 static const int kSize = kKindOffset + kPointerSize;
9598 // Whether the iterator has more elements. This needs to be called before
9599 // calling |CurrentKey| and/or |CurrentValue|.
9602 // Move the index forward one.
9604 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9607 // Populates the array with the next key and value and then moves the iterator
9609 // This returns the |kind| or 0 if the iterator is already at the end.
9610 Smi* Next(JSArray* value_array);
9612 // Returns the current key of the iterator. This should only be called when
9613 // |HasMore| returns true.
9614 inline Object* CurrentKey();
9617 // Transitions the iterator to the non obsolete backing store. This is a NOP
9618 // if the [table] is not obsolete.
9621 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9625 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9628 // Dispatched behavior.
9629 DECLARE_PRINTER(JSSetIterator)
9630 DECLARE_VERIFIER(JSSetIterator)
9632 DECLARE_CAST(JSSetIterator)
9634 // Called by |Next| to populate the array. This allows the subclasses to
9635 // populate the array differently.
9636 inline void PopulateValueArray(FixedArray* array);
9639 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9643 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9646 // Dispatched behavior.
9647 DECLARE_PRINTER(JSMapIterator)
9648 DECLARE_VERIFIER(JSMapIterator)
9650 DECLARE_CAST(JSMapIterator)
9652 // Called by |Next| to populate the array. This allows the subclasses to
9653 // populate the array differently.
9654 inline void PopulateValueArray(FixedArray* array);
9657 // Returns the current value of the iterator. This should only be called when
9658 // |HasMore| returns true.
9659 inline Object* CurrentValue();
9661 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9665 // ES6 section 25.1.1.3 The IteratorResult Interface
9666 class JSIteratorResult final : public JSObject {
9668 // [done]: This is the result status of an iterator next method call. If the
9669 // end of the iterator was reached done is true. If the end was not reached
9670 // done is false and a [value] is available.
9671 DECL_ACCESSORS(done, Object)
9673 // [value]: If [done] is false, this is the current iteration element value.
9674 // If [done] is true, this is the return value of the iterator, if it supplied
9675 // one. If the iterator does not have a return value, value is undefined.
9676 // In that case, the value property may be absent from the conforming object
9677 // if it does not inherit an explicit value property.
9678 DECL_ACCESSORS(value, Object)
9680 // Dispatched behavior.
9681 DECLARE_PRINTER(JSIteratorResult)
9682 DECLARE_VERIFIER(JSIteratorResult)
9684 DECLARE_CAST(JSIteratorResult)
9686 static const int kValueOffset = JSObject::kHeaderSize;
9687 static const int kDoneOffset = kValueOffset + kPointerSize;
9688 static const int kSize = kDoneOffset + kPointerSize;
9690 // Indices of in-object properties.
9691 static const int kValueIndex = 0;
9692 static const int kDoneIndex = 1;
9695 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9699 // Base class for both JSWeakMap and JSWeakSet
9700 class JSWeakCollection: public JSObject {
9702 // [table]: the backing hash table mapping keys to values.
9703 DECL_ACCESSORS(table, Object)
9705 // [next]: linked list of encountered weak maps during GC.
9706 DECL_ACCESSORS(next, Object)
9708 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9709 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9710 Handle<Object> value, int32_t hash);
9711 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9714 static const int kTableOffset = JSObject::kHeaderSize;
9715 static const int kNextOffset = kTableOffset + kPointerSize;
9716 static const int kSize = kNextOffset + kPointerSize;
9719 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9723 // The JSWeakMap describes EcmaScript Harmony weak maps
9724 class JSWeakMap: public JSWeakCollection {
9726 DECLARE_CAST(JSWeakMap)
9728 // Dispatched behavior.
9729 DECLARE_PRINTER(JSWeakMap)
9730 DECLARE_VERIFIER(JSWeakMap)
9733 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9737 // The JSWeakSet describes EcmaScript Harmony weak sets
9738 class JSWeakSet: public JSWeakCollection {
9740 DECLARE_CAST(JSWeakSet)
9742 // Dispatched behavior.
9743 DECLARE_PRINTER(JSWeakSet)
9744 DECLARE_VERIFIER(JSWeakSet)
9747 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9751 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9752 enum class SharedFlag { kNotShared, kShared };
9755 class JSArrayBuffer: public JSObject {
9757 // [backing_store]: backing memory for this array
9758 DECL_ACCESSORS(backing_store, void)
9760 // [byte_length]: length in bytes
9761 DECL_ACCESSORS(byte_length, Object)
9763 inline uint32_t bit_field() const;
9764 inline void set_bit_field(uint32_t bits);
9766 inline bool is_external();
9767 inline void set_is_external(bool value);
9769 inline bool is_neuterable();
9770 inline void set_is_neuterable(bool value);
9772 inline bool was_neutered();
9773 inline void set_was_neutered(bool value);
9775 inline bool is_shared();
9776 inline void set_is_shared(bool value);
9778 DECLARE_CAST(JSArrayBuffer)
9782 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9783 bool is_external, void* data, size_t allocated_length,
9784 SharedFlag shared = SharedFlag::kNotShared);
9786 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9787 Isolate* isolate, size_t allocated_length,
9788 bool initialize = true,
9789 SharedFlag shared = SharedFlag::kNotShared);
9791 // Dispatched behavior.
9792 DECLARE_PRINTER(JSArrayBuffer)
9793 DECLARE_VERIFIER(JSArrayBuffer)
9795 static const int kByteLengthOffset = JSObject::kHeaderSize;
9797 // NOTE: GC will visit objects fields:
9798 // 1. From JSObject::BodyDescriptor::kStartOffset to kByteLengthOffset +
9800 // 2. From start of the internal fields and up to the end of them
9801 static const int kBackingStoreOffset = kByteLengthOffset + kPointerSize;
9802 static const int kBitFieldSlot = kBackingStoreOffset + kPointerSize;
9803 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9804 static const int kBitFieldOffset = kBitFieldSlot;
9806 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9808 static const int kSize = kBitFieldSlot + kPointerSize;
9810 static const int kSizeWithInternalFields =
9811 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9813 template <typename StaticVisitor>
9814 static inline void JSArrayBufferIterateBody(Heap* heap, HeapObject* obj);
9816 static inline void JSArrayBufferIterateBody(HeapObject* obj,
9819 class IsExternal : public BitField<bool, 1, 1> {};
9820 class IsNeuterable : public BitField<bool, 2, 1> {};
9821 class WasNeutered : public BitField<bool, 3, 1> {};
9822 class IsShared : public BitField<bool, 4, 1> {};
9825 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9829 class JSArrayBufferView: public JSObject {
9831 // [buffer]: ArrayBuffer that this typed array views.
9832 DECL_ACCESSORS(buffer, Object)
9834 // [byte_offset]: offset of typed array in bytes.
9835 DECL_ACCESSORS(byte_offset, Object)
9837 // [byte_length]: length of typed array in bytes.
9838 DECL_ACCESSORS(byte_length, Object)
9840 DECLARE_CAST(JSArrayBufferView)
9842 DECLARE_VERIFIER(JSArrayBufferView)
9844 inline bool WasNeutered() const;
9846 static const int kBufferOffset = JSObject::kHeaderSize;
9847 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9848 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9849 static const int kViewSize = kByteLengthOffset + kPointerSize;
9853 DECL_ACCESSORS(raw_byte_offset, Object)
9854 DECL_ACCESSORS(raw_byte_length, Object)
9857 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9861 class JSTypedArray: public JSArrayBufferView {
9863 // [length]: length of typed array in elements.
9864 DECL_ACCESSORS(length, Object)
9865 inline uint32_t length_value() const;
9867 DECLARE_CAST(JSTypedArray)
9869 ExternalArrayType type();
9870 size_t element_size();
9872 Handle<JSArrayBuffer> GetBuffer();
9874 // Dispatched behavior.
9875 DECLARE_PRINTER(JSTypedArray)
9876 DECLARE_VERIFIER(JSTypedArray)
9878 static const int kLengthOffset = kViewSize + kPointerSize;
9879 static const int kSize = kLengthOffset + kPointerSize;
9881 static const int kSizeWithInternalFields =
9882 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9885 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9886 Handle<JSTypedArray> typed_array);
9888 DECL_ACCESSORS(raw_length, Object)
9891 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9895 class JSDataView: public JSArrayBufferView {
9897 DECLARE_CAST(JSDataView)
9899 // Dispatched behavior.
9900 DECLARE_PRINTER(JSDataView)
9901 DECLARE_VERIFIER(JSDataView)
9903 static const int kSize = kViewSize;
9905 static const int kSizeWithInternalFields =
9906 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9909 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9913 // Foreign describes objects pointing from JavaScript to C structures.
9914 class Foreign: public HeapObject {
9916 // [address]: field containing the address.
9917 inline Address foreign_address();
9918 inline void set_foreign_address(Address value);
9920 DECLARE_CAST(Foreign)
9922 // Dispatched behavior.
9923 inline void ForeignIterateBody(ObjectVisitor* v);
9925 template<typename StaticVisitor>
9926 inline void ForeignIterateBody();
9928 // Dispatched behavior.
9929 DECLARE_PRINTER(Foreign)
9930 DECLARE_VERIFIER(Foreign)
9932 // Layout description.
9934 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9935 static const int kSize = kForeignAddressOffset + kPointerSize;
9937 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9940 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9944 // The JSArray describes JavaScript Arrays
9945 // Such an array can be in one of two modes:
9946 // - fast, backing storage is a FixedArray and length <= elements.length();
9947 // Please note: push and pop can be used to grow and shrink the array.
9948 // - slow, backing storage is a HashTable with numbers as keys.
9949 class JSArray: public JSObject {
9951 // [length]: The length property.
9952 DECL_ACCESSORS(length, Object)
9954 // Overload the length setter to skip write barrier when the length
9955 // is set to a smi. This matches the set function on FixedArray.
9956 inline void set_length(Smi* length);
9958 static bool HasReadOnlyLength(Handle<JSArray> array);
9959 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9960 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9962 // Initialize the array with the given capacity. The function may
9963 // fail due to out-of-memory situations, but only if the requested
9964 // capacity is non-zero.
9965 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9967 // If the JSArray has fast elements, and new_length would result in
9968 // normalization, returns true.
9969 bool SetLengthWouldNormalize(uint32_t new_length);
9970 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9972 // Initializes the array to a certain length.
9973 inline bool AllowsSetLength();
9975 static void SetLength(Handle<JSArray> array, uint32_t length);
9976 // Same as above but will also queue splice records if |array| is observed.
9977 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9980 // Set the content of the array to the content of storage.
9981 static inline void SetContent(Handle<JSArray> array,
9982 Handle<FixedArrayBase> storage);
9984 DECLARE_CAST(JSArray)
9986 // Dispatched behavior.
9987 DECLARE_PRINTER(JSArray)
9988 DECLARE_VERIFIER(JSArray)
9990 // Number of element slots to pre-allocate for an empty array.
9991 static const int kPreallocatedArrayElements = 4;
9993 // Layout description.
9994 static const int kLengthOffset = JSObject::kHeaderSize;
9995 static const int kSize = kLengthOffset + kPointerSize;
9998 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10002 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10003 Handle<Map> initial_map);
10006 // JSRegExpResult is just a JSArray with a specific initial map.
10007 // This initial map adds in-object properties for "index" and "input"
10008 // properties, as assigned by RegExp.prototype.exec, which allows
10009 // faster creation of RegExp exec results.
10010 // This class just holds constants used when creating the result.
10011 // After creation the result must be treated as a JSArray in all regards.
10012 class JSRegExpResult: public JSArray {
10014 // Offsets of object fields.
10015 static const int kIndexOffset = JSArray::kSize;
10016 static const int kInputOffset = kIndexOffset + kPointerSize;
10017 static const int kSize = kInputOffset + kPointerSize;
10018 // Indices of in-object properties.
10019 static const int kIndexIndex = 0;
10020 static const int kInputIndex = 1;
10022 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10026 class AccessorInfo: public Struct {
10028 DECL_ACCESSORS(name, Object)
10029 DECL_INT_ACCESSORS(flag)
10030 DECL_ACCESSORS(expected_receiver_type, Object)
10032 inline bool all_can_read();
10033 inline void set_all_can_read(bool value);
10035 inline bool all_can_write();
10036 inline void set_all_can_write(bool value);
10038 inline bool is_special_data_property();
10039 inline void set_is_special_data_property(bool value);
10041 inline PropertyAttributes property_attributes();
10042 inline void set_property_attributes(PropertyAttributes attributes);
10044 // Checks whether the given receiver is compatible with this accessor.
10045 static bool IsCompatibleReceiverMap(Isolate* isolate,
10046 Handle<AccessorInfo> info,
10048 inline bool IsCompatibleReceiver(Object* receiver);
10050 DECLARE_CAST(AccessorInfo)
10052 // Dispatched behavior.
10053 DECLARE_VERIFIER(AccessorInfo)
10055 // Append all descriptors to the array that are not already there.
10056 // Return number added.
10057 static int AppendUnique(Handle<Object> descriptors,
10058 Handle<FixedArray> array,
10059 int valid_descriptors);
10061 static const int kNameOffset = HeapObject::kHeaderSize;
10062 static const int kFlagOffset = kNameOffset + kPointerSize;
10063 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10064 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10067 inline bool HasExpectedReceiverType();
10069 // Bit positions in flag.
10070 static const int kAllCanReadBit = 0;
10071 static const int kAllCanWriteBit = 1;
10072 static const int kSpecialDataProperty = 2;
10073 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10075 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10079 // An accessor must have a getter, but can have no setter.
10081 // When setting a property, V8 searches accessors in prototypes.
10082 // If an accessor was found and it does not have a setter,
10083 // the request is ignored.
10085 // If the accessor in the prototype has the READ_ONLY property attribute, then
10086 // a new value is added to the derived object when the property is set.
10087 // This shadows the accessor in the prototype.
10088 class ExecutableAccessorInfo: public AccessorInfo {
10090 DECL_ACCESSORS(getter, Object)
10091 DECL_ACCESSORS(setter, Object)
10092 DECL_ACCESSORS(data, Object)
10094 DECLARE_CAST(ExecutableAccessorInfo)
10096 // Dispatched behavior.
10097 DECLARE_PRINTER(ExecutableAccessorInfo)
10098 DECLARE_VERIFIER(ExecutableAccessorInfo)
10100 static const int kGetterOffset = AccessorInfo::kSize;
10101 static const int kSetterOffset = kGetterOffset + kPointerSize;
10102 static const int kDataOffset = kSetterOffset + kPointerSize;
10103 static const int kSize = kDataOffset + kPointerSize;
10105 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10108 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10112 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10113 // accessor can either be
10114 // * a pointer to a JavaScript function or proxy: a real accessor
10115 // * undefined: considered an accessor by the spec, too, strangely enough
10116 // * the hole: an accessor which has not been set
10117 // * a pointer to a map: a transition used to ensure map sharing
10118 class AccessorPair: public Struct {
10120 DECL_ACCESSORS(getter, Object)
10121 DECL_ACCESSORS(setter, Object)
10123 DECLARE_CAST(AccessorPair)
10125 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10127 inline Object* get(AccessorComponent component);
10128 inline void set(AccessorComponent component, Object* value);
10130 // Note: Returns undefined instead in case of a hole.
10131 Object* GetComponent(AccessorComponent component);
10133 // Set both components, skipping arguments which are a JavaScript null.
10134 inline void SetComponents(Object* getter, Object* setter);
10136 inline bool Equals(AccessorPair* pair);
10137 inline bool Equals(Object* getter_value, Object* setter_value);
10139 inline bool ContainsAccessor();
10141 // Dispatched behavior.
10142 DECLARE_PRINTER(AccessorPair)
10143 DECLARE_VERIFIER(AccessorPair)
10145 static const int kGetterOffset = HeapObject::kHeaderSize;
10146 static const int kSetterOffset = kGetterOffset + kPointerSize;
10147 static const int kSize = kSetterOffset + kPointerSize;
10150 // Strangely enough, in addition to functions and harmony proxies, the spec
10151 // requires us to consider undefined as a kind of accessor, too:
10153 // Object.defineProperty(obj, "foo", {get: undefined});
10154 // assertTrue("foo" in obj);
10155 inline bool IsJSAccessor(Object* obj);
10157 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10161 class AccessCheckInfo: public Struct {
10163 DECL_ACCESSORS(named_callback, Object)
10164 DECL_ACCESSORS(indexed_callback, Object)
10165 DECL_ACCESSORS(data, Object)
10167 DECLARE_CAST(AccessCheckInfo)
10169 // Dispatched behavior.
10170 DECLARE_PRINTER(AccessCheckInfo)
10171 DECLARE_VERIFIER(AccessCheckInfo)
10173 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10174 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10175 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10176 static const int kSize = kDataOffset + kPointerSize;
10179 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10183 class InterceptorInfo: public Struct {
10185 DECL_ACCESSORS(getter, Object)
10186 DECL_ACCESSORS(setter, Object)
10187 DECL_ACCESSORS(query, Object)
10188 DECL_ACCESSORS(deleter, Object)
10189 DECL_ACCESSORS(enumerator, Object)
10190 DECL_ACCESSORS(data, Object)
10191 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10192 DECL_BOOLEAN_ACCESSORS(all_can_read)
10193 DECL_BOOLEAN_ACCESSORS(non_masking)
10195 inline int flags() const;
10196 inline void set_flags(int flags);
10198 DECLARE_CAST(InterceptorInfo)
10200 // Dispatched behavior.
10201 DECLARE_PRINTER(InterceptorInfo)
10202 DECLARE_VERIFIER(InterceptorInfo)
10204 static const int kGetterOffset = HeapObject::kHeaderSize;
10205 static const int kSetterOffset = kGetterOffset + kPointerSize;
10206 static const int kQueryOffset = kSetterOffset + kPointerSize;
10207 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10208 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10209 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10210 static const int kFlagsOffset = kDataOffset + kPointerSize;
10211 static const int kSize = kFlagsOffset + kPointerSize;
10213 static const int kCanInterceptSymbolsBit = 0;
10214 static const int kAllCanReadBit = 1;
10215 static const int kNonMasking = 2;
10218 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10222 class CallHandlerInfo: public Struct {
10224 DECL_ACCESSORS(callback, Object)
10225 DECL_ACCESSORS(data, Object)
10227 DECLARE_CAST(CallHandlerInfo)
10229 // Dispatched behavior.
10230 DECLARE_PRINTER(CallHandlerInfo)
10231 DECLARE_VERIFIER(CallHandlerInfo)
10233 static const int kCallbackOffset = HeapObject::kHeaderSize;
10234 static const int kDataOffset = kCallbackOffset + kPointerSize;
10235 static const int kSize = kDataOffset + kPointerSize;
10238 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10242 class TemplateInfo: public Struct {
10244 DECL_ACCESSORS(tag, Object)
10245 inline int number_of_properties() const;
10246 inline void set_number_of_properties(int value);
10247 DECL_ACCESSORS(property_list, Object)
10248 DECL_ACCESSORS(property_accessors, Object)
10250 DECLARE_VERIFIER(TemplateInfo)
10252 static const int kTagOffset = HeapObject::kHeaderSize;
10253 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10254 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10255 static const int kPropertyAccessorsOffset =
10256 kPropertyListOffset + kPointerSize;
10257 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10260 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10264 class FunctionTemplateInfo: public TemplateInfo {
10266 DECL_ACCESSORS(serial_number, Object)
10267 DECL_ACCESSORS(call_code, Object)
10268 DECL_ACCESSORS(prototype_template, Object)
10269 DECL_ACCESSORS(parent_template, Object)
10270 DECL_ACCESSORS(named_property_handler, Object)
10271 DECL_ACCESSORS(indexed_property_handler, Object)
10272 DECL_ACCESSORS(instance_template, Object)
10273 DECL_ACCESSORS(class_name, Object)
10274 DECL_ACCESSORS(signature, Object)
10275 DECL_ACCESSORS(instance_call_handler, Object)
10276 DECL_ACCESSORS(access_check_info, Object)
10277 DECL_INT_ACCESSORS(flag)
10279 inline int length() const;
10280 inline void set_length(int value);
10282 // Following properties use flag bits.
10283 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10284 DECL_BOOLEAN_ACCESSORS(undetectable)
10285 // If the bit is set, object instances created by this function
10286 // requires access check.
10287 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10288 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10289 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10290 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10291 DECL_BOOLEAN_ACCESSORS(instantiated)
10292 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10294 DECLARE_CAST(FunctionTemplateInfo)
10296 // Dispatched behavior.
10297 DECLARE_PRINTER(FunctionTemplateInfo)
10298 DECLARE_VERIFIER(FunctionTemplateInfo)
10300 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10301 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10302 static const int kPrototypeTemplateOffset =
10303 kCallCodeOffset + kPointerSize;
10304 static const int kParentTemplateOffset =
10305 kPrototypeTemplateOffset + kPointerSize;
10306 static const int kNamedPropertyHandlerOffset =
10307 kParentTemplateOffset + kPointerSize;
10308 static const int kIndexedPropertyHandlerOffset =
10309 kNamedPropertyHandlerOffset + kPointerSize;
10310 static const int kInstanceTemplateOffset =
10311 kIndexedPropertyHandlerOffset + kPointerSize;
10312 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10313 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10314 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10315 static const int kAccessCheckInfoOffset =
10316 kInstanceCallHandlerOffset + kPointerSize;
10317 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10318 static const int kLengthOffset = kFlagOffset + kPointerSize;
10319 static const int kSize = kLengthOffset + kPointerSize;
10321 // Returns true if |object| is an instance of this function template.
10322 bool IsTemplateFor(Object* object);
10323 bool IsTemplateFor(Map* map);
10325 // Returns the holder JSObject if the function can legally be called with this
10326 // receiver. Returns Heap::null_value() if the call is illegal.
10327 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10330 // Bit position in the flag, from least significant bit position.
10331 static const int kHiddenPrototypeBit = 0;
10332 static const int kUndetectableBit = 1;
10333 static const int kNeedsAccessCheckBit = 2;
10334 static const int kReadOnlyPrototypeBit = 3;
10335 static const int kRemovePrototypeBit = 4;
10336 static const int kDoNotCacheBit = 5;
10337 static const int kInstantiatedBit = 6;
10338 static const int kAcceptAnyReceiver = 7;
10340 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10344 class ObjectTemplateInfo: public TemplateInfo {
10346 DECL_ACCESSORS(constructor, Object)
10347 DECL_ACCESSORS(internal_field_count, Object)
10349 DECLARE_CAST(ObjectTemplateInfo)
10351 // Dispatched behavior.
10352 DECLARE_PRINTER(ObjectTemplateInfo)
10353 DECLARE_VERIFIER(ObjectTemplateInfo)
10355 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10356 static const int kInternalFieldCountOffset =
10357 kConstructorOffset + kPointerSize;
10358 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10362 class TypeSwitchInfo: public Struct {
10364 DECL_ACCESSORS(types, Object)
10366 DECLARE_CAST(TypeSwitchInfo)
10368 // Dispatched behavior.
10369 DECLARE_PRINTER(TypeSwitchInfo)
10370 DECLARE_VERIFIER(TypeSwitchInfo)
10372 static const int kTypesOffset = Struct::kHeaderSize;
10373 static const int kSize = kTypesOffset + kPointerSize;
10377 // The DebugInfo class holds additional information for a function being
10379 class DebugInfo: public Struct {
10381 // The shared function info for the source being debugged.
10382 DECL_ACCESSORS(shared, SharedFunctionInfo)
10383 // Code object for the patched code. This code object is the code object
10384 // currently active for the function.
10385 DECL_ACCESSORS(code, Code)
10386 // Fixed array holding status information for each active break point.
10387 DECL_ACCESSORS(break_points, FixedArray)
10389 // Check if there is a break point at a code position.
10390 bool HasBreakPoint(int code_position);
10391 // Get the break point info object for a code position.
10392 Object* GetBreakPointInfo(int code_position);
10393 // Clear a break point.
10394 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10396 Handle<Object> break_point_object);
10397 // Set a break point.
10398 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10399 int source_position, int statement_position,
10400 Handle<Object> break_point_object);
10401 // Get the break point objects for a code position.
10402 Handle<Object> GetBreakPointObjects(int code_position);
10403 // Find the break point info holding this break point object.
10404 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10405 Handle<Object> break_point_object);
10406 // Get the number of break points for this function.
10407 int GetBreakPointCount();
10409 DECLARE_CAST(DebugInfo)
10411 // Dispatched behavior.
10412 DECLARE_PRINTER(DebugInfo)
10413 DECLARE_VERIFIER(DebugInfo)
10415 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10416 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10417 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10418 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10420 static const int kEstimatedNofBreakPointsInFunction = 16;
10423 static const int kNoBreakPointInfo = -1;
10425 // Lookup the index in the break_points array for a code position.
10426 int GetBreakPointInfoIndex(int code_position);
10428 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10432 // The BreakPointInfo class holds information for break points set in a
10433 // function. The DebugInfo object holds a BreakPointInfo object for each code
10434 // position with one or more break points.
10435 class BreakPointInfo: public Struct {
10437 // The position in the code for the break point.
10438 DECL_INT_ACCESSORS(code_position)
10439 // The position in the source for the break position.
10440 DECL_INT_ACCESSORS(source_position)
10441 // The position in the source for the last statement before this break
10443 DECL_INT_ACCESSORS(statement_position)
10444 // List of related JavaScript break points.
10445 DECL_ACCESSORS(break_point_objects, Object)
10447 // Removes a break point.
10448 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10449 Handle<Object> break_point_object);
10450 // Set a break point.
10451 static void SetBreakPoint(Handle<BreakPointInfo> info,
10452 Handle<Object> break_point_object);
10453 // Check if break point info has this break point object.
10454 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10455 Handle<Object> break_point_object);
10456 // Get the number of break points for this code position.
10457 int GetBreakPointCount();
10459 DECLARE_CAST(BreakPointInfo)
10461 // Dispatched behavior.
10462 DECLARE_PRINTER(BreakPointInfo)
10463 DECLARE_VERIFIER(BreakPointInfo)
10465 static const int kCodePositionIndex = Struct::kHeaderSize;
10466 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10467 static const int kStatementPositionIndex =
10468 kSourcePositionIndex + kPointerSize;
10469 static const int kBreakPointObjectsIndex =
10470 kStatementPositionIndex + kPointerSize;
10471 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10474 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10478 #undef DECL_BOOLEAN_ACCESSORS
10479 #undef DECL_ACCESSORS
10480 #undef DECLARE_CAST
10481 #undef DECLARE_VERIFIER
10483 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10484 V(kStringTable, "string_table", "(Internalized strings)") \
10485 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10486 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10487 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10488 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10489 V(kTop, "top", "(Isolate)") \
10490 V(kRelocatable, "relocatable", "(Relocatable)") \
10491 V(kDebug, "debug", "(Debugger)") \
10492 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10493 V(kHandleScope, "handlescope", "(Handle scope)") \
10494 V(kBuiltins, "builtins", "(Builtins)") \
10495 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10496 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10497 V(kThreadManager, "threadmanager", "(Thread manager)") \
10498 V(kStrongRoots, "strong roots", "(Strong roots)") \
10499 V(kExtensions, "Extensions", "(Extensions)")
10501 class VisitorSynchronization : public AllStatic {
10503 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10505 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10508 #undef DECLARE_ENUM
10510 static const char* const kTags[kNumberOfSyncTags];
10511 static const char* const kTagNames[kNumberOfSyncTags];
10514 // Abstract base class for visiting, and optionally modifying, the
10515 // pointers contained in Objects. Used in GC and serialization/deserialization.
10516 class ObjectVisitor BASE_EMBEDDED {
10518 virtual ~ObjectVisitor() {}
10520 // Visits a contiguous arrays of pointers in the half-open range
10521 // [start, end). Any or all of the values may be modified on return.
10522 virtual void VisitPointers(Object** start, Object** end) = 0;
10524 // Handy shorthand for visiting a single pointer.
10525 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10527 // Visit weak next_code_link in Code object.
10528 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10530 // To allow lazy clearing of inline caches the visitor has
10531 // a rich interface for iterating over Code objects..
10533 // Visits a code target in the instruction stream.
10534 virtual void VisitCodeTarget(RelocInfo* rinfo);
10536 // Visits a code entry in a JS function.
10537 virtual void VisitCodeEntry(Address entry_address);
10539 // Visits a global property cell reference in the instruction stream.
10540 virtual void VisitCell(RelocInfo* rinfo);
10542 // Visits a runtime entry in the instruction stream.
10543 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10545 // Visits the resource of an one-byte or two-byte string.
10546 virtual void VisitExternalOneByteString(
10547 v8::String::ExternalOneByteStringResource** resource) {}
10548 virtual void VisitExternalTwoByteString(
10549 v8::String::ExternalStringResource** resource) {}
10551 // Visits a debug call target in the instruction stream.
10552 virtual void VisitDebugTarget(RelocInfo* rinfo);
10554 // Visits the byte sequence in a function's prologue that contains information
10555 // about the code's age.
10556 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10558 // Visit pointer embedded into a code object.
10559 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10561 // Visits an external reference embedded into a code object.
10562 virtual void VisitExternalReference(RelocInfo* rinfo);
10564 // Visits an external reference.
10565 virtual void VisitExternalReference(Address* p) {}
10567 // Visits an (encoded) internal reference.
10568 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10570 // Visits a handle that has an embedder-assigned class ID.
10571 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10573 // Intended for serialization/deserialization checking: insert, or
10574 // check for the presence of, a tag at this position in the stream.
10575 // Also used for marking up GC roots in heap snapshots.
10576 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10580 class StructBodyDescriptor : public
10581 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10583 static inline int SizeOf(Map* map, HeapObject* object);
10587 // BooleanBit is a helper class for setting and getting a bit in an integer.
10588 class BooleanBit : public AllStatic {
10590 static inline bool get(int value, int bit_position) {
10591 return (value & (1 << bit_position)) != 0;
10594 static inline int set(int value, int bit_position, bool v) {
10596 value |= (1 << bit_position);
10598 value &= ~(1 << bit_position);
10605 class KeyAccumulator final BASE_EMBEDDED {
10607 explicit KeyAccumulator(Isolate* isolate) : isolate_(isolate), length_(0) {}
10609 void AddKey(Handle<Object> key, int check_limit);
10610 void AddKeys(Handle<FixedArray> array, FixedArray::KeyFilter filter);
10611 void AddKeys(Handle<JSObject> array, FixedArray::KeyFilter filter);
10612 void PrepareForComparisons(int count);
10613 Handle<FixedArray> GetKeys();
10615 int GetLength() { return length_; }
10618 void EnsureCapacity(int capacity);
10622 Handle<FixedArray> keys_;
10623 Handle<OrderedHashSet> set_;
10625 DISALLOW_COPY_AND_ASSIGN(KeyAccumulator);
10627 } } // namespace v8::internal
10629 #endif // V8_OBJECTS_H_