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
129 // - SharedFunctionInfo
133 // - ExecutableAccessorInfo
139 // - FunctionTemplateInfo
140 // - ObjectTemplateInfo
149 // Formats of Object*:
150 // Smi: [31 bit signed int] 0
151 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
156 enum KeyedAccessStoreMode {
158 STORE_TRANSITION_TO_OBJECT,
159 STORE_TRANSITION_TO_DOUBLE,
160 STORE_AND_GROW_NO_TRANSITION,
161 STORE_AND_GROW_TRANSITION_TO_OBJECT,
162 STORE_AND_GROW_TRANSITION_TO_DOUBLE,
163 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
164 STORE_NO_TRANSITION_HANDLE_COW
168 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
177 enum ExternalArrayType {
178 kExternalInt8Array = 1,
181 kExternalUint16Array,
183 kExternalUint32Array,
184 kExternalFloat32Array,
185 kExternalFloat64Array,
186 kExternalUint8ClampedArray,
190 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
191 return store_mode == STORE_TRANSITION_TO_OBJECT ||
192 store_mode == STORE_TRANSITION_TO_DOUBLE ||
193 store_mode == STORE_AND_GROW_TRANSITION_TO_OBJECT ||
194 store_mode == STORE_AND_GROW_TRANSITION_TO_DOUBLE;
198 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
199 KeyedAccessStoreMode store_mode) {
200 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
203 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
204 return STORE_AND_GROW_NO_TRANSITION;
206 return STANDARD_STORE;
210 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
211 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
212 store_mode <= STORE_AND_GROW_TRANSITION_TO_DOUBLE;
216 enum IcCheckType { ELEMENT, PROPERTY };
219 // SKIP_WRITE_BARRIER skips the write barrier.
220 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
221 // only performs the generational part.
222 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
223 enum WriteBarrierMode {
225 UPDATE_WEAK_WRITE_BARRIER,
230 // Indicates whether a value can be loaded as a constant.
231 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
234 // PropertyNormalizationMode is used to specify whether to keep
235 // inobject properties when normalizing properties of a JSObject.
236 enum PropertyNormalizationMode {
237 CLEAR_INOBJECT_PROPERTIES,
238 KEEP_INOBJECT_PROPERTIES
242 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
243 // will give the fastest result by tailoring the map to the prototype, but that
244 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
245 // (at least for now) when dynamically modifying the prototype chain of an
246 // object using __proto__ or Object.setPrototypeOf.
247 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
250 // Indicates whether transitions can be added to a source map or not.
251 enum TransitionFlag {
257 // Indicates whether the transition is simple: the target map of the transition
258 // either extends the current map with a new property, or it modifies the
259 // property that was added last to the current map.
260 enum SimpleTransitionFlag {
261 SIMPLE_PROPERTY_TRANSITION,
267 // Indicates whether we are only interested in the descriptors of a particular
268 // map, or in all descriptors in the descriptor array.
269 enum DescriptorFlag {
274 // The GC maintains a bit of information, the MarkingParity, which toggles
275 // from odd to even and back every time marking is completed. Incremental
276 // marking can visit an object twice during a marking phase, so algorithms that
277 // that piggy-back on marking can use the parity to ensure that they only
278 // perform an operation on an object once per marking phase: they record the
279 // MarkingParity when they visit an object, and only re-visit the object when it
280 // is marked again and the MarkingParity changes.
287 // ICs store extra state in a Code object. The default extra state is
289 typedef int ExtraICState;
290 static const ExtraICState kNoExtraICState = 0;
292 // Instance size sentinel for objects of variable size.
293 const int kVariableSizeSentinel = 0;
295 // We may store the unsigned bit field as signed Smi value and do not
297 const int kStubMajorKeyBits = 7;
298 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
300 // All Maps have a field instance_type containing a InstanceType.
301 // It describes the type of the instances.
303 // As an example, a JavaScript object is a heap object and its map
304 // instance_type is JS_OBJECT_TYPE.
306 // The names of the string instance types are intended to systematically
307 // mirror their encoding in the instance_type field of the map. The default
308 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
309 // encoding is mentioned explicitly in the name. Likewise, the default
310 // representation is considered sequential. It is not mentioned in the
311 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
312 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
313 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
315 // NOTE: The following things are some that depend on the string types having
316 // instance_types that are less than those of all other types:
317 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
320 // NOTE: Everything following JS_VALUE_TYPE is considered a
321 // JSObject for GC purposes. The first four entries here have typeof
322 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
323 #define INSTANCE_TYPE_LIST(V) \
325 V(ONE_BYTE_STRING_TYPE) \
326 V(CONS_STRING_TYPE) \
327 V(CONS_ONE_BYTE_STRING_TYPE) \
328 V(SLICED_STRING_TYPE) \
329 V(SLICED_ONE_BYTE_STRING_TYPE) \
330 V(EXTERNAL_STRING_TYPE) \
331 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
332 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
333 V(SHORT_EXTERNAL_STRING_TYPE) \
334 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
335 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
337 V(INTERNALIZED_STRING_TYPE) \
338 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
339 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
340 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
341 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
342 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
343 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
344 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
347 V(SIMD128_VALUE_TYPE) \
353 V(PROPERTY_CELL_TYPE) \
355 V(HEAP_NUMBER_TYPE) \
356 V(MUTABLE_HEAP_NUMBER_TYPE) \
359 V(BYTECODE_ARRAY_TYPE) \
362 V(FIXED_INT8_ARRAY_TYPE) \
363 V(FIXED_UINT8_ARRAY_TYPE) \
364 V(FIXED_INT16_ARRAY_TYPE) \
365 V(FIXED_UINT16_ARRAY_TYPE) \
366 V(FIXED_INT32_ARRAY_TYPE) \
367 V(FIXED_UINT32_ARRAY_TYPE) \
368 V(FIXED_FLOAT32_ARRAY_TYPE) \
369 V(FIXED_FLOAT64_ARRAY_TYPE) \
370 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
374 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
375 V(DECLARED_ACCESSOR_INFO_TYPE) \
376 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
377 V(ACCESSOR_PAIR_TYPE) \
378 V(ACCESS_CHECK_INFO_TYPE) \
379 V(INTERCEPTOR_INFO_TYPE) \
380 V(CALL_HANDLER_INFO_TYPE) \
381 V(FUNCTION_TEMPLATE_INFO_TYPE) \
382 V(OBJECT_TEMPLATE_INFO_TYPE) \
383 V(SIGNATURE_INFO_TYPE) \
384 V(TYPE_SWITCH_INFO_TYPE) \
385 V(ALLOCATION_MEMENTO_TYPE) \
386 V(ALLOCATION_SITE_TYPE) \
389 V(POLYMORPHIC_CODE_CACHE_TYPE) \
390 V(TYPE_FEEDBACK_INFO_TYPE) \
391 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
393 V(PROTOTYPE_INFO_TYPE) \
395 V(FIXED_ARRAY_TYPE) \
396 V(FIXED_DOUBLE_ARRAY_TYPE) \
397 V(SHARED_FUNCTION_INFO_TYPE) \
400 V(JS_MESSAGE_OBJECT_TYPE) \
405 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
406 V(JS_GENERATOR_OBJECT_TYPE) \
408 V(JS_GLOBAL_OBJECT_TYPE) \
409 V(JS_BUILTINS_OBJECT_TYPE) \
410 V(JS_GLOBAL_PROXY_TYPE) \
412 V(JS_ARRAY_BUFFER_TYPE) \
413 V(JS_TYPED_ARRAY_TYPE) \
414 V(JS_DATA_VIEW_TYPE) \
418 V(JS_SET_ITERATOR_TYPE) \
419 V(JS_MAP_ITERATOR_TYPE) \
420 V(JS_WEAK_MAP_TYPE) \
421 V(JS_WEAK_SET_TYPE) \
424 V(JS_FUNCTION_TYPE) \
425 V(JS_FUNCTION_PROXY_TYPE) \
427 V(BREAK_POINT_INFO_TYPE)
430 // Since string types are not consecutive, this macro is used to
431 // iterate over them.
432 #define STRING_TYPE_LIST(V) \
433 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
434 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
436 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
437 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
439 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
440 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
441 SlicedOneByteString) \
442 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
444 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
445 external_one_byte_string, ExternalOneByteString) \
446 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
447 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
448 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
449 short_external_string, ShortExternalString) \
450 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
451 short_external_one_byte_string, ShortExternalOneByteString) \
452 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
453 ExternalTwoByteString::kShortSize, \
454 short_external_string_with_one_byte_data, \
455 ShortExternalStringWithOneByteData) \
457 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
458 InternalizedString) \
459 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
460 one_byte_internalized_string, OneByteInternalizedString) \
461 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
462 external_internalized_string, ExternalInternalizedString) \
463 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
464 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
465 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
466 ExternalTwoByteString::kSize, \
467 external_internalized_string_with_one_byte_data, \
468 ExternalInternalizedStringWithOneByteData) \
469 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
470 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
471 ShortExternalInternalizedString) \
472 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
473 ExternalOneByteString::kShortSize, \
474 short_external_one_byte_internalized_string, \
475 ShortExternalOneByteInternalizedString) \
476 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
477 ExternalTwoByteString::kShortSize, \
478 short_external_internalized_string_with_one_byte_data, \
479 ShortExternalInternalizedStringWithOneByteData)
481 // A struct is a simple object a set of object-valued fields. Including an
482 // object type in this causes the compiler to generate most of the boilerplate
483 // code for the class including allocation and garbage collection routines,
484 // casts and predicates. All you need to define is the class, methods and
485 // object verification routines. Easy, no?
487 // Note that for subtle reasons related to the ordering or numerical values of
488 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
490 #define STRUCT_LIST(V) \
492 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
493 executable_accessor_info) \
494 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
495 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
496 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
497 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
498 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
499 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
500 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
501 V(SCRIPT, Script, script) \
502 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
503 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
504 V(CODE_CACHE, CodeCache, code_cache) \
505 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
506 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
507 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
508 V(DEBUG_INFO, DebugInfo, debug_info) \
509 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
510 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
512 // We use the full 8 bits of the instance_type field to encode heap object
513 // instance types. The high-order bit (bit 7) is set if the object is not a
514 // string, and cleared if it is a string.
515 const uint32_t kIsNotStringMask = 0x80;
516 const uint32_t kStringTag = 0x0;
517 const uint32_t kNotStringTag = 0x80;
519 // Bit 6 indicates that the object is an internalized string (if set) or not.
520 // Bit 7 has to be clear as well.
521 const uint32_t kIsNotInternalizedMask = 0x40;
522 const uint32_t kNotInternalizedTag = 0x40;
523 const uint32_t kInternalizedTag = 0x0;
525 // If bit 7 is clear then bit 2 indicates whether the string consists of
526 // two-byte characters or one-byte characters.
527 const uint32_t kStringEncodingMask = 0x4;
528 const uint32_t kTwoByteStringTag = 0x0;
529 const uint32_t kOneByteStringTag = 0x4;
531 // If bit 7 is clear, the low-order 2 bits indicate the representation
533 const uint32_t kStringRepresentationMask = 0x03;
534 enum StringRepresentationTag {
536 kConsStringTag = 0x1,
537 kExternalStringTag = 0x2,
538 kSlicedStringTag = 0x3
540 const uint32_t kIsIndirectStringMask = 0x1;
541 const uint32_t kIsIndirectStringTag = 0x1;
542 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
543 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
544 STATIC_ASSERT((kConsStringTag &
545 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
546 STATIC_ASSERT((kSlicedStringTag &
547 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
549 // Use this mask to distinguish between cons and slice only after making
550 // sure that the string is one of the two (an indirect string).
551 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
552 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
554 // If bit 7 is clear, then bit 3 indicates whether this two-byte
555 // string actually contains one byte data.
556 const uint32_t kOneByteDataHintMask = 0x08;
557 const uint32_t kOneByteDataHintTag = 0x08;
559 // If bit 7 is clear and string representation indicates an external string,
560 // then bit 4 indicates whether the data pointer is cached.
561 const uint32_t kShortExternalStringMask = 0x10;
562 const uint32_t kShortExternalStringTag = 0x10;
565 // A ConsString with an empty string as the right side is a candidate
566 // for being shortcut by the garbage collector. We don't allocate any
567 // non-flat internalized strings, so we do not shortcut them thereby
568 // avoiding turning internalized strings into strings. The bit-masks
569 // below contain the internalized bit as additional safety.
570 // See heap.cc, mark-compact.cc and objects-visiting.cc.
571 const uint32_t kShortcutTypeMask =
573 kIsNotInternalizedMask |
574 kStringRepresentationMask;
575 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
577 static inline bool IsShortcutCandidate(int type) {
578 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
584 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
585 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
586 ONE_BYTE_INTERNALIZED_STRING_TYPE =
587 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
588 EXTERNAL_INTERNALIZED_STRING_TYPE =
589 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
590 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
591 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
592 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
593 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
595 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
596 kShortExternalStringTag |
598 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
599 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
601 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
602 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
603 kShortExternalStringTag | kInternalizedTag,
604 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
605 ONE_BYTE_STRING_TYPE =
606 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
607 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
608 CONS_ONE_BYTE_STRING_TYPE =
609 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
611 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
612 SLICED_ONE_BYTE_STRING_TYPE =
613 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
614 EXTERNAL_STRING_TYPE =
615 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
616 EXTERNAL_ONE_BYTE_STRING_TYPE =
617 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
618 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
619 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
621 SHORT_EXTERNAL_STRING_TYPE =
622 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
623 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
624 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
625 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
626 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
630 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
632 // Other primitives (cannot contain non-map-word pointers to heap objects).
635 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
637 // Objects allocated in their own spaces (never in new space).
641 // "Data", objects that cannot contain non-map-word pointers to heap
643 MUTABLE_HEAP_NUMBER_TYPE,
648 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
649 FIXED_UINT8_ARRAY_TYPE,
650 FIXED_INT16_ARRAY_TYPE,
651 FIXED_UINT16_ARRAY_TYPE,
652 FIXED_INT32_ARRAY_TYPE,
653 FIXED_UINT32_ARRAY_TYPE,
654 FIXED_FLOAT32_ARRAY_TYPE,
655 FIXED_FLOAT64_ARRAY_TYPE,
656 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
657 FIXED_DOUBLE_ARRAY_TYPE,
658 FILLER_TYPE, // LAST_DATA_TYPE
661 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
662 DECLARED_ACCESSOR_INFO_TYPE,
663 EXECUTABLE_ACCESSOR_INFO_TYPE,
665 ACCESS_CHECK_INFO_TYPE,
666 INTERCEPTOR_INFO_TYPE,
667 CALL_HANDLER_INFO_TYPE,
668 FUNCTION_TEMPLATE_INFO_TYPE,
669 OBJECT_TEMPLATE_INFO_TYPE,
671 TYPE_SWITCH_INFO_TYPE,
672 ALLOCATION_SITE_TYPE,
673 ALLOCATION_MEMENTO_TYPE,
676 POLYMORPHIC_CODE_CACHE_TYPE,
677 TYPE_FEEDBACK_INFO_TYPE,
678 ALIASED_ARGUMENTS_ENTRY_TYPE,
681 BREAK_POINT_INFO_TYPE,
683 SHARED_FUNCTION_INFO_TYPE,
689 // All the following types are subtypes of JSReceiver, which corresponds to
690 // objects in the JS sense. The first and the last type in this range are
691 // the two forms of function. This organization enables using the same
692 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
693 // NONCALLABLE_JS_OBJECT range.
694 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
695 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
696 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
697 JS_MESSAGE_OBJECT_TYPE,
700 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
701 JS_GENERATOR_OBJECT_TYPE,
703 JS_GLOBAL_OBJECT_TYPE,
704 JS_BUILTINS_OBJECT_TYPE,
705 JS_GLOBAL_PROXY_TYPE,
707 JS_ARRAY_BUFFER_TYPE,
712 JS_SET_ITERATOR_TYPE,
713 JS_MAP_ITERATOR_TYPE,
717 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
721 LAST_TYPE = JS_FUNCTION_TYPE,
722 FIRST_NAME_TYPE = FIRST_TYPE,
723 LAST_NAME_TYPE = SYMBOL_TYPE,
724 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
725 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
726 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
727 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
728 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
729 // Boundaries for testing for a fixed typed array.
730 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
731 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
732 // Boundary for promotion to old space.
733 LAST_DATA_TYPE = FILLER_TYPE,
734 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
735 // Note that there is no range for JSObject or JSProxy, since their subtypes
736 // are not continuous in this enum! The enum ranges instead reflect the
737 // external class names, where proxies are treated as either ordinary objects,
739 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
740 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
741 // Boundaries for testing the types represented as JSObject
742 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
743 LAST_JS_OBJECT_TYPE = LAST_TYPE,
744 // Boundaries for testing the types represented as JSProxy
745 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
746 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
747 // Boundaries for testing whether the type is a JavaScript object.
748 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
749 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
750 // Boundaries for testing the types for which typeof is "object".
751 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
752 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
753 // Note that the types for which typeof is "function" are not continuous.
754 // Define this so that we can put assertions on discrete checks.
755 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
758 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
759 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
760 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
761 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
764 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
765 V(FAST_ELEMENTS_SUB_TYPE) \
766 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
767 V(FAST_PROPERTIES_SUB_TYPE) \
768 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
769 V(MAP_CODE_CACHE_SUB_TYPE) \
770 V(SCOPE_INFO_SUB_TYPE) \
771 V(STRING_TABLE_SUB_TYPE) \
772 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
773 V(TRANSITION_ARRAY_SUB_TYPE)
775 enum FixedArraySubInstanceType {
776 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
777 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
778 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
779 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
792 #define DECL_BOOLEAN_ACCESSORS(name) \
793 inline bool name() const; \
794 inline void set_##name(bool value); \
797 #define DECL_ACCESSORS(name, type) \
798 inline type* name() const; \
799 inline void set_##name(type* value, \
800 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
803 #define DECLARE_CAST(type) \
804 INLINE(static type* cast(Object* object)); \
805 INLINE(static const type* cast(const Object* object));
809 class AllocationSite;
810 class AllocationSiteCreationContext;
811 class AllocationSiteUsageContext;
814 class ElementsAccessor;
815 class FixedArrayBase;
816 class FunctionLiteral;
818 class JSBuiltinsObject;
819 class LayoutDescriptor;
820 class LookupIterator;
821 class ObjectHashTable;
824 class SafepointEntry;
825 class SharedFunctionInfo;
827 class TypeFeedbackInfo;
828 class TypeFeedbackVector;
831 // We cannot just say "class HeapType;" if it is created from a template... =8-?
832 template<class> class TypeImpl;
833 struct HeapTypeConfig;
834 typedef TypeImpl<HeapTypeConfig> HeapType;
837 // A template-ized version of the IsXXX functions.
838 template <class C> inline bool Is(Object* obj);
841 #define DECLARE_VERIFIER(Name) void Name##Verify();
843 #define DECLARE_VERIFIER(Name)
847 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
849 #define DECLARE_PRINTER(Name)
853 #define OBJECT_TYPE_LIST(V) \
858 #define HEAP_OBJECT_TYPE_LIST(V) \
860 V(MutableHeapNumber) \
876 V(ExternalTwoByteString) \
877 V(ExternalOneByteString) \
878 V(SeqTwoByteString) \
879 V(SeqOneByteString) \
880 V(InternalizedString) \
883 V(FixedTypedArrayBase) \
886 V(FixedUint16Array) \
888 V(FixedUint32Array) \
890 V(FixedFloat32Array) \
891 V(FixedFloat64Array) \
892 V(FixedUint8ClampedArray) \
898 V(JSContextExtensionObject) \
899 V(JSGeneratorObject) \
901 V(LayoutDescriptor) \
905 V(TypeFeedbackVector) \
906 V(DeoptimizationInputData) \
907 V(DeoptimizationOutputData) \
911 V(FixedDoubleArray) \
915 V(ScriptContextTable) \
921 V(SharedFunctionInfo) \
930 V(JSArrayBufferView) \
939 V(JSWeakCollection) \
946 V(NormalizedMapCache) \
947 V(CompilationCacheTable) \
948 V(CodeCacheHashTable) \
949 V(PolymorphicCodeCacheHashTable) \
954 V(JSBuiltinsObject) \
956 V(UndetectableObject) \
957 V(AccessCheckNeeded) \
965 // Object is the abstract superclass for all classes in the
967 // Object does not use any virtual functions to avoid the
968 // allocation of the C++ vtable.
969 // Since both Smi and HeapObject are subclasses of Object no
970 // data members can be present in Object.
974 bool IsObject() const { return true; }
976 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
977 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
978 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
979 #undef IS_TYPE_FUNCTION_DECL
981 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
982 // a keyed store is of the form a[expression] = foo.
983 enum StoreFromKeyed {
984 MAY_BE_STORE_FROM_KEYED,
985 CERTAINLY_NOT_STORE_FROM_KEYED
988 INLINE(bool IsFixedArrayBase() const);
989 INLINE(bool IsExternal() const);
990 INLINE(bool IsAccessorInfo() const);
992 INLINE(bool IsStruct() const);
993 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
994 INLINE(bool Is##Name() const);
995 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
996 #undef DECLARE_STRUCT_PREDICATE
998 INLINE(bool IsSpecObject()) const;
999 INLINE(bool IsSpecFunction()) const;
1000 INLINE(bool IsTemplateInfo()) const;
1001 INLINE(bool IsNameDictionary() const);
1002 INLINE(bool IsGlobalDictionary() const);
1003 INLINE(bool IsSeededNumberDictionary() const);
1004 INLINE(bool IsUnseededNumberDictionary() const);
1005 INLINE(bool IsOrderedHashSet() const);
1006 INLINE(bool IsOrderedHashMap() const);
1007 bool IsCallable() const;
1008 static bool IsPromise(Handle<Object> object);
1011 INLINE(bool IsUndefined() const);
1012 INLINE(bool IsNull() const);
1013 INLINE(bool IsTheHole() const);
1014 INLINE(bool IsException() const);
1015 INLINE(bool IsUninitialized() const);
1016 INLINE(bool IsTrue() const);
1017 INLINE(bool IsFalse() const);
1018 INLINE(bool IsArgumentsMarker() const);
1020 // Filler objects (fillers and free space objects).
1021 INLINE(bool IsFiller() const);
1023 // Extract the number.
1024 inline double Number();
1025 INLINE(bool IsNaN() const);
1026 INLINE(bool IsMinusZero() const);
1027 bool ToInt32(int32_t* value);
1028 bool ToUint32(uint32_t* value);
1030 inline Representation OptimalRepresentation();
1032 inline ElementsKind OptimalElementsKind();
1034 inline bool FitsRepresentation(Representation representation);
1036 // Checks whether two valid primitive encodings of a property name resolve to
1037 // the same logical property. E.g., the smi 1, the string "1" and the double
1038 // 1 all refer to the same property, so this helper will return true.
1039 inline bool KeyEquals(Object* other);
1041 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1043 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1044 Handle<Object> object,
1045 Representation representation);
1047 inline static Handle<Object> WrapForRead(Isolate* isolate,
1048 Handle<Object> object,
1049 Representation representation);
1051 // Returns true if the object is of the correct type to be used as a
1052 // implementation of a JSObject's elements.
1053 inline bool HasValidElements();
1055 inline bool HasSpecificClassOf(String* name);
1057 bool BooleanValue(); // ECMA-262 9.2.
1059 // ES6 section 7.2.13 Strict Equality Comparison
1060 bool StrictEquals(Object* that);
1062 // Convert to a JSObject if needed.
1063 // native_context is used when creating wrapper object.
1064 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1065 Handle<Object> object);
1066 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1067 Handle<Object> object,
1068 Handle<Context> context);
1070 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1071 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1073 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1074 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1075 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1076 LanguageMode language_mode,
1077 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1079 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1080 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1081 StoreFromKeyed store_mode);
1083 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1084 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1085 StoreFromKeyed store_mode);
1087 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1088 LookupIterator* it, LanguageMode language_mode);
1089 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1090 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1091 LanguageMode language_mode);
1092 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1093 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1094 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1095 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1096 Handle<Object> value, LanguageMode language_mode);
1097 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1098 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1099 LanguageMode language_mode);
1100 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1101 LookupIterator* it, Handle<Object> value);
1102 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1103 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1104 LanguageMode language_mode, StoreFromKeyed store_mode);
1105 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1106 Handle<Object> object, Handle<Name> name,
1107 LanguageMode language_mode = SLOPPY);
1108 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1109 Isolate* isolate, Handle<Object> object, const char* key,
1110 LanguageMode language_mode = SLOPPY);
1111 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1112 Handle<Object> object, Handle<Name> name,
1113 LanguageMode language_mode = SLOPPY);
1115 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1116 LookupIterator* it, LanguageMode language_mode);
1117 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1118 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1120 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1121 Handle<Object> receiver,
1122 Handle<JSReceiver> getter);
1123 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1124 Handle<Object> receiver,
1125 Handle<JSReceiver> setter,
1126 Handle<Object> value);
1128 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1129 Isolate* isolate, Handle<Object> object, uint32_t index,
1130 LanguageMode language_mode = SLOPPY);
1132 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1133 Isolate* isolate, Handle<Object> object, uint32_t index,
1134 Handle<Object> value, LanguageMode language_mode);
1136 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1137 Isolate* isolate, Handle<Object> receiver);
1139 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1141 // Returns the permanent hash code associated with this object. May return
1142 // undefined if not yet created.
1145 // Returns undefined for JSObjects, but returns the hash code for simple
1146 // objects. This avoids a double lookup in the cases where we know we will
1147 // add the hash to the JSObject if it does not already exist.
1148 Object* GetSimpleHash();
1150 // Returns the permanent hash code associated with this object depending on
1151 // the actual object type. May create and store a hash code if needed and none
1153 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1155 // Checks whether this object has the same value as the given one. This
1156 // function is implemented according to ES5, section 9.12 and can be used
1157 // to implement the Harmony "egal" function.
1158 bool SameValue(Object* other);
1160 // Checks whether this object has the same value as the given one.
1161 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1162 // This function is implemented according to ES6, section 7.2.4 and is used
1163 // by ES6 Map and Set.
1164 bool SameValueZero(Object* other);
1166 // Tries to convert an object to an array length. Returns true and sets the
1167 // output parameter if it succeeds.
1168 inline bool ToArrayLength(uint32_t* index);
1170 // Tries to convert an object to an array index. Returns true and sets the
1171 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1172 // allow kMaxUInt32.
1173 inline bool ToArrayIndex(uint32_t* index);
1175 // Returns true if this is a JSValue containing a string and the index is
1176 // < the length of the string. Used to implement [] on strings.
1177 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1179 DECLARE_VERIFIER(Object)
1181 // Verify a pointer is a valid object pointer.
1182 static void VerifyPointer(Object* p);
1185 inline void VerifyApiCallResultType();
1187 // Prints this object without details.
1188 void ShortPrint(FILE* out = stdout);
1190 // Prints this object without details to a message accumulator.
1191 void ShortPrint(StringStream* accumulator);
1193 void ShortPrint(std::ostream& os); // NOLINT
1195 DECLARE_CAST(Object)
1197 // Layout description.
1198 static const int kHeaderSize = 0; // Object does not take up any space.
1201 // For our gdb macros, we should perhaps change these in the future.
1204 // Prints this object with details.
1205 void Print(std::ostream& os); // NOLINT
1207 void Print() { ShortPrint(); }
1208 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1212 friend class LookupIterator;
1213 friend class PrototypeIterator;
1215 // Return the map of the root of object's prototype chain.
1216 Map* GetRootMap(Isolate* isolate);
1218 // Helper for SetProperty and SetSuperProperty.
1219 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1220 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1221 StoreFromKeyed store_mode, bool* found);
1223 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1227 // In objects.h to be usable without objects-inl.h inclusion.
1228 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1229 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1233 explicit Brief(const Object* const v) : value(v) {}
1234 const Object* value;
1238 std::ostream& operator<<(std::ostream& os, const Brief& v);
1241 // Smi represents integer Numbers that can be stored in 31 bits.
1242 // Smis are immediate which means they are NOT allocated in the heap.
1243 // The this pointer has the following format: [31 bit signed int] 0
1244 // For long smis it has the following format:
1245 // [32 bit signed int] [31 bits zero padding] 0
1246 // Smi stands for small integer.
1247 class Smi: public Object {
1249 // Returns the integer value.
1250 inline int value() const { return Internals::SmiValue(this); }
1252 // Convert a value to a Smi object.
1253 static inline Smi* FromInt(int value) {
1254 DCHECK(Smi::IsValid(value));
1255 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1258 static inline Smi* FromIntptr(intptr_t value) {
1259 DCHECK(Smi::IsValid(value));
1260 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1261 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1264 // Returns whether value can be represented in a Smi.
1265 static inline bool IsValid(intptr_t value) {
1266 bool result = Internals::IsValidSmi(value);
1267 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1273 // Dispatched behavior.
1274 void SmiPrint(std::ostream& os) const; // NOLINT
1275 DECLARE_VERIFIER(Smi)
1277 static const int kMinValue =
1278 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1279 static const int kMaxValue = -(kMinValue + 1);
1282 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1286 // Heap objects typically have a map pointer in their first word. However,
1287 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1288 // encoded in the first word. The class MapWord is an abstraction of the
1289 // value in a heap object's first word.
1290 class MapWord BASE_EMBEDDED {
1292 // Normal state: the map word contains a map pointer.
1294 // Create a map word from a map pointer.
1295 static inline MapWord FromMap(const Map* map);
1297 // View this map word as a map pointer.
1298 inline Map* ToMap();
1301 // Scavenge collection: the map word of live objects in the from space
1302 // contains a forwarding address (a heap object pointer in the to space).
1304 // True if this map word is a forwarding address for a scavenge
1305 // collection. Only valid during a scavenge collection (specifically,
1306 // when all map words are heap object pointers, i.e. not during a full GC).
1307 inline bool IsForwardingAddress();
1309 // Create a map word from a forwarding address.
1310 static inline MapWord FromForwardingAddress(HeapObject* object);
1312 // View this map word as a forwarding address.
1313 inline HeapObject* ToForwardingAddress();
1315 static inline MapWord FromRawValue(uintptr_t value) {
1316 return MapWord(value);
1319 inline uintptr_t ToRawValue() {
1324 // HeapObject calls the private constructor and directly reads the value.
1325 friend class HeapObject;
1327 explicit MapWord(uintptr_t value) : value_(value) {}
1333 // The content of an heap object (except for the map pointer). kTaggedValues
1334 // objects can contain both heap pointers and Smis, kMixedValues can contain
1335 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1336 // objects can contain raw values and Smis.
1337 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1340 // HeapObject is the superclass for all classes describing heap allocated
1342 class HeapObject: public Object {
1344 // [map]: Contains a map which contains the object's reflective
1346 inline Map* map() const;
1347 inline void set_map(Map* value);
1348 // The no-write-barrier version. This is OK if the object is white and in
1349 // new space, or if the value is an immortal immutable object, like the maps
1350 // of primitive (non-JS) objects like strings, heap numbers etc.
1351 inline void set_map_no_write_barrier(Map* value);
1353 // Get the map using acquire load.
1354 inline Map* synchronized_map();
1355 inline MapWord synchronized_map_word() const;
1357 // Set the map using release store
1358 inline void synchronized_set_map(Map* value);
1359 inline void synchronized_set_map_no_write_barrier(Map* value);
1360 inline void synchronized_set_map_word(MapWord map_word);
1362 // During garbage collection, the map word of a heap object does not
1363 // necessarily contain a map pointer.
1364 inline MapWord map_word() const;
1365 inline void set_map_word(MapWord map_word);
1367 // The Heap the object was allocated in. Used also to access Isolate.
1368 inline Heap* GetHeap() const;
1370 // Convenience method to get current isolate.
1371 inline Isolate* GetIsolate() const;
1373 // Converts an address to a HeapObject pointer.
1374 static inline HeapObject* FromAddress(Address address) {
1375 DCHECK_TAG_ALIGNED(address);
1376 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1379 // Returns the address of this HeapObject.
1380 inline Address address() {
1381 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1384 // Iterates over pointers contained in the object (including the Map)
1385 void Iterate(ObjectVisitor* v);
1387 // Iterates over all pointers contained in the object except the
1388 // first map pointer. The object type is given in the first
1389 // parameter. This function does not access the map pointer in the
1390 // object, and so is safe to call while the map pointer is modified.
1391 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1393 // Returns the heap object's size in bytes
1396 // Indicates what type of values this heap object may contain.
1397 inline HeapObjectContents ContentType();
1399 // Given a heap object's map pointer, returns the heap size in bytes
1400 // Useful when the map pointer field is used for other purposes.
1402 inline int SizeFromMap(Map* map);
1404 // Returns the field at offset in obj, as a read/write Object* reference.
1405 // Does no checking, and is safe to use during GC, while maps are invalid.
1406 // Does not invoke write barrier, so should only be assigned to
1407 // during marking GC.
1408 static inline Object** RawField(HeapObject* obj, int offset);
1410 // Adds the |code| object related to |name| to the code cache of this map. If
1411 // this map is a dictionary map that is shared, the map copied and installed
1413 static void UpdateMapCodeCache(Handle<HeapObject> object,
1417 DECLARE_CAST(HeapObject)
1419 // Return the write barrier mode for this. Callers of this function
1420 // must be able to present a reference to an DisallowHeapAllocation
1421 // object as a sign that they are not going to use this function
1422 // from code that allocates and thus invalidates the returned write
1424 inline WriteBarrierMode GetWriteBarrierMode(
1425 const DisallowHeapAllocation& promise);
1427 // Dispatched behavior.
1428 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1430 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1432 DECLARE_PRINTER(HeapObject)
1433 DECLARE_VERIFIER(HeapObject)
1435 inline void VerifyObjectField(int offset);
1436 inline void VerifySmiField(int offset);
1438 // Verify a pointer is a valid HeapObject pointer that points to object
1439 // areas in the heap.
1440 static void VerifyHeapPointer(Object* p);
1443 inline AllocationAlignment RequiredAlignment();
1445 // Layout description.
1446 // First field in a heap object is map.
1447 static const int kMapOffset = Object::kHeaderSize;
1448 static const int kHeaderSize = kMapOffset + kPointerSize;
1450 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1453 // helpers for calling an ObjectVisitor to iterate over pointers in the
1454 // half-open range [start, end) specified as integer offsets
1455 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1456 // as above, for the single element at "offset"
1457 inline void IteratePointer(ObjectVisitor* v, int offset);
1458 // as above, for the next code link of a code object.
1459 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1462 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1466 // This class describes a body of an object of a fixed size
1467 // in which all pointer fields are located in the [start_offset, end_offset)
1469 template<int start_offset, int end_offset, int size>
1470 class FixedBodyDescriptor {
1472 static const int kStartOffset = start_offset;
1473 static const int kEndOffset = end_offset;
1474 static const int kSize = size;
1476 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1478 template<typename StaticVisitor>
1479 static inline void IterateBody(HeapObject* obj) {
1480 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1481 HeapObject::RawField(obj, end_offset));
1486 // This class describes a body of an object of a variable size
1487 // in which all pointer fields are located in the [start_offset, object_size)
1489 template<int start_offset>
1490 class FlexibleBodyDescriptor {
1492 static const int kStartOffset = start_offset;
1494 static inline void IterateBody(HeapObject* obj,
1498 template<typename StaticVisitor>
1499 static inline void IterateBody(HeapObject* obj, int object_size) {
1500 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1501 HeapObject::RawField(obj, object_size));
1506 // The HeapNumber class describes heap allocated numbers that cannot be
1507 // represented in a Smi (small integer)
1508 class HeapNumber: public HeapObject {
1510 // [value]: number value.
1511 inline double value() const;
1512 inline void set_value(double value);
1514 DECLARE_CAST(HeapNumber)
1516 // Dispatched behavior.
1517 bool HeapNumberBooleanValue();
1519 void HeapNumberPrint(std::ostream& os); // NOLINT
1520 DECLARE_VERIFIER(HeapNumber)
1522 inline int get_exponent();
1523 inline int get_sign();
1525 // Layout description.
1526 static const int kValueOffset = HeapObject::kHeaderSize;
1527 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1528 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1529 // words within double numbers are endian dependent and they are set
1531 #if defined(V8_TARGET_LITTLE_ENDIAN)
1532 static const int kMantissaOffset = kValueOffset;
1533 static const int kExponentOffset = kValueOffset + 4;
1534 #elif defined(V8_TARGET_BIG_ENDIAN)
1535 static const int kMantissaOffset = kValueOffset + 4;
1536 static const int kExponentOffset = kValueOffset;
1538 #error Unknown byte ordering
1541 static const int kSize = kValueOffset + kDoubleSize;
1542 static const uint32_t kSignMask = 0x80000000u;
1543 static const uint32_t kExponentMask = 0x7ff00000u;
1544 static const uint32_t kMantissaMask = 0xfffffu;
1545 static const int kMantissaBits = 52;
1546 static const int kExponentBits = 11;
1547 static const int kExponentBias = 1023;
1548 static const int kExponentShift = 20;
1549 static const int kInfinityOrNanExponent =
1550 (kExponentMask >> kExponentShift) - kExponentBias;
1551 static const int kMantissaBitsInTopWord = 20;
1552 static const int kNonMantissaBitsInTopWord = 12;
1555 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1559 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1560 class Simd128Value : public HeapObject {
1562 DECLARE_CAST(Simd128Value)
1564 DECLARE_PRINTER(Simd128Value)
1565 DECLARE_VERIFIER(Simd128Value)
1567 // Equality operations.
1568 inline bool Equals(Simd128Value* that);
1570 // Checks that another instance is bit-wise equal.
1571 bool BitwiseEquals(const Simd128Value* other) const;
1572 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1573 uint32_t Hash() const;
1574 // Copies the 16 bytes of SIMD data to the destination address.
1575 void CopyBits(void* destination) const;
1577 // Layout description.
1578 static const int kValueOffset = HeapObject::kHeaderSize;
1579 static const int kSize = kValueOffset + kSimd128Size;
1582 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1586 // V has parameters (TYPE, Type, type, lane count, lane type)
1587 #define SIMD128_TYPES(V) \
1588 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1589 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1590 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1591 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1592 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1593 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1594 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1596 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1597 class Type final : public Simd128Value { \
1599 inline lane_type get_lane(int lane) const; \
1600 inline void set_lane(int lane, lane_type value); \
1602 DECLARE_CAST(Type) \
1604 DECLARE_PRINTER(Type) \
1606 inline bool Equals(Type* that); \
1609 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1611 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1612 #undef SIMD128_VALUE_CLASS
1615 enum EnsureElementsMode {
1616 DONT_ALLOW_DOUBLE_ELEMENTS,
1617 ALLOW_COPIED_DOUBLE_ELEMENTS,
1618 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1622 // Indicator for one component of an AccessorPair.
1623 enum AccessorComponent {
1629 // JSReceiver includes types on which properties can be defined, i.e.,
1630 // JSObject and JSProxy.
1631 class JSReceiver: public HeapObject {
1633 DECLARE_CAST(JSReceiver)
1635 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1636 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1637 Handle<JSReceiver> object, Handle<Name> name);
1638 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1640 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1641 Handle<JSReceiver> object, uint32_t index);
1642 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1643 Handle<JSReceiver> object, uint32_t index);
1645 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1646 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1647 Handle<JSReceiver> object, Handle<Name> name,
1648 LanguageMode language_mode = SLOPPY);
1649 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1650 Handle<JSReceiver> object, Handle<Name> name,
1651 LanguageMode language_mode = SLOPPY);
1652 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1653 LookupIterator* it, LanguageMode language_mode);
1654 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1655 Handle<JSReceiver> object, uint32_t index,
1656 LanguageMode language_mode = SLOPPY);
1658 // Tests for the fast common case for property enumeration.
1659 bool IsSimpleEnum();
1661 // Returns the class name ([[Class]] property in the specification).
1662 String* class_name();
1664 // Returns the constructor name (the name (possibly, inferred name) of the
1665 // function that was used to instantiate the object).
1666 String* constructor_name();
1668 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1669 Handle<JSReceiver> object, Handle<Name> name);
1670 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1671 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1673 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1674 Handle<JSReceiver> object, uint32_t index);
1675 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1676 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1678 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1679 LookupIterator* it);
1682 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1684 static Handle<Object> GetDataProperty(LookupIterator* it);
1687 // Retrieves a permanent object identity hash code. The undefined value might
1688 // be returned in case no hash was created yet.
1689 inline Object* GetIdentityHash();
1691 // Retrieves a permanent object identity hash code. May create and store a
1692 // hash code if needed and none exists.
1693 inline static Handle<Smi> GetOrCreateIdentityHash(
1694 Handle<JSReceiver> object);
1696 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1698 // Computes the enumerable keys for a JSObject. Used for implementing
1699 // "for (n in object) { }".
1700 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1701 Handle<JSReceiver> object,
1702 KeyCollectionType type);
1705 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1709 // The JSObject describes real heap allocated JavaScript objects with
1711 // Note that the map of JSObject changes during execution to enable inline
1713 class JSObject: public JSReceiver {
1715 // [properties]: Backing storage for properties.
1716 // properties is a FixedArray in the fast case and a Dictionary in the
1718 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1719 inline void initialize_properties();
1720 inline bool HasFastProperties();
1721 // Gets slow properties for non-global objects.
1722 inline NameDictionary* property_dictionary();
1723 // Gets global object properties.
1724 inline GlobalDictionary* global_dictionary();
1726 // [elements]: The elements (properties with names that are integers).
1728 // Elements can be in two general modes: fast and slow. Each mode
1729 // corrensponds to a set of object representations of elements that
1730 // have something in common.
1732 // In the fast mode elements is a FixedArray and so each element can
1733 // be quickly accessed. This fact is used in the generated code. The
1734 // elements array can have one of three maps in this mode:
1735 // fixed_array_map, sloppy_arguments_elements_map or
1736 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1737 // the elements array may be shared by a few objects and so before
1738 // writing to any element the array must be copied. Use
1739 // EnsureWritableFastElements in this case.
1741 // In the slow mode the elements is either a NumberDictionary, a
1742 // FixedArray parameter map for a (sloppy) arguments object.
1743 DECL_ACCESSORS(elements, FixedArrayBase)
1744 inline void initialize_elements();
1745 static void ResetElements(Handle<JSObject> object);
1746 static inline void SetMapAndElements(Handle<JSObject> object,
1748 Handle<FixedArrayBase> elements);
1749 inline ElementsKind GetElementsKind();
1750 ElementsAccessor* GetElementsAccessor();
1751 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1752 inline bool HasFastSmiElements();
1753 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1754 inline bool HasFastObjectElements();
1755 // Returns true if an object has elements of FAST_ELEMENTS or
1756 // FAST_SMI_ONLY_ELEMENTS.
1757 inline bool HasFastSmiOrObjectElements();
1758 // Returns true if an object has any of the fast elements kinds.
1759 inline bool HasFastElements();
1760 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1762 inline bool HasFastDoubleElements();
1763 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1765 inline bool HasFastHoleyElements();
1766 inline bool HasSloppyArgumentsElements();
1767 inline bool HasDictionaryElements();
1769 inline bool HasFixedTypedArrayElements();
1771 inline bool HasFixedUint8ClampedElements();
1772 inline bool HasFixedArrayElements();
1773 inline bool HasFixedInt8Elements();
1774 inline bool HasFixedUint8Elements();
1775 inline bool HasFixedInt16Elements();
1776 inline bool HasFixedUint16Elements();
1777 inline bool HasFixedInt32Elements();
1778 inline bool HasFixedUint32Elements();
1779 inline bool HasFixedFloat32Elements();
1780 inline bool HasFixedFloat64Elements();
1782 inline bool HasFastArgumentsElements();
1783 inline bool HasSlowArgumentsElements();
1784 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1786 // Requires: HasFastElements().
1787 static Handle<FixedArray> EnsureWritableFastElements(
1788 Handle<JSObject> object);
1790 // Collects elements starting at index 0.
1791 // Undefined values are placed after non-undefined values.
1792 // Returns the number of non-undefined values.
1793 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1795 // As PrepareElementsForSort, but only on objects where elements is
1796 // a dictionary, and it will stay a dictionary. Collates undefined and
1797 // unexisting elements below limit from position zero of the elements.
1798 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1801 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1802 LookupIterator* it, Handle<Object> value);
1804 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1805 // grant an exemption to ExecutableAccessor callbacks in some cases.
1806 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1808 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1809 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1810 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1812 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1813 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1814 PropertyAttributes attributes,
1815 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1817 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1818 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1819 PropertyAttributes attributes,
1820 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1822 // Equivalent to one of the above depending on whether |name| can be converted
1823 // to an array index.
1824 MUST_USE_RESULT static MaybeHandle<Object>
1825 DefinePropertyOrElementIgnoreAttributes(
1826 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1827 PropertyAttributes attributes = NONE,
1828 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1830 // Adds or reconfigures a property to attributes NONE. It will fail when it
1832 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1833 Handle<Object> value);
1835 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1836 Handle<Object> value, PropertyAttributes attributes);
1838 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1839 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1840 PropertyAttributes attributes);
1842 // Extend the receiver with a single fast property appeared first in the
1843 // passed map. This also extends the property backing store if necessary.
1844 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1846 // Migrates the given object to a map whose field representations are the
1847 // lowest upper bound of all known representations for that field.
1848 static void MigrateInstance(Handle<JSObject> instance);
1850 // Migrates the given object only if the target map is already available,
1851 // or returns false if such a map is not yet available.
1852 static bool TryMigrateInstance(Handle<JSObject> instance);
1854 // Sets the property value in a normalized object given (key, value, details).
1855 // Handles the special representation of JS global objects.
1856 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1857 Handle<Object> value,
1858 PropertyDetails details);
1859 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1860 Handle<Object> value,
1861 PropertyAttributes attributes);
1862 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1864 Handle<Object> value,
1865 PropertyAttributes attributes);
1867 static void OptimizeAsPrototype(Handle<JSObject> object,
1868 PrototypeOptimizationMode mode);
1869 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1870 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1871 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1872 static void InvalidatePrototypeChains(Map* map);
1874 // Alternative implementation of WeakFixedArray::NullCallback.
1875 class PrototypeRegistryCompactionCallback {
1877 static void Callback(Object* value, int old_index, int new_index);
1880 // Retrieve interceptors.
1881 InterceptorInfo* GetNamedInterceptor();
1882 InterceptorInfo* GetIndexedInterceptor();
1884 // Used from JSReceiver.
1885 MUST_USE_RESULT static Maybe<PropertyAttributes>
1886 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1887 MUST_USE_RESULT static Maybe<PropertyAttributes>
1888 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1890 // Retrieves an AccessorPair property from the given object. Might return
1891 // undefined if the property doesn't exist or is of a different kind.
1892 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1893 Handle<JSObject> object,
1895 AccessorComponent component);
1897 // Defines an AccessorPair property on the given object.
1898 // TODO(mstarzinger): Rename to SetAccessor().
1899 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1901 Handle<Object> getter,
1902 Handle<Object> setter,
1903 PropertyAttributes attributes);
1905 // Defines an AccessorInfo property on the given object.
1906 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1907 Handle<JSObject> object,
1908 Handle<AccessorInfo> info);
1910 // The result must be checked first for exceptions. If there's no exception,
1911 // the output parameter |done| indicates whether the interceptor has a result
1913 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1914 LookupIterator* it, bool* done);
1916 // Accessors for hidden properties object.
1918 // Hidden properties are not own properties of the object itself.
1919 // Instead they are stored in an auxiliary structure kept as an own
1920 // property with a special name Heap::hidden_string(). But if the
1921 // receiver is a JSGlobalProxy then the auxiliary object is a property
1922 // of its prototype, and if it's a detached proxy, then you can't have
1923 // hidden properties.
1925 // Sets a hidden property on this object. Returns this object if successful,
1926 // undefined if called on a detached proxy.
1927 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1929 Handle<Object> value);
1930 // Gets the value of a hidden property with the given key. Returns the hole
1931 // if the property doesn't exist (or if called on a detached proxy),
1932 // otherwise returns the value set for the key.
1933 Object* GetHiddenProperty(Handle<Name> key);
1934 // Deletes a hidden property. Deleting a non-existing property is
1935 // considered successful.
1936 static void DeleteHiddenProperty(Handle<JSObject> object,
1938 // Returns true if the object has a property with the hidden string as name.
1939 static bool HasHiddenProperties(Handle<JSObject> object);
1941 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1943 static void ValidateElements(Handle<JSObject> object);
1945 // Makes sure that this object can contain HeapObject as elements.
1946 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1948 // Makes sure that this object can contain the specified elements.
1949 static inline void EnsureCanContainElements(
1950 Handle<JSObject> object,
1953 EnsureElementsMode mode);
1954 static inline void EnsureCanContainElements(
1955 Handle<JSObject> object,
1956 Handle<FixedArrayBase> elements,
1958 EnsureElementsMode mode);
1959 static void EnsureCanContainElements(
1960 Handle<JSObject> object,
1961 Arguments* arguments,
1964 EnsureElementsMode mode);
1966 // Would we convert a fast elements array to dictionary mode given
1967 // an access at key?
1968 bool WouldConvertToSlowElements(uint32_t index);
1970 // Computes the new capacity when expanding the elements of a JSObject.
1971 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1972 // (old_capacity + 50%) + 16
1973 return old_capacity + (old_capacity >> 1) + 16;
1976 // These methods do not perform access checks!
1977 static void UpdateAllocationSite(Handle<JSObject> object,
1978 ElementsKind to_kind);
1980 // Lookup interceptors are used for handling properties controlled by host
1982 inline bool HasNamedInterceptor();
1983 inline bool HasIndexedInterceptor();
1985 // Computes the enumerable keys from interceptors. Used for debug mirrors and
1986 // by JSReceiver::GetKeys.
1987 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
1988 Handle<JSObject> object,
1989 Handle<JSReceiver> receiver);
1990 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
1991 Handle<JSObject> object,
1992 Handle<JSReceiver> receiver);
1994 // Support functions for v8 api (needed for correct interceptor behavior).
1995 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
1996 Handle<JSObject> object, Handle<Name> name);
1997 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
1998 Handle<JSObject> object, uint32_t index);
1999 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2000 Handle<JSObject> object, Handle<Name> name);
2002 // Get the header size for a JSObject. Used to compute the index of
2003 // internal fields as well as the number of internal fields.
2004 inline int GetHeaderSize();
2006 inline int GetInternalFieldCount();
2007 inline int GetInternalFieldOffset(int index);
2008 inline Object* GetInternalField(int index);
2009 inline void SetInternalField(int index, Object* value);
2010 inline void SetInternalField(int index, Smi* value);
2012 // Returns the number of properties on this object filtering out properties
2013 // with the specified attributes (ignoring interceptors).
2014 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2015 // Fill in details for properties into storage starting at the specified
2016 // index. Returns the number of properties added.
2017 int GetOwnPropertyNames(FixedArray* storage, int index,
2018 PropertyAttributes filter = NONE);
2020 // Returns the number of properties on this object filtering out properties
2021 // with the specified attributes (ignoring interceptors).
2022 int NumberOfOwnElements(PropertyAttributes filter);
2023 // Returns the number of enumerable elements (ignoring interceptors).
2024 int NumberOfEnumElements();
2025 // Returns the number of elements on this object filtering out elements
2026 // with the specified attributes (ignoring interceptors).
2027 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2028 // Count and fill in the enumerable elements into storage.
2029 // (storage->length() == NumberOfEnumElements()).
2030 // If storage is NULL, will count the elements without adding
2031 // them to any storage.
2032 // Returns the number of enumerable elements.
2033 int GetEnumElementKeys(FixedArray* storage);
2035 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2038 // Returns a new map with all transitions dropped from the object's current
2039 // map and the ElementsKind set.
2040 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2041 ElementsKind to_kind);
2042 static void TransitionElementsKind(Handle<JSObject> object,
2043 ElementsKind to_kind);
2045 // Always use this to migrate an object to a new map.
2046 // |expected_additional_properties| is only used for fast-to-slow transitions
2047 // and ignored otherwise.
2048 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2049 int expected_additional_properties = 0);
2051 // Convert the object to use the canonical dictionary
2052 // representation. If the object is expected to have additional properties
2053 // added this number can be indicated to have the backing store allocated to
2054 // an initial capacity for holding these properties.
2055 static void NormalizeProperties(Handle<JSObject> object,
2056 PropertyNormalizationMode mode,
2057 int expected_additional_properties,
2058 const char* reason);
2060 // Convert and update the elements backing store to be a
2061 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2062 static Handle<SeededNumberDictionary> NormalizeElements(
2063 Handle<JSObject> object);
2065 void RequireSlowElements(SeededNumberDictionary* dictionary);
2067 // Transform slow named properties to fast variants.
2068 static void MigrateSlowToFast(Handle<JSObject> object,
2069 int unused_property_fields, const char* reason);
2071 inline bool IsUnboxedDoubleField(FieldIndex index);
2073 // Access fast-case object properties at index.
2074 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2075 Representation representation,
2077 inline Object* RawFastPropertyAt(FieldIndex index);
2078 inline double RawFastDoublePropertyAt(FieldIndex index);
2080 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2081 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2082 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2083 inline void WriteToField(int descriptor, Object* value);
2085 // Access to in object properties.
2086 inline int GetInObjectPropertyOffset(int index);
2087 inline Object* InObjectPropertyAt(int index);
2088 inline Object* InObjectPropertyAtPut(int index,
2090 WriteBarrierMode mode
2091 = UPDATE_WRITE_BARRIER);
2093 // Set the object's prototype (only JSReceiver and null are allowed values).
2094 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2095 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2097 // Initializes the body after properties slot, properties slot is
2098 // initialized by set_properties. Fill the pre-allocated fields with
2099 // pre_allocated_value and the rest with filler_value.
2100 // Note: this call does not update write barrier, the caller is responsible
2101 // to ensure that |filler_value| can be collected without WB here.
2102 inline void InitializeBody(Map* map,
2103 Object* pre_allocated_value,
2104 Object* filler_value);
2106 // Check whether this object references another object
2107 bool ReferencesObject(Object* obj);
2109 // Disalow further properties to be added to the oject.
2110 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2111 Handle<JSObject> object);
2113 bool IsExtensible();
2116 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2118 // ES5 Object.freeze
2119 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2121 // Called the first time an object is observed with ES7 Object.observe.
2122 static void SetObserved(Handle<JSObject> object);
2125 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2127 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2128 Handle<JSObject> object,
2129 AllocationSiteUsageContext* site_context,
2130 DeepCopyHints hints = kNoHints);
2131 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2132 Handle<JSObject> object,
2133 AllocationSiteCreationContext* site_context);
2135 DECLARE_CAST(JSObject)
2137 // Dispatched behavior.
2138 void JSObjectShortPrint(StringStream* accumulator);
2139 DECLARE_PRINTER(JSObject)
2140 DECLARE_VERIFIER(JSObject)
2142 void PrintProperties(std::ostream& os); // NOLINT
2143 void PrintElements(std::ostream& os); // NOLINT
2145 #if defined(DEBUG) || defined(OBJECT_PRINT)
2146 void PrintTransitions(std::ostream& os); // NOLINT
2149 static void PrintElementsTransition(
2150 FILE* file, Handle<JSObject> object,
2151 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2152 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2154 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2157 // Structure for collecting spill information about JSObjects.
2158 class SpillInformation {
2162 int number_of_objects_;
2163 int number_of_objects_with_fast_properties_;
2164 int number_of_objects_with_fast_elements_;
2165 int number_of_fast_used_fields_;
2166 int number_of_fast_unused_fields_;
2167 int number_of_slow_used_properties_;
2168 int number_of_slow_unused_properties_;
2169 int number_of_fast_used_elements_;
2170 int number_of_fast_unused_elements_;
2171 int number_of_slow_used_elements_;
2172 int number_of_slow_unused_elements_;
2175 void IncrementSpillStatistics(SpillInformation* info);
2179 // If a GC was caused while constructing this object, the elements pointer
2180 // may point to a one pointer filler map. The object won't be rooted, but
2181 // our heap verification code could stumble across it.
2182 bool ElementsAreSafeToExamine();
2185 Object* SlowReverseLookup(Object* value);
2187 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2188 // Also maximal value of JSArray's length property.
2189 static const uint32_t kMaxElementCount = 0xffffffffu;
2191 // Constants for heuristics controlling conversion of fast elements
2192 // to slow elements.
2194 // Maximal gap that can be introduced by adding an element beyond
2195 // the current elements length.
2196 static const uint32_t kMaxGap = 1024;
2198 // Maximal length of fast elements array that won't be checked for
2199 // being dense enough on expansion.
2200 static const int kMaxUncheckedFastElementsLength = 5000;
2202 // Same as above but for old arrays. This limit is more strict. We
2203 // don't want to be wasteful with long lived objects.
2204 static const int kMaxUncheckedOldFastElementsLength = 500;
2206 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2207 // permissible values (see the DCHECK in heap.cc).
2208 static const int kInitialMaxFastElementArray = 100000;
2210 // This constant applies only to the initial map of "global.Object" and
2211 // not to arbitrary other JSObject maps.
2212 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2214 static const int kMaxInstanceSize = 255 * kPointerSize;
2215 // When extending the backing storage for property values, we increase
2216 // its size by more than the 1 entry necessary, so sequentially adding fields
2217 // to the same object requires fewer allocations and copies.
2218 static const int kFieldsAdded = 3;
2220 // Layout description.
2221 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2222 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2223 static const int kHeaderSize = kElementsOffset + kPointerSize;
2225 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2227 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2229 static inline int SizeOf(Map* map, HeapObject* object);
2232 Context* GetCreationContext();
2234 // Enqueue change record for Object.observe. May cause GC.
2235 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2236 Handle<JSObject> object, const char* type, Handle<Name> name,
2237 Handle<Object> old_value);
2239 // Gets the number of currently used elements.
2240 int GetFastElementsUsage();
2242 // Deletes an existing named property in a normalized object.
2243 static void DeleteNormalizedProperty(Handle<JSObject> object,
2244 Handle<Name> name, int entry);
2246 static bool AllCanRead(LookupIterator* it);
2247 static bool AllCanWrite(LookupIterator* it);
2250 friend class JSReceiver;
2251 friend class Object;
2253 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2254 static void MigrateFastToSlow(Handle<JSObject> object,
2255 Handle<Map> new_map,
2256 int expected_additional_properties);
2258 // Used from Object::GetProperty().
2259 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2260 LookupIterator* it);
2262 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2263 LookupIterator* it, Handle<Object> value);
2265 // Add a property to a slow-case object.
2266 static void AddSlowProperty(Handle<JSObject> object,
2268 Handle<Object> value,
2269 PropertyAttributes attributes);
2271 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2272 LookupIterator* it);
2274 bool ReferencesObjectFromElements(FixedArray* elements,
2278 // Return the hash table backing store or the inline stored identity hash,
2279 // whatever is found.
2280 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2282 // Return the hash table backing store for hidden properties. If there is no
2283 // backing store, allocate one.
2284 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2285 Handle<JSObject> object);
2287 // Set the hidden property backing store to either a hash table or
2288 // the inline-stored identity hash.
2289 static Handle<Object> SetHiddenPropertiesHashTable(
2290 Handle<JSObject> object,
2291 Handle<Object> value);
2293 MUST_USE_RESULT Object* GetIdentityHash();
2295 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2297 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2298 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2300 // Helper for fast versions of preventExtensions, seal, and freeze.
2301 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2302 template <PropertyAttributes attrs>
2303 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2304 Handle<JSObject> object);
2306 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2310 // Common superclass for FixedArrays that allow implementations to share
2311 // common accessors and some code paths.
2312 class FixedArrayBase: public HeapObject {
2314 // [length]: length of the array.
2315 inline int length() const;
2316 inline void set_length(int value);
2318 // Get and set the length using acquire loads and release stores.
2319 inline int synchronized_length() const;
2320 inline void synchronized_set_length(int value);
2322 DECLARE_CAST(FixedArrayBase)
2324 // Layout description.
2325 // Length is smi tagged when it is stored.
2326 static const int kLengthOffset = HeapObject::kHeaderSize;
2327 static const int kHeaderSize = kLengthOffset + kPointerSize;
2331 class FixedDoubleArray;
2332 class IncrementalMarking;
2335 // FixedArray describes fixed-sized arrays with element type Object*.
2336 class FixedArray: public FixedArrayBase {
2338 // Setter and getter for elements.
2339 inline Object* get(int index) const;
2340 void SetValue(uint32_t index, Object* value);
2341 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2342 // Setter that uses write barrier.
2343 inline void set(int index, Object* value);
2344 inline bool is_the_hole(int index);
2346 // Setter that doesn't need write barrier.
2347 inline void set(int index, Smi* value);
2348 // Setter with explicit barrier mode.
2349 inline void set(int index, Object* value, WriteBarrierMode mode);
2351 // Setters for frequently used oddballs located in old space.
2352 inline void set_undefined(int index);
2353 inline void set_null(int index);
2354 inline void set_the_hole(int index);
2356 inline Object** GetFirstElementAddress();
2357 inline bool ContainsOnlySmisOrHoles();
2359 // Gives access to raw memory which stores the array's data.
2360 inline Object** data_start();
2362 inline void FillWithHoles(int from, int to);
2364 // Shrink length and insert filler objects.
2365 void Shrink(int length);
2367 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2369 // Add the elements of a JSArray to this FixedArray.
2370 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2371 Handle<FixedArray> content, Handle<JSObject> array,
2372 KeyFilter filter = ALL_KEYS);
2374 // Computes the union of keys and return the result.
2375 // Used for implementing "for (n in object) { }"
2376 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2377 Handle<FixedArray> first,
2378 Handle<FixedArray> second);
2380 // Copy a sub array from the receiver to dest.
2381 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2383 // Garbage collection support.
2384 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2386 // Code Generation support.
2387 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2389 // Garbage collection support.
2390 inline Object** RawFieldOfElementAt(int index);
2392 DECLARE_CAST(FixedArray)
2394 // Maximal allowed size, in bytes, of a single FixedArray.
2395 // Prevents overflowing size computations, as well as extreme memory
2397 static const int kMaxSize = 128 * MB * kPointerSize;
2398 // Maximally allowed length of a FixedArray.
2399 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2401 // Dispatched behavior.
2402 DECLARE_PRINTER(FixedArray)
2403 DECLARE_VERIFIER(FixedArray)
2405 // Checks if two FixedArrays have identical contents.
2406 bool IsEqualTo(FixedArray* other);
2409 // Swap two elements in a pair of arrays. If this array and the
2410 // numbers array are the same object, the elements are only swapped
2412 void SwapPairs(FixedArray* numbers, int i, int j);
2414 // Sort prefix of this array and the numbers array as pairs wrt. the
2415 // numbers. If the numbers array and the this array are the same
2416 // object, the prefix of this array is sorted.
2417 void SortPairs(FixedArray* numbers, uint32_t len);
2419 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2421 static inline int SizeOf(Map* map, HeapObject* object);
2425 // Set operation on FixedArray without using write barriers. Can
2426 // only be used for storing old space objects or smis.
2427 static inline void NoWriteBarrierSet(FixedArray* array,
2431 // Set operation on FixedArray without incremental write barrier. Can
2432 // only be used if the object is guaranteed to be white (whiteness witness
2434 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2439 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2441 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2445 // FixedDoubleArray describes fixed-sized arrays with element type double.
2446 class FixedDoubleArray: public FixedArrayBase {
2448 // Setter and getter for elements.
2449 inline double get_scalar(int index);
2450 inline uint64_t get_representation(int index);
2451 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2452 // This accessor has to get a Number as |value|.
2453 void SetValue(uint32_t index, Object* value);
2454 inline void set(int index, double value);
2455 inline void set_the_hole(int index);
2457 // Checking for the hole.
2458 inline bool is_the_hole(int index);
2460 // Garbage collection support.
2461 inline static int SizeFor(int length) {
2462 return kHeaderSize + length * kDoubleSize;
2465 // Gives access to raw memory which stores the array's data.
2466 inline double* data_start();
2468 inline void FillWithHoles(int from, int to);
2470 // Code Generation support.
2471 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2473 DECLARE_CAST(FixedDoubleArray)
2475 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2476 // Prevents overflowing size computations, as well as extreme memory
2478 static const int kMaxSize = 512 * MB;
2479 // Maximally allowed length of a FixedArray.
2480 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2482 // Dispatched behavior.
2483 DECLARE_PRINTER(FixedDoubleArray)
2484 DECLARE_VERIFIER(FixedDoubleArray)
2487 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2491 class WeakFixedArray : public FixedArray {
2493 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2494 // This function does not check if the value exists already, callers must
2495 // ensure this themselves if necessary.
2496 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2497 Handle<HeapObject> value,
2498 int* assigned_index = NULL);
2500 // Returns true if an entry was found and removed.
2501 bool Remove(Handle<HeapObject> value);
2503 class NullCallback {
2505 static void Callback(Object* value, int old_index, int new_index) {}
2508 template <class CompactionCallback>
2511 inline Object* Get(int index) const;
2512 inline void Clear(int index);
2513 inline int Length() const;
2515 inline bool IsEmptySlot(int index) const;
2516 static Object* Empty() { return Smi::FromInt(0); }
2520 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2521 void Reset(Object* maybe_array);
2528 WeakFixedArray* list_;
2530 int last_used_index_;
2531 DisallowHeapAllocation no_gc_;
2533 DISALLOW_COPY_AND_ASSIGN(Iterator);
2536 DECLARE_CAST(WeakFixedArray)
2539 static const int kLastUsedIndexIndex = 0;
2540 static const int kFirstIndex = 1;
2542 static Handle<WeakFixedArray> Allocate(
2543 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2545 static void Set(Handle<WeakFixedArray> array, int index,
2546 Handle<HeapObject> value);
2547 inline void clear(int index);
2549 inline int last_used_index() const;
2550 inline void set_last_used_index(int index);
2552 // Disallow inherited setters.
2553 void set(int index, Smi* value);
2554 void set(int index, Object* value);
2555 void set(int index, Object* value, WriteBarrierMode mode);
2556 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2560 // Generic array grows dynamically with O(1) amortized insertion.
2561 class ArrayList : public FixedArray {
2565 // Use this if GC can delete elements from the array.
2566 kReloadLengthAfterAllocation,
2568 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2569 AddMode mode = kNone);
2570 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2571 Handle<Object> obj2, AddMode = kNone);
2572 inline int Length();
2573 inline void SetLength(int length);
2574 inline Object* Get(int index);
2575 inline Object** Slot(int index);
2576 inline void Set(int index, Object* obj);
2577 inline void Clear(int index, Object* undefined);
2578 DECLARE_CAST(ArrayList)
2581 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2582 static const int kLengthIndex = 0;
2583 static const int kFirstIndex = 1;
2584 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2588 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2589 // The format of the these objects is:
2590 // [0]: Number of descriptors
2591 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2592 // [0]: pointer to fixed array with enum cache
2593 // [1]: either Smi(0) or pointer to fixed array with indices
2595 // [2 + number of descriptors * kDescriptorSize]: start of slack
2596 class DescriptorArray: public FixedArray {
2598 // Returns true for both shared empty_descriptor_array and for smis, which the
2599 // map uses to encode additional bit fields when the descriptor array is not
2601 inline bool IsEmpty();
2603 // Returns the number of descriptors in the array.
2604 inline int number_of_descriptors();
2606 inline int number_of_descriptors_storage();
2608 inline int NumberOfSlackDescriptors();
2610 inline void SetNumberOfDescriptors(int number_of_descriptors);
2611 inline int number_of_entries();
2613 inline bool HasEnumCache();
2615 inline void CopyEnumCacheFrom(DescriptorArray* array);
2617 inline FixedArray* GetEnumCache();
2619 inline bool HasEnumIndicesCache();
2621 inline FixedArray* GetEnumIndicesCache();
2623 inline Object** GetEnumCacheSlot();
2625 void ClearEnumCache();
2627 // Initialize or change the enum cache,
2628 // using the supplied storage for the small "bridge".
2629 void SetEnumCache(FixedArray* bridge_storage,
2630 FixedArray* new_cache,
2631 Object* new_index_cache);
2633 bool CanHoldValue(int descriptor, Object* value);
2635 // Accessors for fetching instance descriptor at descriptor number.
2636 inline Name* GetKey(int descriptor_number);
2637 inline Object** GetKeySlot(int descriptor_number);
2638 inline Object* GetValue(int descriptor_number);
2639 inline void SetValue(int descriptor_number, Object* value);
2640 inline Object** GetValueSlot(int descriptor_number);
2641 static inline int GetValueOffset(int descriptor_number);
2642 inline Object** GetDescriptorStartSlot(int descriptor_number);
2643 inline Object** GetDescriptorEndSlot(int descriptor_number);
2644 inline PropertyDetails GetDetails(int descriptor_number);
2645 inline PropertyType GetType(int descriptor_number);
2646 inline int GetFieldIndex(int descriptor_number);
2647 inline HeapType* GetFieldType(int descriptor_number);
2648 inline Object* GetConstant(int descriptor_number);
2649 inline Object* GetCallbacksObject(int descriptor_number);
2650 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2652 inline Name* GetSortedKey(int descriptor_number);
2653 inline int GetSortedKeyIndex(int descriptor_number);
2654 inline void SetSortedKey(int pointer, int descriptor_number);
2655 inline void SetRepresentation(int descriptor_number,
2656 Representation representation);
2658 // Accessor for complete descriptor.
2659 inline void Get(int descriptor_number, Descriptor* desc);
2660 inline void Set(int descriptor_number, Descriptor* desc);
2661 void Replace(int descriptor_number, Descriptor* descriptor);
2663 // Append automatically sets the enumeration index. This should only be used
2664 // to add descriptors in bulk at the end, followed by sorting the descriptor
2666 inline void Append(Descriptor* desc);
2668 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2669 int enumeration_index,
2672 static Handle<DescriptorArray> CopyUpToAddAttributes(
2673 Handle<DescriptorArray> desc,
2674 int enumeration_index,
2675 PropertyAttributes attributes,
2678 // Sort the instance descriptors by the hash codes of their keys.
2681 // Search the instance descriptors for given name.
2682 INLINE(int Search(Name* name, int number_of_own_descriptors));
2684 // As the above, but uses DescriptorLookupCache and updates it when
2686 INLINE(int SearchWithCache(Name* name, Map* map));
2688 // Allocates a DescriptorArray, but returns the singleton
2689 // empty descriptor array object if number_of_descriptors is 0.
2690 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2691 int number_of_descriptors,
2694 DECLARE_CAST(DescriptorArray)
2696 // Constant for denoting key was not found.
2697 static const int kNotFound = -1;
2699 static const int kDescriptorLengthIndex = 0;
2700 static const int kEnumCacheIndex = 1;
2701 static const int kFirstIndex = 2;
2703 // The length of the "bridge" to the enum cache.
2704 static const int kEnumCacheBridgeLength = 2;
2705 static const int kEnumCacheBridgeCacheIndex = 0;
2706 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2708 // Layout description.
2709 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2710 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2711 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2713 // Layout description for the bridge array.
2714 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2716 // Layout of descriptor.
2717 static const int kDescriptorKey = 0;
2718 static const int kDescriptorDetails = 1;
2719 static const int kDescriptorValue = 2;
2720 static const int kDescriptorSize = 3;
2722 #if defined(DEBUG) || defined(OBJECT_PRINT)
2723 // For our gdb macros, we should perhaps change these in the future.
2726 // Print all the descriptors.
2727 void PrintDescriptors(std::ostream& os); // NOLINT
2731 // Is the descriptor array sorted and without duplicates?
2732 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2734 // Is the descriptor array consistent with the back pointers in targets?
2735 bool IsConsistentWithBackPointers(Map* current_map);
2737 // Are two DescriptorArrays equal?
2738 bool IsEqualTo(DescriptorArray* other);
2741 // Returns the fixed array length required to hold number_of_descriptors
2743 static int LengthFor(int number_of_descriptors) {
2744 return ToKeyIndex(number_of_descriptors);
2748 // WhitenessWitness is used to prove that a descriptor array is white
2749 // (unmarked), so incremental write barriers can be skipped because the
2750 // marking invariant cannot be broken and slots pointing into evacuation
2751 // candidates will be discovered when the object is scanned. A witness is
2752 // always stack-allocated right after creating an array. By allocating a
2753 // witness, incremental marking is globally disabled. The witness is then
2754 // passed along wherever needed to statically prove that the array is known to
2756 class WhitenessWitness {
2758 inline explicit WhitenessWitness(DescriptorArray* array);
2759 inline ~WhitenessWitness();
2762 IncrementalMarking* marking_;
2765 // An entry in a DescriptorArray, represented as an (array, index) pair.
2768 inline explicit Entry(DescriptorArray* descs, int index) :
2769 descs_(descs), index_(index) { }
2771 inline PropertyType type();
2772 inline Object* GetCallbackObject();
2775 DescriptorArray* descs_;
2779 // Conversion from descriptor number to array indices.
2780 static int ToKeyIndex(int descriptor_number) {
2781 return kFirstIndex +
2782 (descriptor_number * kDescriptorSize) +
2786 static int ToDetailsIndex(int descriptor_number) {
2787 return kFirstIndex +
2788 (descriptor_number * kDescriptorSize) +
2792 static int ToValueIndex(int descriptor_number) {
2793 return kFirstIndex +
2794 (descriptor_number * kDescriptorSize) +
2798 // Transfer a complete descriptor from the src descriptor array to this
2799 // descriptor array.
2800 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2802 inline void Set(int descriptor_number,
2804 const WhitenessWitness&);
2806 // Swap first and second descriptor.
2807 inline void SwapSortedKeys(int first, int second);
2809 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2813 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2815 template <SearchMode search_mode, typename T>
2816 inline int Search(T* array, Name* name, int valid_entries = 0,
2817 int* out_insertion_index = NULL);
2820 // HashTable is a subclass of FixedArray that implements a hash table
2821 // that uses open addressing and quadratic probing.
2823 // In order for the quadratic probing to work, elements that have not
2824 // yet been used and elements that have been deleted are
2825 // distinguished. Probing continues when deleted elements are
2826 // encountered and stops when unused elements are encountered.
2828 // - Elements with key == undefined have not been used yet.
2829 // - Elements with key == the_hole have been deleted.
2831 // The hash table class is parameterized with a Shape and a Key.
2832 // Shape must be a class with the following interface:
2833 // class ExampleShape {
2835 // // Tells whether key matches other.
2836 // static bool IsMatch(Key key, Object* other);
2837 // // Returns the hash value for key.
2838 // static uint32_t Hash(Key key);
2839 // // Returns the hash value for object.
2840 // static uint32_t HashForObject(Key key, Object* object);
2841 // // Convert key to an object.
2842 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2843 // // The prefix size indicates number of elements in the beginning
2844 // // of the backing storage.
2845 // static const int kPrefixSize = ..;
2846 // // The Element size indicates number of elements per entry.
2847 // static const int kEntrySize = ..;
2849 // The prefix size indicates an amount of memory in the
2850 // beginning of the backing storage that can be used for non-element
2851 // information by subclasses.
2853 template<typename Key>
2856 static const bool UsesSeed = false;
2857 static uint32_t Hash(Key key) { return 0; }
2858 static uint32_t SeededHash(Key key, uint32_t seed) {
2862 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2863 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2865 return HashForObject(key, object);
2870 class HashTableBase : public FixedArray {
2872 // Returns the number of elements in the hash table.
2873 inline int NumberOfElements();
2875 // Returns the number of deleted elements in the hash table.
2876 inline int NumberOfDeletedElements();
2878 // Returns the capacity of the hash table.
2879 inline int Capacity();
2881 // ElementAdded should be called whenever an element is added to a
2883 inline void ElementAdded();
2885 // ElementRemoved should be called whenever an element is removed from
2887 inline void ElementRemoved();
2888 inline void ElementsRemoved(int n);
2890 // Computes the required capacity for a table holding the given
2891 // number of elements. May be more than HashTable::kMaxCapacity.
2892 static inline int ComputeCapacity(int at_least_space_for);
2894 // Tells whether k is a real key. The hole and undefined are not allowed
2895 // as keys and can be used to indicate missing or deleted elements.
2896 inline bool IsKey(Object* k);
2898 // Compute the probe offset (quadratic probing).
2899 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2900 return (n + n * n) >> 1;
2903 static const int kNumberOfElementsIndex = 0;
2904 static const int kNumberOfDeletedElementsIndex = 1;
2905 static const int kCapacityIndex = 2;
2906 static const int kPrefixStartIndex = 3;
2908 // Constant used for denoting a absent entry.
2909 static const int kNotFound = -1;
2912 // Update the number of elements in the hash table.
2913 inline void SetNumberOfElements(int nof);
2915 // Update the number of deleted elements in the hash table.
2916 inline void SetNumberOfDeletedElements(int nod);
2918 // Returns probe entry.
2919 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2920 DCHECK(base::bits::IsPowerOfTwo32(size));
2921 return (hash + GetProbeOffset(number)) & (size - 1);
2924 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2925 return hash & (size - 1);
2928 inline static uint32_t NextProbe(
2929 uint32_t last, uint32_t number, uint32_t size) {
2930 return (last + number) & (size - 1);
2935 template <typename Derived, typename Shape, typename Key>
2936 class HashTable : public HashTableBase {
2939 inline uint32_t Hash(Key key) {
2940 if (Shape::UsesSeed) {
2941 return Shape::SeededHash(key, GetHeap()->HashSeed());
2943 return Shape::Hash(key);
2947 inline uint32_t HashForObject(Key key, Object* object) {
2948 if (Shape::UsesSeed) {
2949 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2951 return Shape::HashForObject(key, object);
2955 // Returns a new HashTable object.
2956 MUST_USE_RESULT static Handle<Derived> New(
2957 Isolate* isolate, int at_least_space_for,
2958 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2959 PretenureFlag pretenure = NOT_TENURED);
2961 DECLARE_CAST(HashTable)
2963 // Garbage collection support.
2964 void IteratePrefix(ObjectVisitor* visitor);
2965 void IterateElements(ObjectVisitor* visitor);
2967 // Find entry for key otherwise return kNotFound.
2968 inline int FindEntry(Key key);
2969 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2970 int FindEntry(Isolate* isolate, Key key);
2972 // Rehashes the table in-place.
2973 void Rehash(Key key);
2975 // Returns the key at entry.
2976 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2978 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
2979 static const int kEntrySize = Shape::kEntrySize;
2980 static const int kElementsStartOffset =
2981 kHeaderSize + kElementsStartIndex * kPointerSize;
2982 static const int kCapacityOffset =
2983 kHeaderSize + kCapacityIndex * kPointerSize;
2985 // Returns the index for an entry (of the key)
2986 static inline int EntryToIndex(int entry) {
2987 return (entry * kEntrySize) + kElementsStartIndex;
2991 friend class ObjectHashTable;
2993 // Find the entry at which to insert element with the given key that
2994 // has the given hash value.
2995 uint32_t FindInsertionEntry(uint32_t hash);
2997 // Attempt to shrink hash table after removal of key.
2998 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3000 // Ensure enough space for n additional elements.
3001 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3002 Handle<Derived> table,
3005 PretenureFlag pretenure = NOT_TENURED);
3007 // Sets the capacity of the hash table.
3008 void SetCapacity(int capacity) {
3009 // To scale a computed hash code to fit within the hash table, we
3010 // use bit-wise AND with a mask, so the capacity must be positive
3012 DCHECK(capacity > 0);
3013 DCHECK(capacity <= kMaxCapacity);
3014 set(kCapacityIndex, Smi::FromInt(capacity));
3017 // Maximal capacity of HashTable. Based on maximal length of underlying
3018 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3020 static const int kMaxCapacity =
3021 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3024 // Returns _expected_ if one of entries given by the first _probe_ probes is
3025 // equal to _expected_. Otherwise, returns the entry given by the probe
3027 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3029 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3031 // Rehashes this hash-table into the new table.
3032 void Rehash(Handle<Derived> new_table, Key key);
3036 // HashTableKey is an abstract superclass for virtual key behavior.
3037 class HashTableKey {
3039 // Returns whether the other object matches this key.
3040 virtual bool IsMatch(Object* other) = 0;
3041 // Returns the hash value for this key.
3042 virtual uint32_t Hash() = 0;
3043 // Returns the hash value for object.
3044 virtual uint32_t HashForObject(Object* key) = 0;
3045 // Returns the key object for storing into the hash table.
3046 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3048 virtual ~HashTableKey() {}
3052 class StringTableShape : public BaseShape<HashTableKey*> {
3054 static inline bool IsMatch(HashTableKey* key, Object* value) {
3055 return key->IsMatch(value);
3058 static inline uint32_t Hash(HashTableKey* key) {
3062 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3063 return key->HashForObject(object);
3066 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3068 static const int kPrefixSize = 0;
3069 static const int kEntrySize = 1;
3072 class SeqOneByteString;
3076 // No special elements in the prefix and the element size is 1
3077 // because only the string itself (the key) needs to be stored.
3078 class StringTable: public HashTable<StringTable,
3082 // Find string in the string table. If it is not there yet, it is
3083 // added. The return value is the string found.
3084 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3085 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3086 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3088 // Tries to internalize given string and returns string handle on success
3089 // or an empty handle otherwise.
3090 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3092 Handle<String> string);
3094 // Looks up a string that is equal to the given string and returns
3095 // string handle if it is found, or an empty handle otherwise.
3096 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3098 Handle<String> str);
3099 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3104 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3106 DECLARE_CAST(StringTable)
3109 template <bool seq_one_byte>
3110 friend class JsonParser;
3112 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3116 template <typename Derived, typename Shape, typename Key>
3117 class Dictionary: public HashTable<Derived, Shape, Key> {
3118 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3121 // Returns the value at entry.
3122 Object* ValueAt(int entry) {
3123 return this->get(Derived::EntryToIndex(entry) + 1);
3126 // Set the value for entry.
3127 void ValueAtPut(int entry, Object* value) {
3128 this->set(Derived::EntryToIndex(entry) + 1, value);
3131 // Returns the property details for the property at entry.
3132 PropertyDetails DetailsAt(int entry) {
3133 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3136 // Set the details for entry.
3137 void DetailsAtPut(int entry, PropertyDetails value) {
3138 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3141 // Returns true if property at given entry is deleted.
3142 bool IsDeleted(int entry) {
3143 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3146 // Delete a property from the dictionary.
3147 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3149 // Attempt to shrink the dictionary after deletion of key.
3150 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3151 Handle<Derived> dictionary,
3153 return DerivedHashTable::Shrink(dictionary, key);
3157 // TODO(dcarney): templatize or move to SeededNumberDictionary
3158 void CopyValuesTo(FixedArray* elements);
3160 // Returns the number of elements in the dictionary filtering out properties
3161 // with the specified attributes.
3162 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3164 // Returns the number of enumerable elements in the dictionary.
3165 int NumberOfEnumElements() {
3166 return NumberOfElementsFilterAttributes(
3167 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3170 // Returns true if the dictionary contains any elements that are non-writable,
3171 // non-configurable, non-enumerable, or have getters/setters.
3172 bool HasComplexElements();
3174 enum SortMode { UNSORTED, SORTED };
3176 // Fill in details for properties into storage.
3177 // Returns the number of properties added.
3178 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3179 SortMode sort_mode);
3181 // Copies enumerable keys to preallocated fixed array.
3182 void CopyEnumKeysTo(FixedArray* storage);
3184 // Accessors for next enumeration index.
3185 void SetNextEnumerationIndex(int index) {
3187 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3190 int NextEnumerationIndex() {
3191 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3194 // Creates a new dictionary.
3195 MUST_USE_RESULT static Handle<Derived> New(
3197 int at_least_space_for,
3198 PretenureFlag pretenure = NOT_TENURED);
3200 // Ensure enough space for n additional elements.
3201 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3204 void Print(std::ostream& os); // NOLINT
3206 // Returns the key (slow).
3207 Object* SlowReverseLookup(Object* value);
3209 // Sets the entry to (key, value) pair.
3210 inline void SetEntry(int entry,
3212 Handle<Object> value);
3213 inline void SetEntry(int entry,
3215 Handle<Object> value,
3216 PropertyDetails details);
3218 MUST_USE_RESULT static Handle<Derived> Add(
3219 Handle<Derived> dictionary,
3221 Handle<Object> value,
3222 PropertyDetails details);
3224 // Returns iteration indices array for the |dictionary|.
3225 // Values are direct indices in the |HashTable| array.
3226 static Handle<FixedArray> BuildIterationIndicesArray(
3227 Handle<Derived> dictionary);
3230 // Generic at put operation.
3231 MUST_USE_RESULT static Handle<Derived> AtPut(
3232 Handle<Derived> dictionary,
3234 Handle<Object> value);
3236 // Add entry to dictionary.
3237 static void AddEntry(
3238 Handle<Derived> dictionary,
3240 Handle<Object> value,
3241 PropertyDetails details,
3244 // Generate new enumeration indices to avoid enumeration index overflow.
3245 // Returns iteration indices array for the |dictionary|.
3246 static Handle<FixedArray> GenerateNewEnumerationIndices(
3247 Handle<Derived> dictionary);
3248 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3249 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3253 template <typename Derived, typename Shape>
3254 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3255 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3258 // Find entry for key, otherwise return kNotFound. Optimized version of
3259 // HashTable::FindEntry.
3260 int FindEntry(Handle<Name> key);
3264 template <typename Key>
3265 class BaseDictionaryShape : public BaseShape<Key> {
3267 template <typename Dictionary>
3268 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3269 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3270 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3271 return PropertyDetails(
3272 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3275 template <typename Dictionary>
3276 static inline void DetailsAtPut(Dictionary* dict, int entry,
3277 PropertyDetails value) {
3278 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3279 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3282 template <typename Dictionary>
3283 static bool IsDeleted(Dictionary* dict, int entry) {
3287 template <typename Dictionary>
3288 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3289 Handle<Object> value, PropertyDetails details);
3293 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3295 static inline bool IsMatch(Handle<Name> key, Object* other);
3296 static inline uint32_t Hash(Handle<Name> key);
3297 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3298 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3299 static const int kPrefixSize = 2;
3300 static const int kEntrySize = 3;
3301 static const bool kIsEnumerable = true;
3305 class NameDictionary
3306 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3307 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3311 DECLARE_CAST(NameDictionary)
3313 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3314 Handle<NameDictionary> dictionary);
3318 class GlobalDictionaryShape : public NameDictionaryShape {
3320 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3322 template <typename Dictionary>
3323 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3325 template <typename Dictionary>
3326 static inline void DetailsAtPut(Dictionary* dict, int entry,
3327 PropertyDetails value);
3329 template <typename Dictionary>
3330 static bool IsDeleted(Dictionary* dict, int entry);
3332 template <typename Dictionary>
3333 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3334 Handle<Object> value, PropertyDetails details);
3338 class GlobalDictionary
3339 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3341 DECLARE_CAST(GlobalDictionary)
3345 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3347 static inline bool IsMatch(uint32_t key, Object* other);
3348 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3349 static const int kEntrySize = 3;
3350 static const bool kIsEnumerable = false;
3354 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3356 static const bool UsesSeed = true;
3357 static const int kPrefixSize = 2;
3359 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3360 static inline uint32_t SeededHashForObject(uint32_t key,
3366 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3368 static const int kPrefixSize = 0;
3370 static inline uint32_t Hash(uint32_t key);
3371 static inline uint32_t HashForObject(uint32_t key, Object* object);
3375 class SeededNumberDictionary
3376 : public Dictionary<SeededNumberDictionary,
3377 SeededNumberDictionaryShape,
3380 DECLARE_CAST(SeededNumberDictionary)
3382 // Type specific at put (default NONE attributes is used when adding).
3383 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3384 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3385 Handle<Object> value, bool used_as_prototype);
3386 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3387 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3388 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3390 // Set an existing entry or add a new one if needed.
3391 // Return the updated dictionary.
3392 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3393 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3394 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3396 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3398 // If slow elements are required we will never go back to fast-case
3399 // for the elements kept in this dictionary. We require slow
3400 // elements if an element has been added at an index larger than
3401 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3402 // when defining a getter or setter with a number key.
3403 inline bool requires_slow_elements();
3404 inline void set_requires_slow_elements();
3406 // Get the value of the max number key that has been added to this
3407 // dictionary. max_number_key can only be called if
3408 // requires_slow_elements returns false.
3409 inline uint32_t max_number_key();
3412 static const int kRequiresSlowElementsMask = 1;
3413 static const int kRequiresSlowElementsTagSize = 1;
3414 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3418 class UnseededNumberDictionary
3419 : public Dictionary<UnseededNumberDictionary,
3420 UnseededNumberDictionaryShape,
3423 DECLARE_CAST(UnseededNumberDictionary)
3425 // Type specific at put (default NONE attributes is used when adding).
3426 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3427 Handle<UnseededNumberDictionary> dictionary,
3429 Handle<Object> value);
3430 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3431 Handle<UnseededNumberDictionary> dictionary,
3433 Handle<Object> value);
3435 // Set an existing entry or add a new one if needed.
3436 // Return the updated dictionary.
3437 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3438 Handle<UnseededNumberDictionary> dictionary,
3440 Handle<Object> value);
3444 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3446 static inline bool IsMatch(Handle<Object> key, Object* other);
3447 static inline uint32_t Hash(Handle<Object> key);
3448 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3449 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3450 static const int kPrefixSize = 0;
3451 static const int kEntrySize = 2;
3455 // ObjectHashTable maps keys that are arbitrary objects to object values by
3456 // using the identity hash of the key for hashing purposes.
3457 class ObjectHashTable: public HashTable<ObjectHashTable,
3458 ObjectHashTableShape,
3461 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3463 DECLARE_CAST(ObjectHashTable)
3465 // Attempt to shrink hash table after removal of key.
3466 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3467 Handle<ObjectHashTable> table,
3468 Handle<Object> key);
3470 // Looks up the value associated with the given key. The hole value is
3471 // returned in case the key is not present.
3472 Object* Lookup(Handle<Object> key);
3473 Object* Lookup(Handle<Object> key, int32_t hash);
3474 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3476 // Adds (or overwrites) the value associated with the given key.
3477 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3479 Handle<Object> value);
3480 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3481 Handle<Object> key, Handle<Object> value,
3484 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3485 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3488 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3489 Handle<Object> key, bool* was_present,
3493 friend class MarkCompactCollector;
3495 void AddEntry(int entry, Object* key, Object* value);
3496 void RemoveEntry(int entry);
3498 // Returns the index to the value of an entry.
3499 static inline int EntryToValueIndex(int entry) {
3500 return EntryToIndex(entry) + 1;
3505 // OrderedHashTable is a HashTable with Object keys that preserves
3506 // insertion order. There are Map and Set interfaces (OrderedHashMap
3507 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3509 // Only Object* keys are supported, with Object::SameValueZero() used as the
3510 // equality operator and Object::GetHash() for the hash function.
3512 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3513 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3514 // Originally attributed to Tyler Close.
3517 // [0]: bucket count
3518 // [1]: element count
3519 // [2]: deleted element count
3520 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3521 // offset into the data table (see below) where the
3522 // first item in this bucket is stored.
3523 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3524 // Capacity() * kEntrySize, where the first entrysize
3525 // items are handled by the derived class and the
3526 // item at kChainOffset is another entry into the
3527 // data table indicating the next entry in this hash
3530 // When we transition the table to a new version we obsolete it and reuse parts
3531 // of the memory to store information how to transition an iterator to the new
3534 // Memory layout for obsolete table:
3535 // [0]: bucket count
3536 // [1]: Next newer table
3537 // [2]: Number of removed holes or -1 when the table was cleared.
3538 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3539 // [3 + NumberOfRemovedHoles()..length]: Not used
3541 template<class Derived, class Iterator, int entrysize>
3542 class OrderedHashTable: public FixedArray {
3544 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3545 static Handle<Derived> Allocate(
3546 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3548 // Returns an OrderedHashTable (possibly |table|) with enough space
3549 // to add at least one new element.
3550 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3552 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3554 static Handle<Derived> Shrink(Handle<Derived> table);
3556 // Returns a new empty OrderedHashTable and records the clearing so that
3557 // exisiting iterators can be updated.
3558 static Handle<Derived> Clear(Handle<Derived> table);
3560 int NumberOfElements() {
3561 return Smi::cast(get(kNumberOfElementsIndex))->value();
3564 int NumberOfDeletedElements() {
3565 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3568 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3570 int NumberOfBuckets() {
3571 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3574 // Returns an index into |this| for the given entry.
3575 int EntryToIndex(int entry) {
3576 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3579 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3582 return !get(kNextTableIndex)->IsSmi();
3585 // The next newer table. This is only valid if the table is obsolete.
3586 Derived* NextTable() {
3587 return Derived::cast(get(kNextTableIndex));
3590 // When the table is obsolete we store the indexes of the removed holes.
3591 int RemovedIndexAt(int index) {
3592 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3595 static const int kNotFound = -1;
3596 static const int kMinCapacity = 4;
3598 static const int kNumberOfBucketsIndex = 0;
3599 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3600 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3601 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3602 static const int kNextTableIndex = kNumberOfElementsIndex;
3604 static const int kNumberOfBucketsOffset =
3605 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3606 static const int kNumberOfElementsOffset =
3607 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3608 static const int kNumberOfDeletedElementsOffset =
3609 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3610 static const int kHashTableStartOffset =
3611 kHeaderSize + kHashTableStartIndex * kPointerSize;
3612 static const int kNextTableOffset =
3613 kHeaderSize + kNextTableIndex * kPointerSize;
3615 static const int kEntrySize = entrysize + 1;
3616 static const int kChainOffset = entrysize;
3618 static const int kLoadFactor = 2;
3620 // NumberOfDeletedElements is set to kClearedTableSentinel when
3621 // the table is cleared, which allows iterator transitions to
3622 // optimize that case.
3623 static const int kClearedTableSentinel = -1;
3626 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3628 void SetNumberOfBuckets(int num) {
3629 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3632 void SetNumberOfElements(int num) {
3633 set(kNumberOfElementsIndex, Smi::FromInt(num));
3636 void SetNumberOfDeletedElements(int num) {
3637 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3641 return NumberOfBuckets() * kLoadFactor;
3644 void SetNextTable(Derived* next_table) {
3645 set(kNextTableIndex, next_table);
3648 void SetRemovedIndexAt(int index, int removed_index) {
3649 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3652 static const int kRemovedHolesIndex = kHashTableStartIndex;
3654 static const int kMaxCapacity =
3655 (FixedArray::kMaxLength - kHashTableStartIndex)
3656 / (1 + (kEntrySize * kLoadFactor));
3660 class JSSetIterator;
3663 class OrderedHashSet: public OrderedHashTable<
3664 OrderedHashSet, JSSetIterator, 1> {
3666 DECLARE_CAST(OrderedHashSet)
3670 class JSMapIterator;
3673 class OrderedHashMap
3674 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3676 DECLARE_CAST(OrderedHashMap)
3678 inline Object* ValueAt(int entry);
3680 static const int kValueOffset = 1;
3684 template <int entrysize>
3685 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3687 static inline bool IsMatch(Handle<Object> key, Object* other);
3688 static inline uint32_t Hash(Handle<Object> key);
3689 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3690 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3691 static const int kPrefixSize = 0;
3692 static const int kEntrySize = entrysize;
3696 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3697 // values. The table wraps the keys in weak cells and store values directly.
3698 // Thus it references keys weakly and values strongly.
3699 class WeakHashTable: public HashTable<WeakHashTable,
3700 WeakHashTableShape<2>,
3703 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3705 DECLARE_CAST(WeakHashTable)
3707 // Looks up the value associated with the given key. The hole value is
3708 // returned in case the key is not present.
3709 Object* Lookup(Handle<HeapObject> key);
3711 // Adds (or overwrites) the value associated with the given key. Mapping a
3712 // key to the hole value causes removal of the whole entry.
3713 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3714 Handle<HeapObject> key,
3715 Handle<HeapObject> value);
3717 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3720 friend class MarkCompactCollector;
3722 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3724 // Returns the index to the value of an entry.
3725 static inline int EntryToValueIndex(int entry) {
3726 return EntryToIndex(entry) + 1;
3731 // ScopeInfo represents information about different scopes of a source
3732 // program and the allocation of the scope's variables. Scope information
3733 // is stored in a compressed form in ScopeInfo objects and is used
3734 // at runtime (stack dumps, deoptimization, etc.).
3736 // This object provides quick access to scope info details for runtime
3738 class ScopeInfo : public FixedArray {
3740 DECLARE_CAST(ScopeInfo)
3742 // Return the type of this scope.
3743 ScopeType scope_type();
3745 // Does this scope call eval?
3748 // Return the language mode of this scope.
3749 LanguageMode language_mode();
3751 // Does this scope make a sloppy eval call?
3752 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3754 // Return the total number of locals allocated on the stack and in the
3755 // context. This includes the parameters that are allocated in the context.
3758 // Return the number of stack slots for code. This number consists of two
3760 // 1. One stack slot per stack allocated local.
3761 // 2. One stack slot for the function name if it is stack allocated.
3762 int StackSlotCount();
3764 // Return the number of context slots for code if a context is allocated. This
3765 // number consists of three parts:
3766 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3767 // 2. One context slot per context allocated local.
3768 // 3. One context slot for the function name if it is context allocated.
3769 // Parameters allocated in the context count as context allocated locals. If
3770 // no contexts are allocated for this scope ContextLength returns 0.
3771 int ContextLength();
3773 // Does this scope declare a "this" binding?
3776 // Does this scope declare a "this" binding, and the "this" binding is stack-
3777 // or context-allocated?
3778 bool HasAllocatedReceiver();
3780 // Is this scope the scope of a named function expression?
3781 bool HasFunctionName();
3783 // Return if this has context allocated locals.
3784 bool HasHeapAllocatedLocals();
3786 // Return if contexts are allocated for this scope.
3789 // Return if this is a function scope with "use asm".
3790 inline bool IsAsmModule();
3792 // Return if this is a nested function within an asm module scope.
3793 inline bool IsAsmFunction();
3795 inline bool HasSimpleParameters();
3797 // Return the function_name if present.
3798 String* FunctionName();
3800 // Return the name of the given parameter.
3801 String* ParameterName(int var);
3803 // Return the name of the given local.
3804 String* LocalName(int var);
3806 // Return the name of the given stack local.
3807 String* StackLocalName(int var);
3809 // Return the name of the given stack local.
3810 int StackLocalIndex(int var);
3812 // Return the name of the given context local.
3813 String* ContextLocalName(int var);
3815 // Return the mode of the given context local.
3816 VariableMode ContextLocalMode(int var);
3818 // Return the initialization flag of the given context local.
3819 InitializationFlag ContextLocalInitFlag(int var);
3821 // Return the initialization flag of the given context local.
3822 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3824 // Return true if this local was introduced by the compiler, and should not be
3825 // exposed to the user in a debugger.
3826 bool LocalIsSynthetic(int var);
3828 String* StrongModeFreeVariableName(int var);
3829 int StrongModeFreeVariableStartPosition(int var);
3830 int StrongModeFreeVariableEndPosition(int var);
3832 // Lookup support for serialized scope info. Returns the
3833 // the stack slot index for a given slot name if the slot is
3834 // present; otherwise returns a value < 0. The name must be an internalized
3836 int StackSlotIndex(String* name);
3838 // Lookup support for serialized scope info. Returns the
3839 // context slot index for a given slot name if the slot is present; otherwise
3840 // returns a value < 0. The name must be an internalized string.
3841 // If the slot is present and mode != NULL, sets *mode to the corresponding
3842 // mode for that variable.
3843 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3844 VariableMode* mode, VariableLocation* location,
3845 InitializationFlag* init_flag,
3846 MaybeAssignedFlag* maybe_assigned_flag);
3848 // Lookup the name of a certain context slot by its index.
3849 String* ContextSlotName(int slot_index);
3851 // Lookup support for serialized scope info. Returns the
3852 // parameter index for a given parameter name if the parameter is present;
3853 // otherwise returns a value < 0. The name must be an internalized string.
3854 int ParameterIndex(String* name);
3856 // Lookup support for serialized scope info. Returns the function context
3857 // slot index if the function name is present and context-allocated (named
3858 // function expressions, only), otherwise returns a value < 0. The name
3859 // must be an internalized string.
3860 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3862 // Lookup support for serialized scope info. Returns the receiver context
3863 // slot index if scope has a "this" binding, and the binding is
3864 // context-allocated. Otherwise returns a value < 0.
3865 int ReceiverContextSlotIndex();
3867 FunctionKind function_kind();
3869 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3870 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3872 // Serializes empty scope info.
3873 static ScopeInfo* Empty(Isolate* isolate);
3879 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3880 // numeric and occupies one array slot.
3881 // 1. A set of properties of the scope
3882 // 2. The number of parameters. This only applies to function scopes. For
3883 // non-function scopes this is 0.
3884 // 3. The number of non-parameter variables allocated on the stack.
3885 // 4. The number of non-parameter and parameter variables allocated in the
3887 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3890 V(StackLocalCount) \
3891 V(ContextLocalCount) \
3892 V(ContextGlobalCount) \
3893 V(StrongModeFreeVariableCount)
3895 #define FIELD_ACCESSORS(name) \
3896 inline void Set##name(int value); \
3898 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3899 #undef FIELD_ACCESSORS
3903 #define DECL_INDEX(name) k##name,
3904 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3909 // The layout of the variable part of a ScopeInfo is as follows:
3910 // 1. ParameterEntries:
3911 // This part stores the names of the parameters for function scopes. One
3912 // slot is used per parameter, so in total this part occupies
3913 // ParameterCount() slots in the array. For other scopes than function
3914 // scopes ParameterCount() is 0.
3915 // 2. StackLocalFirstSlot:
3916 // Index of a first stack slot for stack local. Stack locals belonging to
3917 // this scope are located on a stack at slots starting from this index.
3918 // 3. StackLocalEntries:
3919 // Contains the names of local variables that are allocated on the stack,
3920 // in increasing order of the stack slot index. First local variable has
3921 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3922 // One slot is used per stack local, so in total this part occupies
3923 // StackLocalCount() slots in the array.
3924 // 4. ContextLocalNameEntries:
3925 // Contains the names of local variables and parameters that are allocated
3926 // in the context. They are stored in increasing order of the context slot
3927 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3928 // context local, so in total this part occupies ContextLocalCount() slots
3930 // 5. ContextLocalInfoEntries:
3931 // Contains the variable modes and initialization flags corresponding to
3932 // the context locals in ContextLocalNameEntries. One slot is used per
3933 // context local, so in total this part occupies ContextLocalCount()
3934 // slots in the array.
3935 // 6. StrongModeFreeVariableNameEntries:
3936 // Stores the names of strong mode free variables.
3937 // 7. StrongModeFreeVariablePositionEntries:
3938 // Stores the locations (start and end position) of strong mode free
3940 // 8. RecieverEntryIndex:
3941 // If the scope binds a "this" value, one slot is reserved to hold the
3942 // context or stack slot index for the variable.
3943 // 9. FunctionNameEntryIndex:
3944 // If the scope belongs to a named function expression this part contains
3945 // information about the function variable. It always occupies two array
3946 // slots: a. The name of the function variable.
3947 // b. The context or stack slot index for the variable.
3948 int ParameterEntriesIndex();
3949 int StackLocalFirstSlotIndex();
3950 int StackLocalEntriesIndex();
3951 int ContextLocalNameEntriesIndex();
3952 int ContextGlobalNameEntriesIndex();
3953 int ContextLocalInfoEntriesIndex();
3954 int ContextGlobalInfoEntriesIndex();
3955 int StrongModeFreeVariableNameEntriesIndex();
3956 int StrongModeFreeVariablePositionEntriesIndex();
3957 int ReceiverEntryIndex();
3958 int FunctionNameEntryIndex();
3960 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
3961 VariableLocation* location, InitializationFlag* init_flag,
3962 MaybeAssignedFlag* maybe_assigned_flag);
3964 // Used for the function name variable for named function expressions, and for
3966 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
3968 // Properties of scopes.
3969 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
3970 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
3971 STATIC_ASSERT(LANGUAGE_END == 3);
3972 class LanguageModeField
3973 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
3974 class ReceiverVariableField
3975 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
3976 class FunctionVariableField
3977 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
3979 class FunctionVariableMode
3980 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
3981 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
3983 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
3984 class HasSimpleParametersField
3985 : public BitField<bool, AsmFunctionField::kNext, 1> {};
3986 class FunctionKindField
3987 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
3989 // BitFields representing the encoded information for context locals in the
3990 // ContextLocalInfoEntries part.
3991 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
3992 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
3993 class ContextLocalMaybeAssignedFlag
3994 : public BitField<MaybeAssignedFlag, 4, 1> {};
3996 friend class ScopeIterator;
4000 // The cache for maps used by normalized (dictionary mode) objects.
4001 // Such maps do not have property descriptors, so a typical program
4002 // needs very limited number of distinct normalized maps.
4003 class NormalizedMapCache: public FixedArray {
4005 static Handle<NormalizedMapCache> New(Isolate* isolate);
4007 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4008 PropertyNormalizationMode mode);
4009 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4013 DECLARE_CAST(NormalizedMapCache)
4015 static inline bool IsNormalizedMapCache(const Object* obj);
4017 DECLARE_VERIFIER(NormalizedMapCache)
4019 static const int kEntries = 64;
4021 static inline int GetIndex(Handle<Map> map);
4023 // The following declarations hide base class methods.
4024 Object* get(int index);
4025 void set(int index, Object* value);
4029 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4030 // that is attached to code objects.
4031 class ByteArray: public FixedArrayBase {
4035 // Setter and getter.
4036 inline byte get(int index);
4037 inline void set(int index, byte value);
4039 // Treat contents as an int array.
4040 inline int get_int(int index);
4042 static int SizeFor(int length) {
4043 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4045 // We use byte arrays for free blocks in the heap. Given a desired size in
4046 // bytes that is a multiple of the word size and big enough to hold a byte
4047 // array, this function returns the number of elements a byte array should
4049 static int LengthFor(int size_in_bytes) {
4050 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4051 DCHECK(size_in_bytes >= kHeaderSize);
4052 return size_in_bytes - kHeaderSize;
4055 // Returns data start address.
4056 inline Address GetDataStartAddress();
4058 // Returns a pointer to the ByteArray object for a given data start address.
4059 static inline ByteArray* FromDataStartAddress(Address address);
4061 DECLARE_CAST(ByteArray)
4063 // Dispatched behavior.
4064 inline int ByteArraySize();
4065 DECLARE_PRINTER(ByteArray)
4066 DECLARE_VERIFIER(ByteArray)
4068 // Layout description.
4069 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4071 // Maximal memory consumption for a single ByteArray.
4072 static const int kMaxSize = 512 * MB;
4073 // Maximal length of a single ByteArray.
4074 static const int kMaxLength = kMaxSize - kHeaderSize;
4077 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4081 // BytecodeArray represents a sequence of interpreter bytecodes.
4082 class BytecodeArray : public FixedArrayBase {
4084 static int SizeFor(int length) {
4085 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4088 // Setter and getter
4089 inline byte get(int index);
4090 inline void set(int index, byte value);
4092 // Returns data start address.
4093 inline Address GetFirstBytecodeAddress();
4095 // Accessors for frame size and the number of locals
4096 inline int frame_size() const;
4097 inline void set_frame_size(int value);
4099 DECLARE_CAST(BytecodeArray)
4101 // Dispatched behavior.
4102 inline int BytecodeArraySize();
4104 DECLARE_PRINTER(BytecodeArray)
4105 DECLARE_VERIFIER(BytecodeArray)
4107 void Disassemble(std::ostream& os);
4109 // Layout description.
4110 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4111 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4113 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4115 // Maximal memory consumption for a single BytecodeArray.
4116 static const int kMaxSize = 512 * MB;
4117 // Maximal length of a single BytecodeArray.
4118 static const int kMaxLength = kMaxSize - kHeaderSize;
4121 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4125 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4126 // They look like heap objects (are heap object tagged and have a map) so that
4127 // the heap remains iterable. They have a size and a next pointer.
4128 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4129 // in the free list.
4130 class FreeSpace: public HeapObject {
4132 // [size]: size of the free space including the header.
4133 inline int size() const;
4134 inline void set_size(int value);
4136 inline int nobarrier_size() const;
4137 inline void nobarrier_set_size(int value);
4141 // Accessors for the next field.
4142 inline FreeSpace* next();
4143 inline FreeSpace** next_address();
4144 inline void set_next(FreeSpace* next);
4146 inline static FreeSpace* cast(HeapObject* obj);
4148 // Dispatched behavior.
4149 DECLARE_PRINTER(FreeSpace)
4150 DECLARE_VERIFIER(FreeSpace)
4152 // Layout description.
4153 // Size is smi tagged when it is stored.
4154 static const int kSizeOffset = HeapObject::kHeaderSize;
4155 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4158 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4162 // V has parameters (Type, type, TYPE, C type, element_size)
4163 #define TYPED_ARRAYS(V) \
4164 V(Uint8, uint8, UINT8, uint8_t, 1) \
4165 V(Int8, int8, INT8, int8_t, 1) \
4166 V(Uint16, uint16, UINT16, uint16_t, 2) \
4167 V(Int16, int16, INT16, int16_t, 2) \
4168 V(Uint32, uint32, UINT32, uint32_t, 4) \
4169 V(Int32, int32, INT32, int32_t, 4) \
4170 V(Float32, float32, FLOAT32, float, 4) \
4171 V(Float64, float64, FLOAT64, double, 8) \
4172 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4175 class FixedTypedArrayBase: public FixedArrayBase {
4177 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4178 DECL_ACCESSORS(base_pointer, Object)
4180 // [external_pointer]: Contains the offset between base_pointer and the start
4181 // of the data. If the base_pointer is a nullptr, the external_pointer
4182 // therefore points to the actual backing store.
4183 DECL_ACCESSORS(external_pointer, void)
4185 // Dispatched behavior.
4186 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4188 template <typename StaticVisitor>
4189 inline void FixedTypedArrayBaseIterateBody();
4191 DECLARE_CAST(FixedTypedArrayBase)
4193 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4194 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4195 static const int kHeaderSize =
4196 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4198 static const int kDataOffset = kHeaderSize;
4202 static inline int TypedArraySize(InstanceType type, int length);
4203 inline int TypedArraySize(InstanceType type);
4205 // Use with care: returns raw pointer into heap.
4206 inline void* DataPtr();
4208 inline int DataSize();
4211 static inline int ElementSize(InstanceType type);
4213 inline int DataSize(InstanceType type);
4215 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4219 template <class Traits>
4220 class FixedTypedArray: public FixedTypedArrayBase {
4222 typedef typename Traits::ElementType ElementType;
4223 static const InstanceType kInstanceType = Traits::kInstanceType;
4225 DECLARE_CAST(FixedTypedArray<Traits>)
4227 inline ElementType get_scalar(int index);
4228 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4229 inline void set(int index, ElementType value);
4231 static inline ElementType from_int(int value);
4232 static inline ElementType from_double(double value);
4234 // This accessor applies the correct conversion from Smi, HeapNumber
4236 void SetValue(uint32_t index, Object* value);
4238 DECLARE_PRINTER(FixedTypedArray)
4239 DECLARE_VERIFIER(FixedTypedArray)
4242 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4245 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4246 class Type##ArrayTraits { \
4247 public: /* NOLINT */ \
4248 typedef elementType ElementType; \
4249 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4250 static const char* Designator() { return #type " array"; } \
4251 static inline Handle<Object> ToHandle(Isolate* isolate, \
4252 elementType scalar); \
4253 static inline elementType defaultValue(); \
4256 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4258 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4260 #undef FIXED_TYPED_ARRAY_TRAITS
4263 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4264 // data for code generated by the Hydrogen/Lithium compiler. It also
4265 // contains information about functions that were inlined. If N different
4266 // functions were inlined then first N elements of the literal array will
4267 // contain these functions.
4270 class DeoptimizationInputData: public FixedArray {
4272 // Layout description. Indices in the array.
4273 static const int kTranslationByteArrayIndex = 0;
4274 static const int kInlinedFunctionCountIndex = 1;
4275 static const int kLiteralArrayIndex = 2;
4276 static const int kOsrAstIdIndex = 3;
4277 static const int kOsrPcOffsetIndex = 4;
4278 static const int kOptimizationIdIndex = 5;
4279 static const int kSharedFunctionInfoIndex = 6;
4280 static const int kWeakCellCacheIndex = 7;
4281 static const int kFirstDeoptEntryIndex = 8;
4283 // Offsets of deopt entry elements relative to the start of the entry.
4284 static const int kAstIdRawOffset = 0;
4285 static const int kTranslationIndexOffset = 1;
4286 static const int kArgumentsStackHeightOffset = 2;
4287 static const int kPcOffset = 3;
4288 static const int kDeoptEntrySize = 4;
4290 // Simple element accessors.
4291 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4292 inline type* name(); \
4293 inline void Set##name(type* value);
4295 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4296 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4297 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4298 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4299 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4300 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4301 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4302 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4304 #undef DECLARE_ELEMENT_ACCESSORS
4306 // Accessors for elements of the ith deoptimization entry.
4307 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4308 inline type* name(int i); \
4309 inline void Set##name(int i, type* value);
4311 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4312 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4313 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4314 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4316 #undef DECLARE_ENTRY_ACCESSORS
4318 inline BailoutId AstId(int i);
4320 inline void SetAstId(int i, BailoutId value);
4322 inline int DeoptCount();
4324 // Allocates a DeoptimizationInputData.
4325 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4326 int deopt_entry_count,
4327 PretenureFlag pretenure);
4329 DECLARE_CAST(DeoptimizationInputData)
4331 #ifdef ENABLE_DISASSEMBLER
4332 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4336 static int IndexForEntry(int i) {
4337 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4341 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4345 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4346 // data for code generated by the full compiler.
4347 // The format of the these objects is
4348 // [i * 2]: Ast ID for ith deoptimization.
4349 // [i * 2 + 1]: PC and state of ith deoptimization
4350 class DeoptimizationOutputData: public FixedArray {
4352 inline int DeoptPoints();
4354 inline BailoutId AstId(int index);
4356 inline void SetAstId(int index, BailoutId id);
4358 inline Smi* PcAndState(int index);
4359 inline void SetPcAndState(int index, Smi* offset);
4361 static int LengthOfFixedArray(int deopt_points) {
4362 return deopt_points * 2;
4365 // Allocates a DeoptimizationOutputData.
4366 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4367 int number_of_deopt_points,
4368 PretenureFlag pretenure);
4370 DECLARE_CAST(DeoptimizationOutputData)
4372 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4373 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4378 // HandlerTable is a fixed array containing entries for exception handlers in
4379 // the code object it is associated with. The tables comes in two flavors:
4380 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4381 // exception handler and a range representing the try-block covered by that
4382 // handler. Layout looks as follows:
4383 // [ range-start , range-end , handler-offset , stack-depth ]
4384 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4385 // per call-site that could throw an exception. Layout looks as follows:
4386 // [ return-address-offset , handler-offset ]
4387 class HandlerTable : public FixedArray {
4389 // Conservative prediction whether a given handler will locally catch an
4390 // exception or cause a re-throw to outside the code boundary. Since this is
4391 // undecidable it is merely an approximation (e.g. useful for debugger).
4392 enum CatchPrediction { UNCAUGHT, CAUGHT };
4394 // Accessors for handler table based on ranges.
4395 inline void SetRangeStart(int index, int value);
4396 inline void SetRangeEnd(int index, int value);
4397 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4398 inline void SetRangeDepth(int index, int value);
4400 // Accessors for handler table based on return addresses.
4401 inline void SetReturnOffset(int index, int value);
4402 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4404 // Lookup handler in a table based on ranges.
4405 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4407 // Lookup handler in a table based on return addresses.
4408 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4410 // Returns the required length of the underlying fixed array.
4411 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4412 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4414 DECLARE_CAST(HandlerTable)
4416 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4417 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4418 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4422 // Layout description for handler table based on ranges.
4423 static const int kRangeStartIndex = 0;
4424 static const int kRangeEndIndex = 1;
4425 static const int kRangeHandlerIndex = 2;
4426 static const int kRangeDepthIndex = 3;
4427 static const int kRangeEntrySize = 4;
4429 // Layout description for handler table based on return addresses.
4430 static const int kReturnOffsetIndex = 0;
4431 static const int kReturnHandlerIndex = 1;
4432 static const int kReturnEntrySize = 2;
4434 // Encoding of the {handler} field.
4435 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4436 class HandlerOffsetField : public BitField<int, 1, 30> {};
4440 // Code describes objects with on-the-fly generated machine code.
4441 class Code: public HeapObject {
4443 // Opaque data type for encapsulating code flags like kind, inline
4444 // cache state, and arguments count.
4445 typedef uint32_t Flags;
4447 #define NON_IC_KIND_LIST(V) \
4449 V(OPTIMIZED_FUNCTION) \
4455 #define IC_KIND_LIST(V) \
4466 #define CODE_KIND_LIST(V) \
4467 NON_IC_KIND_LIST(V) \
4471 #define DEFINE_CODE_KIND_ENUM(name) name,
4472 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4473 #undef DEFINE_CODE_KIND_ENUM
4477 // No more than 16 kinds. The value is currently encoded in four bits in
4479 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4481 static const char* Kind2String(Kind kind);
4489 static const int kPrologueOffsetNotSet = -1;
4491 #ifdef ENABLE_DISASSEMBLER
4493 static const char* ICState2String(InlineCacheState state);
4494 static const char* StubType2String(StubType type);
4495 static void PrintExtraICState(std::ostream& os, // NOLINT
4496 Kind kind, ExtraICState extra);
4497 void Disassemble(const char* name, std::ostream& os); // NOLINT
4498 #endif // ENABLE_DISASSEMBLER
4500 // [instruction_size]: Size of the native instructions
4501 inline int instruction_size() const;
4502 inline void set_instruction_size(int value);
4504 // [relocation_info]: Code relocation information
4505 DECL_ACCESSORS(relocation_info, ByteArray)
4506 void InvalidateRelocation();
4507 void InvalidateEmbeddedObjects();
4509 // [handler_table]: Fixed array containing offsets of exception handlers.
4510 DECL_ACCESSORS(handler_table, FixedArray)
4512 // [deoptimization_data]: Array containing data for deopt.
4513 DECL_ACCESSORS(deoptimization_data, FixedArray)
4515 // [raw_type_feedback_info]: This field stores various things, depending on
4516 // the kind of the code object.
4517 // FUNCTION => type feedback information.
4518 // STUB and ICs => major/minor key as Smi.
4519 DECL_ACCESSORS(raw_type_feedback_info, Object)
4520 inline Object* type_feedback_info();
4521 inline void set_type_feedback_info(
4522 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4523 inline uint32_t stub_key();
4524 inline void set_stub_key(uint32_t key);
4526 // [next_code_link]: Link for lists of optimized or deoptimized code.
4527 // Note that storage for this field is overlapped with typefeedback_info.
4528 DECL_ACCESSORS(next_code_link, Object)
4530 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4531 // field does not have to be traced during garbage collection since
4532 // it is only used by the garbage collector itself.
4533 DECL_ACCESSORS(gc_metadata, Object)
4535 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4536 // at the moment when this object was created.
4537 inline void set_ic_age(int count);
4538 inline int ic_age() const;
4540 // [prologue_offset]: Offset of the function prologue, used for aging
4541 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4542 inline int prologue_offset() const;
4543 inline void set_prologue_offset(int offset);
4545 // [constant_pool offset]: Offset of the constant pool.
4546 // Valid for FLAG_enable_embedded_constant_pool only
4547 inline int constant_pool_offset() const;
4548 inline void set_constant_pool_offset(int offset);
4550 // Unchecked accessors to be used during GC.
4551 inline ByteArray* unchecked_relocation_info();
4553 inline int relocation_size();
4555 // [flags]: Various code flags.
4556 inline Flags flags();
4557 inline void set_flags(Flags flags);
4559 // [flags]: Access to specific code flags.
4561 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4562 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4564 inline StubType type(); // Only valid for monomorphic IC stubs.
4566 // Testers for IC stub kinds.
4567 inline bool is_inline_cache_stub();
4568 inline bool is_debug_stub();
4569 inline bool is_handler();
4570 inline bool is_load_stub();
4571 inline bool is_keyed_load_stub();
4572 inline bool is_store_stub();
4573 inline bool is_keyed_store_stub();
4574 inline bool is_call_stub();
4575 inline bool is_binary_op_stub();
4576 inline bool is_compare_ic_stub();
4577 inline bool is_compare_nil_ic_stub();
4578 inline bool is_to_boolean_ic_stub();
4579 inline bool is_keyed_stub();
4580 inline bool is_optimized_code();
4581 inline bool embeds_maps_weakly();
4583 inline bool IsCodeStubOrIC();
4584 inline bool IsJavaScriptCode();
4586 inline void set_raw_kind_specific_flags1(int value);
4587 inline void set_raw_kind_specific_flags2(int value);
4589 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4590 // object was generated by either the hydrogen or the TurboFan optimizing
4591 // compiler (but it may not be an optimized function).
4592 inline bool is_crankshafted();
4593 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4594 inline void set_is_crankshafted(bool value);
4596 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4597 // code object was generated by the TurboFan optimizing compiler.
4598 inline bool is_turbofanned();
4599 inline void set_is_turbofanned(bool value);
4601 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4602 // embedded objects in code should be treated weakly.
4603 inline bool can_have_weak_objects();
4604 inline void set_can_have_weak_objects(bool value);
4606 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4607 // deoptimization support.
4608 inline bool has_deoptimization_support();
4609 inline void set_has_deoptimization_support(bool value);
4611 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4612 // been compiled with debug break slots.
4613 inline bool has_debug_break_slots();
4614 inline void set_has_debug_break_slots(bool value);
4616 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4617 // reloc info includes runtime and external references to support
4618 // serialization/deserialization.
4619 inline bool has_reloc_info_for_serialization();
4620 inline void set_has_reloc_info_for_serialization(bool value);
4622 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4623 // how long the function has been marked for OSR and therefore which
4624 // level of loop nesting we are willing to do on-stack replacement
4626 inline void set_allow_osr_at_loop_nesting_level(int level);
4627 inline int allow_osr_at_loop_nesting_level();
4629 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4630 // the code object was seen on the stack with no IC patching going on.
4631 inline int profiler_ticks();
4632 inline void set_profiler_ticks(int ticks);
4634 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4635 // For builtins, tells which builtin index it has.
4636 // Note that builtins can have a code kind other than BUILTIN, which means
4637 // that for arbitrary code objects, this index value may be random garbage.
4638 // To verify in that case, compare the code object to the indexed builtin.
4639 inline int builtin_index();
4640 inline void set_builtin_index(int id);
4642 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4643 // reserved in the code prologue.
4644 inline unsigned stack_slots();
4645 inline void set_stack_slots(unsigned slots);
4647 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4648 // the instruction stream where the safepoint table starts.
4649 inline unsigned safepoint_table_offset();
4650 inline void set_safepoint_table_offset(unsigned offset);
4652 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4653 // instruction stream where the back edge table starts.
4654 inline unsigned back_edge_table_offset();
4655 inline void set_back_edge_table_offset(unsigned offset);
4657 inline bool back_edges_patched_for_osr();
4659 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4660 inline uint16_t to_boolean_state();
4662 // [has_function_cache]: For kind STUB tells whether there is a function
4663 // cache is passed to the stub.
4664 inline bool has_function_cache();
4665 inline void set_has_function_cache(bool flag);
4668 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4669 // the code is going to be deoptimized because of dead embedded maps.
4670 inline bool marked_for_deoptimization();
4671 inline void set_marked_for_deoptimization(bool flag);
4673 // [constant_pool]: The constant pool for this function.
4674 inline Address constant_pool();
4676 // Get the safepoint entry for the given pc.
4677 SafepointEntry GetSafepointEntry(Address pc);
4679 // Find an object in a stub with a specified map
4680 Object* FindNthObject(int n, Map* match_map);
4682 // Find the first allocation site in an IC stub.
4683 AllocationSite* FindFirstAllocationSite();
4685 // Find the first map in an IC stub.
4686 Map* FindFirstMap();
4687 void FindAllMaps(MapHandleList* maps);
4689 // Find the first handler in an IC stub.
4690 Code* FindFirstHandler();
4692 // Find |length| handlers and put them into |code_list|. Returns false if not
4693 // enough handlers can be found.
4694 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4696 // Find the handler for |map|.
4697 MaybeHandle<Code> FindHandlerForMap(Map* map);
4699 // Find the first name in an IC stub.
4700 Name* FindFirstName();
4702 class FindAndReplacePattern;
4703 // For each (map-to-find, object-to-replace) pair in the pattern, this
4704 // function replaces the corresponding placeholder in the code with the
4705 // object-to-replace. The function assumes that pairs in the pattern come in
4706 // the same order as the placeholders in the code.
4707 // If the placeholder is a weak cell, then the value of weak cell is matched
4708 // against the map-to-find.
4709 void FindAndReplace(const FindAndReplacePattern& pattern);
4711 // The entire code object including its header is copied verbatim to the
4712 // snapshot so that it can be written in one, fast, memcpy during
4713 // deserialization. The deserializer will overwrite some pointers, rather
4714 // like a runtime linker, but the random allocation addresses used in the
4715 // mksnapshot process would still be present in the unlinked snapshot data,
4716 // which would make snapshot production non-reproducible. This method wipes
4717 // out the to-be-overwritten header data for reproducible snapshots.
4718 inline void WipeOutHeader();
4720 // Flags operations.
4721 static inline Flags ComputeFlags(
4722 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4723 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4724 CacheHolderFlag holder = kCacheOnReceiver);
4726 static inline Flags ComputeMonomorphicFlags(
4727 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4728 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4730 static inline Flags ComputeHandlerFlags(
4731 Kind handler_kind, StubType type = NORMAL,
4732 CacheHolderFlag holder = kCacheOnReceiver);
4734 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4735 static inline StubType ExtractTypeFromFlags(Flags flags);
4736 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4737 static inline Kind ExtractKindFromFlags(Flags flags);
4738 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4740 static inline Flags RemoveTypeFromFlags(Flags flags);
4741 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4743 // Convert a target address into a code object.
4744 static inline Code* GetCodeFromTargetAddress(Address address);
4746 // Convert an entry address into an object.
4747 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4749 // Returns the address of the first instruction.
4750 inline byte* instruction_start();
4752 // Returns the address right after the last instruction.
4753 inline byte* instruction_end();
4755 // Returns the size of the instructions, padding, and relocation information.
4756 inline int body_size();
4758 // Returns the address of the first relocation info (read backwards!).
4759 inline byte* relocation_start();
4761 // Code entry point.
4762 inline byte* entry();
4764 // Returns true if pc is inside this object's instructions.
4765 inline bool contains(byte* pc);
4767 // Relocate the code by delta bytes. Called to signal that this code
4768 // object has been moved by delta bytes.
4769 void Relocate(intptr_t delta);
4771 // Migrate code described by desc.
4772 void CopyFrom(const CodeDesc& desc);
4774 // Returns the object size for a given body (used for allocation).
4775 static int SizeFor(int body_size) {
4776 DCHECK_SIZE_TAG_ALIGNED(body_size);
4777 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4780 // Calculate the size of the code object to report for log events. This takes
4781 // the layout of the code object into account.
4782 inline int ExecutableSize();
4784 // Locating source position.
4785 int SourcePosition(Address pc);
4786 int SourceStatementPosition(Address pc);
4790 // Dispatched behavior.
4791 inline int CodeSize();
4792 inline void CodeIterateBody(ObjectVisitor* v);
4794 template<typename StaticVisitor>
4795 inline void CodeIterateBody(Heap* heap);
4797 DECLARE_PRINTER(Code)
4798 DECLARE_VERIFIER(Code)
4800 void ClearInlineCaches();
4801 void ClearInlineCaches(Kind kind);
4803 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4804 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4806 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4808 kToBeExecutedOnceCodeAge = -3,
4809 kNotExecutedCodeAge = -2,
4810 kExecutedOnceCodeAge = -1,
4812 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4814 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4815 kLastCodeAge = kAfterLastCodeAge - 1,
4816 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4817 kIsOldCodeAge = kSexagenarianCodeAge,
4818 kPreAgedCodeAge = kIsOldCodeAge - 1
4820 #undef DECLARE_CODE_AGE_ENUM
4822 // Code aging. Indicates how many full GCs this code has survived without
4823 // being entered through the prologue. Used to determine when it is
4824 // relatively safe to flush this code object and replace it with the lazy
4825 // compilation stub.
4826 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4827 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4828 void MakeYoung(Isolate* isolate);
4829 void MarkToBeExecutedOnce(Isolate* isolate);
4830 void MakeOlder(MarkingParity);
4831 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4834 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4835 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4838 void PrintDeoptLocation(FILE* out, Address pc);
4839 bool CanDeoptAt(Address pc);
4842 void VerifyEmbeddedObjectsDependency();
4846 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4847 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4848 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4851 inline bool CanContainWeakObjects();
4853 inline bool IsWeakObject(Object* object);
4855 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4857 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4858 WeakCell* CachedWeakCell();
4860 // Max loop nesting marker used to postpose OSR. We don't take loop
4861 // nesting that is deeper than 5 levels into account.
4862 static const int kMaxLoopNestingMarker = 6;
4864 static const int kConstantPoolSize =
4865 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4867 // Layout description.
4868 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4869 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4870 static const int kDeoptimizationDataOffset =
4871 kHandlerTableOffset + kPointerSize;
4872 // For FUNCTION kind, we store the type feedback info here.
4873 static const int kTypeFeedbackInfoOffset =
4874 kDeoptimizationDataOffset + kPointerSize;
4875 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4876 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4877 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4878 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4879 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4880 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4881 static const int kKindSpecificFlags2Offset =
4882 kKindSpecificFlags1Offset + kIntSize;
4883 // Note: We might be able to squeeze this into the flags above.
4884 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4885 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4886 static const int kHeaderPaddingStart =
4887 kConstantPoolOffset + kConstantPoolSize;
4889 // Add padding to align the instruction start following right after
4890 // the Code object header.
4891 static const int kHeaderSize =
4892 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4894 // Byte offsets within kKindSpecificFlags1Offset.
4895 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4896 class FullCodeFlagsHasDeoptimizationSupportField:
4897 public BitField<bool, 0, 1> {}; // NOLINT
4898 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4899 class FullCodeFlagsHasRelocInfoForSerialization
4900 : public BitField<bool, 2, 1> {};
4901 // Bit 3 in this bitfield is unused.
4902 class ProfilerTicksField : public BitField<int, 4, 28> {};
4904 // Flags layout. BitField<type, shift, size>.
4905 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4906 class TypeField : public BitField<StubType, 4, 1> {};
4907 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4908 class KindField : public BitField<Kind, 7, 4> {};
4909 class ExtraICStateField: public BitField<ExtraICState, 11,
4910 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4912 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4913 static const int kStackSlotsFirstBit = 0;
4914 static const int kStackSlotsBitCount = 24;
4915 static const int kHasFunctionCacheBit =
4916 kStackSlotsFirstBit + kStackSlotsBitCount;
4917 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4918 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4919 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4921 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4922 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4924 class StackSlotsField: public BitField<int,
4925 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4926 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4928 class MarkedForDeoptimizationField
4929 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
4930 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
4932 class CanHaveWeakObjectsField
4933 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
4935 // KindSpecificFlags2 layout (ALL)
4936 static const int kIsCrankshaftedBit = 0;
4937 class IsCrankshaftedField: public BitField<bool,
4938 kIsCrankshaftedBit, 1> {}; // NOLINT
4940 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
4941 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
4942 static const int kSafepointTableOffsetBitCount = 30;
4944 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
4945 kSafepointTableOffsetBitCount <= 32);
4946 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
4948 class SafepointTableOffsetField: public BitField<int,
4949 kSafepointTableOffsetFirstBit,
4950 kSafepointTableOffsetBitCount> {}; // NOLINT
4952 // KindSpecificFlags2 layout (FUNCTION)
4953 class BackEdgeTableOffsetField: public BitField<int,
4954 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
4955 class AllowOSRAtLoopNestingLevelField: public BitField<int,
4956 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
4957 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
4959 static const int kArgumentsBits = 16;
4960 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
4962 // This constant should be encodable in an ARM instruction.
4963 static const int kFlagsNotUsedInLookup =
4964 TypeField::kMask | CacheHolderField::kMask;
4967 friend class RelocIterator;
4968 friend class Deoptimizer; // For FindCodeAgeSequence.
4970 void ClearInlineCaches(Kind* kind);
4973 byte* FindCodeAgeSequence();
4974 static void GetCodeAgeAndParity(Code* code, Age* age,
4975 MarkingParity* parity);
4976 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
4977 MarkingParity* parity);
4978 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
4980 // Code aging -- platform-specific
4981 static void PatchPlatformCodeAge(Isolate* isolate,
4982 byte* sequence, Age age,
4983 MarkingParity parity);
4985 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
4989 // This class describes the layout of dependent codes array of a map. The
4990 // array is partitioned into several groups of dependent codes. Each group
4991 // contains codes with the same dependency on the map. The array has the
4992 // following layout for n dependency groups:
4994 // +----+----+-----+----+---------+----------+-----+---------+-----------+
4995 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
4996 // +----+----+-----+----+---------+----------+-----+---------+-----------+
4998 // The first n elements are Smis, each of them specifies the number of codes
4999 // in the corresponding group. The subsequent elements contain grouped code
5000 // objects in weak cells. The suffix of the array can be filled with the
5001 // undefined value if the number of codes is less than the length of the
5002 // array. The order of the code objects within a group is not preserved.
5004 // All code indexes used in the class are counted starting from the first
5005 // code object of the first group. In other words, code index 0 corresponds
5006 // to array index n = kCodesStartIndex.
5008 class DependentCode: public FixedArray {
5010 enum DependencyGroup {
5011 // Group of code that weakly embed this map and depend on being
5012 // deoptimized when the map is garbage collected.
5014 // Group of code that embed a transition to this map, and depend on being
5015 // deoptimized when the transition is replaced by a new version.
5017 // Group of code that omit run-time prototype checks for prototypes
5018 // described by this map. The group is deoptimized whenever an object
5019 // described by this map changes shape (and transitions to a new map),
5020 // possibly invalidating the assumptions embedded in the code.
5021 kPrototypeCheckGroup,
5022 // Group of code that depends on global property values in property cells
5023 // not being changed.
5024 kPropertyCellChangedGroup,
5025 // Group of code that omit run-time type checks for the field(s) introduced
5028 // Group of code that omit run-time type checks for initial maps of
5030 kInitialMapChangedGroup,
5031 // Group of code that depends on tenuring information in AllocationSites
5032 // not being changed.
5033 kAllocationSiteTenuringChangedGroup,
5034 // Group of code that depends on element transition information in
5035 // AllocationSites not being changed.
5036 kAllocationSiteTransitionChangedGroup
5039 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5041 // Array for holding the index of the first code object of each group.
5042 // The last element stores the total number of code objects.
5043 class GroupStartIndexes {
5045 explicit GroupStartIndexes(DependentCode* entries);
5046 void Recompute(DependentCode* entries);
5047 int at(int i) { return start_indexes_[i]; }
5048 int number_of_entries() { return start_indexes_[kGroupCount]; }
5050 int start_indexes_[kGroupCount + 1];
5053 bool Contains(DependencyGroup group, WeakCell* code_cell);
5055 static Handle<DependentCode> InsertCompilationDependencies(
5056 Handle<DependentCode> entries, DependencyGroup group,
5057 Handle<Foreign> info);
5059 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5060 DependencyGroup group,
5061 Handle<WeakCell> code_cell);
5063 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5064 WeakCell* code_cell);
5066 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5069 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5070 DependentCode::DependencyGroup group);
5072 bool MarkCodeForDeoptimization(Isolate* isolate,
5073 DependentCode::DependencyGroup group);
5075 // The following low-level accessors should only be used by this class
5076 // and the mark compact collector.
5077 inline int number_of_entries(DependencyGroup group);
5078 inline void set_number_of_entries(DependencyGroup group, int value);
5079 inline Object* object_at(int i);
5080 inline void set_object_at(int i, Object* object);
5081 inline void clear_at(int i);
5082 inline void copy(int from, int to);
5083 DECLARE_CAST(DependentCode)
5085 static const char* DependencyGroupName(DependencyGroup group);
5086 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5089 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5090 DependencyGroup group,
5091 Handle<Object> object);
5092 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5093 // Make a room at the end of the given group by moving out the first
5094 // code objects of the subsequent groups.
5095 inline void ExtendGroup(DependencyGroup group);
5096 // Compact by removing cleared weak cells and return true if there was
5097 // any cleared weak cell.
5099 static int Grow(int number_of_entries) {
5100 if (number_of_entries < 5) return number_of_entries + 1;
5101 return number_of_entries * 5 / 4;
5103 static const int kCodesStartIndex = kGroupCount;
5107 class PrototypeInfo;
5110 // All heap objects have a Map that describes their structure.
5111 // A Map contains information about:
5112 // - Size information about the object
5113 // - How to iterate over an object (for garbage collection)
5114 class Map: public HeapObject {
5117 // Size in bytes or kVariableSizeSentinel if instances do not have
5119 inline int instance_size();
5120 inline void set_instance_size(int value);
5122 // Only to clear an unused byte, remove once byte is used.
5123 inline void clear_unused();
5125 // [inobject_properties_or_constructor_function_index]: Provides access
5126 // to the inobject properties in case of JSObject maps, or the constructor
5127 // function index in case of primitive maps.
5128 inline int inobject_properties_or_constructor_function_index();
5129 inline void set_inobject_properties_or_constructor_function_index(int value);
5130 // Count of properties allocated in the object (JSObject only).
5131 inline int GetInObjectProperties();
5132 inline void SetInObjectProperties(int value);
5133 // Index of the constructor function in the native context (primitives only),
5134 // or the special sentinel value to indicate that there is no object wrapper
5135 // for the primitive (i.e. in case of null or undefined).
5136 static const int kNoConstructorFunctionIndex = 0;
5137 inline int GetConstructorFunctionIndex();
5138 inline void SetConstructorFunctionIndex(int value);
5141 inline InstanceType instance_type();
5142 inline void set_instance_type(InstanceType value);
5144 // Tells how many unused property fields are available in the
5145 // instance (only used for JSObject in fast mode).
5146 inline int unused_property_fields();
5147 inline void set_unused_property_fields(int value);
5150 inline byte bit_field() const;
5151 inline void set_bit_field(byte value);
5154 inline byte bit_field2() const;
5155 inline void set_bit_field2(byte value);
5158 inline uint32_t bit_field3() const;
5159 inline void set_bit_field3(uint32_t bits);
5161 class EnumLengthBits: public BitField<int,
5162 0, kDescriptorIndexBitCount> {}; // NOLINT
5163 class NumberOfOwnDescriptorsBits: public BitField<int,
5164 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5165 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5166 class DictionaryMap : public BitField<bool, 20, 1> {};
5167 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5168 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5169 class Deprecated : public BitField<bool, 23, 1> {};
5170 class IsUnstable : public BitField<bool, 24, 1> {};
5171 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5172 class IsStrong : public BitField<bool, 26, 1> {};
5175 // Keep this bit field at the very end for better code in
5176 // Builtins::kJSConstructStubGeneric stub.
5177 // This counter is used for in-object slack tracking and for map aging.
5178 // The in-object slack tracking is considered enabled when the counter is
5179 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5180 class Counter : public BitField<int, 28, 4> {};
5181 static const int kSlackTrackingCounterStart = 14;
5182 static const int kSlackTrackingCounterEnd = 8;
5183 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5184 static const int kRetainingCounterEnd = 0;
5186 // Tells whether the object in the prototype property will be used
5187 // for instances created from this function. If the prototype
5188 // property is set to a value that is not a JSObject, the prototype
5189 // property will not be used to create instances of the function.
5190 // See ECMA-262, 13.2.2.
5191 inline void set_non_instance_prototype(bool value);
5192 inline bool has_non_instance_prototype();
5194 // Tells whether function has special prototype property. If not, prototype
5195 // property will not be created when accessed (will return undefined),
5196 // and construction from this function will not be allowed.
5197 inline void set_function_with_prototype(bool value);
5198 inline bool function_with_prototype();
5200 // Tells whether the instance with this map should be ignored by the
5201 // Object.getPrototypeOf() function and the __proto__ accessor.
5202 inline void set_is_hidden_prototype();
5203 inline bool is_hidden_prototype();
5205 // Records and queries whether the instance has a named interceptor.
5206 inline void set_has_named_interceptor();
5207 inline bool has_named_interceptor();
5209 // Records and queries whether the instance has an indexed interceptor.
5210 inline void set_has_indexed_interceptor();
5211 inline bool has_indexed_interceptor();
5213 // Tells whether the instance is undetectable.
5214 // An undetectable object is a special class of JSObject: 'typeof' operator
5215 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5216 // a normal JS object. It is useful for implementing undetectable
5217 // document.all in Firefox & Safari.
5218 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5219 inline void set_is_undetectable();
5220 inline bool is_undetectable();
5222 // Tells whether the instance has a call-as-function handler.
5223 inline void set_is_observed();
5224 inline bool is_observed();
5226 inline void set_is_strong();
5227 inline bool is_strong();
5228 inline void set_is_extensible(bool value);
5229 inline bool is_extensible();
5230 inline void set_is_prototype_map(bool value);
5231 inline bool is_prototype_map() const;
5233 inline void set_elements_kind(ElementsKind elements_kind);
5234 inline ElementsKind elements_kind();
5236 // Tells whether the instance has fast elements that are only Smis.
5237 inline bool has_fast_smi_elements();
5239 // Tells whether the instance has fast elements.
5240 inline bool has_fast_object_elements();
5241 inline bool has_fast_smi_or_object_elements();
5242 inline bool has_fast_double_elements();
5243 inline bool has_fast_elements();
5244 inline bool has_sloppy_arguments_elements();
5245 inline bool has_fixed_typed_array_elements();
5246 inline bool has_dictionary_elements();
5248 static bool IsValidElementsTransition(ElementsKind from_kind,
5249 ElementsKind to_kind);
5251 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5252 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5253 bool DictionaryElementsInPrototypeChainOnly();
5255 inline Map* ElementsTransitionMap();
5257 inline FixedArrayBase* GetInitialElements();
5259 // [raw_transitions]: Provides access to the transitions storage field.
5260 // Don't call set_raw_transitions() directly to overwrite transitions, use
5261 // the TransitionArray::ReplaceTransitions() wrapper instead!
5262 DECL_ACCESSORS(raw_transitions, Object)
5263 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5264 // (which prototype maps don't have).
5265 DECL_ACCESSORS(prototype_info, Object)
5266 // PrototypeInfo is created lazily using this helper (which installs it on
5267 // the given prototype's map).
5268 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5269 Handle<JSObject> prototype, Isolate* isolate);
5270 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5271 Handle<Map> prototype_map, Isolate* isolate);
5273 // [prototype chain validity cell]: Associated with a prototype object,
5274 // stored in that object's map's PrototypeInfo, indicates that prototype
5275 // chains through this object are currently valid. The cell will be
5276 // invalidated and replaced when the prototype chain changes.
5277 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5279 static const int kPrototypeChainValid = 0;
5280 static const int kPrototypeChainInvalid = 1;
5283 Map* FindFieldOwner(int descriptor);
5285 inline int GetInObjectPropertyOffset(int index);
5287 int NumberOfFields();
5289 // TODO(ishell): candidate with JSObject::MigrateToMap().
5290 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5291 int target_inobject, int target_unused,
5292 int* old_number_of_fields);
5293 // TODO(ishell): moveit!
5294 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5295 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5296 Handle<HeapType> type1,
5297 Handle<HeapType> type2,
5299 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5300 Representation new_representation,
5301 Handle<HeapType> new_field_type);
5302 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5303 PropertyKind new_kind,
5304 PropertyAttributes new_attributes,
5305 Representation new_representation,
5306 Handle<HeapType> new_field_type,
5307 StoreMode store_mode);
5308 static Handle<Map> CopyGeneralizeAllRepresentations(
5309 Handle<Map> map, int modify_index, StoreMode store_mode,
5310 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5312 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5313 int descriptor_number,
5314 Handle<Object> value);
5316 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5317 const char* reason);
5319 // Returns the constructor name (the name (possibly, inferred name) of the
5320 // function that was used to instantiate the object).
5321 String* constructor_name();
5323 // Tells whether the map is used for JSObjects in dictionary mode (ie
5324 // normalized objects, ie objects for which HasFastProperties returns false).
5325 // A map can never be used for both dictionary mode and fast mode JSObjects.
5326 // False by default and for HeapObjects that are not JSObjects.
5327 inline void set_dictionary_map(bool value);
5328 inline bool is_dictionary_map();
5330 // Tells whether the instance needs security checks when accessing its
5332 inline void set_is_access_check_needed(bool access_check_needed);
5333 inline bool is_access_check_needed();
5335 // Returns true if map has a non-empty stub code cache.
5336 inline bool has_code_cache();
5338 // [prototype]: implicit prototype object.
5339 DECL_ACCESSORS(prototype, Object)
5340 // TODO(jkummerow): make set_prototype private.
5341 static void SetPrototype(
5342 Handle<Map> map, Handle<Object> prototype,
5343 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5345 // [constructor]: points back to the function responsible for this map.
5346 // The field overlaps with the back pointer. All maps in a transition tree
5347 // have the same constructor, so maps with back pointers can walk the
5348 // back pointer chain until they find the map holding their constructor.
5349 DECL_ACCESSORS(constructor_or_backpointer, Object)
5350 inline Object* GetConstructor() const;
5351 inline void SetConstructor(Object* constructor,
5352 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5353 // [back pointer]: points back to the parent map from which a transition
5354 // leads to this map. The field overlaps with the constructor (see above).
5355 inline Object* GetBackPointer();
5356 inline void SetBackPointer(Object* value,
5357 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5359 // [instance descriptors]: describes the object.
5360 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5362 // [layout descriptor]: describes the object layout.
5363 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5364 // |layout descriptor| accessor which can be used from GC.
5365 inline LayoutDescriptor* layout_descriptor_gc_safe();
5366 inline bool HasFastPointerLayout() const;
5368 // |layout descriptor| accessor that is safe to call even when
5369 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5370 // |layout_descriptor| field at all).
5371 inline LayoutDescriptor* GetLayoutDescriptor();
5373 inline void UpdateDescriptors(DescriptorArray* descriptors,
5374 LayoutDescriptor* layout_descriptor);
5375 inline void InitializeDescriptors(DescriptorArray* descriptors,
5376 LayoutDescriptor* layout_descriptor);
5378 // [stub cache]: contains stubs compiled for this map.
5379 DECL_ACCESSORS(code_cache, Object)
5381 // [dependent code]: list of optimized codes that weakly embed this map.
5382 DECL_ACCESSORS(dependent_code, DependentCode)
5384 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5385 DECL_ACCESSORS(weak_cell_cache, Object)
5387 inline PropertyDetails GetLastDescriptorDetails();
5389 inline int LastAdded();
5391 inline int NumberOfOwnDescriptors();
5392 inline void SetNumberOfOwnDescriptors(int number);
5394 inline Cell* RetrieveDescriptorsPointer();
5396 inline int EnumLength();
5397 inline void SetEnumLength(int length);
5399 inline bool owns_descriptors();
5400 inline void set_owns_descriptors(bool owns_descriptors);
5401 inline bool has_instance_call_handler();
5402 inline void set_has_instance_call_handler();
5403 inline void mark_unstable();
5404 inline bool is_stable();
5405 inline void set_migration_target(bool value);
5406 inline bool is_migration_target();
5407 inline void set_counter(int value);
5408 inline int counter();
5409 inline void deprecate();
5410 inline bool is_deprecated();
5411 inline bool CanBeDeprecated();
5412 // Returns a non-deprecated version of the input. If the input was not
5413 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5414 // is found by re-transitioning from the root of the transition tree using the
5415 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5417 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5419 // Returns a non-deprecated version of the input. This method may deprecate
5420 // existing maps along the way if encodings conflict. Not for use while
5421 // gathering type feedback. Use TryUpdate in those cases instead.
5422 static Handle<Map> Update(Handle<Map> map);
5424 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5425 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5426 Descriptor* descriptor,
5427 TransitionFlag flag);
5429 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5432 Handle<HeapType> type,
5433 PropertyAttributes attributes,
5434 Representation representation,
5435 TransitionFlag flag);
5437 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5440 Handle<Object> constant,
5441 PropertyAttributes attributes,
5442 TransitionFlag flag);
5444 // Returns a new map with all transitions dropped from the given map and
5445 // the ElementsKind set.
5446 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5447 ElementsKind to_kind);
5449 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5451 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5453 TransitionFlag flag);
5455 static Handle<Map> CopyForObserved(Handle<Map> map);
5457 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5458 PropertyAttributes attrs_to_add,
5459 Handle<Symbol> transition_marker,
5460 const char* reason);
5462 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5465 // Maximal number of fast properties. Used to restrict the number of map
5466 // transitions to avoid an explosion in the number of maps for objects used as
5468 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5469 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5471 Handle<Object> value,
5472 PropertyAttributes attributes,
5473 StoreFromKeyed store_mode);
5474 static Handle<Map> TransitionToAccessorProperty(
5475 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5476 Handle<Object> accessor, PropertyAttributes attributes);
5477 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5480 PropertyAttributes attributes);
5482 inline void AppendDescriptor(Descriptor* desc);
5484 // Returns a copy of the map, prepared for inserting into the transition
5485 // tree (if the |map| owns descriptors then the new one will share
5486 // descriptors with |map|).
5487 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5489 // Returns a copy of the map, with all transitions dropped from the
5490 // instance descriptors.
5491 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5492 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5494 // Returns the next free property index (only valid for FAST MODE).
5495 int NextFreePropertyIndex();
5497 // Returns the number of properties described in instance_descriptors
5498 // filtering out properties with the specified attributes.
5499 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5500 PropertyAttributes filter = NONE);
5504 // Code cache operations.
5506 // Clears the code cache.
5507 inline void ClearCodeCache(Heap* heap);
5509 // Update code cache.
5510 static void UpdateCodeCache(Handle<Map> map,
5514 // Extend the descriptor array of the map with the list of descriptors.
5515 // In case of duplicates, the latest descriptor is used.
5516 static void AppendCallbackDescriptors(Handle<Map> map,
5517 Handle<Object> descriptors);
5519 static inline int SlackForArraySize(int old_size, int size_limit);
5521 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5523 // Returns the found code or undefined if absent.
5524 Object* FindInCodeCache(Name* name, Code::Flags flags);
5526 // Returns the non-negative index of the code object if it is in the
5527 // cache and -1 otherwise.
5528 int IndexInCodeCache(Object* name, Code* code);
5530 // Removes a code object from the code cache at the given index.
5531 void RemoveFromCodeCache(Name* name, Code* code, int index);
5533 // Computes a hash value for this map, to be used in HashTables and such.
5536 // Returns the map that this map transitions to if its elements_kind
5537 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5538 // |safe_to_add_transitions| is set to false if adding transitions is not
5540 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5542 // Returns the transitioned map for this map with the most generic
5543 // elements_kind that's found in |candidates|, or null handle if no match is
5545 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5546 MapHandleList* candidates);
5548 inline bool CanTransition();
5550 inline bool IsPrimitiveMap();
5551 inline bool IsJSObjectMap();
5552 inline bool IsJSArrayMap();
5553 inline bool IsStringMap();
5554 inline bool IsJSProxyMap();
5555 inline bool IsJSGlobalProxyMap();
5556 inline bool IsJSGlobalObjectMap();
5557 inline bool IsGlobalObjectMap();
5559 inline bool CanOmitMapChecks();
5561 static void AddDependentCode(Handle<Map> map,
5562 DependentCode::DependencyGroup group,
5565 bool IsMapInArrayPrototypeChain();
5567 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5569 // Dispatched behavior.
5570 DECLARE_PRINTER(Map)
5571 DECLARE_VERIFIER(Map)
5574 void DictionaryMapVerify();
5575 void VerifyOmittedMapChecks();
5578 inline int visitor_id();
5579 inline void set_visitor_id(int visitor_id);
5581 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5582 Handle<Object> prototype,
5583 PrototypeOptimizationMode mode);
5585 static const int kMaxPreAllocatedPropertyFields = 255;
5587 // Layout description.
5588 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5589 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5590 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5591 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5592 static const int kConstructorOrBackPointerOffset =
5593 kPrototypeOffset + kPointerSize;
5594 // When there is only one transition, it is stored directly in this field;
5595 // otherwise a transition array is used.
5596 // For prototype maps, this slot is used to store this map's PrototypeInfo
5598 static const int kTransitionsOrPrototypeInfoOffset =
5599 kConstructorOrBackPointerOffset + kPointerSize;
5600 static const int kDescriptorsOffset =
5601 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5602 #if V8_DOUBLE_FIELDS_UNBOXING
5603 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5604 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5606 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5607 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5609 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5610 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5611 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5613 // Layout of pointer fields. Heap iteration code relies on them
5614 // being continuously allocated.
5615 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5616 static const int kPointerFieldsEndOffset = kSize;
5618 // Byte offsets within kInstanceSizesOffset.
5619 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5620 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5621 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5622 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5623 // Note there is one byte available for use here.
5624 static const int kUnusedByte = 2;
5625 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5626 static const int kVisitorIdByte = 3;
5627 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5629 // Byte offsets within kInstanceAttributesOffset attributes.
5630 #if V8_TARGET_LITTLE_ENDIAN
5631 // Order instance type and bit field together such that they can be loaded
5632 // together as a 16-bit word with instance type in the lower 8 bits regardless
5633 // of endianess. Also provide endian-independent offset to that 16-bit word.
5634 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5635 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5637 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5638 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5640 static const int kInstanceTypeAndBitFieldOffset =
5641 kInstanceAttributesOffset + 0;
5642 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5643 static const int kUnusedPropertyFieldsByte = 3;
5644 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5646 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5647 Internals::kMapInstanceTypeAndBitFieldOffset);
5649 // Bit positions for bit field.
5650 static const int kHasNonInstancePrototype = 0;
5651 static const int kIsHiddenPrototype = 1;
5652 static const int kHasNamedInterceptor = 2;
5653 static const int kHasIndexedInterceptor = 3;
5654 static const int kIsUndetectable = 4;
5655 static const int kIsObserved = 5;
5656 static const int kIsAccessCheckNeeded = 6;
5657 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5659 // Bit positions for bit field 2
5660 static const int kIsExtensible = 0;
5661 static const int kStringWrapperSafeForDefaultValueOf = 1;
5662 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5663 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5665 // Derived values from bit field 2
5666 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5667 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5668 static const int8_t kMaximumBitField2FastSmiElementValue =
5669 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5670 Map::ElementsKindBits::kShift) - 1;
5671 static const int8_t kMaximumBitField2FastHoleyElementValue =
5672 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5673 Map::ElementsKindBits::kShift) - 1;
5674 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5675 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5676 Map::ElementsKindBits::kShift) - 1;
5678 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5679 kPointerFieldsEndOffset,
5680 kSize> BodyDescriptor;
5682 // Compares this map to another to see if they describe equivalent objects.
5683 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5684 // it had exactly zero inobject properties.
5685 // The "shared" flags of both this map and |other| are ignored.
5686 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5688 // Returns true if given field is unboxed double.
5689 inline bool IsUnboxedDoubleField(FieldIndex index);
5692 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5693 static void TraceAllTransitions(Map* map);
5696 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5697 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5698 Handle<LayoutDescriptor> layout_descriptor);
5701 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5702 Handle<Name> name, SimpleTransitionFlag flag);
5704 bool EquivalentToForTransition(Map* other);
5705 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5706 static Handle<Map> ShareDescriptor(Handle<Map> map,
5707 Handle<DescriptorArray> descriptors,
5708 Descriptor* descriptor);
5709 static Handle<Map> CopyInstallDescriptors(
5710 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5711 Handle<LayoutDescriptor> layout_descriptor);
5712 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5713 Descriptor* descriptor,
5714 TransitionFlag flag);
5715 static Handle<Map> CopyReplaceDescriptors(
5716 Handle<Map> map, Handle<DescriptorArray> descriptors,
5717 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5718 MaybeHandle<Name> maybe_name, const char* reason,
5719 SimpleTransitionFlag simple_flag);
5721 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5722 Handle<DescriptorArray> descriptors,
5723 Descriptor* descriptor,
5725 TransitionFlag flag);
5726 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5727 Handle<Map> map, int descriptor, PropertyKind kind,
5728 PropertyAttributes attributes, const char** reason);
5730 static Handle<Map> CopyNormalized(Handle<Map> map,
5731 PropertyNormalizationMode mode);
5733 // Fires when the layout of an object with a leaf map changes.
5734 // This includes adding transitions to the leaf map or changing
5735 // the descriptor array.
5736 inline void NotifyLeafMapLayoutChange();
5738 void DeprecateTransitionTree();
5739 bool DeprecateTarget(PropertyKind kind, Name* key,
5740 PropertyAttributes attributes,
5741 DescriptorArray* new_descriptors,
5742 LayoutDescriptor* new_layout_descriptor);
5744 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5746 // Update field type of the given descriptor to new representation and new
5747 // type. The type must be prepared for storing in descriptor array:
5748 // it must be either a simple type or a map wrapped in a weak cell.
5749 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5750 Representation new_representation,
5751 Handle<Object> new_wrapped_type);
5753 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5754 PropertyAttributes attributes);
5755 void PrintGeneralization(FILE* file,
5760 bool constant_to_field,
5761 Representation old_representation,
5762 Representation new_representation,
5763 HeapType* old_field_type,
5764 HeapType* new_field_type);
5766 static const int kFastPropertiesSoftLimit = 12;
5767 static const int kMaxFastProperties = 128;
5769 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5773 // An abstract superclass, a marker class really, for simple structure classes.
5774 // It doesn't carry much functionality but allows struct classes to be
5775 // identified in the type system.
5776 class Struct: public HeapObject {
5778 inline void InitializeBody(int object_size);
5779 DECLARE_CAST(Struct)
5783 // A simple one-element struct, useful where smis need to be boxed.
5784 class Box : public Struct {
5786 // [value]: the boxed contents.
5787 DECL_ACCESSORS(value, Object)
5791 // Dispatched behavior.
5792 DECLARE_PRINTER(Box)
5793 DECLARE_VERIFIER(Box)
5795 static const int kValueOffset = HeapObject::kHeaderSize;
5796 static const int kSize = kValueOffset + kPointerSize;
5799 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5803 // Container for metadata stored on each prototype map.
5804 class PrototypeInfo : public Struct {
5806 static const int UNREGISTERED = -1;
5808 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5809 // or Smi(0) if uninitialized.
5810 DECL_ACCESSORS(prototype_users, Object)
5811 // [registry_slot]: Slot in prototype's user registry where this user
5812 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5813 inline int registry_slot() const;
5814 inline void set_registry_slot(int slot);
5815 // [validity_cell]: Cell containing the validity bit for prototype chains
5816 // going through this object, or Smi(0) if uninitialized.
5817 DECL_ACCESSORS(validity_cell, Object)
5818 // [constructor_name]: User-friendly name of the original constructor.
5819 DECL_ACCESSORS(constructor_name, Object)
5821 DECLARE_CAST(PrototypeInfo)
5823 // Dispatched behavior.
5824 DECLARE_PRINTER(PrototypeInfo)
5825 DECLARE_VERIFIER(PrototypeInfo)
5827 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5828 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5829 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5830 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5831 static const int kSize = kConstructorNameOffset + kPointerSize;
5834 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5838 // Script describes a script which has been added to the VM.
5839 class Script: public Struct {
5848 // Script compilation types.
5849 enum CompilationType {
5850 COMPILATION_TYPE_HOST = 0,
5851 COMPILATION_TYPE_EVAL = 1
5854 // Script compilation state.
5855 enum CompilationState {
5856 COMPILATION_STATE_INITIAL = 0,
5857 COMPILATION_STATE_COMPILED = 1
5860 // [source]: the script source.
5861 DECL_ACCESSORS(source, Object)
5863 // [name]: the script name.
5864 DECL_ACCESSORS(name, Object)
5866 // [id]: the script id.
5867 DECL_ACCESSORS(id, Smi)
5869 // [line_offset]: script line offset in resource from where it was extracted.
5870 DECL_ACCESSORS(line_offset, Smi)
5872 // [column_offset]: script column offset in resource from where it was
5874 DECL_ACCESSORS(column_offset, Smi)
5876 // [context_data]: context data for the context this script was compiled in.
5877 DECL_ACCESSORS(context_data, Object)
5879 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5880 DECL_ACCESSORS(wrapper, HeapObject)
5882 // [type]: the script type.
5883 DECL_ACCESSORS(type, Smi)
5885 // [line_ends]: FixedArray of line ends positions.
5886 DECL_ACCESSORS(line_ends, Object)
5888 // [eval_from_shared]: for eval scripts the shared funcion info for the
5889 // function from which eval was called.
5890 DECL_ACCESSORS(eval_from_shared, Object)
5892 // [eval_from_instructions_offset]: the instruction offset in the code for the
5893 // function from which eval was called where eval was called.
5894 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5896 // [shared_function_infos]: weak fixed array containing all shared
5897 // function infos created from this script.
5898 DECL_ACCESSORS(shared_function_infos, Object)
5900 // [flags]: Holds an exciting bitfield.
5901 DECL_ACCESSORS(flags, Smi)
5903 // [source_url]: sourceURL from magic comment
5904 DECL_ACCESSORS(source_url, Object)
5906 // [source_url]: sourceMappingURL magic comment
5907 DECL_ACCESSORS(source_mapping_url, Object)
5909 // [compilation_type]: how the the script was compiled. Encoded in the
5911 inline CompilationType compilation_type();
5912 inline void set_compilation_type(CompilationType type);
5914 // [compilation_state]: determines whether the script has already been
5915 // compiled. Encoded in the 'flags' field.
5916 inline CompilationState compilation_state();
5917 inline void set_compilation_state(CompilationState state);
5919 // [hide_source]: determines whether the script source can be exposed as
5920 // function source. Encoded in the 'flags' field.
5921 inline bool hide_source();
5922 inline void set_hide_source(bool value);
5924 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
5925 // and used by the embedder to make decisions about the script. V8 just passes
5926 // this through. Encoded in the 'flags' field.
5927 inline v8::ScriptOriginOptions origin_options();
5928 inline void set_origin_options(ScriptOriginOptions origin_options);
5930 DECLARE_CAST(Script)
5932 // If script source is an external string, check that the underlying
5933 // resource is accessible. Otherwise, always return true.
5934 inline bool HasValidSource();
5936 // Convert code position into column number.
5937 static int GetColumnNumber(Handle<Script> script, int code_pos);
5939 // Convert code position into (zero-based) line number.
5940 // The non-handlified version does not allocate, but may be much slower.
5941 static int GetLineNumber(Handle<Script> script, int code_pos);
5942 int GetLineNumber(int code_pos);
5944 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
5946 // Init line_ends array with code positions of line ends inside script source.
5947 static void InitLineEnds(Handle<Script> script);
5949 // Get the JS object wrapping the given script; create it if none exists.
5950 static Handle<JSObject> GetWrapper(Handle<Script> script);
5952 // Look through the list of existing shared function infos to find one
5953 // that matches the function literal. Return empty handle if not found.
5954 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
5956 // Iterate over all script objects on the heap.
5959 explicit Iterator(Isolate* isolate);
5963 WeakFixedArray::Iterator iterator_;
5964 DISALLOW_COPY_AND_ASSIGN(Iterator);
5967 // Dispatched behavior.
5968 DECLARE_PRINTER(Script)
5969 DECLARE_VERIFIER(Script)
5971 static const int kSourceOffset = HeapObject::kHeaderSize;
5972 static const int kNameOffset = kSourceOffset + kPointerSize;
5973 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
5974 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
5975 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
5976 static const int kWrapperOffset = kContextOffset + kPointerSize;
5977 static const int kTypeOffset = kWrapperOffset + kPointerSize;
5978 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
5979 static const int kIdOffset = kLineEndsOffset + kPointerSize;
5980 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
5981 static const int kEvalFrominstructionsOffsetOffset =
5982 kEvalFromSharedOffset + kPointerSize;
5983 static const int kSharedFunctionInfosOffset =
5984 kEvalFrominstructionsOffsetOffset + kPointerSize;
5985 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
5986 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
5987 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
5988 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
5991 int GetLineNumberWithArray(int code_pos);
5993 // Bit positions in the flags field.
5994 static const int kCompilationTypeBit = 0;
5995 static const int kCompilationStateBit = 1;
5996 static const int kHideSourceBit = 2;
5997 static const int kOriginOptionsShift = 3;
5998 static const int kOriginOptionsSize = 3;
5999 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6000 << kOriginOptionsShift;
6002 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6006 // List of builtin functions we want to identify to improve code
6009 // Each entry has a name of a global object property holding an object
6010 // optionally followed by ".prototype", a name of a builtin function
6011 // on the object (the one the id is set for), and a label.
6013 // Installation of ids for the selected builtin functions is handled
6014 // by the bootstrapper.
6015 #define FUNCTIONS_WITH_ID_LIST(V) \
6016 V(Array.prototype, indexOf, ArrayIndexOf) \
6017 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6018 V(Array.prototype, push, ArrayPush) \
6019 V(Array.prototype, pop, ArrayPop) \
6020 V(Array.prototype, shift, ArrayShift) \
6021 V(Function.prototype, apply, FunctionApply) \
6022 V(Function.prototype, call, FunctionCall) \
6023 V(String.prototype, charCodeAt, StringCharCodeAt) \
6024 V(String.prototype, charAt, StringCharAt) \
6025 V(String, fromCharCode, StringFromCharCode) \
6026 V(Math, random, MathRandom) \
6027 V(Math, floor, MathFloor) \
6028 V(Math, round, MathRound) \
6029 V(Math, ceil, MathCeil) \
6030 V(Math, abs, MathAbs) \
6031 V(Math, log, MathLog) \
6032 V(Math, exp, MathExp) \
6033 V(Math, sqrt, MathSqrt) \
6034 V(Math, pow, MathPow) \
6035 V(Math, max, MathMax) \
6036 V(Math, min, MathMin) \
6037 V(Math, cos, MathCos) \
6038 V(Math, sin, MathSin) \
6039 V(Math, tan, MathTan) \
6040 V(Math, acos, MathAcos) \
6041 V(Math, asin, MathAsin) \
6042 V(Math, atan, MathAtan) \
6043 V(Math, atan2, MathAtan2) \
6044 V(Math, imul, MathImul) \
6045 V(Math, clz32, MathClz32) \
6046 V(Math, fround, MathFround)
6048 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6049 V(Atomics, load, AtomicsLoad) \
6050 V(Atomics, store, AtomicsStore)
6052 enum BuiltinFunctionId {
6054 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6056 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6057 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6058 #undef DECLARE_FUNCTION_ID
6059 // Fake id for a special case of Math.pow. Note, it continues the
6060 // list of math functions.
6065 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6066 // that both {code} and {literals} can be NULL to pass search result status.
6067 struct CodeAndLiterals {
6068 Code* code; // Cached optimized code.
6069 FixedArray* literals; // Cached literals array.
6073 // SharedFunctionInfo describes the JSFunction information that can be
6074 // shared by multiple instances of the function.
6075 class SharedFunctionInfo: public HeapObject {
6077 // [name]: Function name.
6078 DECL_ACCESSORS(name, Object)
6080 // [code]: Function code.
6081 DECL_ACCESSORS(code, Code)
6082 inline void ReplaceCode(Code* code);
6084 // [optimized_code_map]: Map from native context to optimized code
6085 // and a shared literals array or Smi(0) if none.
6086 DECL_ACCESSORS(optimized_code_map, Object)
6088 // Returns entry from optimized code map for specified context and OSR entry.
6089 // Note that {code == nullptr} indicates no matching entry has been found,
6090 // whereas {literals == nullptr} indicates the code is context-independent.
6091 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6092 BailoutId osr_ast_id);
6094 // Clear optimized code map.
6095 void ClearOptimizedCodeMap();
6097 // Removed a specific optimized code object from the optimized code map.
6098 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6100 // Trims the optimized code map after entries have been removed.
6101 void TrimOptimizedCodeMap(int shrink_by);
6103 // Add a new entry to the optimized code map for context-independent code.
6104 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6107 // Add a new entry to the optimized code map for context-dependent code.
6108 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6109 Handle<Context> native_context,
6111 Handle<FixedArray> literals,
6112 BailoutId osr_ast_id);
6114 // Set up the link between shared function info and the script. The shared
6115 // function info is added to the list on the script.
6116 static void SetScript(Handle<SharedFunctionInfo> shared,
6117 Handle<Object> script_object);
6119 // Layout description of the optimized code map.
6120 static const int kNextMapIndex = 0;
6121 static const int kSharedCodeIndex = 1;
6122 static const int kEntriesStart = 2;
6123 static const int kContextOffset = 0;
6124 static const int kCachedCodeOffset = 1;
6125 static const int kLiteralsOffset = 2;
6126 static const int kOsrAstIdOffset = 3;
6127 static const int kEntryLength = 4;
6128 static const int kInitialLength = kEntriesStart + kEntryLength;
6130 // [scope_info]: Scope info.
6131 DECL_ACCESSORS(scope_info, ScopeInfo)
6133 // [construct stub]: Code stub for constructing instances of this function.
6134 DECL_ACCESSORS(construct_stub, Code)
6136 // Returns if this function has been compiled to native code yet.
6137 inline bool is_compiled();
6139 // [length]: The function length - usually the number of declared parameters.
6140 // Use up to 2^30 parameters.
6141 inline int length() const;
6142 inline void set_length(int value);
6144 // [internal formal parameter count]: The declared number of parameters.
6145 // For subclass constructors, also includes new.target.
6146 // The size of function's frame is internal_formal_parameter_count + 1.
6147 inline int internal_formal_parameter_count() const;
6148 inline void set_internal_formal_parameter_count(int value);
6150 // Set the formal parameter count so the function code will be
6151 // called without using argument adaptor frames.
6152 inline void DontAdaptArguments();
6154 // [expected_nof_properties]: Expected number of properties for the function.
6155 inline int expected_nof_properties() const;
6156 inline void set_expected_nof_properties(int value);
6158 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6159 // (increasingly) from crankshafted code where sufficient feedback isn't
6161 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6163 // Unconditionally clear the type feedback vector (including vector ICs).
6164 void ClearTypeFeedbackInfo();
6166 // Clear the type feedback vector with a more subtle policy at GC time.
6167 void ClearTypeFeedbackInfoAtGCTime();
6170 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6171 // even if the GC moves this SharedFunctionInfo.
6172 inline int unique_id() const;
6173 inline void set_unique_id(int value);
6176 // [instance class name]: class name for instances.
6177 DECL_ACCESSORS(instance_class_name, Object)
6179 // [function data]: This field holds some additional data for function.
6180 // Currently it has one of:
6181 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6182 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6183 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6184 // In the long run we don't want all functions to have this field but
6185 // we can fix that when we have a better model for storing hidden data
6187 DECL_ACCESSORS(function_data, Object)
6189 inline bool IsApiFunction();
6190 inline FunctionTemplateInfo* get_api_func_data();
6191 inline bool HasBuiltinFunctionId();
6192 inline BuiltinFunctionId builtin_function_id();
6193 inline bool HasBytecodeArray();
6194 inline BytecodeArray* bytecode_array();
6196 // [script info]: Script from which the function originates.
6197 DECL_ACCESSORS(script, Object)
6199 // [num_literals]: Number of literals used by this function.
6200 inline int num_literals() const;
6201 inline void set_num_literals(int value);
6203 // [start_position_and_type]: Field used to store both the source code
6204 // position, whether or not the function is a function expression,
6205 // and whether or not the function is a toplevel function. The two
6206 // least significants bit indicates whether the function is an
6207 // expression and the rest contains the source code position.
6208 inline int start_position_and_type() const;
6209 inline void set_start_position_and_type(int value);
6211 // The function is subject to debugging if a debug info is attached.
6212 inline bool HasDebugInfo();
6213 inline DebugInfo* GetDebugInfo();
6215 // A function has debug code if the compiled code has debug break slots.
6216 inline bool HasDebugCode();
6218 // [debug info]: Debug information.
6219 DECL_ACCESSORS(debug_info, Object)
6221 // [inferred name]: Name inferred from variable or property
6222 // assignment of this function. Used to facilitate debugging and
6223 // profiling of JavaScript code written in OO style, where almost
6224 // all functions are anonymous but are assigned to object
6226 DECL_ACCESSORS(inferred_name, String)
6228 // The function's name if it is non-empty, otherwise the inferred name.
6229 String* DebugName();
6231 // Position of the 'function' token in the script source.
6232 inline int function_token_position() const;
6233 inline void set_function_token_position(int function_token_position);
6235 // Position of this function in the script source.
6236 inline int start_position() const;
6237 inline void set_start_position(int start_position);
6239 // End position of this function in the script source.
6240 inline int end_position() const;
6241 inline void set_end_position(int end_position);
6243 // Is this function a function expression in the source code.
6244 DECL_BOOLEAN_ACCESSORS(is_expression)
6246 // Is this function a top-level function (scripts, evals).
6247 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6249 // Bit field containing various information collected by the compiler to
6250 // drive optimization.
6251 inline int compiler_hints() const;
6252 inline void set_compiler_hints(int value);
6254 inline int ast_node_count() const;
6255 inline void set_ast_node_count(int count);
6257 inline int profiler_ticks() const;
6258 inline void set_profiler_ticks(int ticks);
6260 // Inline cache age is used to infer whether the function survived a context
6261 // disposal or not. In the former case we reset the opt_count.
6262 inline int ic_age();
6263 inline void set_ic_age(int age);
6265 // Indicates if this function can be lazy compiled.
6266 // This is used to determine if we can safely flush code from a function
6267 // when doing GC if we expect that the function will no longer be used.
6268 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6270 // Indicates if this function can be lazy compiled without a context.
6271 // This is used to determine if we can force compilation without reaching
6272 // the function through program execution but through other means (e.g. heap
6273 // iteration by the debugger).
6274 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6276 // Indicates whether optimizations have been disabled for this
6277 // shared function info. If a function is repeatedly optimized or if
6278 // we cannot optimize the function we disable optimization to avoid
6279 // spending time attempting to optimize it again.
6280 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6282 // Indicates the language mode.
6283 inline LanguageMode language_mode();
6284 inline void set_language_mode(LanguageMode language_mode);
6286 // False if the function definitely does not allocate an arguments object.
6287 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6289 // Indicates that this function uses a super property (or an eval that may
6290 // use a super property).
6291 // This is needed to set up the [[HomeObject]] on the function instance.
6292 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6294 // True if the function has any duplicated parameter names.
6295 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6297 // Indicates whether the function is a native function.
6298 // These needs special treatment in .call and .apply since
6299 // null passed as the receiver should not be translated to the
6301 DECL_BOOLEAN_ACCESSORS(native)
6303 // Indicate that this function should always be inlined in optimized code.
6304 DECL_BOOLEAN_ACCESSORS(force_inline)
6306 // Indicates that the function was created by the Function function.
6307 // Though it's anonymous, toString should treat it as if it had the name
6308 // "anonymous". We don't set the name itself so that the system does not
6309 // see a binding for it.
6310 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6312 // Indicates whether the function is a bound function created using
6313 // the bind function.
6314 DECL_BOOLEAN_ACCESSORS(bound)
6316 // Indicates that the function is anonymous (the name field can be set
6317 // through the API, which does not change this flag).
6318 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6320 // Is this a function or top-level/eval code.
6321 DECL_BOOLEAN_ACCESSORS(is_function)
6323 // Indicates that code for this function cannot be compiled with Crankshaft.
6324 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6326 // Indicates that code for this function cannot be flushed.
6327 DECL_BOOLEAN_ACCESSORS(dont_flush)
6329 // Indicates that this function is a generator.
6330 DECL_BOOLEAN_ACCESSORS(is_generator)
6332 // Indicates that this function is an arrow function.
6333 DECL_BOOLEAN_ACCESSORS(is_arrow)
6335 // Indicates that this function is a concise method.
6336 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6338 // Indicates that this function is an accessor (getter or setter).
6339 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6341 // Indicates that this function is a default constructor.
6342 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6344 // Indicates that this function is an asm function.
6345 DECL_BOOLEAN_ACCESSORS(asm_function)
6347 // Indicates that the the shared function info is deserialized from cache.
6348 DECL_BOOLEAN_ACCESSORS(deserialized)
6350 // Indicates that the the shared function info has never been compiled before.
6351 DECL_BOOLEAN_ACCESSORS(never_compiled)
6353 inline FunctionKind kind();
6354 inline void set_kind(FunctionKind kind);
6356 // Indicates whether or not the code in the shared function support
6358 inline bool has_deoptimization_support();
6360 // Enable deoptimization support through recompiled code.
6361 void EnableDeoptimizationSupport(Code* recompiled);
6363 // Disable (further) attempted optimization of all functions sharing this
6364 // shared function info.
6365 void DisableOptimization(BailoutReason reason);
6367 inline BailoutReason disable_optimization_reason();
6369 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6370 // code, returns whether it asserted (i.e., always true if assertions are
6372 bool VerifyBailoutId(BailoutId id);
6374 // [source code]: Source code for the function.
6375 bool HasSourceCode() const;
6376 Handle<Object> GetSourceCode();
6378 // Number of times the function was optimized.
6379 inline int opt_count();
6380 inline void set_opt_count(int opt_count);
6382 // Number of times the function was deoptimized.
6383 inline void set_deopt_count(int value);
6384 inline int deopt_count();
6385 inline void increment_deopt_count();
6387 // Number of time we tried to re-enable optimization after it
6388 // was disabled due to high number of deoptimizations.
6389 inline void set_opt_reenable_tries(int value);
6390 inline int opt_reenable_tries();
6392 inline void TryReenableOptimization();
6394 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6395 inline void set_counters(int value);
6396 inline int counters() const;
6398 // Stores opt_count and bailout_reason as bit-fields.
6399 inline void set_opt_count_and_bailout_reason(int value);
6400 inline int opt_count_and_bailout_reason() const;
6402 inline void set_disable_optimization_reason(BailoutReason reason);
6404 // Tells whether this function should be subject to debugging.
6405 inline bool IsSubjectToDebugging();
6407 // Whether this function is defined in native code or extensions.
6408 inline bool IsBuiltin();
6410 // Check whether or not this function is inlineable.
6411 bool IsInlineable();
6413 // Source size of this function.
6416 // Calculate the instance size.
6417 int CalculateInstanceSize();
6419 // Calculate the number of in-object properties.
6420 int CalculateInObjectProperties();
6422 inline bool has_simple_parameters();
6424 // Initialize a SharedFunctionInfo from a parsed function literal.
6425 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6426 FunctionLiteral* lit);
6428 // Dispatched behavior.
6429 DECLARE_PRINTER(SharedFunctionInfo)
6430 DECLARE_VERIFIER(SharedFunctionInfo)
6432 void ResetForNewContext(int new_ic_age);
6434 // Iterate over all shared function infos that are created from a script.
6435 // That excludes shared function infos created for API functions and C++
6439 explicit Iterator(Isolate* isolate);
6440 SharedFunctionInfo* Next();
6445 Script::Iterator script_iterator_;
6446 WeakFixedArray::Iterator sfi_iterator_;
6447 DisallowHeapAllocation no_gc_;
6448 DISALLOW_COPY_AND_ASSIGN(Iterator);
6451 DECLARE_CAST(SharedFunctionInfo)
6454 static const int kDontAdaptArgumentsSentinel = -1;
6456 // Layout description.
6458 static const int kNameOffset = HeapObject::kHeaderSize;
6459 static const int kCodeOffset = kNameOffset + kPointerSize;
6460 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6461 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6462 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6463 static const int kInstanceClassNameOffset =
6464 kConstructStubOffset + kPointerSize;
6465 static const int kFunctionDataOffset =
6466 kInstanceClassNameOffset + kPointerSize;
6467 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6468 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6469 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6470 static const int kFeedbackVectorOffset =
6471 kInferredNameOffset + kPointerSize;
6473 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6474 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6476 // Just to not break the postmortrem support with conditional offsets
6477 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6478 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6481 #if V8_HOST_ARCH_32_BIT
6483 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6484 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6485 static const int kExpectedNofPropertiesOffset =
6486 kFormalParameterCountOffset + kPointerSize;
6487 static const int kNumLiteralsOffset =
6488 kExpectedNofPropertiesOffset + kPointerSize;
6489 static const int kStartPositionAndTypeOffset =
6490 kNumLiteralsOffset + kPointerSize;
6491 static const int kEndPositionOffset =
6492 kStartPositionAndTypeOffset + kPointerSize;
6493 static const int kFunctionTokenPositionOffset =
6494 kEndPositionOffset + kPointerSize;
6495 static const int kCompilerHintsOffset =
6496 kFunctionTokenPositionOffset + kPointerSize;
6497 static const int kOptCountAndBailoutReasonOffset =
6498 kCompilerHintsOffset + kPointerSize;
6499 static const int kCountersOffset =
6500 kOptCountAndBailoutReasonOffset + kPointerSize;
6501 static const int kAstNodeCountOffset =
6502 kCountersOffset + kPointerSize;
6503 static const int kProfilerTicksOffset =
6504 kAstNodeCountOffset + kPointerSize;
6507 static const int kSize = kProfilerTicksOffset + kPointerSize;
6509 // The only reason to use smi fields instead of int fields
6510 // is to allow iteration without maps decoding during
6511 // garbage collections.
6512 // To avoid wasting space on 64-bit architectures we use
6513 // the following trick: we group integer fields into pairs
6514 // The least significant integer in each pair is shifted left by 1.
6515 // By doing this we guarantee that LSB of each kPointerSize aligned
6516 // word is not set and thus this word cannot be treated as pointer
6517 // to HeapObject during old space traversal.
6518 #if V8_TARGET_LITTLE_ENDIAN
6519 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6520 static const int kFormalParameterCountOffset =
6521 kLengthOffset + kIntSize;
6523 static const int kExpectedNofPropertiesOffset =
6524 kFormalParameterCountOffset + kIntSize;
6525 static const int kNumLiteralsOffset =
6526 kExpectedNofPropertiesOffset + kIntSize;
6528 static const int kEndPositionOffset =
6529 kNumLiteralsOffset + kIntSize;
6530 static const int kStartPositionAndTypeOffset =
6531 kEndPositionOffset + kIntSize;
6533 static const int kFunctionTokenPositionOffset =
6534 kStartPositionAndTypeOffset + kIntSize;
6535 static const int kCompilerHintsOffset =
6536 kFunctionTokenPositionOffset + kIntSize;
6538 static const int kOptCountAndBailoutReasonOffset =
6539 kCompilerHintsOffset + kIntSize;
6540 static const int kCountersOffset =
6541 kOptCountAndBailoutReasonOffset + kIntSize;
6543 static const int kAstNodeCountOffset =
6544 kCountersOffset + kIntSize;
6545 static const int kProfilerTicksOffset =
6546 kAstNodeCountOffset + kIntSize;
6549 static const int kSize = kProfilerTicksOffset + kIntSize;
6551 #elif V8_TARGET_BIG_ENDIAN
6552 static const int kFormalParameterCountOffset =
6553 kLastPointerFieldOffset + kPointerSize;
6554 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6556 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6557 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6559 static const int kStartPositionAndTypeOffset =
6560 kExpectedNofPropertiesOffset + kIntSize;
6561 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6563 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6564 static const int kFunctionTokenPositionOffset =
6565 kCompilerHintsOffset + kIntSize;
6567 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6568 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6570 static const int kProfilerTicksOffset =
6571 kOptCountAndBailoutReasonOffset + kIntSize;
6572 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6575 static const int kSize = kAstNodeCountOffset + kIntSize;
6578 #error Unknown byte ordering
6579 #endif // Big endian
6583 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6585 typedef FixedBodyDescriptor<kNameOffset,
6586 kLastPointerFieldOffset + kPointerSize,
6587 kSize> BodyDescriptor;
6589 // Bit positions in start_position_and_type.
6590 // The source code start position is in the 30 most significant bits of
6591 // the start_position_and_type field.
6592 static const int kIsExpressionBit = 0;
6593 static const int kIsTopLevelBit = 1;
6594 static const int kStartPositionShift = 2;
6595 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6597 // Bit positions in compiler_hints.
6598 enum CompilerHints {
6599 kAllowLazyCompilation,
6600 kAllowLazyCompilationWithoutContext,
6601 kOptimizationDisabled,
6602 kStrictModeFunction,
6603 kStrongModeFunction,
6606 kHasDuplicateParameters,
6611 kNameShouldPrintAsAnonymous,
6618 kIsAccessorFunction,
6619 kIsDefaultConstructor,
6620 kIsSubclassConstructor,
6626 kCompilerHintsCount // Pseudo entry
6628 // Add hints for other modes when they're added.
6629 STATIC_ASSERT(LANGUAGE_END == 3);
6631 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6633 class DeoptCountBits : public BitField<int, 0, 4> {};
6634 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6635 class ICAgeBits : public BitField<int, 22, 8> {};
6637 class OptCountBits : public BitField<int, 0, 22> {};
6638 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6641 #if V8_HOST_ARCH_32_BIT
6642 // On 32 bit platforms, compiler hints is a smi.
6643 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6644 static const int kCompilerHintsSize = kPointerSize;
6646 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6647 static const int kCompilerHintsSmiTagSize = 0;
6648 static const int kCompilerHintsSize = kIntSize;
6651 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6652 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6655 // Constants for optimizing codegen for strict mode function and
6657 // Allows to use byte-width instructions.
6658 static const int kStrictModeBitWithinByte =
6659 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6660 static const int kStrongModeBitWithinByte =
6661 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6663 static const int kNativeBitWithinByte =
6664 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6666 #if defined(V8_TARGET_LITTLE_ENDIAN)
6667 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6668 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6669 static const int kStrongModeByteOffset =
6670 kCompilerHintsOffset +
6671 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6672 static const int kNativeByteOffset = kCompilerHintsOffset +
6673 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6674 #elif defined(V8_TARGET_BIG_ENDIAN)
6675 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6676 (kCompilerHintsSize - 1) -
6677 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6678 static const int kStrongModeByteOffset =
6679 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6680 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6681 static const int kNativeByteOffset = kCompilerHintsOffset +
6682 (kCompilerHintsSize - 1) -
6683 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6685 #error Unknown byte ordering
6689 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6693 // Printing support.
6694 struct SourceCodeOf {
6695 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6696 : value(v), max_length(max) {}
6697 const SharedFunctionInfo* value;
6702 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6705 class JSGeneratorObject: public JSObject {
6707 // [function]: The function corresponding to this generator object.
6708 DECL_ACCESSORS(function, JSFunction)
6710 // [context]: The context of the suspended computation.
6711 DECL_ACCESSORS(context, Context)
6713 // [receiver]: The receiver of the suspended computation.
6714 DECL_ACCESSORS(receiver, Object)
6716 // [continuation]: Offset into code of continuation.
6718 // A positive offset indicates a suspended generator. The special
6719 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6720 // cannot be resumed.
6721 inline int continuation() const;
6722 inline void set_continuation(int continuation);
6723 inline bool is_closed();
6724 inline bool is_executing();
6725 inline bool is_suspended();
6727 // [operand_stack]: Saved operand stack.
6728 DECL_ACCESSORS(operand_stack, FixedArray)
6730 DECLARE_CAST(JSGeneratorObject)
6732 // Dispatched behavior.
6733 DECLARE_PRINTER(JSGeneratorObject)
6734 DECLARE_VERIFIER(JSGeneratorObject)
6736 // Magic sentinel values for the continuation.
6737 static const int kGeneratorExecuting = -1;
6738 static const int kGeneratorClosed = 0;
6740 // Layout description.
6741 static const int kFunctionOffset = JSObject::kHeaderSize;
6742 static const int kContextOffset = kFunctionOffset + kPointerSize;
6743 static const int kReceiverOffset = kContextOffset + kPointerSize;
6744 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6745 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6746 static const int kSize = kOperandStackOffset + kPointerSize;
6748 // Resume mode, for use by runtime functions.
6749 enum ResumeMode { NEXT, THROW };
6751 // Yielding from a generator returns an object with the following inobject
6752 // properties. See Context::iterator_result_map() for the map.
6753 static const int kResultValuePropertyIndex = 0;
6754 static const int kResultDonePropertyIndex = 1;
6755 static const int kResultPropertyCount = 2;
6757 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6758 static const int kResultDonePropertyOffset =
6759 kResultValuePropertyOffset + kPointerSize;
6760 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6763 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6767 // Representation for module instance objects.
6768 class JSModule: public JSObject {
6770 // [context]: the context holding the module's locals, or undefined if none.
6771 DECL_ACCESSORS(context, Object)
6773 // [scope_info]: Scope info.
6774 DECL_ACCESSORS(scope_info, ScopeInfo)
6776 DECLARE_CAST(JSModule)
6778 // Dispatched behavior.
6779 DECLARE_PRINTER(JSModule)
6780 DECLARE_VERIFIER(JSModule)
6782 // Layout description.
6783 static const int kContextOffset = JSObject::kHeaderSize;
6784 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6785 static const int kSize = kScopeInfoOffset + kPointerSize;
6788 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6792 // JSFunction describes JavaScript functions.
6793 class JSFunction: public JSObject {
6795 // [prototype_or_initial_map]:
6796 DECL_ACCESSORS(prototype_or_initial_map, Object)
6798 // [shared]: The information about the function that
6799 // can be shared by instances.
6800 DECL_ACCESSORS(shared, SharedFunctionInfo)
6802 // [context]: The context for this function.
6803 inline Context* context();
6804 inline void set_context(Object* context);
6805 inline JSObject* global_proxy();
6807 // [code]: The generated code object for this function. Executed
6808 // when the function is invoked, e.g. foo() or new foo(). See
6809 // [[Call]] and [[Construct]] description in ECMA-262, section
6811 inline Code* code();
6812 inline void set_code(Code* code);
6813 inline void set_code_no_write_barrier(Code* code);
6814 inline void ReplaceCode(Code* code);
6816 // Tells whether this function is builtin.
6817 inline bool IsBuiltin();
6819 // Tells whether this function inlines the given shared function info.
6820 bool Inlines(SharedFunctionInfo* candidate);
6822 // Tells whether this function should be subject to debugging.
6823 inline bool IsSubjectToDebugging();
6825 // Tells whether or not the function needs arguments adaption.
6826 inline bool NeedsArgumentsAdaption();
6828 // Tells whether or not this function has been optimized.
6829 inline bool IsOptimized();
6831 // Mark this function for lazy recompilation. The function will be
6832 // recompiled the next time it is executed.
6833 void MarkForOptimization();
6834 void AttemptConcurrentOptimization();
6836 // Tells whether or not the function is already marked for lazy
6838 inline bool IsMarkedForOptimization();
6839 inline bool IsMarkedForConcurrentOptimization();
6841 // Tells whether or not the function is on the concurrent recompilation queue.
6842 inline bool IsInOptimizationQueue();
6844 // Inobject slack tracking is the way to reclaim unused inobject space.
6846 // The instance size is initially determined by adding some slack to
6847 // expected_nof_properties (to allow for a few extra properties added
6848 // after the constructor). There is no guarantee that the extra space
6849 // will not be wasted.
6851 // Here is the algorithm to reclaim the unused inobject space:
6852 // - Detect the first constructor call for this JSFunction.
6853 // When it happens enter the "in progress" state: initialize construction
6854 // counter in the initial_map.
6855 // - While the tracking is in progress create objects filled with
6856 // one_pointer_filler_map instead of undefined_value. This way they can be
6857 // resized quickly and safely.
6858 // - Once enough objects have been created compute the 'slack'
6859 // (traverse the map transition tree starting from the
6860 // initial_map and find the lowest value of unused_property_fields).
6861 // - Traverse the transition tree again and decrease the instance size
6862 // of every map. Existing objects will resize automatically (they are
6863 // filled with one_pointer_filler_map). All further allocations will
6864 // use the adjusted instance size.
6865 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6866 // allocations made using different closures could actually create different
6867 // kind of objects (see prototype inheritance pattern).
6869 // Important: inobject slack tracking is not attempted during the snapshot
6872 // True if the initial_map is set and the object constructions countdown
6873 // counter is not zero.
6874 static const int kGenerousAllocationCount =
6875 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6876 inline bool IsInobjectSlackTrackingInProgress();
6878 // Starts the tracking.
6879 // Initializes object constructions countdown counter in the initial map.
6880 void StartInobjectSlackTracking();
6882 // Completes the tracking.
6883 void CompleteInobjectSlackTracking();
6885 // [literals_or_bindings]: Fixed array holding either
6886 // the materialized literals or the bindings of a bound function.
6888 // If the function contains object, regexp or array literals, the
6889 // literals array prefix contains the object, regexp, and array
6890 // function to be used when creating these literals. This is
6891 // necessary so that we do not dynamically lookup the object, regexp
6892 // or array functions. Performing a dynamic lookup, we might end up
6893 // using the functions from a new context that we should not have
6896 // On bound functions, the array is a (copy-on-write) fixed-array containing
6897 // the function that was bound, bound this-value and any bound
6898 // arguments. Bound functions never contain literals.
6899 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6901 inline FixedArray* literals();
6902 inline void set_literals(FixedArray* literals);
6904 inline FixedArray* function_bindings();
6905 inline void set_function_bindings(FixedArray* bindings);
6907 // The initial map for an object created by this constructor.
6908 inline Map* initial_map();
6909 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
6910 Handle<Object> prototype);
6911 inline bool has_initial_map();
6912 static void EnsureHasInitialMap(Handle<JSFunction> function);
6914 // Get and set the prototype property on a JSFunction. If the
6915 // function has an initial map the prototype is set on the initial
6916 // map. Otherwise, the prototype is put in the initial map field
6917 // until an initial map is needed.
6918 inline bool has_prototype();
6919 inline bool has_instance_prototype();
6920 inline Object* prototype();
6921 inline Object* instance_prototype();
6922 static void SetPrototype(Handle<JSFunction> function,
6923 Handle<Object> value);
6924 static void SetInstancePrototype(Handle<JSFunction> function,
6925 Handle<Object> value);
6927 // Creates a new closure for the fucntion with the same bindings,
6928 // bound values, and prototype. An equivalent of spec operations
6929 // ``CloneMethod`` and ``CloneBoundFunction``.
6930 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
6932 // After prototype is removed, it will not be created when accessed, and
6933 // [[Construct]] from this function will not be allowed.
6934 bool RemovePrototype();
6935 inline bool should_have_prototype();
6937 // Accessor for this function's initial map's [[class]]
6938 // property. This is primarily used by ECMA native functions. This
6939 // method sets the class_name field of this function's initial map
6940 // to a given value. It creates an initial map if this function does
6941 // not have one. Note that this method does not copy the initial map
6942 // if it has one already, but simply replaces it with the new value.
6943 // Instances created afterwards will have a map whose [[class]] is
6944 // set to 'value', but there is no guarantees on instances created
6946 void SetInstanceClassName(String* name);
6948 // Returns if this function has been compiled to native code yet.
6949 inline bool is_compiled();
6951 // Returns `false` if formal parameters include rest parameters, optional
6952 // parameters, or destructuring parameters.
6953 // TODO(caitp): make this a flag set during parsing
6954 inline bool has_simple_parameters();
6956 // [next_function_link]: Links functions into various lists, e.g. the list
6957 // of optimized functions hanging off the native_context. The CodeFlusher
6958 // uses this link to chain together flushing candidates. Treated weakly
6959 // by the garbage collector.
6960 DECL_ACCESSORS(next_function_link, Object)
6962 // Prints the name of the function using PrintF.
6963 void PrintName(FILE* out = stdout);
6965 DECLARE_CAST(JSFunction)
6967 // Iterates the objects, including code objects indirectly referenced
6968 // through pointers to the first instruction in the code object.
6969 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
6971 // Dispatched behavior.
6972 DECLARE_PRINTER(JSFunction)
6973 DECLARE_VERIFIER(JSFunction)
6975 // Returns the number of allocated literals.
6976 inline int NumberOfLiterals();
6978 // Used for flags such as --hydrogen-filter.
6979 bool PassesFilter(const char* raw_filter);
6981 // The function's name if it is configured, otherwise shared function info
6983 static Handle<String> GetDebugName(Handle<JSFunction> function);
6985 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
6986 // kSize) is weak and has special handling during garbage collection.
6987 static const int kCodeEntryOffset = JSObject::kHeaderSize;
6988 static const int kPrototypeOrInitialMapOffset =
6989 kCodeEntryOffset + kPointerSize;
6990 static const int kSharedFunctionInfoOffset =
6991 kPrototypeOrInitialMapOffset + kPointerSize;
6992 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
6993 static const int kLiteralsOffset = kContextOffset + kPointerSize;
6994 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
6995 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
6996 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
6998 // Layout of the bound-function binding array.
6999 static const int kBoundFunctionIndex = 0;
7000 static const int kBoundThisIndex = 1;
7001 static const int kBoundArgumentsStartIndex = 2;
7004 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7008 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7009 // and the prototype is hidden. JSGlobalProxy always delegates
7010 // property accesses to its prototype if the prototype is not null.
7012 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7014 // Accessing a JSGlobalProxy requires security check.
7016 class JSGlobalProxy : public JSObject {
7018 // [native_context]: the owner native context of this global proxy object.
7019 // It is null value if this object is not used by any context.
7020 DECL_ACCESSORS(native_context, Object)
7022 // [hash]: The hash code property (undefined if not initialized yet).
7023 DECL_ACCESSORS(hash, Object)
7025 DECLARE_CAST(JSGlobalProxy)
7027 inline bool IsDetachedFrom(GlobalObject* global) const;
7029 // Dispatched behavior.
7030 DECLARE_PRINTER(JSGlobalProxy)
7031 DECLARE_VERIFIER(JSGlobalProxy)
7033 // Layout description.
7034 static const int kNativeContextOffset = JSObject::kHeaderSize;
7035 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7036 static const int kSize = kHashOffset + kPointerSize;
7039 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7043 // Common super class for JavaScript global objects and the special
7044 // builtins global objects.
7045 class GlobalObject: public JSObject {
7047 // [builtins]: the object holding the runtime routines written in JS.
7048 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7050 // [native context]: the natives corresponding to this global object.
7051 DECL_ACCESSORS(native_context, Context)
7053 // [global proxy]: the global proxy object of the context
7054 DECL_ACCESSORS(global_proxy, JSObject)
7056 DECLARE_CAST(GlobalObject)
7058 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7060 // Ensure that the global object has a cell for the given property name.
7061 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7064 // Layout description.
7065 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7066 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7067 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7068 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7071 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7075 // JavaScript global object.
7076 class JSGlobalObject: public GlobalObject {
7078 DECLARE_CAST(JSGlobalObject)
7080 inline bool IsDetached();
7082 // Dispatched behavior.
7083 DECLARE_PRINTER(JSGlobalObject)
7084 DECLARE_VERIFIER(JSGlobalObject)
7086 // Layout description.
7087 static const int kSize = GlobalObject::kHeaderSize;
7090 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7094 // Builtins global object which holds the runtime routines written in
7096 class JSBuiltinsObject: public GlobalObject {
7098 // Accessors for the runtime routines written in JavaScript.
7099 inline Object* javascript_builtin(Builtins::JavaScript id);
7100 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7102 DECLARE_CAST(JSBuiltinsObject)
7104 // Dispatched behavior.
7105 DECLARE_PRINTER(JSBuiltinsObject)
7106 DECLARE_VERIFIER(JSBuiltinsObject)
7108 // Layout description. The size of the builtins object includes
7109 // room for two pointers per runtime routine written in javascript
7110 // (function and code object).
7111 static const int kJSBuiltinsCount = Builtins::id_count;
7112 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7113 static const int kSize =
7114 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7116 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7117 return kJSBuiltinsOffset + id * kPointerSize;
7121 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7125 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7126 class JSValue: public JSObject {
7128 // [value]: the object being wrapped.
7129 DECL_ACCESSORS(value, Object)
7131 DECLARE_CAST(JSValue)
7133 // Dispatched behavior.
7134 DECLARE_PRINTER(JSValue)
7135 DECLARE_VERIFIER(JSValue)
7137 // Layout description.
7138 static const int kValueOffset = JSObject::kHeaderSize;
7139 static const int kSize = kValueOffset + kPointerSize;
7142 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7148 // Representation for JS date objects.
7149 class JSDate: public JSObject {
7151 // If one component is NaN, all of them are, indicating a NaN time value.
7152 // [value]: the time value.
7153 DECL_ACCESSORS(value, Object)
7154 // [year]: caches year. Either undefined, smi, or NaN.
7155 DECL_ACCESSORS(year, Object)
7156 // [month]: caches month. Either undefined, smi, or NaN.
7157 DECL_ACCESSORS(month, Object)
7158 // [day]: caches day. Either undefined, smi, or NaN.
7159 DECL_ACCESSORS(day, Object)
7160 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7161 DECL_ACCESSORS(weekday, Object)
7162 // [hour]: caches hours. Either undefined, smi, or NaN.
7163 DECL_ACCESSORS(hour, Object)
7164 // [min]: caches minutes. Either undefined, smi, or NaN.
7165 DECL_ACCESSORS(min, Object)
7166 // [sec]: caches seconds. Either undefined, smi, or NaN.
7167 DECL_ACCESSORS(sec, Object)
7168 // [cache stamp]: sample of the date cache stamp at the
7169 // moment when chached fields were cached.
7170 DECL_ACCESSORS(cache_stamp, Object)
7172 DECLARE_CAST(JSDate)
7174 // Returns the date field with the specified index.
7175 // See FieldIndex for the list of date fields.
7176 static Object* GetField(Object* date, Smi* index);
7178 void SetValue(Object* value, bool is_value_nan);
7181 // Dispatched behavior.
7182 DECLARE_PRINTER(JSDate)
7183 DECLARE_VERIFIER(JSDate)
7185 // The order is important. It must be kept in sync with date macros
7196 kFirstUncachedField,
7197 kMillisecond = kFirstUncachedField,
7201 kYearUTC = kFirstUTCField,
7214 // Layout description.
7215 static const int kValueOffset = JSObject::kHeaderSize;
7216 static const int kYearOffset = kValueOffset + kPointerSize;
7217 static const int kMonthOffset = kYearOffset + kPointerSize;
7218 static const int kDayOffset = kMonthOffset + kPointerSize;
7219 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7220 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7221 static const int kMinOffset = kHourOffset + kPointerSize;
7222 static const int kSecOffset = kMinOffset + kPointerSize;
7223 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7224 static const int kSize = kCacheStampOffset + kPointerSize;
7227 inline Object* DoGetField(FieldIndex index);
7229 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7231 // Computes and caches the cacheable fields of the date.
7232 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7235 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7239 // Representation of message objects used for error reporting through
7240 // the API. The messages are formatted in JavaScript so this object is
7241 // a real JavaScript object. The information used for formatting the
7242 // error messages are not directly accessible from JavaScript to
7243 // prevent leaking information to user code called during error
7245 class JSMessageObject: public JSObject {
7247 // [type]: the type of error message.
7248 inline int type() const;
7249 inline void set_type(int value);
7251 // [arguments]: the arguments for formatting the error message.
7252 DECL_ACCESSORS(argument, Object)
7254 // [script]: the script from which the error message originated.
7255 DECL_ACCESSORS(script, Object)
7257 // [stack_frames]: an array of stack frames for this error object.
7258 DECL_ACCESSORS(stack_frames, Object)
7260 // [start_position]: the start position in the script for the error message.
7261 inline int start_position() const;
7262 inline void set_start_position(int value);
7264 // [end_position]: the end position in the script for the error message.
7265 inline int end_position() const;
7266 inline void set_end_position(int value);
7268 DECLARE_CAST(JSMessageObject)
7270 // Dispatched behavior.
7271 DECLARE_PRINTER(JSMessageObject)
7272 DECLARE_VERIFIER(JSMessageObject)
7274 // Layout description.
7275 static const int kTypeOffset = JSObject::kHeaderSize;
7276 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7277 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7278 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7279 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7280 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7281 static const int kSize = kEndPositionOffset + kPointerSize;
7283 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7284 kStackFramesOffset + kPointerSize,
7285 kSize> BodyDescriptor;
7289 // Regular expressions
7290 // The regular expression holds a single reference to a FixedArray in
7291 // the kDataOffset field.
7292 // The FixedArray contains the following data:
7293 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7294 // - reference to the original source string
7295 // - reference to the original flag string
7296 // If it is an atom regexp
7297 // - a reference to a literal string to search for
7298 // If it is an irregexp regexp:
7299 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7300 // used for tracking the last usage (used for code flushing).
7301 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7302 // used for tracking the last usage (used for code flushing)..
7303 // - max number of registers used by irregexp implementations.
7304 // - number of capture registers (output values) of the regexp.
7305 class JSRegExp: public JSObject {
7308 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7309 // ATOM: A simple string to match against using an indexOf operation.
7310 // IRREGEXP: Compiled with Irregexp.
7311 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7312 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7319 UNICODE_ESCAPES = 16
7324 explicit Flags(uint32_t value) : value_(value) { }
7325 bool is_global() { return (value_ & GLOBAL) != 0; }
7326 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7327 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7328 bool is_sticky() { return (value_ & STICKY) != 0; }
7329 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7330 uint32_t value() { return value_; }
7335 DECL_ACCESSORS(data, Object)
7337 inline Type TypeTag();
7338 inline int CaptureCount();
7339 inline Flags GetFlags();
7340 inline String* Pattern();
7341 inline Object* DataAt(int index);
7342 // Set implementation data after the object has been prepared.
7343 inline void SetDataAt(int index, Object* value);
7345 static int code_index(bool is_latin1) {
7347 return kIrregexpLatin1CodeIndex;
7349 return kIrregexpUC16CodeIndex;
7353 static int saved_code_index(bool is_latin1) {
7355 return kIrregexpLatin1CodeSavedIndex;
7357 return kIrregexpUC16CodeSavedIndex;
7361 DECLARE_CAST(JSRegExp)
7363 // Dispatched behavior.
7364 DECLARE_VERIFIER(JSRegExp)
7366 static const int kDataOffset = JSObject::kHeaderSize;
7367 static const int kSize = kDataOffset + kPointerSize;
7369 // Indices in the data array.
7370 static const int kTagIndex = 0;
7371 static const int kSourceIndex = kTagIndex + 1;
7372 static const int kFlagsIndex = kSourceIndex + 1;
7373 static const int kDataIndex = kFlagsIndex + 1;
7374 // The data fields are used in different ways depending on the
7375 // value of the tag.
7376 // Atom regexps (literal strings).
7377 static const int kAtomPatternIndex = kDataIndex;
7379 static const int kAtomDataSize = kAtomPatternIndex + 1;
7381 // Irregexp compiled code or bytecode for Latin1. If compilation
7382 // fails, this fields hold an exception object that should be
7383 // thrown if the regexp is used again.
7384 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7385 // Irregexp compiled code or bytecode for UC16. If compilation
7386 // fails, this fields hold an exception object that should be
7387 // thrown if the regexp is used again.
7388 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7390 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7391 // is a potential candidate for flushing.
7392 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7393 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7394 // a potential candidate for flushing.
7395 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7397 // Maximal number of registers used by either Latin1 or UC16.
7398 // Only used to check that there is enough stack space
7399 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7400 // Number of captures in the compiled regexp.
7401 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7403 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7405 // Offsets directly into the data fixed array.
7406 static const int kDataTagOffset =
7407 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7408 static const int kDataOneByteCodeOffset =
7409 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7410 static const int kDataUC16CodeOffset =
7411 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7412 static const int kIrregexpCaptureCountOffset =
7413 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7415 // In-object fields.
7416 static const int kSourceFieldIndex = 0;
7417 static const int kGlobalFieldIndex = 1;
7418 static const int kIgnoreCaseFieldIndex = 2;
7419 static const int kMultilineFieldIndex = 3;
7420 static const int kLastIndexFieldIndex = 4;
7421 static const int kInObjectFieldCount = 5;
7423 // The uninitialized value for a regexp code object.
7424 static const int kUninitializedValue = -1;
7426 // The compilation error value for the regexp code object. The real error
7427 // object is in the saved code field.
7428 static const int kCompilationErrorValue = -2;
7430 // When we store the sweep generation at which we moved the code from the
7431 // code index to the saved code index we mask it of to be in the [0:255]
7433 static const int kCodeAgeMask = 0xff;
7437 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7439 static inline bool IsMatch(HashTableKey* key, Object* value) {
7440 return key->IsMatch(value);
7443 static inline uint32_t Hash(HashTableKey* key) {
7447 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7448 return key->HashForObject(object);
7451 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7453 static const int kPrefixSize = 0;
7454 static const int kEntrySize = 2;
7458 // This cache is used in two different variants. For regexp caching, it simply
7459 // maps identifying info of the regexp to the cached regexp object. Scripts and
7460 // eval code only gets cached after a second probe for the code object. To do
7461 // so, on first "put" only a hash identifying the source is entered into the
7462 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7463 // such lifetimes get reduced, and removed once they reach zero. If a second put
7464 // is called while such a hash is live in the cache, the hash gets replaced by
7465 // an actual cache entry. Age also removes stale live entries from the cache.
7466 // Such entries are identified by SharedFunctionInfos pointing to either the
7467 // recompilation stub, or to "old" code. This avoids memory leaks due to
7468 // premature caching of scripts and eval strings that are never needed later.
7469 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7470 CompilationCacheShape,
7473 // Find cached value for a string key, otherwise return null.
7474 Handle<Object> Lookup(
7475 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7476 Handle<Object> LookupEval(
7477 Handle<String> src, Handle<SharedFunctionInfo> shared,
7478 LanguageMode language_mode, int scope_position);
7479 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7480 static Handle<CompilationCacheTable> Put(
7481 Handle<CompilationCacheTable> cache, Handle<String> src,
7482 Handle<Context> context, LanguageMode language_mode,
7483 Handle<Object> value);
7484 static Handle<CompilationCacheTable> PutEval(
7485 Handle<CompilationCacheTable> cache, Handle<String> src,
7486 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7487 int scope_position);
7488 static Handle<CompilationCacheTable> PutRegExp(
7489 Handle<CompilationCacheTable> cache, Handle<String> src,
7490 JSRegExp::Flags flags, Handle<FixedArray> value);
7491 void Remove(Object* value);
7493 static const int kHashGenerations = 10;
7495 DECLARE_CAST(CompilationCacheTable)
7498 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7502 class CodeCache: public Struct {
7504 DECL_ACCESSORS(default_cache, FixedArray)
7505 DECL_ACCESSORS(normal_type_cache, Object)
7507 // Add the code object to the cache.
7509 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7511 // Lookup code object in the cache. Returns code object if found and undefined
7513 Object* Lookup(Name* name, Code::Flags flags);
7515 // Get the internal index of a code object in the cache. Returns -1 if the
7516 // code object is not in that cache. This index can be used to later call
7517 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7519 int GetIndex(Object* name, Code* code);
7521 // Remove an object from the cache with the provided internal index.
7522 void RemoveByIndex(Object* name, Code* code, int index);
7524 DECLARE_CAST(CodeCache)
7526 // Dispatched behavior.
7527 DECLARE_PRINTER(CodeCache)
7528 DECLARE_VERIFIER(CodeCache)
7530 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7531 static const int kNormalTypeCacheOffset =
7532 kDefaultCacheOffset + kPointerSize;
7533 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7536 static void UpdateDefaultCache(
7537 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7538 static void UpdateNormalTypeCache(
7539 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7540 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7541 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7543 // Code cache layout of the default cache. Elements are alternating name and
7544 // code objects for non normal load/store/call IC's.
7545 static const int kCodeCacheEntrySize = 2;
7546 static const int kCodeCacheEntryNameOffset = 0;
7547 static const int kCodeCacheEntryCodeOffset = 1;
7549 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7553 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7555 static inline bool IsMatch(HashTableKey* key, Object* value) {
7556 return key->IsMatch(value);
7559 static inline uint32_t Hash(HashTableKey* key) {
7563 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7564 return key->HashForObject(object);
7567 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7569 static const int kPrefixSize = 0;
7570 static const int kEntrySize = 2;
7574 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7575 CodeCacheHashTableShape,
7578 Object* Lookup(Name* name, Code::Flags flags);
7579 static Handle<CodeCacheHashTable> Put(
7580 Handle<CodeCacheHashTable> table,
7584 int GetIndex(Name* name, Code::Flags flags);
7585 void RemoveByIndex(int index);
7587 DECLARE_CAST(CodeCacheHashTable)
7589 // Initial size of the fixed array backing the hash table.
7590 static const int kInitialSize = 64;
7593 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7597 class PolymorphicCodeCache: public Struct {
7599 DECL_ACCESSORS(cache, Object)
7601 static void Update(Handle<PolymorphicCodeCache> cache,
7602 MapHandleList* maps,
7607 // Returns an undefined value if the entry is not found.
7608 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7610 DECLARE_CAST(PolymorphicCodeCache)
7612 // Dispatched behavior.
7613 DECLARE_PRINTER(PolymorphicCodeCache)
7614 DECLARE_VERIFIER(PolymorphicCodeCache)
7616 static const int kCacheOffset = HeapObject::kHeaderSize;
7617 static const int kSize = kCacheOffset + kPointerSize;
7620 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7624 class PolymorphicCodeCacheHashTable
7625 : public HashTable<PolymorphicCodeCacheHashTable,
7626 CodeCacheHashTableShape,
7629 Object* Lookup(MapHandleList* maps, int code_kind);
7631 static Handle<PolymorphicCodeCacheHashTable> Put(
7632 Handle<PolymorphicCodeCacheHashTable> hash_table,
7633 MapHandleList* maps,
7637 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7639 static const int kInitialSize = 64;
7641 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7645 class TypeFeedbackInfo: public Struct {
7647 inline int ic_total_count();
7648 inline void set_ic_total_count(int count);
7650 inline int ic_with_type_info_count();
7651 inline void change_ic_with_type_info_count(int delta);
7653 inline int ic_generic_count();
7654 inline void change_ic_generic_count(int delta);
7656 inline void initialize_storage();
7658 inline void change_own_type_change_checksum();
7659 inline int own_type_change_checksum();
7661 inline void set_inlined_type_change_checksum(int checksum);
7662 inline bool matches_inlined_type_change_checksum(int checksum);
7664 DECLARE_CAST(TypeFeedbackInfo)
7666 // Dispatched behavior.
7667 DECLARE_PRINTER(TypeFeedbackInfo)
7668 DECLARE_VERIFIER(TypeFeedbackInfo)
7670 static const int kStorage1Offset = HeapObject::kHeaderSize;
7671 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7672 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7673 static const int kSize = kStorage3Offset + kPointerSize;
7676 static const int kTypeChangeChecksumBits = 7;
7678 class ICTotalCountField: public BitField<int, 0,
7679 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7680 class OwnTypeChangeChecksum: public BitField<int,
7681 kSmiValueSize - kTypeChangeChecksumBits,
7682 kTypeChangeChecksumBits> {}; // NOLINT
7683 class ICsWithTypeInfoCountField: public BitField<int, 0,
7684 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7685 class InlinedTypeChangeChecksum: public BitField<int,
7686 kSmiValueSize - kTypeChangeChecksumBits,
7687 kTypeChangeChecksumBits> {}; // NOLINT
7689 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7693 enum AllocationSiteMode {
7694 DONT_TRACK_ALLOCATION_SITE,
7695 TRACK_ALLOCATION_SITE,
7696 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7700 class AllocationSite: public Struct {
7702 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7703 static const double kPretenureRatio;
7704 static const int kPretenureMinimumCreated = 100;
7706 // Values for pretenure decision field.
7707 enum PretenureDecision {
7713 kLastPretenureDecisionValue = kZombie
7716 const char* PretenureDecisionName(PretenureDecision decision);
7718 DECL_ACCESSORS(transition_info, Object)
7719 // nested_site threads a list of sites that represent nested literals
7720 // walked in a particular order. So [[1, 2], 1, 2] will have one
7721 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7722 DECL_ACCESSORS(nested_site, Object)
7723 DECL_ACCESSORS(pretenure_data, Smi)
7724 DECL_ACCESSORS(pretenure_create_count, Smi)
7725 DECL_ACCESSORS(dependent_code, DependentCode)
7726 DECL_ACCESSORS(weak_next, Object)
7728 inline void Initialize();
7730 // This method is expensive, it should only be called for reporting.
7731 bool IsNestedSite();
7733 // transition_info bitfields, for constructed array transition info.
7734 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7735 class UnusedBits: public BitField<int, 15, 14> {};
7736 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7738 // Bitfields for pretenure_data
7739 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7740 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7741 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7742 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7744 // Increments the mementos found counter and returns true when the first
7745 // memento was found for a given allocation site.
7746 inline bool IncrementMementoFoundCount();
7748 inline void IncrementMementoCreateCount();
7750 PretenureFlag GetPretenureMode();
7752 void ResetPretenureDecision();
7754 inline PretenureDecision pretenure_decision();
7755 inline void set_pretenure_decision(PretenureDecision decision);
7757 inline bool deopt_dependent_code();
7758 inline void set_deopt_dependent_code(bool deopt);
7760 inline int memento_found_count();
7761 inline void set_memento_found_count(int count);
7763 inline int memento_create_count();
7764 inline void set_memento_create_count(int count);
7766 // The pretenuring decision is made during gc, and the zombie state allows
7767 // us to recognize when an allocation site is just being kept alive because
7768 // a later traversal of new space may discover AllocationMementos that point
7769 // to this AllocationSite.
7770 inline bool IsZombie();
7772 inline bool IsMaybeTenure();
7774 inline void MarkZombie();
7776 inline bool MakePretenureDecision(PretenureDecision current_decision,
7778 bool maximum_size_scavenge);
7780 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7782 inline ElementsKind GetElementsKind();
7783 inline void SetElementsKind(ElementsKind kind);
7785 inline bool CanInlineCall();
7786 inline void SetDoNotInlineCall();
7788 inline bool SitePointsToLiteral();
7790 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7791 ElementsKind to_kind);
7793 DECLARE_PRINTER(AllocationSite)
7794 DECLARE_VERIFIER(AllocationSite)
7796 DECLARE_CAST(AllocationSite)
7797 static inline AllocationSiteMode GetMode(
7798 ElementsKind boilerplate_elements_kind);
7799 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7800 static inline bool CanTrack(InstanceType type);
7802 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7803 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7804 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7805 static const int kPretenureCreateCountOffset =
7806 kPretenureDataOffset + kPointerSize;
7807 static const int kDependentCodeOffset =
7808 kPretenureCreateCountOffset + kPointerSize;
7809 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7810 static const int kSize = kWeakNextOffset + kPointerSize;
7812 // During mark compact we need to take special care for the dependent code
7814 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7815 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7817 // For other visitors, use the fixed body descriptor below.
7818 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7819 kDependentCodeOffset + kPointerSize,
7820 kSize> BodyDescriptor;
7823 inline bool PretenuringDecisionMade();
7825 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7829 class AllocationMemento: public Struct {
7831 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7832 static const int kSize = kAllocationSiteOffset + kPointerSize;
7834 DECL_ACCESSORS(allocation_site, Object)
7836 inline bool IsValid();
7837 inline AllocationSite* GetAllocationSite();
7839 DECLARE_PRINTER(AllocationMemento)
7840 DECLARE_VERIFIER(AllocationMemento)
7842 DECLARE_CAST(AllocationMemento)
7845 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7849 // Representation of a slow alias as part of a sloppy arguments objects.
7850 // For fast aliases (if HasSloppyArgumentsElements()):
7851 // - the parameter map contains an index into the context
7852 // - all attributes of the element have default values
7853 // For slow aliases (if HasDictionaryArgumentsElements()):
7854 // - the parameter map contains no fast alias mapping (i.e. the hole)
7855 // - this struct (in the slow backing store) contains an index into the context
7856 // - all attributes are available as part if the property details
7857 class AliasedArgumentsEntry: public Struct {
7859 inline int aliased_context_slot() const;
7860 inline void set_aliased_context_slot(int count);
7862 DECLARE_CAST(AliasedArgumentsEntry)
7864 // Dispatched behavior.
7865 DECLARE_PRINTER(AliasedArgumentsEntry)
7866 DECLARE_VERIFIER(AliasedArgumentsEntry)
7868 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7869 static const int kSize = kAliasedContextSlot + kPointerSize;
7872 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7876 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7877 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7880 class StringHasher {
7882 explicit inline StringHasher(int length, uint32_t seed);
7884 template <typename schar>
7885 static inline uint32_t HashSequentialString(const schar* chars,
7889 // Reads all the data, even for long strings and computes the utf16 length.
7890 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7892 int* utf16_length_out);
7894 // Calculated hash value for a string consisting of 1 to
7895 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7896 // value is represented decimal value.
7897 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7899 // No string is allowed to have a hash of zero. That value is reserved
7900 // for internal properties. If the hash calculation yields zero then we
7902 static const int kZeroHash = 27;
7904 // Reusable parts of the hashing algorithm.
7905 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7906 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7907 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7908 const uc16* chars, int length));
7909 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
7914 // Returns the value to store in the hash field of a string with
7915 // the given length and contents.
7916 uint32_t GetHashField();
7917 // Returns true if the hash of this string can be computed without
7918 // looking at the contents.
7919 inline bool has_trivial_hash();
7920 // Adds a block of characters to the hash.
7921 template<typename Char>
7922 inline void AddCharacters(const Char* chars, int len);
7925 // Add a character to the hash.
7926 inline void AddCharacter(uint16_t c);
7927 // Update index. Returns true if string is still an index.
7928 inline bool UpdateIndex(uint16_t c);
7931 uint32_t raw_running_hash_;
7932 uint32_t array_index_;
7933 bool is_array_index_;
7934 bool is_first_char_;
7935 DISALLOW_COPY_AND_ASSIGN(StringHasher);
7939 class IteratingStringHasher : public StringHasher {
7941 static inline uint32_t Hash(String* string, uint32_t seed);
7942 inline void VisitOneByteString(const uint8_t* chars, int length);
7943 inline void VisitTwoByteString(const uint16_t* chars, int length);
7946 inline IteratingStringHasher(int len, uint32_t seed);
7947 void VisitConsString(ConsString* cons_string);
7948 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
7952 // The characteristics of a string are stored in its map. Retrieving these
7953 // few bits of information is moderately expensive, involving two memory
7954 // loads where the second is dependent on the first. To improve efficiency
7955 // the shape of the string is given its own class so that it can be retrieved
7956 // once and used for several string operations. A StringShape is small enough
7957 // to be passed by value and is immutable, but be aware that flattening a
7958 // string can potentially alter its shape. Also be aware that a GC caused by
7959 // something else can alter the shape of a string due to ConsString
7960 // shortcutting. Keeping these restrictions in mind has proven to be error-
7961 // prone and so we no longer put StringShapes in variables unless there is a
7962 // concrete performance benefit at that particular point in the code.
7963 class StringShape BASE_EMBEDDED {
7965 inline explicit StringShape(const String* s);
7966 inline explicit StringShape(Map* s);
7967 inline explicit StringShape(InstanceType t);
7968 inline bool IsSequential();
7969 inline bool IsExternal();
7970 inline bool IsCons();
7971 inline bool IsSliced();
7972 inline bool IsIndirect();
7973 inline bool IsExternalOneByte();
7974 inline bool IsExternalTwoByte();
7975 inline bool IsSequentialOneByte();
7976 inline bool IsSequentialTwoByte();
7977 inline bool IsInternalized();
7978 inline StringRepresentationTag representation_tag();
7979 inline uint32_t encoding_tag();
7980 inline uint32_t full_representation_tag();
7981 inline uint32_t size_tag();
7983 inline uint32_t type() { return type_; }
7984 inline void invalidate() { valid_ = false; }
7985 inline bool valid() { return valid_; }
7987 inline void invalidate() { }
7993 inline void set_valid() { valid_ = true; }
7996 inline void set_valid() { }
8001 // The Name abstract class captures anything that can be used as a property
8002 // name, i.e., strings and symbols. All names store a hash value.
8003 class Name: public HeapObject {
8005 // Get and set the hash field of the name.
8006 inline uint32_t hash_field();
8007 inline void set_hash_field(uint32_t value);
8009 // Tells whether the hash code has been computed.
8010 inline bool HasHashCode();
8012 // Returns a hash value used for the property table
8013 inline uint32_t Hash();
8015 // Equality operations.
8016 inline bool Equals(Name* other);
8017 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8020 inline bool AsArrayIndex(uint32_t* index);
8022 // If the name is private, it can only name own properties.
8023 inline bool IsPrivate();
8025 // If the name is a non-flat string, this method returns a flat version of the
8026 // string. Otherwise it'll just return the input.
8027 static inline Handle<Name> Flatten(Handle<Name> name,
8028 PretenureFlag pretenure = NOT_TENURED);
8032 DECLARE_PRINTER(Name)
8034 void NameShortPrint();
8035 int NameShortPrint(Vector<char> str);
8038 // Layout description.
8039 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8040 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8041 static const int kHashFieldOffset = kHashFieldSlot;
8043 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8045 static const int kSize = kHashFieldSlot + kPointerSize;
8047 // Mask constant for checking if a name has a computed hash code
8048 // and if it is a string that is an array index. The least significant bit
8049 // indicates whether a hash code has been computed. If the hash code has
8050 // been computed the 2nd bit tells whether the string can be used as an
8052 static const int kHashNotComputedMask = 1;
8053 static const int kIsNotArrayIndexMask = 1 << 1;
8054 static const int kNofHashBitFields = 2;
8056 // Shift constant retrieving hash code from hash field.
8057 static const int kHashShift = kNofHashBitFields;
8059 // Only these bits are relevant in the hash, since the top two are shifted
8061 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8063 // Array index strings this short can keep their index in the hash field.
8064 static const int kMaxCachedArrayIndexLength = 7;
8066 // For strings which are array indexes the hash value has the string length
8067 // mixed into the hash, mainly to avoid a hash value of zero which would be
8068 // the case for the string '0'. 24 bits are used for the array index value.
8069 static const int kArrayIndexValueBits = 24;
8070 static const int kArrayIndexLengthBits =
8071 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8073 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8075 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8076 kArrayIndexValueBits> {}; // NOLINT
8077 class ArrayIndexLengthBits : public BitField<unsigned int,
8078 kNofHashBitFields + kArrayIndexValueBits,
8079 kArrayIndexLengthBits> {}; // NOLINT
8081 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8082 // could use a mask to test if the length of string is less than or equal to
8083 // kMaxCachedArrayIndexLength.
8084 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8086 static const unsigned int kContainsCachedArrayIndexMask =
8087 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8088 << ArrayIndexLengthBits::kShift) |
8089 kIsNotArrayIndexMask;
8091 // Value of empty hash field indicating that the hash is not computed.
8092 static const int kEmptyHashField =
8093 kIsNotArrayIndexMask | kHashNotComputedMask;
8096 static inline bool IsHashFieldComputed(uint32_t field);
8099 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8104 class Symbol: public Name {
8106 // [name]: The print name of a symbol, or undefined if none.
8107 DECL_ACCESSORS(name, Object)
8109 DECL_ACCESSORS(flags, Smi)
8111 // [is_private]: Whether this is a private symbol. Private symbols can only
8112 // be used to designate own properties of objects.
8113 DECL_BOOLEAN_ACCESSORS(is_private)
8115 DECLARE_CAST(Symbol)
8117 // Dispatched behavior.
8118 DECLARE_PRINTER(Symbol)
8119 DECLARE_VERIFIER(Symbol)
8121 // Layout description.
8122 static const int kNameOffset = Name::kSize;
8123 static const int kFlagsOffset = kNameOffset + kPointerSize;
8124 static const int kSize = kFlagsOffset + kPointerSize;
8126 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8128 void SymbolShortPrint(std::ostream& os);
8131 static const int kPrivateBit = 0;
8133 const char* PrivateSymbolToName() const;
8136 friend class Name; // For PrivateSymbolToName.
8139 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8145 // The String abstract class captures JavaScript string values:
8148 // 4.3.16 String Value
8149 // A string value is a member of the type String and is a finite
8150 // ordered sequence of zero or more 16-bit unsigned integer values.
8152 // All string values have a length field.
8153 class String: public Name {
8155 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8157 // Array index strings this short can keep their index in the hash field.
8158 static const int kMaxCachedArrayIndexLength = 7;
8160 // For strings which are array indexes the hash value has the string length
8161 // mixed into the hash, mainly to avoid a hash value of zero which would be
8162 // the case for the string '0'. 24 bits are used for the array index value.
8163 static const int kArrayIndexValueBits = 24;
8164 static const int kArrayIndexLengthBits =
8165 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8167 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8169 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8170 kArrayIndexValueBits> {}; // NOLINT
8171 class ArrayIndexLengthBits : public BitField<unsigned int,
8172 kNofHashBitFields + kArrayIndexValueBits,
8173 kArrayIndexLengthBits> {}; // NOLINT
8175 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8176 // could use a mask to test if the length of string is less than or equal to
8177 // kMaxCachedArrayIndexLength.
8178 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8180 static const unsigned int kContainsCachedArrayIndexMask =
8181 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8182 << ArrayIndexLengthBits::kShift) |
8183 kIsNotArrayIndexMask;
8185 class SubStringRange {
8187 explicit inline SubStringRange(String* string, int first = 0,
8190 inline iterator begin();
8191 inline iterator end();
8199 // Representation of the flat content of a String.
8200 // A non-flat string doesn't have flat content.
8201 // A flat string has content that's encoded as a sequence of either
8202 // one-byte chars or two-byte UC16.
8203 // Returned by String::GetFlatContent().
8206 // Returns true if the string is flat and this structure contains content.
8207 bool IsFlat() { return state_ != NON_FLAT; }
8208 // Returns true if the structure contains one-byte content.
8209 bool IsOneByte() { return state_ == ONE_BYTE; }
8210 // Returns true if the structure contains two-byte content.
8211 bool IsTwoByte() { return state_ == TWO_BYTE; }
8213 // Return the one byte content of the string. Only use if IsOneByte()
8215 Vector<const uint8_t> ToOneByteVector() {
8216 DCHECK_EQ(ONE_BYTE, state_);
8217 return Vector<const uint8_t>(onebyte_start, length_);
8219 // Return the two-byte content of the string. Only use if IsTwoByte()
8221 Vector<const uc16> ToUC16Vector() {
8222 DCHECK_EQ(TWO_BYTE, state_);
8223 return Vector<const uc16>(twobyte_start, length_);
8227 DCHECK(i < length_);
8228 DCHECK(state_ != NON_FLAT);
8229 if (state_ == ONE_BYTE) return onebyte_start[i];
8230 return twobyte_start[i];
8233 bool UsesSameString(const FlatContent& other) const {
8234 return onebyte_start == other.onebyte_start;
8238 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8240 // Constructors only used by String::GetFlatContent().
8241 explicit FlatContent(const uint8_t* start, int length)
8242 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8243 explicit FlatContent(const uc16* start, int length)
8244 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8245 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8248 const uint8_t* onebyte_start;
8249 const uc16* twobyte_start;
8254 friend class String;
8255 friend class IterableSubString;
8258 template <typename Char>
8259 INLINE(Vector<const Char> GetCharVector());
8261 // Get and set the length of the string.
8262 inline int length() const;
8263 inline void set_length(int value);
8265 // Get and set the length of the string using acquire loads and release
8267 inline int synchronized_length() const;
8268 inline void synchronized_set_length(int value);
8270 // Returns whether this string has only one-byte chars, i.e. all of them can
8271 // be one-byte encoded. This might be the case even if the string is
8272 // two-byte. Such strings may appear when the embedder prefers
8273 // two-byte external representations even for one-byte data.
8274 inline bool IsOneByteRepresentation() const;
8275 inline bool IsTwoByteRepresentation() const;
8277 // Cons and slices have an encoding flag that may not represent the actual
8278 // encoding of the underlying string. This is taken into account here.
8279 // Requires: this->IsFlat()
8280 inline bool IsOneByteRepresentationUnderneath();
8281 inline bool IsTwoByteRepresentationUnderneath();
8283 // NOTE: this should be considered only a hint. False negatives are
8285 inline bool HasOnlyOneByteChars();
8287 // Get and set individual two byte chars in the string.
8288 inline void Set(int index, uint16_t value);
8289 // Get individual two byte char in the string. Repeated calls
8290 // to this method are not efficient unless the string is flat.
8291 INLINE(uint16_t Get(int index));
8293 // Flattens the string. Checks first inline to see if it is
8294 // necessary. Does nothing if the string is not a cons string.
8295 // Flattening allocates a sequential string with the same data as
8296 // the given string and mutates the cons string to a degenerate
8297 // form, where the first component is the new sequential string and
8298 // the second component is the empty string. If allocation fails,
8299 // this function returns a failure. If flattening succeeds, this
8300 // function returns the sequential string that is now the first
8301 // component of the cons string.
8303 // Degenerate cons strings are handled specially by the garbage
8304 // collector (see IsShortcutCandidate).
8306 static inline Handle<String> Flatten(Handle<String> string,
8307 PretenureFlag pretenure = NOT_TENURED);
8309 // Tries to return the content of a flat string as a structure holding either
8310 // a flat vector of char or of uc16.
8311 // If the string isn't flat, and therefore doesn't have flat content, the
8312 // returned structure will report so, and can't provide a vector of either
8314 FlatContent GetFlatContent();
8316 // Returns the parent of a sliced string or first part of a flat cons string.
8317 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8318 inline String* GetUnderlying();
8320 // String equality operations.
8321 inline bool Equals(String* other);
8322 inline static bool Equals(Handle<String> one, Handle<String> two);
8323 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8324 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8325 bool IsTwoByteEqualTo(Vector<const uc16> str);
8327 // Return a UTF8 representation of the string. The string is null
8328 // terminated but may optionally contain nulls. Length is returned
8329 // in length_output if length_output is not a null pointer The string
8330 // should be nearly flat, otherwise the performance of this method may
8331 // be very slow (quadratic in the length). Setting robustness_flag to
8332 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8333 // handles unexpected data without causing assert failures and it does not
8334 // do any heap allocations. This is useful when printing stack traces.
8335 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8336 RobustnessFlag robustness_flag,
8337 int offset, int length,
8338 int* length_output = 0);
8339 base::SmartArrayPointer<char> ToCString(
8340 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8341 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8342 int* length_output = 0);
8344 // Return a 16 bit Unicode representation of the string.
8345 // The string should be nearly flat, otherwise the performance of
8346 // of this method may be very bad. Setting robustness_flag to
8347 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8348 // handles unexpected data without causing assert failures and it does not
8349 // do any heap allocations. This is useful when printing stack traces.
8350 base::SmartArrayPointer<uc16> ToWideCString(
8351 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8353 bool ComputeArrayIndex(uint32_t* index);
8356 bool MakeExternal(v8::String::ExternalStringResource* resource);
8357 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8360 inline bool AsArrayIndex(uint32_t* index);
8362 DECLARE_CAST(String)
8364 void PrintOn(FILE* out);
8366 // For use during stack traces. Performs rudimentary sanity check.
8369 // Dispatched behavior.
8370 void StringShortPrint(StringStream* accumulator);
8371 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8372 #if defined(DEBUG) || defined(OBJECT_PRINT)
8373 char* ToAsciiArray();
8375 DECLARE_PRINTER(String)
8376 DECLARE_VERIFIER(String)
8378 inline bool IsFlat();
8380 // Layout description.
8381 static const int kLengthOffset = Name::kSize;
8382 static const int kSize = kLengthOffset + kPointerSize;
8384 // Maximum number of characters to consider when trying to convert a string
8385 // value into an array index.
8386 static const int kMaxArrayIndexSize = 10;
8387 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8390 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8391 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8392 static const int kMaxUtf16CodeUnit = 0xffff;
8393 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8395 // Value of hash field containing computed hash equal to zero.
8396 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8398 // Maximal string length.
8399 static const int kMaxLength = (1 << 28) - 16;
8401 // Max length for computing hash. For strings longer than this limit the
8402 // string length is used as the hash value.
8403 static const int kMaxHashCalcLength = 16383;
8405 // Limit for truncation in short printing.
8406 static const int kMaxShortPrintLength = 1024;
8408 // Support for regular expressions.
8409 const uc16* GetTwoByteData(unsigned start);
8411 // Helper function for flattening strings.
8412 template <typename sinkchar>
8413 static void WriteToFlat(String* source,
8418 // The return value may point to the first aligned word containing the first
8419 // non-one-byte character, rather than directly to the non-one-byte character.
8420 // If the return value is >= the passed length, the entire string was
8422 static inline int NonAsciiStart(const char* chars, int length) {
8423 const char* start = chars;
8424 const char* limit = chars + length;
8426 if (length >= kIntptrSize) {
8427 // Check unaligned bytes.
8428 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8429 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8430 return static_cast<int>(chars - start);
8434 // Check aligned words.
8435 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8436 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8437 while (chars + sizeof(uintptr_t) <= limit) {
8438 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8439 return static_cast<int>(chars - start);
8441 chars += sizeof(uintptr_t);
8444 // Check remaining unaligned bytes.
8445 while (chars < limit) {
8446 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8447 return static_cast<int>(chars - start);
8452 return static_cast<int>(chars - start);
8455 static inline bool IsAscii(const char* chars, int length) {
8456 return NonAsciiStart(chars, length) >= length;
8459 static inline bool IsAscii(const uint8_t* chars, int length) {
8461 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8464 static inline int NonOneByteStart(const uc16* chars, int length) {
8465 const uc16* limit = chars + length;
8466 const uc16* start = chars;
8467 while (chars < limit) {
8468 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8471 return static_cast<int>(chars - start);
8474 static inline bool IsOneByte(const uc16* chars, int length) {
8475 return NonOneByteStart(chars, length) >= length;
8478 template<class Visitor>
8479 static inline ConsString* VisitFlat(Visitor* visitor,
8483 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8484 bool include_ending_line);
8486 // Use the hash field to forward to the canonical internalized string
8487 // when deserializing an internalized string.
8488 inline void SetForwardedInternalizedString(String* string);
8489 inline String* GetForwardedInternalizedString();
8493 friend class StringTableInsertionKey;
8495 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8496 PretenureFlag tenure);
8498 // Slow case of String::Equals. This implementation works on any strings
8499 // but it is most efficient on strings that are almost flat.
8500 bool SlowEquals(String* other);
8502 static bool SlowEquals(Handle<String> one, Handle<String> two);
8504 // Slow case of AsArrayIndex.
8505 bool SlowAsArrayIndex(uint32_t* index);
8507 // Compute and set the hash code.
8508 uint32_t ComputeAndSetHash();
8510 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8514 // The SeqString abstract class captures sequential string values.
8515 class SeqString: public String {
8517 DECLARE_CAST(SeqString)
8519 // Layout description.
8520 static const int kHeaderSize = String::kSize;
8522 // Truncate the string in-place if possible and return the result.
8523 // In case of new_length == 0, the empty string is returned without
8524 // truncating the original string.
8525 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8528 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8532 // The OneByteString class captures sequential one-byte string objects.
8533 // Each character in the OneByteString is an one-byte character.
8534 class SeqOneByteString: public SeqString {
8536 static const bool kHasOneByteEncoding = true;
8538 // Dispatched behavior.
8539 inline uint16_t SeqOneByteStringGet(int index);
8540 inline void SeqOneByteStringSet(int index, uint16_t value);
8542 // Get the address of the characters in this string.
8543 inline Address GetCharsAddress();
8545 inline uint8_t* GetChars();
8547 DECLARE_CAST(SeqOneByteString)
8549 // Garbage collection support. This method is called by the
8550 // garbage collector to compute the actual size of an OneByteString
8552 inline int SeqOneByteStringSize(InstanceType instance_type);
8554 // Computes the size for an OneByteString instance of a given length.
8555 static int SizeFor(int length) {
8556 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8559 // Maximal memory usage for a single sequential one-byte string.
8560 static const int kMaxSize = 512 * MB - 1;
8561 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8564 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8568 // The TwoByteString class captures sequential unicode string objects.
8569 // Each character in the TwoByteString is a two-byte uint16_t.
8570 class SeqTwoByteString: public SeqString {
8572 static const bool kHasOneByteEncoding = false;
8574 // Dispatched behavior.
8575 inline uint16_t SeqTwoByteStringGet(int index);
8576 inline void SeqTwoByteStringSet(int index, uint16_t value);
8578 // Get the address of the characters in this string.
8579 inline Address GetCharsAddress();
8581 inline uc16* GetChars();
8584 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8586 DECLARE_CAST(SeqTwoByteString)
8588 // Garbage collection support. This method is called by the
8589 // garbage collector to compute the actual size of a TwoByteString
8591 inline int SeqTwoByteStringSize(InstanceType instance_type);
8593 // Computes the size for a TwoByteString instance of a given length.
8594 static int SizeFor(int length) {
8595 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8598 // Maximal memory usage for a single sequential two-byte string.
8599 static const int kMaxSize = 512 * MB - 1;
8600 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8601 String::kMaxLength);
8604 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8608 // The ConsString class describes string values built by using the
8609 // addition operator on strings. A ConsString is a pair where the
8610 // first and second components are pointers to other string values.
8611 // One or both components of a ConsString can be pointers to other
8612 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8613 // are non-ConsString string values. The string value represented by
8614 // a ConsString can be obtained by concatenating the leaf string
8615 // values in a left-to-right depth-first traversal of the tree.
8616 class ConsString: public String {
8618 // First string of the cons cell.
8619 inline String* first();
8620 // Doesn't check that the result is a string, even in debug mode. This is
8621 // useful during GC where the mark bits confuse the checks.
8622 inline Object* unchecked_first();
8623 inline void set_first(String* first,
8624 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8626 // Second string of the cons cell.
8627 inline String* second();
8628 // Doesn't check that the result is a string, even in debug mode. This is
8629 // useful during GC where the mark bits confuse the checks.
8630 inline Object* unchecked_second();
8631 inline void set_second(String* second,
8632 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8634 // Dispatched behavior.
8635 uint16_t ConsStringGet(int index);
8637 DECLARE_CAST(ConsString)
8639 // Layout description.
8640 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8641 static const int kSecondOffset = kFirstOffset + kPointerSize;
8642 static const int kSize = kSecondOffset + kPointerSize;
8644 // Minimum length for a cons string.
8645 static const int kMinLength = 13;
8647 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8650 DECLARE_VERIFIER(ConsString)
8653 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8657 // The Sliced String class describes strings that are substrings of another
8658 // sequential string. The motivation is to save time and memory when creating
8659 // a substring. A Sliced String is described as a pointer to the parent,
8660 // the offset from the start of the parent string and the length. Using
8661 // a Sliced String therefore requires unpacking of the parent string and
8662 // adding the offset to the start address. A substring of a Sliced String
8663 // are not nested since the double indirection is simplified when creating
8664 // such a substring.
8665 // Currently missing features are:
8666 // - handling externalized parent strings
8667 // - external strings as parent
8668 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8669 class SlicedString: public String {
8671 inline String* parent();
8672 inline void set_parent(String* parent,
8673 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8674 inline int offset() const;
8675 inline void set_offset(int offset);
8677 // Dispatched behavior.
8678 uint16_t SlicedStringGet(int index);
8680 DECLARE_CAST(SlicedString)
8682 // Layout description.
8683 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8684 static const int kOffsetOffset = kParentOffset + kPointerSize;
8685 static const int kSize = kOffsetOffset + kPointerSize;
8687 // Minimum length for a sliced string.
8688 static const int kMinLength = 13;
8690 typedef FixedBodyDescriptor<kParentOffset,
8691 kOffsetOffset + kPointerSize, kSize>
8694 DECLARE_VERIFIER(SlicedString)
8697 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8701 // The ExternalString class describes string values that are backed by
8702 // a string resource that lies outside the V8 heap. ExternalStrings
8703 // consist of the length field common to all strings, a pointer to the
8704 // external resource. It is important to ensure (externally) that the
8705 // resource is not deallocated while the ExternalString is live in the
8708 // The API expects that all ExternalStrings are created through the
8709 // API. Therefore, ExternalStrings should not be used internally.
8710 class ExternalString: public String {
8712 DECLARE_CAST(ExternalString)
8714 // Layout description.
8715 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8716 static const int kShortSize = kResourceOffset + kPointerSize;
8717 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8718 static const int kSize = kResourceDataOffset + kPointerSize;
8720 static const int kMaxShortLength =
8721 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8723 // Return whether external string is short (data pointer is not cached).
8724 inline bool is_short();
8726 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8729 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8733 // The ExternalOneByteString class is an external string backed by an
8735 class ExternalOneByteString : public ExternalString {
8737 static const bool kHasOneByteEncoding = true;
8739 typedef v8::String::ExternalOneByteStringResource Resource;
8741 // The underlying resource.
8742 inline const Resource* resource();
8743 inline void set_resource(const Resource* buffer);
8745 // Update the pointer cache to the external character array.
8746 // The cached pointer is always valid, as the external character array does =
8747 // not move during lifetime. Deserialization is the only exception, after
8748 // which the pointer cache has to be refreshed.
8749 inline void update_data_cache();
8751 inline const uint8_t* GetChars();
8753 // Dispatched behavior.
8754 inline uint16_t ExternalOneByteStringGet(int index);
8756 DECLARE_CAST(ExternalOneByteString)
8758 // Garbage collection support.
8759 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8761 template <typename StaticVisitor>
8762 inline void ExternalOneByteStringIterateBody();
8765 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8769 // The ExternalTwoByteString class is an external string backed by a UTF-16
8771 class ExternalTwoByteString: public ExternalString {
8773 static const bool kHasOneByteEncoding = false;
8775 typedef v8::String::ExternalStringResource Resource;
8777 // The underlying string resource.
8778 inline const Resource* resource();
8779 inline void set_resource(const Resource* buffer);
8781 // Update the pointer cache to the external character array.
8782 // The cached pointer is always valid, as the external character array does =
8783 // not move during lifetime. Deserialization is the only exception, after
8784 // which the pointer cache has to be refreshed.
8785 inline void update_data_cache();
8787 inline const uint16_t* GetChars();
8789 // Dispatched behavior.
8790 inline uint16_t ExternalTwoByteStringGet(int index);
8793 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8795 DECLARE_CAST(ExternalTwoByteString)
8797 // Garbage collection support.
8798 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8800 template<typename StaticVisitor>
8801 inline void ExternalTwoByteStringIterateBody();
8804 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8808 // Utility superclass for stack-allocated objects that must be updated
8809 // on gc. It provides two ways for the gc to update instances, either
8810 // iterating or updating after gc.
8811 class Relocatable BASE_EMBEDDED {
8813 explicit inline Relocatable(Isolate* isolate);
8814 inline virtual ~Relocatable();
8815 virtual void IterateInstance(ObjectVisitor* v) { }
8816 virtual void PostGarbageCollection() { }
8818 static void PostGarbageCollectionProcessing(Isolate* isolate);
8819 static int ArchiveSpacePerThread();
8820 static char* ArchiveState(Isolate* isolate, char* to);
8821 static char* RestoreState(Isolate* isolate, char* from);
8822 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8823 static void Iterate(ObjectVisitor* v, Relocatable* top);
8824 static char* Iterate(ObjectVisitor* v, char* t);
8832 // A flat string reader provides random access to the contents of a
8833 // string independent of the character width of the string. The handle
8834 // must be valid as long as the reader is being used.
8835 class FlatStringReader : public Relocatable {
8837 FlatStringReader(Isolate* isolate, Handle<String> str);
8838 FlatStringReader(Isolate* isolate, Vector<const char> input);
8839 void PostGarbageCollection();
8840 inline uc32 Get(int index);
8841 template <typename Char>
8842 inline Char Get(int index);
8843 int length() { return length_; }
8852 // This maintains an off-stack representation of the stack frames required
8853 // to traverse a ConsString, allowing an entirely iterative and restartable
8854 // traversal of the entire string
8855 class ConsStringIterator {
8857 inline ConsStringIterator() {}
8858 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8859 Reset(cons_string, offset);
8861 inline void Reset(ConsString* cons_string, int offset = 0) {
8863 // Next will always return NULL.
8864 if (cons_string == NULL) return;
8865 Initialize(cons_string, offset);
8867 // Returns NULL when complete.
8868 inline String* Next(int* offset_out) {
8870 if (depth_ == 0) return NULL;
8871 return Continue(offset_out);
8875 static const int kStackSize = 32;
8876 // Use a mask instead of doing modulo operations for stack wrapping.
8877 static const int kDepthMask = kStackSize-1;
8878 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8879 static inline int OffsetForDepth(int depth);
8881 inline void PushLeft(ConsString* string);
8882 inline void PushRight(ConsString* string);
8883 inline void AdjustMaximumDepth();
8885 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8886 void Initialize(ConsString* cons_string, int offset);
8887 String* Continue(int* offset_out);
8888 String* NextLeaf(bool* blew_stack);
8889 String* Search(int* offset_out);
8891 // Stack must always contain only frames for which right traversal
8892 // has not yet been performed.
8893 ConsString* frames_[kStackSize];
8898 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8902 class StringCharacterStream {
8904 inline StringCharacterStream(String* string,
8906 inline uint16_t GetNext();
8907 inline bool HasMore();
8908 inline void Reset(String* string, int offset = 0);
8909 inline void VisitOneByteString(const uint8_t* chars, int length);
8910 inline void VisitTwoByteString(const uint16_t* chars, int length);
8913 ConsStringIterator iter_;
8916 const uint8_t* buffer8_;
8917 const uint16_t* buffer16_;
8919 const uint8_t* end_;
8920 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
8924 template <typename T>
8925 class VectorIterator {
8927 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
8928 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
8929 T GetNext() { return data_[index_++]; }
8930 bool has_more() { return index_ < data_.length(); }
8932 Vector<const T> data_;
8937 // The Oddball describes objects null, undefined, true, and false.
8938 class Oddball: public HeapObject {
8940 // [to_string]: Cached to_string computed at startup.
8941 DECL_ACCESSORS(to_string, String)
8943 // [to_number]: Cached to_number computed at startup.
8944 DECL_ACCESSORS(to_number, Object)
8946 // [typeof]: Cached type_of computed at startup.
8947 DECL_ACCESSORS(type_of, String)
8949 inline byte kind() const;
8950 inline void set_kind(byte kind);
8952 DECLARE_CAST(Oddball)
8954 // Dispatched behavior.
8955 DECLARE_VERIFIER(Oddball)
8957 // Initialize the fields.
8958 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
8959 const char* to_string, Handle<Object> to_number,
8960 const char* type_of, byte kind);
8962 // Layout description.
8963 static const int kToStringOffset = HeapObject::kHeaderSize;
8964 static const int kToNumberOffset = kToStringOffset + kPointerSize;
8965 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
8966 static const int kKindOffset = kTypeOfOffset + kPointerSize;
8967 static const int kSize = kKindOffset + kPointerSize;
8969 static const byte kFalse = 0;
8970 static const byte kTrue = 1;
8971 static const byte kNotBooleanMask = ~1;
8972 static const byte kTheHole = 2;
8973 static const byte kNull = 3;
8974 static const byte kArgumentMarker = 4;
8975 static const byte kUndefined = 5;
8976 static const byte kUninitialized = 6;
8977 static const byte kOther = 7;
8978 static const byte kException = 8;
8980 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
8981 kSize> BodyDescriptor;
8983 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
8984 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
8985 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
8988 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
8992 class Cell: public HeapObject {
8994 // [value]: value of the cell.
8995 DECL_ACCESSORS(value, Object)
8999 static inline Cell* FromValueAddress(Address value) {
9000 Object* result = FromAddress(value - kValueOffset);
9001 return static_cast<Cell*>(result);
9004 inline Address ValueAddress() {
9005 return address() + kValueOffset;
9008 // Dispatched behavior.
9009 DECLARE_PRINTER(Cell)
9010 DECLARE_VERIFIER(Cell)
9012 // Layout description.
9013 static const int kValueOffset = HeapObject::kHeaderSize;
9014 static const int kSize = kValueOffset + kPointerSize;
9016 typedef FixedBodyDescriptor<kValueOffset,
9017 kValueOffset + kPointerSize,
9018 kSize> BodyDescriptor;
9021 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9025 class PropertyCell : public HeapObject {
9027 // [property_details]: details of the global property.
9028 DECL_ACCESSORS(property_details_raw, Object)
9029 // [value]: value of the global property.
9030 DECL_ACCESSORS(value, Object)
9031 // [dependent_code]: dependent code that depends on the type of the global
9033 DECL_ACCESSORS(dependent_code, DependentCode)
9035 inline PropertyDetails property_details();
9036 inline void set_property_details(PropertyDetails details);
9038 PropertyCellConstantType GetConstantType();
9040 // Computes the new type of the cell's contents for the given value, but
9041 // without actually modifying the details.
9042 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9043 Handle<Object> value,
9044 PropertyDetails details);
9045 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9046 Handle<Object> value, PropertyDetails details);
9048 static Handle<PropertyCell> InvalidateEntry(
9049 Handle<GlobalDictionary> dictionary, int entry);
9051 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9052 Handle<Object> new_value);
9054 DECLARE_CAST(PropertyCell)
9056 // Dispatched behavior.
9057 DECLARE_PRINTER(PropertyCell)
9058 DECLARE_VERIFIER(PropertyCell)
9060 // Layout description.
9061 static const int kDetailsOffset = HeapObject::kHeaderSize;
9062 static const int kValueOffset = kDetailsOffset + kPointerSize;
9063 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9064 static const int kSize = kDependentCodeOffset + kPointerSize;
9066 static const int kPointerFieldsBeginOffset = kValueOffset;
9067 static const int kPointerFieldsEndOffset = kSize;
9069 typedef FixedBodyDescriptor<kValueOffset,
9071 kSize> BodyDescriptor;
9074 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9078 class WeakCell : public HeapObject {
9080 inline Object* value() const;
9082 // This should not be called by anyone except GC.
9083 inline void clear();
9085 // This should not be called by anyone except allocator.
9086 inline void initialize(HeapObject* value);
9088 inline bool cleared() const;
9090 DECL_ACCESSORS(next, Object)
9092 inline void clear_next(Heap* heap);
9094 inline bool next_cleared();
9096 DECLARE_CAST(WeakCell)
9098 DECLARE_PRINTER(WeakCell)
9099 DECLARE_VERIFIER(WeakCell)
9101 // Layout description.
9102 static const int kValueOffset = HeapObject::kHeaderSize;
9103 static const int kNextOffset = kValueOffset + kPointerSize;
9104 static const int kSize = kNextOffset + kPointerSize;
9106 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9109 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9113 // The JSProxy describes EcmaScript Harmony proxies
9114 class JSProxy: public JSReceiver {
9116 // [handler]: The handler property.
9117 DECL_ACCESSORS(handler, Object)
9119 // [hash]: The hash code property (undefined if not initialized yet).
9120 DECL_ACCESSORS(hash, Object)
9122 DECLARE_CAST(JSProxy)
9124 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9125 Handle<JSProxy> proxy,
9126 Handle<Object> receiver,
9129 // If the handler defines an accessor property with a setter, invoke it.
9130 // If it defines an accessor property without a setter, or a data property
9131 // that is read-only, throw. In all these cases set '*done' to true,
9132 // otherwise set it to false.
9134 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9135 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9136 Handle<Object> value, LanguageMode language_mode, bool* done);
9138 MUST_USE_RESULT static Maybe<PropertyAttributes>
9139 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9140 Handle<Object> receiver,
9142 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9143 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9144 Handle<Object> value, LanguageMode language_mode);
9146 // Turn the proxy into an (empty) JSObject.
9147 static void Fix(Handle<JSProxy> proxy);
9149 // Initializes the body after the handler slot.
9150 inline void InitializeBody(int object_size, Object* value);
9152 // Invoke a trap by name. If the trap does not exist on this's handler,
9153 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9154 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9155 Handle<JSProxy> proxy,
9157 Handle<Object> derived_trap,
9159 Handle<Object> args[]);
9161 // Dispatched behavior.
9162 DECLARE_PRINTER(JSProxy)
9163 DECLARE_VERIFIER(JSProxy)
9165 // Layout description. We add padding so that a proxy has the same
9166 // size as a virgin JSObject. This is essential for becoming a JSObject
9168 static const int kHandlerOffset = HeapObject::kHeaderSize;
9169 static const int kHashOffset = kHandlerOffset + kPointerSize;
9170 static const int kPaddingOffset = kHashOffset + kPointerSize;
9171 static const int kSize = JSObject::kHeaderSize;
9172 static const int kHeaderSize = kPaddingOffset;
9173 static const int kPaddingSize = kSize - kPaddingOffset;
9175 STATIC_ASSERT(kPaddingSize >= 0);
9177 typedef FixedBodyDescriptor<kHandlerOffset,
9179 kSize> BodyDescriptor;
9182 friend class JSReceiver;
9184 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9185 Handle<JSProxy> proxy, Handle<Name> name);
9187 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9188 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9190 MUST_USE_RESULT Object* GetIdentityHash();
9192 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9194 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9198 class JSFunctionProxy: public JSProxy {
9200 // [call_trap]: The call trap.
9201 DECL_ACCESSORS(call_trap, Object)
9203 // [construct_trap]: The construct trap.
9204 DECL_ACCESSORS(construct_trap, Object)
9206 DECLARE_CAST(JSFunctionProxy)
9208 // Dispatched behavior.
9209 DECLARE_PRINTER(JSFunctionProxy)
9210 DECLARE_VERIFIER(JSFunctionProxy)
9212 // Layout description.
9213 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9214 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9215 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9216 static const int kSize = JSFunction::kSize;
9217 static const int kPaddingSize = kSize - kPaddingOffset;
9219 STATIC_ASSERT(kPaddingSize >= 0);
9221 typedef FixedBodyDescriptor<kHandlerOffset,
9222 kConstructTrapOffset + kPointerSize,
9223 kSize> BodyDescriptor;
9226 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9230 class JSCollection : public JSObject {
9232 // [table]: the backing hash table
9233 DECL_ACCESSORS(table, Object)
9235 static const int kTableOffset = JSObject::kHeaderSize;
9236 static const int kSize = kTableOffset + kPointerSize;
9239 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9243 // The JSSet describes EcmaScript Harmony sets
9244 class JSSet : public JSCollection {
9248 // Dispatched behavior.
9249 DECLARE_PRINTER(JSSet)
9250 DECLARE_VERIFIER(JSSet)
9253 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9257 // The JSMap describes EcmaScript Harmony maps
9258 class JSMap : public JSCollection {
9262 // Dispatched behavior.
9263 DECLARE_PRINTER(JSMap)
9264 DECLARE_VERIFIER(JSMap)
9267 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9271 // OrderedHashTableIterator is an iterator that iterates over the keys and
9272 // values of an OrderedHashTable.
9274 // The iterator has a reference to the underlying OrderedHashTable data,
9275 // [table], as well as the current [index] the iterator is at.
9277 // When the OrderedHashTable is rehashed it adds a reference from the old table
9278 // to the new table as well as storing enough data about the changes so that the
9279 // iterator [index] can be adjusted accordingly.
9281 // When the [Next] result from the iterator is requested, the iterator checks if
9282 // there is a newer table that it needs to transition to.
9283 template<class Derived, class TableType>
9284 class OrderedHashTableIterator: public JSObject {
9286 // [table]: the backing hash table mapping keys to values.
9287 DECL_ACCESSORS(table, Object)
9289 // [index]: The index into the data table.
9290 DECL_ACCESSORS(index, Object)
9292 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9293 DECL_ACCESSORS(kind, Object)
9296 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9299 static const int kTableOffset = JSObject::kHeaderSize;
9300 static const int kIndexOffset = kTableOffset + kPointerSize;
9301 static const int kKindOffset = kIndexOffset + kPointerSize;
9302 static const int kSize = kKindOffset + kPointerSize;
9310 // Whether the iterator has more elements. This needs to be called before
9311 // calling |CurrentKey| and/or |CurrentValue|.
9314 // Move the index forward one.
9316 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9319 // Populates the array with the next key and value and then moves the iterator
9321 // This returns the |kind| or 0 if the iterator is already at the end.
9322 Smi* Next(JSArray* value_array);
9324 // Returns the current key of the iterator. This should only be called when
9325 // |HasMore| returns true.
9326 inline Object* CurrentKey();
9329 // Transitions the iterator to the non obsolete backing store. This is a NOP
9330 // if the [table] is not obsolete.
9333 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9337 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9340 // Dispatched behavior.
9341 DECLARE_PRINTER(JSSetIterator)
9342 DECLARE_VERIFIER(JSSetIterator)
9344 DECLARE_CAST(JSSetIterator)
9346 // Called by |Next| to populate the array. This allows the subclasses to
9347 // populate the array differently.
9348 inline void PopulateValueArray(FixedArray* array);
9351 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9355 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9358 // Dispatched behavior.
9359 DECLARE_PRINTER(JSMapIterator)
9360 DECLARE_VERIFIER(JSMapIterator)
9362 DECLARE_CAST(JSMapIterator)
9364 // Called by |Next| to populate the array. This allows the subclasses to
9365 // populate the array differently.
9366 inline void PopulateValueArray(FixedArray* array);
9369 // Returns the current value of the iterator. This should only be called when
9370 // |HasMore| returns true.
9371 inline Object* CurrentValue();
9373 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9377 // Base class for both JSWeakMap and JSWeakSet
9378 class JSWeakCollection: public JSObject {
9380 // [table]: the backing hash table mapping keys to values.
9381 DECL_ACCESSORS(table, Object)
9383 // [next]: linked list of encountered weak maps during GC.
9384 DECL_ACCESSORS(next, Object)
9386 static const int kTableOffset = JSObject::kHeaderSize;
9387 static const int kNextOffset = kTableOffset + kPointerSize;
9388 static const int kSize = kNextOffset + kPointerSize;
9391 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9395 // The JSWeakMap describes EcmaScript Harmony weak maps
9396 class JSWeakMap: public JSWeakCollection {
9398 DECLARE_CAST(JSWeakMap)
9400 // Dispatched behavior.
9401 DECLARE_PRINTER(JSWeakMap)
9402 DECLARE_VERIFIER(JSWeakMap)
9405 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9409 // The JSWeakSet describes EcmaScript Harmony weak sets
9410 class JSWeakSet: public JSWeakCollection {
9412 DECLARE_CAST(JSWeakSet)
9414 // Dispatched behavior.
9415 DECLARE_PRINTER(JSWeakSet)
9416 DECLARE_VERIFIER(JSWeakSet)
9419 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9423 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9424 enum class SharedFlag { kNotShared, kShared };
9427 class JSArrayBuffer: public JSObject {
9429 // [backing_store]: backing memory for this array
9430 DECL_ACCESSORS(backing_store, void)
9432 // [byte_length]: length in bytes
9433 DECL_ACCESSORS(byte_length, Object)
9435 inline uint32_t bit_field() const;
9436 inline void set_bit_field(uint32_t bits);
9438 inline bool is_external();
9439 inline void set_is_external(bool value);
9441 inline bool is_neuterable();
9442 inline void set_is_neuterable(bool value);
9444 inline bool was_neutered();
9445 inline void set_was_neutered(bool value);
9447 inline bool is_shared();
9448 inline void set_is_shared(bool value);
9450 DECLARE_CAST(JSArrayBuffer)
9454 // Dispatched behavior.
9455 DECLARE_PRINTER(JSArrayBuffer)
9456 DECLARE_VERIFIER(JSArrayBuffer)
9458 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9459 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9460 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9461 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9462 static const int kBitFieldOffset = kBitFieldSlot;
9464 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9466 static const int kSize = kBitFieldSlot + kPointerSize;
9468 static const int kSizeWithInternalFields =
9469 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9471 class IsExternal : public BitField<bool, 1, 1> {};
9472 class IsNeuterable : public BitField<bool, 2, 1> {};
9473 class WasNeutered : public BitField<bool, 3, 1> {};
9474 class IsShared : public BitField<bool, 4, 1> {};
9477 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9481 class JSArrayBufferView: public JSObject {
9483 // [buffer]: ArrayBuffer that this typed array views.
9484 DECL_ACCESSORS(buffer, Object)
9486 // [byte_offset]: offset of typed array in bytes.
9487 DECL_ACCESSORS(byte_offset, Object)
9489 // [byte_length]: length of typed array in bytes.
9490 DECL_ACCESSORS(byte_length, Object)
9492 DECLARE_CAST(JSArrayBufferView)
9494 DECLARE_VERIFIER(JSArrayBufferView)
9496 inline bool WasNeutered() const;
9498 static const int kBufferOffset = JSObject::kHeaderSize;
9499 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9500 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9501 static const int kViewSize = kByteLengthOffset + kPointerSize;
9505 DECL_ACCESSORS(raw_byte_offset, Object)
9506 DECL_ACCESSORS(raw_byte_length, Object)
9509 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9513 class JSTypedArray: public JSArrayBufferView {
9515 // [length]: length of typed array in elements.
9516 DECL_ACCESSORS(length, Object)
9517 inline uint32_t length_value() const;
9519 DECLARE_CAST(JSTypedArray)
9521 ExternalArrayType type();
9522 size_t element_size();
9524 Handle<JSArrayBuffer> GetBuffer();
9526 // Dispatched behavior.
9527 DECLARE_PRINTER(JSTypedArray)
9528 DECLARE_VERIFIER(JSTypedArray)
9530 static const int kLengthOffset = kViewSize + kPointerSize;
9531 static const int kSize = kLengthOffset + kPointerSize;
9533 static const int kSizeWithInternalFields =
9534 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9537 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9538 Handle<JSTypedArray> typed_array);
9540 DECL_ACCESSORS(raw_length, Object)
9543 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9547 class JSDataView: public JSArrayBufferView {
9549 DECLARE_CAST(JSDataView)
9551 // Dispatched behavior.
9552 DECLARE_PRINTER(JSDataView)
9553 DECLARE_VERIFIER(JSDataView)
9555 static const int kSize = kViewSize;
9557 static const int kSizeWithInternalFields =
9558 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9561 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9565 // Foreign describes objects pointing from JavaScript to C structures.
9566 class Foreign: public HeapObject {
9568 // [address]: field containing the address.
9569 inline Address foreign_address();
9570 inline void set_foreign_address(Address value);
9572 DECLARE_CAST(Foreign)
9574 // Dispatched behavior.
9575 inline void ForeignIterateBody(ObjectVisitor* v);
9577 template<typename StaticVisitor>
9578 inline void ForeignIterateBody();
9580 // Dispatched behavior.
9581 DECLARE_PRINTER(Foreign)
9582 DECLARE_VERIFIER(Foreign)
9584 // Layout description.
9586 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9587 static const int kSize = kForeignAddressOffset + kPointerSize;
9589 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9592 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9596 // The JSArray describes JavaScript Arrays
9597 // Such an array can be in one of two modes:
9598 // - fast, backing storage is a FixedArray and length <= elements.length();
9599 // Please note: push and pop can be used to grow and shrink the array.
9600 // - slow, backing storage is a HashTable with numbers as keys.
9601 class JSArray: public JSObject {
9603 // [length]: The length property.
9604 DECL_ACCESSORS(length, Object)
9606 // Overload the length setter to skip write barrier when the length
9607 // is set to a smi. This matches the set function on FixedArray.
9608 inline void set_length(Smi* length);
9610 static bool HasReadOnlyLength(Handle<JSArray> array);
9611 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9612 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9614 // Initialize the array with the given capacity. The function may
9615 // fail due to out-of-memory situations, but only if the requested
9616 // capacity is non-zero.
9617 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9619 // If the JSArray has fast elements, and new_length would result in
9620 // normalization, returns true.
9621 bool SetLengthWouldNormalize(uint32_t new_length);
9622 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9624 // Initializes the array to a certain length.
9625 inline bool AllowsSetLength();
9627 static void SetLength(Handle<JSArray> array, uint32_t length);
9628 // Same as above but will also queue splice records if |array| is observed.
9629 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9632 // Set the content of the array to the content of storage.
9633 static inline void SetContent(Handle<JSArray> array,
9634 Handle<FixedArrayBase> storage);
9636 DECLARE_CAST(JSArray)
9638 // Dispatched behavior.
9639 DECLARE_PRINTER(JSArray)
9640 DECLARE_VERIFIER(JSArray)
9642 // Number of element slots to pre-allocate for an empty array.
9643 static const int kPreallocatedArrayElements = 4;
9645 // Layout description.
9646 static const int kLengthOffset = JSObject::kHeaderSize;
9647 static const int kSize = kLengthOffset + kPointerSize;
9650 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9654 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9655 Handle<Map> initial_map);
9658 // JSRegExpResult is just a JSArray with a specific initial map.
9659 // This initial map adds in-object properties for "index" and "input"
9660 // properties, as assigned by RegExp.prototype.exec, which allows
9661 // faster creation of RegExp exec results.
9662 // This class just holds constants used when creating the result.
9663 // After creation the result must be treated as a JSArray in all regards.
9664 class JSRegExpResult: public JSArray {
9666 // Offsets of object fields.
9667 static const int kIndexOffset = JSArray::kSize;
9668 static const int kInputOffset = kIndexOffset + kPointerSize;
9669 static const int kSize = kInputOffset + kPointerSize;
9670 // Indices of in-object properties.
9671 static const int kIndexIndex = 0;
9672 static const int kInputIndex = 1;
9674 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9678 class AccessorInfo: public Struct {
9680 DECL_ACCESSORS(name, Object)
9681 DECL_ACCESSORS(flag, Smi)
9682 DECL_ACCESSORS(expected_receiver_type, Object)
9684 inline bool all_can_read();
9685 inline void set_all_can_read(bool value);
9687 inline bool all_can_write();
9688 inline void set_all_can_write(bool value);
9690 inline bool is_special_data_property();
9691 inline void set_is_special_data_property(bool value);
9693 inline PropertyAttributes property_attributes();
9694 inline void set_property_attributes(PropertyAttributes attributes);
9696 // Checks whether the given receiver is compatible with this accessor.
9697 static bool IsCompatibleReceiverMap(Isolate* isolate,
9698 Handle<AccessorInfo> info,
9700 inline bool IsCompatibleReceiver(Object* receiver);
9702 DECLARE_CAST(AccessorInfo)
9704 // Dispatched behavior.
9705 DECLARE_VERIFIER(AccessorInfo)
9707 // Append all descriptors to the array that are not already there.
9708 // Return number added.
9709 static int AppendUnique(Handle<Object> descriptors,
9710 Handle<FixedArray> array,
9711 int valid_descriptors);
9713 static const int kNameOffset = HeapObject::kHeaderSize;
9714 static const int kFlagOffset = kNameOffset + kPointerSize;
9715 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9716 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9719 inline bool HasExpectedReceiverType();
9721 // Bit positions in flag.
9722 static const int kAllCanReadBit = 0;
9723 static const int kAllCanWriteBit = 1;
9724 static const int kSpecialDataProperty = 2;
9725 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9727 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9731 // An accessor must have a getter, but can have no setter.
9733 // When setting a property, V8 searches accessors in prototypes.
9734 // If an accessor was found and it does not have a setter,
9735 // the request is ignored.
9737 // If the accessor in the prototype has the READ_ONLY property attribute, then
9738 // a new value is added to the derived object when the property is set.
9739 // This shadows the accessor in the prototype.
9740 class ExecutableAccessorInfo: public AccessorInfo {
9742 DECL_ACCESSORS(getter, Object)
9743 DECL_ACCESSORS(setter, Object)
9744 DECL_ACCESSORS(data, Object)
9746 DECLARE_CAST(ExecutableAccessorInfo)
9748 // Dispatched behavior.
9749 DECLARE_PRINTER(ExecutableAccessorInfo)
9750 DECLARE_VERIFIER(ExecutableAccessorInfo)
9752 static const int kGetterOffset = AccessorInfo::kSize;
9753 static const int kSetterOffset = kGetterOffset + kPointerSize;
9754 static const int kDataOffset = kSetterOffset + kPointerSize;
9755 static const int kSize = kDataOffset + kPointerSize;
9757 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9760 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9764 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9765 // accessor can either be
9766 // * a pointer to a JavaScript function or proxy: a real accessor
9767 // * undefined: considered an accessor by the spec, too, strangely enough
9768 // * the hole: an accessor which has not been set
9769 // * a pointer to a map: a transition used to ensure map sharing
9770 class AccessorPair: public Struct {
9772 DECL_ACCESSORS(getter, Object)
9773 DECL_ACCESSORS(setter, Object)
9775 DECLARE_CAST(AccessorPair)
9777 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9779 inline Object* get(AccessorComponent component);
9780 inline void set(AccessorComponent component, Object* value);
9782 // Note: Returns undefined instead in case of a hole.
9783 Object* GetComponent(AccessorComponent component);
9785 // Set both components, skipping arguments which are a JavaScript null.
9786 inline void SetComponents(Object* getter, Object* setter);
9788 inline bool Equals(AccessorPair* pair);
9789 inline bool Equals(Object* getter_value, Object* setter_value);
9791 inline bool ContainsAccessor();
9793 // Dispatched behavior.
9794 DECLARE_PRINTER(AccessorPair)
9795 DECLARE_VERIFIER(AccessorPair)
9797 static const int kGetterOffset = HeapObject::kHeaderSize;
9798 static const int kSetterOffset = kGetterOffset + kPointerSize;
9799 static const int kSize = kSetterOffset + kPointerSize;
9802 // Strangely enough, in addition to functions and harmony proxies, the spec
9803 // requires us to consider undefined as a kind of accessor, too:
9805 // Object.defineProperty(obj, "foo", {get: undefined});
9806 // assertTrue("foo" in obj);
9807 inline bool IsJSAccessor(Object* obj);
9809 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9813 class AccessCheckInfo: public Struct {
9815 DECL_ACCESSORS(named_callback, Object)
9816 DECL_ACCESSORS(indexed_callback, Object)
9817 DECL_ACCESSORS(data, Object)
9819 DECLARE_CAST(AccessCheckInfo)
9821 // Dispatched behavior.
9822 DECLARE_PRINTER(AccessCheckInfo)
9823 DECLARE_VERIFIER(AccessCheckInfo)
9825 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9826 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9827 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9828 static const int kSize = kDataOffset + kPointerSize;
9831 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9835 class InterceptorInfo: public Struct {
9837 DECL_ACCESSORS(getter, Object)
9838 DECL_ACCESSORS(setter, Object)
9839 DECL_ACCESSORS(query, Object)
9840 DECL_ACCESSORS(deleter, Object)
9841 DECL_ACCESSORS(enumerator, Object)
9842 DECL_ACCESSORS(data, Object)
9843 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9844 DECL_BOOLEAN_ACCESSORS(all_can_read)
9845 DECL_BOOLEAN_ACCESSORS(non_masking)
9847 inline int flags() const;
9848 inline void set_flags(int flags);
9850 DECLARE_CAST(InterceptorInfo)
9852 // Dispatched behavior.
9853 DECLARE_PRINTER(InterceptorInfo)
9854 DECLARE_VERIFIER(InterceptorInfo)
9856 static const int kGetterOffset = HeapObject::kHeaderSize;
9857 static const int kSetterOffset = kGetterOffset + kPointerSize;
9858 static const int kQueryOffset = kSetterOffset + kPointerSize;
9859 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9860 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9861 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9862 static const int kFlagsOffset = kDataOffset + kPointerSize;
9863 static const int kSize = kFlagsOffset + kPointerSize;
9865 static const int kCanInterceptSymbolsBit = 0;
9866 static const int kAllCanReadBit = 1;
9867 static const int kNonMasking = 2;
9870 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9874 class CallHandlerInfo: public Struct {
9876 DECL_ACCESSORS(callback, Object)
9877 DECL_ACCESSORS(data, Object)
9879 DECLARE_CAST(CallHandlerInfo)
9881 // Dispatched behavior.
9882 DECLARE_PRINTER(CallHandlerInfo)
9883 DECLARE_VERIFIER(CallHandlerInfo)
9885 static const int kCallbackOffset = HeapObject::kHeaderSize;
9886 static const int kDataOffset = kCallbackOffset + kPointerSize;
9887 static const int kSize = kDataOffset + kPointerSize;
9890 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
9894 class TemplateInfo: public Struct {
9896 DECL_ACCESSORS(tag, Object)
9897 inline int number_of_properties() const;
9898 inline void set_number_of_properties(int value);
9899 DECL_ACCESSORS(property_list, Object)
9900 DECL_ACCESSORS(property_accessors, Object)
9902 DECLARE_VERIFIER(TemplateInfo)
9904 static const int kTagOffset = HeapObject::kHeaderSize;
9905 static const int kNumberOfProperties = kTagOffset + kPointerSize;
9906 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
9907 static const int kPropertyAccessorsOffset =
9908 kPropertyListOffset + kPointerSize;
9909 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
9912 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
9916 class FunctionTemplateInfo: public TemplateInfo {
9918 DECL_ACCESSORS(serial_number, Object)
9919 DECL_ACCESSORS(call_code, Object)
9920 DECL_ACCESSORS(prototype_template, Object)
9921 DECL_ACCESSORS(parent_template, Object)
9922 DECL_ACCESSORS(named_property_handler, Object)
9923 DECL_ACCESSORS(indexed_property_handler, Object)
9924 DECL_ACCESSORS(instance_template, Object)
9925 DECL_ACCESSORS(class_name, Object)
9926 DECL_ACCESSORS(signature, Object)
9927 DECL_ACCESSORS(instance_call_handler, Object)
9928 DECL_ACCESSORS(access_check_info, Object)
9929 DECL_ACCESSORS(flag, Smi)
9931 inline int length() const;
9932 inline void set_length(int value);
9934 // Following properties use flag bits.
9935 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
9936 DECL_BOOLEAN_ACCESSORS(undetectable)
9937 // If the bit is set, object instances created by this function
9938 // requires access check.
9939 DECL_BOOLEAN_ACCESSORS(needs_access_check)
9940 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
9941 DECL_BOOLEAN_ACCESSORS(remove_prototype)
9942 DECL_BOOLEAN_ACCESSORS(do_not_cache)
9943 DECL_BOOLEAN_ACCESSORS(instantiated)
9944 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
9946 DECLARE_CAST(FunctionTemplateInfo)
9948 // Dispatched behavior.
9949 DECLARE_PRINTER(FunctionTemplateInfo)
9950 DECLARE_VERIFIER(FunctionTemplateInfo)
9952 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
9953 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
9954 static const int kPrototypeTemplateOffset =
9955 kCallCodeOffset + kPointerSize;
9956 static const int kParentTemplateOffset =
9957 kPrototypeTemplateOffset + kPointerSize;
9958 static const int kNamedPropertyHandlerOffset =
9959 kParentTemplateOffset + kPointerSize;
9960 static const int kIndexedPropertyHandlerOffset =
9961 kNamedPropertyHandlerOffset + kPointerSize;
9962 static const int kInstanceTemplateOffset =
9963 kIndexedPropertyHandlerOffset + kPointerSize;
9964 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
9965 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
9966 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
9967 static const int kAccessCheckInfoOffset =
9968 kInstanceCallHandlerOffset + kPointerSize;
9969 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
9970 static const int kLengthOffset = kFlagOffset + kPointerSize;
9971 static const int kSize = kLengthOffset + kPointerSize;
9973 // Returns true if |object| is an instance of this function template.
9974 bool IsTemplateFor(Object* object);
9975 bool IsTemplateFor(Map* map);
9977 // Returns the holder JSObject if the function can legally be called with this
9978 // receiver. Returns Heap::null_value() if the call is illegal.
9979 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
9982 // Bit position in the flag, from least significant bit position.
9983 static const int kHiddenPrototypeBit = 0;
9984 static const int kUndetectableBit = 1;
9985 static const int kNeedsAccessCheckBit = 2;
9986 static const int kReadOnlyPrototypeBit = 3;
9987 static const int kRemovePrototypeBit = 4;
9988 static const int kDoNotCacheBit = 5;
9989 static const int kInstantiatedBit = 6;
9990 static const int kAcceptAnyReceiver = 7;
9992 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
9996 class ObjectTemplateInfo: public TemplateInfo {
9998 DECL_ACCESSORS(constructor, Object)
9999 DECL_ACCESSORS(internal_field_count, Object)
10001 DECLARE_CAST(ObjectTemplateInfo)
10003 // Dispatched behavior.
10004 DECLARE_PRINTER(ObjectTemplateInfo)
10005 DECLARE_VERIFIER(ObjectTemplateInfo)
10007 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10008 static const int kInternalFieldCountOffset =
10009 kConstructorOffset + kPointerSize;
10010 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10014 class TypeSwitchInfo: public Struct {
10016 DECL_ACCESSORS(types, Object)
10018 DECLARE_CAST(TypeSwitchInfo)
10020 // Dispatched behavior.
10021 DECLARE_PRINTER(TypeSwitchInfo)
10022 DECLARE_VERIFIER(TypeSwitchInfo)
10024 static const int kTypesOffset = Struct::kHeaderSize;
10025 static const int kSize = kTypesOffset + kPointerSize;
10029 // The DebugInfo class holds additional information for a function being
10031 class DebugInfo: public Struct {
10033 // The shared function info for the source being debugged.
10034 DECL_ACCESSORS(shared, SharedFunctionInfo)
10035 // Code object for the patched code. This code object is the code object
10036 // currently active for the function.
10037 DECL_ACCESSORS(code, Code)
10038 // Fixed array holding status information for each active break point.
10039 DECL_ACCESSORS(break_points, FixedArray)
10041 // Check if there is a break point at a code position.
10042 bool HasBreakPoint(int code_position);
10043 // Get the break point info object for a code position.
10044 Object* GetBreakPointInfo(int code_position);
10045 // Clear a break point.
10046 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10048 Handle<Object> break_point_object);
10049 // Set a break point.
10050 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10051 int source_position, int statement_position,
10052 Handle<Object> break_point_object);
10053 // Get the break point objects for a code position.
10054 Handle<Object> GetBreakPointObjects(int code_position);
10055 // Find the break point info holding this break point object.
10056 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10057 Handle<Object> break_point_object);
10058 // Get the number of break points for this function.
10059 int GetBreakPointCount();
10061 DECLARE_CAST(DebugInfo)
10063 // Dispatched behavior.
10064 DECLARE_PRINTER(DebugInfo)
10065 DECLARE_VERIFIER(DebugInfo)
10067 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10068 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10069 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10070 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10072 static const int kEstimatedNofBreakPointsInFunction = 16;
10075 static const int kNoBreakPointInfo = -1;
10077 // Lookup the index in the break_points array for a code position.
10078 int GetBreakPointInfoIndex(int code_position);
10080 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10084 // The BreakPointInfo class holds information for break points set in a
10085 // function. The DebugInfo object holds a BreakPointInfo object for each code
10086 // position with one or more break points.
10087 class BreakPointInfo: public Struct {
10089 // The position in the code for the break point.
10090 DECL_ACCESSORS(code_position, Smi)
10091 // The position in the source for the break position.
10092 DECL_ACCESSORS(source_position, Smi)
10093 // The position in the source for the last statement before this break
10095 DECL_ACCESSORS(statement_position, Smi)
10096 // List of related JavaScript break points.
10097 DECL_ACCESSORS(break_point_objects, Object)
10099 // Removes a break point.
10100 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10101 Handle<Object> break_point_object);
10102 // Set a break point.
10103 static void SetBreakPoint(Handle<BreakPointInfo> info,
10104 Handle<Object> break_point_object);
10105 // Check if break point info has this break point object.
10106 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10107 Handle<Object> break_point_object);
10108 // Get the number of break points for this code position.
10109 int GetBreakPointCount();
10111 DECLARE_CAST(BreakPointInfo)
10113 // Dispatched behavior.
10114 DECLARE_PRINTER(BreakPointInfo)
10115 DECLARE_VERIFIER(BreakPointInfo)
10117 static const int kCodePositionIndex = Struct::kHeaderSize;
10118 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10119 static const int kStatementPositionIndex =
10120 kSourcePositionIndex + kPointerSize;
10121 static const int kBreakPointObjectsIndex =
10122 kStatementPositionIndex + kPointerSize;
10123 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10126 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10130 #undef DECL_BOOLEAN_ACCESSORS
10131 #undef DECL_ACCESSORS
10132 #undef DECLARE_CAST
10133 #undef DECLARE_VERIFIER
10135 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10136 V(kStringTable, "string_table", "(Internalized strings)") \
10137 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10138 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10139 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10140 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10141 V(kTop, "top", "(Isolate)") \
10142 V(kRelocatable, "relocatable", "(Relocatable)") \
10143 V(kDebug, "debug", "(Debugger)") \
10144 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10145 V(kHandleScope, "handlescope", "(Handle scope)") \
10146 V(kBuiltins, "builtins", "(Builtins)") \
10147 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10148 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10149 V(kThreadManager, "threadmanager", "(Thread manager)") \
10150 V(kStrongRoots, "strong roots", "(Strong roots)") \
10151 V(kExtensions, "Extensions", "(Extensions)")
10153 class VisitorSynchronization : public AllStatic {
10155 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10157 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10160 #undef DECLARE_ENUM
10162 static const char* const kTags[kNumberOfSyncTags];
10163 static const char* const kTagNames[kNumberOfSyncTags];
10166 // Abstract base class for visiting, and optionally modifying, the
10167 // pointers contained in Objects. Used in GC and serialization/deserialization.
10168 class ObjectVisitor BASE_EMBEDDED {
10170 virtual ~ObjectVisitor() {}
10172 // Visits a contiguous arrays of pointers in the half-open range
10173 // [start, end). Any or all of the values may be modified on return.
10174 virtual void VisitPointers(Object** start, Object** end) = 0;
10176 // Handy shorthand for visiting a single pointer.
10177 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10179 // Visit weak next_code_link in Code object.
10180 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10182 // To allow lazy clearing of inline caches the visitor has
10183 // a rich interface for iterating over Code objects..
10185 // Visits a code target in the instruction stream.
10186 virtual void VisitCodeTarget(RelocInfo* rinfo);
10188 // Visits a code entry in a JS function.
10189 virtual void VisitCodeEntry(Address entry_address);
10191 // Visits a global property cell reference in the instruction stream.
10192 virtual void VisitCell(RelocInfo* rinfo);
10194 // Visits a runtime entry in the instruction stream.
10195 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10197 // Visits the resource of an one-byte or two-byte string.
10198 virtual void VisitExternalOneByteString(
10199 v8::String::ExternalOneByteStringResource** resource) {}
10200 virtual void VisitExternalTwoByteString(
10201 v8::String::ExternalStringResource** resource) {}
10203 // Visits a debug call target in the instruction stream.
10204 virtual void VisitDebugTarget(RelocInfo* rinfo);
10206 // Visits the byte sequence in a function's prologue that contains information
10207 // about the code's age.
10208 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10210 // Visit pointer embedded into a code object.
10211 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10213 // Visits an external reference embedded into a code object.
10214 virtual void VisitExternalReference(RelocInfo* rinfo);
10216 // Visits an external reference.
10217 virtual void VisitExternalReference(Address* p) {}
10219 // Visits an (encoded) internal reference.
10220 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10222 // Visits a handle that has an embedder-assigned class ID.
10223 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10225 // Intended for serialization/deserialization checking: insert, or
10226 // check for the presence of, a tag at this position in the stream.
10227 // Also used for marking up GC roots in heap snapshots.
10228 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10232 class StructBodyDescriptor : public
10233 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10235 static inline int SizeOf(Map* map, HeapObject* object);
10239 // BooleanBit is a helper class for setting and getting a bit in an
10241 class BooleanBit : public AllStatic {
10243 static inline bool get(Smi* smi, int bit_position) {
10244 return get(smi->value(), bit_position);
10247 static inline bool get(int value, int bit_position) {
10248 return (value & (1 << bit_position)) != 0;
10251 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10252 return Smi::FromInt(set(smi->value(), bit_position, v));
10255 static inline int set(int value, int bit_position, bool v) {
10257 value |= (1 << bit_position);
10259 value &= ~(1 << bit_position);
10265 } } // namespace v8::internal
10267 #endif // V8_OBJECTS_H_