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
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
92 // - ScriptContextTable
103 // - ExternalOneByteString
104 // - ExternalTwoByteString
105 // - InternalizedString
106 // - SeqInternalizedString
107 // - SeqOneByteInternalizedString
108 // - SeqTwoByteInternalizedString
109 // - ConsInternalizedString
110 // - ExternalInternalizedString
111 // - ExternalOneByteInternalizedString
112 // - ExternalTwoByteInternalizedString
132 // - SharedFunctionInfo
136 // - ExecutableAccessorInfo
142 // - FunctionTemplateInfo
143 // - ObjectTemplateInfo
152 // Formats of Object*:
153 // Smi: [31 bit signed int] 0
154 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
159 enum KeyedAccessStoreMode {
161 STORE_TRANSITION_TO_OBJECT,
162 STORE_TRANSITION_TO_DOUBLE,
163 STORE_AND_GROW_NO_TRANSITION,
164 STORE_AND_GROW_TRANSITION_TO_OBJECT,
165 STORE_AND_GROW_TRANSITION_TO_DOUBLE,
166 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
167 STORE_NO_TRANSITION_HANDLE_COW
171 // Valid hints for the abstract operation ToPrimitive,
172 // implemented according to ES6, section 7.1.1.
173 enum class ToPrimitiveHint { kDefault, kNumber, kString };
176 // Valid hints for the abstract operation OrdinaryToPrimitive,
177 // implemented according to ES6, section 7.1.1.
178 enum class OrdinaryToPrimitiveHint { kNumber, kString };
181 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
190 enum ExternalArrayType {
191 kExternalInt8Array = 1,
194 kExternalUint16Array,
196 kExternalUint32Array,
197 kExternalFloat32Array,
198 kExternalFloat64Array,
199 kExternalUint8ClampedArray,
203 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
204 return store_mode == STORE_TRANSITION_TO_OBJECT ||
205 store_mode == STORE_TRANSITION_TO_DOUBLE ||
206 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
207 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
211 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
212 KeyedAccessStoreMode store_mode) {
213 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
216 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
217 return STORE_AND_GROW_NO_TRANSITION;
219 return STANDARD_STORE;
223 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
224 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
225 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
229 enum IcCheckType { ELEMENT, PROPERTY };
232 // SKIP_WRITE_BARRIER skips the write barrier.
233 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
234 // only performs the generational part.
235 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
236 enum WriteBarrierMode {
238 UPDATE_WEAK_WRITE_BARRIER,
243 // Indicates whether a value can be loaded as a constant.
244 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
247 // PropertyNormalizationMode is used to specify whether to keep
248 // inobject properties when normalizing properties of a JSObject.
249 enum PropertyNormalizationMode {
250 CLEAR_INOBJECT_PROPERTIES,
251 KEEP_INOBJECT_PROPERTIES
255 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
256 // will give the fastest result by tailoring the map to the prototype, but that
257 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
258 // (at least for now) when dynamically modifying the prototype chain of an
259 // object using __proto__ or Object.setPrototypeOf.
260 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
263 // Indicates whether transitions can be added to a source map or not.
264 enum TransitionFlag {
270 // Indicates whether the transition is simple: the target map of the transition
271 // either extends the current map with a new property, or it modifies the
272 // property that was added last to the current map.
273 enum SimpleTransitionFlag {
274 SIMPLE_PROPERTY_TRANSITION,
280 // Indicates whether we are only interested in the descriptors of a particular
281 // map, or in all descriptors in the descriptor array.
282 enum DescriptorFlag {
287 // The GC maintains a bit of information, the MarkingParity, which toggles
288 // from odd to even and back every time marking is completed. Incremental
289 // marking can visit an object twice during a marking phase, so algorithms that
290 // that piggy-back on marking can use the parity to ensure that they only
291 // perform an operation on an object once per marking phase: they record the
292 // MarkingParity when they visit an object, and only re-visit the object when it
293 // is marked again and the MarkingParity changes.
300 // ICs store extra state in a Code object. The default extra state is
302 typedef int ExtraICState;
303 static const ExtraICState kNoExtraICState = 0;
305 // Instance size sentinel for objects of variable size.
306 const int kVariableSizeSentinel = 0;
308 // We may store the unsigned bit field as signed Smi value and do not
310 const int kStubMajorKeyBits = 7;
311 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
313 // All Maps have a field instance_type containing a InstanceType.
314 // It describes the type of the instances.
316 // As an example, a JavaScript object is a heap object and its map
317 // instance_type is JS_OBJECT_TYPE.
319 // The names of the string instance types are intended to systematically
320 // mirror their encoding in the instance_type field of the map. The default
321 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
322 // encoding is mentioned explicitly in the name. Likewise, the default
323 // representation is considered sequential. It is not mentioned in the
324 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
325 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
326 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
328 // NOTE: The following things are some that depend on the string types having
329 // instance_types that are less than those of all other types:
330 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
333 // NOTE: Everything following JS_VALUE_TYPE is considered a
334 // JSObject for GC purposes. The first four entries here have typeof
335 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
336 #define INSTANCE_TYPE_LIST(V) \
338 V(ONE_BYTE_STRING_TYPE) \
339 V(CONS_STRING_TYPE) \
340 V(CONS_ONE_BYTE_STRING_TYPE) \
341 V(SLICED_STRING_TYPE) \
342 V(SLICED_ONE_BYTE_STRING_TYPE) \
343 V(EXTERNAL_STRING_TYPE) \
344 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
345 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
346 V(SHORT_EXTERNAL_STRING_TYPE) \
347 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
348 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
350 V(INTERNALIZED_STRING_TYPE) \
351 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
352 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
353 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
354 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
355 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
356 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
357 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
360 V(SIMD128_VALUE_TYPE) \
366 V(PROPERTY_CELL_TYPE) \
368 V(HEAP_NUMBER_TYPE) \
369 V(MUTABLE_HEAP_NUMBER_TYPE) \
372 V(BYTECODE_ARRAY_TYPE) \
375 V(FIXED_INT8_ARRAY_TYPE) \
376 V(FIXED_UINT8_ARRAY_TYPE) \
377 V(FIXED_INT16_ARRAY_TYPE) \
378 V(FIXED_UINT16_ARRAY_TYPE) \
379 V(FIXED_INT32_ARRAY_TYPE) \
380 V(FIXED_UINT32_ARRAY_TYPE) \
381 V(FIXED_FLOAT32_ARRAY_TYPE) \
382 V(FIXED_FLOAT64_ARRAY_TYPE) \
383 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
387 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
388 V(DECLARED_ACCESSOR_INFO_TYPE) \
389 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
390 V(ACCESSOR_PAIR_TYPE) \
391 V(ACCESS_CHECK_INFO_TYPE) \
392 V(INTERCEPTOR_INFO_TYPE) \
393 V(CALL_HANDLER_INFO_TYPE) \
394 V(FUNCTION_TEMPLATE_INFO_TYPE) \
395 V(OBJECT_TEMPLATE_INFO_TYPE) \
396 V(SIGNATURE_INFO_TYPE) \
397 V(TYPE_SWITCH_INFO_TYPE) \
398 V(ALLOCATION_MEMENTO_TYPE) \
399 V(ALLOCATION_SITE_TYPE) \
402 V(POLYMORPHIC_CODE_CACHE_TYPE) \
403 V(TYPE_FEEDBACK_INFO_TYPE) \
404 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
406 V(PROTOTYPE_INFO_TYPE) \
407 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
409 V(FIXED_ARRAY_TYPE) \
410 V(FIXED_DOUBLE_ARRAY_TYPE) \
411 V(SHARED_FUNCTION_INFO_TYPE) \
414 V(JS_MESSAGE_OBJECT_TYPE) \
419 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
420 V(JS_GENERATOR_OBJECT_TYPE) \
422 V(JS_GLOBAL_OBJECT_TYPE) \
423 V(JS_BUILTINS_OBJECT_TYPE) \
424 V(JS_GLOBAL_PROXY_TYPE) \
426 V(JS_ARRAY_BUFFER_TYPE) \
427 V(JS_TYPED_ARRAY_TYPE) \
428 V(JS_DATA_VIEW_TYPE) \
432 V(JS_SET_ITERATOR_TYPE) \
433 V(JS_MAP_ITERATOR_TYPE) \
434 V(JS_ITERATOR_RESULT_TYPE) \
435 V(JS_WEAK_MAP_TYPE) \
436 V(JS_WEAK_SET_TYPE) \
439 V(JS_FUNCTION_TYPE) \
440 V(JS_FUNCTION_PROXY_TYPE) \
442 V(BREAK_POINT_INFO_TYPE)
445 // Since string types are not consecutive, this macro is used to
446 // iterate over them.
447 #define STRING_TYPE_LIST(V) \
448 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
449 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
451 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
452 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
454 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
455 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
456 SlicedOneByteString) \
457 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
459 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
460 external_one_byte_string, ExternalOneByteString) \
461 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
462 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
463 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
464 short_external_string, ShortExternalString) \
465 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
466 short_external_one_byte_string, ShortExternalOneByteString) \
467 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
468 ExternalTwoByteString::kShortSize, \
469 short_external_string_with_one_byte_data, \
470 ShortExternalStringWithOneByteData) \
472 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
473 InternalizedString) \
474 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
475 one_byte_internalized_string, OneByteInternalizedString) \
476 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
477 external_internalized_string, ExternalInternalizedString) \
478 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
479 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
480 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
481 ExternalTwoByteString::kSize, \
482 external_internalized_string_with_one_byte_data, \
483 ExternalInternalizedStringWithOneByteData) \
484 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
485 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
486 ShortExternalInternalizedString) \
487 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
488 ExternalOneByteString::kShortSize, \
489 short_external_one_byte_internalized_string, \
490 ShortExternalOneByteInternalizedString) \
491 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
492 ExternalTwoByteString::kShortSize, \
493 short_external_internalized_string_with_one_byte_data, \
494 ShortExternalInternalizedStringWithOneByteData)
496 // A struct is a simple object a set of object-valued fields. Including an
497 // object type in this causes the compiler to generate most of the boilerplate
498 // code for the class including allocation and garbage collection routines,
499 // casts and predicates. All you need to define is the class, methods and
500 // object verification routines. Easy, no?
502 // Note that for subtle reasons related to the ordering or numerical values of
503 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
505 #define STRUCT_LIST(V) \
507 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
508 executable_accessor_info) \
509 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
510 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
511 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
512 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
513 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
514 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
515 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
516 V(SCRIPT, Script, script) \
517 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
518 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
519 V(CODE_CACHE, CodeCache, code_cache) \
520 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
521 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
522 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
523 V(DEBUG_INFO, DebugInfo, debug_info) \
524 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
525 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
526 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
527 SloppyBlockWithEvalContextExtension, \
528 sloppy_block_with_eval_context_extension)
530 // We use the full 8 bits of the instance_type field to encode heap object
531 // instance types. The high-order bit (bit 7) is set if the object is not a
532 // string, and cleared if it is a string.
533 const uint32_t kIsNotStringMask = 0x80;
534 const uint32_t kStringTag = 0x0;
535 const uint32_t kNotStringTag = 0x80;
537 // Bit 6 indicates that the object is an internalized string (if set) or not.
538 // Bit 7 has to be clear as well.
539 const uint32_t kIsNotInternalizedMask = 0x40;
540 const uint32_t kNotInternalizedTag = 0x40;
541 const uint32_t kInternalizedTag = 0x0;
543 // If bit 7 is clear then bit 2 indicates whether the string consists of
544 // two-byte characters or one-byte characters.
545 const uint32_t kStringEncodingMask = 0x4;
546 const uint32_t kTwoByteStringTag = 0x0;
547 const uint32_t kOneByteStringTag = 0x4;
549 // If bit 7 is clear, the low-order 2 bits indicate the representation
551 const uint32_t kStringRepresentationMask = 0x03;
552 enum StringRepresentationTag {
554 kConsStringTag = 0x1,
555 kExternalStringTag = 0x2,
556 kSlicedStringTag = 0x3
558 const uint32_t kIsIndirectStringMask = 0x1;
559 const uint32_t kIsIndirectStringTag = 0x1;
560 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
561 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
562 STATIC_ASSERT((kConsStringTag &
563 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
564 STATIC_ASSERT((kSlicedStringTag &
565 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
567 // Use this mask to distinguish between cons and slice only after making
568 // sure that the string is one of the two (an indirect string).
569 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
570 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
572 // If bit 7 is clear, then bit 3 indicates whether this two-byte
573 // string actually contains one byte data.
574 const uint32_t kOneByteDataHintMask = 0x08;
575 const uint32_t kOneByteDataHintTag = 0x08;
577 // If bit 7 is clear and string representation indicates an external string,
578 // then bit 4 indicates whether the data pointer is cached.
579 const uint32_t kShortExternalStringMask = 0x10;
580 const uint32_t kShortExternalStringTag = 0x10;
583 // A ConsString with an empty string as the right side is a candidate
584 // for being shortcut by the garbage collector. We don't allocate any
585 // non-flat internalized strings, so we do not shortcut them thereby
586 // avoiding turning internalized strings into strings. The bit-masks
587 // below contain the internalized bit as additional safety.
588 // See heap.cc, mark-compact.cc and objects-visiting.cc.
589 const uint32_t kShortcutTypeMask =
591 kIsNotInternalizedMask |
592 kStringRepresentationMask;
593 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
595 static inline bool IsShortcutCandidate(int type) {
596 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
602 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
603 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
604 ONE_BYTE_INTERNALIZED_STRING_TYPE =
605 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
606 EXTERNAL_INTERNALIZED_STRING_TYPE =
607 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
608 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
609 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
610 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
611 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
613 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
614 kShortExternalStringTag |
616 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
617 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
619 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
620 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
621 kShortExternalStringTag | kInternalizedTag,
622 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
623 ONE_BYTE_STRING_TYPE =
624 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
625 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
626 CONS_ONE_BYTE_STRING_TYPE =
627 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
629 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
630 SLICED_ONE_BYTE_STRING_TYPE =
631 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
632 EXTERNAL_STRING_TYPE =
633 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
634 EXTERNAL_ONE_BYTE_STRING_TYPE =
635 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
636 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
637 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
639 SHORT_EXTERNAL_STRING_TYPE =
640 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
641 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
642 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
643 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
644 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
648 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
650 // Other primitives (cannot contain non-map-word pointers to heap objects).
653 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
655 // Objects allocated in their own spaces (never in new space).
659 // "Data", objects that cannot contain non-map-word pointers to heap
661 MUTABLE_HEAP_NUMBER_TYPE,
666 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
667 FIXED_UINT8_ARRAY_TYPE,
668 FIXED_INT16_ARRAY_TYPE,
669 FIXED_UINT16_ARRAY_TYPE,
670 FIXED_INT32_ARRAY_TYPE,
671 FIXED_UINT32_ARRAY_TYPE,
672 FIXED_FLOAT32_ARRAY_TYPE,
673 FIXED_FLOAT64_ARRAY_TYPE,
674 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
675 FIXED_DOUBLE_ARRAY_TYPE,
676 FILLER_TYPE, // LAST_DATA_TYPE
679 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
680 DECLARED_ACCESSOR_INFO_TYPE,
681 EXECUTABLE_ACCESSOR_INFO_TYPE,
683 ACCESS_CHECK_INFO_TYPE,
684 INTERCEPTOR_INFO_TYPE,
685 CALL_HANDLER_INFO_TYPE,
686 FUNCTION_TEMPLATE_INFO_TYPE,
687 OBJECT_TEMPLATE_INFO_TYPE,
689 TYPE_SWITCH_INFO_TYPE,
690 ALLOCATION_SITE_TYPE,
691 ALLOCATION_MEMENTO_TYPE,
694 POLYMORPHIC_CODE_CACHE_TYPE,
695 TYPE_FEEDBACK_INFO_TYPE,
696 ALIASED_ARGUMENTS_ENTRY_TYPE,
699 BREAK_POINT_INFO_TYPE,
701 SHARED_FUNCTION_INFO_TYPE,
706 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
708 // All the following types are subtypes of JSReceiver, which corresponds to
709 // objects in the JS sense. The first and the last type in this range are
710 // the two forms of function. This organization enables using the same
711 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
712 // NONCALLABLE_JS_OBJECT range.
713 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
714 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
715 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
716 JS_MESSAGE_OBJECT_TYPE,
719 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
720 JS_GENERATOR_OBJECT_TYPE,
722 JS_GLOBAL_OBJECT_TYPE,
723 JS_BUILTINS_OBJECT_TYPE,
724 JS_GLOBAL_PROXY_TYPE,
726 JS_ARRAY_BUFFER_TYPE,
731 JS_SET_ITERATOR_TYPE,
732 JS_MAP_ITERATOR_TYPE,
733 JS_ITERATOR_RESULT_TYPE,
737 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
741 LAST_TYPE = JS_FUNCTION_TYPE,
742 FIRST_NAME_TYPE = FIRST_TYPE,
743 LAST_NAME_TYPE = SYMBOL_TYPE,
744 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
745 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
746 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
747 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
748 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
749 // Boundaries for testing for a fixed typed array.
750 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
751 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
752 // Boundary for promotion to old space.
753 LAST_DATA_TYPE = FILLER_TYPE,
754 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
755 // Note that there is no range for JSObject or JSProxy, since their subtypes
756 // are not continuous in this enum! The enum ranges instead reflect the
757 // external class names, where proxies are treated as either ordinary objects,
759 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
760 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
761 // Boundaries for testing the types represented as JSObject
762 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
763 LAST_JS_OBJECT_TYPE = LAST_TYPE,
764 // Boundaries for testing the types represented as JSProxy
765 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
766 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
767 // Boundaries for testing whether the type is a JavaScript object.
768 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
769 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
770 // Boundaries for testing the types for which typeof is "object".
771 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
772 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
773 // Note that the types for which typeof is "function" are not continuous.
774 // Define this so that we can put assertions on discrete checks.
775 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
778 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
779 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
780 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
781 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
784 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
785 V(FAST_ELEMENTS_SUB_TYPE) \
786 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
787 V(FAST_PROPERTIES_SUB_TYPE) \
788 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
789 V(MAP_CODE_CACHE_SUB_TYPE) \
790 V(SCOPE_INFO_SUB_TYPE) \
791 V(STRING_TABLE_SUB_TYPE) \
792 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
793 V(TRANSITION_ARRAY_SUB_TYPE)
795 enum FixedArraySubInstanceType {
796 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
797 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
798 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
799 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
803 // TODO(bmeurer): Remove this in favor of the ComparisonResult below.
813 // Result of an abstract relational comparison of x and y, implemented according
814 // to ES6 section 7.2.11 Abstract Relational Comparison.
815 enum class ComparisonResult {
818 kGreaterThan, // x > x
819 kUndefined // at least one of x or y was undefined or NaN
823 #define DECL_BOOLEAN_ACCESSORS(name) \
824 inline bool name() const; \
825 inline void set_##name(bool value); \
828 #define DECL_ACCESSORS(name, type) \
829 inline type* name() const; \
830 inline void set_##name(type* value, \
831 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
834 #define DECLARE_CAST(type) \
835 INLINE(static type* cast(Object* object)); \
836 INLINE(static const type* cast(const Object* object));
840 class AllocationSite;
841 class AllocationSiteCreationContext;
842 class AllocationSiteUsageContext;
845 class ElementsAccessor;
846 class FixedArrayBase;
847 class FunctionLiteral;
849 class JSBuiltinsObject;
850 class LayoutDescriptor;
851 class LookupIterator;
852 class ObjectHashTable;
855 class SafepointEntry;
856 class SharedFunctionInfo;
858 class TypeFeedbackInfo;
859 class TypeFeedbackVector;
862 // We cannot just say "class HeapType;" if it is created from a template... =8-?
863 template<class> class TypeImpl;
864 struct HeapTypeConfig;
865 typedef TypeImpl<HeapTypeConfig> HeapType;
868 // A template-ized version of the IsXXX functions.
869 template <class C> inline bool Is(Object* obj);
872 #define DECLARE_VERIFIER(Name) void Name##Verify();
874 #define DECLARE_VERIFIER(Name)
878 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
880 #define DECLARE_PRINTER(Name)
884 #define OBJECT_TYPE_LIST(V) \
889 #define HEAP_OBJECT_TYPE_LIST(V) \
891 V(MutableHeapNumber) \
910 V(ExternalTwoByteString) \
911 V(ExternalOneByteString) \
912 V(SeqTwoByteString) \
913 V(SeqOneByteString) \
914 V(InternalizedString) \
917 V(FixedTypedArrayBase) \
920 V(FixedUint16Array) \
922 V(FixedUint32Array) \
924 V(FixedFloat32Array) \
925 V(FixedFloat64Array) \
926 V(FixedUint8ClampedArray) \
932 V(JSContextExtensionObject) \
933 V(JSGeneratorObject) \
935 V(LayoutDescriptor) \
939 V(TypeFeedbackVector) \
940 V(DeoptimizationInputData) \
941 V(DeoptimizationOutputData) \
945 V(FixedDoubleArray) \
949 V(ScriptContextTable) \
955 V(SharedFunctionInfo) \
964 V(JSArrayBufferView) \
973 V(JSIteratorResult) \
974 V(JSWeakCollection) \
981 V(NormalizedMapCache) \
982 V(CompilationCacheTable) \
983 V(CodeCacheHashTable) \
984 V(PolymorphicCodeCacheHashTable) \
989 V(JSBuiltinsObject) \
991 V(UndetectableObject) \
992 V(AccessCheckNeeded) \
1000 // Object is the abstract superclass for all classes in the
1001 // object hierarchy.
1002 // Object does not use any virtual functions to avoid the
1003 // allocation of the C++ vtable.
1004 // Since both Smi and HeapObject are subclasses of Object no
1005 // data members can be present in Object.
1009 bool IsObject() const { return true; }
1011 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1012 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1013 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1014 #undef IS_TYPE_FUNCTION_DECL
1016 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1017 // a keyed store is of the form a[expression] = foo.
1018 enum StoreFromKeyed {
1019 MAY_BE_STORE_FROM_KEYED,
1020 CERTAINLY_NOT_STORE_FROM_KEYED
1023 INLINE(bool IsFixedArrayBase() const);
1024 INLINE(bool IsExternal() const);
1025 INLINE(bool IsAccessorInfo() const);
1027 INLINE(bool IsStruct() const);
1028 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1029 INLINE(bool Is##Name() const);
1030 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1031 #undef DECLARE_STRUCT_PREDICATE
1033 // ES6, section 7.2.3 IsCallable.
1034 INLINE(bool IsCallable() const);
1036 INLINE(bool IsSpecObject()) const;
1037 INLINE(bool IsTemplateInfo()) const;
1038 INLINE(bool IsNameDictionary() const);
1039 INLINE(bool IsGlobalDictionary() const);
1040 INLINE(bool IsSeededNumberDictionary() const);
1041 INLINE(bool IsUnseededNumberDictionary() const);
1042 INLINE(bool IsOrderedHashSet() const);
1043 INLINE(bool IsOrderedHashMap() const);
1044 static bool IsPromise(Handle<Object> object);
1047 INLINE(bool IsUndefined() const);
1048 INLINE(bool IsNull() const);
1049 INLINE(bool IsTheHole() const);
1050 INLINE(bool IsException() const);
1051 INLINE(bool IsUninitialized() const);
1052 INLINE(bool IsTrue() const);
1053 INLINE(bool IsFalse() const);
1054 INLINE(bool IsArgumentsMarker() const);
1056 // Filler objects (fillers and free space objects).
1057 INLINE(bool IsFiller() const);
1059 // Extract the number.
1060 inline double Number() const;
1061 INLINE(bool IsNaN() const);
1062 INLINE(bool IsMinusZero() const);
1063 bool ToInt32(int32_t* value);
1064 bool ToUint32(uint32_t* value);
1066 inline Representation OptimalRepresentation();
1068 inline ElementsKind OptimalElementsKind();
1070 inline bool FitsRepresentation(Representation representation);
1072 // Checks whether two valid primitive encodings of a property name resolve to
1073 // the same logical property. E.g., the smi 1, the string "1" and the double
1074 // 1 all refer to the same property, so this helper will return true.
1075 inline bool KeyEquals(Object* other);
1077 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1079 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1080 Handle<Object> object,
1081 Representation representation);
1083 inline static Handle<Object> WrapForRead(Isolate* isolate,
1084 Handle<Object> object,
1085 Representation representation);
1087 // Returns true if the object is of the correct type to be used as a
1088 // implementation of a JSObject's elements.
1089 inline bool HasValidElements();
1091 inline bool HasSpecificClassOf(String* name);
1093 bool BooleanValue(); // ECMA-262 9.2.
1095 // ES6 section 7.2.11 Abstract Relational Comparison
1096 MUST_USE_RESULT static Maybe<ComparisonResult> Compare(
1097 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1099 // ES6 section 7.2.12 Abstract Equality Comparison
1100 MUST_USE_RESULT static Maybe<bool> Equals(Handle<Object> x, Handle<Object> y);
1102 // ES6 section 7.2.13 Strict Equality Comparison
1103 bool StrictEquals(Object* that);
1105 // Convert to a JSObject if needed.
1106 // native_context is used when creating wrapper object.
1107 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1108 Handle<Object> object);
1109 MUST_USE_RESULT static MaybeHandle<JSReceiver> ToObject(
1110 Isolate* isolate, Handle<Object> object, Handle<Context> context);
1112 // ES6 section 7.1.14 ToPropertyKey
1113 MUST_USE_RESULT static inline MaybeHandle<Name> ToName(Isolate* isolate,
1114 Handle<Object> input);
1116 // ES6 section 7.1.1 ToPrimitive
1117 MUST_USE_RESULT static inline MaybeHandle<Object> ToPrimitive(
1118 Handle<Object> input, ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1120 // ES6 section 7.1.3 ToNumber
1121 MUST_USE_RESULT static MaybeHandle<Object> ToNumber(Handle<Object> input);
1123 // ES6 section 7.1.12 ToString
1124 MUST_USE_RESULT static MaybeHandle<String> ToString(Isolate* isolate,
1125 Handle<Object> input);
1127 // ES6 section 7.3.9 GetMethod
1128 MUST_USE_RESULT static MaybeHandle<Object> GetMethod(
1129 Handle<JSReceiver> receiver, Handle<Name> name);
1131 // ES6 section 12.5.6 The typeof Operator
1132 static Handle<String> TypeOf(Isolate* isolate, Handle<Object> object);
1134 // ES6 section 12.6 Multiplicative Operators
1135 MUST_USE_RESULT static MaybeHandle<Object> Multiply(
1136 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1137 Strength strength = Strength::WEAK);
1138 MUST_USE_RESULT static MaybeHandle<Object> Divide(
1139 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1140 Strength strength = Strength::WEAK);
1141 MUST_USE_RESULT static MaybeHandle<Object> Modulus(
1142 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1143 Strength strength = Strength::WEAK);
1145 // ES6 section 12.7 Additive Operators
1146 MUST_USE_RESULT static MaybeHandle<Object> Add(
1147 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1148 Strength strength = Strength::WEAK);
1149 MUST_USE_RESULT static MaybeHandle<Object> Subtract(
1150 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1151 Strength strength = Strength::WEAK);
1153 // ES6 section 12.8 Bitwise Shift Operators
1154 MUST_USE_RESULT static MaybeHandle<Object> ShiftLeft(
1155 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1156 Strength strength = Strength::WEAK);
1157 MUST_USE_RESULT static MaybeHandle<Object> ShiftRight(
1158 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1159 Strength strength = Strength::WEAK);
1160 MUST_USE_RESULT static MaybeHandle<Object> ShiftRightLogical(
1161 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1162 Strength strength = Strength::WEAK);
1164 // ES6 section 12.9 Relational Operators
1165 MUST_USE_RESULT static inline Maybe<bool> GreaterThan(
1166 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1167 MUST_USE_RESULT static inline Maybe<bool> GreaterThanOrEqual(
1168 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1169 MUST_USE_RESULT static inline Maybe<bool> LessThan(
1170 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1171 MUST_USE_RESULT static inline Maybe<bool> LessThanOrEqual(
1172 Handle<Object> x, Handle<Object> y, Strength strength = Strength::WEAK);
1174 // ES6 section 12.11 Binary Bitwise Operators
1175 MUST_USE_RESULT static MaybeHandle<Object> BitwiseAnd(
1176 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1177 Strength strength = Strength::WEAK);
1178 MUST_USE_RESULT static MaybeHandle<Object> BitwiseOr(
1179 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1180 Strength strength = Strength::WEAK);
1181 MUST_USE_RESULT static MaybeHandle<Object> BitwiseXor(
1182 Isolate* isolate, Handle<Object> lhs, Handle<Object> rhs,
1183 Strength strength = Strength::WEAK);
1185 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1186 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1188 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1189 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1190 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1191 LanguageMode language_mode,
1192 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1194 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1195 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1196 StoreFromKeyed store_mode);
1198 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1199 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1200 StoreFromKeyed store_mode);
1202 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1203 LookupIterator* it, LanguageMode language_mode);
1204 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1205 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1206 LanguageMode language_mode);
1207 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1208 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1209 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1210 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1211 Handle<Object> value, LanguageMode language_mode);
1212 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1213 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1214 LanguageMode language_mode);
1215 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1216 LookupIterator* it, Handle<Object> value);
1217 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1218 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1219 LanguageMode language_mode, StoreFromKeyed store_mode);
1220 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1221 Handle<Object> object, Handle<Name> name,
1222 LanguageMode language_mode = SLOPPY);
1223 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1224 Isolate* isolate, Handle<Object> object, const char* key,
1225 LanguageMode language_mode = SLOPPY);
1226 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1227 Handle<Object> object, Handle<Name> name,
1228 LanguageMode language_mode = SLOPPY);
1230 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1231 LookupIterator* it, LanguageMode language_mode);
1232 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1233 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1235 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1236 Handle<Object> receiver,
1237 Handle<JSReceiver> getter);
1238 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1239 Handle<Object> receiver,
1240 Handle<JSReceiver> setter,
1241 Handle<Object> value);
1243 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1244 Isolate* isolate, Handle<Object> object, uint32_t index,
1245 LanguageMode language_mode = SLOPPY);
1247 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1248 Isolate* isolate, Handle<Object> object, uint32_t index,
1249 Handle<Object> value, LanguageMode language_mode);
1251 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1252 Isolate* isolate, Handle<Object> receiver);
1254 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1256 // Returns the permanent hash code associated with this object. May return
1257 // undefined if not yet created.
1260 // Returns undefined for JSObjects, but returns the hash code for simple
1261 // objects. This avoids a double lookup in the cases where we know we will
1262 // add the hash to the JSObject if it does not already exist.
1263 Object* GetSimpleHash();
1265 // Returns the permanent hash code associated with this object depending on
1266 // the actual object type. May create and store a hash code if needed and none
1268 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1270 // Checks whether this object has the same value as the given one. This
1271 // function is implemented according to ES5, section 9.12 and can be used
1272 // to implement the Harmony "egal" function.
1273 bool SameValue(Object* other);
1275 // Checks whether this object has the same value as the given one.
1276 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1277 // This function is implemented according to ES6, section 7.2.4 and is used
1278 // by ES6 Map and Set.
1279 bool SameValueZero(Object* other);
1281 // Tries to convert an object to an array length. Returns true and sets the
1282 // output parameter if it succeeds.
1283 inline bool ToArrayLength(uint32_t* index);
1285 // Tries to convert an object to an array index. Returns true and sets the
1286 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1287 // allow kMaxUInt32.
1288 inline bool ToArrayIndex(uint32_t* index);
1290 // Returns true if this is a JSValue containing a string and the index is
1291 // < the length of the string. Used to implement [] on strings.
1292 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1294 DECLARE_VERIFIER(Object)
1296 // Verify a pointer is a valid object pointer.
1297 static void VerifyPointer(Object* p);
1300 inline void VerifyApiCallResultType();
1302 // Prints this object without details.
1303 void ShortPrint(FILE* out = stdout);
1305 // Prints this object without details to a message accumulator.
1306 void ShortPrint(StringStream* accumulator);
1308 void ShortPrint(std::ostream& os); // NOLINT
1310 DECLARE_CAST(Object)
1312 // Layout description.
1313 static const int kHeaderSize = 0; // Object does not take up any space.
1316 // For our gdb macros, we should perhaps change these in the future.
1319 // Prints this object with details.
1320 void Print(std::ostream& os); // NOLINT
1322 void Print() { ShortPrint(); }
1323 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1327 friend class LookupIterator;
1328 friend class PrototypeIterator;
1330 // Return the map of the root of object's prototype chain.
1331 Map* GetRootMap(Isolate* isolate);
1333 // Helper for SetProperty and SetSuperProperty.
1334 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1335 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1336 StoreFromKeyed store_mode, bool* found);
1338 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1342 // In objects.h to be usable without objects-inl.h inclusion.
1343 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1344 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1348 explicit Brief(const Object* const v) : value(v) {}
1349 const Object* value;
1353 std::ostream& operator<<(std::ostream& os, const Brief& v);
1356 // Smi represents integer Numbers that can be stored in 31 bits.
1357 // Smis are immediate which means they are NOT allocated in the heap.
1358 // The this pointer has the following format: [31 bit signed int] 0
1359 // For long smis it has the following format:
1360 // [32 bit signed int] [31 bits zero padding] 0
1361 // Smi stands for small integer.
1362 class Smi: public Object {
1364 // Returns the integer value.
1365 inline int value() const { return Internals::SmiValue(this); }
1367 // Convert a value to a Smi object.
1368 static inline Smi* FromInt(int value) {
1369 DCHECK(Smi::IsValid(value));
1370 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1373 static inline Smi* FromIntptr(intptr_t value) {
1374 DCHECK(Smi::IsValid(value));
1375 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1376 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1379 // Returns whether value can be represented in a Smi.
1380 static inline bool IsValid(intptr_t value) {
1381 bool result = Internals::IsValidSmi(value);
1382 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1388 // Dispatched behavior.
1389 void SmiPrint(std::ostream& os) const; // NOLINT
1390 DECLARE_VERIFIER(Smi)
1392 static const int kMinValue =
1393 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1394 static const int kMaxValue = -(kMinValue + 1);
1397 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1401 // Heap objects typically have a map pointer in their first word. However,
1402 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1403 // encoded in the first word. The class MapWord is an abstraction of the
1404 // value in a heap object's first word.
1405 class MapWord BASE_EMBEDDED {
1407 // Normal state: the map word contains a map pointer.
1409 // Create a map word from a map pointer.
1410 static inline MapWord FromMap(const Map* map);
1412 // View this map word as a map pointer.
1413 inline Map* ToMap();
1416 // Scavenge collection: the map word of live objects in the from space
1417 // contains a forwarding address (a heap object pointer in the to space).
1419 // True if this map word is a forwarding address for a scavenge
1420 // collection. Only valid during a scavenge collection (specifically,
1421 // when all map words are heap object pointers, i.e. not during a full GC).
1422 inline bool IsForwardingAddress();
1424 // Create a map word from a forwarding address.
1425 static inline MapWord FromForwardingAddress(HeapObject* object);
1427 // View this map word as a forwarding address.
1428 inline HeapObject* ToForwardingAddress();
1430 static inline MapWord FromRawValue(uintptr_t value) {
1431 return MapWord(value);
1434 inline uintptr_t ToRawValue() {
1439 // HeapObject calls the private constructor and directly reads the value.
1440 friend class HeapObject;
1442 explicit MapWord(uintptr_t value) : value_(value) {}
1448 // The content of an heap object (except for the map pointer). kTaggedValues
1449 // objects can contain both heap pointers and Smis, kMixedValues can contain
1450 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1451 // objects can contain raw values and Smis.
1452 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1455 // HeapObject is the superclass for all classes describing heap allocated
1457 class HeapObject: public Object {
1459 // [map]: Contains a map which contains the object's reflective
1461 inline Map* map() const;
1462 inline void set_map(Map* value);
1463 // The no-write-barrier version. This is OK if the object is white and in
1464 // new space, or if the value is an immortal immutable object, like the maps
1465 // of primitive (non-JS) objects like strings, heap numbers etc.
1466 inline void set_map_no_write_barrier(Map* value);
1468 // Get the map using acquire load.
1469 inline Map* synchronized_map();
1470 inline MapWord synchronized_map_word() const;
1472 // Set the map using release store
1473 inline void synchronized_set_map(Map* value);
1474 inline void synchronized_set_map_no_write_barrier(Map* value);
1475 inline void synchronized_set_map_word(MapWord map_word);
1477 // During garbage collection, the map word of a heap object does not
1478 // necessarily contain a map pointer.
1479 inline MapWord map_word() const;
1480 inline void set_map_word(MapWord map_word);
1482 // The Heap the object was allocated in. Used also to access Isolate.
1483 inline Heap* GetHeap() const;
1485 // Convenience method to get current isolate.
1486 inline Isolate* GetIsolate() const;
1488 // Converts an address to a HeapObject pointer.
1489 static inline HeapObject* FromAddress(Address address) {
1490 DCHECK_TAG_ALIGNED(address);
1491 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1494 // Returns the address of this HeapObject.
1495 inline Address address() {
1496 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1499 // Iterates over pointers contained in the object (including the Map)
1500 void Iterate(ObjectVisitor* v);
1502 // Iterates over all pointers contained in the object except the
1503 // first map pointer. The object type is given in the first
1504 // parameter. This function does not access the map pointer in the
1505 // object, and so is safe to call while the map pointer is modified.
1506 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1508 // Returns the heap object's size in bytes
1511 // Indicates what type of values this heap object may contain.
1512 inline HeapObjectContents ContentType();
1514 // Given a heap object's map pointer, returns the heap size in bytes
1515 // Useful when the map pointer field is used for other purposes.
1517 inline int SizeFromMap(Map* map);
1519 // Returns the field at offset in obj, as a read/write Object* reference.
1520 // Does no checking, and is safe to use during GC, while maps are invalid.
1521 // Does not invoke write barrier, so should only be assigned to
1522 // during marking GC.
1523 static inline Object** RawField(HeapObject* obj, int offset);
1525 // Adds the |code| object related to |name| to the code cache of this map. If
1526 // this map is a dictionary map that is shared, the map copied and installed
1528 static void UpdateMapCodeCache(Handle<HeapObject> object,
1532 DECLARE_CAST(HeapObject)
1534 // Return the write barrier mode for this. Callers of this function
1535 // must be able to present a reference to an DisallowHeapAllocation
1536 // object as a sign that they are not going to use this function
1537 // from code that allocates and thus invalidates the returned write
1539 inline WriteBarrierMode GetWriteBarrierMode(
1540 const DisallowHeapAllocation& promise);
1542 // Dispatched behavior.
1543 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1545 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1547 DECLARE_PRINTER(HeapObject)
1548 DECLARE_VERIFIER(HeapObject)
1550 inline void VerifyObjectField(int offset);
1551 inline void VerifySmiField(int offset);
1553 // Verify a pointer is a valid HeapObject pointer that points to object
1554 // areas in the heap.
1555 static void VerifyHeapPointer(Object* p);
1558 inline AllocationAlignment RequiredAlignment();
1560 // Layout description.
1561 // First field in a heap object is map.
1562 static const int kMapOffset = Object::kHeaderSize;
1563 static const int kHeaderSize = kMapOffset + kPointerSize;
1565 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1568 // helpers for calling an ObjectVisitor to iterate over pointers in the
1569 // half-open range [start, end) specified as integer offsets
1570 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1571 // as above, for the single element at "offset"
1572 inline void IteratePointer(ObjectVisitor* v, int offset);
1573 // as above, for the next code link of a code object.
1574 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1577 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1581 // This class describes a body of an object of a fixed size
1582 // in which all pointer fields are located in the [start_offset, end_offset)
1584 template<int start_offset, int end_offset, int size>
1585 class FixedBodyDescriptor {
1587 static const int kStartOffset = start_offset;
1588 static const int kEndOffset = end_offset;
1589 static const int kSize = size;
1591 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1593 template<typename StaticVisitor>
1594 static inline void IterateBody(HeapObject* obj) {
1595 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1596 HeapObject::RawField(obj, end_offset));
1601 // This class describes a body of an object of a variable size
1602 // in which all pointer fields are located in the [start_offset, object_size)
1604 template<int start_offset>
1605 class FlexibleBodyDescriptor {
1607 static const int kStartOffset = start_offset;
1609 static inline void IterateBody(HeapObject* obj,
1613 template<typename StaticVisitor>
1614 static inline void IterateBody(HeapObject* obj, int object_size) {
1615 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1616 HeapObject::RawField(obj, object_size));
1621 // The HeapNumber class describes heap allocated numbers that cannot be
1622 // represented in a Smi (small integer)
1623 class HeapNumber: public HeapObject {
1625 // [value]: number value.
1626 inline double value() const;
1627 inline void set_value(double value);
1629 DECLARE_CAST(HeapNumber)
1631 // Dispatched behavior.
1632 bool HeapNumberBooleanValue();
1634 void HeapNumberPrint(std::ostream& os); // NOLINT
1635 DECLARE_VERIFIER(HeapNumber)
1637 inline int get_exponent();
1638 inline int get_sign();
1640 // Layout description.
1641 static const int kValueOffset = HeapObject::kHeaderSize;
1642 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1643 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1644 // words within double numbers are endian dependent and they are set
1646 #if defined(V8_TARGET_LITTLE_ENDIAN)
1647 static const int kMantissaOffset = kValueOffset;
1648 static const int kExponentOffset = kValueOffset + 4;
1649 #elif defined(V8_TARGET_BIG_ENDIAN)
1650 static const int kMantissaOffset = kValueOffset + 4;
1651 static const int kExponentOffset = kValueOffset;
1653 #error Unknown byte ordering
1656 static const int kSize = kValueOffset + kDoubleSize;
1657 static const uint32_t kSignMask = 0x80000000u;
1658 static const uint32_t kExponentMask = 0x7ff00000u;
1659 static const uint32_t kMantissaMask = 0xfffffu;
1660 static const int kMantissaBits = 52;
1661 static const int kExponentBits = 11;
1662 static const int kExponentBias = 1023;
1663 static const int kExponentShift = 20;
1664 static const int kInfinityOrNanExponent =
1665 (kExponentMask >> kExponentShift) - kExponentBias;
1666 static const int kMantissaBitsInTopWord = 20;
1667 static const int kNonMantissaBitsInTopWord = 12;
1670 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1674 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1675 class Simd128Value : public HeapObject {
1677 DECLARE_CAST(Simd128Value)
1679 DECLARE_PRINTER(Simd128Value)
1680 DECLARE_VERIFIER(Simd128Value)
1682 static Handle<String> ToString(Handle<Simd128Value> input);
1684 // Equality operations.
1685 inline bool Equals(Simd128Value* that);
1686 static inline bool Equals(Handle<Simd128Value> one, Handle<Simd128Value> two);
1688 // Checks that another instance is bit-wise equal.
1689 bool BitwiseEquals(const Simd128Value* other) const;
1690 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1691 uint32_t Hash() const;
1692 // Copies the 16 bytes of SIMD data to the destination address.
1693 void CopyBits(void* destination) const;
1695 // Layout description.
1696 static const int kValueOffset = HeapObject::kHeaderSize;
1697 static const int kSize = kValueOffset + kSimd128Size;
1700 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1704 // V has parameters (TYPE, Type, type, lane count, lane type)
1705 #define SIMD128_TYPES(V) \
1706 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1707 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1708 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1709 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1710 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1711 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1712 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1713 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1714 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1715 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1717 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1718 class Type final : public Simd128Value { \
1720 inline lane_type get_lane(int lane) const; \
1721 inline void set_lane(int lane, lane_type value); \
1723 DECLARE_CAST(Type) \
1725 DECLARE_PRINTER(Type) \
1727 static Handle<String> ToString(Handle<Type> input); \
1729 inline bool Equals(Type* that); \
1732 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1734 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1735 #undef SIMD128_VALUE_CLASS
1738 enum EnsureElementsMode {
1739 DONT_ALLOW_DOUBLE_ELEMENTS,
1740 ALLOW_COPIED_DOUBLE_ELEMENTS,
1741 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1745 // Indicator for one component of an AccessorPair.
1746 enum AccessorComponent {
1752 // JSReceiver includes types on which properties can be defined, i.e.,
1753 // JSObject and JSProxy.
1754 class JSReceiver: public HeapObject {
1756 DECLARE_CAST(JSReceiver)
1758 // ES6 section 7.1.1 ToPrimitive
1759 MUST_USE_RESULT static MaybeHandle<Object> ToPrimitive(
1760 Handle<JSReceiver> receiver,
1761 ToPrimitiveHint hint = ToPrimitiveHint::kDefault);
1762 MUST_USE_RESULT static MaybeHandle<Object> OrdinaryToPrimitive(
1763 Handle<JSReceiver> receiver, OrdinaryToPrimitiveHint hint);
1765 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1766 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1767 Handle<JSReceiver> object, Handle<Name> name);
1768 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1770 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1771 Handle<JSReceiver> object, uint32_t index);
1772 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1773 Handle<JSReceiver> object, uint32_t index);
1775 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1776 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1777 Handle<JSReceiver> object, Handle<Name> name,
1778 LanguageMode language_mode = SLOPPY);
1779 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1780 Handle<JSReceiver> object, Handle<Name> name,
1781 LanguageMode language_mode = SLOPPY);
1782 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1783 LookupIterator* it, LanguageMode language_mode);
1784 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1785 Handle<JSReceiver> object, uint32_t index,
1786 LanguageMode language_mode = SLOPPY);
1788 // Tests for the fast common case for property enumeration.
1789 bool IsSimpleEnum();
1791 // Returns the class name ([[Class]] property in the specification).
1792 String* class_name();
1794 // Returns the constructor name (the name (possibly, inferred name) of the
1795 // function that was used to instantiate the object).
1796 String* constructor_name();
1798 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1799 Handle<JSReceiver> object, Handle<Name> name);
1800 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1801 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1803 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1804 Handle<JSReceiver> object, uint32_t index);
1805 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1806 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1808 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1809 LookupIterator* it);
1812 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1814 static Handle<Object> GetDataProperty(LookupIterator* it);
1817 // Retrieves a permanent object identity hash code. The undefined value might
1818 // be returned in case no hash was created yet.
1819 inline Object* GetIdentityHash();
1821 // Retrieves a permanent object identity hash code. May create and store a
1822 // hash code if needed and none exists.
1823 inline static Handle<Smi> GetOrCreateIdentityHash(
1824 Handle<JSReceiver> object);
1826 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1828 // Computes the enumerable keys for a JSObject. Used for implementing
1829 // "for (n in object) { }".
1830 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1831 Handle<JSReceiver> object,
1832 KeyCollectionType type);
1835 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1839 // The JSObject describes real heap allocated JavaScript objects with
1841 // Note that the map of JSObject changes during execution to enable inline
1843 class JSObject: public JSReceiver {
1845 // [properties]: Backing storage for properties.
1846 // properties is a FixedArray in the fast case and a Dictionary in the
1848 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1849 inline void initialize_properties();
1850 inline bool HasFastProperties();
1851 // Gets slow properties for non-global objects.
1852 inline NameDictionary* property_dictionary();
1853 // Gets global object properties.
1854 inline GlobalDictionary* global_dictionary();
1856 // [elements]: The elements (properties with names that are integers).
1858 // Elements can be in two general modes: fast and slow. Each mode
1859 // corrensponds to a set of object representations of elements that
1860 // have something in common.
1862 // In the fast mode elements is a FixedArray and so each element can
1863 // be quickly accessed. This fact is used in the generated code. The
1864 // elements array can have one of three maps in this mode:
1865 // fixed_array_map, sloppy_arguments_elements_map or
1866 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1867 // the elements array may be shared by a few objects and so before
1868 // writing to any element the array must be copied. Use
1869 // EnsureWritableFastElements in this case.
1871 // In the slow mode the elements is either a NumberDictionary, a
1872 // FixedArray parameter map for a (sloppy) arguments object.
1873 DECL_ACCESSORS(elements, FixedArrayBase)
1874 inline void initialize_elements();
1875 static void ResetElements(Handle<JSObject> object);
1876 static inline void SetMapAndElements(Handle<JSObject> object,
1878 Handle<FixedArrayBase> elements);
1879 inline ElementsKind GetElementsKind();
1880 ElementsAccessor* GetElementsAccessor();
1881 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1882 inline bool HasFastSmiElements();
1883 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1884 inline bool HasFastObjectElements();
1885 // Returns true if an object has elements of FAST_ELEMENTS or
1886 // FAST_SMI_ONLY_ELEMENTS.
1887 inline bool HasFastSmiOrObjectElements();
1888 // Returns true if an object has any of the fast elements kinds.
1889 inline bool HasFastElements();
1890 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1892 inline bool HasFastDoubleElements();
1893 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1895 inline bool HasFastHoleyElements();
1896 inline bool HasSloppyArgumentsElements();
1897 inline bool HasDictionaryElements();
1899 inline bool HasFixedTypedArrayElements();
1901 inline bool HasFixedUint8ClampedElements();
1902 inline bool HasFixedArrayElements();
1903 inline bool HasFixedInt8Elements();
1904 inline bool HasFixedUint8Elements();
1905 inline bool HasFixedInt16Elements();
1906 inline bool HasFixedUint16Elements();
1907 inline bool HasFixedInt32Elements();
1908 inline bool HasFixedUint32Elements();
1909 inline bool HasFixedFloat32Elements();
1910 inline bool HasFixedFloat64Elements();
1912 inline bool HasFastArgumentsElements();
1913 inline bool HasSlowArgumentsElements();
1914 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1916 // Requires: HasFastElements().
1917 static Handle<FixedArray> EnsureWritableFastElements(
1918 Handle<JSObject> object);
1920 // Collects elements starting at index 0.
1921 // Undefined values are placed after non-undefined values.
1922 // Returns the number of non-undefined values.
1923 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1925 // As PrepareElementsForSort, but only on objects where elements is
1926 // a dictionary, and it will stay a dictionary. Collates undefined and
1927 // unexisting elements below limit from position zero of the elements.
1928 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1931 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1932 LookupIterator* it, Handle<Object> value);
1934 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1935 // grant an exemption to ExecutableAccessor callbacks in some cases.
1936 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1938 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1939 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1940 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1942 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1943 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1944 PropertyAttributes attributes,
1945 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1947 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1948 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1949 PropertyAttributes attributes,
1950 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1952 // Equivalent to one of the above depending on whether |name| can be converted
1953 // to an array index.
1954 MUST_USE_RESULT static MaybeHandle<Object>
1955 DefinePropertyOrElementIgnoreAttributes(
1956 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1957 PropertyAttributes attributes = NONE,
1958 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1960 // Adds or reconfigures a property to attributes NONE. It will fail when it
1962 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1963 Handle<Object> value);
1965 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1966 Handle<Object> value, PropertyAttributes attributes);
1968 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1969 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1970 PropertyAttributes attributes);
1972 // Extend the receiver with a single fast property appeared first in the
1973 // passed map. This also extends the property backing store if necessary.
1974 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1976 // Migrates the given object to a map whose field representations are the
1977 // lowest upper bound of all known representations for that field.
1978 static void MigrateInstance(Handle<JSObject> instance);
1980 // Migrates the given object only if the target map is already available,
1981 // or returns false if such a map is not yet available.
1982 static bool TryMigrateInstance(Handle<JSObject> instance);
1984 // Sets the property value in a normalized object given (key, value, details).
1985 // Handles the special representation of JS global objects.
1986 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1987 Handle<Object> value,
1988 PropertyDetails details);
1989 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1990 Handle<Object> value,
1991 PropertyAttributes attributes);
1992 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1994 Handle<Object> value,
1995 PropertyAttributes attributes);
1997 static void OptimizeAsPrototype(Handle<JSObject> object,
1998 PrototypeOptimizationMode mode);
1999 static void ReoptimizeIfPrototype(Handle<JSObject> object);
2000 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2001 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
2002 static void InvalidatePrototypeChains(Map* map);
2004 // Alternative implementation of WeakFixedArray::NullCallback.
2005 class PrototypeRegistryCompactionCallback {
2007 static void Callback(Object* value, int old_index, int new_index);
2010 // Retrieve interceptors.
2011 InterceptorInfo* GetNamedInterceptor();
2012 InterceptorInfo* GetIndexedInterceptor();
2014 // Used from JSReceiver.
2015 MUST_USE_RESULT static Maybe<PropertyAttributes>
2016 GetPropertyAttributesWithInterceptor(LookupIterator* it);
2017 MUST_USE_RESULT static Maybe<PropertyAttributes>
2018 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
2020 // Retrieves an AccessorPair property from the given object. Might return
2021 // undefined if the property doesn't exist or is of a different kind.
2022 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
2023 Handle<JSObject> object,
2025 AccessorComponent component);
2027 // Defines an AccessorPair property on the given object.
2028 // TODO(mstarzinger): Rename to SetAccessor().
2029 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
2031 Handle<Object> getter,
2032 Handle<Object> setter,
2033 PropertyAttributes attributes);
2035 // Defines an AccessorInfo property on the given object.
2036 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
2037 Handle<JSObject> object,
2038 Handle<AccessorInfo> info);
2040 // The result must be checked first for exceptions. If there's no exception,
2041 // the output parameter |done| indicates whether the interceptor has a result
2043 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
2044 LookupIterator* it, bool* done);
2046 // Accessors for hidden properties object.
2048 // Hidden properties are not own properties of the object itself.
2049 // Instead they are stored in an auxiliary structure kept as an own
2050 // property with a special name Heap::hidden_string(). But if the
2051 // receiver is a JSGlobalProxy then the auxiliary object is a property
2052 // of its prototype, and if it's a detached proxy, then you can't have
2053 // hidden properties.
2055 // Sets a hidden property on this object. Returns this object if successful,
2056 // undefined if called on a detached proxy.
2057 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
2059 Handle<Object> value);
2060 // Gets the value of a hidden property with the given key. Returns the hole
2061 // if the property doesn't exist (or if called on a detached proxy),
2062 // otherwise returns the value set for the key.
2063 Object* GetHiddenProperty(Handle<Name> key);
2064 // Deletes a hidden property. Deleting a non-existing property is
2065 // considered successful.
2066 static void DeleteHiddenProperty(Handle<JSObject> object,
2068 // Returns true if the object has a property with the hidden string as name.
2069 static bool HasHiddenProperties(Handle<JSObject> object);
2071 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
2073 static void ValidateElements(Handle<JSObject> object);
2075 // Makes sure that this object can contain HeapObject as elements.
2076 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
2078 // Makes sure that this object can contain the specified elements.
2079 static inline void EnsureCanContainElements(
2080 Handle<JSObject> object,
2083 EnsureElementsMode mode);
2084 static inline void EnsureCanContainElements(
2085 Handle<JSObject> object,
2086 Handle<FixedArrayBase> elements,
2088 EnsureElementsMode mode);
2089 static void EnsureCanContainElements(
2090 Handle<JSObject> object,
2091 Arguments* arguments,
2094 EnsureElementsMode mode);
2096 // Would we convert a fast elements array to dictionary mode given
2097 // an access at key?
2098 bool WouldConvertToSlowElements(uint32_t index);
2100 // Computes the new capacity when expanding the elements of a JSObject.
2101 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2102 // (old_capacity + 50%) + 16
2103 return old_capacity + (old_capacity >> 1) + 16;
2106 // These methods do not perform access checks!
2107 static void UpdateAllocationSite(Handle<JSObject> object,
2108 ElementsKind to_kind);
2110 // Lookup interceptors are used for handling properties controlled by host
2112 inline bool HasNamedInterceptor();
2113 inline bool HasIndexedInterceptor();
2115 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2116 // by JSReceiver::GetKeys.
2117 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2118 Handle<JSObject> object,
2119 Handle<JSReceiver> receiver);
2120 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2121 Handle<JSObject> object,
2122 Handle<JSReceiver> receiver);
2124 // Support functions for v8 api (needed for correct interceptor behavior).
2125 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2126 Handle<JSObject> object, Handle<Name> name);
2127 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2128 Handle<JSObject> object, uint32_t index);
2129 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2130 Handle<JSObject> object, Handle<Name> name);
2132 // Get the header size for a JSObject. Used to compute the index of
2133 // internal fields as well as the number of internal fields.
2134 inline int GetHeaderSize();
2136 inline int GetInternalFieldCount();
2137 inline int GetInternalFieldOffset(int index);
2138 inline Object* GetInternalField(int index);
2139 inline void SetInternalField(int index, Object* value);
2140 inline void SetInternalField(int index, Smi* value);
2142 // Returns the number of properties on this object filtering out properties
2143 // with the specified attributes (ignoring interceptors).
2144 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2145 // Fill in details for properties into storage starting at the specified
2146 // index. Returns the number of properties added.
2147 int GetOwnPropertyNames(FixedArray* storage, int index,
2148 PropertyAttributes filter = NONE);
2150 // Returns the number of properties on this object filtering out properties
2151 // with the specified attributes (ignoring interceptors).
2152 int NumberOfOwnElements(PropertyAttributes filter);
2153 // Returns the number of enumerable elements (ignoring interceptors).
2154 int NumberOfEnumElements();
2155 // Returns the number of elements on this object filtering out elements
2156 // with the specified attributes (ignoring interceptors).
2157 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2158 // Count and fill in the enumerable elements into storage.
2159 // (storage->length() == NumberOfEnumElements()).
2160 // If storage is NULL, will count the elements without adding
2161 // them to any storage.
2162 // Returns the number of enumerable elements.
2163 int GetEnumElementKeys(FixedArray* storage);
2165 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2168 // Returns a new map with all transitions dropped from the object's current
2169 // map and the ElementsKind set.
2170 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2171 ElementsKind to_kind);
2172 static void TransitionElementsKind(Handle<JSObject> object,
2173 ElementsKind to_kind);
2175 // Always use this to migrate an object to a new map.
2176 // |expected_additional_properties| is only used for fast-to-slow transitions
2177 // and ignored otherwise.
2178 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2179 int expected_additional_properties = 0);
2181 // Convert the object to use the canonical dictionary
2182 // representation. If the object is expected to have additional properties
2183 // added this number can be indicated to have the backing store allocated to
2184 // an initial capacity for holding these properties.
2185 static void NormalizeProperties(Handle<JSObject> object,
2186 PropertyNormalizationMode mode,
2187 int expected_additional_properties,
2188 const char* reason);
2190 // Convert and update the elements backing store to be a
2191 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2192 static Handle<SeededNumberDictionary> NormalizeElements(
2193 Handle<JSObject> object);
2195 void RequireSlowElements(SeededNumberDictionary* dictionary);
2197 // Transform slow named properties to fast variants.
2198 static void MigrateSlowToFast(Handle<JSObject> object,
2199 int unused_property_fields, const char* reason);
2201 inline bool IsUnboxedDoubleField(FieldIndex index);
2203 // Access fast-case object properties at index.
2204 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2205 Representation representation,
2207 inline Object* RawFastPropertyAt(FieldIndex index);
2208 inline double RawFastDoublePropertyAt(FieldIndex index);
2210 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2211 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2212 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2213 inline void WriteToField(int descriptor, Object* value);
2215 // Access to in object properties.
2216 inline int GetInObjectPropertyOffset(int index);
2217 inline Object* InObjectPropertyAt(int index);
2218 inline Object* InObjectPropertyAtPut(int index,
2220 WriteBarrierMode mode
2221 = UPDATE_WRITE_BARRIER);
2223 // Set the object's prototype (only JSReceiver and null are allowed values).
2224 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2225 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2227 // Initializes the body after properties slot, properties slot is
2228 // initialized by set_properties. Fill the pre-allocated fields with
2229 // pre_allocated_value and the rest with filler_value.
2230 // Note: this call does not update write barrier, the caller is responsible
2231 // to ensure that |filler_value| can be collected without WB here.
2232 inline void InitializeBody(Map* map,
2233 Object* pre_allocated_value,
2234 Object* filler_value);
2236 // Check whether this object references another object
2237 bool ReferencesObject(Object* obj);
2239 // Disalow further properties to be added to the oject.
2240 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2241 Handle<JSObject> object);
2243 bool IsExtensible();
2246 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2248 // ES5 Object.freeze
2249 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2251 // Called the first time an object is observed with ES7 Object.observe.
2252 static void SetObserved(Handle<JSObject> object);
2255 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2257 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2258 Handle<JSObject> object,
2259 AllocationSiteUsageContext* site_context,
2260 DeepCopyHints hints = kNoHints);
2261 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2262 Handle<JSObject> object,
2263 AllocationSiteCreationContext* site_context);
2265 DECLARE_CAST(JSObject)
2267 // Dispatched behavior.
2268 void JSObjectShortPrint(StringStream* accumulator);
2269 DECLARE_PRINTER(JSObject)
2270 DECLARE_VERIFIER(JSObject)
2272 void PrintProperties(std::ostream& os); // NOLINT
2273 void PrintElements(std::ostream& os); // NOLINT
2275 #if defined(DEBUG) || defined(OBJECT_PRINT)
2276 void PrintTransitions(std::ostream& os); // NOLINT
2279 static void PrintElementsTransition(
2280 FILE* file, Handle<JSObject> object,
2281 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2282 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2284 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2287 // Structure for collecting spill information about JSObjects.
2288 class SpillInformation {
2292 int number_of_objects_;
2293 int number_of_objects_with_fast_properties_;
2294 int number_of_objects_with_fast_elements_;
2295 int number_of_fast_used_fields_;
2296 int number_of_fast_unused_fields_;
2297 int number_of_slow_used_properties_;
2298 int number_of_slow_unused_properties_;
2299 int number_of_fast_used_elements_;
2300 int number_of_fast_unused_elements_;
2301 int number_of_slow_used_elements_;
2302 int number_of_slow_unused_elements_;
2305 void IncrementSpillStatistics(SpillInformation* info);
2309 // If a GC was caused while constructing this object, the elements pointer
2310 // may point to a one pointer filler map. The object won't be rooted, but
2311 // our heap verification code could stumble across it.
2312 bool ElementsAreSafeToExamine();
2315 Object* SlowReverseLookup(Object* value);
2317 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2318 // Also maximal value of JSArray's length property.
2319 static const uint32_t kMaxElementCount = 0xffffffffu;
2321 // Constants for heuristics controlling conversion of fast elements
2322 // to slow elements.
2324 // Maximal gap that can be introduced by adding an element beyond
2325 // the current elements length.
2326 static const uint32_t kMaxGap = 1024;
2328 // Maximal length of fast elements array that won't be checked for
2329 // being dense enough on expansion.
2330 static const int kMaxUncheckedFastElementsLength = 5000;
2332 // Same as above but for old arrays. This limit is more strict. We
2333 // don't want to be wasteful with long lived objects.
2334 static const int kMaxUncheckedOldFastElementsLength = 500;
2336 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2337 // permissible values (see the DCHECK in heap.cc).
2338 static const int kInitialMaxFastElementArray = 100000;
2340 // This constant applies only to the initial map of "global.Object" and
2341 // not to arbitrary other JSObject maps.
2342 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2344 static const int kMaxInstanceSize = 255 * kPointerSize;
2345 // When extending the backing storage for property values, we increase
2346 // its size by more than the 1 entry necessary, so sequentially adding fields
2347 // to the same object requires fewer allocations and copies.
2348 static const int kFieldsAdded = 3;
2350 // Layout description.
2351 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2352 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2353 static const int kHeaderSize = kElementsOffset + kPointerSize;
2355 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2357 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2359 static inline int SizeOf(Map* map, HeapObject* object);
2362 Context* GetCreationContext();
2364 // Enqueue change record for Object.observe. May cause GC.
2365 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2366 Handle<JSObject> object, const char* type, Handle<Name> name,
2367 Handle<Object> old_value);
2369 // Gets the number of currently used elements.
2370 int GetFastElementsUsage();
2372 // Deletes an existing named property in a normalized object.
2373 static void DeleteNormalizedProperty(Handle<JSObject> object,
2374 Handle<Name> name, int entry);
2376 static bool AllCanRead(LookupIterator* it);
2377 static bool AllCanWrite(LookupIterator* it);
2380 friend class JSReceiver;
2381 friend class Object;
2383 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2384 static void MigrateFastToSlow(Handle<JSObject> object,
2385 Handle<Map> new_map,
2386 int expected_additional_properties);
2388 // Used from Object::GetProperty().
2389 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2390 LookupIterator* it);
2392 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2393 LookupIterator* it, Handle<Object> value);
2395 // Add a property to a slow-case object.
2396 static void AddSlowProperty(Handle<JSObject> object,
2398 Handle<Object> value,
2399 PropertyAttributes attributes);
2401 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2402 LookupIterator* it);
2404 bool ReferencesObjectFromElements(FixedArray* elements,
2408 // Return the hash table backing store or the inline stored identity hash,
2409 // whatever is found.
2410 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2412 // Return the hash table backing store for hidden properties. If there is no
2413 // backing store, allocate one.
2414 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2415 Handle<JSObject> object);
2417 // Set the hidden property backing store to either a hash table or
2418 // the inline-stored identity hash.
2419 static Handle<Object> SetHiddenPropertiesHashTable(
2420 Handle<JSObject> object,
2421 Handle<Object> value);
2423 MUST_USE_RESULT Object* GetIdentityHash();
2425 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2427 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2428 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2430 // Helper for fast versions of preventExtensions, seal, and freeze.
2431 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2432 template <PropertyAttributes attrs>
2433 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2434 Handle<JSObject> object);
2436 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2440 // Common superclass for FixedArrays that allow implementations to share
2441 // common accessors and some code paths.
2442 class FixedArrayBase: public HeapObject {
2444 // [length]: length of the array.
2445 inline int length() const;
2446 inline void set_length(int value);
2448 // Get and set the length using acquire loads and release stores.
2449 inline int synchronized_length() const;
2450 inline void synchronized_set_length(int value);
2452 DECLARE_CAST(FixedArrayBase)
2454 // Layout description.
2455 // Length is smi tagged when it is stored.
2456 static const int kLengthOffset = HeapObject::kHeaderSize;
2457 static const int kHeaderSize = kLengthOffset + kPointerSize;
2461 class FixedDoubleArray;
2462 class IncrementalMarking;
2465 // FixedArray describes fixed-sized arrays with element type Object*.
2466 class FixedArray: public FixedArrayBase {
2468 // Setter and getter for elements.
2469 inline Object* get(int index) const;
2470 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2471 // Setter that uses write barrier.
2472 inline void set(int index, Object* value);
2473 inline bool is_the_hole(int index);
2475 // Setter that doesn't need write barrier.
2476 inline void set(int index, Smi* value);
2477 // Setter with explicit barrier mode.
2478 inline void set(int index, Object* value, WriteBarrierMode mode);
2480 // Setters for frequently used oddballs located in old space.
2481 inline void set_undefined(int index);
2482 inline void set_null(int index);
2483 inline void set_the_hole(int index);
2485 inline Object** GetFirstElementAddress();
2486 inline bool ContainsOnlySmisOrHoles();
2488 // Gives access to raw memory which stores the array's data.
2489 inline Object** data_start();
2491 inline void FillWithHoles(int from, int to);
2493 // Shrink length and insert filler objects.
2494 void Shrink(int length);
2496 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2498 // Copy a sub array from the receiver to dest.
2499 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2501 // Garbage collection support.
2502 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2504 // Code Generation support.
2505 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2507 // Garbage collection support.
2508 inline Object** RawFieldOfElementAt(int index);
2510 DECLARE_CAST(FixedArray)
2512 // Maximal allowed size, in bytes, of a single FixedArray.
2513 // Prevents overflowing size computations, as well as extreme memory
2515 static const int kMaxSize = 128 * MB * kPointerSize;
2516 // Maximally allowed length of a FixedArray.
2517 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2519 // Dispatched behavior.
2520 DECLARE_PRINTER(FixedArray)
2521 DECLARE_VERIFIER(FixedArray)
2523 // Checks if two FixedArrays have identical contents.
2524 bool IsEqualTo(FixedArray* other);
2527 // Swap two elements in a pair of arrays. If this array and the
2528 // numbers array are the same object, the elements are only swapped
2530 void SwapPairs(FixedArray* numbers, int i, int j);
2532 // Sort prefix of this array and the numbers array as pairs wrt. the
2533 // numbers. If the numbers array and the this array are the same
2534 // object, the prefix of this array is sorted.
2535 void SortPairs(FixedArray* numbers, uint32_t len);
2537 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2539 static inline int SizeOf(Map* map, HeapObject* object);
2543 // Set operation on FixedArray without using write barriers. Can
2544 // only be used for storing old space objects or smis.
2545 static inline void NoWriteBarrierSet(FixedArray* array,
2549 // Set operation on FixedArray without incremental write barrier. Can
2550 // only be used if the object is guaranteed to be white (whiteness witness
2552 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2557 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2559 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2563 // FixedDoubleArray describes fixed-sized arrays with element type double.
2564 class FixedDoubleArray: public FixedArrayBase {
2566 // Setter and getter for elements.
2567 inline double get_scalar(int index);
2568 inline uint64_t get_representation(int index);
2569 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2570 inline void set(int index, double value);
2571 inline void set_the_hole(int index);
2573 // Checking for the hole.
2574 inline bool is_the_hole(int index);
2576 // Garbage collection support.
2577 inline static int SizeFor(int length) {
2578 return kHeaderSize + length * kDoubleSize;
2581 // Gives access to raw memory which stores the array's data.
2582 inline double* data_start();
2584 inline void FillWithHoles(int from, int to);
2586 // Code Generation support.
2587 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2589 DECLARE_CAST(FixedDoubleArray)
2591 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2592 // Prevents overflowing size computations, as well as extreme memory
2594 static const int kMaxSize = 512 * MB;
2595 // Maximally allowed length of a FixedArray.
2596 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2598 // Dispatched behavior.
2599 DECLARE_PRINTER(FixedDoubleArray)
2600 DECLARE_VERIFIER(FixedDoubleArray)
2603 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2607 class WeakFixedArray : public FixedArray {
2609 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2610 // This function does not check if the value exists already, callers must
2611 // ensure this themselves if necessary.
2612 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2613 Handle<HeapObject> value,
2614 int* assigned_index = NULL);
2616 // Returns true if an entry was found and removed.
2617 bool Remove(Handle<HeapObject> value);
2619 class NullCallback {
2621 static void Callback(Object* value, int old_index, int new_index) {}
2624 template <class CompactionCallback>
2627 inline Object* Get(int index) const;
2628 inline void Clear(int index);
2629 inline int Length() const;
2631 inline bool IsEmptySlot(int index) const;
2632 static Object* Empty() { return Smi::FromInt(0); }
2636 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2637 void Reset(Object* maybe_array);
2644 WeakFixedArray* list_;
2646 int last_used_index_;
2647 DisallowHeapAllocation no_gc_;
2649 DISALLOW_COPY_AND_ASSIGN(Iterator);
2652 DECLARE_CAST(WeakFixedArray)
2655 static const int kLastUsedIndexIndex = 0;
2656 static const int kFirstIndex = 1;
2658 static Handle<WeakFixedArray> Allocate(
2659 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2661 static void Set(Handle<WeakFixedArray> array, int index,
2662 Handle<HeapObject> value);
2663 inline void clear(int index);
2665 inline int last_used_index() const;
2666 inline void set_last_used_index(int index);
2668 // Disallow inherited setters.
2669 void set(int index, Smi* value);
2670 void set(int index, Object* value);
2671 void set(int index, Object* value, WriteBarrierMode mode);
2672 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2676 // Generic array grows dynamically with O(1) amortized insertion.
2677 class ArrayList : public FixedArray {
2681 // Use this if GC can delete elements from the array.
2682 kReloadLengthAfterAllocation,
2684 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2685 AddMode mode = kNone);
2686 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2687 Handle<Object> obj2, AddMode = kNone);
2688 inline int Length();
2689 inline void SetLength(int length);
2690 inline Object* Get(int index);
2691 inline Object** Slot(int index);
2692 inline void Set(int index, Object* obj);
2693 inline void Clear(int index, Object* undefined);
2694 DECLARE_CAST(ArrayList)
2697 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2698 static const int kLengthIndex = 0;
2699 static const int kFirstIndex = 1;
2700 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2704 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2705 // The format of the these objects is:
2706 // [0]: Number of descriptors
2707 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2708 // [0]: pointer to fixed array with enum cache
2709 // [1]: either Smi(0) or pointer to fixed array with indices
2711 // [2 + number of descriptors * kDescriptorSize]: start of slack
2712 class DescriptorArray: public FixedArray {
2714 // Returns true for both shared empty_descriptor_array and for smis, which the
2715 // map uses to encode additional bit fields when the descriptor array is not
2717 inline bool IsEmpty();
2719 // Returns the number of descriptors in the array.
2720 inline int number_of_descriptors();
2722 inline int number_of_descriptors_storage();
2724 inline int NumberOfSlackDescriptors();
2726 inline void SetNumberOfDescriptors(int number_of_descriptors);
2727 inline int number_of_entries();
2729 inline bool HasEnumCache();
2731 inline void CopyEnumCacheFrom(DescriptorArray* array);
2733 inline FixedArray* GetEnumCache();
2735 inline bool HasEnumIndicesCache();
2737 inline FixedArray* GetEnumIndicesCache();
2739 inline Object** GetEnumCacheSlot();
2741 void ClearEnumCache();
2743 // Initialize or change the enum cache,
2744 // using the supplied storage for the small "bridge".
2745 void SetEnumCache(FixedArray* bridge_storage,
2746 FixedArray* new_cache,
2747 Object* new_index_cache);
2749 bool CanHoldValue(int descriptor, Object* value);
2751 // Accessors for fetching instance descriptor at descriptor number.
2752 inline Name* GetKey(int descriptor_number);
2753 inline Object** GetKeySlot(int descriptor_number);
2754 inline Object* GetValue(int descriptor_number);
2755 inline void SetValue(int descriptor_number, Object* value);
2756 inline Object** GetValueSlot(int descriptor_number);
2757 static inline int GetValueOffset(int descriptor_number);
2758 inline Object** GetDescriptorStartSlot(int descriptor_number);
2759 inline Object** GetDescriptorEndSlot(int descriptor_number);
2760 inline PropertyDetails GetDetails(int descriptor_number);
2761 inline PropertyType GetType(int descriptor_number);
2762 inline int GetFieldIndex(int descriptor_number);
2763 inline HeapType* GetFieldType(int descriptor_number);
2764 inline Object* GetConstant(int descriptor_number);
2765 inline Object* GetCallbacksObject(int descriptor_number);
2766 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2768 inline Name* GetSortedKey(int descriptor_number);
2769 inline int GetSortedKeyIndex(int descriptor_number);
2770 inline void SetSortedKey(int pointer, int descriptor_number);
2771 inline void SetRepresentation(int descriptor_number,
2772 Representation representation);
2774 // Accessor for complete descriptor.
2775 inline void Get(int descriptor_number, Descriptor* desc);
2776 inline void Set(int descriptor_number, Descriptor* desc);
2777 void Replace(int descriptor_number, Descriptor* descriptor);
2779 // Append automatically sets the enumeration index. This should only be used
2780 // to add descriptors in bulk at the end, followed by sorting the descriptor
2782 inline void Append(Descriptor* desc);
2784 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2785 int enumeration_index,
2788 static Handle<DescriptorArray> CopyUpToAddAttributes(
2789 Handle<DescriptorArray> desc,
2790 int enumeration_index,
2791 PropertyAttributes attributes,
2794 // Sort the instance descriptors by the hash codes of their keys.
2797 // Search the instance descriptors for given name.
2798 INLINE(int Search(Name* name, int number_of_own_descriptors));
2800 // As the above, but uses DescriptorLookupCache and updates it when
2802 INLINE(int SearchWithCache(Name* name, Map* map));
2804 // Allocates a DescriptorArray, but returns the singleton
2805 // empty descriptor array object if number_of_descriptors is 0.
2806 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2807 int number_of_descriptors,
2810 DECLARE_CAST(DescriptorArray)
2812 // Constant for denoting key was not found.
2813 static const int kNotFound = -1;
2815 static const int kDescriptorLengthIndex = 0;
2816 static const int kEnumCacheIndex = 1;
2817 static const int kFirstIndex = 2;
2819 // The length of the "bridge" to the enum cache.
2820 static const int kEnumCacheBridgeLength = 2;
2821 static const int kEnumCacheBridgeCacheIndex = 0;
2822 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2824 // Layout description.
2825 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2826 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2827 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2829 // Layout description for the bridge array.
2830 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2832 // Layout of descriptor.
2833 static const int kDescriptorKey = 0;
2834 static const int kDescriptorDetails = 1;
2835 static const int kDescriptorValue = 2;
2836 static const int kDescriptorSize = 3;
2838 #if defined(DEBUG) || defined(OBJECT_PRINT)
2839 // For our gdb macros, we should perhaps change these in the future.
2842 // Print all the descriptors.
2843 void PrintDescriptors(std::ostream& os); // NOLINT
2847 // Is the descriptor array sorted and without duplicates?
2848 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2850 // Is the descriptor array consistent with the back pointers in targets?
2851 bool IsConsistentWithBackPointers(Map* current_map);
2853 // Are two DescriptorArrays equal?
2854 bool IsEqualTo(DescriptorArray* other);
2857 // Returns the fixed array length required to hold number_of_descriptors
2859 static int LengthFor(int number_of_descriptors) {
2860 return ToKeyIndex(number_of_descriptors);
2864 // WhitenessWitness is used to prove that a descriptor array is white
2865 // (unmarked), so incremental write barriers can be skipped because the
2866 // marking invariant cannot be broken and slots pointing into evacuation
2867 // candidates will be discovered when the object is scanned. A witness is
2868 // always stack-allocated right after creating an array. By allocating a
2869 // witness, incremental marking is globally disabled. The witness is then
2870 // passed along wherever needed to statically prove that the array is known to
2872 class WhitenessWitness {
2874 inline explicit WhitenessWitness(DescriptorArray* array);
2875 inline ~WhitenessWitness();
2878 IncrementalMarking* marking_;
2881 // An entry in a DescriptorArray, represented as an (array, index) pair.
2884 inline explicit Entry(DescriptorArray* descs, int index) :
2885 descs_(descs), index_(index) { }
2887 inline PropertyType type();
2888 inline Object* GetCallbackObject();
2891 DescriptorArray* descs_;
2895 // Conversion from descriptor number to array indices.
2896 static int ToKeyIndex(int descriptor_number) {
2897 return kFirstIndex +
2898 (descriptor_number * kDescriptorSize) +
2902 static int ToDetailsIndex(int descriptor_number) {
2903 return kFirstIndex +
2904 (descriptor_number * kDescriptorSize) +
2908 static int ToValueIndex(int descriptor_number) {
2909 return kFirstIndex +
2910 (descriptor_number * kDescriptorSize) +
2914 // Transfer a complete descriptor from the src descriptor array to this
2915 // descriptor array.
2916 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2918 inline void Set(int descriptor_number,
2920 const WhitenessWitness&);
2922 // Swap first and second descriptor.
2923 inline void SwapSortedKeys(int first, int second);
2925 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2929 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2931 template <SearchMode search_mode, typename T>
2932 inline int Search(T* array, Name* name, int valid_entries = 0,
2933 int* out_insertion_index = NULL);
2936 // HashTable is a subclass of FixedArray that implements a hash table
2937 // that uses open addressing and quadratic probing.
2939 // In order for the quadratic probing to work, elements that have not
2940 // yet been used and elements that have been deleted are
2941 // distinguished. Probing continues when deleted elements are
2942 // encountered and stops when unused elements are encountered.
2944 // - Elements with key == undefined have not been used yet.
2945 // - Elements with key == the_hole have been deleted.
2947 // The hash table class is parameterized with a Shape and a Key.
2948 // Shape must be a class with the following interface:
2949 // class ExampleShape {
2951 // // Tells whether key matches other.
2952 // static bool IsMatch(Key key, Object* other);
2953 // // Returns the hash value for key.
2954 // static uint32_t Hash(Key key);
2955 // // Returns the hash value for object.
2956 // static uint32_t HashForObject(Key key, Object* object);
2957 // // Convert key to an object.
2958 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2959 // // The prefix size indicates number of elements in the beginning
2960 // // of the backing storage.
2961 // static const int kPrefixSize = ..;
2962 // // The Element size indicates number of elements per entry.
2963 // static const int kEntrySize = ..;
2965 // The prefix size indicates an amount of memory in the
2966 // beginning of the backing storage that can be used for non-element
2967 // information by subclasses.
2969 template<typename Key>
2972 static const bool UsesSeed = false;
2973 static uint32_t Hash(Key key) { return 0; }
2974 static uint32_t SeededHash(Key key, uint32_t seed) {
2978 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2979 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2981 return HashForObject(key, object);
2986 class HashTableBase : public FixedArray {
2988 // Returns the number of elements in the hash table.
2989 inline int NumberOfElements();
2991 // Returns the number of deleted elements in the hash table.
2992 inline int NumberOfDeletedElements();
2994 // Returns the capacity of the hash table.
2995 inline int Capacity();
2997 // ElementAdded should be called whenever an element is added to a
2999 inline void ElementAdded();
3001 // ElementRemoved should be called whenever an element is removed from
3003 inline void ElementRemoved();
3004 inline void ElementsRemoved(int n);
3006 // Computes the required capacity for a table holding the given
3007 // number of elements. May be more than HashTable::kMaxCapacity.
3008 static inline int ComputeCapacity(int at_least_space_for);
3010 // Tells whether k is a real key. The hole and undefined are not allowed
3011 // as keys and can be used to indicate missing or deleted elements.
3012 inline bool IsKey(Object* k);
3014 // Compute the probe offset (quadratic probing).
3015 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3016 return (n + n * n) >> 1;
3019 static const int kNumberOfElementsIndex = 0;
3020 static const int kNumberOfDeletedElementsIndex = 1;
3021 static const int kCapacityIndex = 2;
3022 static const int kPrefixStartIndex = 3;
3024 // Constant used for denoting a absent entry.
3025 static const int kNotFound = -1;
3028 // Update the number of elements in the hash table.
3029 inline void SetNumberOfElements(int nof);
3031 // Update the number of deleted elements in the hash table.
3032 inline void SetNumberOfDeletedElements(int nod);
3034 // Returns probe entry.
3035 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3036 DCHECK(base::bits::IsPowerOfTwo32(size));
3037 return (hash + GetProbeOffset(number)) & (size - 1);
3040 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3041 return hash & (size - 1);
3044 inline static uint32_t NextProbe(
3045 uint32_t last, uint32_t number, uint32_t size) {
3046 return (last + number) & (size - 1);
3051 template <typename Derived, typename Shape, typename Key>
3052 class HashTable : public HashTableBase {
3055 inline uint32_t Hash(Key key) {
3056 if (Shape::UsesSeed) {
3057 return Shape::SeededHash(key, GetHeap()->HashSeed());
3059 return Shape::Hash(key);
3063 inline uint32_t HashForObject(Key key, Object* object) {
3064 if (Shape::UsesSeed) {
3065 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3067 return Shape::HashForObject(key, object);
3071 // Returns a new HashTable object.
3072 MUST_USE_RESULT static Handle<Derived> New(
3073 Isolate* isolate, int at_least_space_for,
3074 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3075 PretenureFlag pretenure = NOT_TENURED);
3077 DECLARE_CAST(HashTable)
3079 // Garbage collection support.
3080 void IteratePrefix(ObjectVisitor* visitor);
3081 void IterateElements(ObjectVisitor* visitor);
3083 // Find entry for key otherwise return kNotFound.
3084 inline int FindEntry(Key key);
3085 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3086 int FindEntry(Isolate* isolate, Key key);
3088 // Rehashes the table in-place.
3089 void Rehash(Key key);
3091 // Returns the key at entry.
3092 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3094 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3095 static const int kEntrySize = Shape::kEntrySize;
3096 static const int kElementsStartOffset =
3097 kHeaderSize + kElementsStartIndex * kPointerSize;
3098 static const int kCapacityOffset =
3099 kHeaderSize + kCapacityIndex * kPointerSize;
3101 // Returns the index for an entry (of the key)
3102 static inline int EntryToIndex(int entry) {
3103 return (entry * kEntrySize) + kElementsStartIndex;
3107 friend class ObjectHashTable;
3109 // Find the entry at which to insert element with the given key that
3110 // has the given hash value.
3111 uint32_t FindInsertionEntry(uint32_t hash);
3113 // Attempt to shrink hash table after removal of key.
3114 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3116 // Ensure enough space for n additional elements.
3117 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3118 Handle<Derived> table,
3121 PretenureFlag pretenure = NOT_TENURED);
3123 // Sets the capacity of the hash table.
3124 void SetCapacity(int capacity) {
3125 // To scale a computed hash code to fit within the hash table, we
3126 // use bit-wise AND with a mask, so the capacity must be positive
3128 DCHECK(capacity > 0);
3129 DCHECK(capacity <= kMaxCapacity);
3130 set(kCapacityIndex, Smi::FromInt(capacity));
3133 // Maximal capacity of HashTable. Based on maximal length of underlying
3134 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3136 static const int kMaxCapacity =
3137 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3140 // Returns _expected_ if one of entries given by the first _probe_ probes is
3141 // equal to _expected_. Otherwise, returns the entry given by the probe
3143 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3145 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3147 // Rehashes this hash-table into the new table.
3148 void Rehash(Handle<Derived> new_table, Key key);
3152 // HashTableKey is an abstract superclass for virtual key behavior.
3153 class HashTableKey {
3155 // Returns whether the other object matches this key.
3156 virtual bool IsMatch(Object* other) = 0;
3157 // Returns the hash value for this key.
3158 virtual uint32_t Hash() = 0;
3159 // Returns the hash value for object.
3160 virtual uint32_t HashForObject(Object* key) = 0;
3161 // Returns the key object for storing into the hash table.
3162 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3164 virtual ~HashTableKey() {}
3168 class StringTableShape : public BaseShape<HashTableKey*> {
3170 static inline bool IsMatch(HashTableKey* key, Object* value) {
3171 return key->IsMatch(value);
3174 static inline uint32_t Hash(HashTableKey* key) {
3178 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3179 return key->HashForObject(object);
3182 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3184 static const int kPrefixSize = 0;
3185 static const int kEntrySize = 1;
3188 class SeqOneByteString;
3192 // No special elements in the prefix and the element size is 1
3193 // because only the string itself (the key) needs to be stored.
3194 class StringTable: public HashTable<StringTable,
3198 // Find string in the string table. If it is not there yet, it is
3199 // added. The return value is the string found.
3200 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3201 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3202 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3204 // Tries to internalize given string and returns string handle on success
3205 // or an empty handle otherwise.
3206 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3208 Handle<String> string);
3210 // Looks up a string that is equal to the given string and returns
3211 // string handle if it is found, or an empty handle otherwise.
3212 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3214 Handle<String> str);
3215 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3220 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3222 DECLARE_CAST(StringTable)
3225 template <bool seq_one_byte>
3226 friend class JsonParser;
3228 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3232 template <typename Derived, typename Shape, typename Key>
3233 class Dictionary: public HashTable<Derived, Shape, Key> {
3234 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3237 // Returns the value at entry.
3238 Object* ValueAt(int entry) {
3239 return this->get(Derived::EntryToIndex(entry) + 1);
3242 // Set the value for entry.
3243 void ValueAtPut(int entry, Object* value) {
3244 this->set(Derived::EntryToIndex(entry) + 1, value);
3247 // Returns the property details for the property at entry.
3248 PropertyDetails DetailsAt(int entry) {
3249 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3252 // Set the details for entry.
3253 void DetailsAtPut(int entry, PropertyDetails value) {
3254 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3257 // Returns true if property at given entry is deleted.
3258 bool IsDeleted(int entry) {
3259 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3262 // Delete a property from the dictionary.
3263 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3265 // Attempt to shrink the dictionary after deletion of key.
3266 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3267 Handle<Derived> dictionary,
3269 return DerivedHashTable::Shrink(dictionary, key);
3273 // TODO(dcarney): templatize or move to SeededNumberDictionary
3274 void CopyValuesTo(FixedArray* elements);
3276 // Returns the number of elements in the dictionary filtering out properties
3277 // with the specified attributes.
3278 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3280 // Returns the number of enumerable elements in the dictionary.
3281 int NumberOfEnumElements() {
3282 return NumberOfElementsFilterAttributes(
3283 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3286 // Returns true if the dictionary contains any elements that are non-writable,
3287 // non-configurable, non-enumerable, or have getters/setters.
3288 bool HasComplexElements();
3290 enum SortMode { UNSORTED, SORTED };
3292 // Fill in details for properties into storage.
3293 // Returns the number of properties added.
3294 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3295 SortMode sort_mode);
3297 // Copies enumerable keys to preallocated fixed array.
3298 void CopyEnumKeysTo(FixedArray* storage);
3300 // Accessors for next enumeration index.
3301 void SetNextEnumerationIndex(int index) {
3303 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3306 int NextEnumerationIndex() {
3307 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3310 // Creates a new dictionary.
3311 MUST_USE_RESULT static Handle<Derived> New(
3313 int at_least_space_for,
3314 PretenureFlag pretenure = NOT_TENURED);
3316 // Ensure enough space for n additional elements.
3317 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3320 void Print(std::ostream& os); // NOLINT
3322 // Returns the key (slow).
3323 Object* SlowReverseLookup(Object* value);
3325 // Sets the entry to (key, value) pair.
3326 inline void SetEntry(int entry,
3328 Handle<Object> value);
3329 inline void SetEntry(int entry,
3331 Handle<Object> value,
3332 PropertyDetails details);
3334 MUST_USE_RESULT static Handle<Derived> Add(
3335 Handle<Derived> dictionary,
3337 Handle<Object> value,
3338 PropertyDetails details);
3340 // Returns iteration indices array for the |dictionary|.
3341 // Values are direct indices in the |HashTable| array.
3342 static Handle<FixedArray> BuildIterationIndicesArray(
3343 Handle<Derived> dictionary);
3346 // Generic at put operation.
3347 MUST_USE_RESULT static Handle<Derived> AtPut(
3348 Handle<Derived> dictionary,
3350 Handle<Object> value);
3352 // Add entry to dictionary.
3353 static void AddEntry(
3354 Handle<Derived> dictionary,
3356 Handle<Object> value,
3357 PropertyDetails details,
3360 // Generate new enumeration indices to avoid enumeration index overflow.
3361 // Returns iteration indices array for the |dictionary|.
3362 static Handle<FixedArray> GenerateNewEnumerationIndices(
3363 Handle<Derived> dictionary);
3364 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3365 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3369 template <typename Derived, typename Shape>
3370 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3371 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3374 // Find entry for key, otherwise return kNotFound. Optimized version of
3375 // HashTable::FindEntry.
3376 int FindEntry(Handle<Name> key);
3380 template <typename Key>
3381 class BaseDictionaryShape : public BaseShape<Key> {
3383 template <typename Dictionary>
3384 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3385 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3386 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3387 return PropertyDetails(
3388 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3391 template <typename Dictionary>
3392 static inline void DetailsAtPut(Dictionary* dict, int entry,
3393 PropertyDetails value) {
3394 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3395 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3398 template <typename Dictionary>
3399 static bool IsDeleted(Dictionary* dict, int entry) {
3403 template <typename Dictionary>
3404 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3405 Handle<Object> value, PropertyDetails details);
3409 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3411 static inline bool IsMatch(Handle<Name> key, Object* other);
3412 static inline uint32_t Hash(Handle<Name> key);
3413 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3414 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3415 static const int kPrefixSize = 2;
3416 static const int kEntrySize = 3;
3417 static const bool kIsEnumerable = true;
3421 class NameDictionary
3422 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3423 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3427 DECLARE_CAST(NameDictionary)
3429 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3430 Handle<NameDictionary> dictionary);
3434 class GlobalDictionaryShape : public NameDictionaryShape {
3436 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3438 template <typename Dictionary>
3439 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3441 template <typename Dictionary>
3442 static inline void DetailsAtPut(Dictionary* dict, int entry,
3443 PropertyDetails value);
3445 template <typename Dictionary>
3446 static bool IsDeleted(Dictionary* dict, int entry);
3448 template <typename Dictionary>
3449 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3450 Handle<Object> value, PropertyDetails details);
3454 class GlobalDictionary
3455 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3457 DECLARE_CAST(GlobalDictionary)
3461 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3463 static inline bool IsMatch(uint32_t key, Object* other);
3464 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3465 static const int kEntrySize = 3;
3466 static const bool kIsEnumerable = false;
3470 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3472 static const bool UsesSeed = true;
3473 static const int kPrefixSize = 2;
3475 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3476 static inline uint32_t SeededHashForObject(uint32_t key,
3482 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3484 static const int kPrefixSize = 0;
3486 static inline uint32_t Hash(uint32_t key);
3487 static inline uint32_t HashForObject(uint32_t key, Object* object);
3491 class SeededNumberDictionary
3492 : public Dictionary<SeededNumberDictionary,
3493 SeededNumberDictionaryShape,
3496 DECLARE_CAST(SeededNumberDictionary)
3498 // Type specific at put (default NONE attributes is used when adding).
3499 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3500 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3501 Handle<Object> value, bool used_as_prototype);
3502 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3503 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3504 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3506 // Set an existing entry or add a new one if needed.
3507 // Return the updated dictionary.
3508 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3509 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3510 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3512 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3514 // If slow elements are required we will never go back to fast-case
3515 // for the elements kept in this dictionary. We require slow
3516 // elements if an element has been added at an index larger than
3517 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3518 // when defining a getter or setter with a number key.
3519 inline bool requires_slow_elements();
3520 inline void set_requires_slow_elements();
3522 // Get the value of the max number key that has been added to this
3523 // dictionary. max_number_key can only be called if
3524 // requires_slow_elements returns false.
3525 inline uint32_t max_number_key();
3528 static const int kRequiresSlowElementsMask = 1;
3529 static const int kRequiresSlowElementsTagSize = 1;
3530 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3534 class UnseededNumberDictionary
3535 : public Dictionary<UnseededNumberDictionary,
3536 UnseededNumberDictionaryShape,
3539 DECLARE_CAST(UnseededNumberDictionary)
3541 // Type specific at put (default NONE attributes is used when adding).
3542 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3543 Handle<UnseededNumberDictionary> dictionary,
3545 Handle<Object> value);
3546 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3547 Handle<UnseededNumberDictionary> dictionary,
3549 Handle<Object> value);
3551 // Set an existing entry or add a new one if needed.
3552 // Return the updated dictionary.
3553 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3554 Handle<UnseededNumberDictionary> dictionary,
3556 Handle<Object> value);
3560 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3562 static inline bool IsMatch(Handle<Object> key, Object* other);
3563 static inline uint32_t Hash(Handle<Object> key);
3564 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3565 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3566 static const int kPrefixSize = 0;
3567 static const int kEntrySize = 2;
3571 // ObjectHashTable maps keys that are arbitrary objects to object values by
3572 // using the identity hash of the key for hashing purposes.
3573 class ObjectHashTable: public HashTable<ObjectHashTable,
3574 ObjectHashTableShape,
3577 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3579 DECLARE_CAST(ObjectHashTable)
3581 // Attempt to shrink hash table after removal of key.
3582 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3583 Handle<ObjectHashTable> table,
3584 Handle<Object> key);
3586 // Looks up the value associated with the given key. The hole value is
3587 // returned in case the key is not present.
3588 Object* Lookup(Handle<Object> key);
3589 Object* Lookup(Handle<Object> key, int32_t hash);
3590 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3592 // Adds (or overwrites) the value associated with the given key.
3593 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3595 Handle<Object> value);
3596 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3597 Handle<Object> key, Handle<Object> value,
3600 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3601 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3604 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3605 Handle<Object> key, bool* was_present,
3609 friend class MarkCompactCollector;
3611 void AddEntry(int entry, Object* key, Object* value);
3612 void RemoveEntry(int entry);
3614 // Returns the index to the value of an entry.
3615 static inline int EntryToValueIndex(int entry) {
3616 return EntryToIndex(entry) + 1;
3621 // OrderedHashTable is a HashTable with Object keys that preserves
3622 // insertion order. There are Map and Set interfaces (OrderedHashMap
3623 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3625 // Only Object* keys are supported, with Object::SameValueZero() used as the
3626 // equality operator and Object::GetHash() for the hash function.
3628 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3629 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3630 // Originally attributed to Tyler Close.
3633 // [0]: bucket count
3634 // [1]: element count
3635 // [2]: deleted element count
3636 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3637 // offset into the data table (see below) where the
3638 // first item in this bucket is stored.
3639 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3640 // Capacity() * kEntrySize, where the first entrysize
3641 // items are handled by the derived class and the
3642 // item at kChainOffset is another entry into the
3643 // data table indicating the next entry in this hash
3646 // When we transition the table to a new version we obsolete it and reuse parts
3647 // of the memory to store information how to transition an iterator to the new
3650 // Memory layout for obsolete table:
3651 // [0]: bucket count
3652 // [1]: Next newer table
3653 // [2]: Number of removed holes or -1 when the table was cleared.
3654 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3655 // [3 + NumberOfRemovedHoles()..length]: Not used
3657 template<class Derived, class Iterator, int entrysize>
3658 class OrderedHashTable: public FixedArray {
3660 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3661 static Handle<Derived> Allocate(
3662 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3664 // Returns an OrderedHashTable (possibly |table|) with enough space
3665 // to add at least one new element.
3666 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3668 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3670 static Handle<Derived> Shrink(Handle<Derived> table);
3672 // Returns a new empty OrderedHashTable and records the clearing so that
3673 // exisiting iterators can be updated.
3674 static Handle<Derived> Clear(Handle<Derived> table);
3676 // Returns a true if the OrderedHashTable contains the key
3677 static bool HasKey(Handle<Derived> table, Handle<Object> key);
3679 int NumberOfElements() {
3680 return Smi::cast(get(kNumberOfElementsIndex))->value();
3683 int NumberOfDeletedElements() {
3684 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3687 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3689 int NumberOfBuckets() {
3690 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3693 // Returns an index into |this| for the given entry.
3694 int EntryToIndex(int entry) {
3695 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3698 int HashToBucket(int hash) { return hash & (NumberOfBuckets() - 1); }
3700 int HashToEntry(int hash) {
3701 int bucket = HashToBucket(hash);
3702 Object* entry = this->get(kHashTableStartIndex + bucket);
3703 return Smi::cast(entry)->value();
3706 int KeyToFirstEntry(Object* key) {
3707 Object* hash = key->GetHash();
3708 // If the object does not have an identity hash, it was never used as a key
3709 if (hash->IsUndefined()) return kNotFound;
3710 return HashToEntry(Smi::cast(hash)->value());
3713 int NextChainEntry(int entry) {
3714 Object* next_entry = get(EntryToIndex(entry) + kChainOffset);
3715 return Smi::cast(next_entry)->value();
3718 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3721 return !get(kNextTableIndex)->IsSmi();
3724 // The next newer table. This is only valid if the table is obsolete.
3725 Derived* NextTable() {
3726 return Derived::cast(get(kNextTableIndex));
3729 // When the table is obsolete we store the indexes of the removed holes.
3730 int RemovedIndexAt(int index) {
3731 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3734 static const int kNotFound = -1;
3735 static const int kMinCapacity = 4;
3737 static const int kNumberOfBucketsIndex = 0;
3738 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3739 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3740 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3741 static const int kNextTableIndex = kNumberOfElementsIndex;
3743 static const int kNumberOfBucketsOffset =
3744 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3745 static const int kNumberOfElementsOffset =
3746 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3747 static const int kNumberOfDeletedElementsOffset =
3748 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3749 static const int kHashTableStartOffset =
3750 kHeaderSize + kHashTableStartIndex * kPointerSize;
3751 static const int kNextTableOffset =
3752 kHeaderSize + kNextTableIndex * kPointerSize;
3754 static const int kEntrySize = entrysize + 1;
3755 static const int kChainOffset = entrysize;
3757 static const int kLoadFactor = 2;
3759 // NumberOfDeletedElements is set to kClearedTableSentinel when
3760 // the table is cleared, which allows iterator transitions to
3761 // optimize that case.
3762 static const int kClearedTableSentinel = -1;
3765 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3767 void SetNumberOfBuckets(int num) {
3768 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3771 void SetNumberOfElements(int num) {
3772 set(kNumberOfElementsIndex, Smi::FromInt(num));
3775 void SetNumberOfDeletedElements(int num) {
3776 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3780 return NumberOfBuckets() * kLoadFactor;
3783 void SetNextTable(Derived* next_table) {
3784 set(kNextTableIndex, next_table);
3787 void SetRemovedIndexAt(int index, int removed_index) {
3788 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3791 static const int kRemovedHolesIndex = kHashTableStartIndex;
3793 static const int kMaxCapacity =
3794 (FixedArray::kMaxLength - kHashTableStartIndex)
3795 / (1 + (kEntrySize * kLoadFactor));
3799 class JSSetIterator;
3802 class OrderedHashSet: public OrderedHashTable<
3803 OrderedHashSet, JSSetIterator, 1> {
3805 DECLARE_CAST(OrderedHashSet)
3807 static Handle<OrderedHashSet> Add(Handle<OrderedHashSet> table,
3808 Handle<Object> value);
3812 class JSMapIterator;
3815 class OrderedHashMap
3816 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3818 DECLARE_CAST(OrderedHashMap)
3820 inline Object* ValueAt(int entry);
3822 static const int kValueOffset = 1;
3826 template <int entrysize>
3827 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3829 static inline bool IsMatch(Handle<Object> key, Object* other);
3830 static inline uint32_t Hash(Handle<Object> key);
3831 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3832 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3833 static const int kPrefixSize = 0;
3834 static const int kEntrySize = entrysize;
3838 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3839 // values. The table wraps the keys in weak cells and store values directly.
3840 // Thus it references keys weakly and values strongly.
3841 class WeakHashTable: public HashTable<WeakHashTable,
3842 WeakHashTableShape<2>,
3845 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3847 DECLARE_CAST(WeakHashTable)
3849 // Looks up the value associated with the given key. The hole value is
3850 // returned in case the key is not present.
3851 Object* Lookup(Handle<HeapObject> key);
3853 // Adds (or overwrites) the value associated with the given key. Mapping a
3854 // key to the hole value causes removal of the whole entry.
3855 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3856 Handle<HeapObject> key,
3857 Handle<HeapObject> value);
3859 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3862 friend class MarkCompactCollector;
3864 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3866 // Returns the index to the value of an entry.
3867 static inline int EntryToValueIndex(int entry) {
3868 return EntryToIndex(entry) + 1;
3873 // ScopeInfo represents information about different scopes of a source
3874 // program and the allocation of the scope's variables. Scope information
3875 // is stored in a compressed form in ScopeInfo objects and is used
3876 // at runtime (stack dumps, deoptimization, etc.).
3878 // This object provides quick access to scope info details for runtime
3880 class ScopeInfo : public FixedArray {
3882 DECLARE_CAST(ScopeInfo)
3884 // Return the type of this scope.
3885 ScopeType scope_type();
3887 // Does this scope call eval?
3890 // Return the language mode of this scope.
3891 LanguageMode language_mode();
3893 // True if this scope is a (var) declaration scope.
3894 bool is_declaration_scope();
3896 // Does this scope make a sloppy eval call?
3897 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3899 // Return the total number of locals allocated on the stack and in the
3900 // context. This includes the parameters that are allocated in the context.
3903 // Return the number of stack slots for code. This number consists of two
3905 // 1. One stack slot per stack allocated local.
3906 // 2. One stack slot for the function name if it is stack allocated.
3907 int StackSlotCount();
3909 // Return the number of context slots for code if a context is allocated. This
3910 // number consists of three parts:
3911 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3912 // 2. One context slot per context allocated local.
3913 // 3. One context slot for the function name if it is context allocated.
3914 // Parameters allocated in the context count as context allocated locals. If
3915 // no contexts are allocated for this scope ContextLength returns 0.
3916 int ContextLength();
3918 // Does this scope declare a "this" binding?
3921 // Does this scope declare a "this" binding, and the "this" binding is stack-
3922 // or context-allocated?
3923 bool HasAllocatedReceiver();
3925 // Is this scope the scope of a named function expression?
3926 bool HasFunctionName();
3928 // Return if this has context allocated locals.
3929 bool HasHeapAllocatedLocals();
3931 // Return if contexts are allocated for this scope.
3934 // Return if this is a function scope with "use asm".
3935 inline bool IsAsmModule();
3937 // Return if this is a nested function within an asm module scope.
3938 inline bool IsAsmFunction();
3940 inline bool HasSimpleParameters();
3942 // Return the function_name if present.
3943 String* FunctionName();
3945 // Return the name of the given parameter.
3946 String* ParameterName(int var);
3948 // Return the name of the given local.
3949 String* LocalName(int var);
3951 // Return the name of the given stack local.
3952 String* StackLocalName(int var);
3954 // Return the name of the given stack local.
3955 int StackLocalIndex(int var);
3957 // Return the name of the given context local.
3958 String* ContextLocalName(int var);
3960 // Return the mode of the given context local.
3961 VariableMode ContextLocalMode(int var);
3963 // Return the initialization flag of the given context local.
3964 InitializationFlag ContextLocalInitFlag(int var);
3966 // Return the initialization flag of the given context local.
3967 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3969 // Return true if this local was introduced by the compiler, and should not be
3970 // exposed to the user in a debugger.
3971 bool LocalIsSynthetic(int var);
3973 String* StrongModeFreeVariableName(int var);
3974 int StrongModeFreeVariableStartPosition(int var);
3975 int StrongModeFreeVariableEndPosition(int var);
3977 // Lookup support for serialized scope info. Returns the
3978 // the stack slot index for a given slot name if the slot is
3979 // present; otherwise returns a value < 0. The name must be an internalized
3981 int StackSlotIndex(String* name);
3983 // Lookup support for serialized scope info. Returns the local context slot
3984 // index for a given slot name if the slot is present; otherwise
3985 // returns a value < 0. The name must be an internalized string.
3986 // If the slot is present and mode != NULL, sets *mode to the corresponding
3987 // mode for that variable.
3988 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3989 VariableMode* mode, InitializationFlag* init_flag,
3990 MaybeAssignedFlag* maybe_assigned_flag);
3992 // Similar to ContextSlotIndex() but this method searches only among
3993 // global slots of the serialized scope info. Returns the context slot index
3994 // for a given slot name if the slot is present; otherwise returns a
3995 // value < 0. The name must be an internalized string. If the slot is present
3996 // and mode != NULL, sets *mode to the corresponding mode for that variable.
3997 static int ContextGlobalSlotIndex(Handle<ScopeInfo> scope_info,
3998 Handle<String> name, VariableMode* mode,
3999 InitializationFlag* init_flag,
4000 MaybeAssignedFlag* maybe_assigned_flag);
4002 // Lookup the name of a certain context slot by its index.
4003 String* ContextSlotName(int slot_index);
4005 // Lookup support for serialized scope info. Returns the
4006 // parameter index for a given parameter name if the parameter is present;
4007 // otherwise returns a value < 0. The name must be an internalized string.
4008 int ParameterIndex(String* name);
4010 // Lookup support for serialized scope info. Returns the function context
4011 // slot index if the function name is present and context-allocated (named
4012 // function expressions, only), otherwise returns a value < 0. The name
4013 // must be an internalized string.
4014 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4016 // Lookup support for serialized scope info. Returns the receiver context
4017 // slot index if scope has a "this" binding, and the binding is
4018 // context-allocated. Otherwise returns a value < 0.
4019 int ReceiverContextSlotIndex();
4021 FunctionKind function_kind();
4023 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4024 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4026 // Serializes empty scope info.
4027 static ScopeInfo* Empty(Isolate* isolate);
4033 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4034 // numeric and occupies one array slot.
4035 // 1. A set of properties of the scope
4036 // 2. The number of parameters. This only applies to function scopes. For
4037 // non-function scopes this is 0.
4038 // 3. The number of non-parameter variables allocated on the stack.
4039 // 4. The number of non-parameter and parameter variables allocated in the
4041 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
4044 V(StackLocalCount) \
4045 V(ContextLocalCount) \
4046 V(ContextGlobalCount) \
4047 V(StrongModeFreeVariableCount)
4049 #define FIELD_ACCESSORS(name) \
4050 inline void Set##name(int value); \
4052 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
4053 #undef FIELD_ACCESSORS
4056 #define DECL_INDEX(name) k##name,
4057 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
4063 // The layout of the variable part of a ScopeInfo is as follows:
4064 // 1. ParameterEntries:
4065 // This part stores the names of the parameters for function scopes. One
4066 // slot is used per parameter, so in total this part occupies
4067 // ParameterCount() slots in the array. For other scopes than function
4068 // scopes ParameterCount() is 0.
4069 // 2. StackLocalFirstSlot:
4070 // Index of a first stack slot for stack local. Stack locals belonging to
4071 // this scope are located on a stack at slots starting from this index.
4072 // 3. StackLocalEntries:
4073 // Contains the names of local variables that are allocated on the stack,
4074 // in increasing order of the stack slot index. First local variable has
4075 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4076 // One slot is used per stack local, so in total this part occupies
4077 // StackLocalCount() slots in the array.
4078 // 4. ContextLocalNameEntries:
4079 // Contains the names of local variables and parameters that are allocated
4080 // in the context. They are stored in increasing order of the context slot
4081 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4082 // context local, so in total this part occupies ContextLocalCount() slots
4084 // 5. ContextLocalInfoEntries:
4085 // Contains the variable modes and initialization flags corresponding to
4086 // the context locals in ContextLocalNameEntries. One slot is used per
4087 // context local, so in total this part occupies ContextLocalCount()
4088 // slots in the array.
4089 // 6. StrongModeFreeVariableNameEntries:
4090 // Stores the names of strong mode free variables.
4091 // 7. StrongModeFreeVariablePositionEntries:
4092 // Stores the locations (start and end position) of strong mode free
4094 // 8. RecieverEntryIndex:
4095 // If the scope binds a "this" value, one slot is reserved to hold the
4096 // context or stack slot index for the variable.
4097 // 9. FunctionNameEntryIndex:
4098 // If the scope belongs to a named function expression this part contains
4099 // information about the function variable. It always occupies two array
4100 // slots: a. The name of the function variable.
4101 // b. The context or stack slot index for the variable.
4102 int ParameterEntriesIndex();
4103 int StackLocalFirstSlotIndex();
4104 int StackLocalEntriesIndex();
4105 int ContextLocalNameEntriesIndex();
4106 int ContextGlobalNameEntriesIndex();
4107 int ContextLocalInfoEntriesIndex();
4108 int ContextGlobalInfoEntriesIndex();
4109 int StrongModeFreeVariableNameEntriesIndex();
4110 int StrongModeFreeVariablePositionEntriesIndex();
4111 int ReceiverEntryIndex();
4112 int FunctionNameEntryIndex();
4114 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4115 VariableLocation* location, InitializationFlag* init_flag,
4116 MaybeAssignedFlag* maybe_assigned_flag);
4118 // Used for the function name variable for named function expressions, and for
4120 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4122 // Properties of scopes.
4123 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4124 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4125 STATIC_ASSERT(LANGUAGE_END == 3);
4126 class LanguageModeField
4127 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4128 class DeclarationScopeField
4129 : public BitField<bool, LanguageModeField::kNext, 1> {};
4130 class ReceiverVariableField
4131 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
4133 class FunctionVariableField
4134 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4136 class FunctionVariableMode
4137 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4138 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4140 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4141 class HasSimpleParametersField
4142 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4143 class FunctionKindField
4144 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4146 // BitFields representing the encoded information for context locals in the
4147 // ContextLocalInfoEntries part.
4148 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4149 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4150 class ContextLocalMaybeAssignedFlag
4151 : public BitField<MaybeAssignedFlag, 4, 1> {};
4153 friend class ScopeIterator;
4157 // The cache for maps used by normalized (dictionary mode) objects.
4158 // Such maps do not have property descriptors, so a typical program
4159 // needs very limited number of distinct normalized maps.
4160 class NormalizedMapCache: public FixedArray {
4162 static Handle<NormalizedMapCache> New(Isolate* isolate);
4164 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4165 PropertyNormalizationMode mode);
4166 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4170 DECLARE_CAST(NormalizedMapCache)
4172 static inline bool IsNormalizedMapCache(const Object* obj);
4174 DECLARE_VERIFIER(NormalizedMapCache)
4176 static const int kEntries = 64;
4178 static inline int GetIndex(Handle<Map> map);
4180 // The following declarations hide base class methods.
4181 Object* get(int index);
4182 void set(int index, Object* value);
4186 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4187 // that is attached to code objects.
4188 class ByteArray: public FixedArrayBase {
4192 // Setter and getter.
4193 inline byte get(int index);
4194 inline void set(int index, byte value);
4196 // Treat contents as an int array.
4197 inline int get_int(int index);
4199 static int SizeFor(int length) {
4200 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4202 // We use byte arrays for free blocks in the heap. Given a desired size in
4203 // bytes that is a multiple of the word size and big enough to hold a byte
4204 // array, this function returns the number of elements a byte array should
4206 static int LengthFor(int size_in_bytes) {
4207 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4208 DCHECK(size_in_bytes >= kHeaderSize);
4209 return size_in_bytes - kHeaderSize;
4212 // Returns data start address.
4213 inline Address GetDataStartAddress();
4215 // Returns a pointer to the ByteArray object for a given data start address.
4216 static inline ByteArray* FromDataStartAddress(Address address);
4218 DECLARE_CAST(ByteArray)
4220 // Dispatched behavior.
4221 inline int ByteArraySize();
4222 DECLARE_PRINTER(ByteArray)
4223 DECLARE_VERIFIER(ByteArray)
4225 // Layout description.
4226 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4228 // Maximal memory consumption for a single ByteArray.
4229 static const int kMaxSize = 512 * MB;
4230 // Maximal length of a single ByteArray.
4231 static const int kMaxLength = kMaxSize - kHeaderSize;
4234 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4238 // BytecodeArray represents a sequence of interpreter bytecodes.
4239 class BytecodeArray : public FixedArrayBase {
4241 static int SizeFor(int length) {
4242 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4245 // Setter and getter
4246 inline byte get(int index);
4247 inline void set(int index, byte value);
4249 // Returns data start address.
4250 inline Address GetFirstBytecodeAddress();
4252 // Accessors for frame size.
4253 inline int frame_size() const;
4254 inline void set_frame_size(int frame_size);
4256 // Accessor for register count (derived from frame_size).
4257 inline int register_count() const;
4259 // Accessors for parameter count (including implicit 'this' receiver).
4260 inline int parameter_count() const;
4261 inline void set_parameter_count(int number_of_parameters);
4263 // Accessors for the constant pool.
4264 DECL_ACCESSORS(constant_pool, FixedArray)
4266 DECLARE_CAST(BytecodeArray)
4268 // Dispatched behavior.
4269 inline int BytecodeArraySize();
4270 inline void BytecodeArrayIterateBody(ObjectVisitor* v);
4272 DECLARE_PRINTER(BytecodeArray)
4273 DECLARE_VERIFIER(BytecodeArray)
4275 void Disassemble(std::ostream& os);
4277 // Layout description.
4278 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4279 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4280 static const int kConstantPoolOffset = kParameterSizeOffset + kIntSize;
4281 static const int kHeaderSize = kConstantPoolOffset + kPointerSize;
4283 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4285 // Maximal memory consumption for a single BytecodeArray.
4286 static const int kMaxSize = 512 * MB;
4287 // Maximal length of a single BytecodeArray.
4288 static const int kMaxLength = kMaxSize - kHeaderSize;
4291 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4295 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4296 // They look like heap objects (are heap object tagged and have a map) so that
4297 // the heap remains iterable. They have a size and a next pointer.
4298 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4299 // in the free list.
4300 class FreeSpace: public HeapObject {
4302 // [size]: size of the free space including the header.
4303 inline int size() const;
4304 inline void set_size(int value);
4306 inline int nobarrier_size() const;
4307 inline void nobarrier_set_size(int value);
4311 // Accessors for the next field.
4312 inline FreeSpace* next();
4313 inline FreeSpace** next_address();
4314 inline void set_next(FreeSpace* next);
4316 inline static FreeSpace* cast(HeapObject* obj);
4318 // Dispatched behavior.
4319 DECLARE_PRINTER(FreeSpace)
4320 DECLARE_VERIFIER(FreeSpace)
4322 // Layout description.
4323 // Size is smi tagged when it is stored.
4324 static const int kSizeOffset = HeapObject::kHeaderSize;
4325 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4328 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4332 // V has parameters (Type, type, TYPE, C type, element_size)
4333 #define TYPED_ARRAYS(V) \
4334 V(Uint8, uint8, UINT8, uint8_t, 1) \
4335 V(Int8, int8, INT8, int8_t, 1) \
4336 V(Uint16, uint16, UINT16, uint16_t, 2) \
4337 V(Int16, int16, INT16, int16_t, 2) \
4338 V(Uint32, uint32, UINT32, uint32_t, 4) \
4339 V(Int32, int32, INT32, int32_t, 4) \
4340 V(Float32, float32, FLOAT32, float, 4) \
4341 V(Float64, float64, FLOAT64, double, 8) \
4342 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4345 class FixedTypedArrayBase: public FixedArrayBase {
4347 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4348 DECL_ACCESSORS(base_pointer, Object)
4350 // [external_pointer]: Contains the offset between base_pointer and the start
4351 // of the data. If the base_pointer is a nullptr, the external_pointer
4352 // therefore points to the actual backing store.
4353 DECL_ACCESSORS(external_pointer, void)
4355 // Dispatched behavior.
4356 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4358 template <typename StaticVisitor>
4359 inline void FixedTypedArrayBaseIterateBody();
4361 DECLARE_CAST(FixedTypedArrayBase)
4363 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4364 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4365 static const int kHeaderSize =
4366 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4368 static const int kDataOffset = kHeaderSize;
4372 static inline int TypedArraySize(InstanceType type, int length);
4373 inline int TypedArraySize(InstanceType type);
4375 // Use with care: returns raw pointer into heap.
4376 inline void* DataPtr();
4378 inline int DataSize();
4381 static inline int ElementSize(InstanceType type);
4383 inline int DataSize(InstanceType type);
4385 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4389 template <class Traits>
4390 class FixedTypedArray: public FixedTypedArrayBase {
4392 typedef typename Traits::ElementType ElementType;
4393 static const InstanceType kInstanceType = Traits::kInstanceType;
4395 DECLARE_CAST(FixedTypedArray<Traits>)
4397 inline ElementType get_scalar(int index);
4398 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4399 inline void set(int index, ElementType value);
4401 static inline ElementType from_int(int value);
4402 static inline ElementType from_double(double value);
4404 // This accessor applies the correct conversion from Smi, HeapNumber
4406 inline void SetValue(uint32_t index, Object* value);
4408 DECLARE_PRINTER(FixedTypedArray)
4409 DECLARE_VERIFIER(FixedTypedArray)
4412 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4415 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4416 class Type##ArrayTraits { \
4417 public: /* NOLINT */ \
4418 typedef elementType ElementType; \
4419 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4420 static const char* Designator() { return #type " array"; } \
4421 static inline Handle<Object> ToHandle(Isolate* isolate, \
4422 elementType scalar); \
4423 static inline elementType defaultValue(); \
4426 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4428 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4430 #undef FIXED_TYPED_ARRAY_TRAITS
4433 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4434 // data for code generated by the Hydrogen/Lithium compiler. It also
4435 // contains information about functions that were inlined. If N different
4436 // functions were inlined then first N elements of the literal array will
4437 // contain these functions.
4440 class DeoptimizationInputData: public FixedArray {
4442 // Layout description. Indices in the array.
4443 static const int kTranslationByteArrayIndex = 0;
4444 static const int kInlinedFunctionCountIndex = 1;
4445 static const int kLiteralArrayIndex = 2;
4446 static const int kOsrAstIdIndex = 3;
4447 static const int kOsrPcOffsetIndex = 4;
4448 static const int kOptimizationIdIndex = 5;
4449 static const int kSharedFunctionInfoIndex = 6;
4450 static const int kWeakCellCacheIndex = 7;
4451 static const int kFirstDeoptEntryIndex = 8;
4453 // Offsets of deopt entry elements relative to the start of the entry.
4454 static const int kAstIdRawOffset = 0;
4455 static const int kTranslationIndexOffset = 1;
4456 static const int kArgumentsStackHeightOffset = 2;
4457 static const int kPcOffset = 3;
4458 static const int kDeoptEntrySize = 4;
4460 // Simple element accessors.
4461 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4462 inline type* name(); \
4463 inline void Set##name(type* value);
4465 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4466 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4467 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4468 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4469 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4470 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4471 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4472 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4474 #undef DECLARE_ELEMENT_ACCESSORS
4476 // Accessors for elements of the ith deoptimization entry.
4477 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4478 inline type* name(int i); \
4479 inline void Set##name(int i, type* value);
4481 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4482 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4483 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4484 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4486 #undef DECLARE_ENTRY_ACCESSORS
4488 inline BailoutId AstId(int i);
4490 inline void SetAstId(int i, BailoutId value);
4492 inline int DeoptCount();
4494 // Allocates a DeoptimizationInputData.
4495 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4496 int deopt_entry_count,
4497 PretenureFlag pretenure);
4499 DECLARE_CAST(DeoptimizationInputData)
4501 #ifdef ENABLE_DISASSEMBLER
4502 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4506 static int IndexForEntry(int i) {
4507 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4511 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4515 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4516 // data for code generated by the full compiler.
4517 // The format of the these objects is
4518 // [i * 2]: Ast ID for ith deoptimization.
4519 // [i * 2 + 1]: PC and state of ith deoptimization
4520 class DeoptimizationOutputData: public FixedArray {
4522 inline int DeoptPoints();
4524 inline BailoutId AstId(int index);
4526 inline void SetAstId(int index, BailoutId id);
4528 inline Smi* PcAndState(int index);
4529 inline void SetPcAndState(int index, Smi* offset);
4531 static int LengthOfFixedArray(int deopt_points) {
4532 return deopt_points * 2;
4535 // Allocates a DeoptimizationOutputData.
4536 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4537 int number_of_deopt_points,
4538 PretenureFlag pretenure);
4540 DECLARE_CAST(DeoptimizationOutputData)
4542 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4543 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4548 // HandlerTable is a fixed array containing entries for exception handlers in
4549 // the code object it is associated with. The tables comes in two flavors:
4550 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4551 // exception handler and a range representing the try-block covered by that
4552 // handler. Layout looks as follows:
4553 // [ range-start , range-end , handler-offset , stack-depth ]
4554 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4555 // per call-site that could throw an exception. Layout looks as follows:
4556 // [ return-address-offset , handler-offset ]
4557 class HandlerTable : public FixedArray {
4559 // Conservative prediction whether a given handler will locally catch an
4560 // exception or cause a re-throw to outside the code boundary. Since this is
4561 // undecidable it is merely an approximation (e.g. useful for debugger).
4562 enum CatchPrediction { UNCAUGHT, CAUGHT };
4564 // Accessors for handler table based on ranges.
4565 inline void SetRangeStart(int index, int value);
4566 inline void SetRangeEnd(int index, int value);
4567 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4568 inline void SetRangeDepth(int index, int value);
4570 // Accessors for handler table based on return addresses.
4571 inline void SetReturnOffset(int index, int value);
4572 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4574 // Lookup handler in a table based on ranges.
4575 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4577 // Lookup handler in a table based on return addresses.
4578 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4580 // Returns the required length of the underlying fixed array.
4581 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4582 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4584 DECLARE_CAST(HandlerTable)
4586 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4587 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4588 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4592 // Layout description for handler table based on ranges.
4593 static const int kRangeStartIndex = 0;
4594 static const int kRangeEndIndex = 1;
4595 static const int kRangeHandlerIndex = 2;
4596 static const int kRangeDepthIndex = 3;
4597 static const int kRangeEntrySize = 4;
4599 // Layout description for handler table based on return addresses.
4600 static const int kReturnOffsetIndex = 0;
4601 static const int kReturnHandlerIndex = 1;
4602 static const int kReturnEntrySize = 2;
4604 // Encoding of the {handler} field.
4605 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4606 class HandlerOffsetField : public BitField<int, 1, 30> {};
4610 // Code describes objects with on-the-fly generated machine code.
4611 class Code: public HeapObject {
4613 // Opaque data type for encapsulating code flags like kind, inline
4614 // cache state, and arguments count.
4615 typedef uint32_t Flags;
4617 #define NON_IC_KIND_LIST(V) \
4619 V(OPTIMIZED_FUNCTION) \
4626 #define IC_KIND_LIST(V) \
4637 #define CODE_KIND_LIST(V) \
4638 NON_IC_KIND_LIST(V) \
4642 #define DEFINE_CODE_KIND_ENUM(name) name,
4643 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4644 #undef DEFINE_CODE_KIND_ENUM
4648 // No more than 16 kinds. The value is currently encoded in four bits in
4650 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4652 static const char* Kind2String(Kind kind);
4660 static const int kPrologueOffsetNotSet = -1;
4662 #ifdef ENABLE_DISASSEMBLER
4664 static const char* ICState2String(InlineCacheState state);
4665 static const char* StubType2String(StubType type);
4666 static void PrintExtraICState(std::ostream& os, // NOLINT
4667 Kind kind, ExtraICState extra);
4668 void Disassemble(const char* name, std::ostream& os); // NOLINT
4669 #endif // ENABLE_DISASSEMBLER
4671 // [instruction_size]: Size of the native instructions
4672 inline int instruction_size() const;
4673 inline void set_instruction_size(int value);
4675 // [relocation_info]: Code relocation information
4676 DECL_ACCESSORS(relocation_info, ByteArray)
4677 void InvalidateRelocation();
4678 void InvalidateEmbeddedObjects();
4680 // [handler_table]: Fixed array containing offsets of exception handlers.
4681 DECL_ACCESSORS(handler_table, FixedArray)
4683 // [deoptimization_data]: Array containing data for deopt.
4684 DECL_ACCESSORS(deoptimization_data, FixedArray)
4686 // [raw_type_feedback_info]: This field stores various things, depending on
4687 // the kind of the code object.
4688 // FUNCTION => type feedback information.
4689 // STUB and ICs => major/minor key as Smi.
4690 DECL_ACCESSORS(raw_type_feedback_info, Object)
4691 inline Object* type_feedback_info();
4692 inline void set_type_feedback_info(
4693 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4694 inline uint32_t stub_key();
4695 inline void set_stub_key(uint32_t key);
4697 // [next_code_link]: Link for lists of optimized or deoptimized code.
4698 // Note that storage for this field is overlapped with typefeedback_info.
4699 DECL_ACCESSORS(next_code_link, Object)
4701 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4702 // field does not have to be traced during garbage collection since
4703 // it is only used by the garbage collector itself.
4704 DECL_ACCESSORS(gc_metadata, Object)
4706 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4707 // at the moment when this object was created.
4708 inline void set_ic_age(int count);
4709 inline int ic_age() const;
4711 // [prologue_offset]: Offset of the function prologue, used for aging
4712 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4713 inline int prologue_offset() const;
4714 inline void set_prologue_offset(int offset);
4716 // [constant_pool offset]: Offset of the constant pool.
4717 // Valid for FLAG_enable_embedded_constant_pool only
4718 inline int constant_pool_offset() const;
4719 inline void set_constant_pool_offset(int offset);
4721 // Unchecked accessors to be used during GC.
4722 inline ByteArray* unchecked_relocation_info();
4724 inline int relocation_size();
4726 // [flags]: Various code flags.
4727 inline Flags flags();
4728 inline void set_flags(Flags flags);
4730 // [flags]: Access to specific code flags.
4732 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4733 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4735 inline StubType type(); // Only valid for monomorphic IC stubs.
4737 // Testers for IC stub kinds.
4738 inline bool is_inline_cache_stub();
4739 inline bool is_debug_stub();
4740 inline bool is_handler();
4741 inline bool is_load_stub();
4742 inline bool is_keyed_load_stub();
4743 inline bool is_store_stub();
4744 inline bool is_keyed_store_stub();
4745 inline bool is_call_stub();
4746 inline bool is_binary_op_stub();
4747 inline bool is_compare_ic_stub();
4748 inline bool is_compare_nil_ic_stub();
4749 inline bool is_to_boolean_ic_stub();
4750 inline bool is_keyed_stub();
4751 inline bool is_optimized_code();
4752 inline bool embeds_maps_weakly();
4754 inline bool IsCodeStubOrIC();
4755 inline bool IsJavaScriptCode();
4757 inline void set_raw_kind_specific_flags1(int value);
4758 inline void set_raw_kind_specific_flags2(int value);
4760 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4761 // object was generated by either the hydrogen or the TurboFan optimizing
4762 // compiler (but it may not be an optimized function).
4763 inline bool is_crankshafted();
4764 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4765 inline void set_is_crankshafted(bool value);
4767 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4768 // code object was generated by the TurboFan optimizing compiler.
4769 inline bool is_turbofanned();
4770 inline void set_is_turbofanned(bool value);
4772 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4773 // embedded objects in code should be treated weakly.
4774 inline bool can_have_weak_objects();
4775 inline void set_can_have_weak_objects(bool value);
4777 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4778 // deoptimization support.
4779 inline bool has_deoptimization_support();
4780 inline void set_has_deoptimization_support(bool value);
4782 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4783 // been compiled with debug break slots.
4784 inline bool has_debug_break_slots();
4785 inline void set_has_debug_break_slots(bool value);
4787 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4788 // reloc info includes runtime and external references to support
4789 // serialization/deserialization.
4790 inline bool has_reloc_info_for_serialization();
4791 inline void set_has_reloc_info_for_serialization(bool value);
4793 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4794 // how long the function has been marked for OSR and therefore which
4795 // level of loop nesting we are willing to do on-stack replacement
4797 inline void set_allow_osr_at_loop_nesting_level(int level);
4798 inline int allow_osr_at_loop_nesting_level();
4800 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4801 // the code object was seen on the stack with no IC patching going on.
4802 inline int profiler_ticks();
4803 inline void set_profiler_ticks(int ticks);
4805 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4806 // For builtins, tells which builtin index it has.
4807 // Note that builtins can have a code kind other than BUILTIN, which means
4808 // that for arbitrary code objects, this index value may be random garbage.
4809 // To verify in that case, compare the code object to the indexed builtin.
4810 inline int builtin_index();
4811 inline void set_builtin_index(int id);
4813 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4814 // reserved in the code prologue.
4815 inline unsigned stack_slots();
4816 inline void set_stack_slots(unsigned slots);
4818 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4819 // the instruction stream where the safepoint table starts.
4820 inline unsigned safepoint_table_offset();
4821 inline void set_safepoint_table_offset(unsigned offset);
4823 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4824 // instruction stream where the back edge table starts.
4825 inline unsigned back_edge_table_offset();
4826 inline void set_back_edge_table_offset(unsigned offset);
4828 inline bool back_edges_patched_for_osr();
4830 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4831 inline uint16_t to_boolean_state();
4833 // [has_function_cache]: For kind STUB tells whether there is a function
4834 // cache is passed to the stub.
4835 inline bool has_function_cache();
4836 inline void set_has_function_cache(bool flag);
4839 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4840 // the code is going to be deoptimized because of dead embedded maps.
4841 inline bool marked_for_deoptimization();
4842 inline void set_marked_for_deoptimization(bool flag);
4844 // [constant_pool]: The constant pool for this function.
4845 inline Address constant_pool();
4847 // Get the safepoint entry for the given pc.
4848 SafepointEntry GetSafepointEntry(Address pc);
4850 // Find an object in a stub with a specified map
4851 Object* FindNthObject(int n, Map* match_map);
4853 // Find the first allocation site in an IC stub.
4854 AllocationSite* FindFirstAllocationSite();
4856 // Find the first map in an IC stub.
4857 Map* FindFirstMap();
4858 void FindAllMaps(MapHandleList* maps);
4860 // Find the first handler in an IC stub.
4861 Code* FindFirstHandler();
4863 // Find |length| handlers and put them into |code_list|. Returns false if not
4864 // enough handlers can be found.
4865 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4867 // Find the handler for |map|.
4868 MaybeHandle<Code> FindHandlerForMap(Map* map);
4870 // Find the first name in an IC stub.
4871 Name* FindFirstName();
4873 class FindAndReplacePattern;
4874 // For each (map-to-find, object-to-replace) pair in the pattern, this
4875 // function replaces the corresponding placeholder in the code with the
4876 // object-to-replace. The function assumes that pairs in the pattern come in
4877 // the same order as the placeholders in the code.
4878 // If the placeholder is a weak cell, then the value of weak cell is matched
4879 // against the map-to-find.
4880 void FindAndReplace(const FindAndReplacePattern& pattern);
4882 // The entire code object including its header is copied verbatim to the
4883 // snapshot so that it can be written in one, fast, memcpy during
4884 // deserialization. The deserializer will overwrite some pointers, rather
4885 // like a runtime linker, but the random allocation addresses used in the
4886 // mksnapshot process would still be present in the unlinked snapshot data,
4887 // which would make snapshot production non-reproducible. This method wipes
4888 // out the to-be-overwritten header data for reproducible snapshots.
4889 inline void WipeOutHeader();
4891 // Flags operations.
4892 static inline Flags ComputeFlags(
4893 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4894 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4895 CacheHolderFlag holder = kCacheOnReceiver);
4897 static inline Flags ComputeMonomorphicFlags(
4898 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4899 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4901 static inline Flags ComputeHandlerFlags(
4902 Kind handler_kind, StubType type = NORMAL,
4903 CacheHolderFlag holder = kCacheOnReceiver);
4905 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4906 static inline StubType ExtractTypeFromFlags(Flags flags);
4907 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4908 static inline Kind ExtractKindFromFlags(Flags flags);
4909 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4911 static inline Flags RemoveTypeFromFlags(Flags flags);
4912 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4914 // Convert a target address into a code object.
4915 static inline Code* GetCodeFromTargetAddress(Address address);
4917 // Convert an entry address into an object.
4918 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4920 // Returns the address of the first instruction.
4921 inline byte* instruction_start();
4923 // Returns the address right after the last instruction.
4924 inline byte* instruction_end();
4926 // Returns the size of the instructions, padding, and relocation information.
4927 inline int body_size();
4929 // Returns the address of the first relocation info (read backwards!).
4930 inline byte* relocation_start();
4932 // Code entry point.
4933 inline byte* entry();
4935 // Returns true if pc is inside this object's instructions.
4936 inline bool contains(byte* pc);
4938 // Relocate the code by delta bytes. Called to signal that this code
4939 // object has been moved by delta bytes.
4940 void Relocate(intptr_t delta);
4942 // Migrate code described by desc.
4943 void CopyFrom(const CodeDesc& desc);
4945 // Returns the object size for a given body (used for allocation).
4946 static int SizeFor(int body_size) {
4947 DCHECK_SIZE_TAG_ALIGNED(body_size);
4948 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4951 // Calculate the size of the code object to report for log events. This takes
4952 // the layout of the code object into account.
4953 inline int ExecutableSize();
4955 // Locating source position.
4956 int SourcePosition(Address pc);
4957 int SourceStatementPosition(Address pc);
4961 // Dispatched behavior.
4962 inline int CodeSize();
4963 inline void CodeIterateBody(ObjectVisitor* v);
4965 template<typename StaticVisitor>
4966 inline void CodeIterateBody(Heap* heap);
4968 DECLARE_PRINTER(Code)
4969 DECLARE_VERIFIER(Code)
4971 void ClearInlineCaches();
4972 void ClearInlineCaches(Kind kind);
4974 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4975 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4977 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4979 kToBeExecutedOnceCodeAge = -3,
4980 kNotExecutedCodeAge = -2,
4981 kExecutedOnceCodeAge = -1,
4983 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4985 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4986 kLastCodeAge = kAfterLastCodeAge - 1,
4987 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4988 kIsOldCodeAge = kSexagenarianCodeAge,
4989 kPreAgedCodeAge = kIsOldCodeAge - 1
4991 #undef DECLARE_CODE_AGE_ENUM
4993 // Code aging. Indicates how many full GCs this code has survived without
4994 // being entered through the prologue. Used to determine when it is
4995 // relatively safe to flush this code object and replace it with the lazy
4996 // compilation stub.
4997 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4998 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4999 void MakeYoung(Isolate* isolate);
5000 void MarkToBeExecutedOnce(Isolate* isolate);
5001 void MakeOlder(MarkingParity);
5002 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5005 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5006 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5009 void PrintDeoptLocation(FILE* out, Address pc);
5010 bool CanDeoptAt(Address pc);
5013 void VerifyEmbeddedObjectsDependency();
5017 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5018 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5019 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
5022 inline bool CanContainWeakObjects();
5024 inline bool IsWeakObject(Object* object);
5026 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5028 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5029 WeakCell* CachedWeakCell();
5031 // Max loop nesting marker used to postpose OSR. We don't take loop
5032 // nesting that is deeper than 5 levels into account.
5033 static const int kMaxLoopNestingMarker = 6;
5035 static const int kConstantPoolSize =
5036 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5038 // Layout description.
5039 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5040 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5041 static const int kDeoptimizationDataOffset =
5042 kHandlerTableOffset + kPointerSize;
5043 // For FUNCTION kind, we store the type feedback info here.
5044 static const int kTypeFeedbackInfoOffset =
5045 kDeoptimizationDataOffset + kPointerSize;
5046 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5047 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5048 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5049 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5050 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5051 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5052 static const int kKindSpecificFlags2Offset =
5053 kKindSpecificFlags1Offset + kIntSize;
5054 // Note: We might be able to squeeze this into the flags above.
5055 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5056 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5057 static const int kHeaderPaddingStart =
5058 kConstantPoolOffset + kConstantPoolSize;
5060 // Add padding to align the instruction start following right after
5061 // the Code object header.
5062 static const int kHeaderSize =
5063 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5065 // Byte offsets within kKindSpecificFlags1Offset.
5066 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5067 class FullCodeFlagsHasDeoptimizationSupportField:
5068 public BitField<bool, 0, 1> {}; // NOLINT
5069 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5070 class FullCodeFlagsHasRelocInfoForSerialization
5071 : public BitField<bool, 2, 1> {};
5072 // Bit 3 in this bitfield is unused.
5073 class ProfilerTicksField : public BitField<int, 4, 28> {};
5075 // Flags layout. BitField<type, shift, size>.
5076 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5077 class TypeField : public BitField<StubType, 4, 1> {};
5078 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5079 class KindField : public BitField<Kind, 7, 4> {};
5080 class ExtraICStateField: public BitField<ExtraICState, 11,
5081 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5083 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5084 static const int kStackSlotsFirstBit = 0;
5085 static const int kStackSlotsBitCount = 24;
5086 static const int kHasFunctionCacheBit =
5087 kStackSlotsFirstBit + kStackSlotsBitCount;
5088 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5089 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5090 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5092 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5093 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5095 class StackSlotsField: public BitField<int,
5096 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5097 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5099 class MarkedForDeoptimizationField
5100 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5101 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5103 class CanHaveWeakObjectsField
5104 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5106 // KindSpecificFlags2 layout (ALL)
5107 static const int kIsCrankshaftedBit = 0;
5108 class IsCrankshaftedField: public BitField<bool,
5109 kIsCrankshaftedBit, 1> {}; // NOLINT
5111 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5112 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5113 static const int kSafepointTableOffsetBitCount = 30;
5115 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5116 kSafepointTableOffsetBitCount <= 32);
5117 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5119 class SafepointTableOffsetField: public BitField<int,
5120 kSafepointTableOffsetFirstBit,
5121 kSafepointTableOffsetBitCount> {}; // NOLINT
5123 // KindSpecificFlags2 layout (FUNCTION)
5124 class BackEdgeTableOffsetField: public BitField<int,
5125 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5126 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5127 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5128 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5130 static const int kArgumentsBits = 16;
5131 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5133 // This constant should be encodable in an ARM instruction.
5134 static const int kFlagsNotUsedInLookup =
5135 TypeField::kMask | CacheHolderField::kMask;
5138 friend class RelocIterator;
5139 friend class Deoptimizer; // For FindCodeAgeSequence.
5141 void ClearInlineCaches(Kind* kind);
5144 byte* FindCodeAgeSequence();
5145 static void GetCodeAgeAndParity(Code* code, Age* age,
5146 MarkingParity* parity);
5147 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5148 MarkingParity* parity);
5149 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5151 // Code aging -- platform-specific
5152 static void PatchPlatformCodeAge(Isolate* isolate,
5153 byte* sequence, Age age,
5154 MarkingParity parity);
5156 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5160 // This class describes the layout of dependent codes array of a map. The
5161 // array is partitioned into several groups of dependent codes. Each group
5162 // contains codes with the same dependency on the map. The array has the
5163 // following layout for n dependency groups:
5165 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5166 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5167 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5169 // The first n elements are Smis, each of them specifies the number of codes
5170 // in the corresponding group. The subsequent elements contain grouped code
5171 // objects in weak cells. The suffix of the array can be filled with the
5172 // undefined value if the number of codes is less than the length of the
5173 // array. The order of the code objects within a group is not preserved.
5175 // All code indexes used in the class are counted starting from the first
5176 // code object of the first group. In other words, code index 0 corresponds
5177 // to array index n = kCodesStartIndex.
5179 class DependentCode: public FixedArray {
5181 enum DependencyGroup {
5182 // Group of code that weakly embed this map and depend on being
5183 // deoptimized when the map is garbage collected.
5185 // Group of code that embed a transition to this map, and depend on being
5186 // deoptimized when the transition is replaced by a new version.
5188 // Group of code that omit run-time prototype checks for prototypes
5189 // described by this map. The group is deoptimized whenever an object
5190 // described by this map changes shape (and transitions to a new map),
5191 // possibly invalidating the assumptions embedded in the code.
5192 kPrototypeCheckGroup,
5193 // Group of code that depends on global property values in property cells
5194 // not being changed.
5195 kPropertyCellChangedGroup,
5196 // Group of code that omit run-time type checks for the field(s) introduced
5199 // Group of code that omit run-time type checks for initial maps of
5201 kInitialMapChangedGroup,
5202 // Group of code that depends on tenuring information in AllocationSites
5203 // not being changed.
5204 kAllocationSiteTenuringChangedGroup,
5205 // Group of code that depends on element transition information in
5206 // AllocationSites not being changed.
5207 kAllocationSiteTransitionChangedGroup
5210 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5212 // Array for holding the index of the first code object of each group.
5213 // The last element stores the total number of code objects.
5214 class GroupStartIndexes {
5216 explicit GroupStartIndexes(DependentCode* entries);
5217 void Recompute(DependentCode* entries);
5218 int at(int i) { return start_indexes_[i]; }
5219 int number_of_entries() { return start_indexes_[kGroupCount]; }
5221 int start_indexes_[kGroupCount + 1];
5224 bool Contains(DependencyGroup group, WeakCell* code_cell);
5226 static Handle<DependentCode> InsertCompilationDependencies(
5227 Handle<DependentCode> entries, DependencyGroup group,
5228 Handle<Foreign> info);
5230 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5231 DependencyGroup group,
5232 Handle<WeakCell> code_cell);
5234 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5235 WeakCell* code_cell);
5237 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5240 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5241 DependentCode::DependencyGroup group);
5243 bool MarkCodeForDeoptimization(Isolate* isolate,
5244 DependentCode::DependencyGroup group);
5246 // The following low-level accessors should only be used by this class
5247 // and the mark compact collector.
5248 inline int number_of_entries(DependencyGroup group);
5249 inline void set_number_of_entries(DependencyGroup group, int value);
5250 inline Object* object_at(int i);
5251 inline void set_object_at(int i, Object* object);
5252 inline void clear_at(int i);
5253 inline void copy(int from, int to);
5254 DECLARE_CAST(DependentCode)
5256 static const char* DependencyGroupName(DependencyGroup group);
5257 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5260 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5261 DependencyGroup group,
5262 Handle<Object> object);
5263 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5264 // Make a room at the end of the given group by moving out the first
5265 // code objects of the subsequent groups.
5266 inline void ExtendGroup(DependencyGroup group);
5267 // Compact by removing cleared weak cells and return true if there was
5268 // any cleared weak cell.
5270 static int Grow(int number_of_entries) {
5271 if (number_of_entries < 5) return number_of_entries + 1;
5272 return number_of_entries * 5 / 4;
5274 static const int kCodesStartIndex = kGroupCount;
5278 class PrototypeInfo;
5281 // All heap objects have a Map that describes their structure.
5282 // A Map contains information about:
5283 // - Size information about the object
5284 // - How to iterate over an object (for garbage collection)
5285 class Map: public HeapObject {
5288 // Size in bytes or kVariableSizeSentinel if instances do not have
5290 inline int instance_size();
5291 inline void set_instance_size(int value);
5293 // Only to clear an unused byte, remove once byte is used.
5294 inline void clear_unused();
5296 // [inobject_properties_or_constructor_function_index]: Provides access
5297 // to the inobject properties in case of JSObject maps, or the constructor
5298 // function index in case of primitive maps.
5299 inline int inobject_properties_or_constructor_function_index();
5300 inline void set_inobject_properties_or_constructor_function_index(int value);
5301 // Count of properties allocated in the object (JSObject only).
5302 inline int GetInObjectProperties();
5303 inline void SetInObjectProperties(int value);
5304 // Index of the constructor function in the native context (primitives only),
5305 // or the special sentinel value to indicate that there is no object wrapper
5306 // for the primitive (i.e. in case of null or undefined).
5307 static const int kNoConstructorFunctionIndex = 0;
5308 inline int GetConstructorFunctionIndex();
5309 inline void SetConstructorFunctionIndex(int value);
5312 inline InstanceType instance_type();
5313 inline void set_instance_type(InstanceType value);
5315 // Tells how many unused property fields are available in the
5316 // instance (only used for JSObject in fast mode).
5317 inline int unused_property_fields();
5318 inline void set_unused_property_fields(int value);
5321 inline byte bit_field() const;
5322 inline void set_bit_field(byte value);
5325 inline byte bit_field2() const;
5326 inline void set_bit_field2(byte value);
5329 inline uint32_t bit_field3() const;
5330 inline void set_bit_field3(uint32_t bits);
5332 class EnumLengthBits: public BitField<int,
5333 0, kDescriptorIndexBitCount> {}; // NOLINT
5334 class NumberOfOwnDescriptorsBits: public BitField<int,
5335 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5336 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5337 class DictionaryMap : public BitField<bool, 20, 1> {};
5338 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5339 class IsHiddenPrototype : public BitField<bool, 22, 1> {};
5340 class Deprecated : public BitField<bool, 23, 1> {};
5341 class IsUnstable : public BitField<bool, 24, 1> {};
5342 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5343 class IsStrong : public BitField<bool, 26, 1> {};
5346 // Keep this bit field at the very end for better code in
5347 // Builtins::kJSConstructStubGeneric stub.
5348 // This counter is used for in-object slack tracking and for map aging.
5349 // The in-object slack tracking is considered enabled when the counter is
5350 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5351 class Counter : public BitField<int, 28, 4> {};
5352 static const int kSlackTrackingCounterStart = 14;
5353 static const int kSlackTrackingCounterEnd = 8;
5354 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5355 static const int kRetainingCounterEnd = 0;
5357 // Tells whether the object in the prototype property will be used
5358 // for instances created from this function. If the prototype
5359 // property is set to a value that is not a JSObject, the prototype
5360 // property will not be used to create instances of the function.
5361 // See ECMA-262, 13.2.2.
5362 inline void set_non_instance_prototype(bool value);
5363 inline bool has_non_instance_prototype();
5365 // Tells whether function has special prototype property. If not, prototype
5366 // property will not be created when accessed (will return undefined),
5367 // and construction from this function will not be allowed.
5368 inline void set_function_with_prototype(bool value);
5369 inline bool function_with_prototype();
5371 // Tells whether the instance with this map should be ignored by the
5372 // Object.getPrototypeOf() function and the __proto__ accessor.
5373 inline void set_is_hidden_prototype();
5374 inline bool is_hidden_prototype() const;
5376 // Records and queries whether the instance has a named interceptor.
5377 inline void set_has_named_interceptor();
5378 inline bool has_named_interceptor();
5380 // Records and queries whether the instance has an indexed interceptor.
5381 inline void set_has_indexed_interceptor();
5382 inline bool has_indexed_interceptor();
5384 // Tells whether the instance is undetectable.
5385 // An undetectable object is a special class of JSObject: 'typeof' operator
5386 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5387 // a normal JS object. It is useful for implementing undetectable
5388 // document.all in Firefox & Safari.
5389 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5390 inline void set_is_undetectable();
5391 inline bool is_undetectable();
5393 // Tells whether the instance has a call-as-function handler.
5394 inline void set_is_observed();
5395 inline bool is_observed();
5397 // Tells whether the instance has a [[Call]] internal field.
5398 // This property is implemented according to ES6, section 7.2.3.
5399 inline void set_is_callable();
5400 inline bool is_callable() const;
5402 inline void set_is_strong();
5403 inline bool is_strong();
5404 inline void set_is_extensible(bool value);
5405 inline bool is_extensible();
5406 inline void set_is_prototype_map(bool value);
5407 inline bool is_prototype_map() const;
5409 inline void set_elements_kind(ElementsKind elements_kind);
5410 inline ElementsKind elements_kind();
5412 // Tells whether the instance has fast elements that are only Smis.
5413 inline bool has_fast_smi_elements();
5415 // Tells whether the instance has fast elements.
5416 inline bool has_fast_object_elements();
5417 inline bool has_fast_smi_or_object_elements();
5418 inline bool has_fast_double_elements();
5419 inline bool has_fast_elements();
5420 inline bool has_sloppy_arguments_elements();
5421 inline bool has_fixed_typed_array_elements();
5422 inline bool has_dictionary_elements();
5424 static bool IsValidElementsTransition(ElementsKind from_kind,
5425 ElementsKind to_kind);
5427 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5428 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5429 bool DictionaryElementsInPrototypeChainOnly();
5431 inline Map* ElementsTransitionMap();
5433 inline FixedArrayBase* GetInitialElements();
5435 // [raw_transitions]: Provides access to the transitions storage field.
5436 // Don't call set_raw_transitions() directly to overwrite transitions, use
5437 // the TransitionArray::ReplaceTransitions() wrapper instead!
5438 DECL_ACCESSORS(raw_transitions, Object)
5439 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5440 // (which prototype maps don't have).
5441 DECL_ACCESSORS(prototype_info, Object)
5442 // PrototypeInfo is created lazily using this helper (which installs it on
5443 // the given prototype's map).
5444 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5445 Handle<JSObject> prototype, Isolate* isolate);
5446 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5447 Handle<Map> prototype_map, Isolate* isolate);
5449 // [prototype chain validity cell]: Associated with a prototype object,
5450 // stored in that object's map's PrototypeInfo, indicates that prototype
5451 // chains through this object are currently valid. The cell will be
5452 // invalidated and replaced when the prototype chain changes.
5453 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5455 static const int kPrototypeChainValid = 0;
5456 static const int kPrototypeChainInvalid = 1;
5459 Map* FindFieldOwner(int descriptor);
5461 inline int GetInObjectPropertyOffset(int index);
5463 int NumberOfFields();
5465 // TODO(ishell): candidate with JSObject::MigrateToMap().
5466 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5467 int target_inobject, int target_unused,
5468 int* old_number_of_fields);
5469 // TODO(ishell): moveit!
5470 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5471 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5472 Representation rep1, Handle<HeapType> type1, Representation rep2,
5473 Handle<HeapType> type2, Isolate* isolate);
5474 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5475 Representation new_representation,
5476 Handle<HeapType> new_field_type);
5477 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5478 PropertyKind new_kind,
5479 PropertyAttributes new_attributes,
5480 Representation new_representation,
5481 Handle<HeapType> new_field_type,
5482 StoreMode store_mode);
5483 static Handle<Map> CopyGeneralizeAllRepresentations(
5484 Handle<Map> map, int modify_index, StoreMode store_mode,
5485 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5487 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5488 int descriptor_number,
5489 Handle<Object> value);
5491 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5492 const char* reason);
5494 // Returns the constructor name (the name (possibly, inferred name) of the
5495 // function that was used to instantiate the object).
5496 String* constructor_name();
5498 // Tells whether the map is used for JSObjects in dictionary mode (ie
5499 // normalized objects, ie objects for which HasFastProperties returns false).
5500 // A map can never be used for both dictionary mode and fast mode JSObjects.
5501 // False by default and for HeapObjects that are not JSObjects.
5502 inline void set_dictionary_map(bool value);
5503 inline bool is_dictionary_map();
5505 // Tells whether the instance needs security checks when accessing its
5507 inline void set_is_access_check_needed(bool access_check_needed);
5508 inline bool is_access_check_needed();
5510 // Returns true if map has a non-empty stub code cache.
5511 inline bool has_code_cache();
5513 // [prototype]: implicit prototype object.
5514 DECL_ACCESSORS(prototype, Object)
5515 // TODO(jkummerow): make set_prototype private.
5516 static void SetPrototype(
5517 Handle<Map> map, Handle<Object> prototype,
5518 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5520 // [constructor]: points back to the function responsible for this map.
5521 // The field overlaps with the back pointer. All maps in a transition tree
5522 // have the same constructor, so maps with back pointers can walk the
5523 // back pointer chain until they find the map holding their constructor.
5524 DECL_ACCESSORS(constructor_or_backpointer, Object)
5525 inline Object* GetConstructor() const;
5526 inline void SetConstructor(Object* constructor,
5527 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5528 // [back pointer]: points back to the parent map from which a transition
5529 // leads to this map. The field overlaps with the constructor (see above).
5530 inline Object* GetBackPointer();
5531 inline void SetBackPointer(Object* value,
5532 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5534 // [instance descriptors]: describes the object.
5535 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5537 // [layout descriptor]: describes the object layout.
5538 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5539 // |layout descriptor| accessor which can be used from GC.
5540 inline LayoutDescriptor* layout_descriptor_gc_safe();
5541 inline bool HasFastPointerLayout() const;
5543 // |layout descriptor| accessor that is safe to call even when
5544 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5545 // |layout_descriptor| field at all).
5546 inline LayoutDescriptor* GetLayoutDescriptor();
5548 inline void UpdateDescriptors(DescriptorArray* descriptors,
5549 LayoutDescriptor* layout_descriptor);
5550 inline void InitializeDescriptors(DescriptorArray* descriptors,
5551 LayoutDescriptor* layout_descriptor);
5553 // [stub cache]: contains stubs compiled for this map.
5554 DECL_ACCESSORS(code_cache, Object)
5556 // [dependent code]: list of optimized codes that weakly embed this map.
5557 DECL_ACCESSORS(dependent_code, DependentCode)
5559 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5560 DECL_ACCESSORS(weak_cell_cache, Object)
5562 inline PropertyDetails GetLastDescriptorDetails();
5564 inline int LastAdded();
5566 inline int NumberOfOwnDescriptors();
5567 inline void SetNumberOfOwnDescriptors(int number);
5569 inline Cell* RetrieveDescriptorsPointer();
5571 inline int EnumLength();
5572 inline void SetEnumLength(int length);
5574 inline bool owns_descriptors();
5575 inline void set_owns_descriptors(bool owns_descriptors);
5576 inline void mark_unstable();
5577 inline bool is_stable();
5578 inline void set_migration_target(bool value);
5579 inline bool is_migration_target();
5580 inline void set_counter(int value);
5581 inline int counter();
5582 inline void deprecate();
5583 inline bool is_deprecated();
5584 inline bool CanBeDeprecated();
5585 // Returns a non-deprecated version of the input. If the input was not
5586 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5587 // is found by re-transitioning from the root of the transition tree using the
5588 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5590 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5592 // Returns a non-deprecated version of the input. This method may deprecate
5593 // existing maps along the way if encodings conflict. Not for use while
5594 // gathering type feedback. Use TryUpdate in those cases instead.
5595 static Handle<Map> Update(Handle<Map> map);
5597 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5598 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5599 Descriptor* descriptor,
5600 TransitionFlag flag);
5602 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5605 Handle<HeapType> type,
5606 PropertyAttributes attributes,
5607 Representation representation,
5608 TransitionFlag flag);
5610 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5613 Handle<Object> constant,
5614 PropertyAttributes attributes,
5615 TransitionFlag flag);
5617 // Returns a new map with all transitions dropped from the given map and
5618 // the ElementsKind set.
5619 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5620 ElementsKind to_kind);
5622 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5624 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5626 TransitionFlag flag);
5628 static Handle<Map> CopyForObserved(Handle<Map> map);
5630 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5631 PropertyAttributes attrs_to_add,
5632 Handle<Symbol> transition_marker,
5633 const char* reason);
5635 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5638 // Maximal number of fast properties. Used to restrict the number of map
5639 // transitions to avoid an explosion in the number of maps for objects used as
5641 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5642 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5644 Handle<Object> value,
5645 PropertyAttributes attributes,
5646 StoreFromKeyed store_mode);
5647 static Handle<Map> TransitionToAccessorProperty(
5648 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5649 Handle<Object> accessor, PropertyAttributes attributes);
5650 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5653 PropertyAttributes attributes);
5655 inline void AppendDescriptor(Descriptor* desc);
5657 // Returns a copy of the map, prepared for inserting into the transition
5658 // tree (if the |map| owns descriptors then the new one will share
5659 // descriptors with |map|).
5660 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5662 // Returns a copy of the map, with all transitions dropped from the
5663 // instance descriptors.
5664 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5665 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5667 // Returns the next free property index (only valid for FAST MODE).
5668 int NextFreePropertyIndex();
5670 // Returns the number of properties described in instance_descriptors
5671 // filtering out properties with the specified attributes.
5672 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5673 PropertyAttributes filter = NONE);
5677 // Code cache operations.
5679 // Clears the code cache.
5680 inline void ClearCodeCache(Heap* heap);
5682 // Update code cache.
5683 static void UpdateCodeCache(Handle<Map> map,
5687 // Extend the descriptor array of the map with the list of descriptors.
5688 // In case of duplicates, the latest descriptor is used.
5689 static void AppendCallbackDescriptors(Handle<Map> map,
5690 Handle<Object> descriptors);
5692 static inline int SlackForArraySize(int old_size, int size_limit);
5694 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5696 // Returns the found code or undefined if absent.
5697 Object* FindInCodeCache(Name* name, Code::Flags flags);
5699 // Returns the non-negative index of the code object if it is in the
5700 // cache and -1 otherwise.
5701 int IndexInCodeCache(Object* name, Code* code);
5703 // Removes a code object from the code cache at the given index.
5704 void RemoveFromCodeCache(Name* name, Code* code, int index);
5706 // Computes a hash value for this map, to be used in HashTables and such.
5709 // Returns the map that this map transitions to if its elements_kind
5710 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5711 // |safe_to_add_transitions| is set to false if adding transitions is not
5713 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5715 // Returns the transitioned map for this map with the most generic
5716 // elements_kind that's found in |candidates|, or null handle if no match is
5718 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5719 MapHandleList* candidates);
5721 inline bool CanTransition();
5723 inline bool IsPrimitiveMap();
5724 inline bool IsJSObjectMap();
5725 inline bool IsJSArrayMap();
5726 inline bool IsStringMap();
5727 inline bool IsJSProxyMap();
5728 inline bool IsJSGlobalProxyMap();
5729 inline bool IsJSGlobalObjectMap();
5730 inline bool IsGlobalObjectMap();
5732 inline bool CanOmitMapChecks();
5734 static void AddDependentCode(Handle<Map> map,
5735 DependentCode::DependencyGroup group,
5738 bool IsMapInArrayPrototypeChain();
5740 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5742 // Dispatched behavior.
5743 DECLARE_PRINTER(Map)
5744 DECLARE_VERIFIER(Map)
5747 void DictionaryMapVerify();
5748 void VerifyOmittedMapChecks();
5751 inline int visitor_id();
5752 inline void set_visitor_id(int visitor_id);
5754 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5755 Handle<Object> prototype,
5756 PrototypeOptimizationMode mode);
5758 static const int kMaxPreAllocatedPropertyFields = 255;
5760 // Layout description.
5761 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5762 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5763 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5764 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5765 static const int kConstructorOrBackPointerOffset =
5766 kPrototypeOffset + kPointerSize;
5767 // When there is only one transition, it is stored directly in this field;
5768 // otherwise a transition array is used.
5769 // For prototype maps, this slot is used to store this map's PrototypeInfo
5771 static const int kTransitionsOrPrototypeInfoOffset =
5772 kConstructorOrBackPointerOffset + kPointerSize;
5773 static const int kDescriptorsOffset =
5774 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5775 #if V8_DOUBLE_FIELDS_UNBOXING
5776 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5777 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5779 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5780 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5782 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5783 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5784 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5786 // Layout of pointer fields. Heap iteration code relies on them
5787 // being continuously allocated.
5788 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5789 static const int kPointerFieldsEndOffset = kSize;
5791 // Byte offsets within kInstanceSizesOffset.
5792 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5793 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5794 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5795 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5796 // Note there is one byte available for use here.
5797 static const int kUnusedByte = 2;
5798 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5799 static const int kVisitorIdByte = 3;
5800 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5802 // Byte offsets within kInstanceAttributesOffset attributes.
5803 #if V8_TARGET_LITTLE_ENDIAN
5804 // Order instance type and bit field together such that they can be loaded
5805 // together as a 16-bit word with instance type in the lower 8 bits regardless
5806 // of endianess. Also provide endian-independent offset to that 16-bit word.
5807 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5808 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5810 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5811 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5813 static const int kInstanceTypeAndBitFieldOffset =
5814 kInstanceAttributesOffset + 0;
5815 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5816 static const int kUnusedPropertyFieldsByte = 3;
5817 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5819 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5820 Internals::kMapInstanceTypeAndBitFieldOffset);
5822 // Bit positions for bit field.
5823 static const int kHasNonInstancePrototype = 0;
5824 static const int kIsCallable = 1;
5825 static const int kHasNamedInterceptor = 2;
5826 static const int kHasIndexedInterceptor = 3;
5827 static const int kIsUndetectable = 4;
5828 static const int kIsObserved = 5;
5829 static const int kIsAccessCheckNeeded = 6;
5830 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5832 // Bit positions for bit field 2
5833 static const int kIsExtensible = 0;
5835 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5836 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5838 // Derived values from bit field 2
5839 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5840 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5841 static const int8_t kMaximumBitField2FastSmiElementValue =
5842 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5843 Map::ElementsKindBits::kShift) - 1;
5844 static const int8_t kMaximumBitField2FastHoleyElementValue =
5845 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5846 Map::ElementsKindBits::kShift) - 1;
5847 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5848 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5849 Map::ElementsKindBits::kShift) - 1;
5851 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5852 kPointerFieldsEndOffset,
5853 kSize> BodyDescriptor;
5855 // Compares this map to another to see if they describe equivalent objects.
5856 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5857 // it had exactly zero inobject properties.
5858 // The "shared" flags of both this map and |other| are ignored.
5859 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5861 // Returns true if given field is unboxed double.
5862 inline bool IsUnboxedDoubleField(FieldIndex index);
5865 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5866 static void TraceAllTransitions(Map* map);
5869 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5870 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5871 Handle<LayoutDescriptor> layout_descriptor);
5874 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5875 Handle<Name> name, SimpleTransitionFlag flag);
5877 bool EquivalentToForTransition(Map* other);
5878 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5879 static Handle<Map> ShareDescriptor(Handle<Map> map,
5880 Handle<DescriptorArray> descriptors,
5881 Descriptor* descriptor);
5882 static Handle<Map> CopyInstallDescriptors(
5883 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5884 Handle<LayoutDescriptor> layout_descriptor);
5885 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5886 Descriptor* descriptor,
5887 TransitionFlag flag);
5888 static Handle<Map> CopyReplaceDescriptors(
5889 Handle<Map> map, Handle<DescriptorArray> descriptors,
5890 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5891 MaybeHandle<Name> maybe_name, const char* reason,
5892 SimpleTransitionFlag simple_flag);
5894 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5895 Handle<DescriptorArray> descriptors,
5896 Descriptor* descriptor,
5898 TransitionFlag flag);
5899 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5900 Handle<Map> map, int descriptor, PropertyKind kind,
5901 PropertyAttributes attributes, const char** reason);
5903 static Handle<Map> CopyNormalized(Handle<Map> map,
5904 PropertyNormalizationMode mode);
5906 // Fires when the layout of an object with a leaf map changes.
5907 // This includes adding transitions to the leaf map or changing
5908 // the descriptor array.
5909 inline void NotifyLeafMapLayoutChange();
5911 void DeprecateTransitionTree();
5912 bool DeprecateTarget(PropertyKind kind, Name* key,
5913 PropertyAttributes attributes,
5914 DescriptorArray* new_descriptors,
5915 LayoutDescriptor* new_layout_descriptor);
5917 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5919 // Update field type of the given descriptor to new representation and new
5920 // type. The type must be prepared for storing in descriptor array:
5921 // it must be either a simple type or a map wrapped in a weak cell.
5922 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5923 Representation new_representation,
5924 Handle<Object> new_wrapped_type);
5926 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5927 PropertyAttributes attributes);
5928 void PrintGeneralization(FILE* file,
5933 bool constant_to_field,
5934 Representation old_representation,
5935 Representation new_representation,
5936 HeapType* old_field_type,
5937 HeapType* new_field_type);
5939 static const int kFastPropertiesSoftLimit = 12;
5940 static const int kMaxFastProperties = 128;
5942 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5946 // An abstract superclass, a marker class really, for simple structure classes.
5947 // It doesn't carry much functionality but allows struct classes to be
5948 // identified in the type system.
5949 class Struct: public HeapObject {
5951 inline void InitializeBody(int object_size);
5952 DECLARE_CAST(Struct)
5956 // A simple one-element struct, useful where smis need to be boxed.
5957 class Box : public Struct {
5959 // [value]: the boxed contents.
5960 DECL_ACCESSORS(value, Object)
5964 // Dispatched behavior.
5965 DECLARE_PRINTER(Box)
5966 DECLARE_VERIFIER(Box)
5968 static const int kValueOffset = HeapObject::kHeaderSize;
5969 static const int kSize = kValueOffset + kPointerSize;
5972 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5976 // Container for metadata stored on each prototype map.
5977 class PrototypeInfo : public Struct {
5979 static const int UNREGISTERED = -1;
5981 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5982 // or Smi(0) if uninitialized.
5983 DECL_ACCESSORS(prototype_users, Object)
5984 // [registry_slot]: Slot in prototype's user registry where this user
5985 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5986 inline int registry_slot() const;
5987 inline void set_registry_slot(int slot);
5988 // [validity_cell]: Cell containing the validity bit for prototype chains
5989 // going through this object, or Smi(0) if uninitialized.
5990 DECL_ACCESSORS(validity_cell, Object)
5991 // [constructor_name]: User-friendly name of the original constructor.
5992 DECL_ACCESSORS(constructor_name, Object)
5994 DECLARE_CAST(PrototypeInfo)
5996 // Dispatched behavior.
5997 DECLARE_PRINTER(PrototypeInfo)
5998 DECLARE_VERIFIER(PrototypeInfo)
6000 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6001 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
6002 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
6003 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6004 static const int kSize = kConstructorNameOffset + kPointerSize;
6007 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6011 // Pair used to store both a ScopeInfo and an extension object in the extension
6012 // slot of a block context. Needed in the rare case where a declaration block
6013 // scope (a "varblock" as used to desugar parameter destructuring) also contains
6014 // a sloppy direct eval. (In no other case both are needed at the same time.)
6015 class SloppyBlockWithEvalContextExtension : public Struct {
6017 // [scope_info]: Scope info.
6018 DECL_ACCESSORS(scope_info, ScopeInfo)
6019 // [extension]: Extension object.
6020 DECL_ACCESSORS(extension, JSObject)
6022 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
6024 // Dispatched behavior.
6025 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
6026 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
6028 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
6029 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
6030 static const int kSize = kExtensionOffset + kPointerSize;
6033 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
6037 // Script describes a script which has been added to the VM.
6038 class Script: public Struct {
6047 // Script compilation types.
6048 enum CompilationType {
6049 COMPILATION_TYPE_HOST = 0,
6050 COMPILATION_TYPE_EVAL = 1
6053 // Script compilation state.
6054 enum CompilationState {
6055 COMPILATION_STATE_INITIAL = 0,
6056 COMPILATION_STATE_COMPILED = 1
6059 // [source]: the script source.
6060 DECL_ACCESSORS(source, Object)
6062 // [name]: the script name.
6063 DECL_ACCESSORS(name, Object)
6065 // [id]: the script id.
6066 DECL_ACCESSORS(id, Smi)
6068 // [line_offset]: script line offset in resource from where it was extracted.
6069 DECL_ACCESSORS(line_offset, Smi)
6071 // [column_offset]: script column offset in resource from where it was
6073 DECL_ACCESSORS(column_offset, Smi)
6075 // [context_data]: context data for the context this script was compiled in.
6076 DECL_ACCESSORS(context_data, Object)
6078 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6079 DECL_ACCESSORS(wrapper, HeapObject)
6081 // [type]: the script type.
6082 DECL_ACCESSORS(type, Smi)
6084 // [line_ends]: FixedArray of line ends positions.
6085 DECL_ACCESSORS(line_ends, Object)
6087 // [eval_from_shared]: for eval scripts the shared funcion info for the
6088 // function from which eval was called.
6089 DECL_ACCESSORS(eval_from_shared, Object)
6091 // [eval_from_instructions_offset]: the instruction offset in the code for the
6092 // function from which eval was called where eval was called.
6093 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6095 // [shared_function_infos]: weak fixed array containing all shared
6096 // function infos created from this script.
6097 DECL_ACCESSORS(shared_function_infos, Object)
6099 // [flags]: Holds an exciting bitfield.
6100 DECL_ACCESSORS(flags, Smi)
6102 // [source_url]: sourceURL from magic comment
6103 DECL_ACCESSORS(source_url, Object)
6105 // [source_url]: sourceMappingURL magic comment
6106 DECL_ACCESSORS(source_mapping_url, Object)
6108 // [compilation_type]: how the the script was compiled. Encoded in the
6110 inline CompilationType compilation_type();
6111 inline void set_compilation_type(CompilationType type);
6113 // [compilation_state]: determines whether the script has already been
6114 // compiled. Encoded in the 'flags' field.
6115 inline CompilationState compilation_state();
6116 inline void set_compilation_state(CompilationState state);
6118 // [hide_source]: determines whether the script source can be exposed as
6119 // function source. Encoded in the 'flags' field.
6120 inline bool hide_source();
6121 inline void set_hide_source(bool value);
6123 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6124 // and used by the embedder to make decisions about the script. V8 just passes
6125 // this through. Encoded in the 'flags' field.
6126 inline v8::ScriptOriginOptions origin_options();
6127 inline void set_origin_options(ScriptOriginOptions origin_options);
6129 DECLARE_CAST(Script)
6131 // If script source is an external string, check that the underlying
6132 // resource is accessible. Otherwise, always return true.
6133 inline bool HasValidSource();
6135 // Convert code position into column number.
6136 static int GetColumnNumber(Handle<Script> script, int code_pos);
6138 // Convert code position into (zero-based) line number.
6139 // The non-handlified version does not allocate, but may be much slower.
6140 static int GetLineNumber(Handle<Script> script, int code_pos);
6141 int GetLineNumber(int code_pos);
6143 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6145 // Init line_ends array with code positions of line ends inside script source.
6146 static void InitLineEnds(Handle<Script> script);
6148 // Get the JS object wrapping the given script; create it if none exists.
6149 static Handle<JSObject> GetWrapper(Handle<Script> script);
6151 // Look through the list of existing shared function infos to find one
6152 // that matches the function literal. Return empty handle if not found.
6153 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6155 // Iterate over all script objects on the heap.
6158 explicit Iterator(Isolate* isolate);
6162 WeakFixedArray::Iterator iterator_;
6163 DISALLOW_COPY_AND_ASSIGN(Iterator);
6166 // Dispatched behavior.
6167 DECLARE_PRINTER(Script)
6168 DECLARE_VERIFIER(Script)
6170 static const int kSourceOffset = HeapObject::kHeaderSize;
6171 static const int kNameOffset = kSourceOffset + kPointerSize;
6172 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6173 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6174 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6175 static const int kWrapperOffset = kContextOffset + kPointerSize;
6176 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6177 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6178 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6179 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6180 static const int kEvalFrominstructionsOffsetOffset =
6181 kEvalFromSharedOffset + kPointerSize;
6182 static const int kSharedFunctionInfosOffset =
6183 kEvalFrominstructionsOffsetOffset + kPointerSize;
6184 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6185 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6186 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6187 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6190 int GetLineNumberWithArray(int code_pos);
6192 // Bit positions in the flags field.
6193 static const int kCompilationTypeBit = 0;
6194 static const int kCompilationStateBit = 1;
6195 static const int kHideSourceBit = 2;
6196 static const int kOriginOptionsShift = 3;
6197 static const int kOriginOptionsSize = 3;
6198 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6199 << kOriginOptionsShift;
6201 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6205 // List of builtin functions we want to identify to improve code
6208 // Each entry has a name of a global object property holding an object
6209 // optionally followed by ".prototype", a name of a builtin function
6210 // on the object (the one the id is set for), and a label.
6212 // Installation of ids for the selected builtin functions is handled
6213 // by the bootstrapper.
6214 #define FUNCTIONS_WITH_ID_LIST(V) \
6215 V(Array.prototype, indexOf, ArrayIndexOf) \
6216 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6217 V(Array.prototype, push, ArrayPush) \
6218 V(Array.prototype, pop, ArrayPop) \
6219 V(Array.prototype, shift, ArrayShift) \
6220 V(Function.prototype, apply, FunctionApply) \
6221 V(Function.prototype, call, FunctionCall) \
6222 V(String.prototype, charCodeAt, StringCharCodeAt) \
6223 V(String.prototype, charAt, StringCharAt) \
6224 V(String, fromCharCode, StringFromCharCode) \
6225 V(Math, random, MathRandom) \
6226 V(Math, floor, MathFloor) \
6227 V(Math, round, MathRound) \
6228 V(Math, ceil, MathCeil) \
6229 V(Math, abs, MathAbs) \
6230 V(Math, log, MathLog) \
6231 V(Math, exp, MathExp) \
6232 V(Math, sqrt, MathSqrt) \
6233 V(Math, pow, MathPow) \
6234 V(Math, max, MathMax) \
6235 V(Math, min, MathMin) \
6236 V(Math, cos, MathCos) \
6237 V(Math, sin, MathSin) \
6238 V(Math, tan, MathTan) \
6239 V(Math, acos, MathAcos) \
6240 V(Math, asin, MathAsin) \
6241 V(Math, atan, MathAtan) \
6242 V(Math, atan2, MathAtan2) \
6243 V(Math, imul, MathImul) \
6244 V(Math, clz32, MathClz32) \
6245 V(Math, fround, MathFround)
6247 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6248 V(Atomics, load, AtomicsLoad) \
6249 V(Atomics, store, AtomicsStore)
6251 enum BuiltinFunctionId {
6253 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6255 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6256 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6257 #undef DECLARE_FUNCTION_ID
6258 // Fake id for a special case of Math.pow. Note, it continues the
6259 // list of math functions.
6264 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6265 // that both {code} and {literals} can be NULL to pass search result status.
6266 struct CodeAndLiterals {
6267 Code* code; // Cached optimized code.
6268 FixedArray* literals; // Cached literals array.
6272 // SharedFunctionInfo describes the JSFunction information that can be
6273 // shared by multiple instances of the function.
6274 class SharedFunctionInfo: public HeapObject {
6276 // [name]: Function name.
6277 DECL_ACCESSORS(name, Object)
6279 // [code]: Function code.
6280 DECL_ACCESSORS(code, Code)
6281 inline void ReplaceCode(Code* code);
6283 // [optimized_code_map]: Map from native context to optimized code
6284 // and a shared literals array or Smi(0) if none.
6285 DECL_ACCESSORS(optimized_code_map, Object)
6287 // Returns entry from optimized code map for specified context and OSR entry.
6288 // Note that {code == nullptr, literals == nullptr} indicates no matching
6289 // entry has been found, whereas {code, literals == nullptr} indicates that
6290 // code is context-independent.
6291 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6292 BailoutId osr_ast_id);
6294 // Clear optimized code map.
6295 void ClearOptimizedCodeMap();
6297 // Removes a specific optimized code object from the optimized code map.
6298 // In case of non-OSR the code reference is cleared from the cache entry but
6299 // the entry itself is left in the map in order to proceed sharing literals.
6300 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6302 // Trims the optimized code map after entries have been removed.
6303 void TrimOptimizedCodeMap(int shrink_by);
6305 // Add a new entry to the optimized code map for context-independent code.
6306 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6309 // Add a new entry to the optimized code map for context-dependent code.
6310 // |code| is either a code object or an undefined value. In the latter case
6311 // the entry just maps |native_context, osr_ast_id| pair to |literals| array.
6312 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6313 Handle<Context> native_context,
6314 Handle<HeapObject> code,
6315 Handle<FixedArray> literals,
6316 BailoutId osr_ast_id);
6318 // Set up the link between shared function info and the script. The shared
6319 // function info is added to the list on the script.
6320 static void SetScript(Handle<SharedFunctionInfo> shared,
6321 Handle<Object> script_object);
6323 // Layout description of the optimized code map.
6324 static const int kNextMapIndex = 0;
6325 static const int kSharedCodeIndex = 1;
6326 static const int kEntriesStart = 2;
6327 static const int kContextOffset = 0;
6328 static const int kCachedCodeOffset = 1;
6329 static const int kLiteralsOffset = 2;
6330 static const int kOsrAstIdOffset = 3;
6331 static const int kEntryLength = 4;
6332 static const int kInitialLength = kEntriesStart + kEntryLength;
6334 static const int kNotFound = -1;
6336 // [scope_info]: Scope info.
6337 DECL_ACCESSORS(scope_info, ScopeInfo)
6339 // [construct stub]: Code stub for constructing instances of this function.
6340 DECL_ACCESSORS(construct_stub, Code)
6342 // Returns if this function has been compiled to native code yet.
6343 inline bool is_compiled();
6345 // [length]: The function length - usually the number of declared parameters.
6346 // Use up to 2^30 parameters.
6347 inline int length() const;
6348 inline void set_length(int value);
6350 // [internal formal parameter count]: The declared number of parameters.
6351 // For subclass constructors, also includes new.target.
6352 // The size of function's frame is internal_formal_parameter_count + 1.
6353 inline int internal_formal_parameter_count() const;
6354 inline void set_internal_formal_parameter_count(int value);
6356 // Set the formal parameter count so the function code will be
6357 // called without using argument adaptor frames.
6358 inline void DontAdaptArguments();
6360 // [expected_nof_properties]: Expected number of properties for the function.
6361 inline int expected_nof_properties() const;
6362 inline void set_expected_nof_properties(int value);
6364 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6365 // (increasingly) from crankshafted code where sufficient feedback isn't
6367 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6369 // Unconditionally clear the type feedback vector (including vector ICs).
6370 void ClearTypeFeedbackInfo();
6372 // Clear the type feedback vector with a more subtle policy at GC time.
6373 void ClearTypeFeedbackInfoAtGCTime();
6376 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6377 // even if the GC moves this SharedFunctionInfo.
6378 inline int unique_id() const;
6379 inline void set_unique_id(int value);
6382 // [instance class name]: class name for instances.
6383 DECL_ACCESSORS(instance_class_name, Object)
6385 // [function data]: This field holds some additional data for function.
6386 // Currently it has one of:
6387 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6388 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6389 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6390 // In the long run we don't want all functions to have this field but
6391 // we can fix that when we have a better model for storing hidden data
6393 DECL_ACCESSORS(function_data, Object)
6395 inline bool IsApiFunction();
6396 inline FunctionTemplateInfo* get_api_func_data();
6397 inline bool HasBuiltinFunctionId();
6398 inline BuiltinFunctionId builtin_function_id();
6399 inline bool HasBytecodeArray();
6400 inline BytecodeArray* bytecode_array();
6402 // [script info]: Script from which the function originates.
6403 DECL_ACCESSORS(script, Object)
6405 // [num_literals]: Number of literals used by this function.
6406 inline int num_literals() const;
6407 inline void set_num_literals(int value);
6409 // [start_position_and_type]: Field used to store both the source code
6410 // position, whether or not the function is a function expression,
6411 // and whether or not the function is a toplevel function. The two
6412 // least significants bit indicates whether the function is an
6413 // expression and the rest contains the source code position.
6414 inline int start_position_and_type() const;
6415 inline void set_start_position_and_type(int value);
6417 // The function is subject to debugging if a debug info is attached.
6418 inline bool HasDebugInfo();
6419 inline DebugInfo* GetDebugInfo();
6421 // A function has debug code if the compiled code has debug break slots.
6422 inline bool HasDebugCode();
6424 // [debug info]: Debug information.
6425 DECL_ACCESSORS(debug_info, Object)
6427 // [inferred name]: Name inferred from variable or property
6428 // assignment of this function. Used to facilitate debugging and
6429 // profiling of JavaScript code written in OO style, where almost
6430 // all functions are anonymous but are assigned to object
6432 DECL_ACCESSORS(inferred_name, String)
6434 // The function's name if it is non-empty, otherwise the inferred name.
6435 String* DebugName();
6437 // Position of the 'function' token in the script source.
6438 inline int function_token_position() const;
6439 inline void set_function_token_position(int function_token_position);
6441 // Position of this function in the script source.
6442 inline int start_position() const;
6443 inline void set_start_position(int start_position);
6445 // End position of this function in the script source.
6446 inline int end_position() const;
6447 inline void set_end_position(int end_position);
6449 // Is this function a function expression in the source code.
6450 DECL_BOOLEAN_ACCESSORS(is_expression)
6452 // Is this function a top-level function (scripts, evals).
6453 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6455 // Bit field containing various information collected by the compiler to
6456 // drive optimization.
6457 inline int compiler_hints() const;
6458 inline void set_compiler_hints(int value);
6460 inline int ast_node_count() const;
6461 inline void set_ast_node_count(int count);
6463 inline int profiler_ticks() const;
6464 inline void set_profiler_ticks(int ticks);
6466 // Inline cache age is used to infer whether the function survived a context
6467 // disposal or not. In the former case we reset the opt_count.
6468 inline int ic_age();
6469 inline void set_ic_age(int age);
6471 // Indicates if this function can be lazy compiled.
6472 // This is used to determine if we can safely flush code from a function
6473 // when doing GC if we expect that the function will no longer be used.
6474 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6476 // Indicates if this function can be lazy compiled without a context.
6477 // This is used to determine if we can force compilation without reaching
6478 // the function through program execution but through other means (e.g. heap
6479 // iteration by the debugger).
6480 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6482 // Indicates whether optimizations have been disabled for this
6483 // shared function info. If a function is repeatedly optimized or if
6484 // we cannot optimize the function we disable optimization to avoid
6485 // spending time attempting to optimize it again.
6486 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6488 // Indicates the language mode.
6489 inline LanguageMode language_mode();
6490 inline void set_language_mode(LanguageMode language_mode);
6492 // False if the function definitely does not allocate an arguments object.
6493 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6495 // Indicates that this function uses a super property (or an eval that may
6496 // use a super property).
6497 // This is needed to set up the [[HomeObject]] on the function instance.
6498 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6500 // True if the function has any duplicated parameter names.
6501 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6503 // Indicates whether the function is a native function.
6504 // These needs special treatment in .call and .apply since
6505 // null passed as the receiver should not be translated to the
6507 DECL_BOOLEAN_ACCESSORS(native)
6509 // Indicate that this function should always be inlined in optimized code.
6510 DECL_BOOLEAN_ACCESSORS(force_inline)
6512 // Indicates that the function was created by the Function function.
6513 // Though it's anonymous, toString should treat it as if it had the name
6514 // "anonymous". We don't set the name itself so that the system does not
6515 // see a binding for it.
6516 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6518 // Indicates whether the function is a bound function created using
6519 // the bind function.
6520 DECL_BOOLEAN_ACCESSORS(bound)
6522 // Indicates that the function is anonymous (the name field can be set
6523 // through the API, which does not change this flag).
6524 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6526 // Is this a function or top-level/eval code.
6527 DECL_BOOLEAN_ACCESSORS(is_function)
6529 // Indicates that code for this function cannot be compiled with Crankshaft.
6530 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6532 // Indicates that code for this function cannot be flushed.
6533 DECL_BOOLEAN_ACCESSORS(dont_flush)
6535 // Indicates that this function is a generator.
6536 DECL_BOOLEAN_ACCESSORS(is_generator)
6538 // Indicates that this function is an arrow function.
6539 DECL_BOOLEAN_ACCESSORS(is_arrow)
6541 // Indicates that this function is a concise method.
6542 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6544 // Indicates that this function is an accessor (getter or setter).
6545 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6547 // Indicates that this function is a default constructor.
6548 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6550 // Indicates that this function is an asm function.
6551 DECL_BOOLEAN_ACCESSORS(asm_function)
6553 // Indicates that the the shared function info is deserialized from cache.
6554 DECL_BOOLEAN_ACCESSORS(deserialized)
6556 // Indicates that the the shared function info has never been compiled before.
6557 DECL_BOOLEAN_ACCESSORS(never_compiled)
6559 inline FunctionKind kind();
6560 inline void set_kind(FunctionKind kind);
6562 // Indicates whether or not the code in the shared function support
6564 inline bool has_deoptimization_support();
6566 // Enable deoptimization support through recompiled code.
6567 void EnableDeoptimizationSupport(Code* recompiled);
6569 // Disable (further) attempted optimization of all functions sharing this
6570 // shared function info.
6571 void DisableOptimization(BailoutReason reason);
6573 inline BailoutReason disable_optimization_reason();
6575 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6576 // code, returns whether it asserted (i.e., always true if assertions are
6578 bool VerifyBailoutId(BailoutId id);
6580 // [source code]: Source code for the function.
6581 bool HasSourceCode() const;
6582 Handle<Object> GetSourceCode();
6584 // Number of times the function was optimized.
6585 inline int opt_count();
6586 inline void set_opt_count(int opt_count);
6588 // Number of times the function was deoptimized.
6589 inline void set_deopt_count(int value);
6590 inline int deopt_count();
6591 inline void increment_deopt_count();
6593 // Number of time we tried to re-enable optimization after it
6594 // was disabled due to high number of deoptimizations.
6595 inline void set_opt_reenable_tries(int value);
6596 inline int opt_reenable_tries();
6598 inline void TryReenableOptimization();
6600 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6601 inline void set_counters(int value);
6602 inline int counters() const;
6604 // Stores opt_count and bailout_reason as bit-fields.
6605 inline void set_opt_count_and_bailout_reason(int value);
6606 inline int opt_count_and_bailout_reason() const;
6608 inline void set_disable_optimization_reason(BailoutReason reason);
6610 // Tells whether this function should be subject to debugging.
6611 inline bool IsSubjectToDebugging();
6613 // Whether this function is defined in native code or extensions.
6614 inline bool IsBuiltin();
6616 // Check whether or not this function is inlineable.
6617 bool IsInlineable();
6619 // Source size of this function.
6622 // Calculate the instance size.
6623 int CalculateInstanceSize();
6625 // Calculate the number of in-object properties.
6626 int CalculateInObjectProperties();
6628 inline bool has_simple_parameters();
6630 // Initialize a SharedFunctionInfo from a parsed function literal.
6631 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6632 FunctionLiteral* lit);
6634 // Dispatched behavior.
6635 DECLARE_PRINTER(SharedFunctionInfo)
6636 DECLARE_VERIFIER(SharedFunctionInfo)
6638 void ResetForNewContext(int new_ic_age);
6640 // Iterate over all shared function infos that are created from a script.
6641 // That excludes shared function infos created for API functions and C++
6645 explicit Iterator(Isolate* isolate);
6646 SharedFunctionInfo* Next();
6651 Script::Iterator script_iterator_;
6652 WeakFixedArray::Iterator sfi_iterator_;
6653 DisallowHeapAllocation no_gc_;
6654 DISALLOW_COPY_AND_ASSIGN(Iterator);
6657 DECLARE_CAST(SharedFunctionInfo)
6660 static const int kDontAdaptArgumentsSentinel = -1;
6662 // Layout description.
6664 static const int kNameOffset = HeapObject::kHeaderSize;
6665 static const int kCodeOffset = kNameOffset + kPointerSize;
6666 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6667 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6668 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6669 static const int kInstanceClassNameOffset =
6670 kConstructStubOffset + kPointerSize;
6671 static const int kFunctionDataOffset =
6672 kInstanceClassNameOffset + kPointerSize;
6673 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6674 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6675 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6676 static const int kFeedbackVectorOffset =
6677 kInferredNameOffset + kPointerSize;
6679 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6680 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6682 // Just to not break the postmortrem support with conditional offsets
6683 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6684 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6687 #if V8_HOST_ARCH_32_BIT
6689 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6690 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6691 static const int kExpectedNofPropertiesOffset =
6692 kFormalParameterCountOffset + kPointerSize;
6693 static const int kNumLiteralsOffset =
6694 kExpectedNofPropertiesOffset + kPointerSize;
6695 static const int kStartPositionAndTypeOffset =
6696 kNumLiteralsOffset + kPointerSize;
6697 static const int kEndPositionOffset =
6698 kStartPositionAndTypeOffset + kPointerSize;
6699 static const int kFunctionTokenPositionOffset =
6700 kEndPositionOffset + kPointerSize;
6701 static const int kCompilerHintsOffset =
6702 kFunctionTokenPositionOffset + kPointerSize;
6703 static const int kOptCountAndBailoutReasonOffset =
6704 kCompilerHintsOffset + kPointerSize;
6705 static const int kCountersOffset =
6706 kOptCountAndBailoutReasonOffset + kPointerSize;
6707 static const int kAstNodeCountOffset =
6708 kCountersOffset + kPointerSize;
6709 static const int kProfilerTicksOffset =
6710 kAstNodeCountOffset + kPointerSize;
6713 static const int kSize = kProfilerTicksOffset + kPointerSize;
6715 // The only reason to use smi fields instead of int fields
6716 // is to allow iteration without maps decoding during
6717 // garbage collections.
6718 // To avoid wasting space on 64-bit architectures we use
6719 // the following trick: we group integer fields into pairs
6720 // The least significant integer in each pair is shifted left by 1.
6721 // By doing this we guarantee that LSB of each kPointerSize aligned
6722 // word is not set and thus this word cannot be treated as pointer
6723 // to HeapObject during old space traversal.
6724 #if V8_TARGET_LITTLE_ENDIAN
6725 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6726 static const int kFormalParameterCountOffset =
6727 kLengthOffset + kIntSize;
6729 static const int kExpectedNofPropertiesOffset =
6730 kFormalParameterCountOffset + kIntSize;
6731 static const int kNumLiteralsOffset =
6732 kExpectedNofPropertiesOffset + kIntSize;
6734 static const int kEndPositionOffset =
6735 kNumLiteralsOffset + kIntSize;
6736 static const int kStartPositionAndTypeOffset =
6737 kEndPositionOffset + kIntSize;
6739 static const int kFunctionTokenPositionOffset =
6740 kStartPositionAndTypeOffset + kIntSize;
6741 static const int kCompilerHintsOffset =
6742 kFunctionTokenPositionOffset + kIntSize;
6744 static const int kOptCountAndBailoutReasonOffset =
6745 kCompilerHintsOffset + kIntSize;
6746 static const int kCountersOffset =
6747 kOptCountAndBailoutReasonOffset + kIntSize;
6749 static const int kAstNodeCountOffset =
6750 kCountersOffset + kIntSize;
6751 static const int kProfilerTicksOffset =
6752 kAstNodeCountOffset + kIntSize;
6755 static const int kSize = kProfilerTicksOffset + kIntSize;
6757 #elif V8_TARGET_BIG_ENDIAN
6758 static const int kFormalParameterCountOffset =
6759 kLastPointerFieldOffset + kPointerSize;
6760 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6762 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6763 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6765 static const int kStartPositionAndTypeOffset =
6766 kExpectedNofPropertiesOffset + kIntSize;
6767 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6769 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6770 static const int kFunctionTokenPositionOffset =
6771 kCompilerHintsOffset + kIntSize;
6773 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6774 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6776 static const int kProfilerTicksOffset =
6777 kOptCountAndBailoutReasonOffset + kIntSize;
6778 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6781 static const int kSize = kAstNodeCountOffset + kIntSize;
6784 #error Unknown byte ordering
6785 #endif // Big endian
6789 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6791 typedef FixedBodyDescriptor<kNameOffset,
6792 kLastPointerFieldOffset + kPointerSize,
6793 kSize> BodyDescriptor;
6795 // Bit positions in start_position_and_type.
6796 // The source code start position is in the 30 most significant bits of
6797 // the start_position_and_type field.
6798 static const int kIsExpressionBit = 0;
6799 static const int kIsTopLevelBit = 1;
6800 static const int kStartPositionShift = 2;
6801 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6803 // Bit positions in compiler_hints.
6804 enum CompilerHints {
6805 kAllowLazyCompilation,
6806 kAllowLazyCompilationWithoutContext,
6807 kOptimizationDisabled,
6809 kStrictModeFunction,
6810 kStrongModeFunction,
6813 kHasDuplicateParameters,
6817 kNameShouldPrintAsAnonymous,
6824 kIsAccessorFunction,
6825 kIsDefaultConstructor,
6826 kIsSubclassConstructor,
6832 kCompilerHintsCount // Pseudo entry
6834 // Add hints for other modes when they're added.
6835 STATIC_ASSERT(LANGUAGE_END == 3);
6837 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6839 class DeoptCountBits : public BitField<int, 0, 4> {};
6840 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6841 class ICAgeBits : public BitField<int, 22, 8> {};
6843 class OptCountBits : public BitField<int, 0, 22> {};
6844 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6847 #if V8_HOST_ARCH_32_BIT
6848 // On 32 bit platforms, compiler hints is a smi.
6849 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6850 static const int kCompilerHintsSize = kPointerSize;
6852 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6853 static const int kCompilerHintsSmiTagSize = 0;
6854 static const int kCompilerHintsSize = kIntSize;
6857 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6858 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6861 // Constants for optimizing codegen for strict mode function and
6863 // Allows to use byte-width instructions.
6864 static const int kStrictModeBitWithinByte =
6865 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6866 static const int kStrongModeBitWithinByte =
6867 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6869 static const int kNativeBitWithinByte =
6870 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6872 static const int kBoundBitWithinByte =
6873 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6875 #if defined(V8_TARGET_LITTLE_ENDIAN)
6876 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6877 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6878 static const int kStrongModeByteOffset =
6879 kCompilerHintsOffset +
6880 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6881 static const int kNativeByteOffset = kCompilerHintsOffset +
6882 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6883 static const int kBoundByteOffset =
6884 kCompilerHintsOffset +
6885 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6886 #elif defined(V8_TARGET_BIG_ENDIAN)
6887 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6888 (kCompilerHintsSize - 1) -
6889 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6890 static const int kStrongModeByteOffset =
6891 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6892 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6893 static const int kNativeByteOffset = kCompilerHintsOffset +
6894 (kCompilerHintsSize - 1) -
6895 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6896 static const int kBoundByteOffset =
6897 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6898 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6900 #error Unknown byte ordering
6904 // Returns entry from optimized code map for specified context and OSR entry.
6905 // The result is either kNotFound, kSharedCodeIndex for context-independent
6906 // entry or a start index of the context-dependent entry.
6907 int SearchOptimizedCodeMapEntry(Context* native_context,
6908 BailoutId osr_ast_id);
6910 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6914 // Printing support.
6915 struct SourceCodeOf {
6916 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6917 : value(v), max_length(max) {}
6918 const SharedFunctionInfo* value;
6923 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6926 class JSGeneratorObject: public JSObject {
6928 // [function]: The function corresponding to this generator object.
6929 DECL_ACCESSORS(function, JSFunction)
6931 // [context]: The context of the suspended computation.
6932 DECL_ACCESSORS(context, Context)
6934 // [receiver]: The receiver of the suspended computation.
6935 DECL_ACCESSORS(receiver, Object)
6937 // [continuation]: Offset into code of continuation.
6939 // A positive offset indicates a suspended generator. The special
6940 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6941 // cannot be resumed.
6942 inline int continuation() const;
6943 inline void set_continuation(int continuation);
6944 inline bool is_closed();
6945 inline bool is_executing();
6946 inline bool is_suspended();
6948 // [operand_stack]: Saved operand stack.
6949 DECL_ACCESSORS(operand_stack, FixedArray)
6951 DECLARE_CAST(JSGeneratorObject)
6953 // Dispatched behavior.
6954 DECLARE_PRINTER(JSGeneratorObject)
6955 DECLARE_VERIFIER(JSGeneratorObject)
6957 // Magic sentinel values for the continuation.
6958 static const int kGeneratorExecuting = -1;
6959 static const int kGeneratorClosed = 0;
6961 // Layout description.
6962 static const int kFunctionOffset = JSObject::kHeaderSize;
6963 static const int kContextOffset = kFunctionOffset + kPointerSize;
6964 static const int kReceiverOffset = kContextOffset + kPointerSize;
6965 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6966 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6967 static const int kSize = kOperandStackOffset + kPointerSize;
6969 // Resume mode, for use by runtime functions.
6970 enum ResumeMode { NEXT, THROW };
6973 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6977 // Representation for module instance objects.
6978 class JSModule: public JSObject {
6980 // [context]: the context holding the module's locals, or undefined if none.
6981 DECL_ACCESSORS(context, Object)
6983 // [scope_info]: Scope info.
6984 DECL_ACCESSORS(scope_info, ScopeInfo)
6986 DECLARE_CAST(JSModule)
6988 // Dispatched behavior.
6989 DECLARE_PRINTER(JSModule)
6990 DECLARE_VERIFIER(JSModule)
6992 // Layout description.
6993 static const int kContextOffset = JSObject::kHeaderSize;
6994 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6995 static const int kSize = kScopeInfoOffset + kPointerSize;
6998 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7002 // JSFunction describes JavaScript functions.
7003 class JSFunction: public JSObject {
7005 // [prototype_or_initial_map]:
7006 DECL_ACCESSORS(prototype_or_initial_map, Object)
7008 // [shared]: The information about the function that
7009 // can be shared by instances.
7010 DECL_ACCESSORS(shared, SharedFunctionInfo)
7012 // [context]: The context for this function.
7013 inline Context* context();
7014 inline void set_context(Object* context);
7015 inline JSObject* global_proxy();
7017 // [code]: The generated code object for this function. Executed
7018 // when the function is invoked, e.g. foo() or new foo(). See
7019 // [[Call]] and [[Construct]] description in ECMA-262, section
7021 inline Code* code();
7022 inline void set_code(Code* code);
7023 inline void set_code_no_write_barrier(Code* code);
7024 inline void ReplaceCode(Code* code);
7026 // Tells whether this function is builtin.
7027 inline bool IsBuiltin();
7029 // Tells whether this function inlines the given shared function info.
7030 bool Inlines(SharedFunctionInfo* candidate);
7032 // Tells whether this function should be subject to debugging.
7033 inline bool IsSubjectToDebugging();
7035 // Tells whether or not the function needs arguments adaption.
7036 inline bool NeedsArgumentsAdaption();
7038 // Tells whether or not this function has been optimized.
7039 inline bool IsOptimized();
7041 // Mark this function for lazy recompilation. The function will be
7042 // recompiled the next time it is executed.
7043 void MarkForOptimization();
7044 void AttemptConcurrentOptimization();
7046 // Tells whether or not the function is already marked for lazy
7048 inline bool IsMarkedForOptimization();
7049 inline bool IsMarkedForConcurrentOptimization();
7051 // Tells whether or not the function is on the concurrent recompilation queue.
7052 inline bool IsInOptimizationQueue();
7054 // Inobject slack tracking is the way to reclaim unused inobject space.
7056 // The instance size is initially determined by adding some slack to
7057 // expected_nof_properties (to allow for a few extra properties added
7058 // after the constructor). There is no guarantee that the extra space
7059 // will not be wasted.
7061 // Here is the algorithm to reclaim the unused inobject space:
7062 // - Detect the first constructor call for this JSFunction.
7063 // When it happens enter the "in progress" state: initialize construction
7064 // counter in the initial_map.
7065 // - While the tracking is in progress create objects filled with
7066 // one_pointer_filler_map instead of undefined_value. This way they can be
7067 // resized quickly and safely.
7068 // - Once enough objects have been created compute the 'slack'
7069 // (traverse the map transition tree starting from the
7070 // initial_map and find the lowest value of unused_property_fields).
7071 // - Traverse the transition tree again and decrease the instance size
7072 // of every map. Existing objects will resize automatically (they are
7073 // filled with one_pointer_filler_map). All further allocations will
7074 // use the adjusted instance size.
7075 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7076 // allocations made using different closures could actually create different
7077 // kind of objects (see prototype inheritance pattern).
7079 // Important: inobject slack tracking is not attempted during the snapshot
7082 // True if the initial_map is set and the object constructions countdown
7083 // counter is not zero.
7084 static const int kGenerousAllocationCount =
7085 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7086 inline bool IsInobjectSlackTrackingInProgress();
7088 // Starts the tracking.
7089 // Initializes object constructions countdown counter in the initial map.
7090 void StartInobjectSlackTracking();
7092 // Completes the tracking.
7093 void CompleteInobjectSlackTracking();
7095 // [literals_or_bindings]: Fixed array holding either
7096 // the materialized literals or the bindings of a bound function.
7098 // If the function contains object, regexp or array literals, the
7099 // literals array prefix contains the object, regexp, and array
7100 // function to be used when creating these literals. This is
7101 // necessary so that we do not dynamically lookup the object, regexp
7102 // or array functions. Performing a dynamic lookup, we might end up
7103 // using the functions from a new context that we should not have
7106 // On bound functions, the array is a (copy-on-write) fixed-array containing
7107 // the function that was bound, bound this-value and any bound
7108 // arguments. Bound functions never contain literals.
7109 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7111 inline FixedArray* literals();
7112 inline void set_literals(FixedArray* literals);
7114 inline FixedArray* function_bindings();
7115 inline void set_function_bindings(FixedArray* bindings);
7117 // The initial map for an object created by this constructor.
7118 inline Map* initial_map();
7119 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7120 Handle<Object> prototype);
7121 inline bool has_initial_map();
7122 static void EnsureHasInitialMap(Handle<JSFunction> function);
7124 // Get and set the prototype property on a JSFunction. If the
7125 // function has an initial map the prototype is set on the initial
7126 // map. Otherwise, the prototype is put in the initial map field
7127 // until an initial map is needed.
7128 inline bool has_prototype();
7129 inline bool has_instance_prototype();
7130 inline Object* prototype();
7131 inline Object* instance_prototype();
7132 static void SetPrototype(Handle<JSFunction> function,
7133 Handle<Object> value);
7134 static void SetInstancePrototype(Handle<JSFunction> function,
7135 Handle<Object> value);
7137 // Creates a new closure for the fucntion with the same bindings,
7138 // bound values, and prototype. An equivalent of spec operations
7139 // ``CloneMethod`` and ``CloneBoundFunction``.
7140 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7142 // After prototype is removed, it will not be created when accessed, and
7143 // [[Construct]] from this function will not be allowed.
7144 bool RemovePrototype();
7145 inline bool should_have_prototype();
7147 // Accessor for this function's initial map's [[class]]
7148 // property. This is primarily used by ECMA native functions. This
7149 // method sets the class_name field of this function's initial map
7150 // to a given value. It creates an initial map if this function does
7151 // not have one. Note that this method does not copy the initial map
7152 // if it has one already, but simply replaces it with the new value.
7153 // Instances created afterwards will have a map whose [[class]] is
7154 // set to 'value', but there is no guarantees on instances created
7156 void SetInstanceClassName(String* name);
7158 // Returns if this function has been compiled to native code yet.
7159 inline bool is_compiled();
7161 // Returns `false` if formal parameters include rest parameters, optional
7162 // parameters, or destructuring parameters.
7163 // TODO(caitp): make this a flag set during parsing
7164 inline bool has_simple_parameters();
7166 // [next_function_link]: Links functions into various lists, e.g. the list
7167 // of optimized functions hanging off the native_context. The CodeFlusher
7168 // uses this link to chain together flushing candidates. Treated weakly
7169 // by the garbage collector.
7170 DECL_ACCESSORS(next_function_link, Object)
7172 // Prints the name of the function using PrintF.
7173 void PrintName(FILE* out = stdout);
7175 DECLARE_CAST(JSFunction)
7177 // Iterates the objects, including code objects indirectly referenced
7178 // through pointers to the first instruction in the code object.
7179 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7181 // Dispatched behavior.
7182 DECLARE_PRINTER(JSFunction)
7183 DECLARE_VERIFIER(JSFunction)
7185 // Returns the number of allocated literals.
7186 inline int NumberOfLiterals();
7188 // Used for flags such as --hydrogen-filter.
7189 bool PassesFilter(const char* raw_filter);
7191 // The function's name if it is configured, otherwise shared function info
7193 static Handle<String> GetDebugName(Handle<JSFunction> function);
7195 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7196 // kSize) is weak and has special handling during garbage collection.
7197 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7198 static const int kPrototypeOrInitialMapOffset =
7199 kCodeEntryOffset + kPointerSize;
7200 static const int kSharedFunctionInfoOffset =
7201 kPrototypeOrInitialMapOffset + kPointerSize;
7202 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7203 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7204 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7205 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7206 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7208 // Layout of the bound-function binding array.
7209 static const int kBoundFunctionIndex = 0;
7210 static const int kBoundThisIndex = 1;
7211 static const int kBoundArgumentsStartIndex = 2;
7214 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7218 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7219 // and the prototype is hidden. JSGlobalProxy always delegates
7220 // property accesses to its prototype if the prototype is not null.
7222 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7224 // Accessing a JSGlobalProxy requires security check.
7226 class JSGlobalProxy : public JSObject {
7228 // [native_context]: the owner native context of this global proxy object.
7229 // It is null value if this object is not used by any context.
7230 DECL_ACCESSORS(native_context, Object)
7232 // [hash]: The hash code property (undefined if not initialized yet).
7233 DECL_ACCESSORS(hash, Object)
7235 DECLARE_CAST(JSGlobalProxy)
7237 inline bool IsDetachedFrom(GlobalObject* global) const;
7239 // Dispatched behavior.
7240 DECLARE_PRINTER(JSGlobalProxy)
7241 DECLARE_VERIFIER(JSGlobalProxy)
7243 // Layout description.
7244 static const int kNativeContextOffset = JSObject::kHeaderSize;
7245 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7246 static const int kSize = kHashOffset + kPointerSize;
7249 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7253 // Common super class for JavaScript global objects and the special
7254 // builtins global objects.
7255 class GlobalObject: public JSObject {
7257 // [builtins]: the object holding the runtime routines written in JS.
7258 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7260 // [native context]: the natives corresponding to this global object.
7261 DECL_ACCESSORS(native_context, Context)
7263 // [global proxy]: the global proxy object of the context
7264 DECL_ACCESSORS(global_proxy, JSObject)
7266 DECLARE_CAST(GlobalObject)
7268 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7270 // Ensure that the global object has a cell for the given property name.
7271 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7274 // Layout description.
7275 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7276 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7277 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7278 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7281 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7285 // JavaScript global object.
7286 class JSGlobalObject: public GlobalObject {
7288 DECLARE_CAST(JSGlobalObject)
7290 inline bool IsDetached();
7292 // Dispatched behavior.
7293 DECLARE_PRINTER(JSGlobalObject)
7294 DECLARE_VERIFIER(JSGlobalObject)
7296 // Layout description.
7297 static const int kSize = GlobalObject::kHeaderSize;
7300 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7304 // Builtins global object which holds the runtime routines written in
7306 class JSBuiltinsObject: public GlobalObject {
7308 DECLARE_CAST(JSBuiltinsObject)
7310 // Dispatched behavior.
7311 DECLARE_PRINTER(JSBuiltinsObject)
7312 DECLARE_VERIFIER(JSBuiltinsObject)
7314 // Layout description.
7315 static const int kSize = GlobalObject::kHeaderSize;
7318 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7322 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7323 class JSValue: public JSObject {
7325 // [value]: the object being wrapped.
7326 DECL_ACCESSORS(value, Object)
7328 DECLARE_CAST(JSValue)
7330 // Dispatched behavior.
7331 DECLARE_PRINTER(JSValue)
7332 DECLARE_VERIFIER(JSValue)
7334 // Layout description.
7335 static const int kValueOffset = JSObject::kHeaderSize;
7336 static const int kSize = kValueOffset + kPointerSize;
7339 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7345 // Representation for JS date objects.
7346 class JSDate: public JSObject {
7348 // If one component is NaN, all of them are, indicating a NaN time value.
7349 // [value]: the time value.
7350 DECL_ACCESSORS(value, Object)
7351 // [year]: caches year. Either undefined, smi, or NaN.
7352 DECL_ACCESSORS(year, Object)
7353 // [month]: caches month. Either undefined, smi, or NaN.
7354 DECL_ACCESSORS(month, Object)
7355 // [day]: caches day. Either undefined, smi, or NaN.
7356 DECL_ACCESSORS(day, Object)
7357 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7358 DECL_ACCESSORS(weekday, Object)
7359 // [hour]: caches hours. Either undefined, smi, or NaN.
7360 DECL_ACCESSORS(hour, Object)
7361 // [min]: caches minutes. Either undefined, smi, or NaN.
7362 DECL_ACCESSORS(min, Object)
7363 // [sec]: caches seconds. Either undefined, smi, or NaN.
7364 DECL_ACCESSORS(sec, Object)
7365 // [cache stamp]: sample of the date cache stamp at the
7366 // moment when chached fields were cached.
7367 DECL_ACCESSORS(cache_stamp, Object)
7369 DECLARE_CAST(JSDate)
7371 // Returns the date field with the specified index.
7372 // See FieldIndex for the list of date fields.
7373 static Object* GetField(Object* date, Smi* index);
7375 void SetValue(Object* value, bool is_value_nan);
7377 // ES6 section 20.3.4.45 Date.prototype [ @@toPrimitive ]
7378 static MUST_USE_RESULT MaybeHandle<Object> ToPrimitive(
7379 Handle<JSReceiver> receiver, Handle<Object> hint);
7381 // Dispatched behavior.
7382 DECLARE_PRINTER(JSDate)
7383 DECLARE_VERIFIER(JSDate)
7385 // The order is important. It must be kept in sync with date macros
7396 kFirstUncachedField,
7397 kMillisecond = kFirstUncachedField,
7401 kYearUTC = kFirstUTCField,
7414 // Layout description.
7415 static const int kValueOffset = JSObject::kHeaderSize;
7416 static const int kYearOffset = kValueOffset + kPointerSize;
7417 static const int kMonthOffset = kYearOffset + kPointerSize;
7418 static const int kDayOffset = kMonthOffset + kPointerSize;
7419 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7420 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7421 static const int kMinOffset = kHourOffset + kPointerSize;
7422 static const int kSecOffset = kMinOffset + kPointerSize;
7423 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7424 static const int kSize = kCacheStampOffset + kPointerSize;
7427 inline Object* DoGetField(FieldIndex index);
7429 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7431 // Computes and caches the cacheable fields of the date.
7432 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7435 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7439 // Representation of message objects used for error reporting through
7440 // the API. The messages are formatted in JavaScript so this object is
7441 // a real JavaScript object. The information used for formatting the
7442 // error messages are not directly accessible from JavaScript to
7443 // prevent leaking information to user code called during error
7445 class JSMessageObject: public JSObject {
7447 // [type]: the type of error message.
7448 inline int type() const;
7449 inline void set_type(int value);
7451 // [arguments]: the arguments for formatting the error message.
7452 DECL_ACCESSORS(argument, Object)
7454 // [script]: the script from which the error message originated.
7455 DECL_ACCESSORS(script, Object)
7457 // [stack_frames]: an array of stack frames for this error object.
7458 DECL_ACCESSORS(stack_frames, Object)
7460 // [start_position]: the start position in the script for the error message.
7461 inline int start_position() const;
7462 inline void set_start_position(int value);
7464 // [end_position]: the end position in the script for the error message.
7465 inline int end_position() const;
7466 inline void set_end_position(int value);
7468 DECLARE_CAST(JSMessageObject)
7470 // Dispatched behavior.
7471 DECLARE_PRINTER(JSMessageObject)
7472 DECLARE_VERIFIER(JSMessageObject)
7474 // Layout description.
7475 static const int kTypeOffset = JSObject::kHeaderSize;
7476 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7477 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7478 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7479 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7480 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7481 static const int kSize = kEndPositionOffset + kPointerSize;
7483 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7484 kStackFramesOffset + kPointerSize,
7485 kSize> BodyDescriptor;
7489 // Regular expressions
7490 // The regular expression holds a single reference to a FixedArray in
7491 // the kDataOffset field.
7492 // The FixedArray contains the following data:
7493 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7494 // - reference to the original source string
7495 // - reference to the original flag string
7496 // If it is an atom regexp
7497 // - a reference to a literal string to search for
7498 // If it is an irregexp regexp:
7499 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7500 // used for tracking the last usage (used for code flushing).
7501 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7502 // used for tracking the last usage (used for code flushing)..
7503 // - max number of registers used by irregexp implementations.
7504 // - number of capture registers (output values) of the regexp.
7505 class JSRegExp: public JSObject {
7508 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7509 // ATOM: A simple string to match against using an indexOf operation.
7510 // IRREGEXP: Compiled with Irregexp.
7511 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7512 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7519 UNICODE_ESCAPES = 16
7524 explicit Flags(uint32_t value) : value_(value) { }
7525 bool is_global() { return (value_ & GLOBAL) != 0; }
7526 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7527 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7528 bool is_sticky() { return (value_ & STICKY) != 0; }
7529 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7530 uint32_t value() { return value_; }
7535 DECL_ACCESSORS(data, Object)
7537 inline Type TypeTag();
7538 inline int CaptureCount();
7539 inline Flags GetFlags();
7540 inline String* Pattern();
7541 inline Object* DataAt(int index);
7542 // Set implementation data after the object has been prepared.
7543 inline void SetDataAt(int index, Object* value);
7545 static int code_index(bool is_latin1) {
7547 return kIrregexpLatin1CodeIndex;
7549 return kIrregexpUC16CodeIndex;
7553 static int saved_code_index(bool is_latin1) {
7555 return kIrregexpLatin1CodeSavedIndex;
7557 return kIrregexpUC16CodeSavedIndex;
7561 DECLARE_CAST(JSRegExp)
7563 // Dispatched behavior.
7564 DECLARE_VERIFIER(JSRegExp)
7566 static const int kDataOffset = JSObject::kHeaderSize;
7567 static const int kSize = kDataOffset + kPointerSize;
7569 // Indices in the data array.
7570 static const int kTagIndex = 0;
7571 static const int kSourceIndex = kTagIndex + 1;
7572 static const int kFlagsIndex = kSourceIndex + 1;
7573 static const int kDataIndex = kFlagsIndex + 1;
7574 // The data fields are used in different ways depending on the
7575 // value of the tag.
7576 // Atom regexps (literal strings).
7577 static const int kAtomPatternIndex = kDataIndex;
7579 static const int kAtomDataSize = kAtomPatternIndex + 1;
7581 // Irregexp compiled code or bytecode for Latin1. If compilation
7582 // fails, this fields hold an exception object that should be
7583 // thrown if the regexp is used again.
7584 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7585 // Irregexp compiled code or bytecode for UC16. If compilation
7586 // fails, this fields hold an exception object that should be
7587 // thrown if the regexp is used again.
7588 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7590 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7591 // is a potential candidate for flushing.
7592 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7593 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7594 // a potential candidate for flushing.
7595 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7597 // Maximal number of registers used by either Latin1 or UC16.
7598 // Only used to check that there is enough stack space
7599 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7600 // Number of captures in the compiled regexp.
7601 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7603 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7605 // Offsets directly into the data fixed array.
7606 static const int kDataTagOffset =
7607 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7608 static const int kDataOneByteCodeOffset =
7609 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7610 static const int kDataUC16CodeOffset =
7611 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7612 static const int kIrregexpCaptureCountOffset =
7613 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7615 // In-object fields.
7616 static const int kSourceFieldIndex = 0;
7617 static const int kGlobalFieldIndex = 1;
7618 static const int kIgnoreCaseFieldIndex = 2;
7619 static const int kMultilineFieldIndex = 3;
7620 static const int kLastIndexFieldIndex = 4;
7621 static const int kInObjectFieldCount = 5;
7623 // The uninitialized value for a regexp code object.
7624 static const int kUninitializedValue = -1;
7626 // The compilation error value for the regexp code object. The real error
7627 // object is in the saved code field.
7628 static const int kCompilationErrorValue = -2;
7630 // When we store the sweep generation at which we moved the code from the
7631 // code index to the saved code index we mask it of to be in the [0:255]
7633 static const int kCodeAgeMask = 0xff;
7637 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7639 static inline bool IsMatch(HashTableKey* key, Object* value) {
7640 return key->IsMatch(value);
7643 static inline uint32_t Hash(HashTableKey* key) {
7647 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7648 return key->HashForObject(object);
7651 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7653 static const int kPrefixSize = 0;
7654 static const int kEntrySize = 2;
7658 // This cache is used in two different variants. For regexp caching, it simply
7659 // maps identifying info of the regexp to the cached regexp object. Scripts and
7660 // eval code only gets cached after a second probe for the code object. To do
7661 // so, on first "put" only a hash identifying the source is entered into the
7662 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7663 // such lifetimes get reduced, and removed once they reach zero. If a second put
7664 // is called while such a hash is live in the cache, the hash gets replaced by
7665 // an actual cache entry. Age also removes stale live entries from the cache.
7666 // Such entries are identified by SharedFunctionInfos pointing to either the
7667 // recompilation stub, or to "old" code. This avoids memory leaks due to
7668 // premature caching of scripts and eval strings that are never needed later.
7669 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7670 CompilationCacheShape,
7673 // Find cached value for a string key, otherwise return null.
7674 Handle<Object> Lookup(
7675 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7676 Handle<Object> LookupEval(
7677 Handle<String> src, Handle<SharedFunctionInfo> shared,
7678 LanguageMode language_mode, int scope_position);
7679 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7680 static Handle<CompilationCacheTable> Put(
7681 Handle<CompilationCacheTable> cache, Handle<String> src,
7682 Handle<Context> context, LanguageMode language_mode,
7683 Handle<Object> value);
7684 static Handle<CompilationCacheTable> PutEval(
7685 Handle<CompilationCacheTable> cache, Handle<String> src,
7686 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7687 int scope_position);
7688 static Handle<CompilationCacheTable> PutRegExp(
7689 Handle<CompilationCacheTable> cache, Handle<String> src,
7690 JSRegExp::Flags flags, Handle<FixedArray> value);
7691 void Remove(Object* value);
7693 static const int kHashGenerations = 10;
7695 DECLARE_CAST(CompilationCacheTable)
7698 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7702 class CodeCache: public Struct {
7704 DECL_ACCESSORS(default_cache, FixedArray)
7705 DECL_ACCESSORS(normal_type_cache, Object)
7707 // Add the code object to the cache.
7709 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7711 // Lookup code object in the cache. Returns code object if found and undefined
7713 Object* Lookup(Name* name, Code::Flags flags);
7715 // Get the internal index of a code object in the cache. Returns -1 if the
7716 // code object is not in that cache. This index can be used to later call
7717 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7719 int GetIndex(Object* name, Code* code);
7721 // Remove an object from the cache with the provided internal index.
7722 void RemoveByIndex(Object* name, Code* code, int index);
7724 DECLARE_CAST(CodeCache)
7726 // Dispatched behavior.
7727 DECLARE_PRINTER(CodeCache)
7728 DECLARE_VERIFIER(CodeCache)
7730 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7731 static const int kNormalTypeCacheOffset =
7732 kDefaultCacheOffset + kPointerSize;
7733 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7736 static void UpdateDefaultCache(
7737 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7738 static void UpdateNormalTypeCache(
7739 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7740 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7741 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7743 // Code cache layout of the default cache. Elements are alternating name and
7744 // code objects for non normal load/store/call IC's.
7745 static const int kCodeCacheEntrySize = 2;
7746 static const int kCodeCacheEntryNameOffset = 0;
7747 static const int kCodeCacheEntryCodeOffset = 1;
7749 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7753 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7755 static inline bool IsMatch(HashTableKey* key, Object* value) {
7756 return key->IsMatch(value);
7759 static inline uint32_t Hash(HashTableKey* key) {
7763 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7764 return key->HashForObject(object);
7767 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7769 static const int kPrefixSize = 0;
7770 static const int kEntrySize = 2;
7774 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7775 CodeCacheHashTableShape,
7778 Object* Lookup(Name* name, Code::Flags flags);
7779 static Handle<CodeCacheHashTable> Put(
7780 Handle<CodeCacheHashTable> table,
7784 int GetIndex(Name* name, Code::Flags flags);
7785 void RemoveByIndex(int index);
7787 DECLARE_CAST(CodeCacheHashTable)
7789 // Initial size of the fixed array backing the hash table.
7790 static const int kInitialSize = 64;
7793 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7797 class PolymorphicCodeCache: public Struct {
7799 DECL_ACCESSORS(cache, Object)
7801 static void Update(Handle<PolymorphicCodeCache> cache,
7802 MapHandleList* maps,
7807 // Returns an undefined value if the entry is not found.
7808 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7810 DECLARE_CAST(PolymorphicCodeCache)
7812 // Dispatched behavior.
7813 DECLARE_PRINTER(PolymorphicCodeCache)
7814 DECLARE_VERIFIER(PolymorphicCodeCache)
7816 static const int kCacheOffset = HeapObject::kHeaderSize;
7817 static const int kSize = kCacheOffset + kPointerSize;
7820 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7824 class PolymorphicCodeCacheHashTable
7825 : public HashTable<PolymorphicCodeCacheHashTable,
7826 CodeCacheHashTableShape,
7829 Object* Lookup(MapHandleList* maps, int code_kind);
7831 static Handle<PolymorphicCodeCacheHashTable> Put(
7832 Handle<PolymorphicCodeCacheHashTable> hash_table,
7833 MapHandleList* maps,
7837 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7839 static const int kInitialSize = 64;
7841 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7845 class TypeFeedbackInfo: public Struct {
7847 inline int ic_total_count();
7848 inline void set_ic_total_count(int count);
7850 inline int ic_with_type_info_count();
7851 inline void change_ic_with_type_info_count(int delta);
7853 inline int ic_generic_count();
7854 inline void change_ic_generic_count(int delta);
7856 inline void initialize_storage();
7858 inline void change_own_type_change_checksum();
7859 inline int own_type_change_checksum();
7861 inline void set_inlined_type_change_checksum(int checksum);
7862 inline bool matches_inlined_type_change_checksum(int checksum);
7864 DECLARE_CAST(TypeFeedbackInfo)
7866 // Dispatched behavior.
7867 DECLARE_PRINTER(TypeFeedbackInfo)
7868 DECLARE_VERIFIER(TypeFeedbackInfo)
7870 static const int kStorage1Offset = HeapObject::kHeaderSize;
7871 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7872 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7873 static const int kSize = kStorage3Offset + kPointerSize;
7876 static const int kTypeChangeChecksumBits = 7;
7878 class ICTotalCountField: public BitField<int, 0,
7879 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7880 class OwnTypeChangeChecksum: public BitField<int,
7881 kSmiValueSize - kTypeChangeChecksumBits,
7882 kTypeChangeChecksumBits> {}; // NOLINT
7883 class ICsWithTypeInfoCountField: public BitField<int, 0,
7884 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7885 class InlinedTypeChangeChecksum: public BitField<int,
7886 kSmiValueSize - kTypeChangeChecksumBits,
7887 kTypeChangeChecksumBits> {}; // NOLINT
7889 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7893 enum AllocationSiteMode {
7894 DONT_TRACK_ALLOCATION_SITE,
7895 TRACK_ALLOCATION_SITE,
7896 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7900 class AllocationSite: public Struct {
7902 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7903 static const double kPretenureRatio;
7904 static const int kPretenureMinimumCreated = 100;
7906 // Values for pretenure decision field.
7907 enum PretenureDecision {
7913 kLastPretenureDecisionValue = kZombie
7916 const char* PretenureDecisionName(PretenureDecision decision);
7918 DECL_ACCESSORS(transition_info, Object)
7919 // nested_site threads a list of sites that represent nested literals
7920 // walked in a particular order. So [[1, 2], 1, 2] will have one
7921 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7922 DECL_ACCESSORS(nested_site, Object)
7923 DECL_ACCESSORS(pretenure_data, Smi)
7924 DECL_ACCESSORS(pretenure_create_count, Smi)
7925 DECL_ACCESSORS(dependent_code, DependentCode)
7926 DECL_ACCESSORS(weak_next, Object)
7928 inline void Initialize();
7930 // This method is expensive, it should only be called for reporting.
7931 bool IsNestedSite();
7933 // transition_info bitfields, for constructed array transition info.
7934 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7935 class UnusedBits: public BitField<int, 15, 14> {};
7936 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7938 // Bitfields for pretenure_data
7939 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7940 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7941 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7942 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7944 // Increments the mementos found counter and returns true when the first
7945 // memento was found for a given allocation site.
7946 inline bool IncrementMementoFoundCount();
7948 inline void IncrementMementoCreateCount();
7950 PretenureFlag GetPretenureMode();
7952 void ResetPretenureDecision();
7954 inline PretenureDecision pretenure_decision();
7955 inline void set_pretenure_decision(PretenureDecision decision);
7957 inline bool deopt_dependent_code();
7958 inline void set_deopt_dependent_code(bool deopt);
7960 inline int memento_found_count();
7961 inline void set_memento_found_count(int count);
7963 inline int memento_create_count();
7964 inline void set_memento_create_count(int count);
7966 // The pretenuring decision is made during gc, and the zombie state allows
7967 // us to recognize when an allocation site is just being kept alive because
7968 // a later traversal of new space may discover AllocationMementos that point
7969 // to this AllocationSite.
7970 inline bool IsZombie();
7972 inline bool IsMaybeTenure();
7974 inline void MarkZombie();
7976 inline bool MakePretenureDecision(PretenureDecision current_decision,
7978 bool maximum_size_scavenge);
7980 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7982 inline ElementsKind GetElementsKind();
7983 inline void SetElementsKind(ElementsKind kind);
7985 inline bool CanInlineCall();
7986 inline void SetDoNotInlineCall();
7988 inline bool SitePointsToLiteral();
7990 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7991 ElementsKind to_kind);
7993 DECLARE_PRINTER(AllocationSite)
7994 DECLARE_VERIFIER(AllocationSite)
7996 DECLARE_CAST(AllocationSite)
7997 static inline AllocationSiteMode GetMode(
7998 ElementsKind boilerplate_elements_kind);
7999 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8000 static inline bool CanTrack(InstanceType type);
8002 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8003 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8004 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8005 static const int kPretenureCreateCountOffset =
8006 kPretenureDataOffset + kPointerSize;
8007 static const int kDependentCodeOffset =
8008 kPretenureCreateCountOffset + kPointerSize;
8009 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8010 static const int kSize = kWeakNextOffset + kPointerSize;
8012 // During mark compact we need to take special care for the dependent code
8014 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8015 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8017 // For other visitors, use the fixed body descriptor below.
8018 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8019 kDependentCodeOffset + kPointerSize,
8020 kSize> BodyDescriptor;
8023 inline bool PretenuringDecisionMade();
8025 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8029 class AllocationMemento: public Struct {
8031 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8032 static const int kSize = kAllocationSiteOffset + kPointerSize;
8034 DECL_ACCESSORS(allocation_site, Object)
8036 inline bool IsValid();
8037 inline AllocationSite* GetAllocationSite();
8039 DECLARE_PRINTER(AllocationMemento)
8040 DECLARE_VERIFIER(AllocationMemento)
8042 DECLARE_CAST(AllocationMemento)
8045 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8049 // Representation of a slow alias as part of a sloppy arguments objects.
8050 // For fast aliases (if HasSloppyArgumentsElements()):
8051 // - the parameter map contains an index into the context
8052 // - all attributes of the element have default values
8053 // For slow aliases (if HasDictionaryArgumentsElements()):
8054 // - the parameter map contains no fast alias mapping (i.e. the hole)
8055 // - this struct (in the slow backing store) contains an index into the context
8056 // - all attributes are available as part if the property details
8057 class AliasedArgumentsEntry: public Struct {
8059 inline int aliased_context_slot() const;
8060 inline void set_aliased_context_slot(int count);
8062 DECLARE_CAST(AliasedArgumentsEntry)
8064 // Dispatched behavior.
8065 DECLARE_PRINTER(AliasedArgumentsEntry)
8066 DECLARE_VERIFIER(AliasedArgumentsEntry)
8068 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8069 static const int kSize = kAliasedContextSlot + kPointerSize;
8072 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8076 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8077 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8080 class StringHasher {
8082 explicit inline StringHasher(int length, uint32_t seed);
8084 template <typename schar>
8085 static inline uint32_t HashSequentialString(const schar* chars,
8089 // Reads all the data, even for long strings and computes the utf16 length.
8090 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8092 int* utf16_length_out);
8094 // Calculated hash value for a string consisting of 1 to
8095 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8096 // value is represented decimal value.
8097 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8099 // No string is allowed to have a hash of zero. That value is reserved
8100 // for internal properties. If the hash calculation yields zero then we
8102 static const int kZeroHash = 27;
8104 // Reusable parts of the hashing algorithm.
8105 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8106 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8107 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8108 const uc16* chars, int length));
8109 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8114 // Returns the value to store in the hash field of a string with
8115 // the given length and contents.
8116 uint32_t GetHashField();
8117 // Returns true if the hash of this string can be computed without
8118 // looking at the contents.
8119 inline bool has_trivial_hash();
8120 // Adds a block of characters to the hash.
8121 template<typename Char>
8122 inline void AddCharacters(const Char* chars, int len);
8125 // Add a character to the hash.
8126 inline void AddCharacter(uint16_t c);
8127 // Update index. Returns true if string is still an index.
8128 inline bool UpdateIndex(uint16_t c);
8131 uint32_t raw_running_hash_;
8132 uint32_t array_index_;
8133 bool is_array_index_;
8134 bool is_first_char_;
8135 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8139 class IteratingStringHasher : public StringHasher {
8141 static inline uint32_t Hash(String* string, uint32_t seed);
8142 inline void VisitOneByteString(const uint8_t* chars, int length);
8143 inline void VisitTwoByteString(const uint16_t* chars, int length);
8146 inline IteratingStringHasher(int len, uint32_t seed);
8147 void VisitConsString(ConsString* cons_string);
8148 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8152 // The characteristics of a string are stored in its map. Retrieving these
8153 // few bits of information is moderately expensive, involving two memory
8154 // loads where the second is dependent on the first. To improve efficiency
8155 // the shape of the string is given its own class so that it can be retrieved
8156 // once and used for several string operations. A StringShape is small enough
8157 // to be passed by value and is immutable, but be aware that flattening a
8158 // string can potentially alter its shape. Also be aware that a GC caused by
8159 // something else can alter the shape of a string due to ConsString
8160 // shortcutting. Keeping these restrictions in mind has proven to be error-
8161 // prone and so we no longer put StringShapes in variables unless there is a
8162 // concrete performance benefit at that particular point in the code.
8163 class StringShape BASE_EMBEDDED {
8165 inline explicit StringShape(const String* s);
8166 inline explicit StringShape(Map* s);
8167 inline explicit StringShape(InstanceType t);
8168 inline bool IsSequential();
8169 inline bool IsExternal();
8170 inline bool IsCons();
8171 inline bool IsSliced();
8172 inline bool IsIndirect();
8173 inline bool IsExternalOneByte();
8174 inline bool IsExternalTwoByte();
8175 inline bool IsSequentialOneByte();
8176 inline bool IsSequentialTwoByte();
8177 inline bool IsInternalized();
8178 inline StringRepresentationTag representation_tag();
8179 inline uint32_t encoding_tag();
8180 inline uint32_t full_representation_tag();
8181 inline uint32_t size_tag();
8183 inline uint32_t type() { return type_; }
8184 inline void invalidate() { valid_ = false; }
8185 inline bool valid() { return valid_; }
8187 inline void invalidate() { }
8193 inline void set_valid() { valid_ = true; }
8196 inline void set_valid() { }
8201 // The Name abstract class captures anything that can be used as a property
8202 // name, i.e., strings and symbols. All names store a hash value.
8203 class Name: public HeapObject {
8205 // Get and set the hash field of the name.
8206 inline uint32_t hash_field();
8207 inline void set_hash_field(uint32_t value);
8209 // Tells whether the hash code has been computed.
8210 inline bool HasHashCode();
8212 // Returns a hash value used for the property table
8213 inline uint32_t Hash();
8215 // Equality operations.
8216 inline bool Equals(Name* other);
8217 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8220 inline bool AsArrayIndex(uint32_t* index);
8222 // If the name is private, it can only name own properties.
8223 inline bool IsPrivate();
8225 // If the name is a non-flat string, this method returns a flat version of the
8226 // string. Otherwise it'll just return the input.
8227 static inline Handle<Name> Flatten(Handle<Name> name,
8228 PretenureFlag pretenure = NOT_TENURED);
8230 // Return a string version of this name that is converted according to the
8231 // rules described in ES6 section 9.2.11.
8232 MUST_USE_RESULT static MaybeHandle<String> ToFunctionName(Handle<Name> name);
8236 DECLARE_PRINTER(Name)
8238 void NameShortPrint();
8239 int NameShortPrint(Vector<char> str);
8242 // Layout description.
8243 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8244 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8245 static const int kHashFieldOffset = kHashFieldSlot;
8247 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8249 static const int kSize = kHashFieldSlot + kPointerSize;
8251 // Mask constant for checking if a name has a computed hash code
8252 // and if it is a string that is an array index. The least significant bit
8253 // indicates whether a hash code has been computed. If the hash code has
8254 // been computed the 2nd bit tells whether the string can be used as an
8256 static const int kHashNotComputedMask = 1;
8257 static const int kIsNotArrayIndexMask = 1 << 1;
8258 static const int kNofHashBitFields = 2;
8260 // Shift constant retrieving hash code from hash field.
8261 static const int kHashShift = kNofHashBitFields;
8263 // Only these bits are relevant in the hash, since the top two are shifted
8265 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8267 // Array index strings this short can keep their index in the hash field.
8268 static const int kMaxCachedArrayIndexLength = 7;
8270 // For strings which are array indexes the hash value has the string length
8271 // mixed into the hash, mainly to avoid a hash value of zero which would be
8272 // the case for the string '0'. 24 bits are used for the array index value.
8273 static const int kArrayIndexValueBits = 24;
8274 static const int kArrayIndexLengthBits =
8275 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8277 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8279 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8280 kArrayIndexValueBits> {}; // NOLINT
8281 class ArrayIndexLengthBits : public BitField<unsigned int,
8282 kNofHashBitFields + kArrayIndexValueBits,
8283 kArrayIndexLengthBits> {}; // NOLINT
8285 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8286 // could use a mask to test if the length of string is less than or equal to
8287 // kMaxCachedArrayIndexLength.
8288 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8290 static const unsigned int kContainsCachedArrayIndexMask =
8291 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8292 << ArrayIndexLengthBits::kShift) |
8293 kIsNotArrayIndexMask;
8295 // Value of empty hash field indicating that the hash is not computed.
8296 static const int kEmptyHashField =
8297 kIsNotArrayIndexMask | kHashNotComputedMask;
8300 static inline bool IsHashFieldComputed(uint32_t field);
8303 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8308 class Symbol: public Name {
8310 // [name]: The print name of a symbol, or undefined if none.
8311 DECL_ACCESSORS(name, Object)
8313 DECL_ACCESSORS(flags, Smi)
8315 // [is_private]: Whether this is a private symbol. Private symbols can only
8316 // be used to designate own properties of objects.
8317 DECL_BOOLEAN_ACCESSORS(is_private)
8319 DECLARE_CAST(Symbol)
8321 // Dispatched behavior.
8322 DECLARE_PRINTER(Symbol)
8323 DECLARE_VERIFIER(Symbol)
8325 // Layout description.
8326 static const int kNameOffset = Name::kSize;
8327 static const int kFlagsOffset = kNameOffset + kPointerSize;
8328 static const int kSize = kFlagsOffset + kPointerSize;
8330 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8332 void SymbolShortPrint(std::ostream& os);
8335 static const int kPrivateBit = 0;
8337 const char* PrivateSymbolToName() const;
8340 friend class Name; // For PrivateSymbolToName.
8343 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8349 // The String abstract class captures JavaScript string values:
8352 // 4.3.16 String Value
8353 // A string value is a member of the type String and is a finite
8354 // ordered sequence of zero or more 16-bit unsigned integer values.
8356 // All string values have a length field.
8357 class String: public Name {
8359 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8361 // Array index strings this short can keep their index in the hash field.
8362 static const int kMaxCachedArrayIndexLength = 7;
8364 // For strings which are array indexes the hash value has the string length
8365 // mixed into the hash, mainly to avoid a hash value of zero which would be
8366 // the case for the string '0'. 24 bits are used for the array index value.
8367 static const int kArrayIndexValueBits = 24;
8368 static const int kArrayIndexLengthBits =
8369 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8371 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8373 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8374 kArrayIndexValueBits> {}; // NOLINT
8375 class ArrayIndexLengthBits : public BitField<unsigned int,
8376 kNofHashBitFields + kArrayIndexValueBits,
8377 kArrayIndexLengthBits> {}; // NOLINT
8379 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8380 // could use a mask to test if the length of string is less than or equal to
8381 // kMaxCachedArrayIndexLength.
8382 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8384 static const unsigned int kContainsCachedArrayIndexMask =
8385 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8386 << ArrayIndexLengthBits::kShift) |
8387 kIsNotArrayIndexMask;
8389 class SubStringRange {
8391 explicit inline SubStringRange(String* string, int first = 0,
8394 inline iterator begin();
8395 inline iterator end();
8403 // Representation of the flat content of a String.
8404 // A non-flat string doesn't have flat content.
8405 // A flat string has content that's encoded as a sequence of either
8406 // one-byte chars or two-byte UC16.
8407 // Returned by String::GetFlatContent().
8410 // Returns true if the string is flat and this structure contains content.
8411 bool IsFlat() { return state_ != NON_FLAT; }
8412 // Returns true if the structure contains one-byte content.
8413 bool IsOneByte() { return state_ == ONE_BYTE; }
8414 // Returns true if the structure contains two-byte content.
8415 bool IsTwoByte() { return state_ == TWO_BYTE; }
8417 // Return the one byte content of the string. Only use if IsOneByte()
8419 Vector<const uint8_t> ToOneByteVector() {
8420 DCHECK_EQ(ONE_BYTE, state_);
8421 return Vector<const uint8_t>(onebyte_start, length_);
8423 // Return the two-byte content of the string. Only use if IsTwoByte()
8425 Vector<const uc16> ToUC16Vector() {
8426 DCHECK_EQ(TWO_BYTE, state_);
8427 return Vector<const uc16>(twobyte_start, length_);
8431 DCHECK(i < length_);
8432 DCHECK(state_ != NON_FLAT);
8433 if (state_ == ONE_BYTE) return onebyte_start[i];
8434 return twobyte_start[i];
8437 bool UsesSameString(const FlatContent& other) const {
8438 return onebyte_start == other.onebyte_start;
8442 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8444 // Constructors only used by String::GetFlatContent().
8445 explicit FlatContent(const uint8_t* start, int length)
8446 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8447 explicit FlatContent(const uc16* start, int length)
8448 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8449 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8452 const uint8_t* onebyte_start;
8453 const uc16* twobyte_start;
8458 friend class String;
8459 friend class IterableSubString;
8462 template <typename Char>
8463 INLINE(Vector<const Char> GetCharVector());
8465 // Get and set the length of the string.
8466 inline int length() const;
8467 inline void set_length(int value);
8469 // Get and set the length of the string using acquire loads and release
8471 inline int synchronized_length() const;
8472 inline void synchronized_set_length(int value);
8474 // Returns whether this string has only one-byte chars, i.e. all of them can
8475 // be one-byte encoded. This might be the case even if the string is
8476 // two-byte. Such strings may appear when the embedder prefers
8477 // two-byte external representations even for one-byte data.
8478 inline bool IsOneByteRepresentation() const;
8479 inline bool IsTwoByteRepresentation() const;
8481 // Cons and slices have an encoding flag that may not represent the actual
8482 // encoding of the underlying string. This is taken into account here.
8483 // Requires: this->IsFlat()
8484 inline bool IsOneByteRepresentationUnderneath();
8485 inline bool IsTwoByteRepresentationUnderneath();
8487 // NOTE: this should be considered only a hint. False negatives are
8489 inline bool HasOnlyOneByteChars();
8491 // Get and set individual two byte chars in the string.
8492 inline void Set(int index, uint16_t value);
8493 // Get individual two byte char in the string. Repeated calls
8494 // to this method are not efficient unless the string is flat.
8495 INLINE(uint16_t Get(int index));
8497 // ES6 section 7.1.3.1 ToNumber Applied to the String Type
8498 static Handle<Object> ToNumber(Handle<String> subject);
8500 // Flattens the string. Checks first inline to see if it is
8501 // necessary. Does nothing if the string is not a cons string.
8502 // Flattening allocates a sequential string with the same data as
8503 // the given string and mutates the cons string to a degenerate
8504 // form, where the first component is the new sequential string and
8505 // the second component is the empty string. If allocation fails,
8506 // this function returns a failure. If flattening succeeds, this
8507 // function returns the sequential string that is now the first
8508 // component of the cons string.
8510 // Degenerate cons strings are handled specially by the garbage
8511 // collector (see IsShortcutCandidate).
8513 static inline Handle<String> Flatten(Handle<String> string,
8514 PretenureFlag pretenure = NOT_TENURED);
8516 // Tries to return the content of a flat string as a structure holding either
8517 // a flat vector of char or of uc16.
8518 // If the string isn't flat, and therefore doesn't have flat content, the
8519 // returned structure will report so, and can't provide a vector of either
8521 FlatContent GetFlatContent();
8523 // Returns the parent of a sliced string or first part of a flat cons string.
8524 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8525 inline String* GetUnderlying();
8527 // String relational comparison, implemented according to ES6 section 7.2.11
8528 // Abstract Relational Comparison (step 5): The comparison of Strings uses a
8529 // simple lexicographic ordering on sequences of code unit values. There is no
8530 // attempt to use the more complex, semantically oriented definitions of
8531 // character or string equality and collating order defined in the Unicode
8532 // specification. Therefore String values that are canonically equal according
8533 // to the Unicode standard could test as unequal. In effect this algorithm
8534 // assumes that both Strings are already in normalized form. Also, note that
8535 // for strings containing supplementary characters, lexicographic ordering on
8536 // sequences of UTF-16 code unit values differs from that on sequences of code
8538 MUST_USE_RESULT static ComparisonResult Compare(Handle<String> x,
8541 // String equality operations.
8542 inline bool Equals(String* other);
8543 inline static bool Equals(Handle<String> one, Handle<String> two);
8544 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8545 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8546 bool IsTwoByteEqualTo(Vector<const uc16> str);
8548 // Return a UTF8 representation of the string. The string is null
8549 // terminated but may optionally contain nulls. Length is returned
8550 // in length_output if length_output is not a null pointer The string
8551 // should be nearly flat, otherwise the performance of this method may
8552 // be very slow (quadratic in the length). Setting robustness_flag to
8553 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8554 // handles unexpected data without causing assert failures and it does not
8555 // do any heap allocations. This is useful when printing stack traces.
8556 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8557 RobustnessFlag robustness_flag,
8558 int offset, int length,
8559 int* length_output = 0);
8560 base::SmartArrayPointer<char> ToCString(
8561 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8562 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8563 int* length_output = 0);
8565 // Return a 16 bit Unicode representation of the string.
8566 // The string should be nearly flat, otherwise the performance of
8567 // of this method may be very bad. Setting robustness_flag to
8568 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8569 // handles unexpected data without causing assert failures and it does not
8570 // do any heap allocations. This is useful when printing stack traces.
8571 base::SmartArrayPointer<uc16> ToWideCString(
8572 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8574 bool ComputeArrayIndex(uint32_t* index);
8577 bool MakeExternal(v8::String::ExternalStringResource* resource);
8578 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8581 inline bool AsArrayIndex(uint32_t* index);
8583 DECLARE_CAST(String)
8585 void PrintOn(FILE* out);
8587 // For use during stack traces. Performs rudimentary sanity check.
8590 // Dispatched behavior.
8591 void StringShortPrint(StringStream* accumulator);
8592 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8593 #if defined(DEBUG) || defined(OBJECT_PRINT)
8594 char* ToAsciiArray();
8596 DECLARE_PRINTER(String)
8597 DECLARE_VERIFIER(String)
8599 inline bool IsFlat();
8601 // Layout description.
8602 static const int kLengthOffset = Name::kSize;
8603 static const int kSize = kLengthOffset + kPointerSize;
8605 // Maximum number of characters to consider when trying to convert a string
8606 // value into an array index.
8607 static const int kMaxArrayIndexSize = 10;
8608 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8611 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8612 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8613 static const int kMaxUtf16CodeUnit = 0xffff;
8614 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8616 // Value of hash field containing computed hash equal to zero.
8617 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8619 // Maximal string length.
8620 static const int kMaxLength = (1 << 28) - 16;
8622 // Max length for computing hash. For strings longer than this limit the
8623 // string length is used as the hash value.
8624 static const int kMaxHashCalcLength = 16383;
8626 // Limit for truncation in short printing.
8627 static const int kMaxShortPrintLength = 1024;
8629 // Support for regular expressions.
8630 const uc16* GetTwoByteData(unsigned start);
8632 // Helper function for flattening strings.
8633 template <typename sinkchar>
8634 static void WriteToFlat(String* source,
8639 // The return value may point to the first aligned word containing the first
8640 // non-one-byte character, rather than directly to the non-one-byte character.
8641 // If the return value is >= the passed length, the entire string was
8643 static inline int NonAsciiStart(const char* chars, int length) {
8644 const char* start = chars;
8645 const char* limit = chars + length;
8647 if (length >= kIntptrSize) {
8648 // Check unaligned bytes.
8649 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8650 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8651 return static_cast<int>(chars - start);
8655 // Check aligned words.
8656 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8657 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8658 while (chars + sizeof(uintptr_t) <= limit) {
8659 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8660 return static_cast<int>(chars - start);
8662 chars += sizeof(uintptr_t);
8665 // Check remaining unaligned bytes.
8666 while (chars < limit) {
8667 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8668 return static_cast<int>(chars - start);
8673 return static_cast<int>(chars - start);
8676 static inline bool IsAscii(const char* chars, int length) {
8677 return NonAsciiStart(chars, length) >= length;
8680 static inline bool IsAscii(const uint8_t* chars, int length) {
8682 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8685 static inline int NonOneByteStart(const uc16* chars, int length) {
8686 const uc16* limit = chars + length;
8687 const uc16* start = chars;
8688 while (chars < limit) {
8689 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8692 return static_cast<int>(chars - start);
8695 static inline bool IsOneByte(const uc16* chars, int length) {
8696 return NonOneByteStart(chars, length) >= length;
8699 template<class Visitor>
8700 static inline ConsString* VisitFlat(Visitor* visitor,
8704 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8705 bool include_ending_line);
8707 // Use the hash field to forward to the canonical internalized string
8708 // when deserializing an internalized string.
8709 inline void SetForwardedInternalizedString(String* string);
8710 inline String* GetForwardedInternalizedString();
8714 friend class StringTableInsertionKey;
8716 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8717 PretenureFlag tenure);
8719 // Slow case of String::Equals. This implementation works on any strings
8720 // but it is most efficient on strings that are almost flat.
8721 bool SlowEquals(String* other);
8723 static bool SlowEquals(Handle<String> one, Handle<String> two);
8725 // Slow case of AsArrayIndex.
8726 bool SlowAsArrayIndex(uint32_t* index);
8728 // Compute and set the hash code.
8729 uint32_t ComputeAndSetHash();
8731 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8735 // The SeqString abstract class captures sequential string values.
8736 class SeqString: public String {
8738 DECLARE_CAST(SeqString)
8740 // Layout description.
8741 static const int kHeaderSize = String::kSize;
8743 // Truncate the string in-place if possible and return the result.
8744 // In case of new_length == 0, the empty string is returned without
8745 // truncating the original string.
8746 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8749 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8753 // The OneByteString class captures sequential one-byte string objects.
8754 // Each character in the OneByteString is an one-byte character.
8755 class SeqOneByteString: public SeqString {
8757 static const bool kHasOneByteEncoding = true;
8759 // Dispatched behavior.
8760 inline uint16_t SeqOneByteStringGet(int index);
8761 inline void SeqOneByteStringSet(int index, uint16_t value);
8763 // Get the address of the characters in this string.
8764 inline Address GetCharsAddress();
8766 inline uint8_t* GetChars();
8768 DECLARE_CAST(SeqOneByteString)
8770 // Garbage collection support. This method is called by the
8771 // garbage collector to compute the actual size of an OneByteString
8773 inline int SeqOneByteStringSize(InstanceType instance_type);
8775 // Computes the size for an OneByteString instance of a given length.
8776 static int SizeFor(int length) {
8777 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8780 // Maximal memory usage for a single sequential one-byte string.
8781 static const int kMaxSize = 512 * MB - 1;
8782 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8785 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8789 // The TwoByteString class captures sequential unicode string objects.
8790 // Each character in the TwoByteString is a two-byte uint16_t.
8791 class SeqTwoByteString: public SeqString {
8793 static const bool kHasOneByteEncoding = false;
8795 // Dispatched behavior.
8796 inline uint16_t SeqTwoByteStringGet(int index);
8797 inline void SeqTwoByteStringSet(int index, uint16_t value);
8799 // Get the address of the characters in this string.
8800 inline Address GetCharsAddress();
8802 inline uc16* GetChars();
8805 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8807 DECLARE_CAST(SeqTwoByteString)
8809 // Garbage collection support. This method is called by the
8810 // garbage collector to compute the actual size of a TwoByteString
8812 inline int SeqTwoByteStringSize(InstanceType instance_type);
8814 // Computes the size for a TwoByteString instance of a given length.
8815 static int SizeFor(int length) {
8816 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8819 // Maximal memory usage for a single sequential two-byte string.
8820 static const int kMaxSize = 512 * MB - 1;
8821 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8822 String::kMaxLength);
8825 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8829 // The ConsString class describes string values built by using the
8830 // addition operator on strings. A ConsString is a pair where the
8831 // first and second components are pointers to other string values.
8832 // One or both components of a ConsString can be pointers to other
8833 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8834 // are non-ConsString string values. The string value represented by
8835 // a ConsString can be obtained by concatenating the leaf string
8836 // values in a left-to-right depth-first traversal of the tree.
8837 class ConsString: public String {
8839 // First string of the cons cell.
8840 inline String* first();
8841 // Doesn't check that the result is a string, even in debug mode. This is
8842 // useful during GC where the mark bits confuse the checks.
8843 inline Object* unchecked_first();
8844 inline void set_first(String* first,
8845 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8847 // Second string of the cons cell.
8848 inline String* second();
8849 // Doesn't check that the result is a string, even in debug mode. This is
8850 // useful during GC where the mark bits confuse the checks.
8851 inline Object* unchecked_second();
8852 inline void set_second(String* second,
8853 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8855 // Dispatched behavior.
8856 uint16_t ConsStringGet(int index);
8858 DECLARE_CAST(ConsString)
8860 // Layout description.
8861 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8862 static const int kSecondOffset = kFirstOffset + kPointerSize;
8863 static const int kSize = kSecondOffset + kPointerSize;
8865 // Minimum length for a cons string.
8866 static const int kMinLength = 13;
8868 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8871 DECLARE_VERIFIER(ConsString)
8874 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8878 // The Sliced String class describes strings that are substrings of another
8879 // sequential string. The motivation is to save time and memory when creating
8880 // a substring. A Sliced String is described as a pointer to the parent,
8881 // the offset from the start of the parent string and the length. Using
8882 // a Sliced String therefore requires unpacking of the parent string and
8883 // adding the offset to the start address. A substring of a Sliced String
8884 // are not nested since the double indirection is simplified when creating
8885 // such a substring.
8886 // Currently missing features are:
8887 // - handling externalized parent strings
8888 // - external strings as parent
8889 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8890 class SlicedString: public String {
8892 inline String* parent();
8893 inline void set_parent(String* parent,
8894 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8895 inline int offset() const;
8896 inline void set_offset(int offset);
8898 // Dispatched behavior.
8899 uint16_t SlicedStringGet(int index);
8901 DECLARE_CAST(SlicedString)
8903 // Layout description.
8904 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8905 static const int kOffsetOffset = kParentOffset + kPointerSize;
8906 static const int kSize = kOffsetOffset + kPointerSize;
8908 // Minimum length for a sliced string.
8909 static const int kMinLength = 13;
8911 typedef FixedBodyDescriptor<kParentOffset,
8912 kOffsetOffset + kPointerSize, kSize>
8915 DECLARE_VERIFIER(SlicedString)
8918 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8922 // The ExternalString class describes string values that are backed by
8923 // a string resource that lies outside the V8 heap. ExternalStrings
8924 // consist of the length field common to all strings, a pointer to the
8925 // external resource. It is important to ensure (externally) that the
8926 // resource is not deallocated while the ExternalString is live in the
8929 // The API expects that all ExternalStrings are created through the
8930 // API. Therefore, ExternalStrings should not be used internally.
8931 class ExternalString: public String {
8933 DECLARE_CAST(ExternalString)
8935 // Layout description.
8936 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8937 static const int kShortSize = kResourceOffset + kPointerSize;
8938 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8939 static const int kSize = kResourceDataOffset + kPointerSize;
8941 static const int kMaxShortLength =
8942 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8944 // Return whether external string is short (data pointer is not cached).
8945 inline bool is_short();
8947 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8950 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8954 // The ExternalOneByteString class is an external string backed by an
8956 class ExternalOneByteString : public ExternalString {
8958 static const bool kHasOneByteEncoding = true;
8960 typedef v8::String::ExternalOneByteStringResource Resource;
8962 // The underlying resource.
8963 inline const Resource* resource();
8964 inline void set_resource(const Resource* buffer);
8966 // Update the pointer cache to the external character array.
8967 // The cached pointer is always valid, as the external character array does =
8968 // not move during lifetime. Deserialization is the only exception, after
8969 // which the pointer cache has to be refreshed.
8970 inline void update_data_cache();
8972 inline const uint8_t* GetChars();
8974 // Dispatched behavior.
8975 inline uint16_t ExternalOneByteStringGet(int index);
8977 DECLARE_CAST(ExternalOneByteString)
8979 // Garbage collection support.
8980 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8982 template <typename StaticVisitor>
8983 inline void ExternalOneByteStringIterateBody();
8986 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8990 // The ExternalTwoByteString class is an external string backed by a UTF-16
8992 class ExternalTwoByteString: public ExternalString {
8994 static const bool kHasOneByteEncoding = false;
8996 typedef v8::String::ExternalStringResource Resource;
8998 // The underlying string resource.
8999 inline const Resource* resource();
9000 inline void set_resource(const Resource* buffer);
9002 // Update the pointer cache to the external character array.
9003 // The cached pointer is always valid, as the external character array does =
9004 // not move during lifetime. Deserialization is the only exception, after
9005 // which the pointer cache has to be refreshed.
9006 inline void update_data_cache();
9008 inline const uint16_t* GetChars();
9010 // Dispatched behavior.
9011 inline uint16_t ExternalTwoByteStringGet(int index);
9014 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9016 DECLARE_CAST(ExternalTwoByteString)
9018 // Garbage collection support.
9019 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9021 template<typename StaticVisitor>
9022 inline void ExternalTwoByteStringIterateBody();
9025 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9029 // Utility superclass for stack-allocated objects that must be updated
9030 // on gc. It provides two ways for the gc to update instances, either
9031 // iterating or updating after gc.
9032 class Relocatable BASE_EMBEDDED {
9034 explicit inline Relocatable(Isolate* isolate);
9035 inline virtual ~Relocatable();
9036 virtual void IterateInstance(ObjectVisitor* v) { }
9037 virtual void PostGarbageCollection() { }
9039 static void PostGarbageCollectionProcessing(Isolate* isolate);
9040 static int ArchiveSpacePerThread();
9041 static char* ArchiveState(Isolate* isolate, char* to);
9042 static char* RestoreState(Isolate* isolate, char* from);
9043 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9044 static void Iterate(ObjectVisitor* v, Relocatable* top);
9045 static char* Iterate(ObjectVisitor* v, char* t);
9053 // A flat string reader provides random access to the contents of a
9054 // string independent of the character width of the string. The handle
9055 // must be valid as long as the reader is being used.
9056 class FlatStringReader : public Relocatable {
9058 FlatStringReader(Isolate* isolate, Handle<String> str);
9059 FlatStringReader(Isolate* isolate, Vector<const char> input);
9060 void PostGarbageCollection();
9061 inline uc32 Get(int index);
9062 template <typename Char>
9063 inline Char Get(int index);
9064 int length() { return length_; }
9073 // This maintains an off-stack representation of the stack frames required
9074 // to traverse a ConsString, allowing an entirely iterative and restartable
9075 // traversal of the entire string
9076 class ConsStringIterator {
9078 inline ConsStringIterator() {}
9079 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9080 Reset(cons_string, offset);
9082 inline void Reset(ConsString* cons_string, int offset = 0) {
9084 // Next will always return NULL.
9085 if (cons_string == NULL) return;
9086 Initialize(cons_string, offset);
9088 // Returns NULL when complete.
9089 inline String* Next(int* offset_out) {
9091 if (depth_ == 0) return NULL;
9092 return Continue(offset_out);
9096 static const int kStackSize = 32;
9097 // Use a mask instead of doing modulo operations for stack wrapping.
9098 static const int kDepthMask = kStackSize-1;
9099 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9100 static inline int OffsetForDepth(int depth);
9102 inline void PushLeft(ConsString* string);
9103 inline void PushRight(ConsString* string);
9104 inline void AdjustMaximumDepth();
9106 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9107 void Initialize(ConsString* cons_string, int offset);
9108 String* Continue(int* offset_out);
9109 String* NextLeaf(bool* blew_stack);
9110 String* Search(int* offset_out);
9112 // Stack must always contain only frames for which right traversal
9113 // has not yet been performed.
9114 ConsString* frames_[kStackSize];
9119 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9123 class StringCharacterStream {
9125 inline StringCharacterStream(String* string,
9127 inline uint16_t GetNext();
9128 inline bool HasMore();
9129 inline void Reset(String* string, int offset = 0);
9130 inline void VisitOneByteString(const uint8_t* chars, int length);
9131 inline void VisitTwoByteString(const uint16_t* chars, int length);
9134 ConsStringIterator iter_;
9137 const uint8_t* buffer8_;
9138 const uint16_t* buffer16_;
9140 const uint8_t* end_;
9141 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9145 template <typename T>
9146 class VectorIterator {
9148 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9149 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9150 T GetNext() { return data_[index_++]; }
9151 bool has_more() { return index_ < data_.length(); }
9153 Vector<const T> data_;
9158 // The Oddball describes objects null, undefined, true, and false.
9159 class Oddball: public HeapObject {
9161 // [to_string]: Cached to_string computed at startup.
9162 DECL_ACCESSORS(to_string, String)
9164 // [to_number]: Cached to_number computed at startup.
9165 DECL_ACCESSORS(to_number, Object)
9167 // [typeof]: Cached type_of computed at startup.
9168 DECL_ACCESSORS(type_of, String)
9170 inline byte kind() const;
9171 inline void set_kind(byte kind);
9173 // ES6 section 7.1.3 ToNumber for Boolean, Null, Undefined.
9174 MUST_USE_RESULT static inline Handle<Object> ToNumber(Handle<Oddball> input);
9176 DECLARE_CAST(Oddball)
9178 // Dispatched behavior.
9179 DECLARE_VERIFIER(Oddball)
9181 // Initialize the fields.
9182 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9183 const char* to_string, Handle<Object> to_number,
9184 const char* type_of, byte kind);
9186 // Layout description.
9187 static const int kToStringOffset = HeapObject::kHeaderSize;
9188 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9189 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9190 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9191 static const int kSize = kKindOffset + kPointerSize;
9193 static const byte kFalse = 0;
9194 static const byte kTrue = 1;
9195 static const byte kNotBooleanMask = ~1;
9196 static const byte kTheHole = 2;
9197 static const byte kNull = 3;
9198 static const byte kArgumentMarker = 4;
9199 static const byte kUndefined = 5;
9200 static const byte kUninitialized = 6;
9201 static const byte kOther = 7;
9202 static const byte kException = 8;
9204 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9205 kSize> BodyDescriptor;
9207 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9208 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9209 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9212 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9216 class Cell: public HeapObject {
9218 // [value]: value of the cell.
9219 DECL_ACCESSORS(value, Object)
9223 static inline Cell* FromValueAddress(Address value) {
9224 Object* result = FromAddress(value - kValueOffset);
9225 return static_cast<Cell*>(result);
9228 inline Address ValueAddress() {
9229 return address() + kValueOffset;
9232 // Dispatched behavior.
9233 DECLARE_PRINTER(Cell)
9234 DECLARE_VERIFIER(Cell)
9236 // Layout description.
9237 static const int kValueOffset = HeapObject::kHeaderSize;
9238 static const int kSize = kValueOffset + kPointerSize;
9240 typedef FixedBodyDescriptor<kValueOffset,
9241 kValueOffset + kPointerSize,
9242 kSize> BodyDescriptor;
9245 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9249 class PropertyCell : public HeapObject {
9251 // [property_details]: details of the global property.
9252 DECL_ACCESSORS(property_details_raw, Object)
9253 // [value]: value of the global property.
9254 DECL_ACCESSORS(value, Object)
9255 // [dependent_code]: dependent code that depends on the type of the global
9257 DECL_ACCESSORS(dependent_code, DependentCode)
9259 inline PropertyDetails property_details();
9260 inline void set_property_details(PropertyDetails details);
9262 PropertyCellConstantType GetConstantType();
9264 // Computes the new type of the cell's contents for the given value, but
9265 // without actually modifying the details.
9266 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9267 Handle<Object> value,
9268 PropertyDetails details);
9269 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9270 Handle<Object> value, PropertyDetails details);
9272 static Handle<PropertyCell> InvalidateEntry(
9273 Handle<GlobalDictionary> dictionary, int entry);
9275 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9276 Handle<Object> new_value);
9278 DECLARE_CAST(PropertyCell)
9280 // Dispatched behavior.
9281 DECLARE_PRINTER(PropertyCell)
9282 DECLARE_VERIFIER(PropertyCell)
9284 // Layout description.
9285 static const int kDetailsOffset = HeapObject::kHeaderSize;
9286 static const int kValueOffset = kDetailsOffset + kPointerSize;
9287 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9288 static const int kSize = kDependentCodeOffset + kPointerSize;
9290 static const int kPointerFieldsBeginOffset = kValueOffset;
9291 static const int kPointerFieldsEndOffset = kSize;
9293 typedef FixedBodyDescriptor<kValueOffset,
9295 kSize> BodyDescriptor;
9298 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9302 class WeakCell : public HeapObject {
9304 inline Object* value() const;
9306 // This should not be called by anyone except GC.
9307 inline void clear();
9309 // This should not be called by anyone except allocator.
9310 inline void initialize(HeapObject* value);
9312 inline bool cleared() const;
9314 DECL_ACCESSORS(next, Object)
9316 inline void clear_next(Heap* heap);
9318 inline bool next_cleared();
9320 DECLARE_CAST(WeakCell)
9322 DECLARE_PRINTER(WeakCell)
9323 DECLARE_VERIFIER(WeakCell)
9325 // Layout description.
9326 static const int kValueOffset = HeapObject::kHeaderSize;
9327 static const int kNextOffset = kValueOffset + kPointerSize;
9328 static const int kSize = kNextOffset + kPointerSize;
9330 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9333 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9337 // The JSProxy describes EcmaScript Harmony proxies
9338 class JSProxy: public JSReceiver {
9340 // [handler]: The handler property.
9341 DECL_ACCESSORS(handler, Object)
9343 // [hash]: The hash code property (undefined if not initialized yet).
9344 DECL_ACCESSORS(hash, Object)
9346 DECLARE_CAST(JSProxy)
9348 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9349 Handle<JSProxy> proxy,
9350 Handle<Object> receiver,
9353 // If the handler defines an accessor property with a setter, invoke it.
9354 // If it defines an accessor property without a setter, or a data property
9355 // that is read-only, throw. In all these cases set '*done' to true,
9356 // otherwise set it to false.
9358 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9359 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9360 Handle<Object> value, LanguageMode language_mode, bool* done);
9362 MUST_USE_RESULT static Maybe<PropertyAttributes>
9363 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9364 Handle<Object> receiver,
9366 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9367 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9368 Handle<Object> value, LanguageMode language_mode);
9370 // Turn the proxy into an (empty) JSObject.
9371 static void Fix(Handle<JSProxy> proxy);
9373 // Initializes the body after the handler slot.
9374 inline void InitializeBody(int object_size, Object* value);
9376 // Invoke a trap by name. If the trap does not exist on this's handler,
9377 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9378 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9379 Handle<JSProxy> proxy,
9381 Handle<Object> derived_trap,
9383 Handle<Object> args[]);
9385 // Dispatched behavior.
9386 DECLARE_PRINTER(JSProxy)
9387 DECLARE_VERIFIER(JSProxy)
9389 // Layout description. We add padding so that a proxy has the same
9390 // size as a virgin JSObject. This is essential for becoming a JSObject
9392 static const int kHandlerOffset = HeapObject::kHeaderSize;
9393 static const int kHashOffset = kHandlerOffset + kPointerSize;
9394 static const int kPaddingOffset = kHashOffset + kPointerSize;
9395 static const int kSize = JSObject::kHeaderSize;
9396 static const int kHeaderSize = kPaddingOffset;
9397 static const int kPaddingSize = kSize - kPaddingOffset;
9399 STATIC_ASSERT(kPaddingSize >= 0);
9401 typedef FixedBodyDescriptor<kHandlerOffset,
9403 kSize> BodyDescriptor;
9406 friend class JSReceiver;
9408 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9409 Handle<JSProxy> proxy, Handle<Name> name);
9411 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9412 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9414 MUST_USE_RESULT Object* GetIdentityHash();
9416 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9418 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9422 class JSFunctionProxy: public JSProxy {
9424 // [call_trap]: The call trap.
9425 DECL_ACCESSORS(call_trap, JSReceiver)
9427 // [construct_trap]: The construct trap.
9428 DECL_ACCESSORS(construct_trap, Object)
9430 DECLARE_CAST(JSFunctionProxy)
9432 // Dispatched behavior.
9433 DECLARE_PRINTER(JSFunctionProxy)
9434 DECLARE_VERIFIER(JSFunctionProxy)
9436 // Layout description.
9437 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9438 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9439 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9440 static const int kSize = JSFunction::kSize;
9441 static const int kPaddingSize = kSize - kPaddingOffset;
9443 STATIC_ASSERT(kPaddingSize >= 0);
9445 typedef FixedBodyDescriptor<kHandlerOffset,
9446 kConstructTrapOffset + kPointerSize,
9447 kSize> BodyDescriptor;
9450 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9454 class JSCollection : public JSObject {
9456 // [table]: the backing hash table
9457 DECL_ACCESSORS(table, Object)
9459 static const int kTableOffset = JSObject::kHeaderSize;
9460 static const int kSize = kTableOffset + kPointerSize;
9463 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9467 // The JSSet describes EcmaScript Harmony sets
9468 class JSSet : public JSCollection {
9472 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9473 static void Clear(Handle<JSSet> set);
9475 // Dispatched behavior.
9476 DECLARE_PRINTER(JSSet)
9477 DECLARE_VERIFIER(JSSet)
9480 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9484 // The JSMap describes EcmaScript Harmony maps
9485 class JSMap : public JSCollection {
9489 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9490 static void Clear(Handle<JSMap> map);
9492 // Dispatched behavior.
9493 DECLARE_PRINTER(JSMap)
9494 DECLARE_VERIFIER(JSMap)
9497 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9501 // OrderedHashTableIterator is an iterator that iterates over the keys and
9502 // values of an OrderedHashTable.
9504 // The iterator has a reference to the underlying OrderedHashTable data,
9505 // [table], as well as the current [index] the iterator is at.
9507 // When the OrderedHashTable is rehashed it adds a reference from the old table
9508 // to the new table as well as storing enough data about the changes so that the
9509 // iterator [index] can be adjusted accordingly.
9511 // When the [Next] result from the iterator is requested, the iterator checks if
9512 // there is a newer table that it needs to transition to.
9513 template<class Derived, class TableType>
9514 class OrderedHashTableIterator: public JSObject {
9516 // [table]: the backing hash table mapping keys to values.
9517 DECL_ACCESSORS(table, Object)
9519 // [index]: The index into the data table.
9520 DECL_ACCESSORS(index, Object)
9522 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9523 DECL_ACCESSORS(kind, Object)
9526 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9529 static const int kTableOffset = JSObject::kHeaderSize;
9530 static const int kIndexOffset = kTableOffset + kPointerSize;
9531 static const int kKindOffset = kIndexOffset + kPointerSize;
9532 static const int kSize = kKindOffset + kPointerSize;
9540 // Whether the iterator has more elements. This needs to be called before
9541 // calling |CurrentKey| and/or |CurrentValue|.
9544 // Move the index forward one.
9546 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9549 // Populates the array with the next key and value and then moves the iterator
9551 // This returns the |kind| or 0 if the iterator is already at the end.
9552 Smi* Next(JSArray* value_array);
9554 // Returns the current key of the iterator. This should only be called when
9555 // |HasMore| returns true.
9556 inline Object* CurrentKey();
9559 // Transitions the iterator to the non obsolete backing store. This is a NOP
9560 // if the [table] is not obsolete.
9563 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9567 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9570 // Dispatched behavior.
9571 DECLARE_PRINTER(JSSetIterator)
9572 DECLARE_VERIFIER(JSSetIterator)
9574 DECLARE_CAST(JSSetIterator)
9576 // Called by |Next| to populate the array. This allows the subclasses to
9577 // populate the array differently.
9578 inline void PopulateValueArray(FixedArray* array);
9581 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9585 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9588 // Dispatched behavior.
9589 DECLARE_PRINTER(JSMapIterator)
9590 DECLARE_VERIFIER(JSMapIterator)
9592 DECLARE_CAST(JSMapIterator)
9594 // Called by |Next| to populate the array. This allows the subclasses to
9595 // populate the array differently.
9596 inline void PopulateValueArray(FixedArray* array);
9599 // Returns the current value of the iterator. This should only be called when
9600 // |HasMore| returns true.
9601 inline Object* CurrentValue();
9603 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9607 // ES6 section 25.1.1.3 The IteratorResult Interface
9608 class JSIteratorResult final : public JSObject {
9610 // [done]: This is the result status of an iterator next method call. If the
9611 // end of the iterator was reached done is true. If the end was not reached
9612 // done is false and a [value] is available.
9613 DECL_ACCESSORS(done, Object)
9615 // [value]: If [done] is false, this is the current iteration element value.
9616 // If [done] is true, this is the return value of the iterator, if it supplied
9617 // one. If the iterator does not have a return value, value is undefined.
9618 // In that case, the value property may be absent from the conforming object
9619 // if it does not inherit an explicit value property.
9620 DECL_ACCESSORS(value, Object)
9622 // Dispatched behavior.
9623 DECLARE_PRINTER(JSIteratorResult)
9624 DECLARE_VERIFIER(JSIteratorResult)
9626 DECLARE_CAST(JSIteratorResult)
9628 static const int kValueOffset = JSObject::kHeaderSize;
9629 static const int kDoneOffset = kValueOffset + kPointerSize;
9630 static const int kSize = kDoneOffset + kPointerSize;
9632 // Indices of in-object properties.
9633 static const int kValueIndex = 0;
9634 static const int kDoneIndex = 1;
9637 DISALLOW_IMPLICIT_CONSTRUCTORS(JSIteratorResult);
9641 // Base class for both JSWeakMap and JSWeakSet
9642 class JSWeakCollection: public JSObject {
9644 // [table]: the backing hash table mapping keys to values.
9645 DECL_ACCESSORS(table, Object)
9647 // [next]: linked list of encountered weak maps during GC.
9648 DECL_ACCESSORS(next, Object)
9650 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9651 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9652 Handle<Object> value, int32_t hash);
9653 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9656 static const int kTableOffset = JSObject::kHeaderSize;
9657 static const int kNextOffset = kTableOffset + kPointerSize;
9658 static const int kSize = kNextOffset + kPointerSize;
9661 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9665 // The JSWeakMap describes EcmaScript Harmony weak maps
9666 class JSWeakMap: public JSWeakCollection {
9668 DECLARE_CAST(JSWeakMap)
9670 // Dispatched behavior.
9671 DECLARE_PRINTER(JSWeakMap)
9672 DECLARE_VERIFIER(JSWeakMap)
9675 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9679 // The JSWeakSet describes EcmaScript Harmony weak sets
9680 class JSWeakSet: public JSWeakCollection {
9682 DECLARE_CAST(JSWeakSet)
9684 // Dispatched behavior.
9685 DECLARE_PRINTER(JSWeakSet)
9686 DECLARE_VERIFIER(JSWeakSet)
9689 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9693 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9694 enum class SharedFlag { kNotShared, kShared };
9697 class JSArrayBuffer: public JSObject {
9699 // [backing_store]: backing memory for this array
9700 DECL_ACCESSORS(backing_store, void)
9702 // [byte_length]: length in bytes
9703 DECL_ACCESSORS(byte_length, Object)
9705 inline uint32_t bit_field() const;
9706 inline void set_bit_field(uint32_t bits);
9708 inline bool is_external();
9709 inline void set_is_external(bool value);
9711 inline bool is_neuterable();
9712 inline void set_is_neuterable(bool value);
9714 inline bool was_neutered();
9715 inline void set_was_neutered(bool value);
9717 inline bool is_shared();
9718 inline void set_is_shared(bool value);
9720 DECLARE_CAST(JSArrayBuffer)
9724 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9725 bool is_external, void* data, size_t allocated_length,
9726 SharedFlag shared = SharedFlag::kNotShared);
9728 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9729 Isolate* isolate, size_t allocated_length,
9730 bool initialize = true,
9731 SharedFlag shared = SharedFlag::kNotShared);
9733 // Dispatched behavior.
9734 DECLARE_PRINTER(JSArrayBuffer)
9735 DECLARE_VERIFIER(JSArrayBuffer)
9737 static const int kByteLengthOffset = JSObject::kHeaderSize;
9739 // NOTE: GC will visit objects fields:
9740 // 1. From JSObject::BodyDescriptor::kStartOffset to kByteLengthOffset +
9742 // 2. From start of the internal fields and up to the end of them
9743 static const int kBackingStoreOffset = kByteLengthOffset + kPointerSize;
9744 static const int kBitFieldSlot = kBackingStoreOffset + kPointerSize;
9745 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9746 static const int kBitFieldOffset = kBitFieldSlot;
9748 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9750 static const int kSize = kBitFieldSlot + kPointerSize;
9752 static const int kSizeWithInternalFields =
9753 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9755 template <typename StaticVisitor>
9756 static inline void JSArrayBufferIterateBody(Heap* heap, HeapObject* obj);
9758 static inline void JSArrayBufferIterateBody(HeapObject* obj,
9761 class IsExternal : public BitField<bool, 1, 1> {};
9762 class IsNeuterable : public BitField<bool, 2, 1> {};
9763 class WasNeutered : public BitField<bool, 3, 1> {};
9764 class IsShared : public BitField<bool, 4, 1> {};
9767 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9771 class JSArrayBufferView: public JSObject {
9773 // [buffer]: ArrayBuffer that this typed array views.
9774 DECL_ACCESSORS(buffer, Object)
9776 // [byte_offset]: offset of typed array in bytes.
9777 DECL_ACCESSORS(byte_offset, Object)
9779 // [byte_length]: length of typed array in bytes.
9780 DECL_ACCESSORS(byte_length, Object)
9782 DECLARE_CAST(JSArrayBufferView)
9784 DECLARE_VERIFIER(JSArrayBufferView)
9786 inline bool WasNeutered() const;
9788 static const int kBufferOffset = JSObject::kHeaderSize;
9789 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9790 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9791 static const int kViewSize = kByteLengthOffset + kPointerSize;
9795 DECL_ACCESSORS(raw_byte_offset, Object)
9796 DECL_ACCESSORS(raw_byte_length, Object)
9799 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9803 class JSTypedArray: public JSArrayBufferView {
9805 // [length]: length of typed array in elements.
9806 DECL_ACCESSORS(length, Object)
9807 inline uint32_t length_value() const;
9809 DECLARE_CAST(JSTypedArray)
9811 ExternalArrayType type();
9812 size_t element_size();
9814 Handle<JSArrayBuffer> GetBuffer();
9816 // Dispatched behavior.
9817 DECLARE_PRINTER(JSTypedArray)
9818 DECLARE_VERIFIER(JSTypedArray)
9820 static const int kLengthOffset = kViewSize + kPointerSize;
9821 static const int kSize = kLengthOffset + kPointerSize;
9823 static const int kSizeWithInternalFields =
9824 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9827 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9828 Handle<JSTypedArray> typed_array);
9830 DECL_ACCESSORS(raw_length, Object)
9833 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9837 class JSDataView: public JSArrayBufferView {
9839 DECLARE_CAST(JSDataView)
9841 // Dispatched behavior.
9842 DECLARE_PRINTER(JSDataView)
9843 DECLARE_VERIFIER(JSDataView)
9845 static const int kSize = kViewSize;
9847 static const int kSizeWithInternalFields =
9848 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9851 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9855 // Foreign describes objects pointing from JavaScript to C structures.
9856 class Foreign: public HeapObject {
9858 // [address]: field containing the address.
9859 inline Address foreign_address();
9860 inline void set_foreign_address(Address value);
9862 DECLARE_CAST(Foreign)
9864 // Dispatched behavior.
9865 inline void ForeignIterateBody(ObjectVisitor* v);
9867 template<typename StaticVisitor>
9868 inline void ForeignIterateBody();
9870 // Dispatched behavior.
9871 DECLARE_PRINTER(Foreign)
9872 DECLARE_VERIFIER(Foreign)
9874 // Layout description.
9876 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9877 static const int kSize = kForeignAddressOffset + kPointerSize;
9879 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9882 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9886 // The JSArray describes JavaScript Arrays
9887 // Such an array can be in one of two modes:
9888 // - fast, backing storage is a FixedArray and length <= elements.length();
9889 // Please note: push and pop can be used to grow and shrink the array.
9890 // - slow, backing storage is a HashTable with numbers as keys.
9891 class JSArray: public JSObject {
9893 // [length]: The length property.
9894 DECL_ACCESSORS(length, Object)
9896 // Overload the length setter to skip write barrier when the length
9897 // is set to a smi. This matches the set function on FixedArray.
9898 inline void set_length(Smi* length);
9900 static bool HasReadOnlyLength(Handle<JSArray> array);
9901 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9902 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9904 // Initialize the array with the given capacity. The function may
9905 // fail due to out-of-memory situations, but only if the requested
9906 // capacity is non-zero.
9907 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9909 // If the JSArray has fast elements, and new_length would result in
9910 // normalization, returns true.
9911 bool SetLengthWouldNormalize(uint32_t new_length);
9912 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9914 // Initializes the array to a certain length.
9915 inline bool AllowsSetLength();
9917 static void SetLength(Handle<JSArray> array, uint32_t length);
9918 // Same as above but will also queue splice records if |array| is observed.
9919 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9922 // Set the content of the array to the content of storage.
9923 static inline void SetContent(Handle<JSArray> array,
9924 Handle<FixedArrayBase> storage);
9926 DECLARE_CAST(JSArray)
9928 // Dispatched behavior.
9929 DECLARE_PRINTER(JSArray)
9930 DECLARE_VERIFIER(JSArray)
9932 // Number of element slots to pre-allocate for an empty array.
9933 static const int kPreallocatedArrayElements = 4;
9935 // Layout description.
9936 static const int kLengthOffset = JSObject::kHeaderSize;
9937 static const int kSize = kLengthOffset + kPointerSize;
9940 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9944 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9945 Handle<Map> initial_map);
9948 // JSRegExpResult is just a JSArray with a specific initial map.
9949 // This initial map adds in-object properties for "index" and "input"
9950 // properties, as assigned by RegExp.prototype.exec, which allows
9951 // faster creation of RegExp exec results.
9952 // This class just holds constants used when creating the result.
9953 // After creation the result must be treated as a JSArray in all regards.
9954 class JSRegExpResult: public JSArray {
9956 // Offsets of object fields.
9957 static const int kIndexOffset = JSArray::kSize;
9958 static const int kInputOffset = kIndexOffset + kPointerSize;
9959 static const int kSize = kInputOffset + kPointerSize;
9960 // Indices of in-object properties.
9961 static const int kIndexIndex = 0;
9962 static const int kInputIndex = 1;
9964 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9968 class AccessorInfo: public Struct {
9970 DECL_ACCESSORS(name, Object)
9971 DECL_ACCESSORS(flag, Smi)
9972 DECL_ACCESSORS(expected_receiver_type, Object)
9974 inline bool all_can_read();
9975 inline void set_all_can_read(bool value);
9977 inline bool all_can_write();
9978 inline void set_all_can_write(bool value);
9980 inline bool is_special_data_property();
9981 inline void set_is_special_data_property(bool value);
9983 inline PropertyAttributes property_attributes();
9984 inline void set_property_attributes(PropertyAttributes attributes);
9986 // Checks whether the given receiver is compatible with this accessor.
9987 static bool IsCompatibleReceiverMap(Isolate* isolate,
9988 Handle<AccessorInfo> info,
9990 inline bool IsCompatibleReceiver(Object* receiver);
9992 DECLARE_CAST(AccessorInfo)
9994 // Dispatched behavior.
9995 DECLARE_VERIFIER(AccessorInfo)
9997 // Append all descriptors to the array that are not already there.
9998 // Return number added.
9999 static int AppendUnique(Handle<Object> descriptors,
10000 Handle<FixedArray> array,
10001 int valid_descriptors);
10003 static const int kNameOffset = HeapObject::kHeaderSize;
10004 static const int kFlagOffset = kNameOffset + kPointerSize;
10005 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10006 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10009 inline bool HasExpectedReceiverType();
10011 // Bit positions in flag.
10012 static const int kAllCanReadBit = 0;
10013 static const int kAllCanWriteBit = 1;
10014 static const int kSpecialDataProperty = 2;
10015 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10017 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10021 // An accessor must have a getter, but can have no setter.
10023 // When setting a property, V8 searches accessors in prototypes.
10024 // If an accessor was found and it does not have a setter,
10025 // the request is ignored.
10027 // If the accessor in the prototype has the READ_ONLY property attribute, then
10028 // a new value is added to the derived object when the property is set.
10029 // This shadows the accessor in the prototype.
10030 class ExecutableAccessorInfo: public AccessorInfo {
10032 DECL_ACCESSORS(getter, Object)
10033 DECL_ACCESSORS(setter, Object)
10034 DECL_ACCESSORS(data, Object)
10036 DECLARE_CAST(ExecutableAccessorInfo)
10038 // Dispatched behavior.
10039 DECLARE_PRINTER(ExecutableAccessorInfo)
10040 DECLARE_VERIFIER(ExecutableAccessorInfo)
10042 static const int kGetterOffset = AccessorInfo::kSize;
10043 static const int kSetterOffset = kGetterOffset + kPointerSize;
10044 static const int kDataOffset = kSetterOffset + kPointerSize;
10045 static const int kSize = kDataOffset + kPointerSize;
10047 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10050 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10054 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10055 // accessor can either be
10056 // * a pointer to a JavaScript function or proxy: a real accessor
10057 // * undefined: considered an accessor by the spec, too, strangely enough
10058 // * the hole: an accessor which has not been set
10059 // * a pointer to a map: a transition used to ensure map sharing
10060 class AccessorPair: public Struct {
10062 DECL_ACCESSORS(getter, Object)
10063 DECL_ACCESSORS(setter, Object)
10065 DECLARE_CAST(AccessorPair)
10067 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10069 inline Object* get(AccessorComponent component);
10070 inline void set(AccessorComponent component, Object* value);
10072 // Note: Returns undefined instead in case of a hole.
10073 Object* GetComponent(AccessorComponent component);
10075 // Set both components, skipping arguments which are a JavaScript null.
10076 inline void SetComponents(Object* getter, Object* setter);
10078 inline bool Equals(AccessorPair* pair);
10079 inline bool Equals(Object* getter_value, Object* setter_value);
10081 inline bool ContainsAccessor();
10083 // Dispatched behavior.
10084 DECLARE_PRINTER(AccessorPair)
10085 DECLARE_VERIFIER(AccessorPair)
10087 static const int kGetterOffset = HeapObject::kHeaderSize;
10088 static const int kSetterOffset = kGetterOffset + kPointerSize;
10089 static const int kSize = kSetterOffset + kPointerSize;
10092 // Strangely enough, in addition to functions and harmony proxies, the spec
10093 // requires us to consider undefined as a kind of accessor, too:
10095 // Object.defineProperty(obj, "foo", {get: undefined});
10096 // assertTrue("foo" in obj);
10097 inline bool IsJSAccessor(Object* obj);
10099 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10103 class AccessCheckInfo: public Struct {
10105 DECL_ACCESSORS(named_callback, Object)
10106 DECL_ACCESSORS(indexed_callback, Object)
10107 DECL_ACCESSORS(data, Object)
10109 DECLARE_CAST(AccessCheckInfo)
10111 // Dispatched behavior.
10112 DECLARE_PRINTER(AccessCheckInfo)
10113 DECLARE_VERIFIER(AccessCheckInfo)
10115 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10116 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10117 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10118 static const int kSize = kDataOffset + kPointerSize;
10121 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10125 class InterceptorInfo: public Struct {
10127 DECL_ACCESSORS(getter, Object)
10128 DECL_ACCESSORS(setter, Object)
10129 DECL_ACCESSORS(query, Object)
10130 DECL_ACCESSORS(deleter, Object)
10131 DECL_ACCESSORS(enumerator, Object)
10132 DECL_ACCESSORS(data, Object)
10133 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10134 DECL_BOOLEAN_ACCESSORS(all_can_read)
10135 DECL_BOOLEAN_ACCESSORS(non_masking)
10137 inline int flags() const;
10138 inline void set_flags(int flags);
10140 DECLARE_CAST(InterceptorInfo)
10142 // Dispatched behavior.
10143 DECLARE_PRINTER(InterceptorInfo)
10144 DECLARE_VERIFIER(InterceptorInfo)
10146 static const int kGetterOffset = HeapObject::kHeaderSize;
10147 static const int kSetterOffset = kGetterOffset + kPointerSize;
10148 static const int kQueryOffset = kSetterOffset + kPointerSize;
10149 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10150 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10151 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10152 static const int kFlagsOffset = kDataOffset + kPointerSize;
10153 static const int kSize = kFlagsOffset + kPointerSize;
10155 static const int kCanInterceptSymbolsBit = 0;
10156 static const int kAllCanReadBit = 1;
10157 static const int kNonMasking = 2;
10160 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10164 class CallHandlerInfo: public Struct {
10166 DECL_ACCESSORS(callback, Object)
10167 DECL_ACCESSORS(data, Object)
10169 DECLARE_CAST(CallHandlerInfo)
10171 // Dispatched behavior.
10172 DECLARE_PRINTER(CallHandlerInfo)
10173 DECLARE_VERIFIER(CallHandlerInfo)
10175 static const int kCallbackOffset = HeapObject::kHeaderSize;
10176 static const int kDataOffset = kCallbackOffset + kPointerSize;
10177 static const int kSize = kDataOffset + kPointerSize;
10180 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10184 class TemplateInfo: public Struct {
10186 DECL_ACCESSORS(tag, Object)
10187 inline int number_of_properties() const;
10188 inline void set_number_of_properties(int value);
10189 DECL_ACCESSORS(property_list, Object)
10190 DECL_ACCESSORS(property_accessors, Object)
10192 DECLARE_VERIFIER(TemplateInfo)
10194 static const int kTagOffset = HeapObject::kHeaderSize;
10195 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10196 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10197 static const int kPropertyAccessorsOffset =
10198 kPropertyListOffset + kPointerSize;
10199 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10202 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10206 class FunctionTemplateInfo: public TemplateInfo {
10208 DECL_ACCESSORS(serial_number, Object)
10209 DECL_ACCESSORS(call_code, Object)
10210 DECL_ACCESSORS(prototype_template, Object)
10211 DECL_ACCESSORS(parent_template, Object)
10212 DECL_ACCESSORS(named_property_handler, Object)
10213 DECL_ACCESSORS(indexed_property_handler, Object)
10214 DECL_ACCESSORS(instance_template, Object)
10215 DECL_ACCESSORS(class_name, Object)
10216 DECL_ACCESSORS(signature, Object)
10217 DECL_ACCESSORS(instance_call_handler, Object)
10218 DECL_ACCESSORS(access_check_info, Object)
10219 DECL_ACCESSORS(flag, Smi)
10221 inline int length() const;
10222 inline void set_length(int value);
10224 // Following properties use flag bits.
10225 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10226 DECL_BOOLEAN_ACCESSORS(undetectable)
10227 // If the bit is set, object instances created by this function
10228 // requires access check.
10229 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10230 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10231 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10232 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10233 DECL_BOOLEAN_ACCESSORS(instantiated)
10234 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10236 DECLARE_CAST(FunctionTemplateInfo)
10238 // Dispatched behavior.
10239 DECLARE_PRINTER(FunctionTemplateInfo)
10240 DECLARE_VERIFIER(FunctionTemplateInfo)
10242 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10243 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10244 static const int kPrototypeTemplateOffset =
10245 kCallCodeOffset + kPointerSize;
10246 static const int kParentTemplateOffset =
10247 kPrototypeTemplateOffset + kPointerSize;
10248 static const int kNamedPropertyHandlerOffset =
10249 kParentTemplateOffset + kPointerSize;
10250 static const int kIndexedPropertyHandlerOffset =
10251 kNamedPropertyHandlerOffset + kPointerSize;
10252 static const int kInstanceTemplateOffset =
10253 kIndexedPropertyHandlerOffset + kPointerSize;
10254 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10255 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10256 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10257 static const int kAccessCheckInfoOffset =
10258 kInstanceCallHandlerOffset + kPointerSize;
10259 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10260 static const int kLengthOffset = kFlagOffset + kPointerSize;
10261 static const int kSize = kLengthOffset + kPointerSize;
10263 // Returns true if |object| is an instance of this function template.
10264 bool IsTemplateFor(Object* object);
10265 bool IsTemplateFor(Map* map);
10267 // Returns the holder JSObject if the function can legally be called with this
10268 // receiver. Returns Heap::null_value() if the call is illegal.
10269 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10272 // Bit position in the flag, from least significant bit position.
10273 static const int kHiddenPrototypeBit = 0;
10274 static const int kUndetectableBit = 1;
10275 static const int kNeedsAccessCheckBit = 2;
10276 static const int kReadOnlyPrototypeBit = 3;
10277 static const int kRemovePrototypeBit = 4;
10278 static const int kDoNotCacheBit = 5;
10279 static const int kInstantiatedBit = 6;
10280 static const int kAcceptAnyReceiver = 7;
10282 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10286 class ObjectTemplateInfo: public TemplateInfo {
10288 DECL_ACCESSORS(constructor, Object)
10289 DECL_ACCESSORS(internal_field_count, Object)
10291 DECLARE_CAST(ObjectTemplateInfo)
10293 // Dispatched behavior.
10294 DECLARE_PRINTER(ObjectTemplateInfo)
10295 DECLARE_VERIFIER(ObjectTemplateInfo)
10297 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10298 static const int kInternalFieldCountOffset =
10299 kConstructorOffset + kPointerSize;
10300 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10304 class TypeSwitchInfo: public Struct {
10306 DECL_ACCESSORS(types, Object)
10308 DECLARE_CAST(TypeSwitchInfo)
10310 // Dispatched behavior.
10311 DECLARE_PRINTER(TypeSwitchInfo)
10312 DECLARE_VERIFIER(TypeSwitchInfo)
10314 static const int kTypesOffset = Struct::kHeaderSize;
10315 static const int kSize = kTypesOffset + kPointerSize;
10319 // The DebugInfo class holds additional information for a function being
10321 class DebugInfo: public Struct {
10323 // The shared function info for the source being debugged.
10324 DECL_ACCESSORS(shared, SharedFunctionInfo)
10325 // Code object for the patched code. This code object is the code object
10326 // currently active for the function.
10327 DECL_ACCESSORS(code, Code)
10328 // Fixed array holding status information for each active break point.
10329 DECL_ACCESSORS(break_points, FixedArray)
10331 // Check if there is a break point at a code position.
10332 bool HasBreakPoint(int code_position);
10333 // Get the break point info object for a code position.
10334 Object* GetBreakPointInfo(int code_position);
10335 // Clear a break point.
10336 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10338 Handle<Object> break_point_object);
10339 // Set a break point.
10340 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10341 int source_position, int statement_position,
10342 Handle<Object> break_point_object);
10343 // Get the break point objects for a code position.
10344 Handle<Object> GetBreakPointObjects(int code_position);
10345 // Find the break point info holding this break point object.
10346 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10347 Handle<Object> break_point_object);
10348 // Get the number of break points for this function.
10349 int GetBreakPointCount();
10351 DECLARE_CAST(DebugInfo)
10353 // Dispatched behavior.
10354 DECLARE_PRINTER(DebugInfo)
10355 DECLARE_VERIFIER(DebugInfo)
10357 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10358 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10359 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10360 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10362 static const int kEstimatedNofBreakPointsInFunction = 16;
10365 static const int kNoBreakPointInfo = -1;
10367 // Lookup the index in the break_points array for a code position.
10368 int GetBreakPointInfoIndex(int code_position);
10370 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10374 // The BreakPointInfo class holds information for break points set in a
10375 // function. The DebugInfo object holds a BreakPointInfo object for each code
10376 // position with one or more break points.
10377 class BreakPointInfo: public Struct {
10379 // The position in the code for the break point.
10380 DECL_ACCESSORS(code_position, Smi)
10381 // The position in the source for the break position.
10382 DECL_ACCESSORS(source_position, Smi)
10383 // The position in the source for the last statement before this break
10385 DECL_ACCESSORS(statement_position, Smi)
10386 // List of related JavaScript break points.
10387 DECL_ACCESSORS(break_point_objects, Object)
10389 // Removes a break point.
10390 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10391 Handle<Object> break_point_object);
10392 // Set a break point.
10393 static void SetBreakPoint(Handle<BreakPointInfo> info,
10394 Handle<Object> break_point_object);
10395 // Check if break point info has this break point object.
10396 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10397 Handle<Object> break_point_object);
10398 // Get the number of break points for this code position.
10399 int GetBreakPointCount();
10401 DECLARE_CAST(BreakPointInfo)
10403 // Dispatched behavior.
10404 DECLARE_PRINTER(BreakPointInfo)
10405 DECLARE_VERIFIER(BreakPointInfo)
10407 static const int kCodePositionIndex = Struct::kHeaderSize;
10408 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10409 static const int kStatementPositionIndex =
10410 kSourcePositionIndex + kPointerSize;
10411 static const int kBreakPointObjectsIndex =
10412 kStatementPositionIndex + kPointerSize;
10413 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10416 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10420 #undef DECL_BOOLEAN_ACCESSORS
10421 #undef DECL_ACCESSORS
10422 #undef DECLARE_CAST
10423 #undef DECLARE_VERIFIER
10425 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10426 V(kStringTable, "string_table", "(Internalized strings)") \
10427 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10428 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10429 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10430 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10431 V(kTop, "top", "(Isolate)") \
10432 V(kRelocatable, "relocatable", "(Relocatable)") \
10433 V(kDebug, "debug", "(Debugger)") \
10434 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10435 V(kHandleScope, "handlescope", "(Handle scope)") \
10436 V(kBuiltins, "builtins", "(Builtins)") \
10437 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10438 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10439 V(kThreadManager, "threadmanager", "(Thread manager)") \
10440 V(kStrongRoots, "strong roots", "(Strong roots)") \
10441 V(kExtensions, "Extensions", "(Extensions)")
10443 class VisitorSynchronization : public AllStatic {
10445 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10447 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10450 #undef DECLARE_ENUM
10452 static const char* const kTags[kNumberOfSyncTags];
10453 static const char* const kTagNames[kNumberOfSyncTags];
10456 // Abstract base class for visiting, and optionally modifying, the
10457 // pointers contained in Objects. Used in GC and serialization/deserialization.
10458 class ObjectVisitor BASE_EMBEDDED {
10460 virtual ~ObjectVisitor() {}
10462 // Visits a contiguous arrays of pointers in the half-open range
10463 // [start, end). Any or all of the values may be modified on return.
10464 virtual void VisitPointers(Object** start, Object** end) = 0;
10466 // Handy shorthand for visiting a single pointer.
10467 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10469 // Visit weak next_code_link in Code object.
10470 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10472 // To allow lazy clearing of inline caches the visitor has
10473 // a rich interface for iterating over Code objects..
10475 // Visits a code target in the instruction stream.
10476 virtual void VisitCodeTarget(RelocInfo* rinfo);
10478 // Visits a code entry in a JS function.
10479 virtual void VisitCodeEntry(Address entry_address);
10481 // Visits a global property cell reference in the instruction stream.
10482 virtual void VisitCell(RelocInfo* rinfo);
10484 // Visits a runtime entry in the instruction stream.
10485 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10487 // Visits the resource of an one-byte or two-byte string.
10488 virtual void VisitExternalOneByteString(
10489 v8::String::ExternalOneByteStringResource** resource) {}
10490 virtual void VisitExternalTwoByteString(
10491 v8::String::ExternalStringResource** resource) {}
10493 // Visits a debug call target in the instruction stream.
10494 virtual void VisitDebugTarget(RelocInfo* rinfo);
10496 // Visits the byte sequence in a function's prologue that contains information
10497 // about the code's age.
10498 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10500 // Visit pointer embedded into a code object.
10501 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10503 // Visits an external reference embedded into a code object.
10504 virtual void VisitExternalReference(RelocInfo* rinfo);
10506 // Visits an external reference.
10507 virtual void VisitExternalReference(Address* p) {}
10509 // Visits an (encoded) internal reference.
10510 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10512 // Visits a handle that has an embedder-assigned class ID.
10513 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10515 // Intended for serialization/deserialization checking: insert, or
10516 // check for the presence of, a tag at this position in the stream.
10517 // Also used for marking up GC roots in heap snapshots.
10518 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10522 class StructBodyDescriptor : public
10523 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10525 static inline int SizeOf(Map* map, HeapObject* object);
10529 // BooleanBit is a helper class for setting and getting a bit in an
10531 class BooleanBit : public AllStatic {
10533 static inline bool get(Smi* smi, int bit_position) {
10534 return get(smi->value(), bit_position);
10537 static inline bool get(int value, int bit_position) {
10538 return (value & (1 << bit_position)) != 0;
10541 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10542 return Smi::FromInt(set(smi->value(), bit_position, v));
10545 static inline int set(int value, int bit_position, bool v) {
10547 value |= (1 << bit_position);
10549 value &= ~(1 << bit_position);
10556 class KeyAccumulator final BASE_EMBEDDED {
10558 explicit KeyAccumulator(Isolate* isolate) : isolate_(isolate), length_(0) {}
10560 void AddKey(Handle<Object> key, int check_limit);
10561 void AddKeys(Handle<FixedArray> array, FixedArray::KeyFilter filter);
10562 void AddKeys(Handle<JSObject> array, FixedArray::KeyFilter filter);
10563 void PrepareForComparisons(int count);
10564 Handle<FixedArray> GetKeys();
10566 int GetLength() { return length_; }
10569 void EnsureCapacity(int capacity);
10573 Handle<FixedArray> keys_;
10574 Handle<OrderedHashSet> set_;
10576 DISALLOW_COPY_AND_ASSIGN(KeyAccumulator);
10578 } } // namespace v8::internal
10580 #endif // V8_OBJECTS_H_