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 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
180 enum ExternalArrayType {
181 kExternalInt8Array = 1,
184 kExternalUint16Array,
186 kExternalUint32Array,
187 kExternalFloat32Array,
188 kExternalFloat64Array,
189 kExternalUint8ClampedArray,
193 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
194 return store_mode == STORE_TRANSITION_TO_OBJECT ||
195 store_mode == STORE_TRANSITION_TO_DOUBLE ||
196 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
197 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
201 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
202 KeyedAccessStoreMode store_mode) {
203 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
206 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
207 return STORE_AND_GROW_NO_TRANSITION;
209 return STANDARD_STORE;
213 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
214 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
215 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
219 enum IcCheckType { ELEMENT, PROPERTY };
222 // SKIP_WRITE_BARRIER skips the write barrier.
223 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
224 // only performs the generational part.
225 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
226 enum WriteBarrierMode {
228 UPDATE_WEAK_WRITE_BARRIER,
233 // Indicates whether a value can be loaded as a constant.
234 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
237 // PropertyNormalizationMode is used to specify whether to keep
238 // inobject properties when normalizing properties of a JSObject.
239 enum PropertyNormalizationMode {
240 CLEAR_INOBJECT_PROPERTIES,
241 KEEP_INOBJECT_PROPERTIES
245 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
246 // will give the fastest result by tailoring the map to the prototype, but that
247 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
248 // (at least for now) when dynamically modifying the prototype chain of an
249 // object using __proto__ or Object.setPrototypeOf.
250 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
253 // Indicates whether transitions can be added to a source map or not.
254 enum TransitionFlag {
260 // Indicates whether the transition is simple: the target map of the transition
261 // either extends the current map with a new property, or it modifies the
262 // property that was added last to the current map.
263 enum SimpleTransitionFlag {
264 SIMPLE_PROPERTY_TRANSITION,
270 // Indicates whether we are only interested in the descriptors of a particular
271 // map, or in all descriptors in the descriptor array.
272 enum DescriptorFlag {
277 // The GC maintains a bit of information, the MarkingParity, which toggles
278 // from odd to even and back every time marking is completed. Incremental
279 // marking can visit an object twice during a marking phase, so algorithms that
280 // that piggy-back on marking can use the parity to ensure that they only
281 // perform an operation on an object once per marking phase: they record the
282 // MarkingParity when they visit an object, and only re-visit the object when it
283 // is marked again and the MarkingParity changes.
290 // ICs store extra state in a Code object. The default extra state is
292 typedef int ExtraICState;
293 static const ExtraICState kNoExtraICState = 0;
295 // Instance size sentinel for objects of variable size.
296 const int kVariableSizeSentinel = 0;
298 // We may store the unsigned bit field as signed Smi value and do not
300 const int kStubMajorKeyBits = 7;
301 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
303 // All Maps have a field instance_type containing a InstanceType.
304 // It describes the type of the instances.
306 // As an example, a JavaScript object is a heap object and its map
307 // instance_type is JS_OBJECT_TYPE.
309 // The names of the string instance types are intended to systematically
310 // mirror their encoding in the instance_type field of the map. The default
311 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
312 // encoding is mentioned explicitly in the name. Likewise, the default
313 // representation is considered sequential. It is not mentioned in the
314 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
315 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
316 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
318 // NOTE: The following things are some that depend on the string types having
319 // instance_types that are less than those of all other types:
320 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
323 // NOTE: Everything following JS_VALUE_TYPE is considered a
324 // JSObject for GC purposes. The first four entries here have typeof
325 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
326 #define INSTANCE_TYPE_LIST(V) \
328 V(ONE_BYTE_STRING_TYPE) \
329 V(CONS_STRING_TYPE) \
330 V(CONS_ONE_BYTE_STRING_TYPE) \
331 V(SLICED_STRING_TYPE) \
332 V(SLICED_ONE_BYTE_STRING_TYPE) \
333 V(EXTERNAL_STRING_TYPE) \
334 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
335 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
336 V(SHORT_EXTERNAL_STRING_TYPE) \
337 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
338 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
340 V(INTERNALIZED_STRING_TYPE) \
341 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
342 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
343 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
344 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
345 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
346 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
347 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
350 V(SIMD128_VALUE_TYPE) \
356 V(PROPERTY_CELL_TYPE) \
358 V(HEAP_NUMBER_TYPE) \
359 V(MUTABLE_HEAP_NUMBER_TYPE) \
362 V(BYTECODE_ARRAY_TYPE) \
365 V(FIXED_INT8_ARRAY_TYPE) \
366 V(FIXED_UINT8_ARRAY_TYPE) \
367 V(FIXED_INT16_ARRAY_TYPE) \
368 V(FIXED_UINT16_ARRAY_TYPE) \
369 V(FIXED_INT32_ARRAY_TYPE) \
370 V(FIXED_UINT32_ARRAY_TYPE) \
371 V(FIXED_FLOAT32_ARRAY_TYPE) \
372 V(FIXED_FLOAT64_ARRAY_TYPE) \
373 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
377 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
378 V(DECLARED_ACCESSOR_INFO_TYPE) \
379 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
380 V(ACCESSOR_PAIR_TYPE) \
381 V(ACCESS_CHECK_INFO_TYPE) \
382 V(INTERCEPTOR_INFO_TYPE) \
383 V(CALL_HANDLER_INFO_TYPE) \
384 V(FUNCTION_TEMPLATE_INFO_TYPE) \
385 V(OBJECT_TEMPLATE_INFO_TYPE) \
386 V(SIGNATURE_INFO_TYPE) \
387 V(TYPE_SWITCH_INFO_TYPE) \
388 V(ALLOCATION_MEMENTO_TYPE) \
389 V(ALLOCATION_SITE_TYPE) \
392 V(POLYMORPHIC_CODE_CACHE_TYPE) \
393 V(TYPE_FEEDBACK_INFO_TYPE) \
394 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
396 V(PROTOTYPE_INFO_TYPE) \
397 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
399 V(FIXED_ARRAY_TYPE) \
400 V(FIXED_DOUBLE_ARRAY_TYPE) \
401 V(SHARED_FUNCTION_INFO_TYPE) \
404 V(JS_MESSAGE_OBJECT_TYPE) \
409 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
410 V(JS_GENERATOR_OBJECT_TYPE) \
412 V(JS_GLOBAL_OBJECT_TYPE) \
413 V(JS_BUILTINS_OBJECT_TYPE) \
414 V(JS_GLOBAL_PROXY_TYPE) \
416 V(JS_ARRAY_BUFFER_TYPE) \
417 V(JS_TYPED_ARRAY_TYPE) \
418 V(JS_DATA_VIEW_TYPE) \
422 V(JS_SET_ITERATOR_TYPE) \
423 V(JS_MAP_ITERATOR_TYPE) \
424 V(JS_WEAK_MAP_TYPE) \
425 V(JS_WEAK_SET_TYPE) \
428 V(JS_FUNCTION_TYPE) \
429 V(JS_FUNCTION_PROXY_TYPE) \
431 V(BREAK_POINT_INFO_TYPE)
434 // Since string types are not consecutive, this macro is used to
435 // iterate over them.
436 #define STRING_TYPE_LIST(V) \
437 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
438 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
440 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
441 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
443 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
444 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
445 SlicedOneByteString) \
446 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
448 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
449 external_one_byte_string, ExternalOneByteString) \
450 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
451 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
452 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
453 short_external_string, ShortExternalString) \
454 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
455 short_external_one_byte_string, ShortExternalOneByteString) \
456 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
457 ExternalTwoByteString::kShortSize, \
458 short_external_string_with_one_byte_data, \
459 ShortExternalStringWithOneByteData) \
461 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
462 InternalizedString) \
463 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
464 one_byte_internalized_string, OneByteInternalizedString) \
465 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
466 external_internalized_string, ExternalInternalizedString) \
467 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
468 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
469 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
470 ExternalTwoByteString::kSize, \
471 external_internalized_string_with_one_byte_data, \
472 ExternalInternalizedStringWithOneByteData) \
473 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
474 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
475 ShortExternalInternalizedString) \
476 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
477 ExternalOneByteString::kShortSize, \
478 short_external_one_byte_internalized_string, \
479 ShortExternalOneByteInternalizedString) \
480 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
481 ExternalTwoByteString::kShortSize, \
482 short_external_internalized_string_with_one_byte_data, \
483 ShortExternalInternalizedStringWithOneByteData)
485 // A struct is a simple object a set of object-valued fields. Including an
486 // object type in this causes the compiler to generate most of the boilerplate
487 // code for the class including allocation and garbage collection routines,
488 // casts and predicates. All you need to define is the class, methods and
489 // object verification routines. Easy, no?
491 // Note that for subtle reasons related to the ordering or numerical values of
492 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
494 #define STRUCT_LIST(V) \
496 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
497 executable_accessor_info) \
498 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
499 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
500 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
501 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
502 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
503 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
504 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
505 V(SCRIPT, Script, script) \
506 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
507 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
508 V(CODE_CACHE, CodeCache, code_cache) \
509 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
510 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
511 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
512 V(DEBUG_INFO, DebugInfo, debug_info) \
513 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
514 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
515 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
516 SloppyBlockWithEvalContextExtension, \
517 sloppy_block_with_eval_context_extension)
519 // We use the full 8 bits of the instance_type field to encode heap object
520 // instance types. The high-order bit (bit 7) is set if the object is not a
521 // string, and cleared if it is a string.
522 const uint32_t kIsNotStringMask = 0x80;
523 const uint32_t kStringTag = 0x0;
524 const uint32_t kNotStringTag = 0x80;
526 // Bit 6 indicates that the object is an internalized string (if set) or not.
527 // Bit 7 has to be clear as well.
528 const uint32_t kIsNotInternalizedMask = 0x40;
529 const uint32_t kNotInternalizedTag = 0x40;
530 const uint32_t kInternalizedTag = 0x0;
532 // If bit 7 is clear then bit 2 indicates whether the string consists of
533 // two-byte characters or one-byte characters.
534 const uint32_t kStringEncodingMask = 0x4;
535 const uint32_t kTwoByteStringTag = 0x0;
536 const uint32_t kOneByteStringTag = 0x4;
538 // If bit 7 is clear, the low-order 2 bits indicate the representation
540 const uint32_t kStringRepresentationMask = 0x03;
541 enum StringRepresentationTag {
543 kConsStringTag = 0x1,
544 kExternalStringTag = 0x2,
545 kSlicedStringTag = 0x3
547 const uint32_t kIsIndirectStringMask = 0x1;
548 const uint32_t kIsIndirectStringTag = 0x1;
549 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
550 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
551 STATIC_ASSERT((kConsStringTag &
552 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
553 STATIC_ASSERT((kSlicedStringTag &
554 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
556 // Use this mask to distinguish between cons and slice only after making
557 // sure that the string is one of the two (an indirect string).
558 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
559 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
561 // If bit 7 is clear, then bit 3 indicates whether this two-byte
562 // string actually contains one byte data.
563 const uint32_t kOneByteDataHintMask = 0x08;
564 const uint32_t kOneByteDataHintTag = 0x08;
566 // If bit 7 is clear and string representation indicates an external string,
567 // then bit 4 indicates whether the data pointer is cached.
568 const uint32_t kShortExternalStringMask = 0x10;
569 const uint32_t kShortExternalStringTag = 0x10;
572 // A ConsString with an empty string as the right side is a candidate
573 // for being shortcut by the garbage collector. We don't allocate any
574 // non-flat internalized strings, so we do not shortcut them thereby
575 // avoiding turning internalized strings into strings. The bit-masks
576 // below contain the internalized bit as additional safety.
577 // See heap.cc, mark-compact.cc and objects-visiting.cc.
578 const uint32_t kShortcutTypeMask =
580 kIsNotInternalizedMask |
581 kStringRepresentationMask;
582 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
584 static inline bool IsShortcutCandidate(int type) {
585 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
591 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
592 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
593 ONE_BYTE_INTERNALIZED_STRING_TYPE =
594 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
595 EXTERNAL_INTERNALIZED_STRING_TYPE =
596 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
597 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
598 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
599 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
600 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
602 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
603 kShortExternalStringTag |
605 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
606 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
608 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
609 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
610 kShortExternalStringTag | kInternalizedTag,
611 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
612 ONE_BYTE_STRING_TYPE =
613 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
614 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
615 CONS_ONE_BYTE_STRING_TYPE =
616 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
618 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
619 SLICED_ONE_BYTE_STRING_TYPE =
620 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
621 EXTERNAL_STRING_TYPE =
622 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
623 EXTERNAL_ONE_BYTE_STRING_TYPE =
624 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
625 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
626 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
628 SHORT_EXTERNAL_STRING_TYPE =
629 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
630 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
631 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
632 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
633 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
637 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
639 // Other primitives (cannot contain non-map-word pointers to heap objects).
642 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
644 // Objects allocated in their own spaces (never in new space).
648 // "Data", objects that cannot contain non-map-word pointers to heap
650 MUTABLE_HEAP_NUMBER_TYPE,
655 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
656 FIXED_UINT8_ARRAY_TYPE,
657 FIXED_INT16_ARRAY_TYPE,
658 FIXED_UINT16_ARRAY_TYPE,
659 FIXED_INT32_ARRAY_TYPE,
660 FIXED_UINT32_ARRAY_TYPE,
661 FIXED_FLOAT32_ARRAY_TYPE,
662 FIXED_FLOAT64_ARRAY_TYPE,
663 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
664 FIXED_DOUBLE_ARRAY_TYPE,
665 FILLER_TYPE, // LAST_DATA_TYPE
668 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
669 DECLARED_ACCESSOR_INFO_TYPE,
670 EXECUTABLE_ACCESSOR_INFO_TYPE,
672 ACCESS_CHECK_INFO_TYPE,
673 INTERCEPTOR_INFO_TYPE,
674 CALL_HANDLER_INFO_TYPE,
675 FUNCTION_TEMPLATE_INFO_TYPE,
676 OBJECT_TEMPLATE_INFO_TYPE,
678 TYPE_SWITCH_INFO_TYPE,
679 ALLOCATION_SITE_TYPE,
680 ALLOCATION_MEMENTO_TYPE,
683 POLYMORPHIC_CODE_CACHE_TYPE,
684 TYPE_FEEDBACK_INFO_TYPE,
685 ALIASED_ARGUMENTS_ENTRY_TYPE,
688 BREAK_POINT_INFO_TYPE,
690 SHARED_FUNCTION_INFO_TYPE,
695 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
697 // All the following types are subtypes of JSReceiver, which corresponds to
698 // objects in the JS sense. The first and the last type in this range are
699 // the two forms of function. This organization enables using the same
700 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
701 // NONCALLABLE_JS_OBJECT range.
702 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
703 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
704 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
705 JS_MESSAGE_OBJECT_TYPE,
708 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
709 JS_GENERATOR_OBJECT_TYPE,
711 JS_GLOBAL_OBJECT_TYPE,
712 JS_BUILTINS_OBJECT_TYPE,
713 JS_GLOBAL_PROXY_TYPE,
715 JS_ARRAY_BUFFER_TYPE,
720 JS_SET_ITERATOR_TYPE,
721 JS_MAP_ITERATOR_TYPE,
725 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
729 LAST_TYPE = JS_FUNCTION_TYPE,
730 FIRST_NAME_TYPE = FIRST_TYPE,
731 LAST_NAME_TYPE = SYMBOL_TYPE,
732 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
733 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
734 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
735 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
736 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
737 // Boundaries for testing for a fixed typed array.
738 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
739 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
740 // Boundary for promotion to old space.
741 LAST_DATA_TYPE = FILLER_TYPE,
742 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
743 // Note that there is no range for JSObject or JSProxy, since their subtypes
744 // are not continuous in this enum! The enum ranges instead reflect the
745 // external class names, where proxies are treated as either ordinary objects,
747 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
748 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
749 // Boundaries for testing the types represented as JSObject
750 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
751 LAST_JS_OBJECT_TYPE = LAST_TYPE,
752 // Boundaries for testing the types represented as JSProxy
753 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
754 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
755 // Boundaries for testing whether the type is a JavaScript object.
756 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
757 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
758 // Boundaries for testing the types for which typeof is "object".
759 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
760 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
761 // Note that the types for which typeof is "function" are not continuous.
762 // Define this so that we can put assertions on discrete checks.
763 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
766 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
767 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
768 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
769 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
772 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
773 V(FAST_ELEMENTS_SUB_TYPE) \
774 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
775 V(FAST_PROPERTIES_SUB_TYPE) \
776 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
777 V(MAP_CODE_CACHE_SUB_TYPE) \
778 V(SCOPE_INFO_SUB_TYPE) \
779 V(STRING_TABLE_SUB_TYPE) \
780 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
781 V(TRANSITION_ARRAY_SUB_TYPE)
783 enum FixedArraySubInstanceType {
784 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
785 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
786 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
787 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
800 #define DECL_BOOLEAN_ACCESSORS(name) \
801 inline bool name() const; \
802 inline void set_##name(bool value); \
805 #define DECL_ACCESSORS(name, type) \
806 inline type* name() const; \
807 inline void set_##name(type* value, \
808 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
811 #define DECLARE_CAST(type) \
812 INLINE(static type* cast(Object* object)); \
813 INLINE(static const type* cast(const Object* object));
817 class AllocationSite;
818 class AllocationSiteCreationContext;
819 class AllocationSiteUsageContext;
822 class ElementsAccessor;
823 class FixedArrayBase;
824 class FunctionLiteral;
826 class JSBuiltinsObject;
827 class LayoutDescriptor;
828 class LookupIterator;
829 class ObjectHashTable;
832 class SafepointEntry;
833 class SharedFunctionInfo;
835 class TypeFeedbackInfo;
836 class TypeFeedbackVector;
839 // We cannot just say "class HeapType;" if it is created from a template... =8-?
840 template<class> class TypeImpl;
841 struct HeapTypeConfig;
842 typedef TypeImpl<HeapTypeConfig> HeapType;
845 // A template-ized version of the IsXXX functions.
846 template <class C> inline bool Is(Object* obj);
849 #define DECLARE_VERIFIER(Name) void Name##Verify();
851 #define DECLARE_VERIFIER(Name)
855 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
857 #define DECLARE_PRINTER(Name)
861 #define OBJECT_TYPE_LIST(V) \
866 #define HEAP_OBJECT_TYPE_LIST(V) \
868 V(MutableHeapNumber) \
887 V(ExternalTwoByteString) \
888 V(ExternalOneByteString) \
889 V(SeqTwoByteString) \
890 V(SeqOneByteString) \
891 V(InternalizedString) \
894 V(FixedTypedArrayBase) \
897 V(FixedUint16Array) \
899 V(FixedUint32Array) \
901 V(FixedFloat32Array) \
902 V(FixedFloat64Array) \
903 V(FixedUint8ClampedArray) \
909 V(JSContextExtensionObject) \
910 V(JSGeneratorObject) \
912 V(LayoutDescriptor) \
916 V(TypeFeedbackVector) \
917 V(DeoptimizationInputData) \
918 V(DeoptimizationOutputData) \
922 V(FixedDoubleArray) \
926 V(ScriptContextTable) \
932 V(SharedFunctionInfo) \
941 V(JSArrayBufferView) \
950 V(JSWeakCollection) \
957 V(NormalizedMapCache) \
958 V(CompilationCacheTable) \
959 V(CodeCacheHashTable) \
960 V(PolymorphicCodeCacheHashTable) \
965 V(JSBuiltinsObject) \
967 V(UndetectableObject) \
968 V(AccessCheckNeeded) \
976 // Object is the abstract superclass for all classes in the
978 // Object does not use any virtual functions to avoid the
979 // allocation of the C++ vtable.
980 // Since both Smi and HeapObject are subclasses of Object no
981 // data members can be present in Object.
985 bool IsObject() const { return true; }
987 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
988 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
989 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
990 #undef IS_TYPE_FUNCTION_DECL
992 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
993 // a keyed store is of the form a[expression] = foo.
994 enum StoreFromKeyed {
995 MAY_BE_STORE_FROM_KEYED,
996 CERTAINLY_NOT_STORE_FROM_KEYED
999 INLINE(bool IsFixedArrayBase() const);
1000 INLINE(bool IsExternal() const);
1001 INLINE(bool IsAccessorInfo() const);
1003 INLINE(bool IsStruct() const);
1004 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1005 INLINE(bool Is##Name() const);
1006 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1007 #undef DECLARE_STRUCT_PREDICATE
1009 INLINE(bool IsSpecObject()) const;
1010 INLINE(bool IsSpecFunction()) const;
1011 INLINE(bool IsTemplateInfo()) const;
1012 INLINE(bool IsNameDictionary() const);
1013 INLINE(bool IsGlobalDictionary() const);
1014 INLINE(bool IsSeededNumberDictionary() const);
1015 INLINE(bool IsUnseededNumberDictionary() const);
1016 INLINE(bool IsOrderedHashSet() const);
1017 INLINE(bool IsOrderedHashMap() const);
1018 bool IsCallable() const;
1019 static bool IsPromise(Handle<Object> object);
1022 INLINE(bool IsUndefined() const);
1023 INLINE(bool IsNull() const);
1024 INLINE(bool IsTheHole() const);
1025 INLINE(bool IsException() const);
1026 INLINE(bool IsUninitialized() const);
1027 INLINE(bool IsTrue() const);
1028 INLINE(bool IsFalse() const);
1029 INLINE(bool IsArgumentsMarker() const);
1031 // Filler objects (fillers and free space objects).
1032 INLINE(bool IsFiller() const);
1034 // Extract the number.
1035 inline double Number();
1036 INLINE(bool IsNaN() const);
1037 INLINE(bool IsMinusZero() const);
1038 bool ToInt32(int32_t* value);
1039 bool ToUint32(uint32_t* value);
1041 inline Representation OptimalRepresentation();
1043 inline ElementsKind OptimalElementsKind();
1045 inline bool FitsRepresentation(Representation representation);
1047 // Checks whether two valid primitive encodings of a property name resolve to
1048 // the same logical property. E.g., the smi 1, the string "1" and the double
1049 // 1 all refer to the same property, so this helper will return true.
1050 inline bool KeyEquals(Object* other);
1052 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1054 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1055 Handle<Object> object,
1056 Representation representation);
1058 inline static Handle<Object> WrapForRead(Isolate* isolate,
1059 Handle<Object> object,
1060 Representation representation);
1062 // Returns true if the object is of the correct type to be used as a
1063 // implementation of a JSObject's elements.
1064 inline bool HasValidElements();
1066 inline bool HasSpecificClassOf(String* name);
1068 bool BooleanValue(); // ECMA-262 9.2.
1070 // ES6 section 7.2.13 Strict Equality Comparison
1071 bool StrictEquals(Object* that);
1073 // Convert to a JSObject if needed.
1074 // native_context is used when creating wrapper object.
1075 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1076 Handle<Object> object);
1077 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1078 Handle<Object> object,
1079 Handle<Context> context);
1081 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1082 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1084 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1085 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1086 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1087 LanguageMode language_mode,
1088 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1090 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1091 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1092 StoreFromKeyed store_mode);
1094 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1095 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1096 StoreFromKeyed store_mode);
1098 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1099 LookupIterator* it, LanguageMode language_mode);
1100 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1101 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1102 LanguageMode language_mode);
1103 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1104 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1105 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1106 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1107 Handle<Object> value, LanguageMode language_mode);
1108 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1109 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1110 LanguageMode language_mode);
1111 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1112 LookupIterator* it, Handle<Object> value);
1113 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1114 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1115 LanguageMode language_mode, StoreFromKeyed store_mode);
1116 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1117 Handle<Object> object, Handle<Name> name,
1118 LanguageMode language_mode = SLOPPY);
1119 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1120 Isolate* isolate, Handle<Object> object, const char* key,
1121 LanguageMode language_mode = SLOPPY);
1122 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1123 Handle<Object> object, Handle<Name> name,
1124 LanguageMode language_mode = SLOPPY);
1126 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1127 LookupIterator* it, LanguageMode language_mode);
1128 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1129 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1131 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1132 Handle<Object> receiver,
1133 Handle<JSReceiver> getter);
1134 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1135 Handle<Object> receiver,
1136 Handle<JSReceiver> setter,
1137 Handle<Object> value);
1139 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1140 Isolate* isolate, Handle<Object> object, uint32_t index,
1141 LanguageMode language_mode = SLOPPY);
1143 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1144 Isolate* isolate, Handle<Object> object, uint32_t index,
1145 Handle<Object> value, LanguageMode language_mode);
1147 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1148 Isolate* isolate, Handle<Object> receiver);
1150 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1152 // Returns the permanent hash code associated with this object. May return
1153 // undefined if not yet created.
1156 // Returns undefined for JSObjects, but returns the hash code for simple
1157 // objects. This avoids a double lookup in the cases where we know we will
1158 // add the hash to the JSObject if it does not already exist.
1159 Object* GetSimpleHash();
1161 // Returns the permanent hash code associated with this object depending on
1162 // the actual object type. May create and store a hash code if needed and none
1164 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1166 // Checks whether this object has the same value as the given one. This
1167 // function is implemented according to ES5, section 9.12 and can be used
1168 // to implement the Harmony "egal" function.
1169 bool SameValue(Object* other);
1171 // Checks whether this object has the same value as the given one.
1172 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1173 // This function is implemented according to ES6, section 7.2.4 and is used
1174 // by ES6 Map and Set.
1175 bool SameValueZero(Object* other);
1177 // Tries to convert an object to an array length. Returns true and sets the
1178 // output parameter if it succeeds.
1179 inline bool ToArrayLength(uint32_t* index);
1181 // Tries to convert an object to an array index. Returns true and sets the
1182 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1183 // allow kMaxUInt32.
1184 inline bool ToArrayIndex(uint32_t* index);
1186 // Returns true if this is a JSValue containing a string and the index is
1187 // < the length of the string. Used to implement [] on strings.
1188 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1190 DECLARE_VERIFIER(Object)
1192 // Verify a pointer is a valid object pointer.
1193 static void VerifyPointer(Object* p);
1196 inline void VerifyApiCallResultType();
1198 // Prints this object without details.
1199 void ShortPrint(FILE* out = stdout);
1201 // Prints this object without details to a message accumulator.
1202 void ShortPrint(StringStream* accumulator);
1204 void ShortPrint(std::ostream& os); // NOLINT
1206 DECLARE_CAST(Object)
1208 // Layout description.
1209 static const int kHeaderSize = 0; // Object does not take up any space.
1212 // For our gdb macros, we should perhaps change these in the future.
1215 // Prints this object with details.
1216 void Print(std::ostream& os); // NOLINT
1218 void Print() { ShortPrint(); }
1219 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1223 friend class LookupIterator;
1224 friend class PrototypeIterator;
1226 // Return the map of the root of object's prototype chain.
1227 Map* GetRootMap(Isolate* isolate);
1229 // Helper for SetProperty and SetSuperProperty.
1230 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1231 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1232 StoreFromKeyed store_mode, bool* found);
1234 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1238 // In objects.h to be usable without objects-inl.h inclusion.
1239 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1240 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1244 explicit Brief(const Object* const v) : value(v) {}
1245 const Object* value;
1249 std::ostream& operator<<(std::ostream& os, const Brief& v);
1252 // Smi represents integer Numbers that can be stored in 31 bits.
1253 // Smis are immediate which means they are NOT allocated in the heap.
1254 // The this pointer has the following format: [31 bit signed int] 0
1255 // For long smis it has the following format:
1256 // [32 bit signed int] [31 bits zero padding] 0
1257 // Smi stands for small integer.
1258 class Smi: public Object {
1260 // Returns the integer value.
1261 inline int value() const { return Internals::SmiValue(this); }
1263 // Convert a value to a Smi object.
1264 static inline Smi* FromInt(int value) {
1265 DCHECK(Smi::IsValid(value));
1266 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1269 static inline Smi* FromIntptr(intptr_t value) {
1270 DCHECK(Smi::IsValid(value));
1271 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1272 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1275 // Returns whether value can be represented in a Smi.
1276 static inline bool IsValid(intptr_t value) {
1277 bool result = Internals::IsValidSmi(value);
1278 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1284 // Dispatched behavior.
1285 void SmiPrint(std::ostream& os) const; // NOLINT
1286 DECLARE_VERIFIER(Smi)
1288 static const int kMinValue =
1289 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1290 static const int kMaxValue = -(kMinValue + 1);
1293 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1297 // Heap objects typically have a map pointer in their first word. However,
1298 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1299 // encoded in the first word. The class MapWord is an abstraction of the
1300 // value in a heap object's first word.
1301 class MapWord BASE_EMBEDDED {
1303 // Normal state: the map word contains a map pointer.
1305 // Create a map word from a map pointer.
1306 static inline MapWord FromMap(const Map* map);
1308 // View this map word as a map pointer.
1309 inline Map* ToMap();
1312 // Scavenge collection: the map word of live objects in the from space
1313 // contains a forwarding address (a heap object pointer in the to space).
1315 // True if this map word is a forwarding address for a scavenge
1316 // collection. Only valid during a scavenge collection (specifically,
1317 // when all map words are heap object pointers, i.e. not during a full GC).
1318 inline bool IsForwardingAddress();
1320 // Create a map word from a forwarding address.
1321 static inline MapWord FromForwardingAddress(HeapObject* object);
1323 // View this map word as a forwarding address.
1324 inline HeapObject* ToForwardingAddress();
1326 static inline MapWord FromRawValue(uintptr_t value) {
1327 return MapWord(value);
1330 inline uintptr_t ToRawValue() {
1335 // HeapObject calls the private constructor and directly reads the value.
1336 friend class HeapObject;
1338 explicit MapWord(uintptr_t value) : value_(value) {}
1344 // The content of an heap object (except for the map pointer). kTaggedValues
1345 // objects can contain both heap pointers and Smis, kMixedValues can contain
1346 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1347 // objects can contain raw values and Smis.
1348 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1351 // HeapObject is the superclass for all classes describing heap allocated
1353 class HeapObject: public Object {
1355 // [map]: Contains a map which contains the object's reflective
1357 inline Map* map() const;
1358 inline void set_map(Map* value);
1359 // The no-write-barrier version. This is OK if the object is white and in
1360 // new space, or if the value is an immortal immutable object, like the maps
1361 // of primitive (non-JS) objects like strings, heap numbers etc.
1362 inline void set_map_no_write_barrier(Map* value);
1364 // Get the map using acquire load.
1365 inline Map* synchronized_map();
1366 inline MapWord synchronized_map_word() const;
1368 // Set the map using release store
1369 inline void synchronized_set_map(Map* value);
1370 inline void synchronized_set_map_no_write_barrier(Map* value);
1371 inline void synchronized_set_map_word(MapWord map_word);
1373 // During garbage collection, the map word of a heap object does not
1374 // necessarily contain a map pointer.
1375 inline MapWord map_word() const;
1376 inline void set_map_word(MapWord map_word);
1378 // The Heap the object was allocated in. Used also to access Isolate.
1379 inline Heap* GetHeap() const;
1381 // Convenience method to get current isolate.
1382 inline Isolate* GetIsolate() const;
1384 // Converts an address to a HeapObject pointer.
1385 static inline HeapObject* FromAddress(Address address) {
1386 DCHECK_TAG_ALIGNED(address);
1387 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1390 // Returns the address of this HeapObject.
1391 inline Address address() {
1392 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1395 // Iterates over pointers contained in the object (including the Map)
1396 void Iterate(ObjectVisitor* v);
1398 // Iterates over all pointers contained in the object except the
1399 // first map pointer. The object type is given in the first
1400 // parameter. This function does not access the map pointer in the
1401 // object, and so is safe to call while the map pointer is modified.
1402 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1404 // Returns the heap object's size in bytes
1407 // Indicates what type of values this heap object may contain.
1408 inline HeapObjectContents ContentType();
1410 // Given a heap object's map pointer, returns the heap size in bytes
1411 // Useful when the map pointer field is used for other purposes.
1413 inline int SizeFromMap(Map* map);
1415 // Returns the field at offset in obj, as a read/write Object* reference.
1416 // Does no checking, and is safe to use during GC, while maps are invalid.
1417 // Does not invoke write barrier, so should only be assigned to
1418 // during marking GC.
1419 static inline Object** RawField(HeapObject* obj, int offset);
1421 // Adds the |code| object related to |name| to the code cache of this map. If
1422 // this map is a dictionary map that is shared, the map copied and installed
1424 static void UpdateMapCodeCache(Handle<HeapObject> object,
1428 DECLARE_CAST(HeapObject)
1430 // Return the write barrier mode for this. Callers of this function
1431 // must be able to present a reference to an DisallowHeapAllocation
1432 // object as a sign that they are not going to use this function
1433 // from code that allocates and thus invalidates the returned write
1435 inline WriteBarrierMode GetWriteBarrierMode(
1436 const DisallowHeapAllocation& promise);
1438 // Dispatched behavior.
1439 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1441 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1443 DECLARE_PRINTER(HeapObject)
1444 DECLARE_VERIFIER(HeapObject)
1446 inline void VerifyObjectField(int offset);
1447 inline void VerifySmiField(int offset);
1449 // Verify a pointer is a valid HeapObject pointer that points to object
1450 // areas in the heap.
1451 static void VerifyHeapPointer(Object* p);
1454 inline AllocationAlignment RequiredAlignment();
1456 // Layout description.
1457 // First field in a heap object is map.
1458 static const int kMapOffset = Object::kHeaderSize;
1459 static const int kHeaderSize = kMapOffset + kPointerSize;
1461 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1464 // helpers for calling an ObjectVisitor to iterate over pointers in the
1465 // half-open range [start, end) specified as integer offsets
1466 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1467 // as above, for the single element at "offset"
1468 inline void IteratePointer(ObjectVisitor* v, int offset);
1469 // as above, for the next code link of a code object.
1470 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1473 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1477 // This class describes a body of an object of a fixed size
1478 // in which all pointer fields are located in the [start_offset, end_offset)
1480 template<int start_offset, int end_offset, int size>
1481 class FixedBodyDescriptor {
1483 static const int kStartOffset = start_offset;
1484 static const int kEndOffset = end_offset;
1485 static const int kSize = size;
1487 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1489 template<typename StaticVisitor>
1490 static inline void IterateBody(HeapObject* obj) {
1491 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1492 HeapObject::RawField(obj, end_offset));
1497 // This class describes a body of an object of a variable size
1498 // in which all pointer fields are located in the [start_offset, object_size)
1500 template<int start_offset>
1501 class FlexibleBodyDescriptor {
1503 static const int kStartOffset = start_offset;
1505 static inline void IterateBody(HeapObject* obj,
1509 template<typename StaticVisitor>
1510 static inline void IterateBody(HeapObject* obj, int object_size) {
1511 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1512 HeapObject::RawField(obj, object_size));
1517 // The HeapNumber class describes heap allocated numbers that cannot be
1518 // represented in a Smi (small integer)
1519 class HeapNumber: public HeapObject {
1521 // [value]: number value.
1522 inline double value() const;
1523 inline void set_value(double value);
1525 DECLARE_CAST(HeapNumber)
1527 // Dispatched behavior.
1528 bool HeapNumberBooleanValue();
1530 void HeapNumberPrint(std::ostream& os); // NOLINT
1531 DECLARE_VERIFIER(HeapNumber)
1533 inline int get_exponent();
1534 inline int get_sign();
1536 // Layout description.
1537 static const int kValueOffset = HeapObject::kHeaderSize;
1538 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1539 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1540 // words within double numbers are endian dependent and they are set
1542 #if defined(V8_TARGET_LITTLE_ENDIAN)
1543 static const int kMantissaOffset = kValueOffset;
1544 static const int kExponentOffset = kValueOffset + 4;
1545 #elif defined(V8_TARGET_BIG_ENDIAN)
1546 static const int kMantissaOffset = kValueOffset + 4;
1547 static const int kExponentOffset = kValueOffset;
1549 #error Unknown byte ordering
1552 static const int kSize = kValueOffset + kDoubleSize;
1553 static const uint32_t kSignMask = 0x80000000u;
1554 static const uint32_t kExponentMask = 0x7ff00000u;
1555 static const uint32_t kMantissaMask = 0xfffffu;
1556 static const int kMantissaBits = 52;
1557 static const int kExponentBits = 11;
1558 static const int kExponentBias = 1023;
1559 static const int kExponentShift = 20;
1560 static const int kInfinityOrNanExponent =
1561 (kExponentMask >> kExponentShift) - kExponentBias;
1562 static const int kMantissaBitsInTopWord = 20;
1563 static const int kNonMantissaBitsInTopWord = 12;
1566 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1570 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1571 class Simd128Value : public HeapObject {
1573 DECLARE_CAST(Simd128Value)
1575 DECLARE_PRINTER(Simd128Value)
1576 DECLARE_VERIFIER(Simd128Value)
1578 // Equality operations.
1579 inline bool Equals(Simd128Value* that);
1581 // Checks that another instance is bit-wise equal.
1582 bool BitwiseEquals(const Simd128Value* other) const;
1583 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1584 uint32_t Hash() const;
1585 // Copies the 16 bytes of SIMD data to the destination address.
1586 void CopyBits(void* destination) const;
1588 // Layout description.
1589 static const int kValueOffset = HeapObject::kHeaderSize;
1590 static const int kSize = kValueOffset + kSimd128Size;
1593 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1597 // V has parameters (TYPE, Type, type, lane count, lane type)
1598 #define SIMD128_TYPES(V) \
1599 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1600 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1601 V(UINT32X4, Uint32x4, uint32x4, 4, uint32_t) \
1602 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1603 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1604 V(UINT16X8, Uint16x8, uint16x8, 8, uint16_t) \
1605 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1606 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1607 V(UINT8X16, Uint8x16, uint8x16, 16, uint8_t) \
1608 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1610 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1611 class Type final : public Simd128Value { \
1613 inline lane_type get_lane(int lane) const; \
1614 inline void set_lane(int lane, lane_type value); \
1616 DECLARE_CAST(Type) \
1618 DECLARE_PRINTER(Type) \
1620 inline bool Equals(Type* that); \
1623 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1625 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1626 #undef SIMD128_VALUE_CLASS
1629 enum EnsureElementsMode {
1630 DONT_ALLOW_DOUBLE_ELEMENTS,
1631 ALLOW_COPIED_DOUBLE_ELEMENTS,
1632 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1636 // Indicator for one component of an AccessorPair.
1637 enum AccessorComponent {
1643 // JSReceiver includes types on which properties can be defined, i.e.,
1644 // JSObject and JSProxy.
1645 class JSReceiver: public HeapObject {
1647 DECLARE_CAST(JSReceiver)
1649 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1650 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1651 Handle<JSReceiver> object, Handle<Name> name);
1652 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1654 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1655 Handle<JSReceiver> object, uint32_t index);
1656 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1657 Handle<JSReceiver> object, uint32_t index);
1659 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1660 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1661 Handle<JSReceiver> object, Handle<Name> name,
1662 LanguageMode language_mode = SLOPPY);
1663 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1664 Handle<JSReceiver> object, Handle<Name> name,
1665 LanguageMode language_mode = SLOPPY);
1666 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1667 LookupIterator* it, LanguageMode language_mode);
1668 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1669 Handle<JSReceiver> object, uint32_t index,
1670 LanguageMode language_mode = SLOPPY);
1672 // Tests for the fast common case for property enumeration.
1673 bool IsSimpleEnum();
1675 // Returns the class name ([[Class]] property in the specification).
1676 String* class_name();
1678 // Returns the constructor name (the name (possibly, inferred name) of the
1679 // function that was used to instantiate the object).
1680 String* constructor_name();
1682 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1683 Handle<JSReceiver> object, Handle<Name> name);
1684 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1685 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1687 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1688 Handle<JSReceiver> object, uint32_t index);
1689 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1690 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1692 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1693 LookupIterator* it);
1696 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1698 static Handle<Object> GetDataProperty(LookupIterator* it);
1701 // Retrieves a permanent object identity hash code. The undefined value might
1702 // be returned in case no hash was created yet.
1703 inline Object* GetIdentityHash();
1705 // Retrieves a permanent object identity hash code. May create and store a
1706 // hash code if needed and none exists.
1707 inline static Handle<Smi> GetOrCreateIdentityHash(
1708 Handle<JSReceiver> object);
1710 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1712 // Computes the enumerable keys for a JSObject. Used for implementing
1713 // "for (n in object) { }".
1714 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1715 Handle<JSReceiver> object,
1716 KeyCollectionType type);
1719 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1723 // The JSObject describes real heap allocated JavaScript objects with
1725 // Note that the map of JSObject changes during execution to enable inline
1727 class JSObject: public JSReceiver {
1729 // [properties]: Backing storage for properties.
1730 // properties is a FixedArray in the fast case and a Dictionary in the
1732 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1733 inline void initialize_properties();
1734 inline bool HasFastProperties();
1735 // Gets slow properties for non-global objects.
1736 inline NameDictionary* property_dictionary();
1737 // Gets global object properties.
1738 inline GlobalDictionary* global_dictionary();
1740 // [elements]: The elements (properties with names that are integers).
1742 // Elements can be in two general modes: fast and slow. Each mode
1743 // corrensponds to a set of object representations of elements that
1744 // have something in common.
1746 // In the fast mode elements is a FixedArray and so each element can
1747 // be quickly accessed. This fact is used in the generated code. The
1748 // elements array can have one of three maps in this mode:
1749 // fixed_array_map, sloppy_arguments_elements_map or
1750 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1751 // the elements array may be shared by a few objects and so before
1752 // writing to any element the array must be copied. Use
1753 // EnsureWritableFastElements in this case.
1755 // In the slow mode the elements is either a NumberDictionary, a
1756 // FixedArray parameter map for a (sloppy) arguments object.
1757 DECL_ACCESSORS(elements, FixedArrayBase)
1758 inline void initialize_elements();
1759 static void ResetElements(Handle<JSObject> object);
1760 static inline void SetMapAndElements(Handle<JSObject> object,
1762 Handle<FixedArrayBase> elements);
1763 inline ElementsKind GetElementsKind();
1764 ElementsAccessor* GetElementsAccessor();
1765 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1766 inline bool HasFastSmiElements();
1767 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1768 inline bool HasFastObjectElements();
1769 // Returns true if an object has elements of FAST_ELEMENTS or
1770 // FAST_SMI_ONLY_ELEMENTS.
1771 inline bool HasFastSmiOrObjectElements();
1772 // Returns true if an object has any of the fast elements kinds.
1773 inline bool HasFastElements();
1774 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1776 inline bool HasFastDoubleElements();
1777 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1779 inline bool HasFastHoleyElements();
1780 inline bool HasSloppyArgumentsElements();
1781 inline bool HasDictionaryElements();
1783 inline bool HasFixedTypedArrayElements();
1785 inline bool HasFixedUint8ClampedElements();
1786 inline bool HasFixedArrayElements();
1787 inline bool HasFixedInt8Elements();
1788 inline bool HasFixedUint8Elements();
1789 inline bool HasFixedInt16Elements();
1790 inline bool HasFixedUint16Elements();
1791 inline bool HasFixedInt32Elements();
1792 inline bool HasFixedUint32Elements();
1793 inline bool HasFixedFloat32Elements();
1794 inline bool HasFixedFloat64Elements();
1796 inline bool HasFastArgumentsElements();
1797 inline bool HasSlowArgumentsElements();
1798 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1800 // Requires: HasFastElements().
1801 static Handle<FixedArray> EnsureWritableFastElements(
1802 Handle<JSObject> object);
1804 // Collects elements starting at index 0.
1805 // Undefined values are placed after non-undefined values.
1806 // Returns the number of non-undefined values.
1807 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1809 // As PrepareElementsForSort, but only on objects where elements is
1810 // a dictionary, and it will stay a dictionary. Collates undefined and
1811 // unexisting elements below limit from position zero of the elements.
1812 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1815 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1816 LookupIterator* it, Handle<Object> value);
1818 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1819 // grant an exemption to ExecutableAccessor callbacks in some cases.
1820 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1822 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1823 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1824 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1826 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1827 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1828 PropertyAttributes attributes,
1829 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1831 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1832 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1833 PropertyAttributes attributes,
1834 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1836 // Equivalent to one of the above depending on whether |name| can be converted
1837 // to an array index.
1838 MUST_USE_RESULT static MaybeHandle<Object>
1839 DefinePropertyOrElementIgnoreAttributes(
1840 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1841 PropertyAttributes attributes = NONE,
1842 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1844 // Adds or reconfigures a property to attributes NONE. It will fail when it
1846 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1847 Handle<Object> value);
1849 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1850 Handle<Object> value, PropertyAttributes attributes);
1852 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1853 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1854 PropertyAttributes attributes);
1856 // Extend the receiver with a single fast property appeared first in the
1857 // passed map. This also extends the property backing store if necessary.
1858 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1860 // Migrates the given object to a map whose field representations are the
1861 // lowest upper bound of all known representations for that field.
1862 static void MigrateInstance(Handle<JSObject> instance);
1864 // Migrates the given object only if the target map is already available,
1865 // or returns false if such a map is not yet available.
1866 static bool TryMigrateInstance(Handle<JSObject> instance);
1868 // Sets the property value in a normalized object given (key, value, details).
1869 // Handles the special representation of JS global objects.
1870 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1871 Handle<Object> value,
1872 PropertyDetails details);
1873 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1874 Handle<Object> value,
1875 PropertyAttributes attributes);
1876 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1878 Handle<Object> value,
1879 PropertyAttributes attributes);
1881 static void OptimizeAsPrototype(Handle<JSObject> object,
1882 PrototypeOptimizationMode mode);
1883 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1884 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1885 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1886 static void InvalidatePrototypeChains(Map* map);
1888 // Alternative implementation of WeakFixedArray::NullCallback.
1889 class PrototypeRegistryCompactionCallback {
1891 static void Callback(Object* value, int old_index, int new_index);
1894 // Retrieve interceptors.
1895 InterceptorInfo* GetNamedInterceptor();
1896 InterceptorInfo* GetIndexedInterceptor();
1898 // Used from JSReceiver.
1899 MUST_USE_RESULT static Maybe<PropertyAttributes>
1900 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1901 MUST_USE_RESULT static Maybe<PropertyAttributes>
1902 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1904 // Retrieves an AccessorPair property from the given object. Might return
1905 // undefined if the property doesn't exist or is of a different kind.
1906 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1907 Handle<JSObject> object,
1909 AccessorComponent component);
1911 // Defines an AccessorPair property on the given object.
1912 // TODO(mstarzinger): Rename to SetAccessor().
1913 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1915 Handle<Object> getter,
1916 Handle<Object> setter,
1917 PropertyAttributes attributes);
1919 // Defines an AccessorInfo property on the given object.
1920 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1921 Handle<JSObject> object,
1922 Handle<AccessorInfo> info);
1924 // The result must be checked first for exceptions. If there's no exception,
1925 // the output parameter |done| indicates whether the interceptor has a result
1927 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1928 LookupIterator* it, bool* done);
1930 // Accessors for hidden properties object.
1932 // Hidden properties are not own properties of the object itself.
1933 // Instead they are stored in an auxiliary structure kept as an own
1934 // property with a special name Heap::hidden_string(). But if the
1935 // receiver is a JSGlobalProxy then the auxiliary object is a property
1936 // of its prototype, and if it's a detached proxy, then you can't have
1937 // hidden properties.
1939 // Sets a hidden property on this object. Returns this object if successful,
1940 // undefined if called on a detached proxy.
1941 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1943 Handle<Object> value);
1944 // Gets the value of a hidden property with the given key. Returns the hole
1945 // if the property doesn't exist (or if called on a detached proxy),
1946 // otherwise returns the value set for the key.
1947 Object* GetHiddenProperty(Handle<Name> key);
1948 // Deletes a hidden property. Deleting a non-existing property is
1949 // considered successful.
1950 static void DeleteHiddenProperty(Handle<JSObject> object,
1952 // Returns true if the object has a property with the hidden string as name.
1953 static bool HasHiddenProperties(Handle<JSObject> object);
1955 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1957 static void ValidateElements(Handle<JSObject> object);
1959 // Makes sure that this object can contain HeapObject as elements.
1960 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1962 // Makes sure that this object can contain the specified elements.
1963 static inline void EnsureCanContainElements(
1964 Handle<JSObject> object,
1967 EnsureElementsMode mode);
1968 static inline void EnsureCanContainElements(
1969 Handle<JSObject> object,
1970 Handle<FixedArrayBase> elements,
1972 EnsureElementsMode mode);
1973 static void EnsureCanContainElements(
1974 Handle<JSObject> object,
1975 Arguments* arguments,
1978 EnsureElementsMode mode);
1980 // Would we convert a fast elements array to dictionary mode given
1981 // an access at key?
1982 bool WouldConvertToSlowElements(uint32_t index);
1984 // Computes the new capacity when expanding the elements of a JSObject.
1985 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1986 // (old_capacity + 50%) + 16
1987 return old_capacity + (old_capacity >> 1) + 16;
1990 // These methods do not perform access checks!
1991 static void UpdateAllocationSite(Handle<JSObject> object,
1992 ElementsKind to_kind);
1994 // Lookup interceptors are used for handling properties controlled by host
1996 inline bool HasNamedInterceptor();
1997 inline bool HasIndexedInterceptor();
1999 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2000 // by JSReceiver::GetKeys.
2001 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2002 Handle<JSObject> object,
2003 Handle<JSReceiver> receiver);
2004 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2005 Handle<JSObject> object,
2006 Handle<JSReceiver> receiver);
2008 // Support functions for v8 api (needed for correct interceptor behavior).
2009 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2010 Handle<JSObject> object, Handle<Name> name);
2011 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2012 Handle<JSObject> object, uint32_t index);
2013 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2014 Handle<JSObject> object, Handle<Name> name);
2016 // Get the header size for a JSObject. Used to compute the index of
2017 // internal fields as well as the number of internal fields.
2018 inline int GetHeaderSize();
2020 inline int GetInternalFieldCount();
2021 inline int GetInternalFieldOffset(int index);
2022 inline Object* GetInternalField(int index);
2023 inline void SetInternalField(int index, Object* value);
2024 inline void SetInternalField(int index, Smi* value);
2026 // Returns the number of properties on this object filtering out properties
2027 // with the specified attributes (ignoring interceptors).
2028 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2029 // Fill in details for properties into storage starting at the specified
2030 // index. Returns the number of properties added.
2031 int GetOwnPropertyNames(FixedArray* storage, int index,
2032 PropertyAttributes filter = NONE);
2034 // Returns the number of properties on this object filtering out properties
2035 // with the specified attributes (ignoring interceptors).
2036 int NumberOfOwnElements(PropertyAttributes filter);
2037 // Returns the number of enumerable elements (ignoring interceptors).
2038 int NumberOfEnumElements();
2039 // Returns the number of elements on this object filtering out elements
2040 // with the specified attributes (ignoring interceptors).
2041 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2042 // Count and fill in the enumerable elements into storage.
2043 // (storage->length() == NumberOfEnumElements()).
2044 // If storage is NULL, will count the elements without adding
2045 // them to any storage.
2046 // Returns the number of enumerable elements.
2047 int GetEnumElementKeys(FixedArray* storage);
2049 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2052 // Returns a new map with all transitions dropped from the object's current
2053 // map and the ElementsKind set.
2054 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2055 ElementsKind to_kind);
2056 static void TransitionElementsKind(Handle<JSObject> object,
2057 ElementsKind to_kind);
2059 // Always use this to migrate an object to a new map.
2060 // |expected_additional_properties| is only used for fast-to-slow transitions
2061 // and ignored otherwise.
2062 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2063 int expected_additional_properties = 0);
2065 // Convert the object to use the canonical dictionary
2066 // representation. If the object is expected to have additional properties
2067 // added this number can be indicated to have the backing store allocated to
2068 // an initial capacity for holding these properties.
2069 static void NormalizeProperties(Handle<JSObject> object,
2070 PropertyNormalizationMode mode,
2071 int expected_additional_properties,
2072 const char* reason);
2074 // Convert and update the elements backing store to be a
2075 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2076 static Handle<SeededNumberDictionary> NormalizeElements(
2077 Handle<JSObject> object);
2079 void RequireSlowElements(SeededNumberDictionary* dictionary);
2081 // Transform slow named properties to fast variants.
2082 static void MigrateSlowToFast(Handle<JSObject> object,
2083 int unused_property_fields, const char* reason);
2085 inline bool IsUnboxedDoubleField(FieldIndex index);
2087 // Access fast-case object properties at index.
2088 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2089 Representation representation,
2091 inline Object* RawFastPropertyAt(FieldIndex index);
2092 inline double RawFastDoublePropertyAt(FieldIndex index);
2094 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2095 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2096 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2097 inline void WriteToField(int descriptor, Object* value);
2099 // Access to in object properties.
2100 inline int GetInObjectPropertyOffset(int index);
2101 inline Object* InObjectPropertyAt(int index);
2102 inline Object* InObjectPropertyAtPut(int index,
2104 WriteBarrierMode mode
2105 = UPDATE_WRITE_BARRIER);
2107 // Set the object's prototype (only JSReceiver and null are allowed values).
2108 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2109 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2111 // Initializes the body after properties slot, properties slot is
2112 // initialized by set_properties. Fill the pre-allocated fields with
2113 // pre_allocated_value and the rest with filler_value.
2114 // Note: this call does not update write barrier, the caller is responsible
2115 // to ensure that |filler_value| can be collected without WB here.
2116 inline void InitializeBody(Map* map,
2117 Object* pre_allocated_value,
2118 Object* filler_value);
2120 // Check whether this object references another object
2121 bool ReferencesObject(Object* obj);
2123 // Disalow further properties to be added to the oject.
2124 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2125 Handle<JSObject> object);
2127 bool IsExtensible();
2130 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2132 // ES5 Object.freeze
2133 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2135 // Called the first time an object is observed with ES7 Object.observe.
2136 static void SetObserved(Handle<JSObject> object);
2139 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2141 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2142 Handle<JSObject> object,
2143 AllocationSiteUsageContext* site_context,
2144 DeepCopyHints hints = kNoHints);
2145 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2146 Handle<JSObject> object,
2147 AllocationSiteCreationContext* site_context);
2149 DECLARE_CAST(JSObject)
2151 // Dispatched behavior.
2152 void JSObjectShortPrint(StringStream* accumulator);
2153 DECLARE_PRINTER(JSObject)
2154 DECLARE_VERIFIER(JSObject)
2156 void PrintProperties(std::ostream& os); // NOLINT
2157 void PrintElements(std::ostream& os); // NOLINT
2159 #if defined(DEBUG) || defined(OBJECT_PRINT)
2160 void PrintTransitions(std::ostream& os); // NOLINT
2163 static void PrintElementsTransition(
2164 FILE* file, Handle<JSObject> object,
2165 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2166 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2168 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2171 // Structure for collecting spill information about JSObjects.
2172 class SpillInformation {
2176 int number_of_objects_;
2177 int number_of_objects_with_fast_properties_;
2178 int number_of_objects_with_fast_elements_;
2179 int number_of_fast_used_fields_;
2180 int number_of_fast_unused_fields_;
2181 int number_of_slow_used_properties_;
2182 int number_of_slow_unused_properties_;
2183 int number_of_fast_used_elements_;
2184 int number_of_fast_unused_elements_;
2185 int number_of_slow_used_elements_;
2186 int number_of_slow_unused_elements_;
2189 void IncrementSpillStatistics(SpillInformation* info);
2193 // If a GC was caused while constructing this object, the elements pointer
2194 // may point to a one pointer filler map. The object won't be rooted, but
2195 // our heap verification code could stumble across it.
2196 bool ElementsAreSafeToExamine();
2199 Object* SlowReverseLookup(Object* value);
2201 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2202 // Also maximal value of JSArray's length property.
2203 static const uint32_t kMaxElementCount = 0xffffffffu;
2205 // Constants for heuristics controlling conversion of fast elements
2206 // to slow elements.
2208 // Maximal gap that can be introduced by adding an element beyond
2209 // the current elements length.
2210 static const uint32_t kMaxGap = 1024;
2212 // Maximal length of fast elements array that won't be checked for
2213 // being dense enough on expansion.
2214 static const int kMaxUncheckedFastElementsLength = 5000;
2216 // Same as above but for old arrays. This limit is more strict. We
2217 // don't want to be wasteful with long lived objects.
2218 static const int kMaxUncheckedOldFastElementsLength = 500;
2220 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2221 // permissible values (see the DCHECK in heap.cc).
2222 static const int kInitialMaxFastElementArray = 100000;
2224 // This constant applies only to the initial map of "global.Object" and
2225 // not to arbitrary other JSObject maps.
2226 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2228 static const int kMaxInstanceSize = 255 * kPointerSize;
2229 // When extending the backing storage for property values, we increase
2230 // its size by more than the 1 entry necessary, so sequentially adding fields
2231 // to the same object requires fewer allocations and copies.
2232 static const int kFieldsAdded = 3;
2234 // Layout description.
2235 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2236 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2237 static const int kHeaderSize = kElementsOffset + kPointerSize;
2239 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2241 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2243 static inline int SizeOf(Map* map, HeapObject* object);
2246 Context* GetCreationContext();
2248 // Enqueue change record for Object.observe. May cause GC.
2249 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2250 Handle<JSObject> object, const char* type, Handle<Name> name,
2251 Handle<Object> old_value);
2253 // Gets the number of currently used elements.
2254 int GetFastElementsUsage();
2256 // Deletes an existing named property in a normalized object.
2257 static void DeleteNormalizedProperty(Handle<JSObject> object,
2258 Handle<Name> name, int entry);
2260 static bool AllCanRead(LookupIterator* it);
2261 static bool AllCanWrite(LookupIterator* it);
2264 friend class JSReceiver;
2265 friend class Object;
2267 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2268 static void MigrateFastToSlow(Handle<JSObject> object,
2269 Handle<Map> new_map,
2270 int expected_additional_properties);
2272 // Used from Object::GetProperty().
2273 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2274 LookupIterator* it);
2276 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2277 LookupIterator* it, Handle<Object> value);
2279 // Add a property to a slow-case object.
2280 static void AddSlowProperty(Handle<JSObject> object,
2282 Handle<Object> value,
2283 PropertyAttributes attributes);
2285 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2286 LookupIterator* it);
2288 bool ReferencesObjectFromElements(FixedArray* elements,
2292 // Return the hash table backing store or the inline stored identity hash,
2293 // whatever is found.
2294 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2296 // Return the hash table backing store for hidden properties. If there is no
2297 // backing store, allocate one.
2298 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2299 Handle<JSObject> object);
2301 // Set the hidden property backing store to either a hash table or
2302 // the inline-stored identity hash.
2303 static Handle<Object> SetHiddenPropertiesHashTable(
2304 Handle<JSObject> object,
2305 Handle<Object> value);
2307 MUST_USE_RESULT Object* GetIdentityHash();
2309 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2311 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2312 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2314 // Helper for fast versions of preventExtensions, seal, and freeze.
2315 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2316 template <PropertyAttributes attrs>
2317 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2318 Handle<JSObject> object);
2320 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2324 // Common superclass for FixedArrays that allow implementations to share
2325 // common accessors and some code paths.
2326 class FixedArrayBase: public HeapObject {
2328 // [length]: length of the array.
2329 inline int length() const;
2330 inline void set_length(int value);
2332 // Get and set the length using acquire loads and release stores.
2333 inline int synchronized_length() const;
2334 inline void synchronized_set_length(int value);
2336 DECLARE_CAST(FixedArrayBase)
2338 // Layout description.
2339 // Length is smi tagged when it is stored.
2340 static const int kLengthOffset = HeapObject::kHeaderSize;
2341 static const int kHeaderSize = kLengthOffset + kPointerSize;
2345 class FixedDoubleArray;
2346 class IncrementalMarking;
2349 // FixedArray describes fixed-sized arrays with element type Object*.
2350 class FixedArray: public FixedArrayBase {
2352 // Setter and getter for elements.
2353 inline Object* get(int index) const;
2354 void SetValue(uint32_t index, Object* value);
2355 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2356 // Setter that uses write barrier.
2357 inline void set(int index, Object* value);
2358 inline bool is_the_hole(int index);
2360 // Setter that doesn't need write barrier.
2361 inline void set(int index, Smi* value);
2362 // Setter with explicit barrier mode.
2363 inline void set(int index, Object* value, WriteBarrierMode mode);
2365 // Setters for frequently used oddballs located in old space.
2366 inline void set_undefined(int index);
2367 inline void set_null(int index);
2368 inline void set_the_hole(int index);
2370 inline Object** GetFirstElementAddress();
2371 inline bool ContainsOnlySmisOrHoles();
2373 // Gives access to raw memory which stores the array's data.
2374 inline Object** data_start();
2376 inline void FillWithHoles(int from, int to);
2378 // Shrink length and insert filler objects.
2379 void Shrink(int length);
2381 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2383 // Add the elements of a JSArray to this FixedArray.
2384 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2385 Handle<FixedArray> content, Handle<JSObject> array,
2386 KeyFilter filter = ALL_KEYS);
2388 // Computes the union of keys and return the result.
2389 // Used for implementing "for (n in object) { }"
2390 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2391 Handle<FixedArray> first,
2392 Handle<FixedArray> second);
2394 // Copy a sub array from the receiver to dest.
2395 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2397 // Garbage collection support.
2398 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2400 // Code Generation support.
2401 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2403 // Garbage collection support.
2404 inline Object** RawFieldOfElementAt(int index);
2406 DECLARE_CAST(FixedArray)
2408 // Maximal allowed size, in bytes, of a single FixedArray.
2409 // Prevents overflowing size computations, as well as extreme memory
2411 static const int kMaxSize = 128 * MB * kPointerSize;
2412 // Maximally allowed length of a FixedArray.
2413 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2415 // Dispatched behavior.
2416 DECLARE_PRINTER(FixedArray)
2417 DECLARE_VERIFIER(FixedArray)
2419 // Checks if two FixedArrays have identical contents.
2420 bool IsEqualTo(FixedArray* other);
2423 // Swap two elements in a pair of arrays. If this array and the
2424 // numbers array are the same object, the elements are only swapped
2426 void SwapPairs(FixedArray* numbers, int i, int j);
2428 // Sort prefix of this array and the numbers array as pairs wrt. the
2429 // numbers. If the numbers array and the this array are the same
2430 // object, the prefix of this array is sorted.
2431 void SortPairs(FixedArray* numbers, uint32_t len);
2433 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2435 static inline int SizeOf(Map* map, HeapObject* object);
2439 // Set operation on FixedArray without using write barriers. Can
2440 // only be used for storing old space objects or smis.
2441 static inline void NoWriteBarrierSet(FixedArray* array,
2445 // Set operation on FixedArray without incremental write barrier. Can
2446 // only be used if the object is guaranteed to be white (whiteness witness
2448 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2453 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2455 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2459 // FixedDoubleArray describes fixed-sized arrays with element type double.
2460 class FixedDoubleArray: public FixedArrayBase {
2462 // Setter and getter for elements.
2463 inline double get_scalar(int index);
2464 inline uint64_t get_representation(int index);
2465 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2466 // This accessor has to get a Number as |value|.
2467 void SetValue(uint32_t index, Object* value);
2468 inline void set(int index, double value);
2469 inline void set_the_hole(int index);
2471 // Checking for the hole.
2472 inline bool is_the_hole(int index);
2474 // Garbage collection support.
2475 inline static int SizeFor(int length) {
2476 return kHeaderSize + length * kDoubleSize;
2479 // Gives access to raw memory which stores the array's data.
2480 inline double* data_start();
2482 inline void FillWithHoles(int from, int to);
2484 // Code Generation support.
2485 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2487 DECLARE_CAST(FixedDoubleArray)
2489 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2490 // Prevents overflowing size computations, as well as extreme memory
2492 static const int kMaxSize = 512 * MB;
2493 // Maximally allowed length of a FixedArray.
2494 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2496 // Dispatched behavior.
2497 DECLARE_PRINTER(FixedDoubleArray)
2498 DECLARE_VERIFIER(FixedDoubleArray)
2501 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2505 class WeakFixedArray : public FixedArray {
2507 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2508 // This function does not check if the value exists already, callers must
2509 // ensure this themselves if necessary.
2510 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2511 Handle<HeapObject> value,
2512 int* assigned_index = NULL);
2514 // Returns true if an entry was found and removed.
2515 bool Remove(Handle<HeapObject> value);
2517 class NullCallback {
2519 static void Callback(Object* value, int old_index, int new_index) {}
2522 template <class CompactionCallback>
2525 inline Object* Get(int index) const;
2526 inline void Clear(int index);
2527 inline int Length() const;
2529 inline bool IsEmptySlot(int index) const;
2530 static Object* Empty() { return Smi::FromInt(0); }
2534 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2535 void Reset(Object* maybe_array);
2542 WeakFixedArray* list_;
2544 int last_used_index_;
2545 DisallowHeapAllocation no_gc_;
2547 DISALLOW_COPY_AND_ASSIGN(Iterator);
2550 DECLARE_CAST(WeakFixedArray)
2553 static const int kLastUsedIndexIndex = 0;
2554 static const int kFirstIndex = 1;
2556 static Handle<WeakFixedArray> Allocate(
2557 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2559 static void Set(Handle<WeakFixedArray> array, int index,
2560 Handle<HeapObject> value);
2561 inline void clear(int index);
2563 inline int last_used_index() const;
2564 inline void set_last_used_index(int index);
2566 // Disallow inherited setters.
2567 void set(int index, Smi* value);
2568 void set(int index, Object* value);
2569 void set(int index, Object* value, WriteBarrierMode mode);
2570 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2574 // Generic array grows dynamically with O(1) amortized insertion.
2575 class ArrayList : public FixedArray {
2579 // Use this if GC can delete elements from the array.
2580 kReloadLengthAfterAllocation,
2582 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2583 AddMode mode = kNone);
2584 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2585 Handle<Object> obj2, AddMode = kNone);
2586 inline int Length();
2587 inline void SetLength(int length);
2588 inline Object* Get(int index);
2589 inline Object** Slot(int index);
2590 inline void Set(int index, Object* obj);
2591 inline void Clear(int index, Object* undefined);
2592 DECLARE_CAST(ArrayList)
2595 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2596 static const int kLengthIndex = 0;
2597 static const int kFirstIndex = 1;
2598 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2602 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2603 // The format of the these objects is:
2604 // [0]: Number of descriptors
2605 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2606 // [0]: pointer to fixed array with enum cache
2607 // [1]: either Smi(0) or pointer to fixed array with indices
2609 // [2 + number of descriptors * kDescriptorSize]: start of slack
2610 class DescriptorArray: public FixedArray {
2612 // Returns true for both shared empty_descriptor_array and for smis, which the
2613 // map uses to encode additional bit fields when the descriptor array is not
2615 inline bool IsEmpty();
2617 // Returns the number of descriptors in the array.
2618 inline int number_of_descriptors();
2620 inline int number_of_descriptors_storage();
2622 inline int NumberOfSlackDescriptors();
2624 inline void SetNumberOfDescriptors(int number_of_descriptors);
2625 inline int number_of_entries();
2627 inline bool HasEnumCache();
2629 inline void CopyEnumCacheFrom(DescriptorArray* array);
2631 inline FixedArray* GetEnumCache();
2633 inline bool HasEnumIndicesCache();
2635 inline FixedArray* GetEnumIndicesCache();
2637 inline Object** GetEnumCacheSlot();
2639 void ClearEnumCache();
2641 // Initialize or change the enum cache,
2642 // using the supplied storage for the small "bridge".
2643 void SetEnumCache(FixedArray* bridge_storage,
2644 FixedArray* new_cache,
2645 Object* new_index_cache);
2647 bool CanHoldValue(int descriptor, Object* value);
2649 // Accessors for fetching instance descriptor at descriptor number.
2650 inline Name* GetKey(int descriptor_number);
2651 inline Object** GetKeySlot(int descriptor_number);
2652 inline Object* GetValue(int descriptor_number);
2653 inline void SetValue(int descriptor_number, Object* value);
2654 inline Object** GetValueSlot(int descriptor_number);
2655 static inline int GetValueOffset(int descriptor_number);
2656 inline Object** GetDescriptorStartSlot(int descriptor_number);
2657 inline Object** GetDescriptorEndSlot(int descriptor_number);
2658 inline PropertyDetails GetDetails(int descriptor_number);
2659 inline PropertyType GetType(int descriptor_number);
2660 inline int GetFieldIndex(int descriptor_number);
2661 inline HeapType* GetFieldType(int descriptor_number);
2662 inline Object* GetConstant(int descriptor_number);
2663 inline Object* GetCallbacksObject(int descriptor_number);
2664 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2666 inline Name* GetSortedKey(int descriptor_number);
2667 inline int GetSortedKeyIndex(int descriptor_number);
2668 inline void SetSortedKey(int pointer, int descriptor_number);
2669 inline void SetRepresentation(int descriptor_number,
2670 Representation representation);
2672 // Accessor for complete descriptor.
2673 inline void Get(int descriptor_number, Descriptor* desc);
2674 inline void Set(int descriptor_number, Descriptor* desc);
2675 void Replace(int descriptor_number, Descriptor* descriptor);
2677 // Append automatically sets the enumeration index. This should only be used
2678 // to add descriptors in bulk at the end, followed by sorting the descriptor
2680 inline void Append(Descriptor* desc);
2682 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2683 int enumeration_index,
2686 static Handle<DescriptorArray> CopyUpToAddAttributes(
2687 Handle<DescriptorArray> desc,
2688 int enumeration_index,
2689 PropertyAttributes attributes,
2692 // Sort the instance descriptors by the hash codes of their keys.
2695 // Search the instance descriptors for given name.
2696 INLINE(int Search(Name* name, int number_of_own_descriptors));
2698 // As the above, but uses DescriptorLookupCache and updates it when
2700 INLINE(int SearchWithCache(Name* name, Map* map));
2702 // Allocates a DescriptorArray, but returns the singleton
2703 // empty descriptor array object if number_of_descriptors is 0.
2704 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2705 int number_of_descriptors,
2708 DECLARE_CAST(DescriptorArray)
2710 // Constant for denoting key was not found.
2711 static const int kNotFound = -1;
2713 static const int kDescriptorLengthIndex = 0;
2714 static const int kEnumCacheIndex = 1;
2715 static const int kFirstIndex = 2;
2717 // The length of the "bridge" to the enum cache.
2718 static const int kEnumCacheBridgeLength = 2;
2719 static const int kEnumCacheBridgeCacheIndex = 0;
2720 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2722 // Layout description.
2723 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2724 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2725 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2727 // Layout description for the bridge array.
2728 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2730 // Layout of descriptor.
2731 static const int kDescriptorKey = 0;
2732 static const int kDescriptorDetails = 1;
2733 static const int kDescriptorValue = 2;
2734 static const int kDescriptorSize = 3;
2736 #if defined(DEBUG) || defined(OBJECT_PRINT)
2737 // For our gdb macros, we should perhaps change these in the future.
2740 // Print all the descriptors.
2741 void PrintDescriptors(std::ostream& os); // NOLINT
2745 // Is the descriptor array sorted and without duplicates?
2746 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2748 // Is the descriptor array consistent with the back pointers in targets?
2749 bool IsConsistentWithBackPointers(Map* current_map);
2751 // Are two DescriptorArrays equal?
2752 bool IsEqualTo(DescriptorArray* other);
2755 // Returns the fixed array length required to hold number_of_descriptors
2757 static int LengthFor(int number_of_descriptors) {
2758 return ToKeyIndex(number_of_descriptors);
2762 // WhitenessWitness is used to prove that a descriptor array is white
2763 // (unmarked), so incremental write barriers can be skipped because the
2764 // marking invariant cannot be broken and slots pointing into evacuation
2765 // candidates will be discovered when the object is scanned. A witness is
2766 // always stack-allocated right after creating an array. By allocating a
2767 // witness, incremental marking is globally disabled. The witness is then
2768 // passed along wherever needed to statically prove that the array is known to
2770 class WhitenessWitness {
2772 inline explicit WhitenessWitness(DescriptorArray* array);
2773 inline ~WhitenessWitness();
2776 IncrementalMarking* marking_;
2779 // An entry in a DescriptorArray, represented as an (array, index) pair.
2782 inline explicit Entry(DescriptorArray* descs, int index) :
2783 descs_(descs), index_(index) { }
2785 inline PropertyType type();
2786 inline Object* GetCallbackObject();
2789 DescriptorArray* descs_;
2793 // Conversion from descriptor number to array indices.
2794 static int ToKeyIndex(int descriptor_number) {
2795 return kFirstIndex +
2796 (descriptor_number * kDescriptorSize) +
2800 static int ToDetailsIndex(int descriptor_number) {
2801 return kFirstIndex +
2802 (descriptor_number * kDescriptorSize) +
2806 static int ToValueIndex(int descriptor_number) {
2807 return kFirstIndex +
2808 (descriptor_number * kDescriptorSize) +
2812 // Transfer a complete descriptor from the src descriptor array to this
2813 // descriptor array.
2814 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2816 inline void Set(int descriptor_number,
2818 const WhitenessWitness&);
2820 // Swap first and second descriptor.
2821 inline void SwapSortedKeys(int first, int second);
2823 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2827 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2829 template <SearchMode search_mode, typename T>
2830 inline int Search(T* array, Name* name, int valid_entries = 0,
2831 int* out_insertion_index = NULL);
2834 // HashTable is a subclass of FixedArray that implements a hash table
2835 // that uses open addressing and quadratic probing.
2837 // In order for the quadratic probing to work, elements that have not
2838 // yet been used and elements that have been deleted are
2839 // distinguished. Probing continues when deleted elements are
2840 // encountered and stops when unused elements are encountered.
2842 // - Elements with key == undefined have not been used yet.
2843 // - Elements with key == the_hole have been deleted.
2845 // The hash table class is parameterized with a Shape and a Key.
2846 // Shape must be a class with the following interface:
2847 // class ExampleShape {
2849 // // Tells whether key matches other.
2850 // static bool IsMatch(Key key, Object* other);
2851 // // Returns the hash value for key.
2852 // static uint32_t Hash(Key key);
2853 // // Returns the hash value for object.
2854 // static uint32_t HashForObject(Key key, Object* object);
2855 // // Convert key to an object.
2856 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2857 // // The prefix size indicates number of elements in the beginning
2858 // // of the backing storage.
2859 // static const int kPrefixSize = ..;
2860 // // The Element size indicates number of elements per entry.
2861 // static const int kEntrySize = ..;
2863 // The prefix size indicates an amount of memory in the
2864 // beginning of the backing storage that can be used for non-element
2865 // information by subclasses.
2867 template<typename Key>
2870 static const bool UsesSeed = false;
2871 static uint32_t Hash(Key key) { return 0; }
2872 static uint32_t SeededHash(Key key, uint32_t seed) {
2876 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2877 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2879 return HashForObject(key, object);
2884 class HashTableBase : public FixedArray {
2886 // Returns the number of elements in the hash table.
2887 inline int NumberOfElements();
2889 // Returns the number of deleted elements in the hash table.
2890 inline int NumberOfDeletedElements();
2892 // Returns the capacity of the hash table.
2893 inline int Capacity();
2895 // ElementAdded should be called whenever an element is added to a
2897 inline void ElementAdded();
2899 // ElementRemoved should be called whenever an element is removed from
2901 inline void ElementRemoved();
2902 inline void ElementsRemoved(int n);
2904 // Computes the required capacity for a table holding the given
2905 // number of elements. May be more than HashTable::kMaxCapacity.
2906 static inline int ComputeCapacity(int at_least_space_for);
2908 // Tells whether k is a real key. The hole and undefined are not allowed
2909 // as keys and can be used to indicate missing or deleted elements.
2910 inline bool IsKey(Object* k);
2912 // Compute the probe offset (quadratic probing).
2913 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2914 return (n + n * n) >> 1;
2917 static const int kNumberOfElementsIndex = 0;
2918 static const int kNumberOfDeletedElementsIndex = 1;
2919 static const int kCapacityIndex = 2;
2920 static const int kPrefixStartIndex = 3;
2922 // Constant used for denoting a absent entry.
2923 static const int kNotFound = -1;
2926 // Update the number of elements in the hash table.
2927 inline void SetNumberOfElements(int nof);
2929 // Update the number of deleted elements in the hash table.
2930 inline void SetNumberOfDeletedElements(int nod);
2932 // Returns probe entry.
2933 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2934 DCHECK(base::bits::IsPowerOfTwo32(size));
2935 return (hash + GetProbeOffset(number)) & (size - 1);
2938 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2939 return hash & (size - 1);
2942 inline static uint32_t NextProbe(
2943 uint32_t last, uint32_t number, uint32_t size) {
2944 return (last + number) & (size - 1);
2949 template <typename Derived, typename Shape, typename Key>
2950 class HashTable : public HashTableBase {
2953 inline uint32_t Hash(Key key) {
2954 if (Shape::UsesSeed) {
2955 return Shape::SeededHash(key, GetHeap()->HashSeed());
2957 return Shape::Hash(key);
2961 inline uint32_t HashForObject(Key key, Object* object) {
2962 if (Shape::UsesSeed) {
2963 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2965 return Shape::HashForObject(key, object);
2969 // Returns a new HashTable object.
2970 MUST_USE_RESULT static Handle<Derived> New(
2971 Isolate* isolate, int at_least_space_for,
2972 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2973 PretenureFlag pretenure = NOT_TENURED);
2975 DECLARE_CAST(HashTable)
2977 // Garbage collection support.
2978 void IteratePrefix(ObjectVisitor* visitor);
2979 void IterateElements(ObjectVisitor* visitor);
2981 // Find entry for key otherwise return kNotFound.
2982 inline int FindEntry(Key key);
2983 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2984 int FindEntry(Isolate* isolate, Key key);
2986 // Rehashes the table in-place.
2987 void Rehash(Key key);
2989 // Returns the key at entry.
2990 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2992 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
2993 static const int kEntrySize = Shape::kEntrySize;
2994 static const int kElementsStartOffset =
2995 kHeaderSize + kElementsStartIndex * kPointerSize;
2996 static const int kCapacityOffset =
2997 kHeaderSize + kCapacityIndex * kPointerSize;
2999 // Returns the index for an entry (of the key)
3000 static inline int EntryToIndex(int entry) {
3001 return (entry * kEntrySize) + kElementsStartIndex;
3005 friend class ObjectHashTable;
3007 // Find the entry at which to insert element with the given key that
3008 // has the given hash value.
3009 uint32_t FindInsertionEntry(uint32_t hash);
3011 // Attempt to shrink hash table after removal of key.
3012 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3014 // Ensure enough space for n additional elements.
3015 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3016 Handle<Derived> table,
3019 PretenureFlag pretenure = NOT_TENURED);
3021 // Sets the capacity of the hash table.
3022 void SetCapacity(int capacity) {
3023 // To scale a computed hash code to fit within the hash table, we
3024 // use bit-wise AND with a mask, so the capacity must be positive
3026 DCHECK(capacity > 0);
3027 DCHECK(capacity <= kMaxCapacity);
3028 set(kCapacityIndex, Smi::FromInt(capacity));
3031 // Maximal capacity of HashTable. Based on maximal length of underlying
3032 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3034 static const int kMaxCapacity =
3035 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3038 // Returns _expected_ if one of entries given by the first _probe_ probes is
3039 // equal to _expected_. Otherwise, returns the entry given by the probe
3041 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3043 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3045 // Rehashes this hash-table into the new table.
3046 void Rehash(Handle<Derived> new_table, Key key);
3050 // HashTableKey is an abstract superclass for virtual key behavior.
3051 class HashTableKey {
3053 // Returns whether the other object matches this key.
3054 virtual bool IsMatch(Object* other) = 0;
3055 // Returns the hash value for this key.
3056 virtual uint32_t Hash() = 0;
3057 // Returns the hash value for object.
3058 virtual uint32_t HashForObject(Object* key) = 0;
3059 // Returns the key object for storing into the hash table.
3060 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3062 virtual ~HashTableKey() {}
3066 class StringTableShape : public BaseShape<HashTableKey*> {
3068 static inline bool IsMatch(HashTableKey* key, Object* value) {
3069 return key->IsMatch(value);
3072 static inline uint32_t Hash(HashTableKey* key) {
3076 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3077 return key->HashForObject(object);
3080 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3082 static const int kPrefixSize = 0;
3083 static const int kEntrySize = 1;
3086 class SeqOneByteString;
3090 // No special elements in the prefix and the element size is 1
3091 // because only the string itself (the key) needs to be stored.
3092 class StringTable: public HashTable<StringTable,
3096 // Find string in the string table. If it is not there yet, it is
3097 // added. The return value is the string found.
3098 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3099 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3100 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3102 // Tries to internalize given string and returns string handle on success
3103 // or an empty handle otherwise.
3104 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3106 Handle<String> string);
3108 // Looks up a string that is equal to the given string and returns
3109 // string handle if it is found, or an empty handle otherwise.
3110 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3112 Handle<String> str);
3113 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3118 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3120 DECLARE_CAST(StringTable)
3123 template <bool seq_one_byte>
3124 friend class JsonParser;
3126 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3130 template <typename Derived, typename Shape, typename Key>
3131 class Dictionary: public HashTable<Derived, Shape, Key> {
3132 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3135 // Returns the value at entry.
3136 Object* ValueAt(int entry) {
3137 return this->get(Derived::EntryToIndex(entry) + 1);
3140 // Set the value for entry.
3141 void ValueAtPut(int entry, Object* value) {
3142 this->set(Derived::EntryToIndex(entry) + 1, value);
3145 // Returns the property details for the property at entry.
3146 PropertyDetails DetailsAt(int entry) {
3147 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3150 // Set the details for entry.
3151 void DetailsAtPut(int entry, PropertyDetails value) {
3152 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3155 // Returns true if property at given entry is deleted.
3156 bool IsDeleted(int entry) {
3157 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3160 // Delete a property from the dictionary.
3161 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3163 // Attempt to shrink the dictionary after deletion of key.
3164 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3165 Handle<Derived> dictionary,
3167 return DerivedHashTable::Shrink(dictionary, key);
3171 // TODO(dcarney): templatize or move to SeededNumberDictionary
3172 void CopyValuesTo(FixedArray* elements);
3174 // Returns the number of elements in the dictionary filtering out properties
3175 // with the specified attributes.
3176 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3178 // Returns the number of enumerable elements in the dictionary.
3179 int NumberOfEnumElements() {
3180 return NumberOfElementsFilterAttributes(
3181 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3184 // Returns true if the dictionary contains any elements that are non-writable,
3185 // non-configurable, non-enumerable, or have getters/setters.
3186 bool HasComplexElements();
3188 enum SortMode { UNSORTED, SORTED };
3190 // Fill in details for properties into storage.
3191 // Returns the number of properties added.
3192 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3193 SortMode sort_mode);
3195 // Copies enumerable keys to preallocated fixed array.
3196 void CopyEnumKeysTo(FixedArray* storage);
3198 // Accessors for next enumeration index.
3199 void SetNextEnumerationIndex(int index) {
3201 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3204 int NextEnumerationIndex() {
3205 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3208 // Creates a new dictionary.
3209 MUST_USE_RESULT static Handle<Derived> New(
3211 int at_least_space_for,
3212 PretenureFlag pretenure = NOT_TENURED);
3214 // Ensure enough space for n additional elements.
3215 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3218 void Print(std::ostream& os); // NOLINT
3220 // Returns the key (slow).
3221 Object* SlowReverseLookup(Object* value);
3223 // Sets the entry to (key, value) pair.
3224 inline void SetEntry(int entry,
3226 Handle<Object> value);
3227 inline void SetEntry(int entry,
3229 Handle<Object> value,
3230 PropertyDetails details);
3232 MUST_USE_RESULT static Handle<Derived> Add(
3233 Handle<Derived> dictionary,
3235 Handle<Object> value,
3236 PropertyDetails details);
3238 // Returns iteration indices array for the |dictionary|.
3239 // Values are direct indices in the |HashTable| array.
3240 static Handle<FixedArray> BuildIterationIndicesArray(
3241 Handle<Derived> dictionary);
3244 // Generic at put operation.
3245 MUST_USE_RESULT static Handle<Derived> AtPut(
3246 Handle<Derived> dictionary,
3248 Handle<Object> value);
3250 // Add entry to dictionary.
3251 static void AddEntry(
3252 Handle<Derived> dictionary,
3254 Handle<Object> value,
3255 PropertyDetails details,
3258 // Generate new enumeration indices to avoid enumeration index overflow.
3259 // Returns iteration indices array for the |dictionary|.
3260 static Handle<FixedArray> GenerateNewEnumerationIndices(
3261 Handle<Derived> dictionary);
3262 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3263 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3267 template <typename Derived, typename Shape>
3268 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3269 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3272 // Find entry for key, otherwise return kNotFound. Optimized version of
3273 // HashTable::FindEntry.
3274 int FindEntry(Handle<Name> key);
3278 template <typename Key>
3279 class BaseDictionaryShape : public BaseShape<Key> {
3281 template <typename Dictionary>
3282 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3283 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3284 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3285 return PropertyDetails(
3286 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3289 template <typename Dictionary>
3290 static inline void DetailsAtPut(Dictionary* dict, int entry,
3291 PropertyDetails value) {
3292 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3293 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3296 template <typename Dictionary>
3297 static bool IsDeleted(Dictionary* dict, int entry) {
3301 template <typename Dictionary>
3302 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3303 Handle<Object> value, PropertyDetails details);
3307 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3309 static inline bool IsMatch(Handle<Name> key, Object* other);
3310 static inline uint32_t Hash(Handle<Name> key);
3311 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3312 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3313 static const int kPrefixSize = 2;
3314 static const int kEntrySize = 3;
3315 static const bool kIsEnumerable = true;
3319 class NameDictionary
3320 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3321 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3325 DECLARE_CAST(NameDictionary)
3327 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3328 Handle<NameDictionary> dictionary);
3332 class GlobalDictionaryShape : public NameDictionaryShape {
3334 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3336 template <typename Dictionary>
3337 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3339 template <typename Dictionary>
3340 static inline void DetailsAtPut(Dictionary* dict, int entry,
3341 PropertyDetails value);
3343 template <typename Dictionary>
3344 static bool IsDeleted(Dictionary* dict, int entry);
3346 template <typename Dictionary>
3347 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3348 Handle<Object> value, PropertyDetails details);
3352 class GlobalDictionary
3353 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3355 DECLARE_CAST(GlobalDictionary)
3359 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3361 static inline bool IsMatch(uint32_t key, Object* other);
3362 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3363 static const int kEntrySize = 3;
3364 static const bool kIsEnumerable = false;
3368 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3370 static const bool UsesSeed = true;
3371 static const int kPrefixSize = 2;
3373 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3374 static inline uint32_t SeededHashForObject(uint32_t key,
3380 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3382 static const int kPrefixSize = 0;
3384 static inline uint32_t Hash(uint32_t key);
3385 static inline uint32_t HashForObject(uint32_t key, Object* object);
3389 class SeededNumberDictionary
3390 : public Dictionary<SeededNumberDictionary,
3391 SeededNumberDictionaryShape,
3394 DECLARE_CAST(SeededNumberDictionary)
3396 // Type specific at put (default NONE attributes is used when adding).
3397 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3398 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3399 Handle<Object> value, bool used_as_prototype);
3400 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3401 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3402 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3404 // Set an existing entry or add a new one if needed.
3405 // Return the updated dictionary.
3406 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3407 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3408 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3410 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3412 // If slow elements are required we will never go back to fast-case
3413 // for the elements kept in this dictionary. We require slow
3414 // elements if an element has been added at an index larger than
3415 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3416 // when defining a getter or setter with a number key.
3417 inline bool requires_slow_elements();
3418 inline void set_requires_slow_elements();
3420 // Get the value of the max number key that has been added to this
3421 // dictionary. max_number_key can only be called if
3422 // requires_slow_elements returns false.
3423 inline uint32_t max_number_key();
3426 static const int kRequiresSlowElementsMask = 1;
3427 static const int kRequiresSlowElementsTagSize = 1;
3428 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3432 class UnseededNumberDictionary
3433 : public Dictionary<UnseededNumberDictionary,
3434 UnseededNumberDictionaryShape,
3437 DECLARE_CAST(UnseededNumberDictionary)
3439 // Type specific at put (default NONE attributes is used when adding).
3440 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3441 Handle<UnseededNumberDictionary> dictionary,
3443 Handle<Object> value);
3444 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3445 Handle<UnseededNumberDictionary> dictionary,
3447 Handle<Object> value);
3449 // Set an existing entry or add a new one if needed.
3450 // Return the updated dictionary.
3451 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3452 Handle<UnseededNumberDictionary> dictionary,
3454 Handle<Object> value);
3458 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3460 static inline bool IsMatch(Handle<Object> key, Object* other);
3461 static inline uint32_t Hash(Handle<Object> key);
3462 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3463 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3464 static const int kPrefixSize = 0;
3465 static const int kEntrySize = 2;
3469 // ObjectHashTable maps keys that are arbitrary objects to object values by
3470 // using the identity hash of the key for hashing purposes.
3471 class ObjectHashTable: public HashTable<ObjectHashTable,
3472 ObjectHashTableShape,
3475 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3477 DECLARE_CAST(ObjectHashTable)
3479 // Attempt to shrink hash table after removal of key.
3480 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3481 Handle<ObjectHashTable> table,
3482 Handle<Object> key);
3484 // Looks up the value associated with the given key. The hole value is
3485 // returned in case the key is not present.
3486 Object* Lookup(Handle<Object> key);
3487 Object* Lookup(Handle<Object> key, int32_t hash);
3488 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3490 // Adds (or overwrites) the value associated with the given key.
3491 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3493 Handle<Object> value);
3494 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3495 Handle<Object> key, Handle<Object> value,
3498 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3499 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3502 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3503 Handle<Object> key, bool* was_present,
3507 friend class MarkCompactCollector;
3509 void AddEntry(int entry, Object* key, Object* value);
3510 void RemoveEntry(int entry);
3512 // Returns the index to the value of an entry.
3513 static inline int EntryToValueIndex(int entry) {
3514 return EntryToIndex(entry) + 1;
3519 // OrderedHashTable is a HashTable with Object keys that preserves
3520 // insertion order. There are Map and Set interfaces (OrderedHashMap
3521 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3523 // Only Object* keys are supported, with Object::SameValueZero() used as the
3524 // equality operator and Object::GetHash() for the hash function.
3526 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3527 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3528 // Originally attributed to Tyler Close.
3531 // [0]: bucket count
3532 // [1]: element count
3533 // [2]: deleted element count
3534 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3535 // offset into the data table (see below) where the
3536 // first item in this bucket is stored.
3537 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3538 // Capacity() * kEntrySize, where the first entrysize
3539 // items are handled by the derived class and the
3540 // item at kChainOffset is another entry into the
3541 // data table indicating the next entry in this hash
3544 // When we transition the table to a new version we obsolete it and reuse parts
3545 // of the memory to store information how to transition an iterator to the new
3548 // Memory layout for obsolete table:
3549 // [0]: bucket count
3550 // [1]: Next newer table
3551 // [2]: Number of removed holes or -1 when the table was cleared.
3552 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3553 // [3 + NumberOfRemovedHoles()..length]: Not used
3555 template<class Derived, class Iterator, int entrysize>
3556 class OrderedHashTable: public FixedArray {
3558 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3559 static Handle<Derived> Allocate(
3560 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3562 // Returns an OrderedHashTable (possibly |table|) with enough space
3563 // to add at least one new element.
3564 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3566 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3568 static Handle<Derived> Shrink(Handle<Derived> table);
3570 // Returns a new empty OrderedHashTable and records the clearing so that
3571 // exisiting iterators can be updated.
3572 static Handle<Derived> Clear(Handle<Derived> table);
3574 int NumberOfElements() {
3575 return Smi::cast(get(kNumberOfElementsIndex))->value();
3578 int NumberOfDeletedElements() {
3579 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3582 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3584 int NumberOfBuckets() {
3585 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3588 // Returns an index into |this| for the given entry.
3589 int EntryToIndex(int entry) {
3590 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3593 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3596 return !get(kNextTableIndex)->IsSmi();
3599 // The next newer table. This is only valid if the table is obsolete.
3600 Derived* NextTable() {
3601 return Derived::cast(get(kNextTableIndex));
3604 // When the table is obsolete we store the indexes of the removed holes.
3605 int RemovedIndexAt(int index) {
3606 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3609 static const int kNotFound = -1;
3610 static const int kMinCapacity = 4;
3612 static const int kNumberOfBucketsIndex = 0;
3613 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3614 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3615 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3616 static const int kNextTableIndex = kNumberOfElementsIndex;
3618 static const int kNumberOfBucketsOffset =
3619 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3620 static const int kNumberOfElementsOffset =
3621 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3622 static const int kNumberOfDeletedElementsOffset =
3623 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3624 static const int kHashTableStartOffset =
3625 kHeaderSize + kHashTableStartIndex * kPointerSize;
3626 static const int kNextTableOffset =
3627 kHeaderSize + kNextTableIndex * kPointerSize;
3629 static const int kEntrySize = entrysize + 1;
3630 static const int kChainOffset = entrysize;
3632 static const int kLoadFactor = 2;
3634 // NumberOfDeletedElements is set to kClearedTableSentinel when
3635 // the table is cleared, which allows iterator transitions to
3636 // optimize that case.
3637 static const int kClearedTableSentinel = -1;
3640 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3642 void SetNumberOfBuckets(int num) {
3643 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3646 void SetNumberOfElements(int num) {
3647 set(kNumberOfElementsIndex, Smi::FromInt(num));
3650 void SetNumberOfDeletedElements(int num) {
3651 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3655 return NumberOfBuckets() * kLoadFactor;
3658 void SetNextTable(Derived* next_table) {
3659 set(kNextTableIndex, next_table);
3662 void SetRemovedIndexAt(int index, int removed_index) {
3663 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3666 static const int kRemovedHolesIndex = kHashTableStartIndex;
3668 static const int kMaxCapacity =
3669 (FixedArray::kMaxLength - kHashTableStartIndex)
3670 / (1 + (kEntrySize * kLoadFactor));
3674 class JSSetIterator;
3677 class OrderedHashSet: public OrderedHashTable<
3678 OrderedHashSet, JSSetIterator, 1> {
3680 DECLARE_CAST(OrderedHashSet)
3684 class JSMapIterator;
3687 class OrderedHashMap
3688 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3690 DECLARE_CAST(OrderedHashMap)
3692 inline Object* ValueAt(int entry);
3694 static const int kValueOffset = 1;
3698 template <int entrysize>
3699 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3701 static inline bool IsMatch(Handle<Object> key, Object* other);
3702 static inline uint32_t Hash(Handle<Object> key);
3703 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3704 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3705 static const int kPrefixSize = 0;
3706 static const int kEntrySize = entrysize;
3710 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3711 // values. The table wraps the keys in weak cells and store values directly.
3712 // Thus it references keys weakly and values strongly.
3713 class WeakHashTable: public HashTable<WeakHashTable,
3714 WeakHashTableShape<2>,
3717 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3719 DECLARE_CAST(WeakHashTable)
3721 // Looks up the value associated with the given key. The hole value is
3722 // returned in case the key is not present.
3723 Object* Lookup(Handle<HeapObject> key);
3725 // Adds (or overwrites) the value associated with the given key. Mapping a
3726 // key to the hole value causes removal of the whole entry.
3727 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3728 Handle<HeapObject> key,
3729 Handle<HeapObject> value);
3731 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3734 friend class MarkCompactCollector;
3736 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3738 // Returns the index to the value of an entry.
3739 static inline int EntryToValueIndex(int entry) {
3740 return EntryToIndex(entry) + 1;
3745 // ScopeInfo represents information about different scopes of a source
3746 // program and the allocation of the scope's variables. Scope information
3747 // is stored in a compressed form in ScopeInfo objects and is used
3748 // at runtime (stack dumps, deoptimization, etc.).
3750 // This object provides quick access to scope info details for runtime
3752 class ScopeInfo : public FixedArray {
3754 DECLARE_CAST(ScopeInfo)
3756 // Return the type of this scope.
3757 ScopeType scope_type();
3759 // Does this scope call eval?
3762 // Return the language mode of this scope.
3763 LanguageMode language_mode();
3765 // True if this scope is a (var) declaration scope.
3766 bool is_declaration_scope();
3768 // Does this scope make a sloppy eval call?
3769 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3771 // Return the total number of locals allocated on the stack and in the
3772 // context. This includes the parameters that are allocated in the context.
3775 // Return the number of stack slots for code. This number consists of two
3777 // 1. One stack slot per stack allocated local.
3778 // 2. One stack slot for the function name if it is stack allocated.
3779 int StackSlotCount();
3781 // Return the number of context slots for code if a context is allocated. This
3782 // number consists of three parts:
3783 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3784 // 2. One context slot per context allocated local.
3785 // 3. One context slot for the function name if it is context allocated.
3786 // Parameters allocated in the context count as context allocated locals. If
3787 // no contexts are allocated for this scope ContextLength returns 0.
3788 int ContextLength();
3790 // Does this scope declare a "this" binding?
3793 // Does this scope declare a "this" binding, and the "this" binding is stack-
3794 // or context-allocated?
3795 bool HasAllocatedReceiver();
3797 // Is this scope the scope of a named function expression?
3798 bool HasFunctionName();
3800 // Return if this has context allocated locals.
3801 bool HasHeapAllocatedLocals();
3803 // Return if contexts are allocated for this scope.
3806 // Return if this is a function scope with "use asm".
3807 inline bool IsAsmModule();
3809 // Return if this is a nested function within an asm module scope.
3810 inline bool IsAsmFunction();
3812 inline bool HasSimpleParameters();
3814 // Return the function_name if present.
3815 String* FunctionName();
3817 // Return the name of the given parameter.
3818 String* ParameterName(int var);
3820 // Return the name of the given local.
3821 String* LocalName(int var);
3823 // Return the name of the given stack local.
3824 String* StackLocalName(int var);
3826 // Return the name of the given stack local.
3827 int StackLocalIndex(int var);
3829 // Return the name of the given context local.
3830 String* ContextLocalName(int var);
3832 // Return the mode of the given context local.
3833 VariableMode ContextLocalMode(int var);
3835 // Return the initialization flag of the given context local.
3836 InitializationFlag ContextLocalInitFlag(int var);
3838 // Return the initialization flag of the given context local.
3839 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3841 // Return true if this local was introduced by the compiler, and should not be
3842 // exposed to the user in a debugger.
3843 bool LocalIsSynthetic(int var);
3845 String* StrongModeFreeVariableName(int var);
3846 int StrongModeFreeVariableStartPosition(int var);
3847 int StrongModeFreeVariableEndPosition(int var);
3849 // Lookup support for serialized scope info. Returns the
3850 // the stack slot index for a given slot name if the slot is
3851 // present; otherwise returns a value < 0. The name must be an internalized
3853 int StackSlotIndex(String* name);
3855 // Lookup support for serialized scope info. Returns the
3856 // context slot index for a given slot name if the slot is present; otherwise
3857 // returns a value < 0. The name must be an internalized string.
3858 // If the slot is present and mode != NULL, sets *mode to the corresponding
3859 // mode for that variable.
3860 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3861 VariableMode* mode, VariableLocation* location,
3862 InitializationFlag* init_flag,
3863 MaybeAssignedFlag* maybe_assigned_flag);
3865 // Lookup the name of a certain context slot by its index.
3866 String* ContextSlotName(int slot_index);
3868 // Lookup support for serialized scope info. Returns the
3869 // parameter index for a given parameter name if the parameter is present;
3870 // otherwise returns a value < 0. The name must be an internalized string.
3871 int ParameterIndex(String* name);
3873 // Lookup support for serialized scope info. Returns the function context
3874 // slot index if the function name is present and context-allocated (named
3875 // function expressions, only), otherwise returns a value < 0. The name
3876 // must be an internalized string.
3877 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3879 // Lookup support for serialized scope info. Returns the receiver context
3880 // slot index if scope has a "this" binding, and the binding is
3881 // context-allocated. Otherwise returns a value < 0.
3882 int ReceiverContextSlotIndex();
3884 FunctionKind function_kind();
3886 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3887 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3889 // Serializes empty scope info.
3890 static ScopeInfo* Empty(Isolate* isolate);
3896 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3897 // numeric and occupies one array slot.
3898 // 1. A set of properties of the scope
3899 // 2. The number of parameters. This only applies to function scopes. For
3900 // non-function scopes this is 0.
3901 // 3. The number of non-parameter variables allocated on the stack.
3902 // 4. The number of non-parameter and parameter variables allocated in the
3904 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3907 V(StackLocalCount) \
3908 V(ContextLocalCount) \
3909 V(ContextGlobalCount) \
3910 V(StrongModeFreeVariableCount)
3912 #define FIELD_ACCESSORS(name) \
3913 inline void Set##name(int value); \
3915 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3916 #undef FIELD_ACCESSORS
3920 #define DECL_INDEX(name) k##name,
3921 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3926 // The layout of the variable part of a ScopeInfo is as follows:
3927 // 1. ParameterEntries:
3928 // This part stores the names of the parameters for function scopes. One
3929 // slot is used per parameter, so in total this part occupies
3930 // ParameterCount() slots in the array. For other scopes than function
3931 // scopes ParameterCount() is 0.
3932 // 2. StackLocalFirstSlot:
3933 // Index of a first stack slot for stack local. Stack locals belonging to
3934 // this scope are located on a stack at slots starting from this index.
3935 // 3. StackLocalEntries:
3936 // Contains the names of local variables that are allocated on the stack,
3937 // in increasing order of the stack slot index. First local variable has
3938 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3939 // One slot is used per stack local, so in total this part occupies
3940 // StackLocalCount() slots in the array.
3941 // 4. ContextLocalNameEntries:
3942 // Contains the names of local variables and parameters that are allocated
3943 // in the context. They are stored in increasing order of the context slot
3944 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3945 // context local, so in total this part occupies ContextLocalCount() slots
3947 // 5. ContextLocalInfoEntries:
3948 // Contains the variable modes and initialization flags corresponding to
3949 // the context locals in ContextLocalNameEntries. One slot is used per
3950 // context local, so in total this part occupies ContextLocalCount()
3951 // slots in the array.
3952 // 6. StrongModeFreeVariableNameEntries:
3953 // Stores the names of strong mode free variables.
3954 // 7. StrongModeFreeVariablePositionEntries:
3955 // Stores the locations (start and end position) of strong mode free
3957 // 8. RecieverEntryIndex:
3958 // If the scope binds a "this" value, one slot is reserved to hold the
3959 // context or stack slot index for the variable.
3960 // 9. FunctionNameEntryIndex:
3961 // If the scope belongs to a named function expression this part contains
3962 // information about the function variable. It always occupies two array
3963 // slots: a. The name of the function variable.
3964 // b. The context or stack slot index for the variable.
3965 int ParameterEntriesIndex();
3966 int StackLocalFirstSlotIndex();
3967 int StackLocalEntriesIndex();
3968 int ContextLocalNameEntriesIndex();
3969 int ContextGlobalNameEntriesIndex();
3970 int ContextLocalInfoEntriesIndex();
3971 int ContextGlobalInfoEntriesIndex();
3972 int StrongModeFreeVariableNameEntriesIndex();
3973 int StrongModeFreeVariablePositionEntriesIndex();
3974 int ReceiverEntryIndex();
3975 int FunctionNameEntryIndex();
3977 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
3978 VariableLocation* location, InitializationFlag* init_flag,
3979 MaybeAssignedFlag* maybe_assigned_flag);
3981 // Used for the function name variable for named function expressions, and for
3983 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
3985 // Properties of scopes.
3986 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
3987 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
3988 STATIC_ASSERT(LANGUAGE_END == 3);
3989 class LanguageModeField
3990 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
3991 class DeclarationScopeField
3992 : public BitField<bool, LanguageModeField::kNext, 1> {};
3993 class ReceiverVariableField
3994 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
3996 class FunctionVariableField
3997 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
3999 class FunctionVariableMode
4000 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4001 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4003 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4004 class HasSimpleParametersField
4005 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4006 class FunctionKindField
4007 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4009 // BitFields representing the encoded information for context locals in the
4010 // ContextLocalInfoEntries part.
4011 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4012 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4013 class ContextLocalMaybeAssignedFlag
4014 : public BitField<MaybeAssignedFlag, 4, 1> {};
4016 friend class ScopeIterator;
4020 // The cache for maps used by normalized (dictionary mode) objects.
4021 // Such maps do not have property descriptors, so a typical program
4022 // needs very limited number of distinct normalized maps.
4023 class NormalizedMapCache: public FixedArray {
4025 static Handle<NormalizedMapCache> New(Isolate* isolate);
4027 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4028 PropertyNormalizationMode mode);
4029 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4033 DECLARE_CAST(NormalizedMapCache)
4035 static inline bool IsNormalizedMapCache(const Object* obj);
4037 DECLARE_VERIFIER(NormalizedMapCache)
4039 static const int kEntries = 64;
4041 static inline int GetIndex(Handle<Map> map);
4043 // The following declarations hide base class methods.
4044 Object* get(int index);
4045 void set(int index, Object* value);
4049 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4050 // that is attached to code objects.
4051 class ByteArray: public FixedArrayBase {
4055 // Setter and getter.
4056 inline byte get(int index);
4057 inline void set(int index, byte value);
4059 // Treat contents as an int array.
4060 inline int get_int(int index);
4062 static int SizeFor(int length) {
4063 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4065 // We use byte arrays for free blocks in the heap. Given a desired size in
4066 // bytes that is a multiple of the word size and big enough to hold a byte
4067 // array, this function returns the number of elements a byte array should
4069 static int LengthFor(int size_in_bytes) {
4070 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4071 DCHECK(size_in_bytes >= kHeaderSize);
4072 return size_in_bytes - kHeaderSize;
4075 // Returns data start address.
4076 inline Address GetDataStartAddress();
4078 // Returns a pointer to the ByteArray object for a given data start address.
4079 static inline ByteArray* FromDataStartAddress(Address address);
4081 DECLARE_CAST(ByteArray)
4083 // Dispatched behavior.
4084 inline int ByteArraySize();
4085 DECLARE_PRINTER(ByteArray)
4086 DECLARE_VERIFIER(ByteArray)
4088 // Layout description.
4089 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4091 // Maximal memory consumption for a single ByteArray.
4092 static const int kMaxSize = 512 * MB;
4093 // Maximal length of a single ByteArray.
4094 static const int kMaxLength = kMaxSize - kHeaderSize;
4097 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4101 // BytecodeArray represents a sequence of interpreter bytecodes.
4102 class BytecodeArray : public FixedArrayBase {
4104 static int SizeFor(int length) {
4105 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4108 // Setter and getter
4109 inline byte get(int index);
4110 inline void set(int index, byte value);
4112 // Returns data start address.
4113 inline Address GetFirstBytecodeAddress();
4115 // Accessors for frame size.
4116 inline int frame_size() const;
4117 inline void set_frame_size(int frame_size);
4119 // Accessors for parameter count (including implicit 'this' receiver).
4120 inline int parameter_count() const;
4121 inline void set_parameter_count(int number_of_parameters);
4123 DECLARE_CAST(BytecodeArray)
4125 // Dispatched behavior.
4126 inline int BytecodeArraySize();
4128 DECLARE_PRINTER(BytecodeArray)
4129 DECLARE_VERIFIER(BytecodeArray)
4131 void Disassemble(std::ostream& os);
4133 // Layout description.
4134 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4135 static const int kParameterSizeOffset = kFrameSizeOffset + kIntSize;
4136 static const int kHeaderSize = kParameterSizeOffset + kIntSize;
4138 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4140 // Maximal memory consumption for a single BytecodeArray.
4141 static const int kMaxSize = 512 * MB;
4142 // Maximal length of a single BytecodeArray.
4143 static const int kMaxLength = kMaxSize - kHeaderSize;
4146 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4150 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4151 // They look like heap objects (are heap object tagged and have a map) so that
4152 // the heap remains iterable. They have a size and a next pointer.
4153 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4154 // in the free list.
4155 class FreeSpace: public HeapObject {
4157 // [size]: size of the free space including the header.
4158 inline int size() const;
4159 inline void set_size(int value);
4161 inline int nobarrier_size() const;
4162 inline void nobarrier_set_size(int value);
4166 // Accessors for the next field.
4167 inline FreeSpace* next();
4168 inline FreeSpace** next_address();
4169 inline void set_next(FreeSpace* next);
4171 inline static FreeSpace* cast(HeapObject* obj);
4173 // Dispatched behavior.
4174 DECLARE_PRINTER(FreeSpace)
4175 DECLARE_VERIFIER(FreeSpace)
4177 // Layout description.
4178 // Size is smi tagged when it is stored.
4179 static const int kSizeOffset = HeapObject::kHeaderSize;
4180 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4183 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4187 // V has parameters (Type, type, TYPE, C type, element_size)
4188 #define TYPED_ARRAYS(V) \
4189 V(Uint8, uint8, UINT8, uint8_t, 1) \
4190 V(Int8, int8, INT8, int8_t, 1) \
4191 V(Uint16, uint16, UINT16, uint16_t, 2) \
4192 V(Int16, int16, INT16, int16_t, 2) \
4193 V(Uint32, uint32, UINT32, uint32_t, 4) \
4194 V(Int32, int32, INT32, int32_t, 4) \
4195 V(Float32, float32, FLOAT32, float, 4) \
4196 V(Float64, float64, FLOAT64, double, 8) \
4197 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4200 class FixedTypedArrayBase: public FixedArrayBase {
4202 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4203 DECL_ACCESSORS(base_pointer, Object)
4205 // [external_pointer]: Contains the offset between base_pointer and the start
4206 // of the data. If the base_pointer is a nullptr, the external_pointer
4207 // therefore points to the actual backing store.
4208 DECL_ACCESSORS(external_pointer, void)
4210 // Dispatched behavior.
4211 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4213 template <typename StaticVisitor>
4214 inline void FixedTypedArrayBaseIterateBody();
4216 DECLARE_CAST(FixedTypedArrayBase)
4218 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4219 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4220 static const int kHeaderSize =
4221 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4223 static const int kDataOffset = kHeaderSize;
4227 static inline int TypedArraySize(InstanceType type, int length);
4228 inline int TypedArraySize(InstanceType type);
4230 // Use with care: returns raw pointer into heap.
4231 inline void* DataPtr();
4233 inline int DataSize();
4236 static inline int ElementSize(InstanceType type);
4238 inline int DataSize(InstanceType type);
4240 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4244 template <class Traits>
4245 class FixedTypedArray: public FixedTypedArrayBase {
4247 typedef typename Traits::ElementType ElementType;
4248 static const InstanceType kInstanceType = Traits::kInstanceType;
4250 DECLARE_CAST(FixedTypedArray<Traits>)
4252 inline ElementType get_scalar(int index);
4253 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4254 inline void set(int index, ElementType value);
4256 static inline ElementType from_int(int value);
4257 static inline ElementType from_double(double value);
4259 // This accessor applies the correct conversion from Smi, HeapNumber
4261 void SetValue(uint32_t index, Object* value);
4263 DECLARE_PRINTER(FixedTypedArray)
4264 DECLARE_VERIFIER(FixedTypedArray)
4267 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4270 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4271 class Type##ArrayTraits { \
4272 public: /* NOLINT */ \
4273 typedef elementType ElementType; \
4274 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4275 static const char* Designator() { return #type " array"; } \
4276 static inline Handle<Object> ToHandle(Isolate* isolate, \
4277 elementType scalar); \
4278 static inline elementType defaultValue(); \
4281 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4283 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4285 #undef FIXED_TYPED_ARRAY_TRAITS
4288 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4289 // data for code generated by the Hydrogen/Lithium compiler. It also
4290 // contains information about functions that were inlined. If N different
4291 // functions were inlined then first N elements of the literal array will
4292 // contain these functions.
4295 class DeoptimizationInputData: public FixedArray {
4297 // Layout description. Indices in the array.
4298 static const int kTranslationByteArrayIndex = 0;
4299 static const int kInlinedFunctionCountIndex = 1;
4300 static const int kLiteralArrayIndex = 2;
4301 static const int kOsrAstIdIndex = 3;
4302 static const int kOsrPcOffsetIndex = 4;
4303 static const int kOptimizationIdIndex = 5;
4304 static const int kSharedFunctionInfoIndex = 6;
4305 static const int kWeakCellCacheIndex = 7;
4306 static const int kFirstDeoptEntryIndex = 8;
4308 // Offsets of deopt entry elements relative to the start of the entry.
4309 static const int kAstIdRawOffset = 0;
4310 static const int kTranslationIndexOffset = 1;
4311 static const int kArgumentsStackHeightOffset = 2;
4312 static const int kPcOffset = 3;
4313 static const int kDeoptEntrySize = 4;
4315 // Simple element accessors.
4316 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4317 inline type* name(); \
4318 inline void Set##name(type* value);
4320 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4321 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4322 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4323 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4324 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4325 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4326 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4327 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4329 #undef DECLARE_ELEMENT_ACCESSORS
4331 // Accessors for elements of the ith deoptimization entry.
4332 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4333 inline type* name(int i); \
4334 inline void Set##name(int i, type* value);
4336 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4337 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4338 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4339 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4341 #undef DECLARE_ENTRY_ACCESSORS
4343 inline BailoutId AstId(int i);
4345 inline void SetAstId(int i, BailoutId value);
4347 inline int DeoptCount();
4349 // Allocates a DeoptimizationInputData.
4350 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4351 int deopt_entry_count,
4352 PretenureFlag pretenure);
4354 DECLARE_CAST(DeoptimizationInputData)
4356 #ifdef ENABLE_DISASSEMBLER
4357 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4361 static int IndexForEntry(int i) {
4362 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4366 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4370 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4371 // data for code generated by the full compiler.
4372 // The format of the these objects is
4373 // [i * 2]: Ast ID for ith deoptimization.
4374 // [i * 2 + 1]: PC and state of ith deoptimization
4375 class DeoptimizationOutputData: public FixedArray {
4377 inline int DeoptPoints();
4379 inline BailoutId AstId(int index);
4381 inline void SetAstId(int index, BailoutId id);
4383 inline Smi* PcAndState(int index);
4384 inline void SetPcAndState(int index, Smi* offset);
4386 static int LengthOfFixedArray(int deopt_points) {
4387 return deopt_points * 2;
4390 // Allocates a DeoptimizationOutputData.
4391 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4392 int number_of_deopt_points,
4393 PretenureFlag pretenure);
4395 DECLARE_CAST(DeoptimizationOutputData)
4397 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4398 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4403 // HandlerTable is a fixed array containing entries for exception handlers in
4404 // the code object it is associated with. The tables comes in two flavors:
4405 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4406 // exception handler and a range representing the try-block covered by that
4407 // handler. Layout looks as follows:
4408 // [ range-start , range-end , handler-offset , stack-depth ]
4409 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4410 // per call-site that could throw an exception. Layout looks as follows:
4411 // [ return-address-offset , handler-offset ]
4412 class HandlerTable : public FixedArray {
4414 // Conservative prediction whether a given handler will locally catch an
4415 // exception or cause a re-throw to outside the code boundary. Since this is
4416 // undecidable it is merely an approximation (e.g. useful for debugger).
4417 enum CatchPrediction { UNCAUGHT, CAUGHT };
4419 // Accessors for handler table based on ranges.
4420 inline void SetRangeStart(int index, int value);
4421 inline void SetRangeEnd(int index, int value);
4422 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4423 inline void SetRangeDepth(int index, int value);
4425 // Accessors for handler table based on return addresses.
4426 inline void SetReturnOffset(int index, int value);
4427 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4429 // Lookup handler in a table based on ranges.
4430 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4432 // Lookup handler in a table based on return addresses.
4433 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4435 // Returns the required length of the underlying fixed array.
4436 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4437 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4439 DECLARE_CAST(HandlerTable)
4441 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4442 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4443 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4447 // Layout description for handler table based on ranges.
4448 static const int kRangeStartIndex = 0;
4449 static const int kRangeEndIndex = 1;
4450 static const int kRangeHandlerIndex = 2;
4451 static const int kRangeDepthIndex = 3;
4452 static const int kRangeEntrySize = 4;
4454 // Layout description for handler table based on return addresses.
4455 static const int kReturnOffsetIndex = 0;
4456 static const int kReturnHandlerIndex = 1;
4457 static const int kReturnEntrySize = 2;
4459 // Encoding of the {handler} field.
4460 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4461 class HandlerOffsetField : public BitField<int, 1, 30> {};
4465 // Code describes objects with on-the-fly generated machine code.
4466 class Code: public HeapObject {
4468 // Opaque data type for encapsulating code flags like kind, inline
4469 // cache state, and arguments count.
4470 typedef uint32_t Flags;
4472 #define NON_IC_KIND_LIST(V) \
4474 V(OPTIMIZED_FUNCTION) \
4481 #define IC_KIND_LIST(V) \
4492 #define CODE_KIND_LIST(V) \
4493 NON_IC_KIND_LIST(V) \
4497 #define DEFINE_CODE_KIND_ENUM(name) name,
4498 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4499 #undef DEFINE_CODE_KIND_ENUM
4503 // No more than 16 kinds. The value is currently encoded in four bits in
4505 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4507 static const char* Kind2String(Kind kind);
4515 static const int kPrologueOffsetNotSet = -1;
4517 #ifdef ENABLE_DISASSEMBLER
4519 static const char* ICState2String(InlineCacheState state);
4520 static const char* StubType2String(StubType type);
4521 static void PrintExtraICState(std::ostream& os, // NOLINT
4522 Kind kind, ExtraICState extra);
4523 void Disassemble(const char* name, std::ostream& os); // NOLINT
4524 #endif // ENABLE_DISASSEMBLER
4526 // [instruction_size]: Size of the native instructions
4527 inline int instruction_size() const;
4528 inline void set_instruction_size(int value);
4530 // [relocation_info]: Code relocation information
4531 DECL_ACCESSORS(relocation_info, ByteArray)
4532 void InvalidateRelocation();
4533 void InvalidateEmbeddedObjects();
4535 // [handler_table]: Fixed array containing offsets of exception handlers.
4536 DECL_ACCESSORS(handler_table, FixedArray)
4538 // [deoptimization_data]: Array containing data for deopt.
4539 DECL_ACCESSORS(deoptimization_data, FixedArray)
4541 // [raw_type_feedback_info]: This field stores various things, depending on
4542 // the kind of the code object.
4543 // FUNCTION => type feedback information.
4544 // STUB and ICs => major/minor key as Smi.
4545 DECL_ACCESSORS(raw_type_feedback_info, Object)
4546 inline Object* type_feedback_info();
4547 inline void set_type_feedback_info(
4548 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4549 inline uint32_t stub_key();
4550 inline void set_stub_key(uint32_t key);
4552 // [next_code_link]: Link for lists of optimized or deoptimized code.
4553 // Note that storage for this field is overlapped with typefeedback_info.
4554 DECL_ACCESSORS(next_code_link, Object)
4556 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4557 // field does not have to be traced during garbage collection since
4558 // it is only used by the garbage collector itself.
4559 DECL_ACCESSORS(gc_metadata, Object)
4561 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4562 // at the moment when this object was created.
4563 inline void set_ic_age(int count);
4564 inline int ic_age() const;
4566 // [prologue_offset]: Offset of the function prologue, used for aging
4567 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4568 inline int prologue_offset() const;
4569 inline void set_prologue_offset(int offset);
4571 // [constant_pool offset]: Offset of the constant pool.
4572 // Valid for FLAG_enable_embedded_constant_pool only
4573 inline int constant_pool_offset() const;
4574 inline void set_constant_pool_offset(int offset);
4576 // Unchecked accessors to be used during GC.
4577 inline ByteArray* unchecked_relocation_info();
4579 inline int relocation_size();
4581 // [flags]: Various code flags.
4582 inline Flags flags();
4583 inline void set_flags(Flags flags);
4585 // [flags]: Access to specific code flags.
4587 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4588 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4590 inline StubType type(); // Only valid for monomorphic IC stubs.
4592 // Testers for IC stub kinds.
4593 inline bool is_inline_cache_stub();
4594 inline bool is_debug_stub();
4595 inline bool is_handler();
4596 inline bool is_load_stub();
4597 inline bool is_keyed_load_stub();
4598 inline bool is_store_stub();
4599 inline bool is_keyed_store_stub();
4600 inline bool is_call_stub();
4601 inline bool is_binary_op_stub();
4602 inline bool is_compare_ic_stub();
4603 inline bool is_compare_nil_ic_stub();
4604 inline bool is_to_boolean_ic_stub();
4605 inline bool is_keyed_stub();
4606 inline bool is_optimized_code();
4607 inline bool embeds_maps_weakly();
4609 inline bool IsCodeStubOrIC();
4610 inline bool IsJavaScriptCode();
4612 inline void set_raw_kind_specific_flags1(int value);
4613 inline void set_raw_kind_specific_flags2(int value);
4615 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4616 // object was generated by either the hydrogen or the TurboFan optimizing
4617 // compiler (but it may not be an optimized function).
4618 inline bool is_crankshafted();
4619 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4620 inline void set_is_crankshafted(bool value);
4622 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4623 // code object was generated by the TurboFan optimizing compiler.
4624 inline bool is_turbofanned();
4625 inline void set_is_turbofanned(bool value);
4627 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4628 // embedded objects in code should be treated weakly.
4629 inline bool can_have_weak_objects();
4630 inline void set_can_have_weak_objects(bool value);
4632 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4633 // deoptimization support.
4634 inline bool has_deoptimization_support();
4635 inline void set_has_deoptimization_support(bool value);
4637 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4638 // been compiled with debug break slots.
4639 inline bool has_debug_break_slots();
4640 inline void set_has_debug_break_slots(bool value);
4642 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4643 // reloc info includes runtime and external references to support
4644 // serialization/deserialization.
4645 inline bool has_reloc_info_for_serialization();
4646 inline void set_has_reloc_info_for_serialization(bool value);
4648 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4649 // how long the function has been marked for OSR and therefore which
4650 // level of loop nesting we are willing to do on-stack replacement
4652 inline void set_allow_osr_at_loop_nesting_level(int level);
4653 inline int allow_osr_at_loop_nesting_level();
4655 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4656 // the code object was seen on the stack with no IC patching going on.
4657 inline int profiler_ticks();
4658 inline void set_profiler_ticks(int ticks);
4660 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4661 // For builtins, tells which builtin index it has.
4662 // Note that builtins can have a code kind other than BUILTIN, which means
4663 // that for arbitrary code objects, this index value may be random garbage.
4664 // To verify in that case, compare the code object to the indexed builtin.
4665 inline int builtin_index();
4666 inline void set_builtin_index(int id);
4668 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4669 // reserved in the code prologue.
4670 inline unsigned stack_slots();
4671 inline void set_stack_slots(unsigned slots);
4673 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4674 // the instruction stream where the safepoint table starts.
4675 inline unsigned safepoint_table_offset();
4676 inline void set_safepoint_table_offset(unsigned offset);
4678 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4679 // instruction stream where the back edge table starts.
4680 inline unsigned back_edge_table_offset();
4681 inline void set_back_edge_table_offset(unsigned offset);
4683 inline bool back_edges_patched_for_osr();
4685 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4686 inline uint16_t to_boolean_state();
4688 // [has_function_cache]: For kind STUB tells whether there is a function
4689 // cache is passed to the stub.
4690 inline bool has_function_cache();
4691 inline void set_has_function_cache(bool flag);
4694 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4695 // the code is going to be deoptimized because of dead embedded maps.
4696 inline bool marked_for_deoptimization();
4697 inline void set_marked_for_deoptimization(bool flag);
4699 // [constant_pool]: The constant pool for this function.
4700 inline Address constant_pool();
4702 // Get the safepoint entry for the given pc.
4703 SafepointEntry GetSafepointEntry(Address pc);
4705 // Find an object in a stub with a specified map
4706 Object* FindNthObject(int n, Map* match_map);
4708 // Find the first allocation site in an IC stub.
4709 AllocationSite* FindFirstAllocationSite();
4711 // Find the first map in an IC stub.
4712 Map* FindFirstMap();
4713 void FindAllMaps(MapHandleList* maps);
4715 // Find the first handler in an IC stub.
4716 Code* FindFirstHandler();
4718 // Find |length| handlers and put them into |code_list|. Returns false if not
4719 // enough handlers can be found.
4720 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4722 // Find the handler for |map|.
4723 MaybeHandle<Code> FindHandlerForMap(Map* map);
4725 // Find the first name in an IC stub.
4726 Name* FindFirstName();
4728 class FindAndReplacePattern;
4729 // For each (map-to-find, object-to-replace) pair in the pattern, this
4730 // function replaces the corresponding placeholder in the code with the
4731 // object-to-replace. The function assumes that pairs in the pattern come in
4732 // the same order as the placeholders in the code.
4733 // If the placeholder is a weak cell, then the value of weak cell is matched
4734 // against the map-to-find.
4735 void FindAndReplace(const FindAndReplacePattern& pattern);
4737 // The entire code object including its header is copied verbatim to the
4738 // snapshot so that it can be written in one, fast, memcpy during
4739 // deserialization. The deserializer will overwrite some pointers, rather
4740 // like a runtime linker, but the random allocation addresses used in the
4741 // mksnapshot process would still be present in the unlinked snapshot data,
4742 // which would make snapshot production non-reproducible. This method wipes
4743 // out the to-be-overwritten header data for reproducible snapshots.
4744 inline void WipeOutHeader();
4746 // Flags operations.
4747 static inline Flags ComputeFlags(
4748 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4749 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4750 CacheHolderFlag holder = kCacheOnReceiver);
4752 static inline Flags ComputeMonomorphicFlags(
4753 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4754 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4756 static inline Flags ComputeHandlerFlags(
4757 Kind handler_kind, StubType type = NORMAL,
4758 CacheHolderFlag holder = kCacheOnReceiver);
4760 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4761 static inline StubType ExtractTypeFromFlags(Flags flags);
4762 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4763 static inline Kind ExtractKindFromFlags(Flags flags);
4764 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4766 static inline Flags RemoveTypeFromFlags(Flags flags);
4767 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4769 // Convert a target address into a code object.
4770 static inline Code* GetCodeFromTargetAddress(Address address);
4772 // Convert an entry address into an object.
4773 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4775 // Returns the address of the first instruction.
4776 inline byte* instruction_start();
4778 // Returns the address right after the last instruction.
4779 inline byte* instruction_end();
4781 // Returns the size of the instructions, padding, and relocation information.
4782 inline int body_size();
4784 // Returns the address of the first relocation info (read backwards!).
4785 inline byte* relocation_start();
4787 // Code entry point.
4788 inline byte* entry();
4790 // Returns true if pc is inside this object's instructions.
4791 inline bool contains(byte* pc);
4793 // Relocate the code by delta bytes. Called to signal that this code
4794 // object has been moved by delta bytes.
4795 void Relocate(intptr_t delta);
4797 // Migrate code described by desc.
4798 void CopyFrom(const CodeDesc& desc);
4800 // Returns the object size for a given body (used for allocation).
4801 static int SizeFor(int body_size) {
4802 DCHECK_SIZE_TAG_ALIGNED(body_size);
4803 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4806 // Calculate the size of the code object to report for log events. This takes
4807 // the layout of the code object into account.
4808 inline int ExecutableSize();
4810 // Locating source position.
4811 int SourcePosition(Address pc);
4812 int SourceStatementPosition(Address pc);
4816 // Dispatched behavior.
4817 inline int CodeSize();
4818 inline void CodeIterateBody(ObjectVisitor* v);
4820 template<typename StaticVisitor>
4821 inline void CodeIterateBody(Heap* heap);
4823 DECLARE_PRINTER(Code)
4824 DECLARE_VERIFIER(Code)
4826 void ClearInlineCaches();
4827 void ClearInlineCaches(Kind kind);
4829 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4830 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4832 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4834 kToBeExecutedOnceCodeAge = -3,
4835 kNotExecutedCodeAge = -2,
4836 kExecutedOnceCodeAge = -1,
4838 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4840 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4841 kLastCodeAge = kAfterLastCodeAge - 1,
4842 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4843 kIsOldCodeAge = kSexagenarianCodeAge,
4844 kPreAgedCodeAge = kIsOldCodeAge - 1
4846 #undef DECLARE_CODE_AGE_ENUM
4848 // Code aging. Indicates how many full GCs this code has survived without
4849 // being entered through the prologue. Used to determine when it is
4850 // relatively safe to flush this code object and replace it with the lazy
4851 // compilation stub.
4852 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4853 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4854 void MakeYoung(Isolate* isolate);
4855 void MarkToBeExecutedOnce(Isolate* isolate);
4856 void MakeOlder(MarkingParity);
4857 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4860 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4861 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4864 void PrintDeoptLocation(FILE* out, Address pc);
4865 bool CanDeoptAt(Address pc);
4868 void VerifyEmbeddedObjectsDependency();
4872 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4873 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4874 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4877 inline bool CanContainWeakObjects();
4879 inline bool IsWeakObject(Object* object);
4881 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4883 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4884 WeakCell* CachedWeakCell();
4886 // Max loop nesting marker used to postpose OSR. We don't take loop
4887 // nesting that is deeper than 5 levels into account.
4888 static const int kMaxLoopNestingMarker = 6;
4890 static const int kConstantPoolSize =
4891 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4893 // Layout description.
4894 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4895 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4896 static const int kDeoptimizationDataOffset =
4897 kHandlerTableOffset + kPointerSize;
4898 // For FUNCTION kind, we store the type feedback info here.
4899 static const int kTypeFeedbackInfoOffset =
4900 kDeoptimizationDataOffset + kPointerSize;
4901 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4902 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4903 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4904 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4905 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4906 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4907 static const int kKindSpecificFlags2Offset =
4908 kKindSpecificFlags1Offset + kIntSize;
4909 // Note: We might be able to squeeze this into the flags above.
4910 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4911 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4912 static const int kHeaderPaddingStart =
4913 kConstantPoolOffset + kConstantPoolSize;
4915 // Add padding to align the instruction start following right after
4916 // the Code object header.
4917 static const int kHeaderSize =
4918 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4920 // Byte offsets within kKindSpecificFlags1Offset.
4921 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4922 class FullCodeFlagsHasDeoptimizationSupportField:
4923 public BitField<bool, 0, 1> {}; // NOLINT
4924 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4925 class FullCodeFlagsHasRelocInfoForSerialization
4926 : public BitField<bool, 2, 1> {};
4927 // Bit 3 in this bitfield is unused.
4928 class ProfilerTicksField : public BitField<int, 4, 28> {};
4930 // Flags layout. BitField<type, shift, size>.
4931 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4932 class TypeField : public BitField<StubType, 4, 1> {};
4933 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4934 class KindField : public BitField<Kind, 7, 4> {};
4935 class ExtraICStateField: public BitField<ExtraICState, 11,
4936 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4938 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4939 static const int kStackSlotsFirstBit = 0;
4940 static const int kStackSlotsBitCount = 24;
4941 static const int kHasFunctionCacheBit =
4942 kStackSlotsFirstBit + kStackSlotsBitCount;
4943 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4944 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4945 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4947 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4948 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4950 class StackSlotsField: public BitField<int,
4951 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4952 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4954 class MarkedForDeoptimizationField
4955 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
4956 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
4958 class CanHaveWeakObjectsField
4959 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
4961 // KindSpecificFlags2 layout (ALL)
4962 static const int kIsCrankshaftedBit = 0;
4963 class IsCrankshaftedField: public BitField<bool,
4964 kIsCrankshaftedBit, 1> {}; // NOLINT
4966 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
4967 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
4968 static const int kSafepointTableOffsetBitCount = 30;
4970 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
4971 kSafepointTableOffsetBitCount <= 32);
4972 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
4974 class SafepointTableOffsetField: public BitField<int,
4975 kSafepointTableOffsetFirstBit,
4976 kSafepointTableOffsetBitCount> {}; // NOLINT
4978 // KindSpecificFlags2 layout (FUNCTION)
4979 class BackEdgeTableOffsetField: public BitField<int,
4980 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
4981 class AllowOSRAtLoopNestingLevelField: public BitField<int,
4982 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
4983 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
4985 static const int kArgumentsBits = 16;
4986 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
4988 // This constant should be encodable in an ARM instruction.
4989 static const int kFlagsNotUsedInLookup =
4990 TypeField::kMask | CacheHolderField::kMask;
4993 friend class RelocIterator;
4994 friend class Deoptimizer; // For FindCodeAgeSequence.
4996 void ClearInlineCaches(Kind* kind);
4999 byte* FindCodeAgeSequence();
5000 static void GetCodeAgeAndParity(Code* code, Age* age,
5001 MarkingParity* parity);
5002 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5003 MarkingParity* parity);
5004 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5006 // Code aging -- platform-specific
5007 static void PatchPlatformCodeAge(Isolate* isolate,
5008 byte* sequence, Age age,
5009 MarkingParity parity);
5011 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5015 // This class describes the layout of dependent codes array of a map. The
5016 // array is partitioned into several groups of dependent codes. Each group
5017 // contains codes with the same dependency on the map. The array has the
5018 // following layout for n dependency groups:
5020 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5021 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5022 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5024 // The first n elements are Smis, each of them specifies the number of codes
5025 // in the corresponding group. The subsequent elements contain grouped code
5026 // objects in weak cells. The suffix of the array can be filled with the
5027 // undefined value if the number of codes is less than the length of the
5028 // array. The order of the code objects within a group is not preserved.
5030 // All code indexes used in the class are counted starting from the first
5031 // code object of the first group. In other words, code index 0 corresponds
5032 // to array index n = kCodesStartIndex.
5034 class DependentCode: public FixedArray {
5036 enum DependencyGroup {
5037 // Group of code that weakly embed this map and depend on being
5038 // deoptimized when the map is garbage collected.
5040 // Group of code that embed a transition to this map, and depend on being
5041 // deoptimized when the transition is replaced by a new version.
5043 // Group of code that omit run-time prototype checks for prototypes
5044 // described by this map. The group is deoptimized whenever an object
5045 // described by this map changes shape (and transitions to a new map),
5046 // possibly invalidating the assumptions embedded in the code.
5047 kPrototypeCheckGroup,
5048 // Group of code that depends on global property values in property cells
5049 // not being changed.
5050 kPropertyCellChangedGroup,
5051 // Group of code that omit run-time type checks for the field(s) introduced
5054 // Group of code that omit run-time type checks for initial maps of
5056 kInitialMapChangedGroup,
5057 // Group of code that depends on tenuring information in AllocationSites
5058 // not being changed.
5059 kAllocationSiteTenuringChangedGroup,
5060 // Group of code that depends on element transition information in
5061 // AllocationSites not being changed.
5062 kAllocationSiteTransitionChangedGroup
5065 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5067 // Array for holding the index of the first code object of each group.
5068 // The last element stores the total number of code objects.
5069 class GroupStartIndexes {
5071 explicit GroupStartIndexes(DependentCode* entries);
5072 void Recompute(DependentCode* entries);
5073 int at(int i) { return start_indexes_[i]; }
5074 int number_of_entries() { return start_indexes_[kGroupCount]; }
5076 int start_indexes_[kGroupCount + 1];
5079 bool Contains(DependencyGroup group, WeakCell* code_cell);
5081 static Handle<DependentCode> InsertCompilationDependencies(
5082 Handle<DependentCode> entries, DependencyGroup group,
5083 Handle<Foreign> info);
5085 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5086 DependencyGroup group,
5087 Handle<WeakCell> code_cell);
5089 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5090 WeakCell* code_cell);
5092 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5095 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5096 DependentCode::DependencyGroup group);
5098 bool MarkCodeForDeoptimization(Isolate* isolate,
5099 DependentCode::DependencyGroup group);
5101 // The following low-level accessors should only be used by this class
5102 // and the mark compact collector.
5103 inline int number_of_entries(DependencyGroup group);
5104 inline void set_number_of_entries(DependencyGroup group, int value);
5105 inline Object* object_at(int i);
5106 inline void set_object_at(int i, Object* object);
5107 inline void clear_at(int i);
5108 inline void copy(int from, int to);
5109 DECLARE_CAST(DependentCode)
5111 static const char* DependencyGroupName(DependencyGroup group);
5112 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5115 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5116 DependencyGroup group,
5117 Handle<Object> object);
5118 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5119 // Make a room at the end of the given group by moving out the first
5120 // code objects of the subsequent groups.
5121 inline void ExtendGroup(DependencyGroup group);
5122 // Compact by removing cleared weak cells and return true if there was
5123 // any cleared weak cell.
5125 static int Grow(int number_of_entries) {
5126 if (number_of_entries < 5) return number_of_entries + 1;
5127 return number_of_entries * 5 / 4;
5129 static const int kCodesStartIndex = kGroupCount;
5133 class PrototypeInfo;
5136 // All heap objects have a Map that describes their structure.
5137 // A Map contains information about:
5138 // - Size information about the object
5139 // - How to iterate over an object (for garbage collection)
5140 class Map: public HeapObject {
5143 // Size in bytes or kVariableSizeSentinel if instances do not have
5145 inline int instance_size();
5146 inline void set_instance_size(int value);
5148 // Only to clear an unused byte, remove once byte is used.
5149 inline void clear_unused();
5151 // [inobject_properties_or_constructor_function_index]: Provides access
5152 // to the inobject properties in case of JSObject maps, or the constructor
5153 // function index in case of primitive maps.
5154 inline int inobject_properties_or_constructor_function_index();
5155 inline void set_inobject_properties_or_constructor_function_index(int value);
5156 // Count of properties allocated in the object (JSObject only).
5157 inline int GetInObjectProperties();
5158 inline void SetInObjectProperties(int value);
5159 // Index of the constructor function in the native context (primitives only),
5160 // or the special sentinel value to indicate that there is no object wrapper
5161 // for the primitive (i.e. in case of null or undefined).
5162 static const int kNoConstructorFunctionIndex = 0;
5163 inline int GetConstructorFunctionIndex();
5164 inline void SetConstructorFunctionIndex(int value);
5167 inline InstanceType instance_type();
5168 inline void set_instance_type(InstanceType value);
5170 // Tells how many unused property fields are available in the
5171 // instance (only used for JSObject in fast mode).
5172 inline int unused_property_fields();
5173 inline void set_unused_property_fields(int value);
5176 inline byte bit_field() const;
5177 inline void set_bit_field(byte value);
5180 inline byte bit_field2() const;
5181 inline void set_bit_field2(byte value);
5184 inline uint32_t bit_field3() const;
5185 inline void set_bit_field3(uint32_t bits);
5187 class EnumLengthBits: public BitField<int,
5188 0, kDescriptorIndexBitCount> {}; // NOLINT
5189 class NumberOfOwnDescriptorsBits: public BitField<int,
5190 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5191 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5192 class DictionaryMap : public BitField<bool, 20, 1> {};
5193 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5194 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5195 class Deprecated : public BitField<bool, 23, 1> {};
5196 class IsUnstable : public BitField<bool, 24, 1> {};
5197 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5198 class IsStrong : public BitField<bool, 26, 1> {};
5201 // Keep this bit field at the very end for better code in
5202 // Builtins::kJSConstructStubGeneric stub.
5203 // This counter is used for in-object slack tracking and for map aging.
5204 // The in-object slack tracking is considered enabled when the counter is
5205 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5206 class Counter : public BitField<int, 28, 4> {};
5207 static const int kSlackTrackingCounterStart = 14;
5208 static const int kSlackTrackingCounterEnd = 8;
5209 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5210 static const int kRetainingCounterEnd = 0;
5212 // Tells whether the object in the prototype property will be used
5213 // for instances created from this function. If the prototype
5214 // property is set to a value that is not a JSObject, the prototype
5215 // property will not be used to create instances of the function.
5216 // See ECMA-262, 13.2.2.
5217 inline void set_non_instance_prototype(bool value);
5218 inline bool has_non_instance_prototype();
5220 // Tells whether function has special prototype property. If not, prototype
5221 // property will not be created when accessed (will return undefined),
5222 // and construction from this function will not be allowed.
5223 inline void set_function_with_prototype(bool value);
5224 inline bool function_with_prototype();
5226 // Tells whether the instance with this map should be ignored by the
5227 // Object.getPrototypeOf() function and the __proto__ accessor.
5228 inline void set_is_hidden_prototype();
5229 inline bool is_hidden_prototype();
5231 // Records and queries whether the instance has a named interceptor.
5232 inline void set_has_named_interceptor();
5233 inline bool has_named_interceptor();
5235 // Records and queries whether the instance has an indexed interceptor.
5236 inline void set_has_indexed_interceptor();
5237 inline bool has_indexed_interceptor();
5239 // Tells whether the instance is undetectable.
5240 // An undetectable object is a special class of JSObject: 'typeof' operator
5241 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5242 // a normal JS object. It is useful for implementing undetectable
5243 // document.all in Firefox & Safari.
5244 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5245 inline void set_is_undetectable();
5246 inline bool is_undetectable();
5248 // Tells whether the instance has a call-as-function handler.
5249 inline void set_is_observed();
5250 inline bool is_observed();
5252 inline void set_is_strong();
5253 inline bool is_strong();
5254 inline void set_is_extensible(bool value);
5255 inline bool is_extensible();
5256 inline void set_is_prototype_map(bool value);
5257 inline bool is_prototype_map() const;
5259 inline void set_elements_kind(ElementsKind elements_kind);
5260 inline ElementsKind elements_kind();
5262 // Tells whether the instance has fast elements that are only Smis.
5263 inline bool has_fast_smi_elements();
5265 // Tells whether the instance has fast elements.
5266 inline bool has_fast_object_elements();
5267 inline bool has_fast_smi_or_object_elements();
5268 inline bool has_fast_double_elements();
5269 inline bool has_fast_elements();
5270 inline bool has_sloppy_arguments_elements();
5271 inline bool has_fixed_typed_array_elements();
5272 inline bool has_dictionary_elements();
5274 static bool IsValidElementsTransition(ElementsKind from_kind,
5275 ElementsKind to_kind);
5277 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5278 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5279 bool DictionaryElementsInPrototypeChainOnly();
5281 inline Map* ElementsTransitionMap();
5283 inline FixedArrayBase* GetInitialElements();
5285 // [raw_transitions]: Provides access to the transitions storage field.
5286 // Don't call set_raw_transitions() directly to overwrite transitions, use
5287 // the TransitionArray::ReplaceTransitions() wrapper instead!
5288 DECL_ACCESSORS(raw_transitions, Object)
5289 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5290 // (which prototype maps don't have).
5291 DECL_ACCESSORS(prototype_info, Object)
5292 // PrototypeInfo is created lazily using this helper (which installs it on
5293 // the given prototype's map).
5294 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5295 Handle<JSObject> prototype, Isolate* isolate);
5296 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5297 Handle<Map> prototype_map, Isolate* isolate);
5299 // [prototype chain validity cell]: Associated with a prototype object,
5300 // stored in that object's map's PrototypeInfo, indicates that prototype
5301 // chains through this object are currently valid. The cell will be
5302 // invalidated and replaced when the prototype chain changes.
5303 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5305 static const int kPrototypeChainValid = 0;
5306 static const int kPrototypeChainInvalid = 1;
5309 Map* FindFieldOwner(int descriptor);
5311 inline int GetInObjectPropertyOffset(int index);
5313 int NumberOfFields();
5315 // TODO(ishell): candidate with JSObject::MigrateToMap().
5316 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5317 int target_inobject, int target_unused,
5318 int* old_number_of_fields);
5319 // TODO(ishell): moveit!
5320 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5321 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5322 Handle<HeapType> type1,
5323 Handle<HeapType> type2,
5325 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5326 Representation new_representation,
5327 Handle<HeapType> new_field_type);
5328 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5329 PropertyKind new_kind,
5330 PropertyAttributes new_attributes,
5331 Representation new_representation,
5332 Handle<HeapType> new_field_type,
5333 StoreMode store_mode);
5334 static Handle<Map> CopyGeneralizeAllRepresentations(
5335 Handle<Map> map, int modify_index, StoreMode store_mode,
5336 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5338 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5339 int descriptor_number,
5340 Handle<Object> value);
5342 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5343 const char* reason);
5345 // Returns the constructor name (the name (possibly, inferred name) of the
5346 // function that was used to instantiate the object).
5347 String* constructor_name();
5349 // Tells whether the map is used for JSObjects in dictionary mode (ie
5350 // normalized objects, ie objects for which HasFastProperties returns false).
5351 // A map can never be used for both dictionary mode and fast mode JSObjects.
5352 // False by default and for HeapObjects that are not JSObjects.
5353 inline void set_dictionary_map(bool value);
5354 inline bool is_dictionary_map();
5356 // Tells whether the instance needs security checks when accessing its
5358 inline void set_is_access_check_needed(bool access_check_needed);
5359 inline bool is_access_check_needed();
5361 // Returns true if map has a non-empty stub code cache.
5362 inline bool has_code_cache();
5364 // [prototype]: implicit prototype object.
5365 DECL_ACCESSORS(prototype, Object)
5366 // TODO(jkummerow): make set_prototype private.
5367 static void SetPrototype(
5368 Handle<Map> map, Handle<Object> prototype,
5369 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5371 // [constructor]: points back to the function responsible for this map.
5372 // The field overlaps with the back pointer. All maps in a transition tree
5373 // have the same constructor, so maps with back pointers can walk the
5374 // back pointer chain until they find the map holding their constructor.
5375 DECL_ACCESSORS(constructor_or_backpointer, Object)
5376 inline Object* GetConstructor() const;
5377 inline void SetConstructor(Object* constructor,
5378 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5379 // [back pointer]: points back to the parent map from which a transition
5380 // leads to this map. The field overlaps with the constructor (see above).
5381 inline Object* GetBackPointer();
5382 inline void SetBackPointer(Object* value,
5383 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5385 // [instance descriptors]: describes the object.
5386 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5388 // [layout descriptor]: describes the object layout.
5389 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5390 // |layout descriptor| accessor which can be used from GC.
5391 inline LayoutDescriptor* layout_descriptor_gc_safe();
5392 inline bool HasFastPointerLayout() const;
5394 // |layout descriptor| accessor that is safe to call even when
5395 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5396 // |layout_descriptor| field at all).
5397 inline LayoutDescriptor* GetLayoutDescriptor();
5399 inline void UpdateDescriptors(DescriptorArray* descriptors,
5400 LayoutDescriptor* layout_descriptor);
5401 inline void InitializeDescriptors(DescriptorArray* descriptors,
5402 LayoutDescriptor* layout_descriptor);
5404 // [stub cache]: contains stubs compiled for this map.
5405 DECL_ACCESSORS(code_cache, Object)
5407 // [dependent code]: list of optimized codes that weakly embed this map.
5408 DECL_ACCESSORS(dependent_code, DependentCode)
5410 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5411 DECL_ACCESSORS(weak_cell_cache, Object)
5413 inline PropertyDetails GetLastDescriptorDetails();
5415 inline int LastAdded();
5417 inline int NumberOfOwnDescriptors();
5418 inline void SetNumberOfOwnDescriptors(int number);
5420 inline Cell* RetrieveDescriptorsPointer();
5422 inline int EnumLength();
5423 inline void SetEnumLength(int length);
5425 inline bool owns_descriptors();
5426 inline void set_owns_descriptors(bool owns_descriptors);
5427 inline bool has_instance_call_handler();
5428 inline void set_has_instance_call_handler();
5429 inline void mark_unstable();
5430 inline bool is_stable();
5431 inline void set_migration_target(bool value);
5432 inline bool is_migration_target();
5433 inline void set_counter(int value);
5434 inline int counter();
5435 inline void deprecate();
5436 inline bool is_deprecated();
5437 inline bool CanBeDeprecated();
5438 // Returns a non-deprecated version of the input. If the input was not
5439 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5440 // is found by re-transitioning from the root of the transition tree using the
5441 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5443 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5445 // Returns a non-deprecated version of the input. This method may deprecate
5446 // existing maps along the way if encodings conflict. Not for use while
5447 // gathering type feedback. Use TryUpdate in those cases instead.
5448 static Handle<Map> Update(Handle<Map> map);
5450 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5451 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5452 Descriptor* descriptor,
5453 TransitionFlag flag);
5455 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5458 Handle<HeapType> type,
5459 PropertyAttributes attributes,
5460 Representation representation,
5461 TransitionFlag flag);
5463 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5466 Handle<Object> constant,
5467 PropertyAttributes attributes,
5468 TransitionFlag flag);
5470 // Returns a new map with all transitions dropped from the given map and
5471 // the ElementsKind set.
5472 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5473 ElementsKind to_kind);
5475 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5477 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5479 TransitionFlag flag);
5481 static Handle<Map> CopyForObserved(Handle<Map> map);
5483 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5484 PropertyAttributes attrs_to_add,
5485 Handle<Symbol> transition_marker,
5486 const char* reason);
5488 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5491 // Maximal number of fast properties. Used to restrict the number of map
5492 // transitions to avoid an explosion in the number of maps for objects used as
5494 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5495 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5497 Handle<Object> value,
5498 PropertyAttributes attributes,
5499 StoreFromKeyed store_mode);
5500 static Handle<Map> TransitionToAccessorProperty(
5501 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5502 Handle<Object> accessor, PropertyAttributes attributes);
5503 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5506 PropertyAttributes attributes);
5508 inline void AppendDescriptor(Descriptor* desc);
5510 // Returns a copy of the map, prepared for inserting into the transition
5511 // tree (if the |map| owns descriptors then the new one will share
5512 // descriptors with |map|).
5513 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5515 // Returns a copy of the map, with all transitions dropped from the
5516 // instance descriptors.
5517 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5518 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5520 // Returns the next free property index (only valid for FAST MODE).
5521 int NextFreePropertyIndex();
5523 // Returns the number of properties described in instance_descriptors
5524 // filtering out properties with the specified attributes.
5525 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5526 PropertyAttributes filter = NONE);
5530 // Code cache operations.
5532 // Clears the code cache.
5533 inline void ClearCodeCache(Heap* heap);
5535 // Update code cache.
5536 static void UpdateCodeCache(Handle<Map> map,
5540 // Extend the descriptor array of the map with the list of descriptors.
5541 // In case of duplicates, the latest descriptor is used.
5542 static void AppendCallbackDescriptors(Handle<Map> map,
5543 Handle<Object> descriptors);
5545 static inline int SlackForArraySize(int old_size, int size_limit);
5547 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5549 // Returns the found code or undefined if absent.
5550 Object* FindInCodeCache(Name* name, Code::Flags flags);
5552 // Returns the non-negative index of the code object if it is in the
5553 // cache and -1 otherwise.
5554 int IndexInCodeCache(Object* name, Code* code);
5556 // Removes a code object from the code cache at the given index.
5557 void RemoveFromCodeCache(Name* name, Code* code, int index);
5559 // Computes a hash value for this map, to be used in HashTables and such.
5562 // Returns the map that this map transitions to if its elements_kind
5563 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5564 // |safe_to_add_transitions| is set to false if adding transitions is not
5566 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5568 // Returns the transitioned map for this map with the most generic
5569 // elements_kind that's found in |candidates|, or null handle if no match is
5571 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5572 MapHandleList* candidates);
5574 inline bool CanTransition();
5576 inline bool IsPrimitiveMap();
5577 inline bool IsJSObjectMap();
5578 inline bool IsJSArrayMap();
5579 inline bool IsStringMap();
5580 inline bool IsJSProxyMap();
5581 inline bool IsJSGlobalProxyMap();
5582 inline bool IsJSGlobalObjectMap();
5583 inline bool IsGlobalObjectMap();
5585 inline bool CanOmitMapChecks();
5587 static void AddDependentCode(Handle<Map> map,
5588 DependentCode::DependencyGroup group,
5591 bool IsMapInArrayPrototypeChain();
5593 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5595 // Dispatched behavior.
5596 DECLARE_PRINTER(Map)
5597 DECLARE_VERIFIER(Map)
5600 void DictionaryMapVerify();
5601 void VerifyOmittedMapChecks();
5604 inline int visitor_id();
5605 inline void set_visitor_id(int visitor_id);
5607 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5608 Handle<Object> prototype,
5609 PrototypeOptimizationMode mode);
5611 static const int kMaxPreAllocatedPropertyFields = 255;
5613 // Layout description.
5614 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5615 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5616 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5617 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5618 static const int kConstructorOrBackPointerOffset =
5619 kPrototypeOffset + kPointerSize;
5620 // When there is only one transition, it is stored directly in this field;
5621 // otherwise a transition array is used.
5622 // For prototype maps, this slot is used to store this map's PrototypeInfo
5624 static const int kTransitionsOrPrototypeInfoOffset =
5625 kConstructorOrBackPointerOffset + kPointerSize;
5626 static const int kDescriptorsOffset =
5627 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5628 #if V8_DOUBLE_FIELDS_UNBOXING
5629 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5630 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5632 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5633 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5635 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5636 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5637 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5639 // Layout of pointer fields. Heap iteration code relies on them
5640 // being continuously allocated.
5641 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5642 static const int kPointerFieldsEndOffset = kSize;
5644 // Byte offsets within kInstanceSizesOffset.
5645 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5646 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5647 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5648 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5649 // Note there is one byte available for use here.
5650 static const int kUnusedByte = 2;
5651 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5652 static const int kVisitorIdByte = 3;
5653 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5655 // Byte offsets within kInstanceAttributesOffset attributes.
5656 #if V8_TARGET_LITTLE_ENDIAN
5657 // Order instance type and bit field together such that they can be loaded
5658 // together as a 16-bit word with instance type in the lower 8 bits regardless
5659 // of endianess. Also provide endian-independent offset to that 16-bit word.
5660 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5661 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5663 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5664 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5666 static const int kInstanceTypeAndBitFieldOffset =
5667 kInstanceAttributesOffset + 0;
5668 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5669 static const int kUnusedPropertyFieldsByte = 3;
5670 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5672 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5673 Internals::kMapInstanceTypeAndBitFieldOffset);
5675 // Bit positions for bit field.
5676 static const int kHasNonInstancePrototype = 0;
5677 static const int kIsHiddenPrototype = 1;
5678 static const int kHasNamedInterceptor = 2;
5679 static const int kHasIndexedInterceptor = 3;
5680 static const int kIsUndetectable = 4;
5681 static const int kIsObserved = 5;
5682 static const int kIsAccessCheckNeeded = 6;
5683 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5685 // Bit positions for bit field 2
5686 static const int kIsExtensible = 0;
5687 static const int kStringWrapperSafeForDefaultValueOf = 1;
5688 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5689 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5691 // Derived values from bit field 2
5692 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5693 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5694 static const int8_t kMaximumBitField2FastSmiElementValue =
5695 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5696 Map::ElementsKindBits::kShift) - 1;
5697 static const int8_t kMaximumBitField2FastHoleyElementValue =
5698 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5699 Map::ElementsKindBits::kShift) - 1;
5700 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5701 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5702 Map::ElementsKindBits::kShift) - 1;
5704 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5705 kPointerFieldsEndOffset,
5706 kSize> BodyDescriptor;
5708 // Compares this map to another to see if they describe equivalent objects.
5709 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5710 // it had exactly zero inobject properties.
5711 // The "shared" flags of both this map and |other| are ignored.
5712 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5714 // Returns true if given field is unboxed double.
5715 inline bool IsUnboxedDoubleField(FieldIndex index);
5718 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5719 static void TraceAllTransitions(Map* map);
5722 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5723 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5724 Handle<LayoutDescriptor> layout_descriptor);
5727 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5728 Handle<Name> name, SimpleTransitionFlag flag);
5730 bool EquivalentToForTransition(Map* other);
5731 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5732 static Handle<Map> ShareDescriptor(Handle<Map> map,
5733 Handle<DescriptorArray> descriptors,
5734 Descriptor* descriptor);
5735 static Handle<Map> CopyInstallDescriptors(
5736 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5737 Handle<LayoutDescriptor> layout_descriptor);
5738 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5739 Descriptor* descriptor,
5740 TransitionFlag flag);
5741 static Handle<Map> CopyReplaceDescriptors(
5742 Handle<Map> map, Handle<DescriptorArray> descriptors,
5743 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5744 MaybeHandle<Name> maybe_name, const char* reason,
5745 SimpleTransitionFlag simple_flag);
5747 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5748 Handle<DescriptorArray> descriptors,
5749 Descriptor* descriptor,
5751 TransitionFlag flag);
5752 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5753 Handle<Map> map, int descriptor, PropertyKind kind,
5754 PropertyAttributes attributes, const char** reason);
5756 static Handle<Map> CopyNormalized(Handle<Map> map,
5757 PropertyNormalizationMode mode);
5759 // Fires when the layout of an object with a leaf map changes.
5760 // This includes adding transitions to the leaf map or changing
5761 // the descriptor array.
5762 inline void NotifyLeafMapLayoutChange();
5764 void DeprecateTransitionTree();
5765 bool DeprecateTarget(PropertyKind kind, Name* key,
5766 PropertyAttributes attributes,
5767 DescriptorArray* new_descriptors,
5768 LayoutDescriptor* new_layout_descriptor);
5770 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5772 // Update field type of the given descriptor to new representation and new
5773 // type. The type must be prepared for storing in descriptor array:
5774 // it must be either a simple type or a map wrapped in a weak cell.
5775 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5776 Representation new_representation,
5777 Handle<Object> new_wrapped_type);
5779 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5780 PropertyAttributes attributes);
5781 void PrintGeneralization(FILE* file,
5786 bool constant_to_field,
5787 Representation old_representation,
5788 Representation new_representation,
5789 HeapType* old_field_type,
5790 HeapType* new_field_type);
5792 static const int kFastPropertiesSoftLimit = 12;
5793 static const int kMaxFastProperties = 128;
5795 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5799 // An abstract superclass, a marker class really, for simple structure classes.
5800 // It doesn't carry much functionality but allows struct classes to be
5801 // identified in the type system.
5802 class Struct: public HeapObject {
5804 inline void InitializeBody(int object_size);
5805 DECLARE_CAST(Struct)
5809 // A simple one-element struct, useful where smis need to be boxed.
5810 class Box : public Struct {
5812 // [value]: the boxed contents.
5813 DECL_ACCESSORS(value, Object)
5817 // Dispatched behavior.
5818 DECLARE_PRINTER(Box)
5819 DECLARE_VERIFIER(Box)
5821 static const int kValueOffset = HeapObject::kHeaderSize;
5822 static const int kSize = kValueOffset + kPointerSize;
5825 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5829 // Container for metadata stored on each prototype map.
5830 class PrototypeInfo : public Struct {
5832 static const int UNREGISTERED = -1;
5834 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5835 // or Smi(0) if uninitialized.
5836 DECL_ACCESSORS(prototype_users, Object)
5837 // [registry_slot]: Slot in prototype's user registry where this user
5838 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5839 inline int registry_slot() const;
5840 inline void set_registry_slot(int slot);
5841 // [validity_cell]: Cell containing the validity bit for prototype chains
5842 // going through this object, or Smi(0) if uninitialized.
5843 DECL_ACCESSORS(validity_cell, Object)
5844 // [constructor_name]: User-friendly name of the original constructor.
5845 DECL_ACCESSORS(constructor_name, Object)
5847 DECLARE_CAST(PrototypeInfo)
5849 // Dispatched behavior.
5850 DECLARE_PRINTER(PrototypeInfo)
5851 DECLARE_VERIFIER(PrototypeInfo)
5853 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5854 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5855 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5856 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5857 static const int kSize = kConstructorNameOffset + kPointerSize;
5860 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5864 // Pair used to store both a ScopeInfo and an extension object in the extension
5865 // slot of a block context. Needed in the rare case where a declaration block
5866 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5867 // a sloppy direct eval. (In no other case both are needed at the same time.)
5868 class SloppyBlockWithEvalContextExtension : public Struct {
5870 // [scope_info]: Scope info.
5871 DECL_ACCESSORS(scope_info, ScopeInfo)
5872 // [extension]: Extension object.
5873 DECL_ACCESSORS(extension, JSObject)
5875 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5877 // Dispatched behavior.
5878 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5879 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5881 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5882 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5883 static const int kSize = kExtensionOffset + kPointerSize;
5886 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5890 // Script describes a script which has been added to the VM.
5891 class Script: public Struct {
5900 // Script compilation types.
5901 enum CompilationType {
5902 COMPILATION_TYPE_HOST = 0,
5903 COMPILATION_TYPE_EVAL = 1
5906 // Script compilation state.
5907 enum CompilationState {
5908 COMPILATION_STATE_INITIAL = 0,
5909 COMPILATION_STATE_COMPILED = 1
5912 // [source]: the script source.
5913 DECL_ACCESSORS(source, Object)
5915 // [name]: the script name.
5916 DECL_ACCESSORS(name, Object)
5918 // [id]: the script id.
5919 DECL_ACCESSORS(id, Smi)
5921 // [line_offset]: script line offset in resource from where it was extracted.
5922 DECL_ACCESSORS(line_offset, Smi)
5924 // [column_offset]: script column offset in resource from where it was
5926 DECL_ACCESSORS(column_offset, Smi)
5928 // [context_data]: context data for the context this script was compiled in.
5929 DECL_ACCESSORS(context_data, Object)
5931 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5932 DECL_ACCESSORS(wrapper, HeapObject)
5934 // [type]: the script type.
5935 DECL_ACCESSORS(type, Smi)
5937 // [line_ends]: FixedArray of line ends positions.
5938 DECL_ACCESSORS(line_ends, Object)
5940 // [eval_from_shared]: for eval scripts the shared funcion info for the
5941 // function from which eval was called.
5942 DECL_ACCESSORS(eval_from_shared, Object)
5944 // [eval_from_instructions_offset]: the instruction offset in the code for the
5945 // function from which eval was called where eval was called.
5946 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5948 // [shared_function_infos]: weak fixed array containing all shared
5949 // function infos created from this script.
5950 DECL_ACCESSORS(shared_function_infos, Object)
5952 // [flags]: Holds an exciting bitfield.
5953 DECL_ACCESSORS(flags, Smi)
5955 // [source_url]: sourceURL from magic comment
5956 DECL_ACCESSORS(source_url, Object)
5958 // [source_url]: sourceMappingURL magic comment
5959 DECL_ACCESSORS(source_mapping_url, Object)
5961 // [compilation_type]: how the the script was compiled. Encoded in the
5963 inline CompilationType compilation_type();
5964 inline void set_compilation_type(CompilationType type);
5966 // [compilation_state]: determines whether the script has already been
5967 // compiled. Encoded in the 'flags' field.
5968 inline CompilationState compilation_state();
5969 inline void set_compilation_state(CompilationState state);
5971 // [hide_source]: determines whether the script source can be exposed as
5972 // function source. Encoded in the 'flags' field.
5973 inline bool hide_source();
5974 inline void set_hide_source(bool value);
5976 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
5977 // and used by the embedder to make decisions about the script. V8 just passes
5978 // this through. Encoded in the 'flags' field.
5979 inline v8::ScriptOriginOptions origin_options();
5980 inline void set_origin_options(ScriptOriginOptions origin_options);
5982 DECLARE_CAST(Script)
5984 // If script source is an external string, check that the underlying
5985 // resource is accessible. Otherwise, always return true.
5986 inline bool HasValidSource();
5988 // Convert code position into column number.
5989 static int GetColumnNumber(Handle<Script> script, int code_pos);
5991 // Convert code position into (zero-based) line number.
5992 // The non-handlified version does not allocate, but may be much slower.
5993 static int GetLineNumber(Handle<Script> script, int code_pos);
5994 int GetLineNumber(int code_pos);
5996 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
5998 // Init line_ends array with code positions of line ends inside script source.
5999 static void InitLineEnds(Handle<Script> script);
6001 // Get the JS object wrapping the given script; create it if none exists.
6002 static Handle<JSObject> GetWrapper(Handle<Script> script);
6004 // Look through the list of existing shared function infos to find one
6005 // that matches the function literal. Return empty handle if not found.
6006 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6008 // Iterate over all script objects on the heap.
6011 explicit Iterator(Isolate* isolate);
6015 WeakFixedArray::Iterator iterator_;
6016 DISALLOW_COPY_AND_ASSIGN(Iterator);
6019 // Dispatched behavior.
6020 DECLARE_PRINTER(Script)
6021 DECLARE_VERIFIER(Script)
6023 static const int kSourceOffset = HeapObject::kHeaderSize;
6024 static const int kNameOffset = kSourceOffset + kPointerSize;
6025 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6026 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6027 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6028 static const int kWrapperOffset = kContextOffset + kPointerSize;
6029 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6030 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6031 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6032 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6033 static const int kEvalFrominstructionsOffsetOffset =
6034 kEvalFromSharedOffset + kPointerSize;
6035 static const int kSharedFunctionInfosOffset =
6036 kEvalFrominstructionsOffsetOffset + kPointerSize;
6037 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6038 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6039 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6040 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6043 int GetLineNumberWithArray(int code_pos);
6045 // Bit positions in the flags field.
6046 static const int kCompilationTypeBit = 0;
6047 static const int kCompilationStateBit = 1;
6048 static const int kHideSourceBit = 2;
6049 static const int kOriginOptionsShift = 3;
6050 static const int kOriginOptionsSize = 3;
6051 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6052 << kOriginOptionsShift;
6054 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6058 // List of builtin functions we want to identify to improve code
6061 // Each entry has a name of a global object property holding an object
6062 // optionally followed by ".prototype", a name of a builtin function
6063 // on the object (the one the id is set for), and a label.
6065 // Installation of ids for the selected builtin functions is handled
6066 // by the bootstrapper.
6067 #define FUNCTIONS_WITH_ID_LIST(V) \
6068 V(Array.prototype, indexOf, ArrayIndexOf) \
6069 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6070 V(Array.prototype, push, ArrayPush) \
6071 V(Array.prototype, pop, ArrayPop) \
6072 V(Array.prototype, shift, ArrayShift) \
6073 V(Function.prototype, apply, FunctionApply) \
6074 V(Function.prototype, call, FunctionCall) \
6075 V(String.prototype, charCodeAt, StringCharCodeAt) \
6076 V(String.prototype, charAt, StringCharAt) \
6077 V(String, fromCharCode, StringFromCharCode) \
6078 V(Math, random, MathRandom) \
6079 V(Math, floor, MathFloor) \
6080 V(Math, round, MathRound) \
6081 V(Math, ceil, MathCeil) \
6082 V(Math, abs, MathAbs) \
6083 V(Math, log, MathLog) \
6084 V(Math, exp, MathExp) \
6085 V(Math, sqrt, MathSqrt) \
6086 V(Math, pow, MathPow) \
6087 V(Math, max, MathMax) \
6088 V(Math, min, MathMin) \
6089 V(Math, cos, MathCos) \
6090 V(Math, sin, MathSin) \
6091 V(Math, tan, MathTan) \
6092 V(Math, acos, MathAcos) \
6093 V(Math, asin, MathAsin) \
6094 V(Math, atan, MathAtan) \
6095 V(Math, atan2, MathAtan2) \
6096 V(Math, imul, MathImul) \
6097 V(Math, clz32, MathClz32) \
6098 V(Math, fround, MathFround)
6100 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6101 V(Atomics, load, AtomicsLoad) \
6102 V(Atomics, store, AtomicsStore)
6104 enum BuiltinFunctionId {
6106 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6108 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6109 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6110 #undef DECLARE_FUNCTION_ID
6111 // Fake id for a special case of Math.pow. Note, it continues the
6112 // list of math functions.
6117 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6118 // that both {code} and {literals} can be NULL to pass search result status.
6119 struct CodeAndLiterals {
6120 Code* code; // Cached optimized code.
6121 FixedArray* literals; // Cached literals array.
6125 // SharedFunctionInfo describes the JSFunction information that can be
6126 // shared by multiple instances of the function.
6127 class SharedFunctionInfo: public HeapObject {
6129 // [name]: Function name.
6130 DECL_ACCESSORS(name, Object)
6132 // [code]: Function code.
6133 DECL_ACCESSORS(code, Code)
6134 inline void ReplaceCode(Code* code);
6136 // [optimized_code_map]: Map from native context to optimized code
6137 // and a shared literals array or Smi(0) if none.
6138 DECL_ACCESSORS(optimized_code_map, Object)
6140 // Returns entry from optimized code map for specified context and OSR entry.
6141 // Note that {code == nullptr} indicates no matching entry has been found,
6142 // whereas {literals == nullptr} indicates the code is context-independent.
6143 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6144 BailoutId osr_ast_id);
6146 // Clear optimized code map.
6147 void ClearOptimizedCodeMap();
6149 // Removed a specific optimized code object from the optimized code map.
6150 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6152 // Trims the optimized code map after entries have been removed.
6153 void TrimOptimizedCodeMap(int shrink_by);
6155 // Add a new entry to the optimized code map for context-independent code.
6156 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6159 // Add a new entry to the optimized code map for context-dependent code.
6160 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6161 Handle<Context> native_context,
6163 Handle<FixedArray> literals,
6164 BailoutId osr_ast_id);
6166 // Set up the link between shared function info and the script. The shared
6167 // function info is added to the list on the script.
6168 static void SetScript(Handle<SharedFunctionInfo> shared,
6169 Handle<Object> script_object);
6171 // Layout description of the optimized code map.
6172 static const int kNextMapIndex = 0;
6173 static const int kSharedCodeIndex = 1;
6174 static const int kEntriesStart = 2;
6175 static const int kContextOffset = 0;
6176 static const int kCachedCodeOffset = 1;
6177 static const int kLiteralsOffset = 2;
6178 static const int kOsrAstIdOffset = 3;
6179 static const int kEntryLength = 4;
6180 static const int kInitialLength = kEntriesStart + kEntryLength;
6182 // [scope_info]: Scope info.
6183 DECL_ACCESSORS(scope_info, ScopeInfo)
6185 // [construct stub]: Code stub for constructing instances of this function.
6186 DECL_ACCESSORS(construct_stub, Code)
6188 // Returns if this function has been compiled to native code yet.
6189 inline bool is_compiled();
6191 // [length]: The function length - usually the number of declared parameters.
6192 // Use up to 2^30 parameters.
6193 inline int length() const;
6194 inline void set_length(int value);
6196 // [internal formal parameter count]: The declared number of parameters.
6197 // For subclass constructors, also includes new.target.
6198 // The size of function's frame is internal_formal_parameter_count + 1.
6199 inline int internal_formal_parameter_count() const;
6200 inline void set_internal_formal_parameter_count(int value);
6202 // Set the formal parameter count so the function code will be
6203 // called without using argument adaptor frames.
6204 inline void DontAdaptArguments();
6206 // [expected_nof_properties]: Expected number of properties for the function.
6207 inline int expected_nof_properties() const;
6208 inline void set_expected_nof_properties(int value);
6210 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6211 // (increasingly) from crankshafted code where sufficient feedback isn't
6213 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6215 // Unconditionally clear the type feedback vector (including vector ICs).
6216 void ClearTypeFeedbackInfo();
6218 // Clear the type feedback vector with a more subtle policy at GC time.
6219 void ClearTypeFeedbackInfoAtGCTime();
6222 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6223 // even if the GC moves this SharedFunctionInfo.
6224 inline int unique_id() const;
6225 inline void set_unique_id(int value);
6228 // [instance class name]: class name for instances.
6229 DECL_ACCESSORS(instance_class_name, Object)
6231 // [function data]: This field holds some additional data for function.
6232 // Currently it has one of:
6233 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6234 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6235 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6236 // In the long run we don't want all functions to have this field but
6237 // we can fix that when we have a better model for storing hidden data
6239 DECL_ACCESSORS(function_data, Object)
6241 inline bool IsApiFunction();
6242 inline FunctionTemplateInfo* get_api_func_data();
6243 inline bool HasBuiltinFunctionId();
6244 inline BuiltinFunctionId builtin_function_id();
6245 inline bool HasBytecodeArray();
6246 inline BytecodeArray* bytecode_array();
6248 // [script info]: Script from which the function originates.
6249 DECL_ACCESSORS(script, Object)
6251 // [num_literals]: Number of literals used by this function.
6252 inline int num_literals() const;
6253 inline void set_num_literals(int value);
6255 // [start_position_and_type]: Field used to store both the source code
6256 // position, whether or not the function is a function expression,
6257 // and whether or not the function is a toplevel function. The two
6258 // least significants bit indicates whether the function is an
6259 // expression and the rest contains the source code position.
6260 inline int start_position_and_type() const;
6261 inline void set_start_position_and_type(int value);
6263 // The function is subject to debugging if a debug info is attached.
6264 inline bool HasDebugInfo();
6265 inline DebugInfo* GetDebugInfo();
6267 // A function has debug code if the compiled code has debug break slots.
6268 inline bool HasDebugCode();
6270 // [debug info]: Debug information.
6271 DECL_ACCESSORS(debug_info, Object)
6273 // [inferred name]: Name inferred from variable or property
6274 // assignment of this function. Used to facilitate debugging and
6275 // profiling of JavaScript code written in OO style, where almost
6276 // all functions are anonymous but are assigned to object
6278 DECL_ACCESSORS(inferred_name, String)
6280 // The function's name if it is non-empty, otherwise the inferred name.
6281 String* DebugName();
6283 // Position of the 'function' token in the script source.
6284 inline int function_token_position() const;
6285 inline void set_function_token_position(int function_token_position);
6287 // Position of this function in the script source.
6288 inline int start_position() const;
6289 inline void set_start_position(int start_position);
6291 // End position of this function in the script source.
6292 inline int end_position() const;
6293 inline void set_end_position(int end_position);
6295 // Is this function a function expression in the source code.
6296 DECL_BOOLEAN_ACCESSORS(is_expression)
6298 // Is this function a top-level function (scripts, evals).
6299 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6301 // Bit field containing various information collected by the compiler to
6302 // drive optimization.
6303 inline int compiler_hints() const;
6304 inline void set_compiler_hints(int value);
6306 inline int ast_node_count() const;
6307 inline void set_ast_node_count(int count);
6309 inline int profiler_ticks() const;
6310 inline void set_profiler_ticks(int ticks);
6312 // Inline cache age is used to infer whether the function survived a context
6313 // disposal or not. In the former case we reset the opt_count.
6314 inline int ic_age();
6315 inline void set_ic_age(int age);
6317 // Indicates if this function can be lazy compiled.
6318 // This is used to determine if we can safely flush code from a function
6319 // when doing GC if we expect that the function will no longer be used.
6320 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6322 // Indicates if this function can be lazy compiled without a context.
6323 // This is used to determine if we can force compilation without reaching
6324 // the function through program execution but through other means (e.g. heap
6325 // iteration by the debugger).
6326 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6328 // Indicates whether optimizations have been disabled for this
6329 // shared function info. If a function is repeatedly optimized or if
6330 // we cannot optimize the function we disable optimization to avoid
6331 // spending time attempting to optimize it again.
6332 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6334 // Indicates the language mode.
6335 inline LanguageMode language_mode();
6336 inline void set_language_mode(LanguageMode language_mode);
6338 // False if the function definitely does not allocate an arguments object.
6339 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6341 // Indicates that this function uses a super property (or an eval that may
6342 // use a super property).
6343 // This is needed to set up the [[HomeObject]] on the function instance.
6344 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6346 // True if the function has any duplicated parameter names.
6347 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6349 // Indicates whether the function is a native function.
6350 // These needs special treatment in .call and .apply since
6351 // null passed as the receiver should not be translated to the
6353 DECL_BOOLEAN_ACCESSORS(native)
6355 // Indicate that this function should always be inlined in optimized code.
6356 DECL_BOOLEAN_ACCESSORS(force_inline)
6358 // Indicates that the function was created by the Function function.
6359 // Though it's anonymous, toString should treat it as if it had the name
6360 // "anonymous". We don't set the name itself so that the system does not
6361 // see a binding for it.
6362 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6364 // Indicates whether the function is a bound function created using
6365 // the bind function.
6366 DECL_BOOLEAN_ACCESSORS(bound)
6368 // Indicates that the function is anonymous (the name field can be set
6369 // through the API, which does not change this flag).
6370 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6372 // Is this a function or top-level/eval code.
6373 DECL_BOOLEAN_ACCESSORS(is_function)
6375 // Indicates that code for this function cannot be compiled with Crankshaft.
6376 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6378 // Indicates that code for this function cannot be flushed.
6379 DECL_BOOLEAN_ACCESSORS(dont_flush)
6381 // Indicates that this function is a generator.
6382 DECL_BOOLEAN_ACCESSORS(is_generator)
6384 // Indicates that this function is an arrow function.
6385 DECL_BOOLEAN_ACCESSORS(is_arrow)
6387 // Indicates that this function is a concise method.
6388 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6390 // Indicates that this function is an accessor (getter or setter).
6391 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6393 // Indicates that this function is a default constructor.
6394 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6396 // Indicates that this function is an asm function.
6397 DECL_BOOLEAN_ACCESSORS(asm_function)
6399 // Indicates that the the shared function info is deserialized from cache.
6400 DECL_BOOLEAN_ACCESSORS(deserialized)
6402 // Indicates that the the shared function info has never been compiled before.
6403 DECL_BOOLEAN_ACCESSORS(never_compiled)
6405 inline FunctionKind kind();
6406 inline void set_kind(FunctionKind kind);
6408 // Indicates whether or not the code in the shared function support
6410 inline bool has_deoptimization_support();
6412 // Enable deoptimization support through recompiled code.
6413 void EnableDeoptimizationSupport(Code* recompiled);
6415 // Disable (further) attempted optimization of all functions sharing this
6416 // shared function info.
6417 void DisableOptimization(BailoutReason reason);
6419 inline BailoutReason disable_optimization_reason();
6421 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6422 // code, returns whether it asserted (i.e., always true if assertions are
6424 bool VerifyBailoutId(BailoutId id);
6426 // [source code]: Source code for the function.
6427 bool HasSourceCode() const;
6428 Handle<Object> GetSourceCode();
6430 // Number of times the function was optimized.
6431 inline int opt_count();
6432 inline void set_opt_count(int opt_count);
6434 // Number of times the function was deoptimized.
6435 inline void set_deopt_count(int value);
6436 inline int deopt_count();
6437 inline void increment_deopt_count();
6439 // Number of time we tried to re-enable optimization after it
6440 // was disabled due to high number of deoptimizations.
6441 inline void set_opt_reenable_tries(int value);
6442 inline int opt_reenable_tries();
6444 inline void TryReenableOptimization();
6446 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6447 inline void set_counters(int value);
6448 inline int counters() const;
6450 // Stores opt_count and bailout_reason as bit-fields.
6451 inline void set_opt_count_and_bailout_reason(int value);
6452 inline int opt_count_and_bailout_reason() const;
6454 inline void set_disable_optimization_reason(BailoutReason reason);
6456 // Tells whether this function should be subject to debugging.
6457 inline bool IsSubjectToDebugging();
6459 // Whether this function is defined in native code or extensions.
6460 inline bool IsBuiltin();
6462 // Check whether or not this function is inlineable.
6463 bool IsInlineable();
6465 // Source size of this function.
6468 // Calculate the instance size.
6469 int CalculateInstanceSize();
6471 // Calculate the number of in-object properties.
6472 int CalculateInObjectProperties();
6474 inline bool has_simple_parameters();
6476 // Initialize a SharedFunctionInfo from a parsed function literal.
6477 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6478 FunctionLiteral* lit);
6480 // Dispatched behavior.
6481 DECLARE_PRINTER(SharedFunctionInfo)
6482 DECLARE_VERIFIER(SharedFunctionInfo)
6484 void ResetForNewContext(int new_ic_age);
6486 // Iterate over all shared function infos that are created from a script.
6487 // That excludes shared function infos created for API functions and C++
6491 explicit Iterator(Isolate* isolate);
6492 SharedFunctionInfo* Next();
6497 Script::Iterator script_iterator_;
6498 WeakFixedArray::Iterator sfi_iterator_;
6499 DisallowHeapAllocation no_gc_;
6500 DISALLOW_COPY_AND_ASSIGN(Iterator);
6503 DECLARE_CAST(SharedFunctionInfo)
6506 static const int kDontAdaptArgumentsSentinel = -1;
6508 // Layout description.
6510 static const int kNameOffset = HeapObject::kHeaderSize;
6511 static const int kCodeOffset = kNameOffset + kPointerSize;
6512 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6513 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6514 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6515 static const int kInstanceClassNameOffset =
6516 kConstructStubOffset + kPointerSize;
6517 static const int kFunctionDataOffset =
6518 kInstanceClassNameOffset + kPointerSize;
6519 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6520 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6521 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6522 static const int kFeedbackVectorOffset =
6523 kInferredNameOffset + kPointerSize;
6525 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6526 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6528 // Just to not break the postmortrem support with conditional offsets
6529 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6530 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6533 #if V8_HOST_ARCH_32_BIT
6535 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6536 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6537 static const int kExpectedNofPropertiesOffset =
6538 kFormalParameterCountOffset + kPointerSize;
6539 static const int kNumLiteralsOffset =
6540 kExpectedNofPropertiesOffset + kPointerSize;
6541 static const int kStartPositionAndTypeOffset =
6542 kNumLiteralsOffset + kPointerSize;
6543 static const int kEndPositionOffset =
6544 kStartPositionAndTypeOffset + kPointerSize;
6545 static const int kFunctionTokenPositionOffset =
6546 kEndPositionOffset + kPointerSize;
6547 static const int kCompilerHintsOffset =
6548 kFunctionTokenPositionOffset + kPointerSize;
6549 static const int kOptCountAndBailoutReasonOffset =
6550 kCompilerHintsOffset + kPointerSize;
6551 static const int kCountersOffset =
6552 kOptCountAndBailoutReasonOffset + kPointerSize;
6553 static const int kAstNodeCountOffset =
6554 kCountersOffset + kPointerSize;
6555 static const int kProfilerTicksOffset =
6556 kAstNodeCountOffset + kPointerSize;
6559 static const int kSize = kProfilerTicksOffset + kPointerSize;
6561 // The only reason to use smi fields instead of int fields
6562 // is to allow iteration without maps decoding during
6563 // garbage collections.
6564 // To avoid wasting space on 64-bit architectures we use
6565 // the following trick: we group integer fields into pairs
6566 // The least significant integer in each pair is shifted left by 1.
6567 // By doing this we guarantee that LSB of each kPointerSize aligned
6568 // word is not set and thus this word cannot be treated as pointer
6569 // to HeapObject during old space traversal.
6570 #if V8_TARGET_LITTLE_ENDIAN
6571 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6572 static const int kFormalParameterCountOffset =
6573 kLengthOffset + kIntSize;
6575 static const int kExpectedNofPropertiesOffset =
6576 kFormalParameterCountOffset + kIntSize;
6577 static const int kNumLiteralsOffset =
6578 kExpectedNofPropertiesOffset + kIntSize;
6580 static const int kEndPositionOffset =
6581 kNumLiteralsOffset + kIntSize;
6582 static const int kStartPositionAndTypeOffset =
6583 kEndPositionOffset + kIntSize;
6585 static const int kFunctionTokenPositionOffset =
6586 kStartPositionAndTypeOffset + kIntSize;
6587 static const int kCompilerHintsOffset =
6588 kFunctionTokenPositionOffset + kIntSize;
6590 static const int kOptCountAndBailoutReasonOffset =
6591 kCompilerHintsOffset + kIntSize;
6592 static const int kCountersOffset =
6593 kOptCountAndBailoutReasonOffset + kIntSize;
6595 static const int kAstNodeCountOffset =
6596 kCountersOffset + kIntSize;
6597 static const int kProfilerTicksOffset =
6598 kAstNodeCountOffset + kIntSize;
6601 static const int kSize = kProfilerTicksOffset + kIntSize;
6603 #elif V8_TARGET_BIG_ENDIAN
6604 static const int kFormalParameterCountOffset =
6605 kLastPointerFieldOffset + kPointerSize;
6606 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6608 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6609 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6611 static const int kStartPositionAndTypeOffset =
6612 kExpectedNofPropertiesOffset + kIntSize;
6613 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6615 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6616 static const int kFunctionTokenPositionOffset =
6617 kCompilerHintsOffset + kIntSize;
6619 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6620 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6622 static const int kProfilerTicksOffset =
6623 kOptCountAndBailoutReasonOffset + kIntSize;
6624 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6627 static const int kSize = kAstNodeCountOffset + kIntSize;
6630 #error Unknown byte ordering
6631 #endif // Big endian
6635 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6637 typedef FixedBodyDescriptor<kNameOffset,
6638 kLastPointerFieldOffset + kPointerSize,
6639 kSize> BodyDescriptor;
6641 // Bit positions in start_position_and_type.
6642 // The source code start position is in the 30 most significant bits of
6643 // the start_position_and_type field.
6644 static const int kIsExpressionBit = 0;
6645 static const int kIsTopLevelBit = 1;
6646 static const int kStartPositionShift = 2;
6647 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6649 // Bit positions in compiler_hints.
6650 enum CompilerHints {
6651 kAllowLazyCompilation,
6652 kAllowLazyCompilationWithoutContext,
6653 kOptimizationDisabled,
6654 kStrictModeFunction,
6655 kStrongModeFunction,
6658 kHasDuplicateParameters,
6663 kNameShouldPrintAsAnonymous,
6670 kIsAccessorFunction,
6671 kIsDefaultConstructor,
6672 kIsSubclassConstructor,
6678 kCompilerHintsCount // Pseudo entry
6680 // Add hints for other modes when they're added.
6681 STATIC_ASSERT(LANGUAGE_END == 3);
6683 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6685 class DeoptCountBits : public BitField<int, 0, 4> {};
6686 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6687 class ICAgeBits : public BitField<int, 22, 8> {};
6689 class OptCountBits : public BitField<int, 0, 22> {};
6690 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6693 #if V8_HOST_ARCH_32_BIT
6694 // On 32 bit platforms, compiler hints is a smi.
6695 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6696 static const int kCompilerHintsSize = kPointerSize;
6698 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6699 static const int kCompilerHintsSmiTagSize = 0;
6700 static const int kCompilerHintsSize = kIntSize;
6703 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6704 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6707 // Constants for optimizing codegen for strict mode function and
6709 // Allows to use byte-width instructions.
6710 static const int kStrictModeBitWithinByte =
6711 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6712 static const int kStrongModeBitWithinByte =
6713 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6715 static const int kNativeBitWithinByte =
6716 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6718 static const int kBoundBitWithinByte =
6719 (kBoundFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6721 #if defined(V8_TARGET_LITTLE_ENDIAN)
6722 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6723 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6724 static const int kStrongModeByteOffset =
6725 kCompilerHintsOffset +
6726 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6727 static const int kNativeByteOffset = kCompilerHintsOffset +
6728 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6729 static const int kBoundByteOffset =
6730 kCompilerHintsOffset +
6731 (kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6732 #elif defined(V8_TARGET_BIG_ENDIAN)
6733 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6734 (kCompilerHintsSize - 1) -
6735 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6736 static const int kStrongModeByteOffset =
6737 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6738 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6739 static const int kNativeByteOffset = kCompilerHintsOffset +
6740 (kCompilerHintsSize - 1) -
6741 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6742 static const int kBoundByteOffset =
6743 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6744 ((kBoundFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6746 #error Unknown byte ordering
6750 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6754 // Printing support.
6755 struct SourceCodeOf {
6756 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6757 : value(v), max_length(max) {}
6758 const SharedFunctionInfo* value;
6763 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6766 class JSGeneratorObject: public JSObject {
6768 // [function]: The function corresponding to this generator object.
6769 DECL_ACCESSORS(function, JSFunction)
6771 // [context]: The context of the suspended computation.
6772 DECL_ACCESSORS(context, Context)
6774 // [receiver]: The receiver of the suspended computation.
6775 DECL_ACCESSORS(receiver, Object)
6777 // [continuation]: Offset into code of continuation.
6779 // A positive offset indicates a suspended generator. The special
6780 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6781 // cannot be resumed.
6782 inline int continuation() const;
6783 inline void set_continuation(int continuation);
6784 inline bool is_closed();
6785 inline bool is_executing();
6786 inline bool is_suspended();
6788 // [operand_stack]: Saved operand stack.
6789 DECL_ACCESSORS(operand_stack, FixedArray)
6791 DECLARE_CAST(JSGeneratorObject)
6793 // Dispatched behavior.
6794 DECLARE_PRINTER(JSGeneratorObject)
6795 DECLARE_VERIFIER(JSGeneratorObject)
6797 // Magic sentinel values for the continuation.
6798 static const int kGeneratorExecuting = -1;
6799 static const int kGeneratorClosed = 0;
6801 // Layout description.
6802 static const int kFunctionOffset = JSObject::kHeaderSize;
6803 static const int kContextOffset = kFunctionOffset + kPointerSize;
6804 static const int kReceiverOffset = kContextOffset + kPointerSize;
6805 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6806 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6807 static const int kSize = kOperandStackOffset + kPointerSize;
6809 // Resume mode, for use by runtime functions.
6810 enum ResumeMode { NEXT, THROW };
6812 // Yielding from a generator returns an object with the following inobject
6813 // properties. See Context::iterator_result_map() for the map.
6814 static const int kResultValuePropertyIndex = 0;
6815 static const int kResultDonePropertyIndex = 1;
6816 static const int kResultPropertyCount = 2;
6818 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6819 static const int kResultDonePropertyOffset =
6820 kResultValuePropertyOffset + kPointerSize;
6821 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6824 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6828 // Representation for module instance objects.
6829 class JSModule: public JSObject {
6831 // [context]: the context holding the module's locals, or undefined if none.
6832 DECL_ACCESSORS(context, Object)
6834 // [scope_info]: Scope info.
6835 DECL_ACCESSORS(scope_info, ScopeInfo)
6837 DECLARE_CAST(JSModule)
6839 // Dispatched behavior.
6840 DECLARE_PRINTER(JSModule)
6841 DECLARE_VERIFIER(JSModule)
6843 // Layout description.
6844 static const int kContextOffset = JSObject::kHeaderSize;
6845 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6846 static const int kSize = kScopeInfoOffset + kPointerSize;
6849 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6853 // JSFunction describes JavaScript functions.
6854 class JSFunction: public JSObject {
6856 // [prototype_or_initial_map]:
6857 DECL_ACCESSORS(prototype_or_initial_map, Object)
6859 // [shared]: The information about the function that
6860 // can be shared by instances.
6861 DECL_ACCESSORS(shared, SharedFunctionInfo)
6863 // [context]: The context for this function.
6864 inline Context* context();
6865 inline void set_context(Object* context);
6866 inline JSObject* global_proxy();
6868 // [code]: The generated code object for this function. Executed
6869 // when the function is invoked, e.g. foo() or new foo(). See
6870 // [[Call]] and [[Construct]] description in ECMA-262, section
6872 inline Code* code();
6873 inline void set_code(Code* code);
6874 inline void set_code_no_write_barrier(Code* code);
6875 inline void ReplaceCode(Code* code);
6877 // Tells whether this function is builtin.
6878 inline bool IsBuiltin();
6880 // Tells whether this function inlines the given shared function info.
6881 bool Inlines(SharedFunctionInfo* candidate);
6883 // Tells whether this function should be subject to debugging.
6884 inline bool IsSubjectToDebugging();
6886 // Tells whether or not the function needs arguments adaption.
6887 inline bool NeedsArgumentsAdaption();
6889 // Tells whether or not this function has been optimized.
6890 inline bool IsOptimized();
6892 // Mark this function for lazy recompilation. The function will be
6893 // recompiled the next time it is executed.
6894 void MarkForOptimization();
6895 void AttemptConcurrentOptimization();
6897 // Tells whether or not the function is already marked for lazy
6899 inline bool IsMarkedForOptimization();
6900 inline bool IsMarkedForConcurrentOptimization();
6902 // Tells whether or not the function is on the concurrent recompilation queue.
6903 inline bool IsInOptimizationQueue();
6905 // Inobject slack tracking is the way to reclaim unused inobject space.
6907 // The instance size is initially determined by adding some slack to
6908 // expected_nof_properties (to allow for a few extra properties added
6909 // after the constructor). There is no guarantee that the extra space
6910 // will not be wasted.
6912 // Here is the algorithm to reclaim the unused inobject space:
6913 // - Detect the first constructor call for this JSFunction.
6914 // When it happens enter the "in progress" state: initialize construction
6915 // counter in the initial_map.
6916 // - While the tracking is in progress create objects filled with
6917 // one_pointer_filler_map instead of undefined_value. This way they can be
6918 // resized quickly and safely.
6919 // - Once enough objects have been created compute the 'slack'
6920 // (traverse the map transition tree starting from the
6921 // initial_map and find the lowest value of unused_property_fields).
6922 // - Traverse the transition tree again and decrease the instance size
6923 // of every map. Existing objects will resize automatically (they are
6924 // filled with one_pointer_filler_map). All further allocations will
6925 // use the adjusted instance size.
6926 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6927 // allocations made using different closures could actually create different
6928 // kind of objects (see prototype inheritance pattern).
6930 // Important: inobject slack tracking is not attempted during the snapshot
6933 // True if the initial_map is set and the object constructions countdown
6934 // counter is not zero.
6935 static const int kGenerousAllocationCount =
6936 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6937 inline bool IsInobjectSlackTrackingInProgress();
6939 // Starts the tracking.
6940 // Initializes object constructions countdown counter in the initial map.
6941 void StartInobjectSlackTracking();
6943 // Completes the tracking.
6944 void CompleteInobjectSlackTracking();
6946 // [literals_or_bindings]: Fixed array holding either
6947 // the materialized literals or the bindings of a bound function.
6949 // If the function contains object, regexp or array literals, the
6950 // literals array prefix contains the object, regexp, and array
6951 // function to be used when creating these literals. This is
6952 // necessary so that we do not dynamically lookup the object, regexp
6953 // or array functions. Performing a dynamic lookup, we might end up
6954 // using the functions from a new context that we should not have
6957 // On bound functions, the array is a (copy-on-write) fixed-array containing
6958 // the function that was bound, bound this-value and any bound
6959 // arguments. Bound functions never contain literals.
6960 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6962 inline FixedArray* literals();
6963 inline void set_literals(FixedArray* literals);
6965 inline FixedArray* function_bindings();
6966 inline void set_function_bindings(FixedArray* bindings);
6968 // The initial map for an object created by this constructor.
6969 inline Map* initial_map();
6970 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
6971 Handle<Object> prototype);
6972 inline bool has_initial_map();
6973 static void EnsureHasInitialMap(Handle<JSFunction> function);
6975 // Get and set the prototype property on a JSFunction. If the
6976 // function has an initial map the prototype is set on the initial
6977 // map. Otherwise, the prototype is put in the initial map field
6978 // until an initial map is needed.
6979 inline bool has_prototype();
6980 inline bool has_instance_prototype();
6981 inline Object* prototype();
6982 inline Object* instance_prototype();
6983 static void SetPrototype(Handle<JSFunction> function,
6984 Handle<Object> value);
6985 static void SetInstancePrototype(Handle<JSFunction> function,
6986 Handle<Object> value);
6988 // Creates a new closure for the fucntion with the same bindings,
6989 // bound values, and prototype. An equivalent of spec operations
6990 // ``CloneMethod`` and ``CloneBoundFunction``.
6991 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
6993 // After prototype is removed, it will not be created when accessed, and
6994 // [[Construct]] from this function will not be allowed.
6995 bool RemovePrototype();
6996 inline bool should_have_prototype();
6998 // Accessor for this function's initial map's [[class]]
6999 // property. This is primarily used by ECMA native functions. This
7000 // method sets the class_name field of this function's initial map
7001 // to a given value. It creates an initial map if this function does
7002 // not have one. Note that this method does not copy the initial map
7003 // if it has one already, but simply replaces it with the new value.
7004 // Instances created afterwards will have a map whose [[class]] is
7005 // set to 'value', but there is no guarantees on instances created
7007 void SetInstanceClassName(String* name);
7009 // Returns if this function has been compiled to native code yet.
7010 inline bool is_compiled();
7012 // Returns `false` if formal parameters include rest parameters, optional
7013 // parameters, or destructuring parameters.
7014 // TODO(caitp): make this a flag set during parsing
7015 inline bool has_simple_parameters();
7017 // [next_function_link]: Links functions into various lists, e.g. the list
7018 // of optimized functions hanging off the native_context. The CodeFlusher
7019 // uses this link to chain together flushing candidates. Treated weakly
7020 // by the garbage collector.
7021 DECL_ACCESSORS(next_function_link, Object)
7023 // Prints the name of the function using PrintF.
7024 void PrintName(FILE* out = stdout);
7026 DECLARE_CAST(JSFunction)
7028 // Iterates the objects, including code objects indirectly referenced
7029 // through pointers to the first instruction in the code object.
7030 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7032 // Dispatched behavior.
7033 DECLARE_PRINTER(JSFunction)
7034 DECLARE_VERIFIER(JSFunction)
7036 // Returns the number of allocated literals.
7037 inline int NumberOfLiterals();
7039 // Used for flags such as --hydrogen-filter.
7040 bool PassesFilter(const char* raw_filter);
7042 // The function's name if it is configured, otherwise shared function info
7044 static Handle<String> GetDebugName(Handle<JSFunction> function);
7046 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7047 // kSize) is weak and has special handling during garbage collection.
7048 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7049 static const int kPrototypeOrInitialMapOffset =
7050 kCodeEntryOffset + kPointerSize;
7051 static const int kSharedFunctionInfoOffset =
7052 kPrototypeOrInitialMapOffset + kPointerSize;
7053 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7054 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7055 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7056 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7057 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7059 // Layout of the bound-function binding array.
7060 static const int kBoundFunctionIndex = 0;
7061 static const int kBoundThisIndex = 1;
7062 static const int kBoundArgumentsStartIndex = 2;
7065 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7069 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7070 // and the prototype is hidden. JSGlobalProxy always delegates
7071 // property accesses to its prototype if the prototype is not null.
7073 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7075 // Accessing a JSGlobalProxy requires security check.
7077 class JSGlobalProxy : public JSObject {
7079 // [native_context]: the owner native context of this global proxy object.
7080 // It is null value if this object is not used by any context.
7081 DECL_ACCESSORS(native_context, Object)
7083 // [hash]: The hash code property (undefined if not initialized yet).
7084 DECL_ACCESSORS(hash, Object)
7086 DECLARE_CAST(JSGlobalProxy)
7088 inline bool IsDetachedFrom(GlobalObject* global) const;
7090 // Dispatched behavior.
7091 DECLARE_PRINTER(JSGlobalProxy)
7092 DECLARE_VERIFIER(JSGlobalProxy)
7094 // Layout description.
7095 static const int kNativeContextOffset = JSObject::kHeaderSize;
7096 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7097 static const int kSize = kHashOffset + kPointerSize;
7100 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7104 // Common super class for JavaScript global objects and the special
7105 // builtins global objects.
7106 class GlobalObject: public JSObject {
7108 // [builtins]: the object holding the runtime routines written in JS.
7109 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7111 // [native context]: the natives corresponding to this global object.
7112 DECL_ACCESSORS(native_context, Context)
7114 // [global proxy]: the global proxy object of the context
7115 DECL_ACCESSORS(global_proxy, JSObject)
7117 DECLARE_CAST(GlobalObject)
7119 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7121 // Ensure that the global object has a cell for the given property name.
7122 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7125 // Layout description.
7126 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7127 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7128 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7129 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7132 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7136 // JavaScript global object.
7137 class JSGlobalObject: public GlobalObject {
7139 DECLARE_CAST(JSGlobalObject)
7141 inline bool IsDetached();
7143 // Dispatched behavior.
7144 DECLARE_PRINTER(JSGlobalObject)
7145 DECLARE_VERIFIER(JSGlobalObject)
7147 // Layout description.
7148 static const int kSize = GlobalObject::kHeaderSize;
7151 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7155 // Builtins global object which holds the runtime routines written in
7157 class JSBuiltinsObject: public GlobalObject {
7159 DECLARE_CAST(JSBuiltinsObject)
7161 // Dispatched behavior.
7162 DECLARE_PRINTER(JSBuiltinsObject)
7163 DECLARE_VERIFIER(JSBuiltinsObject)
7165 // Layout description.
7166 static const int kSize = GlobalObject::kHeaderSize;
7169 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7173 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7174 class JSValue: public JSObject {
7176 // [value]: the object being wrapped.
7177 DECL_ACCESSORS(value, Object)
7179 DECLARE_CAST(JSValue)
7181 // Dispatched behavior.
7182 DECLARE_PRINTER(JSValue)
7183 DECLARE_VERIFIER(JSValue)
7185 // Layout description.
7186 static const int kValueOffset = JSObject::kHeaderSize;
7187 static const int kSize = kValueOffset + kPointerSize;
7190 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7196 // Representation for JS date objects.
7197 class JSDate: public JSObject {
7199 // If one component is NaN, all of them are, indicating a NaN time value.
7200 // [value]: the time value.
7201 DECL_ACCESSORS(value, Object)
7202 // [year]: caches year. Either undefined, smi, or NaN.
7203 DECL_ACCESSORS(year, Object)
7204 // [month]: caches month. Either undefined, smi, or NaN.
7205 DECL_ACCESSORS(month, Object)
7206 // [day]: caches day. Either undefined, smi, or NaN.
7207 DECL_ACCESSORS(day, Object)
7208 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7209 DECL_ACCESSORS(weekday, Object)
7210 // [hour]: caches hours. Either undefined, smi, or NaN.
7211 DECL_ACCESSORS(hour, Object)
7212 // [min]: caches minutes. Either undefined, smi, or NaN.
7213 DECL_ACCESSORS(min, Object)
7214 // [sec]: caches seconds. Either undefined, smi, or NaN.
7215 DECL_ACCESSORS(sec, Object)
7216 // [cache stamp]: sample of the date cache stamp at the
7217 // moment when chached fields were cached.
7218 DECL_ACCESSORS(cache_stamp, Object)
7220 DECLARE_CAST(JSDate)
7222 // Returns the date field with the specified index.
7223 // See FieldIndex for the list of date fields.
7224 static Object* GetField(Object* date, Smi* index);
7226 void SetValue(Object* value, bool is_value_nan);
7229 // Dispatched behavior.
7230 DECLARE_PRINTER(JSDate)
7231 DECLARE_VERIFIER(JSDate)
7233 // The order is important. It must be kept in sync with date macros
7244 kFirstUncachedField,
7245 kMillisecond = kFirstUncachedField,
7249 kYearUTC = kFirstUTCField,
7262 // Layout description.
7263 static const int kValueOffset = JSObject::kHeaderSize;
7264 static const int kYearOffset = kValueOffset + kPointerSize;
7265 static const int kMonthOffset = kYearOffset + kPointerSize;
7266 static const int kDayOffset = kMonthOffset + kPointerSize;
7267 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7268 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7269 static const int kMinOffset = kHourOffset + kPointerSize;
7270 static const int kSecOffset = kMinOffset + kPointerSize;
7271 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7272 static const int kSize = kCacheStampOffset + kPointerSize;
7275 inline Object* DoGetField(FieldIndex index);
7277 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7279 // Computes and caches the cacheable fields of the date.
7280 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7283 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7287 // Representation of message objects used for error reporting through
7288 // the API. The messages are formatted in JavaScript so this object is
7289 // a real JavaScript object. The information used for formatting the
7290 // error messages are not directly accessible from JavaScript to
7291 // prevent leaking information to user code called during error
7293 class JSMessageObject: public JSObject {
7295 // [type]: the type of error message.
7296 inline int type() const;
7297 inline void set_type(int value);
7299 // [arguments]: the arguments for formatting the error message.
7300 DECL_ACCESSORS(argument, Object)
7302 // [script]: the script from which the error message originated.
7303 DECL_ACCESSORS(script, Object)
7305 // [stack_frames]: an array of stack frames for this error object.
7306 DECL_ACCESSORS(stack_frames, Object)
7308 // [start_position]: the start position in the script for the error message.
7309 inline int start_position() const;
7310 inline void set_start_position(int value);
7312 // [end_position]: the end position in the script for the error message.
7313 inline int end_position() const;
7314 inline void set_end_position(int value);
7316 DECLARE_CAST(JSMessageObject)
7318 // Dispatched behavior.
7319 DECLARE_PRINTER(JSMessageObject)
7320 DECLARE_VERIFIER(JSMessageObject)
7322 // Layout description.
7323 static const int kTypeOffset = JSObject::kHeaderSize;
7324 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7325 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7326 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7327 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7328 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7329 static const int kSize = kEndPositionOffset + kPointerSize;
7331 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7332 kStackFramesOffset + kPointerSize,
7333 kSize> BodyDescriptor;
7337 // Regular expressions
7338 // The regular expression holds a single reference to a FixedArray in
7339 // the kDataOffset field.
7340 // The FixedArray contains the following data:
7341 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7342 // - reference to the original source string
7343 // - reference to the original flag string
7344 // If it is an atom regexp
7345 // - a reference to a literal string to search for
7346 // If it is an irregexp regexp:
7347 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7348 // used for tracking the last usage (used for code flushing).
7349 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7350 // used for tracking the last usage (used for code flushing)..
7351 // - max number of registers used by irregexp implementations.
7352 // - number of capture registers (output values) of the regexp.
7353 class JSRegExp: public JSObject {
7356 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7357 // ATOM: A simple string to match against using an indexOf operation.
7358 // IRREGEXP: Compiled with Irregexp.
7359 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7360 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7367 UNICODE_ESCAPES = 16
7372 explicit Flags(uint32_t value) : value_(value) { }
7373 bool is_global() { return (value_ & GLOBAL) != 0; }
7374 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7375 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7376 bool is_sticky() { return (value_ & STICKY) != 0; }
7377 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7378 uint32_t value() { return value_; }
7383 DECL_ACCESSORS(data, Object)
7385 inline Type TypeTag();
7386 inline int CaptureCount();
7387 inline Flags GetFlags();
7388 inline String* Pattern();
7389 inline Object* DataAt(int index);
7390 // Set implementation data after the object has been prepared.
7391 inline void SetDataAt(int index, Object* value);
7393 static int code_index(bool is_latin1) {
7395 return kIrregexpLatin1CodeIndex;
7397 return kIrregexpUC16CodeIndex;
7401 static int saved_code_index(bool is_latin1) {
7403 return kIrregexpLatin1CodeSavedIndex;
7405 return kIrregexpUC16CodeSavedIndex;
7409 DECLARE_CAST(JSRegExp)
7411 // Dispatched behavior.
7412 DECLARE_VERIFIER(JSRegExp)
7414 static const int kDataOffset = JSObject::kHeaderSize;
7415 static const int kSize = kDataOffset + kPointerSize;
7417 // Indices in the data array.
7418 static const int kTagIndex = 0;
7419 static const int kSourceIndex = kTagIndex + 1;
7420 static const int kFlagsIndex = kSourceIndex + 1;
7421 static const int kDataIndex = kFlagsIndex + 1;
7422 // The data fields are used in different ways depending on the
7423 // value of the tag.
7424 // Atom regexps (literal strings).
7425 static const int kAtomPatternIndex = kDataIndex;
7427 static const int kAtomDataSize = kAtomPatternIndex + 1;
7429 // Irregexp compiled code or bytecode for Latin1. If compilation
7430 // fails, this fields hold an exception object that should be
7431 // thrown if the regexp is used again.
7432 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7433 // Irregexp compiled code or bytecode for UC16. If compilation
7434 // fails, this fields hold an exception object that should be
7435 // thrown if the regexp is used again.
7436 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7438 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7439 // is a potential candidate for flushing.
7440 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7441 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7442 // a potential candidate for flushing.
7443 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7445 // Maximal number of registers used by either Latin1 or UC16.
7446 // Only used to check that there is enough stack space
7447 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7448 // Number of captures in the compiled regexp.
7449 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7451 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7453 // Offsets directly into the data fixed array.
7454 static const int kDataTagOffset =
7455 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7456 static const int kDataOneByteCodeOffset =
7457 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7458 static const int kDataUC16CodeOffset =
7459 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7460 static const int kIrregexpCaptureCountOffset =
7461 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7463 // In-object fields.
7464 static const int kSourceFieldIndex = 0;
7465 static const int kGlobalFieldIndex = 1;
7466 static const int kIgnoreCaseFieldIndex = 2;
7467 static const int kMultilineFieldIndex = 3;
7468 static const int kLastIndexFieldIndex = 4;
7469 static const int kInObjectFieldCount = 5;
7471 // The uninitialized value for a regexp code object.
7472 static const int kUninitializedValue = -1;
7474 // The compilation error value for the regexp code object. The real error
7475 // object is in the saved code field.
7476 static const int kCompilationErrorValue = -2;
7478 // When we store the sweep generation at which we moved the code from the
7479 // code index to the saved code index we mask it of to be in the [0:255]
7481 static const int kCodeAgeMask = 0xff;
7485 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7487 static inline bool IsMatch(HashTableKey* key, Object* value) {
7488 return key->IsMatch(value);
7491 static inline uint32_t Hash(HashTableKey* key) {
7495 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7496 return key->HashForObject(object);
7499 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7501 static const int kPrefixSize = 0;
7502 static const int kEntrySize = 2;
7506 // This cache is used in two different variants. For regexp caching, it simply
7507 // maps identifying info of the regexp to the cached regexp object. Scripts and
7508 // eval code only gets cached after a second probe for the code object. To do
7509 // so, on first "put" only a hash identifying the source is entered into the
7510 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7511 // such lifetimes get reduced, and removed once they reach zero. If a second put
7512 // is called while such a hash is live in the cache, the hash gets replaced by
7513 // an actual cache entry. Age also removes stale live entries from the cache.
7514 // Such entries are identified by SharedFunctionInfos pointing to either the
7515 // recompilation stub, or to "old" code. This avoids memory leaks due to
7516 // premature caching of scripts and eval strings that are never needed later.
7517 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7518 CompilationCacheShape,
7521 // Find cached value for a string key, otherwise return null.
7522 Handle<Object> Lookup(
7523 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7524 Handle<Object> LookupEval(
7525 Handle<String> src, Handle<SharedFunctionInfo> shared,
7526 LanguageMode language_mode, int scope_position);
7527 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7528 static Handle<CompilationCacheTable> Put(
7529 Handle<CompilationCacheTable> cache, Handle<String> src,
7530 Handle<Context> context, LanguageMode language_mode,
7531 Handle<Object> value);
7532 static Handle<CompilationCacheTable> PutEval(
7533 Handle<CompilationCacheTable> cache, Handle<String> src,
7534 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7535 int scope_position);
7536 static Handle<CompilationCacheTable> PutRegExp(
7537 Handle<CompilationCacheTable> cache, Handle<String> src,
7538 JSRegExp::Flags flags, Handle<FixedArray> value);
7539 void Remove(Object* value);
7541 static const int kHashGenerations = 10;
7543 DECLARE_CAST(CompilationCacheTable)
7546 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7550 class CodeCache: public Struct {
7552 DECL_ACCESSORS(default_cache, FixedArray)
7553 DECL_ACCESSORS(normal_type_cache, Object)
7555 // Add the code object to the cache.
7557 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7559 // Lookup code object in the cache. Returns code object if found and undefined
7561 Object* Lookup(Name* name, Code::Flags flags);
7563 // Get the internal index of a code object in the cache. Returns -1 if the
7564 // code object is not in that cache. This index can be used to later call
7565 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7567 int GetIndex(Object* name, Code* code);
7569 // Remove an object from the cache with the provided internal index.
7570 void RemoveByIndex(Object* name, Code* code, int index);
7572 DECLARE_CAST(CodeCache)
7574 // Dispatched behavior.
7575 DECLARE_PRINTER(CodeCache)
7576 DECLARE_VERIFIER(CodeCache)
7578 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7579 static const int kNormalTypeCacheOffset =
7580 kDefaultCacheOffset + kPointerSize;
7581 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7584 static void UpdateDefaultCache(
7585 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7586 static void UpdateNormalTypeCache(
7587 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7588 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7589 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7591 // Code cache layout of the default cache. Elements are alternating name and
7592 // code objects for non normal load/store/call IC's.
7593 static const int kCodeCacheEntrySize = 2;
7594 static const int kCodeCacheEntryNameOffset = 0;
7595 static const int kCodeCacheEntryCodeOffset = 1;
7597 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7601 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7603 static inline bool IsMatch(HashTableKey* key, Object* value) {
7604 return key->IsMatch(value);
7607 static inline uint32_t Hash(HashTableKey* key) {
7611 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7612 return key->HashForObject(object);
7615 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7617 static const int kPrefixSize = 0;
7618 static const int kEntrySize = 2;
7622 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7623 CodeCacheHashTableShape,
7626 Object* Lookup(Name* name, Code::Flags flags);
7627 static Handle<CodeCacheHashTable> Put(
7628 Handle<CodeCacheHashTable> table,
7632 int GetIndex(Name* name, Code::Flags flags);
7633 void RemoveByIndex(int index);
7635 DECLARE_CAST(CodeCacheHashTable)
7637 // Initial size of the fixed array backing the hash table.
7638 static const int kInitialSize = 64;
7641 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7645 class PolymorphicCodeCache: public Struct {
7647 DECL_ACCESSORS(cache, Object)
7649 static void Update(Handle<PolymorphicCodeCache> cache,
7650 MapHandleList* maps,
7655 // Returns an undefined value if the entry is not found.
7656 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7658 DECLARE_CAST(PolymorphicCodeCache)
7660 // Dispatched behavior.
7661 DECLARE_PRINTER(PolymorphicCodeCache)
7662 DECLARE_VERIFIER(PolymorphicCodeCache)
7664 static const int kCacheOffset = HeapObject::kHeaderSize;
7665 static const int kSize = kCacheOffset + kPointerSize;
7668 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7672 class PolymorphicCodeCacheHashTable
7673 : public HashTable<PolymorphicCodeCacheHashTable,
7674 CodeCacheHashTableShape,
7677 Object* Lookup(MapHandleList* maps, int code_kind);
7679 static Handle<PolymorphicCodeCacheHashTable> Put(
7680 Handle<PolymorphicCodeCacheHashTable> hash_table,
7681 MapHandleList* maps,
7685 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7687 static const int kInitialSize = 64;
7689 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7693 class TypeFeedbackInfo: public Struct {
7695 inline int ic_total_count();
7696 inline void set_ic_total_count(int count);
7698 inline int ic_with_type_info_count();
7699 inline void change_ic_with_type_info_count(int delta);
7701 inline int ic_generic_count();
7702 inline void change_ic_generic_count(int delta);
7704 inline void initialize_storage();
7706 inline void change_own_type_change_checksum();
7707 inline int own_type_change_checksum();
7709 inline void set_inlined_type_change_checksum(int checksum);
7710 inline bool matches_inlined_type_change_checksum(int checksum);
7712 DECLARE_CAST(TypeFeedbackInfo)
7714 // Dispatched behavior.
7715 DECLARE_PRINTER(TypeFeedbackInfo)
7716 DECLARE_VERIFIER(TypeFeedbackInfo)
7718 static const int kStorage1Offset = HeapObject::kHeaderSize;
7719 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7720 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7721 static const int kSize = kStorage3Offset + kPointerSize;
7724 static const int kTypeChangeChecksumBits = 7;
7726 class ICTotalCountField: public BitField<int, 0,
7727 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7728 class OwnTypeChangeChecksum: public BitField<int,
7729 kSmiValueSize - kTypeChangeChecksumBits,
7730 kTypeChangeChecksumBits> {}; // NOLINT
7731 class ICsWithTypeInfoCountField: public BitField<int, 0,
7732 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7733 class InlinedTypeChangeChecksum: public BitField<int,
7734 kSmiValueSize - kTypeChangeChecksumBits,
7735 kTypeChangeChecksumBits> {}; // NOLINT
7737 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7741 enum AllocationSiteMode {
7742 DONT_TRACK_ALLOCATION_SITE,
7743 TRACK_ALLOCATION_SITE,
7744 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7748 class AllocationSite: public Struct {
7750 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7751 static const double kPretenureRatio;
7752 static const int kPretenureMinimumCreated = 100;
7754 // Values for pretenure decision field.
7755 enum PretenureDecision {
7761 kLastPretenureDecisionValue = kZombie
7764 const char* PretenureDecisionName(PretenureDecision decision);
7766 DECL_ACCESSORS(transition_info, Object)
7767 // nested_site threads a list of sites that represent nested literals
7768 // walked in a particular order. So [[1, 2], 1, 2] will have one
7769 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7770 DECL_ACCESSORS(nested_site, Object)
7771 DECL_ACCESSORS(pretenure_data, Smi)
7772 DECL_ACCESSORS(pretenure_create_count, Smi)
7773 DECL_ACCESSORS(dependent_code, DependentCode)
7774 DECL_ACCESSORS(weak_next, Object)
7776 inline void Initialize();
7778 // This method is expensive, it should only be called for reporting.
7779 bool IsNestedSite();
7781 // transition_info bitfields, for constructed array transition info.
7782 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7783 class UnusedBits: public BitField<int, 15, 14> {};
7784 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7786 // Bitfields for pretenure_data
7787 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7788 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7789 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7790 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7792 // Increments the mementos found counter and returns true when the first
7793 // memento was found for a given allocation site.
7794 inline bool IncrementMementoFoundCount();
7796 inline void IncrementMementoCreateCount();
7798 PretenureFlag GetPretenureMode();
7800 void ResetPretenureDecision();
7802 inline PretenureDecision pretenure_decision();
7803 inline void set_pretenure_decision(PretenureDecision decision);
7805 inline bool deopt_dependent_code();
7806 inline void set_deopt_dependent_code(bool deopt);
7808 inline int memento_found_count();
7809 inline void set_memento_found_count(int count);
7811 inline int memento_create_count();
7812 inline void set_memento_create_count(int count);
7814 // The pretenuring decision is made during gc, and the zombie state allows
7815 // us to recognize when an allocation site is just being kept alive because
7816 // a later traversal of new space may discover AllocationMementos that point
7817 // to this AllocationSite.
7818 inline bool IsZombie();
7820 inline bool IsMaybeTenure();
7822 inline void MarkZombie();
7824 inline bool MakePretenureDecision(PretenureDecision current_decision,
7826 bool maximum_size_scavenge);
7828 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7830 inline ElementsKind GetElementsKind();
7831 inline void SetElementsKind(ElementsKind kind);
7833 inline bool CanInlineCall();
7834 inline void SetDoNotInlineCall();
7836 inline bool SitePointsToLiteral();
7838 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7839 ElementsKind to_kind);
7841 DECLARE_PRINTER(AllocationSite)
7842 DECLARE_VERIFIER(AllocationSite)
7844 DECLARE_CAST(AllocationSite)
7845 static inline AllocationSiteMode GetMode(
7846 ElementsKind boilerplate_elements_kind);
7847 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7848 static inline bool CanTrack(InstanceType type);
7850 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7851 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7852 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7853 static const int kPretenureCreateCountOffset =
7854 kPretenureDataOffset + kPointerSize;
7855 static const int kDependentCodeOffset =
7856 kPretenureCreateCountOffset + kPointerSize;
7857 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7858 static const int kSize = kWeakNextOffset + kPointerSize;
7860 // During mark compact we need to take special care for the dependent code
7862 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7863 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7865 // For other visitors, use the fixed body descriptor below.
7866 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7867 kDependentCodeOffset + kPointerSize,
7868 kSize> BodyDescriptor;
7871 inline bool PretenuringDecisionMade();
7873 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7877 class AllocationMemento: public Struct {
7879 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7880 static const int kSize = kAllocationSiteOffset + kPointerSize;
7882 DECL_ACCESSORS(allocation_site, Object)
7884 inline bool IsValid();
7885 inline AllocationSite* GetAllocationSite();
7887 DECLARE_PRINTER(AllocationMemento)
7888 DECLARE_VERIFIER(AllocationMemento)
7890 DECLARE_CAST(AllocationMemento)
7893 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7897 // Representation of a slow alias as part of a sloppy arguments objects.
7898 // For fast aliases (if HasSloppyArgumentsElements()):
7899 // - the parameter map contains an index into the context
7900 // - all attributes of the element have default values
7901 // For slow aliases (if HasDictionaryArgumentsElements()):
7902 // - the parameter map contains no fast alias mapping (i.e. the hole)
7903 // - this struct (in the slow backing store) contains an index into the context
7904 // - all attributes are available as part if the property details
7905 class AliasedArgumentsEntry: public Struct {
7907 inline int aliased_context_slot() const;
7908 inline void set_aliased_context_slot(int count);
7910 DECLARE_CAST(AliasedArgumentsEntry)
7912 // Dispatched behavior.
7913 DECLARE_PRINTER(AliasedArgumentsEntry)
7914 DECLARE_VERIFIER(AliasedArgumentsEntry)
7916 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7917 static const int kSize = kAliasedContextSlot + kPointerSize;
7920 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7924 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7925 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7928 class StringHasher {
7930 explicit inline StringHasher(int length, uint32_t seed);
7932 template <typename schar>
7933 static inline uint32_t HashSequentialString(const schar* chars,
7937 // Reads all the data, even for long strings and computes the utf16 length.
7938 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7940 int* utf16_length_out);
7942 // Calculated hash value for a string consisting of 1 to
7943 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7944 // value is represented decimal value.
7945 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7947 // No string is allowed to have a hash of zero. That value is reserved
7948 // for internal properties. If the hash calculation yields zero then we
7950 static const int kZeroHash = 27;
7952 // Reusable parts of the hashing algorithm.
7953 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7954 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7955 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7956 const uc16* chars, int length));
7957 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
7962 // Returns the value to store in the hash field of a string with
7963 // the given length and contents.
7964 uint32_t GetHashField();
7965 // Returns true if the hash of this string can be computed without
7966 // looking at the contents.
7967 inline bool has_trivial_hash();
7968 // Adds a block of characters to the hash.
7969 template<typename Char>
7970 inline void AddCharacters(const Char* chars, int len);
7973 // Add a character to the hash.
7974 inline void AddCharacter(uint16_t c);
7975 // Update index. Returns true if string is still an index.
7976 inline bool UpdateIndex(uint16_t c);
7979 uint32_t raw_running_hash_;
7980 uint32_t array_index_;
7981 bool is_array_index_;
7982 bool is_first_char_;
7983 DISALLOW_COPY_AND_ASSIGN(StringHasher);
7987 class IteratingStringHasher : public StringHasher {
7989 static inline uint32_t Hash(String* string, uint32_t seed);
7990 inline void VisitOneByteString(const uint8_t* chars, int length);
7991 inline void VisitTwoByteString(const uint16_t* chars, int length);
7994 inline IteratingStringHasher(int len, uint32_t seed);
7995 void VisitConsString(ConsString* cons_string);
7996 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8000 // The characteristics of a string are stored in its map. Retrieving these
8001 // few bits of information is moderately expensive, involving two memory
8002 // loads where the second is dependent on the first. To improve efficiency
8003 // the shape of the string is given its own class so that it can be retrieved
8004 // once and used for several string operations. A StringShape is small enough
8005 // to be passed by value and is immutable, but be aware that flattening a
8006 // string can potentially alter its shape. Also be aware that a GC caused by
8007 // something else can alter the shape of a string due to ConsString
8008 // shortcutting. Keeping these restrictions in mind has proven to be error-
8009 // prone and so we no longer put StringShapes in variables unless there is a
8010 // concrete performance benefit at that particular point in the code.
8011 class StringShape BASE_EMBEDDED {
8013 inline explicit StringShape(const String* s);
8014 inline explicit StringShape(Map* s);
8015 inline explicit StringShape(InstanceType t);
8016 inline bool IsSequential();
8017 inline bool IsExternal();
8018 inline bool IsCons();
8019 inline bool IsSliced();
8020 inline bool IsIndirect();
8021 inline bool IsExternalOneByte();
8022 inline bool IsExternalTwoByte();
8023 inline bool IsSequentialOneByte();
8024 inline bool IsSequentialTwoByte();
8025 inline bool IsInternalized();
8026 inline StringRepresentationTag representation_tag();
8027 inline uint32_t encoding_tag();
8028 inline uint32_t full_representation_tag();
8029 inline uint32_t size_tag();
8031 inline uint32_t type() { return type_; }
8032 inline void invalidate() { valid_ = false; }
8033 inline bool valid() { return valid_; }
8035 inline void invalidate() { }
8041 inline void set_valid() { valid_ = true; }
8044 inline void set_valid() { }
8049 // The Name abstract class captures anything that can be used as a property
8050 // name, i.e., strings and symbols. All names store a hash value.
8051 class Name: public HeapObject {
8053 // Get and set the hash field of the name.
8054 inline uint32_t hash_field();
8055 inline void set_hash_field(uint32_t value);
8057 // Tells whether the hash code has been computed.
8058 inline bool HasHashCode();
8060 // Returns a hash value used for the property table
8061 inline uint32_t Hash();
8063 // Equality operations.
8064 inline bool Equals(Name* other);
8065 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8068 inline bool AsArrayIndex(uint32_t* index);
8070 // If the name is private, it can only name own properties.
8071 inline bool IsPrivate();
8073 // If the name is a non-flat string, this method returns a flat version of the
8074 // string. Otherwise it'll just return the input.
8075 static inline Handle<Name> Flatten(Handle<Name> name,
8076 PretenureFlag pretenure = NOT_TENURED);
8080 DECLARE_PRINTER(Name)
8082 void NameShortPrint();
8083 int NameShortPrint(Vector<char> str);
8086 // Layout description.
8087 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8088 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8089 static const int kHashFieldOffset = kHashFieldSlot;
8091 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8093 static const int kSize = kHashFieldSlot + kPointerSize;
8095 // Mask constant for checking if a name has a computed hash code
8096 // and if it is a string that is an array index. The least significant bit
8097 // indicates whether a hash code has been computed. If the hash code has
8098 // been computed the 2nd bit tells whether the string can be used as an
8100 static const int kHashNotComputedMask = 1;
8101 static const int kIsNotArrayIndexMask = 1 << 1;
8102 static const int kNofHashBitFields = 2;
8104 // Shift constant retrieving hash code from hash field.
8105 static const int kHashShift = kNofHashBitFields;
8107 // Only these bits are relevant in the hash, since the top two are shifted
8109 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8111 // Array index strings this short can keep their index in the hash field.
8112 static const int kMaxCachedArrayIndexLength = 7;
8114 // For strings which are array indexes the hash value has the string length
8115 // mixed into the hash, mainly to avoid a hash value of zero which would be
8116 // the case for the string '0'. 24 bits are used for the array index value.
8117 static const int kArrayIndexValueBits = 24;
8118 static const int kArrayIndexLengthBits =
8119 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8121 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8123 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8124 kArrayIndexValueBits> {}; // NOLINT
8125 class ArrayIndexLengthBits : public BitField<unsigned int,
8126 kNofHashBitFields + kArrayIndexValueBits,
8127 kArrayIndexLengthBits> {}; // NOLINT
8129 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8130 // could use a mask to test if the length of string is less than or equal to
8131 // kMaxCachedArrayIndexLength.
8132 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8134 static const unsigned int kContainsCachedArrayIndexMask =
8135 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8136 << ArrayIndexLengthBits::kShift) |
8137 kIsNotArrayIndexMask;
8139 // Value of empty hash field indicating that the hash is not computed.
8140 static const int kEmptyHashField =
8141 kIsNotArrayIndexMask | kHashNotComputedMask;
8144 static inline bool IsHashFieldComputed(uint32_t field);
8147 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8152 class Symbol: public Name {
8154 // [name]: The print name of a symbol, or undefined if none.
8155 DECL_ACCESSORS(name, Object)
8157 DECL_ACCESSORS(flags, Smi)
8159 // [is_private]: Whether this is a private symbol. Private symbols can only
8160 // be used to designate own properties of objects.
8161 DECL_BOOLEAN_ACCESSORS(is_private)
8163 DECLARE_CAST(Symbol)
8165 // Dispatched behavior.
8166 DECLARE_PRINTER(Symbol)
8167 DECLARE_VERIFIER(Symbol)
8169 // Layout description.
8170 static const int kNameOffset = Name::kSize;
8171 static const int kFlagsOffset = kNameOffset + kPointerSize;
8172 static const int kSize = kFlagsOffset + kPointerSize;
8174 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8176 void SymbolShortPrint(std::ostream& os);
8179 static const int kPrivateBit = 0;
8181 const char* PrivateSymbolToName() const;
8184 friend class Name; // For PrivateSymbolToName.
8187 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8193 // The String abstract class captures JavaScript string values:
8196 // 4.3.16 String Value
8197 // A string value is a member of the type String and is a finite
8198 // ordered sequence of zero or more 16-bit unsigned integer values.
8200 // All string values have a length field.
8201 class String: public Name {
8203 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8205 // Array index strings this short can keep their index in the hash field.
8206 static const int kMaxCachedArrayIndexLength = 7;
8208 // For strings which are array indexes the hash value has the string length
8209 // mixed into the hash, mainly to avoid a hash value of zero which would be
8210 // the case for the string '0'. 24 bits are used for the array index value.
8211 static const int kArrayIndexValueBits = 24;
8212 static const int kArrayIndexLengthBits =
8213 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8215 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8217 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8218 kArrayIndexValueBits> {}; // NOLINT
8219 class ArrayIndexLengthBits : public BitField<unsigned int,
8220 kNofHashBitFields + kArrayIndexValueBits,
8221 kArrayIndexLengthBits> {}; // NOLINT
8223 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8224 // could use a mask to test if the length of string is less than or equal to
8225 // kMaxCachedArrayIndexLength.
8226 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8228 static const unsigned int kContainsCachedArrayIndexMask =
8229 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8230 << ArrayIndexLengthBits::kShift) |
8231 kIsNotArrayIndexMask;
8233 class SubStringRange {
8235 explicit inline SubStringRange(String* string, int first = 0,
8238 inline iterator begin();
8239 inline iterator end();
8247 // Representation of the flat content of a String.
8248 // A non-flat string doesn't have flat content.
8249 // A flat string has content that's encoded as a sequence of either
8250 // one-byte chars or two-byte UC16.
8251 // Returned by String::GetFlatContent().
8254 // Returns true if the string is flat and this structure contains content.
8255 bool IsFlat() { return state_ != NON_FLAT; }
8256 // Returns true if the structure contains one-byte content.
8257 bool IsOneByte() { return state_ == ONE_BYTE; }
8258 // Returns true if the structure contains two-byte content.
8259 bool IsTwoByte() { return state_ == TWO_BYTE; }
8261 // Return the one byte content of the string. Only use if IsOneByte()
8263 Vector<const uint8_t> ToOneByteVector() {
8264 DCHECK_EQ(ONE_BYTE, state_);
8265 return Vector<const uint8_t>(onebyte_start, length_);
8267 // Return the two-byte content of the string. Only use if IsTwoByte()
8269 Vector<const uc16> ToUC16Vector() {
8270 DCHECK_EQ(TWO_BYTE, state_);
8271 return Vector<const uc16>(twobyte_start, length_);
8275 DCHECK(i < length_);
8276 DCHECK(state_ != NON_FLAT);
8277 if (state_ == ONE_BYTE) return onebyte_start[i];
8278 return twobyte_start[i];
8281 bool UsesSameString(const FlatContent& other) const {
8282 return onebyte_start == other.onebyte_start;
8286 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8288 // Constructors only used by String::GetFlatContent().
8289 explicit FlatContent(const uint8_t* start, int length)
8290 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8291 explicit FlatContent(const uc16* start, int length)
8292 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8293 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8296 const uint8_t* onebyte_start;
8297 const uc16* twobyte_start;
8302 friend class String;
8303 friend class IterableSubString;
8306 template <typename Char>
8307 INLINE(Vector<const Char> GetCharVector());
8309 // Get and set the length of the string.
8310 inline int length() const;
8311 inline void set_length(int value);
8313 // Get and set the length of the string using acquire loads and release
8315 inline int synchronized_length() const;
8316 inline void synchronized_set_length(int value);
8318 // Returns whether this string has only one-byte chars, i.e. all of them can
8319 // be one-byte encoded. This might be the case even if the string is
8320 // two-byte. Such strings may appear when the embedder prefers
8321 // two-byte external representations even for one-byte data.
8322 inline bool IsOneByteRepresentation() const;
8323 inline bool IsTwoByteRepresentation() const;
8325 // Cons and slices have an encoding flag that may not represent the actual
8326 // encoding of the underlying string. This is taken into account here.
8327 // Requires: this->IsFlat()
8328 inline bool IsOneByteRepresentationUnderneath();
8329 inline bool IsTwoByteRepresentationUnderneath();
8331 // NOTE: this should be considered only a hint. False negatives are
8333 inline bool HasOnlyOneByteChars();
8335 // Get and set individual two byte chars in the string.
8336 inline void Set(int index, uint16_t value);
8337 // Get individual two byte char in the string. Repeated calls
8338 // to this method are not efficient unless the string is flat.
8339 INLINE(uint16_t Get(int index));
8341 // Flattens the string. Checks first inline to see if it is
8342 // necessary. Does nothing if the string is not a cons string.
8343 // Flattening allocates a sequential string with the same data as
8344 // the given string and mutates the cons string to a degenerate
8345 // form, where the first component is the new sequential string and
8346 // the second component is the empty string. If allocation fails,
8347 // this function returns a failure. If flattening succeeds, this
8348 // function returns the sequential string that is now the first
8349 // component of the cons string.
8351 // Degenerate cons strings are handled specially by the garbage
8352 // collector (see IsShortcutCandidate).
8354 static inline Handle<String> Flatten(Handle<String> string,
8355 PretenureFlag pretenure = NOT_TENURED);
8357 // Tries to return the content of a flat string as a structure holding either
8358 // a flat vector of char or of uc16.
8359 // If the string isn't flat, and therefore doesn't have flat content, the
8360 // returned structure will report so, and can't provide a vector of either
8362 FlatContent GetFlatContent();
8364 // Returns the parent of a sliced string or first part of a flat cons string.
8365 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8366 inline String* GetUnderlying();
8368 // String equality operations.
8369 inline bool Equals(String* other);
8370 inline static bool Equals(Handle<String> one, Handle<String> two);
8371 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8372 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8373 bool IsTwoByteEqualTo(Vector<const uc16> str);
8375 // Return a UTF8 representation of the string. The string is null
8376 // terminated but may optionally contain nulls. Length is returned
8377 // in length_output if length_output is not a null pointer The string
8378 // should be nearly flat, otherwise the performance of this method may
8379 // be very slow (quadratic in the length). Setting robustness_flag to
8380 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8381 // handles unexpected data without causing assert failures and it does not
8382 // do any heap allocations. This is useful when printing stack traces.
8383 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8384 RobustnessFlag robustness_flag,
8385 int offset, int length,
8386 int* length_output = 0);
8387 base::SmartArrayPointer<char> ToCString(
8388 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8389 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8390 int* length_output = 0);
8392 // Return a 16 bit Unicode representation of the string.
8393 // The string should be nearly flat, otherwise the performance of
8394 // of this method may be very bad. Setting robustness_flag to
8395 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8396 // handles unexpected data without causing assert failures and it does not
8397 // do any heap allocations. This is useful when printing stack traces.
8398 base::SmartArrayPointer<uc16> ToWideCString(
8399 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8401 bool ComputeArrayIndex(uint32_t* index);
8404 bool MakeExternal(v8::String::ExternalStringResource* resource);
8405 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8408 inline bool AsArrayIndex(uint32_t* index);
8410 DECLARE_CAST(String)
8412 void PrintOn(FILE* out);
8414 // For use during stack traces. Performs rudimentary sanity check.
8417 // Dispatched behavior.
8418 void StringShortPrint(StringStream* accumulator);
8419 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8420 #if defined(DEBUG) || defined(OBJECT_PRINT)
8421 char* ToAsciiArray();
8423 DECLARE_PRINTER(String)
8424 DECLARE_VERIFIER(String)
8426 inline bool IsFlat();
8428 // Layout description.
8429 static const int kLengthOffset = Name::kSize;
8430 static const int kSize = kLengthOffset + kPointerSize;
8432 // Maximum number of characters to consider when trying to convert a string
8433 // value into an array index.
8434 static const int kMaxArrayIndexSize = 10;
8435 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8438 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8439 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8440 static const int kMaxUtf16CodeUnit = 0xffff;
8441 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8443 // Value of hash field containing computed hash equal to zero.
8444 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8446 // Maximal string length.
8447 static const int kMaxLength = (1 << 28) - 16;
8449 // Max length for computing hash. For strings longer than this limit the
8450 // string length is used as the hash value.
8451 static const int kMaxHashCalcLength = 16383;
8453 // Limit for truncation in short printing.
8454 static const int kMaxShortPrintLength = 1024;
8456 // Support for regular expressions.
8457 const uc16* GetTwoByteData(unsigned start);
8459 // Helper function for flattening strings.
8460 template <typename sinkchar>
8461 static void WriteToFlat(String* source,
8466 // The return value may point to the first aligned word containing the first
8467 // non-one-byte character, rather than directly to the non-one-byte character.
8468 // If the return value is >= the passed length, the entire string was
8470 static inline int NonAsciiStart(const char* chars, int length) {
8471 const char* start = chars;
8472 const char* limit = chars + length;
8474 if (length >= kIntptrSize) {
8475 // Check unaligned bytes.
8476 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8477 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8478 return static_cast<int>(chars - start);
8482 // Check aligned words.
8483 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8484 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8485 while (chars + sizeof(uintptr_t) <= limit) {
8486 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8487 return static_cast<int>(chars - start);
8489 chars += sizeof(uintptr_t);
8492 // Check remaining unaligned bytes.
8493 while (chars < limit) {
8494 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8495 return static_cast<int>(chars - start);
8500 return static_cast<int>(chars - start);
8503 static inline bool IsAscii(const char* chars, int length) {
8504 return NonAsciiStart(chars, length) >= length;
8507 static inline bool IsAscii(const uint8_t* chars, int length) {
8509 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8512 static inline int NonOneByteStart(const uc16* chars, int length) {
8513 const uc16* limit = chars + length;
8514 const uc16* start = chars;
8515 while (chars < limit) {
8516 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8519 return static_cast<int>(chars - start);
8522 static inline bool IsOneByte(const uc16* chars, int length) {
8523 return NonOneByteStart(chars, length) >= length;
8526 template<class Visitor>
8527 static inline ConsString* VisitFlat(Visitor* visitor,
8531 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8532 bool include_ending_line);
8534 // Use the hash field to forward to the canonical internalized string
8535 // when deserializing an internalized string.
8536 inline void SetForwardedInternalizedString(String* string);
8537 inline String* GetForwardedInternalizedString();
8541 friend class StringTableInsertionKey;
8543 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8544 PretenureFlag tenure);
8546 // Slow case of String::Equals. This implementation works on any strings
8547 // but it is most efficient on strings that are almost flat.
8548 bool SlowEquals(String* other);
8550 static bool SlowEquals(Handle<String> one, Handle<String> two);
8552 // Slow case of AsArrayIndex.
8553 bool SlowAsArrayIndex(uint32_t* index);
8555 // Compute and set the hash code.
8556 uint32_t ComputeAndSetHash();
8558 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8562 // The SeqString abstract class captures sequential string values.
8563 class SeqString: public String {
8565 DECLARE_CAST(SeqString)
8567 // Layout description.
8568 static const int kHeaderSize = String::kSize;
8570 // Truncate the string in-place if possible and return the result.
8571 // In case of new_length == 0, the empty string is returned without
8572 // truncating the original string.
8573 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8576 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8580 // The OneByteString class captures sequential one-byte string objects.
8581 // Each character in the OneByteString is an one-byte character.
8582 class SeqOneByteString: public SeqString {
8584 static const bool kHasOneByteEncoding = true;
8586 // Dispatched behavior.
8587 inline uint16_t SeqOneByteStringGet(int index);
8588 inline void SeqOneByteStringSet(int index, uint16_t value);
8590 // Get the address of the characters in this string.
8591 inline Address GetCharsAddress();
8593 inline uint8_t* GetChars();
8595 DECLARE_CAST(SeqOneByteString)
8597 // Garbage collection support. This method is called by the
8598 // garbage collector to compute the actual size of an OneByteString
8600 inline int SeqOneByteStringSize(InstanceType instance_type);
8602 // Computes the size for an OneByteString instance of a given length.
8603 static int SizeFor(int length) {
8604 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8607 // Maximal memory usage for a single sequential one-byte string.
8608 static const int kMaxSize = 512 * MB - 1;
8609 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8612 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8616 // The TwoByteString class captures sequential unicode string objects.
8617 // Each character in the TwoByteString is a two-byte uint16_t.
8618 class SeqTwoByteString: public SeqString {
8620 static const bool kHasOneByteEncoding = false;
8622 // Dispatched behavior.
8623 inline uint16_t SeqTwoByteStringGet(int index);
8624 inline void SeqTwoByteStringSet(int index, uint16_t value);
8626 // Get the address of the characters in this string.
8627 inline Address GetCharsAddress();
8629 inline uc16* GetChars();
8632 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8634 DECLARE_CAST(SeqTwoByteString)
8636 // Garbage collection support. This method is called by the
8637 // garbage collector to compute the actual size of a TwoByteString
8639 inline int SeqTwoByteStringSize(InstanceType instance_type);
8641 // Computes the size for a TwoByteString instance of a given length.
8642 static int SizeFor(int length) {
8643 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8646 // Maximal memory usage for a single sequential two-byte string.
8647 static const int kMaxSize = 512 * MB - 1;
8648 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8649 String::kMaxLength);
8652 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8656 // The ConsString class describes string values built by using the
8657 // addition operator on strings. A ConsString is a pair where the
8658 // first and second components are pointers to other string values.
8659 // One or both components of a ConsString can be pointers to other
8660 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8661 // are non-ConsString string values. The string value represented by
8662 // a ConsString can be obtained by concatenating the leaf string
8663 // values in a left-to-right depth-first traversal of the tree.
8664 class ConsString: public String {
8666 // First string of the cons cell.
8667 inline String* first();
8668 // Doesn't check that the result is a string, even in debug mode. This is
8669 // useful during GC where the mark bits confuse the checks.
8670 inline Object* unchecked_first();
8671 inline void set_first(String* first,
8672 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8674 // Second string of the cons cell.
8675 inline String* second();
8676 // Doesn't check that the result is a string, even in debug mode. This is
8677 // useful during GC where the mark bits confuse the checks.
8678 inline Object* unchecked_second();
8679 inline void set_second(String* second,
8680 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8682 // Dispatched behavior.
8683 uint16_t ConsStringGet(int index);
8685 DECLARE_CAST(ConsString)
8687 // Layout description.
8688 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8689 static const int kSecondOffset = kFirstOffset + kPointerSize;
8690 static const int kSize = kSecondOffset + kPointerSize;
8692 // Minimum length for a cons string.
8693 static const int kMinLength = 13;
8695 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8698 DECLARE_VERIFIER(ConsString)
8701 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8705 // The Sliced String class describes strings that are substrings of another
8706 // sequential string. The motivation is to save time and memory when creating
8707 // a substring. A Sliced String is described as a pointer to the parent,
8708 // the offset from the start of the parent string and the length. Using
8709 // a Sliced String therefore requires unpacking of the parent string and
8710 // adding the offset to the start address. A substring of a Sliced String
8711 // are not nested since the double indirection is simplified when creating
8712 // such a substring.
8713 // Currently missing features are:
8714 // - handling externalized parent strings
8715 // - external strings as parent
8716 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8717 class SlicedString: public String {
8719 inline String* parent();
8720 inline void set_parent(String* parent,
8721 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8722 inline int offset() const;
8723 inline void set_offset(int offset);
8725 // Dispatched behavior.
8726 uint16_t SlicedStringGet(int index);
8728 DECLARE_CAST(SlicedString)
8730 // Layout description.
8731 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8732 static const int kOffsetOffset = kParentOffset + kPointerSize;
8733 static const int kSize = kOffsetOffset + kPointerSize;
8735 // Minimum length for a sliced string.
8736 static const int kMinLength = 13;
8738 typedef FixedBodyDescriptor<kParentOffset,
8739 kOffsetOffset + kPointerSize, kSize>
8742 DECLARE_VERIFIER(SlicedString)
8745 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8749 // The ExternalString class describes string values that are backed by
8750 // a string resource that lies outside the V8 heap. ExternalStrings
8751 // consist of the length field common to all strings, a pointer to the
8752 // external resource. It is important to ensure (externally) that the
8753 // resource is not deallocated while the ExternalString is live in the
8756 // The API expects that all ExternalStrings are created through the
8757 // API. Therefore, ExternalStrings should not be used internally.
8758 class ExternalString: public String {
8760 DECLARE_CAST(ExternalString)
8762 // Layout description.
8763 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8764 static const int kShortSize = kResourceOffset + kPointerSize;
8765 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8766 static const int kSize = kResourceDataOffset + kPointerSize;
8768 static const int kMaxShortLength =
8769 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8771 // Return whether external string is short (data pointer is not cached).
8772 inline bool is_short();
8774 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8777 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8781 // The ExternalOneByteString class is an external string backed by an
8783 class ExternalOneByteString : public ExternalString {
8785 static const bool kHasOneByteEncoding = true;
8787 typedef v8::String::ExternalOneByteStringResource Resource;
8789 // The underlying resource.
8790 inline const Resource* resource();
8791 inline void set_resource(const Resource* buffer);
8793 // Update the pointer cache to the external character array.
8794 // The cached pointer is always valid, as the external character array does =
8795 // not move during lifetime. Deserialization is the only exception, after
8796 // which the pointer cache has to be refreshed.
8797 inline void update_data_cache();
8799 inline const uint8_t* GetChars();
8801 // Dispatched behavior.
8802 inline uint16_t ExternalOneByteStringGet(int index);
8804 DECLARE_CAST(ExternalOneByteString)
8806 // Garbage collection support.
8807 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8809 template <typename StaticVisitor>
8810 inline void ExternalOneByteStringIterateBody();
8813 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8817 // The ExternalTwoByteString class is an external string backed by a UTF-16
8819 class ExternalTwoByteString: public ExternalString {
8821 static const bool kHasOneByteEncoding = false;
8823 typedef v8::String::ExternalStringResource Resource;
8825 // The underlying string resource.
8826 inline const Resource* resource();
8827 inline void set_resource(const Resource* buffer);
8829 // Update the pointer cache to the external character array.
8830 // The cached pointer is always valid, as the external character array does =
8831 // not move during lifetime. Deserialization is the only exception, after
8832 // which the pointer cache has to be refreshed.
8833 inline void update_data_cache();
8835 inline const uint16_t* GetChars();
8837 // Dispatched behavior.
8838 inline uint16_t ExternalTwoByteStringGet(int index);
8841 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8843 DECLARE_CAST(ExternalTwoByteString)
8845 // Garbage collection support.
8846 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8848 template<typename StaticVisitor>
8849 inline void ExternalTwoByteStringIterateBody();
8852 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8856 // Utility superclass for stack-allocated objects that must be updated
8857 // on gc. It provides two ways for the gc to update instances, either
8858 // iterating or updating after gc.
8859 class Relocatable BASE_EMBEDDED {
8861 explicit inline Relocatable(Isolate* isolate);
8862 inline virtual ~Relocatable();
8863 virtual void IterateInstance(ObjectVisitor* v) { }
8864 virtual void PostGarbageCollection() { }
8866 static void PostGarbageCollectionProcessing(Isolate* isolate);
8867 static int ArchiveSpacePerThread();
8868 static char* ArchiveState(Isolate* isolate, char* to);
8869 static char* RestoreState(Isolate* isolate, char* from);
8870 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8871 static void Iterate(ObjectVisitor* v, Relocatable* top);
8872 static char* Iterate(ObjectVisitor* v, char* t);
8880 // A flat string reader provides random access to the contents of a
8881 // string independent of the character width of the string. The handle
8882 // must be valid as long as the reader is being used.
8883 class FlatStringReader : public Relocatable {
8885 FlatStringReader(Isolate* isolate, Handle<String> str);
8886 FlatStringReader(Isolate* isolate, Vector<const char> input);
8887 void PostGarbageCollection();
8888 inline uc32 Get(int index);
8889 template <typename Char>
8890 inline Char Get(int index);
8891 int length() { return length_; }
8900 // This maintains an off-stack representation of the stack frames required
8901 // to traverse a ConsString, allowing an entirely iterative and restartable
8902 // traversal of the entire string
8903 class ConsStringIterator {
8905 inline ConsStringIterator() {}
8906 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8907 Reset(cons_string, offset);
8909 inline void Reset(ConsString* cons_string, int offset = 0) {
8911 // Next will always return NULL.
8912 if (cons_string == NULL) return;
8913 Initialize(cons_string, offset);
8915 // Returns NULL when complete.
8916 inline String* Next(int* offset_out) {
8918 if (depth_ == 0) return NULL;
8919 return Continue(offset_out);
8923 static const int kStackSize = 32;
8924 // Use a mask instead of doing modulo operations for stack wrapping.
8925 static const int kDepthMask = kStackSize-1;
8926 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8927 static inline int OffsetForDepth(int depth);
8929 inline void PushLeft(ConsString* string);
8930 inline void PushRight(ConsString* string);
8931 inline void AdjustMaximumDepth();
8933 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8934 void Initialize(ConsString* cons_string, int offset);
8935 String* Continue(int* offset_out);
8936 String* NextLeaf(bool* blew_stack);
8937 String* Search(int* offset_out);
8939 // Stack must always contain only frames for which right traversal
8940 // has not yet been performed.
8941 ConsString* frames_[kStackSize];
8946 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8950 class StringCharacterStream {
8952 inline StringCharacterStream(String* string,
8954 inline uint16_t GetNext();
8955 inline bool HasMore();
8956 inline void Reset(String* string, int offset = 0);
8957 inline void VisitOneByteString(const uint8_t* chars, int length);
8958 inline void VisitTwoByteString(const uint16_t* chars, int length);
8961 ConsStringIterator iter_;
8964 const uint8_t* buffer8_;
8965 const uint16_t* buffer16_;
8967 const uint8_t* end_;
8968 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
8972 template <typename T>
8973 class VectorIterator {
8975 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
8976 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
8977 T GetNext() { return data_[index_++]; }
8978 bool has_more() { return index_ < data_.length(); }
8980 Vector<const T> data_;
8985 // The Oddball describes objects null, undefined, true, and false.
8986 class Oddball: public HeapObject {
8988 // [to_string]: Cached to_string computed at startup.
8989 DECL_ACCESSORS(to_string, String)
8991 // [to_number]: Cached to_number computed at startup.
8992 DECL_ACCESSORS(to_number, Object)
8994 // [typeof]: Cached type_of computed at startup.
8995 DECL_ACCESSORS(type_of, String)
8997 inline byte kind() const;
8998 inline void set_kind(byte kind);
9000 DECLARE_CAST(Oddball)
9002 // Dispatched behavior.
9003 DECLARE_VERIFIER(Oddball)
9005 // Initialize the fields.
9006 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
9007 const char* to_string, Handle<Object> to_number,
9008 const char* type_of, byte kind);
9010 // Layout description.
9011 static const int kToStringOffset = HeapObject::kHeaderSize;
9012 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9013 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9014 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9015 static const int kSize = kKindOffset + kPointerSize;
9017 static const byte kFalse = 0;
9018 static const byte kTrue = 1;
9019 static const byte kNotBooleanMask = ~1;
9020 static const byte kTheHole = 2;
9021 static const byte kNull = 3;
9022 static const byte kArgumentMarker = 4;
9023 static const byte kUndefined = 5;
9024 static const byte kUninitialized = 6;
9025 static const byte kOther = 7;
9026 static const byte kException = 8;
9028 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9029 kSize> BodyDescriptor;
9031 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9032 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9033 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9036 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9040 class Cell: public HeapObject {
9042 // [value]: value of the cell.
9043 DECL_ACCESSORS(value, Object)
9047 static inline Cell* FromValueAddress(Address value) {
9048 Object* result = FromAddress(value - kValueOffset);
9049 return static_cast<Cell*>(result);
9052 inline Address ValueAddress() {
9053 return address() + kValueOffset;
9056 // Dispatched behavior.
9057 DECLARE_PRINTER(Cell)
9058 DECLARE_VERIFIER(Cell)
9060 // Layout description.
9061 static const int kValueOffset = HeapObject::kHeaderSize;
9062 static const int kSize = kValueOffset + kPointerSize;
9064 typedef FixedBodyDescriptor<kValueOffset,
9065 kValueOffset + kPointerSize,
9066 kSize> BodyDescriptor;
9069 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9073 class PropertyCell : public HeapObject {
9075 // [property_details]: details of the global property.
9076 DECL_ACCESSORS(property_details_raw, Object)
9077 // [value]: value of the global property.
9078 DECL_ACCESSORS(value, Object)
9079 // [dependent_code]: dependent code that depends on the type of the global
9081 DECL_ACCESSORS(dependent_code, DependentCode)
9083 inline PropertyDetails property_details();
9084 inline void set_property_details(PropertyDetails details);
9086 PropertyCellConstantType GetConstantType();
9088 // Computes the new type of the cell's contents for the given value, but
9089 // without actually modifying the details.
9090 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9091 Handle<Object> value,
9092 PropertyDetails details);
9093 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9094 Handle<Object> value, PropertyDetails details);
9096 static Handle<PropertyCell> InvalidateEntry(
9097 Handle<GlobalDictionary> dictionary, int entry);
9099 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9100 Handle<Object> new_value);
9102 DECLARE_CAST(PropertyCell)
9104 // Dispatched behavior.
9105 DECLARE_PRINTER(PropertyCell)
9106 DECLARE_VERIFIER(PropertyCell)
9108 // Layout description.
9109 static const int kDetailsOffset = HeapObject::kHeaderSize;
9110 static const int kValueOffset = kDetailsOffset + kPointerSize;
9111 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9112 static const int kSize = kDependentCodeOffset + kPointerSize;
9114 static const int kPointerFieldsBeginOffset = kValueOffset;
9115 static const int kPointerFieldsEndOffset = kSize;
9117 typedef FixedBodyDescriptor<kValueOffset,
9119 kSize> BodyDescriptor;
9122 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9126 class WeakCell : public HeapObject {
9128 inline Object* value() const;
9130 // This should not be called by anyone except GC.
9131 inline void clear();
9133 // This should not be called by anyone except allocator.
9134 inline void initialize(HeapObject* value);
9136 inline bool cleared() const;
9138 DECL_ACCESSORS(next, Object)
9140 inline void clear_next(Heap* heap);
9142 inline bool next_cleared();
9144 DECLARE_CAST(WeakCell)
9146 DECLARE_PRINTER(WeakCell)
9147 DECLARE_VERIFIER(WeakCell)
9149 // Layout description.
9150 static const int kValueOffset = HeapObject::kHeaderSize;
9151 static const int kNextOffset = kValueOffset + kPointerSize;
9152 static const int kSize = kNextOffset + kPointerSize;
9154 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9157 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9161 // The JSProxy describes EcmaScript Harmony proxies
9162 class JSProxy: public JSReceiver {
9164 // [handler]: The handler property.
9165 DECL_ACCESSORS(handler, Object)
9167 // [hash]: The hash code property (undefined if not initialized yet).
9168 DECL_ACCESSORS(hash, Object)
9170 DECLARE_CAST(JSProxy)
9172 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9173 Handle<JSProxy> proxy,
9174 Handle<Object> receiver,
9177 // If the handler defines an accessor property with a setter, invoke it.
9178 // If it defines an accessor property without a setter, or a data property
9179 // that is read-only, throw. In all these cases set '*done' to true,
9180 // otherwise set it to false.
9182 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9183 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9184 Handle<Object> value, LanguageMode language_mode, bool* done);
9186 MUST_USE_RESULT static Maybe<PropertyAttributes>
9187 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9188 Handle<Object> receiver,
9190 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9191 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9192 Handle<Object> value, LanguageMode language_mode);
9194 // Turn the proxy into an (empty) JSObject.
9195 static void Fix(Handle<JSProxy> proxy);
9197 // Initializes the body after the handler slot.
9198 inline void InitializeBody(int object_size, Object* value);
9200 // Invoke a trap by name. If the trap does not exist on this's handler,
9201 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9202 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9203 Handle<JSProxy> proxy,
9205 Handle<Object> derived_trap,
9207 Handle<Object> args[]);
9209 // Dispatched behavior.
9210 DECLARE_PRINTER(JSProxy)
9211 DECLARE_VERIFIER(JSProxy)
9213 // Layout description. We add padding so that a proxy has the same
9214 // size as a virgin JSObject. This is essential for becoming a JSObject
9216 static const int kHandlerOffset = HeapObject::kHeaderSize;
9217 static const int kHashOffset = kHandlerOffset + kPointerSize;
9218 static const int kPaddingOffset = kHashOffset + kPointerSize;
9219 static const int kSize = JSObject::kHeaderSize;
9220 static const int kHeaderSize = kPaddingOffset;
9221 static const int kPaddingSize = kSize - kPaddingOffset;
9223 STATIC_ASSERT(kPaddingSize >= 0);
9225 typedef FixedBodyDescriptor<kHandlerOffset,
9227 kSize> BodyDescriptor;
9230 friend class JSReceiver;
9232 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9233 Handle<JSProxy> proxy, Handle<Name> name);
9235 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9236 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9238 MUST_USE_RESULT Object* GetIdentityHash();
9240 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9242 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9246 class JSFunctionProxy: public JSProxy {
9248 // [call_trap]: The call trap.
9249 DECL_ACCESSORS(call_trap, Object)
9251 // [construct_trap]: The construct trap.
9252 DECL_ACCESSORS(construct_trap, Object)
9254 DECLARE_CAST(JSFunctionProxy)
9256 // Dispatched behavior.
9257 DECLARE_PRINTER(JSFunctionProxy)
9258 DECLARE_VERIFIER(JSFunctionProxy)
9260 // Layout description.
9261 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9262 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9263 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9264 static const int kSize = JSFunction::kSize;
9265 static const int kPaddingSize = kSize - kPaddingOffset;
9267 STATIC_ASSERT(kPaddingSize >= 0);
9269 typedef FixedBodyDescriptor<kHandlerOffset,
9270 kConstructTrapOffset + kPointerSize,
9271 kSize> BodyDescriptor;
9274 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9278 class JSCollection : public JSObject {
9280 // [table]: the backing hash table
9281 DECL_ACCESSORS(table, Object)
9283 static const int kTableOffset = JSObject::kHeaderSize;
9284 static const int kSize = kTableOffset + kPointerSize;
9287 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9291 // The JSSet describes EcmaScript Harmony sets
9292 class JSSet : public JSCollection {
9296 static void Initialize(Handle<JSSet> set, Isolate* isolate);
9297 static void Clear(Handle<JSSet> set);
9299 // Dispatched behavior.
9300 DECLARE_PRINTER(JSSet)
9301 DECLARE_VERIFIER(JSSet)
9304 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9308 // The JSMap describes EcmaScript Harmony maps
9309 class JSMap : public JSCollection {
9313 static void Initialize(Handle<JSMap> map, Isolate* isolate);
9314 static void Clear(Handle<JSMap> map);
9316 // Dispatched behavior.
9317 DECLARE_PRINTER(JSMap)
9318 DECLARE_VERIFIER(JSMap)
9321 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9325 // OrderedHashTableIterator is an iterator that iterates over the keys and
9326 // values of an OrderedHashTable.
9328 // The iterator has a reference to the underlying OrderedHashTable data,
9329 // [table], as well as the current [index] the iterator is at.
9331 // When the OrderedHashTable is rehashed it adds a reference from the old table
9332 // to the new table as well as storing enough data about the changes so that the
9333 // iterator [index] can be adjusted accordingly.
9335 // When the [Next] result from the iterator is requested, the iterator checks if
9336 // there is a newer table that it needs to transition to.
9337 template<class Derived, class TableType>
9338 class OrderedHashTableIterator: public JSObject {
9340 // [table]: the backing hash table mapping keys to values.
9341 DECL_ACCESSORS(table, Object)
9343 // [index]: The index into the data table.
9344 DECL_ACCESSORS(index, Object)
9346 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9347 DECL_ACCESSORS(kind, Object)
9350 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9353 static const int kTableOffset = JSObject::kHeaderSize;
9354 static const int kIndexOffset = kTableOffset + kPointerSize;
9355 static const int kKindOffset = kIndexOffset + kPointerSize;
9356 static const int kSize = kKindOffset + kPointerSize;
9364 // Whether the iterator has more elements. This needs to be called before
9365 // calling |CurrentKey| and/or |CurrentValue|.
9368 // Move the index forward one.
9370 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9373 // Populates the array with the next key and value and then moves the iterator
9375 // This returns the |kind| or 0 if the iterator is already at the end.
9376 Smi* Next(JSArray* value_array);
9378 // Returns the current key of the iterator. This should only be called when
9379 // |HasMore| returns true.
9380 inline Object* CurrentKey();
9383 // Transitions the iterator to the non obsolete backing store. This is a NOP
9384 // if the [table] is not obsolete.
9387 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9391 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9394 // Dispatched behavior.
9395 DECLARE_PRINTER(JSSetIterator)
9396 DECLARE_VERIFIER(JSSetIterator)
9398 DECLARE_CAST(JSSetIterator)
9400 // Called by |Next| to populate the array. This allows the subclasses to
9401 // populate the array differently.
9402 inline void PopulateValueArray(FixedArray* array);
9405 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9409 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9412 // Dispatched behavior.
9413 DECLARE_PRINTER(JSMapIterator)
9414 DECLARE_VERIFIER(JSMapIterator)
9416 DECLARE_CAST(JSMapIterator)
9418 // Called by |Next| to populate the array. This allows the subclasses to
9419 // populate the array differently.
9420 inline void PopulateValueArray(FixedArray* array);
9423 // Returns the current value of the iterator. This should only be called when
9424 // |HasMore| returns true.
9425 inline Object* CurrentValue();
9427 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9431 // Base class for both JSWeakMap and JSWeakSet
9432 class JSWeakCollection: public JSObject {
9434 // [table]: the backing hash table mapping keys to values.
9435 DECL_ACCESSORS(table, Object)
9437 // [next]: linked list of encountered weak maps during GC.
9438 DECL_ACCESSORS(next, Object)
9440 static void Initialize(Handle<JSWeakCollection> collection, Isolate* isolate);
9441 static void Set(Handle<JSWeakCollection> collection, Handle<Object> key,
9442 Handle<Object> value, int32_t hash);
9443 static bool Delete(Handle<JSWeakCollection> collection, Handle<Object> key,
9446 static const int kTableOffset = JSObject::kHeaderSize;
9447 static const int kNextOffset = kTableOffset + kPointerSize;
9448 static const int kSize = kNextOffset + kPointerSize;
9451 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9455 // The JSWeakMap describes EcmaScript Harmony weak maps
9456 class JSWeakMap: public JSWeakCollection {
9458 DECLARE_CAST(JSWeakMap)
9460 // Dispatched behavior.
9461 DECLARE_PRINTER(JSWeakMap)
9462 DECLARE_VERIFIER(JSWeakMap)
9465 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9469 // The JSWeakSet describes EcmaScript Harmony weak sets
9470 class JSWeakSet: public JSWeakCollection {
9472 DECLARE_CAST(JSWeakSet)
9474 // Dispatched behavior.
9475 DECLARE_PRINTER(JSWeakSet)
9476 DECLARE_VERIFIER(JSWeakSet)
9479 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9483 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9484 enum class SharedFlag { kNotShared, kShared };
9487 class JSArrayBuffer: public JSObject {
9489 // [backing_store]: backing memory for this array
9490 DECL_ACCESSORS(backing_store, void)
9492 // [byte_length]: length in bytes
9493 DECL_ACCESSORS(byte_length, Object)
9495 inline uint32_t bit_field() const;
9496 inline void set_bit_field(uint32_t bits);
9498 inline bool is_external();
9499 inline void set_is_external(bool value);
9501 inline bool is_neuterable();
9502 inline void set_is_neuterable(bool value);
9504 inline bool was_neutered();
9505 inline void set_was_neutered(bool value);
9507 inline bool is_shared();
9508 inline void set_is_shared(bool value);
9510 DECLARE_CAST(JSArrayBuffer)
9514 static void Setup(Handle<JSArrayBuffer> array_buffer, Isolate* isolate,
9515 bool is_external, void* data, size_t allocated_length,
9516 SharedFlag shared = SharedFlag::kNotShared);
9518 static bool SetupAllocatingData(Handle<JSArrayBuffer> array_buffer,
9519 Isolate* isolate, size_t allocated_length,
9520 bool initialize = true,
9521 SharedFlag shared = SharedFlag::kNotShared);
9523 // Dispatched behavior.
9524 DECLARE_PRINTER(JSArrayBuffer)
9525 DECLARE_VERIFIER(JSArrayBuffer)
9527 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9528 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9529 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9530 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9531 static const int kBitFieldOffset = kBitFieldSlot;
9533 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9535 static const int kSize = kBitFieldSlot + kPointerSize;
9537 static const int kSizeWithInternalFields =
9538 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9540 class IsExternal : public BitField<bool, 1, 1> {};
9541 class IsNeuterable : public BitField<bool, 2, 1> {};
9542 class WasNeutered : public BitField<bool, 3, 1> {};
9543 class IsShared : public BitField<bool, 4, 1> {};
9546 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9550 class JSArrayBufferView: public JSObject {
9552 // [buffer]: ArrayBuffer that this typed array views.
9553 DECL_ACCESSORS(buffer, Object)
9555 // [byte_offset]: offset of typed array in bytes.
9556 DECL_ACCESSORS(byte_offset, Object)
9558 // [byte_length]: length of typed array in bytes.
9559 DECL_ACCESSORS(byte_length, Object)
9561 DECLARE_CAST(JSArrayBufferView)
9563 DECLARE_VERIFIER(JSArrayBufferView)
9565 inline bool WasNeutered() const;
9567 static const int kBufferOffset = JSObject::kHeaderSize;
9568 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9569 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9570 static const int kViewSize = kByteLengthOffset + kPointerSize;
9574 DECL_ACCESSORS(raw_byte_offset, Object)
9575 DECL_ACCESSORS(raw_byte_length, Object)
9578 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9582 class JSTypedArray: public JSArrayBufferView {
9584 // [length]: length of typed array in elements.
9585 DECL_ACCESSORS(length, Object)
9586 inline uint32_t length_value() const;
9588 DECLARE_CAST(JSTypedArray)
9590 ExternalArrayType type();
9591 size_t element_size();
9593 Handle<JSArrayBuffer> GetBuffer();
9595 // Dispatched behavior.
9596 DECLARE_PRINTER(JSTypedArray)
9597 DECLARE_VERIFIER(JSTypedArray)
9599 static const int kLengthOffset = kViewSize + kPointerSize;
9600 static const int kSize = kLengthOffset + kPointerSize;
9602 static const int kSizeWithInternalFields =
9603 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9606 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9607 Handle<JSTypedArray> typed_array);
9609 DECL_ACCESSORS(raw_length, Object)
9612 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9616 class JSDataView: public JSArrayBufferView {
9618 DECLARE_CAST(JSDataView)
9620 // Dispatched behavior.
9621 DECLARE_PRINTER(JSDataView)
9622 DECLARE_VERIFIER(JSDataView)
9624 static const int kSize = kViewSize;
9626 static const int kSizeWithInternalFields =
9627 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9630 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9634 // Foreign describes objects pointing from JavaScript to C structures.
9635 class Foreign: public HeapObject {
9637 // [address]: field containing the address.
9638 inline Address foreign_address();
9639 inline void set_foreign_address(Address value);
9641 DECLARE_CAST(Foreign)
9643 // Dispatched behavior.
9644 inline void ForeignIterateBody(ObjectVisitor* v);
9646 template<typename StaticVisitor>
9647 inline void ForeignIterateBody();
9649 // Dispatched behavior.
9650 DECLARE_PRINTER(Foreign)
9651 DECLARE_VERIFIER(Foreign)
9653 // Layout description.
9655 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9656 static const int kSize = kForeignAddressOffset + kPointerSize;
9658 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9661 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9665 // The JSArray describes JavaScript Arrays
9666 // Such an array can be in one of two modes:
9667 // - fast, backing storage is a FixedArray and length <= elements.length();
9668 // Please note: push and pop can be used to grow and shrink the array.
9669 // - slow, backing storage is a HashTable with numbers as keys.
9670 class JSArray: public JSObject {
9672 // [length]: The length property.
9673 DECL_ACCESSORS(length, Object)
9675 // Overload the length setter to skip write barrier when the length
9676 // is set to a smi. This matches the set function on FixedArray.
9677 inline void set_length(Smi* length);
9679 static bool HasReadOnlyLength(Handle<JSArray> array);
9680 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9681 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9683 // Initialize the array with the given capacity. The function may
9684 // fail due to out-of-memory situations, but only if the requested
9685 // capacity is non-zero.
9686 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9688 // If the JSArray has fast elements, and new_length would result in
9689 // normalization, returns true.
9690 bool SetLengthWouldNormalize(uint32_t new_length);
9691 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9693 // Initializes the array to a certain length.
9694 inline bool AllowsSetLength();
9696 static void SetLength(Handle<JSArray> array, uint32_t length);
9697 // Same as above but will also queue splice records if |array| is observed.
9698 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9701 // Set the content of the array to the content of storage.
9702 static inline void SetContent(Handle<JSArray> array,
9703 Handle<FixedArrayBase> storage);
9705 DECLARE_CAST(JSArray)
9707 // Dispatched behavior.
9708 DECLARE_PRINTER(JSArray)
9709 DECLARE_VERIFIER(JSArray)
9711 // Number of element slots to pre-allocate for an empty array.
9712 static const int kPreallocatedArrayElements = 4;
9714 // Layout description.
9715 static const int kLengthOffset = JSObject::kHeaderSize;
9716 static const int kSize = kLengthOffset + kPointerSize;
9719 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9723 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9724 Handle<Map> initial_map);
9727 // JSRegExpResult is just a JSArray with a specific initial map.
9728 // This initial map adds in-object properties for "index" and "input"
9729 // properties, as assigned by RegExp.prototype.exec, which allows
9730 // faster creation of RegExp exec results.
9731 // This class just holds constants used when creating the result.
9732 // After creation the result must be treated as a JSArray in all regards.
9733 class JSRegExpResult: public JSArray {
9735 // Offsets of object fields.
9736 static const int kIndexOffset = JSArray::kSize;
9737 static const int kInputOffset = kIndexOffset + kPointerSize;
9738 static const int kSize = kInputOffset + kPointerSize;
9739 // Indices of in-object properties.
9740 static const int kIndexIndex = 0;
9741 static const int kInputIndex = 1;
9743 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9747 class AccessorInfo: public Struct {
9749 DECL_ACCESSORS(name, Object)
9750 DECL_ACCESSORS(flag, Smi)
9751 DECL_ACCESSORS(expected_receiver_type, Object)
9753 inline bool all_can_read();
9754 inline void set_all_can_read(bool value);
9756 inline bool all_can_write();
9757 inline void set_all_can_write(bool value);
9759 inline bool is_special_data_property();
9760 inline void set_is_special_data_property(bool value);
9762 inline PropertyAttributes property_attributes();
9763 inline void set_property_attributes(PropertyAttributes attributes);
9765 // Checks whether the given receiver is compatible with this accessor.
9766 static bool IsCompatibleReceiverMap(Isolate* isolate,
9767 Handle<AccessorInfo> info,
9769 inline bool IsCompatibleReceiver(Object* receiver);
9771 DECLARE_CAST(AccessorInfo)
9773 // Dispatched behavior.
9774 DECLARE_VERIFIER(AccessorInfo)
9776 // Append all descriptors to the array that are not already there.
9777 // Return number added.
9778 static int AppendUnique(Handle<Object> descriptors,
9779 Handle<FixedArray> array,
9780 int valid_descriptors);
9782 static const int kNameOffset = HeapObject::kHeaderSize;
9783 static const int kFlagOffset = kNameOffset + kPointerSize;
9784 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9785 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9788 inline bool HasExpectedReceiverType();
9790 // Bit positions in flag.
9791 static const int kAllCanReadBit = 0;
9792 static const int kAllCanWriteBit = 1;
9793 static const int kSpecialDataProperty = 2;
9794 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9796 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9800 // An accessor must have a getter, but can have no setter.
9802 // When setting a property, V8 searches accessors in prototypes.
9803 // If an accessor was found and it does not have a setter,
9804 // the request is ignored.
9806 // If the accessor in the prototype has the READ_ONLY property attribute, then
9807 // a new value is added to the derived object when the property is set.
9808 // This shadows the accessor in the prototype.
9809 class ExecutableAccessorInfo: public AccessorInfo {
9811 DECL_ACCESSORS(getter, Object)
9812 DECL_ACCESSORS(setter, Object)
9813 DECL_ACCESSORS(data, Object)
9815 DECLARE_CAST(ExecutableAccessorInfo)
9817 // Dispatched behavior.
9818 DECLARE_PRINTER(ExecutableAccessorInfo)
9819 DECLARE_VERIFIER(ExecutableAccessorInfo)
9821 static const int kGetterOffset = AccessorInfo::kSize;
9822 static const int kSetterOffset = kGetterOffset + kPointerSize;
9823 static const int kDataOffset = kSetterOffset + kPointerSize;
9824 static const int kSize = kDataOffset + kPointerSize;
9826 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9829 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9833 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9834 // accessor can either be
9835 // * a pointer to a JavaScript function or proxy: a real accessor
9836 // * undefined: considered an accessor by the spec, too, strangely enough
9837 // * the hole: an accessor which has not been set
9838 // * a pointer to a map: a transition used to ensure map sharing
9839 class AccessorPair: public Struct {
9841 DECL_ACCESSORS(getter, Object)
9842 DECL_ACCESSORS(setter, Object)
9844 DECLARE_CAST(AccessorPair)
9846 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9848 inline Object* get(AccessorComponent component);
9849 inline void set(AccessorComponent component, Object* value);
9851 // Note: Returns undefined instead in case of a hole.
9852 Object* GetComponent(AccessorComponent component);
9854 // Set both components, skipping arguments which are a JavaScript null.
9855 inline void SetComponents(Object* getter, Object* setter);
9857 inline bool Equals(AccessorPair* pair);
9858 inline bool Equals(Object* getter_value, Object* setter_value);
9860 inline bool ContainsAccessor();
9862 // Dispatched behavior.
9863 DECLARE_PRINTER(AccessorPair)
9864 DECLARE_VERIFIER(AccessorPair)
9866 static const int kGetterOffset = HeapObject::kHeaderSize;
9867 static const int kSetterOffset = kGetterOffset + kPointerSize;
9868 static const int kSize = kSetterOffset + kPointerSize;
9871 // Strangely enough, in addition to functions and harmony proxies, the spec
9872 // requires us to consider undefined as a kind of accessor, too:
9874 // Object.defineProperty(obj, "foo", {get: undefined});
9875 // assertTrue("foo" in obj);
9876 inline bool IsJSAccessor(Object* obj);
9878 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9882 class AccessCheckInfo: public Struct {
9884 DECL_ACCESSORS(named_callback, Object)
9885 DECL_ACCESSORS(indexed_callback, Object)
9886 DECL_ACCESSORS(data, Object)
9888 DECLARE_CAST(AccessCheckInfo)
9890 // Dispatched behavior.
9891 DECLARE_PRINTER(AccessCheckInfo)
9892 DECLARE_VERIFIER(AccessCheckInfo)
9894 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9895 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9896 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9897 static const int kSize = kDataOffset + kPointerSize;
9900 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9904 class InterceptorInfo: public Struct {
9906 DECL_ACCESSORS(getter, Object)
9907 DECL_ACCESSORS(setter, Object)
9908 DECL_ACCESSORS(query, Object)
9909 DECL_ACCESSORS(deleter, Object)
9910 DECL_ACCESSORS(enumerator, Object)
9911 DECL_ACCESSORS(data, Object)
9912 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9913 DECL_BOOLEAN_ACCESSORS(all_can_read)
9914 DECL_BOOLEAN_ACCESSORS(non_masking)
9916 inline int flags() const;
9917 inline void set_flags(int flags);
9919 DECLARE_CAST(InterceptorInfo)
9921 // Dispatched behavior.
9922 DECLARE_PRINTER(InterceptorInfo)
9923 DECLARE_VERIFIER(InterceptorInfo)
9925 static const int kGetterOffset = HeapObject::kHeaderSize;
9926 static const int kSetterOffset = kGetterOffset + kPointerSize;
9927 static const int kQueryOffset = kSetterOffset + kPointerSize;
9928 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9929 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9930 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9931 static const int kFlagsOffset = kDataOffset + kPointerSize;
9932 static const int kSize = kFlagsOffset + kPointerSize;
9934 static const int kCanInterceptSymbolsBit = 0;
9935 static const int kAllCanReadBit = 1;
9936 static const int kNonMasking = 2;
9939 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9943 class CallHandlerInfo: public Struct {
9945 DECL_ACCESSORS(callback, Object)
9946 DECL_ACCESSORS(data, Object)
9948 DECLARE_CAST(CallHandlerInfo)
9950 // Dispatched behavior.
9951 DECLARE_PRINTER(CallHandlerInfo)
9952 DECLARE_VERIFIER(CallHandlerInfo)
9954 static const int kCallbackOffset = HeapObject::kHeaderSize;
9955 static const int kDataOffset = kCallbackOffset + kPointerSize;
9956 static const int kSize = kDataOffset + kPointerSize;
9959 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
9963 class TemplateInfo: public Struct {
9965 DECL_ACCESSORS(tag, Object)
9966 inline int number_of_properties() const;
9967 inline void set_number_of_properties(int value);
9968 DECL_ACCESSORS(property_list, Object)
9969 DECL_ACCESSORS(property_accessors, Object)
9971 DECLARE_VERIFIER(TemplateInfo)
9973 static const int kTagOffset = HeapObject::kHeaderSize;
9974 static const int kNumberOfProperties = kTagOffset + kPointerSize;
9975 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
9976 static const int kPropertyAccessorsOffset =
9977 kPropertyListOffset + kPointerSize;
9978 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
9981 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
9985 class FunctionTemplateInfo: public TemplateInfo {
9987 DECL_ACCESSORS(serial_number, Object)
9988 DECL_ACCESSORS(call_code, Object)
9989 DECL_ACCESSORS(prototype_template, Object)
9990 DECL_ACCESSORS(parent_template, Object)
9991 DECL_ACCESSORS(named_property_handler, Object)
9992 DECL_ACCESSORS(indexed_property_handler, Object)
9993 DECL_ACCESSORS(instance_template, Object)
9994 DECL_ACCESSORS(class_name, Object)
9995 DECL_ACCESSORS(signature, Object)
9996 DECL_ACCESSORS(instance_call_handler, Object)
9997 DECL_ACCESSORS(access_check_info, Object)
9998 DECL_ACCESSORS(flag, Smi)
10000 inline int length() const;
10001 inline void set_length(int value);
10003 // Following properties use flag bits.
10004 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10005 DECL_BOOLEAN_ACCESSORS(undetectable)
10006 // If the bit is set, object instances created by this function
10007 // requires access check.
10008 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10009 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10010 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10011 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10012 DECL_BOOLEAN_ACCESSORS(instantiated)
10013 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10015 DECLARE_CAST(FunctionTemplateInfo)
10017 // Dispatched behavior.
10018 DECLARE_PRINTER(FunctionTemplateInfo)
10019 DECLARE_VERIFIER(FunctionTemplateInfo)
10021 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10022 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10023 static const int kPrototypeTemplateOffset =
10024 kCallCodeOffset + kPointerSize;
10025 static const int kParentTemplateOffset =
10026 kPrototypeTemplateOffset + kPointerSize;
10027 static const int kNamedPropertyHandlerOffset =
10028 kParentTemplateOffset + kPointerSize;
10029 static const int kIndexedPropertyHandlerOffset =
10030 kNamedPropertyHandlerOffset + kPointerSize;
10031 static const int kInstanceTemplateOffset =
10032 kIndexedPropertyHandlerOffset + kPointerSize;
10033 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10034 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10035 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10036 static const int kAccessCheckInfoOffset =
10037 kInstanceCallHandlerOffset + kPointerSize;
10038 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10039 static const int kLengthOffset = kFlagOffset + kPointerSize;
10040 static const int kSize = kLengthOffset + kPointerSize;
10042 // Returns true if |object| is an instance of this function template.
10043 bool IsTemplateFor(Object* object);
10044 bool IsTemplateFor(Map* map);
10046 // Returns the holder JSObject if the function can legally be called with this
10047 // receiver. Returns Heap::null_value() if the call is illegal.
10048 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10051 // Bit position in the flag, from least significant bit position.
10052 static const int kHiddenPrototypeBit = 0;
10053 static const int kUndetectableBit = 1;
10054 static const int kNeedsAccessCheckBit = 2;
10055 static const int kReadOnlyPrototypeBit = 3;
10056 static const int kRemovePrototypeBit = 4;
10057 static const int kDoNotCacheBit = 5;
10058 static const int kInstantiatedBit = 6;
10059 static const int kAcceptAnyReceiver = 7;
10061 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10065 class ObjectTemplateInfo: public TemplateInfo {
10067 DECL_ACCESSORS(constructor, Object)
10068 DECL_ACCESSORS(internal_field_count, Object)
10070 DECLARE_CAST(ObjectTemplateInfo)
10072 // Dispatched behavior.
10073 DECLARE_PRINTER(ObjectTemplateInfo)
10074 DECLARE_VERIFIER(ObjectTemplateInfo)
10076 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10077 static const int kInternalFieldCountOffset =
10078 kConstructorOffset + kPointerSize;
10079 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10083 class TypeSwitchInfo: public Struct {
10085 DECL_ACCESSORS(types, Object)
10087 DECLARE_CAST(TypeSwitchInfo)
10089 // Dispatched behavior.
10090 DECLARE_PRINTER(TypeSwitchInfo)
10091 DECLARE_VERIFIER(TypeSwitchInfo)
10093 static const int kTypesOffset = Struct::kHeaderSize;
10094 static const int kSize = kTypesOffset + kPointerSize;
10098 // The DebugInfo class holds additional information for a function being
10100 class DebugInfo: public Struct {
10102 // The shared function info for the source being debugged.
10103 DECL_ACCESSORS(shared, SharedFunctionInfo)
10104 // Code object for the patched code. This code object is the code object
10105 // currently active for the function.
10106 DECL_ACCESSORS(code, Code)
10107 // Fixed array holding status information for each active break point.
10108 DECL_ACCESSORS(break_points, FixedArray)
10110 // Check if there is a break point at a code position.
10111 bool HasBreakPoint(int code_position);
10112 // Get the break point info object for a code position.
10113 Object* GetBreakPointInfo(int code_position);
10114 // Clear a break point.
10115 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10117 Handle<Object> break_point_object);
10118 // Set a break point.
10119 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10120 int source_position, int statement_position,
10121 Handle<Object> break_point_object);
10122 // Get the break point objects for a code position.
10123 Handle<Object> GetBreakPointObjects(int code_position);
10124 // Find the break point info holding this break point object.
10125 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10126 Handle<Object> break_point_object);
10127 // Get the number of break points for this function.
10128 int GetBreakPointCount();
10130 DECLARE_CAST(DebugInfo)
10132 // Dispatched behavior.
10133 DECLARE_PRINTER(DebugInfo)
10134 DECLARE_VERIFIER(DebugInfo)
10136 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10137 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10138 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10139 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10141 static const int kEstimatedNofBreakPointsInFunction = 16;
10144 static const int kNoBreakPointInfo = -1;
10146 // Lookup the index in the break_points array for a code position.
10147 int GetBreakPointInfoIndex(int code_position);
10149 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10153 // The BreakPointInfo class holds information for break points set in a
10154 // function. The DebugInfo object holds a BreakPointInfo object for each code
10155 // position with one or more break points.
10156 class BreakPointInfo: public Struct {
10158 // The position in the code for the break point.
10159 DECL_ACCESSORS(code_position, Smi)
10160 // The position in the source for the break position.
10161 DECL_ACCESSORS(source_position, Smi)
10162 // The position in the source for the last statement before this break
10164 DECL_ACCESSORS(statement_position, Smi)
10165 // List of related JavaScript break points.
10166 DECL_ACCESSORS(break_point_objects, Object)
10168 // Removes a break point.
10169 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10170 Handle<Object> break_point_object);
10171 // Set a break point.
10172 static void SetBreakPoint(Handle<BreakPointInfo> info,
10173 Handle<Object> break_point_object);
10174 // Check if break point info has this break point object.
10175 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10176 Handle<Object> break_point_object);
10177 // Get the number of break points for this code position.
10178 int GetBreakPointCount();
10180 DECLARE_CAST(BreakPointInfo)
10182 // Dispatched behavior.
10183 DECLARE_PRINTER(BreakPointInfo)
10184 DECLARE_VERIFIER(BreakPointInfo)
10186 static const int kCodePositionIndex = Struct::kHeaderSize;
10187 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10188 static const int kStatementPositionIndex =
10189 kSourcePositionIndex + kPointerSize;
10190 static const int kBreakPointObjectsIndex =
10191 kStatementPositionIndex + kPointerSize;
10192 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10195 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10199 #undef DECL_BOOLEAN_ACCESSORS
10200 #undef DECL_ACCESSORS
10201 #undef DECLARE_CAST
10202 #undef DECLARE_VERIFIER
10204 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10205 V(kStringTable, "string_table", "(Internalized strings)") \
10206 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10207 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10208 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10209 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10210 V(kTop, "top", "(Isolate)") \
10211 V(kRelocatable, "relocatable", "(Relocatable)") \
10212 V(kDebug, "debug", "(Debugger)") \
10213 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10214 V(kHandleScope, "handlescope", "(Handle scope)") \
10215 V(kBuiltins, "builtins", "(Builtins)") \
10216 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10217 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10218 V(kThreadManager, "threadmanager", "(Thread manager)") \
10219 V(kStrongRoots, "strong roots", "(Strong roots)") \
10220 V(kExtensions, "Extensions", "(Extensions)")
10222 class VisitorSynchronization : public AllStatic {
10224 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10226 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10229 #undef DECLARE_ENUM
10231 static const char* const kTags[kNumberOfSyncTags];
10232 static const char* const kTagNames[kNumberOfSyncTags];
10235 // Abstract base class for visiting, and optionally modifying, the
10236 // pointers contained in Objects. Used in GC and serialization/deserialization.
10237 class ObjectVisitor BASE_EMBEDDED {
10239 virtual ~ObjectVisitor() {}
10241 // Visits a contiguous arrays of pointers in the half-open range
10242 // [start, end). Any or all of the values may be modified on return.
10243 virtual void VisitPointers(Object** start, Object** end) = 0;
10245 // Handy shorthand for visiting a single pointer.
10246 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10248 // Visit weak next_code_link in Code object.
10249 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10251 // To allow lazy clearing of inline caches the visitor has
10252 // a rich interface for iterating over Code objects..
10254 // Visits a code target in the instruction stream.
10255 virtual void VisitCodeTarget(RelocInfo* rinfo);
10257 // Visits a code entry in a JS function.
10258 virtual void VisitCodeEntry(Address entry_address);
10260 // Visits a global property cell reference in the instruction stream.
10261 virtual void VisitCell(RelocInfo* rinfo);
10263 // Visits a runtime entry in the instruction stream.
10264 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10266 // Visits the resource of an one-byte or two-byte string.
10267 virtual void VisitExternalOneByteString(
10268 v8::String::ExternalOneByteStringResource** resource) {}
10269 virtual void VisitExternalTwoByteString(
10270 v8::String::ExternalStringResource** resource) {}
10272 // Visits a debug call target in the instruction stream.
10273 virtual void VisitDebugTarget(RelocInfo* rinfo);
10275 // Visits the byte sequence in a function's prologue that contains information
10276 // about the code's age.
10277 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10279 // Visit pointer embedded into a code object.
10280 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10282 // Visits an external reference embedded into a code object.
10283 virtual void VisitExternalReference(RelocInfo* rinfo);
10285 // Visits an external reference.
10286 virtual void VisitExternalReference(Address* p) {}
10288 // Visits an (encoded) internal reference.
10289 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10291 // Visits a handle that has an embedder-assigned class ID.
10292 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10294 // Intended for serialization/deserialization checking: insert, or
10295 // check for the presence of, a tag at this position in the stream.
10296 // Also used for marking up GC roots in heap snapshots.
10297 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10301 class StructBodyDescriptor : public
10302 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10304 static inline int SizeOf(Map* map, HeapObject* object);
10308 // BooleanBit is a helper class for setting and getting a bit in an
10310 class BooleanBit : public AllStatic {
10312 static inline bool get(Smi* smi, int bit_position) {
10313 return get(smi->value(), bit_position);
10316 static inline bool get(int value, int bit_position) {
10317 return (value & (1 << bit_position)) != 0;
10320 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10321 return Smi::FromInt(set(smi->value(), bit_position, v));
10324 static inline int set(int value, int bit_position, bool v) {
10326 value |= (1 << bit_position);
10328 value &= ~(1 << bit_position);
10334 } } // namespace v8::internal
10336 #endif // V8_OBJECTS_H_