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) \
394 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE) \
396 V(FIXED_ARRAY_TYPE) \
397 V(FIXED_DOUBLE_ARRAY_TYPE) \
398 V(SHARED_FUNCTION_INFO_TYPE) \
401 V(JS_MESSAGE_OBJECT_TYPE) \
406 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
407 V(JS_GENERATOR_OBJECT_TYPE) \
409 V(JS_GLOBAL_OBJECT_TYPE) \
410 V(JS_BUILTINS_OBJECT_TYPE) \
411 V(JS_GLOBAL_PROXY_TYPE) \
413 V(JS_ARRAY_BUFFER_TYPE) \
414 V(JS_TYPED_ARRAY_TYPE) \
415 V(JS_DATA_VIEW_TYPE) \
419 V(JS_SET_ITERATOR_TYPE) \
420 V(JS_MAP_ITERATOR_TYPE) \
421 V(JS_WEAK_MAP_TYPE) \
422 V(JS_WEAK_SET_TYPE) \
425 V(JS_FUNCTION_TYPE) \
426 V(JS_FUNCTION_PROXY_TYPE) \
428 V(BREAK_POINT_INFO_TYPE)
431 // Since string types are not consecutive, this macro is used to
432 // iterate over them.
433 #define STRING_TYPE_LIST(V) \
434 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
435 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
437 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
438 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
440 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
441 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
442 SlicedOneByteString) \
443 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
445 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
446 external_one_byte_string, ExternalOneByteString) \
447 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
448 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
449 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
450 short_external_string, ShortExternalString) \
451 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
452 short_external_one_byte_string, ShortExternalOneByteString) \
453 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
454 ExternalTwoByteString::kShortSize, \
455 short_external_string_with_one_byte_data, \
456 ShortExternalStringWithOneByteData) \
458 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
459 InternalizedString) \
460 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
461 one_byte_internalized_string, OneByteInternalizedString) \
462 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
463 external_internalized_string, ExternalInternalizedString) \
464 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
465 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
466 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
467 ExternalTwoByteString::kSize, \
468 external_internalized_string_with_one_byte_data, \
469 ExternalInternalizedStringWithOneByteData) \
470 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
471 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
472 ShortExternalInternalizedString) \
473 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
474 ExternalOneByteString::kShortSize, \
475 short_external_one_byte_internalized_string, \
476 ShortExternalOneByteInternalizedString) \
477 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
478 ExternalTwoByteString::kShortSize, \
479 short_external_internalized_string_with_one_byte_data, \
480 ShortExternalInternalizedStringWithOneByteData)
482 // A struct is a simple object a set of object-valued fields. Including an
483 // object type in this causes the compiler to generate most of the boilerplate
484 // code for the class including allocation and garbage collection routines,
485 // casts and predicates. All you need to define is the class, methods and
486 // object verification routines. Easy, no?
488 // Note that for subtle reasons related to the ordering or numerical values of
489 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
491 #define STRUCT_LIST(V) \
493 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
494 executable_accessor_info) \
495 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
496 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
497 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
498 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
499 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
500 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
501 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
502 V(SCRIPT, Script, script) \
503 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
504 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
505 V(CODE_CACHE, CodeCache, code_cache) \
506 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
507 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
508 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
509 V(DEBUG_INFO, DebugInfo, debug_info) \
510 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
511 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info) \
512 V(SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION, \
513 SloppyBlockWithEvalContextExtension, \
514 sloppy_block_with_eval_context_extension)
516 // We use the full 8 bits of the instance_type field to encode heap object
517 // instance types. The high-order bit (bit 7) is set if the object is not a
518 // string, and cleared if it is a string.
519 const uint32_t kIsNotStringMask = 0x80;
520 const uint32_t kStringTag = 0x0;
521 const uint32_t kNotStringTag = 0x80;
523 // Bit 6 indicates that the object is an internalized string (if set) or not.
524 // Bit 7 has to be clear as well.
525 const uint32_t kIsNotInternalizedMask = 0x40;
526 const uint32_t kNotInternalizedTag = 0x40;
527 const uint32_t kInternalizedTag = 0x0;
529 // If bit 7 is clear then bit 2 indicates whether the string consists of
530 // two-byte characters or one-byte characters.
531 const uint32_t kStringEncodingMask = 0x4;
532 const uint32_t kTwoByteStringTag = 0x0;
533 const uint32_t kOneByteStringTag = 0x4;
535 // If bit 7 is clear, the low-order 2 bits indicate the representation
537 const uint32_t kStringRepresentationMask = 0x03;
538 enum StringRepresentationTag {
540 kConsStringTag = 0x1,
541 kExternalStringTag = 0x2,
542 kSlicedStringTag = 0x3
544 const uint32_t kIsIndirectStringMask = 0x1;
545 const uint32_t kIsIndirectStringTag = 0x1;
546 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
547 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
548 STATIC_ASSERT((kConsStringTag &
549 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
550 STATIC_ASSERT((kSlicedStringTag &
551 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
553 // Use this mask to distinguish between cons and slice only after making
554 // sure that the string is one of the two (an indirect string).
555 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
556 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
558 // If bit 7 is clear, then bit 3 indicates whether this two-byte
559 // string actually contains one byte data.
560 const uint32_t kOneByteDataHintMask = 0x08;
561 const uint32_t kOneByteDataHintTag = 0x08;
563 // If bit 7 is clear and string representation indicates an external string,
564 // then bit 4 indicates whether the data pointer is cached.
565 const uint32_t kShortExternalStringMask = 0x10;
566 const uint32_t kShortExternalStringTag = 0x10;
569 // A ConsString with an empty string as the right side is a candidate
570 // for being shortcut by the garbage collector. We don't allocate any
571 // non-flat internalized strings, so we do not shortcut them thereby
572 // avoiding turning internalized strings into strings. The bit-masks
573 // below contain the internalized bit as additional safety.
574 // See heap.cc, mark-compact.cc and objects-visiting.cc.
575 const uint32_t kShortcutTypeMask =
577 kIsNotInternalizedMask |
578 kStringRepresentationMask;
579 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
581 static inline bool IsShortcutCandidate(int type) {
582 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
588 INTERNALIZED_STRING_TYPE = kTwoByteStringTag | kSeqStringTag |
589 kInternalizedTag, // FIRST_PRIMITIVE_TYPE
590 ONE_BYTE_INTERNALIZED_STRING_TYPE =
591 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
592 EXTERNAL_INTERNALIZED_STRING_TYPE =
593 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
594 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
595 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
596 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
597 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
599 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
600 kShortExternalStringTag |
602 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
603 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
605 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
606 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
607 kShortExternalStringTag | kInternalizedTag,
608 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
609 ONE_BYTE_STRING_TYPE =
610 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
611 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
612 CONS_ONE_BYTE_STRING_TYPE =
613 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
615 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
616 SLICED_ONE_BYTE_STRING_TYPE =
617 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
618 EXTERNAL_STRING_TYPE =
619 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
620 EXTERNAL_ONE_BYTE_STRING_TYPE =
621 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
622 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
623 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
625 SHORT_EXTERNAL_STRING_TYPE =
626 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
627 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
628 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
629 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
630 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
634 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
636 // Other primitives (cannot contain non-map-word pointers to heap objects).
639 ODDBALL_TYPE, // LAST_PRIMITIVE_TYPE
641 // Objects allocated in their own spaces (never in new space).
645 // "Data", objects that cannot contain non-map-word pointers to heap
647 MUTABLE_HEAP_NUMBER_TYPE,
652 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
653 FIXED_UINT8_ARRAY_TYPE,
654 FIXED_INT16_ARRAY_TYPE,
655 FIXED_UINT16_ARRAY_TYPE,
656 FIXED_INT32_ARRAY_TYPE,
657 FIXED_UINT32_ARRAY_TYPE,
658 FIXED_FLOAT32_ARRAY_TYPE,
659 FIXED_FLOAT64_ARRAY_TYPE,
660 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
661 FIXED_DOUBLE_ARRAY_TYPE,
662 FILLER_TYPE, // LAST_DATA_TYPE
665 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
666 DECLARED_ACCESSOR_INFO_TYPE,
667 EXECUTABLE_ACCESSOR_INFO_TYPE,
669 ACCESS_CHECK_INFO_TYPE,
670 INTERCEPTOR_INFO_TYPE,
671 CALL_HANDLER_INFO_TYPE,
672 FUNCTION_TEMPLATE_INFO_TYPE,
673 OBJECT_TEMPLATE_INFO_TYPE,
675 TYPE_SWITCH_INFO_TYPE,
676 ALLOCATION_SITE_TYPE,
677 ALLOCATION_MEMENTO_TYPE,
680 POLYMORPHIC_CODE_CACHE_TYPE,
681 TYPE_FEEDBACK_INFO_TYPE,
682 ALIASED_ARGUMENTS_ENTRY_TYPE,
685 BREAK_POINT_INFO_TYPE,
687 SHARED_FUNCTION_INFO_TYPE,
692 SLOPPY_BLOCK_WITH_EVAL_CONTEXT_EXTENSION_TYPE,
694 // All the following types are subtypes of JSReceiver, which corresponds to
695 // objects in the JS sense. The first and the last type in this range are
696 // the two forms of function. This organization enables using the same
697 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
698 // NONCALLABLE_JS_OBJECT range.
699 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
700 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
701 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
702 JS_MESSAGE_OBJECT_TYPE,
705 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
706 JS_GENERATOR_OBJECT_TYPE,
708 JS_GLOBAL_OBJECT_TYPE,
709 JS_BUILTINS_OBJECT_TYPE,
710 JS_GLOBAL_PROXY_TYPE,
712 JS_ARRAY_BUFFER_TYPE,
717 JS_SET_ITERATOR_TYPE,
718 JS_MAP_ITERATOR_TYPE,
722 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
726 LAST_TYPE = JS_FUNCTION_TYPE,
727 FIRST_NAME_TYPE = FIRST_TYPE,
728 LAST_NAME_TYPE = SYMBOL_TYPE,
729 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
730 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
731 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
732 FIRST_PRIMITIVE_TYPE = FIRST_NAME_TYPE,
733 LAST_PRIMITIVE_TYPE = ODDBALL_TYPE,
734 // Boundaries for testing for a fixed typed array.
735 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
736 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
737 // Boundary for promotion to old space.
738 LAST_DATA_TYPE = FILLER_TYPE,
739 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
740 // Note that there is no range for JSObject or JSProxy, since their subtypes
741 // are not continuous in this enum! The enum ranges instead reflect the
742 // external class names, where proxies are treated as either ordinary objects,
744 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
745 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
746 // Boundaries for testing the types represented as JSObject
747 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
748 LAST_JS_OBJECT_TYPE = LAST_TYPE,
749 // Boundaries for testing the types represented as JSProxy
750 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
751 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
752 // Boundaries for testing whether the type is a JavaScript object.
753 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
754 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
755 // Boundaries for testing the types for which typeof is "object".
756 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
757 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
758 // Note that the types for which typeof is "function" are not continuous.
759 // Define this so that we can put assertions on discrete checks.
760 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
763 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
764 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
765 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
766 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
769 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
770 V(FAST_ELEMENTS_SUB_TYPE) \
771 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
772 V(FAST_PROPERTIES_SUB_TYPE) \
773 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
774 V(MAP_CODE_CACHE_SUB_TYPE) \
775 V(SCOPE_INFO_SUB_TYPE) \
776 V(STRING_TABLE_SUB_TYPE) \
777 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
778 V(TRANSITION_ARRAY_SUB_TYPE)
780 enum FixedArraySubInstanceType {
781 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
782 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
783 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
784 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
797 #define DECL_BOOLEAN_ACCESSORS(name) \
798 inline bool name() const; \
799 inline void set_##name(bool value); \
802 #define DECL_ACCESSORS(name, type) \
803 inline type* name() const; \
804 inline void set_##name(type* value, \
805 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
808 #define DECLARE_CAST(type) \
809 INLINE(static type* cast(Object* object)); \
810 INLINE(static const type* cast(const Object* object));
814 class AllocationSite;
815 class AllocationSiteCreationContext;
816 class AllocationSiteUsageContext;
819 class ElementsAccessor;
820 class FixedArrayBase;
821 class FunctionLiteral;
823 class JSBuiltinsObject;
824 class LayoutDescriptor;
825 class LookupIterator;
826 class ObjectHashTable;
829 class SafepointEntry;
830 class SharedFunctionInfo;
832 class TypeFeedbackInfo;
833 class TypeFeedbackVector;
836 // We cannot just say "class HeapType;" if it is created from a template... =8-?
837 template<class> class TypeImpl;
838 struct HeapTypeConfig;
839 typedef TypeImpl<HeapTypeConfig> HeapType;
842 // A template-ized version of the IsXXX functions.
843 template <class C> inline bool Is(Object* obj);
846 #define DECLARE_VERIFIER(Name) void Name##Verify();
848 #define DECLARE_VERIFIER(Name)
852 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
854 #define DECLARE_PRINTER(Name)
858 #define OBJECT_TYPE_LIST(V) \
863 #define HEAP_OBJECT_TYPE_LIST(V) \
865 V(MutableHeapNumber) \
881 V(ExternalTwoByteString) \
882 V(ExternalOneByteString) \
883 V(SeqTwoByteString) \
884 V(SeqOneByteString) \
885 V(InternalizedString) \
888 V(FixedTypedArrayBase) \
891 V(FixedUint16Array) \
893 V(FixedUint32Array) \
895 V(FixedFloat32Array) \
896 V(FixedFloat64Array) \
897 V(FixedUint8ClampedArray) \
903 V(JSContextExtensionObject) \
904 V(JSGeneratorObject) \
906 V(LayoutDescriptor) \
910 V(TypeFeedbackVector) \
911 V(DeoptimizationInputData) \
912 V(DeoptimizationOutputData) \
916 V(FixedDoubleArray) \
920 V(ScriptContextTable) \
926 V(SharedFunctionInfo) \
935 V(JSArrayBufferView) \
944 V(JSWeakCollection) \
951 V(NormalizedMapCache) \
952 V(CompilationCacheTable) \
953 V(CodeCacheHashTable) \
954 V(PolymorphicCodeCacheHashTable) \
959 V(JSBuiltinsObject) \
961 V(UndetectableObject) \
962 V(AccessCheckNeeded) \
970 // Object is the abstract superclass for all classes in the
972 // Object does not use any virtual functions to avoid the
973 // allocation of the C++ vtable.
974 // Since both Smi and HeapObject are subclasses of Object no
975 // data members can be present in Object.
979 bool IsObject() const { return true; }
981 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
982 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
983 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
984 #undef IS_TYPE_FUNCTION_DECL
986 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
987 // a keyed store is of the form a[expression] = foo.
988 enum StoreFromKeyed {
989 MAY_BE_STORE_FROM_KEYED,
990 CERTAINLY_NOT_STORE_FROM_KEYED
993 INLINE(bool IsFixedArrayBase() const);
994 INLINE(bool IsExternal() const);
995 INLINE(bool IsAccessorInfo() const);
997 INLINE(bool IsStruct() const);
998 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
999 INLINE(bool Is##Name() const);
1000 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1001 #undef DECLARE_STRUCT_PREDICATE
1003 INLINE(bool IsSpecObject()) const;
1004 INLINE(bool IsSpecFunction()) const;
1005 INLINE(bool IsTemplateInfo()) const;
1006 INLINE(bool IsNameDictionary() const);
1007 INLINE(bool IsGlobalDictionary() const);
1008 INLINE(bool IsSeededNumberDictionary() const);
1009 INLINE(bool IsUnseededNumberDictionary() const);
1010 INLINE(bool IsOrderedHashSet() const);
1011 INLINE(bool IsOrderedHashMap() const);
1012 bool IsCallable() const;
1013 static bool IsPromise(Handle<Object> object);
1016 INLINE(bool IsUndefined() const);
1017 INLINE(bool IsNull() const);
1018 INLINE(bool IsTheHole() const);
1019 INLINE(bool IsException() const);
1020 INLINE(bool IsUninitialized() const);
1021 INLINE(bool IsTrue() const);
1022 INLINE(bool IsFalse() const);
1023 INLINE(bool IsArgumentsMarker() const);
1025 // Filler objects (fillers and free space objects).
1026 INLINE(bool IsFiller() const);
1028 // Extract the number.
1029 inline double Number();
1030 INLINE(bool IsNaN() const);
1031 INLINE(bool IsMinusZero() const);
1032 bool ToInt32(int32_t* value);
1033 bool ToUint32(uint32_t* value);
1035 inline Representation OptimalRepresentation();
1037 inline ElementsKind OptimalElementsKind();
1039 inline bool FitsRepresentation(Representation representation);
1041 // Checks whether two valid primitive encodings of a property name resolve to
1042 // the same logical property. E.g., the smi 1, the string "1" and the double
1043 // 1 all refer to the same property, so this helper will return true.
1044 inline bool KeyEquals(Object* other);
1046 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1048 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1049 Handle<Object> object,
1050 Representation representation);
1052 inline static Handle<Object> WrapForRead(Isolate* isolate,
1053 Handle<Object> object,
1054 Representation representation);
1056 // Returns true if the object is of the correct type to be used as a
1057 // implementation of a JSObject's elements.
1058 inline bool HasValidElements();
1060 inline bool HasSpecificClassOf(String* name);
1062 bool BooleanValue(); // ECMA-262 9.2.
1064 // ES6 section 7.2.13 Strict Equality Comparison
1065 bool StrictEquals(Object* that);
1067 // Convert to a JSObject if needed.
1068 // native_context is used when creating wrapper object.
1069 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1070 Handle<Object> object);
1071 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1072 Handle<Object> object,
1073 Handle<Context> context);
1075 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1076 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1078 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1079 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1080 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1081 LanguageMode language_mode,
1082 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1084 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1085 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1086 StoreFromKeyed store_mode);
1088 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1089 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1090 StoreFromKeyed store_mode);
1092 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1093 LookupIterator* it, LanguageMode language_mode);
1094 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1095 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1096 LanguageMode language_mode);
1097 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1098 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1099 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1100 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1101 Handle<Object> value, LanguageMode language_mode);
1102 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1103 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1104 LanguageMode language_mode);
1105 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1106 LookupIterator* it, Handle<Object> value);
1107 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1108 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1109 LanguageMode language_mode, StoreFromKeyed store_mode);
1110 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1111 Handle<Object> object, Handle<Name> name,
1112 LanguageMode language_mode = SLOPPY);
1113 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1114 Isolate* isolate, Handle<Object> object, const char* key,
1115 LanguageMode language_mode = SLOPPY);
1116 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1117 Handle<Object> object, Handle<Name> name,
1118 LanguageMode language_mode = SLOPPY);
1120 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1121 LookupIterator* it, LanguageMode language_mode);
1122 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1123 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1125 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1126 Handle<Object> receiver,
1127 Handle<JSReceiver> getter);
1128 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1129 Handle<Object> receiver,
1130 Handle<JSReceiver> setter,
1131 Handle<Object> value);
1133 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1134 Isolate* isolate, Handle<Object> object, uint32_t index,
1135 LanguageMode language_mode = SLOPPY);
1137 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1138 Isolate* isolate, Handle<Object> object, uint32_t index,
1139 Handle<Object> value, LanguageMode language_mode);
1141 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1142 Isolate* isolate, Handle<Object> receiver);
1144 bool HasInPrototypeChain(Isolate* isolate, Object* object);
1146 // Returns the permanent hash code associated with this object. May return
1147 // undefined if not yet created.
1150 // Returns undefined for JSObjects, but returns the hash code for simple
1151 // objects. This avoids a double lookup in the cases where we know we will
1152 // add the hash to the JSObject if it does not already exist.
1153 Object* GetSimpleHash();
1155 // Returns the permanent hash code associated with this object depending on
1156 // the actual object type. May create and store a hash code if needed and none
1158 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1160 // Checks whether this object has the same value as the given one. This
1161 // function is implemented according to ES5, section 9.12 and can be used
1162 // to implement the Harmony "egal" function.
1163 bool SameValue(Object* other);
1165 // Checks whether this object has the same value as the given one.
1166 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1167 // This function is implemented according to ES6, section 7.2.4 and is used
1168 // by ES6 Map and Set.
1169 bool SameValueZero(Object* other);
1171 // Tries to convert an object to an array length. Returns true and sets the
1172 // output parameter if it succeeds.
1173 inline bool ToArrayLength(uint32_t* index);
1175 // Tries to convert an object to an array index. Returns true and sets the
1176 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1177 // allow kMaxUInt32.
1178 inline bool ToArrayIndex(uint32_t* index);
1180 // Returns true if this is a JSValue containing a string and the index is
1181 // < the length of the string. Used to implement [] on strings.
1182 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1184 DECLARE_VERIFIER(Object)
1186 // Verify a pointer is a valid object pointer.
1187 static void VerifyPointer(Object* p);
1190 inline void VerifyApiCallResultType();
1192 // Prints this object without details.
1193 void ShortPrint(FILE* out = stdout);
1195 // Prints this object without details to a message accumulator.
1196 void ShortPrint(StringStream* accumulator);
1198 void ShortPrint(std::ostream& os); // NOLINT
1200 DECLARE_CAST(Object)
1202 // Layout description.
1203 static const int kHeaderSize = 0; // Object does not take up any space.
1206 // For our gdb macros, we should perhaps change these in the future.
1209 // Prints this object with details.
1210 void Print(std::ostream& os); // NOLINT
1212 void Print() { ShortPrint(); }
1213 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1217 friend class LookupIterator;
1218 friend class PrototypeIterator;
1220 // Return the map of the root of object's prototype chain.
1221 Map* GetRootMap(Isolate* isolate);
1223 // Helper for SetProperty and SetSuperProperty.
1224 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1225 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1226 StoreFromKeyed store_mode, bool* found);
1228 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1232 // In objects.h to be usable without objects-inl.h inclusion.
1233 bool Object::IsSmi() const { return HAS_SMI_TAG(this); }
1234 bool Object::IsHeapObject() const { return Internals::HasHeapObjectTag(this); }
1238 explicit Brief(const Object* const v) : value(v) {}
1239 const Object* value;
1243 std::ostream& operator<<(std::ostream& os, const Brief& v);
1246 // Smi represents integer Numbers that can be stored in 31 bits.
1247 // Smis are immediate which means they are NOT allocated in the heap.
1248 // The this pointer has the following format: [31 bit signed int] 0
1249 // For long smis it has the following format:
1250 // [32 bit signed int] [31 bits zero padding] 0
1251 // Smi stands for small integer.
1252 class Smi: public Object {
1254 // Returns the integer value.
1255 inline int value() const { return Internals::SmiValue(this); }
1257 // Convert a value to a Smi object.
1258 static inline Smi* FromInt(int value) {
1259 DCHECK(Smi::IsValid(value));
1260 return reinterpret_cast<Smi*>(Internals::IntToSmi(value));
1263 static inline Smi* FromIntptr(intptr_t value) {
1264 DCHECK(Smi::IsValid(value));
1265 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
1266 return reinterpret_cast<Smi*>((value << smi_shift_bits) | kSmiTag);
1269 // Returns whether value can be represented in a Smi.
1270 static inline bool IsValid(intptr_t value) {
1271 bool result = Internals::IsValidSmi(value);
1272 DCHECK_EQ(result, value >= kMinValue && value <= kMaxValue);
1278 // Dispatched behavior.
1279 void SmiPrint(std::ostream& os) const; // NOLINT
1280 DECLARE_VERIFIER(Smi)
1282 static const int kMinValue =
1283 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1284 static const int kMaxValue = -(kMinValue + 1);
1287 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1291 // Heap objects typically have a map pointer in their first word. However,
1292 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1293 // encoded in the first word. The class MapWord is an abstraction of the
1294 // value in a heap object's first word.
1295 class MapWord BASE_EMBEDDED {
1297 // Normal state: the map word contains a map pointer.
1299 // Create a map word from a map pointer.
1300 static inline MapWord FromMap(const Map* map);
1302 // View this map word as a map pointer.
1303 inline Map* ToMap();
1306 // Scavenge collection: the map word of live objects in the from space
1307 // contains a forwarding address (a heap object pointer in the to space).
1309 // True if this map word is a forwarding address for a scavenge
1310 // collection. Only valid during a scavenge collection (specifically,
1311 // when all map words are heap object pointers, i.e. not during a full GC).
1312 inline bool IsForwardingAddress();
1314 // Create a map word from a forwarding address.
1315 static inline MapWord FromForwardingAddress(HeapObject* object);
1317 // View this map word as a forwarding address.
1318 inline HeapObject* ToForwardingAddress();
1320 static inline MapWord FromRawValue(uintptr_t value) {
1321 return MapWord(value);
1324 inline uintptr_t ToRawValue() {
1329 // HeapObject calls the private constructor and directly reads the value.
1330 friend class HeapObject;
1332 explicit MapWord(uintptr_t value) : value_(value) {}
1338 // The content of an heap object (except for the map pointer). kTaggedValues
1339 // objects can contain both heap pointers and Smis, kMixedValues can contain
1340 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1341 // objects can contain raw values and Smis.
1342 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1345 // HeapObject is the superclass for all classes describing heap allocated
1347 class HeapObject: public Object {
1349 // [map]: Contains a map which contains the object's reflective
1351 inline Map* map() const;
1352 inline void set_map(Map* value);
1353 // The no-write-barrier version. This is OK if the object is white and in
1354 // new space, or if the value is an immortal immutable object, like the maps
1355 // of primitive (non-JS) objects like strings, heap numbers etc.
1356 inline void set_map_no_write_barrier(Map* value);
1358 // Get the map using acquire load.
1359 inline Map* synchronized_map();
1360 inline MapWord synchronized_map_word() const;
1362 // Set the map using release store
1363 inline void synchronized_set_map(Map* value);
1364 inline void synchronized_set_map_no_write_barrier(Map* value);
1365 inline void synchronized_set_map_word(MapWord map_word);
1367 // During garbage collection, the map word of a heap object does not
1368 // necessarily contain a map pointer.
1369 inline MapWord map_word() const;
1370 inline void set_map_word(MapWord map_word);
1372 // The Heap the object was allocated in. Used also to access Isolate.
1373 inline Heap* GetHeap() const;
1375 // Convenience method to get current isolate.
1376 inline Isolate* GetIsolate() const;
1378 // Converts an address to a HeapObject pointer.
1379 static inline HeapObject* FromAddress(Address address) {
1380 DCHECK_TAG_ALIGNED(address);
1381 return reinterpret_cast<HeapObject*>(address + kHeapObjectTag);
1384 // Returns the address of this HeapObject.
1385 inline Address address() {
1386 return reinterpret_cast<Address>(this) - kHeapObjectTag;
1389 // Iterates over pointers contained in the object (including the Map)
1390 void Iterate(ObjectVisitor* v);
1392 // Iterates over all pointers contained in the object except the
1393 // first map pointer. The object type is given in the first
1394 // parameter. This function does not access the map pointer in the
1395 // object, and so is safe to call while the map pointer is modified.
1396 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1398 // Returns the heap object's size in bytes
1401 // Indicates what type of values this heap object may contain.
1402 inline HeapObjectContents ContentType();
1404 // Given a heap object's map pointer, returns the heap size in bytes
1405 // Useful when the map pointer field is used for other purposes.
1407 inline int SizeFromMap(Map* map);
1409 // Returns the field at offset in obj, as a read/write Object* reference.
1410 // Does no checking, and is safe to use during GC, while maps are invalid.
1411 // Does not invoke write barrier, so should only be assigned to
1412 // during marking GC.
1413 static inline Object** RawField(HeapObject* obj, int offset);
1415 // Adds the |code| object related to |name| to the code cache of this map. If
1416 // this map is a dictionary map that is shared, the map copied and installed
1418 static void UpdateMapCodeCache(Handle<HeapObject> object,
1422 DECLARE_CAST(HeapObject)
1424 // Return the write barrier mode for this. Callers of this function
1425 // must be able to present a reference to an DisallowHeapAllocation
1426 // object as a sign that they are not going to use this function
1427 // from code that allocates and thus invalidates the returned write
1429 inline WriteBarrierMode GetWriteBarrierMode(
1430 const DisallowHeapAllocation& promise);
1432 // Dispatched behavior.
1433 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1435 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1437 DECLARE_PRINTER(HeapObject)
1438 DECLARE_VERIFIER(HeapObject)
1440 inline void VerifyObjectField(int offset);
1441 inline void VerifySmiField(int offset);
1443 // Verify a pointer is a valid HeapObject pointer that points to object
1444 // areas in the heap.
1445 static void VerifyHeapPointer(Object* p);
1448 inline AllocationAlignment RequiredAlignment();
1450 // Layout description.
1451 // First field in a heap object is map.
1452 static const int kMapOffset = Object::kHeaderSize;
1453 static const int kHeaderSize = kMapOffset + kPointerSize;
1455 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1458 // helpers for calling an ObjectVisitor to iterate over pointers in the
1459 // half-open range [start, end) specified as integer offsets
1460 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1461 // as above, for the single element at "offset"
1462 inline void IteratePointer(ObjectVisitor* v, int offset);
1463 // as above, for the next code link of a code object.
1464 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1467 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1471 // This class describes a body of an object of a fixed size
1472 // in which all pointer fields are located in the [start_offset, end_offset)
1474 template<int start_offset, int end_offset, int size>
1475 class FixedBodyDescriptor {
1477 static const int kStartOffset = start_offset;
1478 static const int kEndOffset = end_offset;
1479 static const int kSize = size;
1481 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1483 template<typename StaticVisitor>
1484 static inline void IterateBody(HeapObject* obj) {
1485 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1486 HeapObject::RawField(obj, end_offset));
1491 // This class describes a body of an object of a variable size
1492 // in which all pointer fields are located in the [start_offset, object_size)
1494 template<int start_offset>
1495 class FlexibleBodyDescriptor {
1497 static const int kStartOffset = start_offset;
1499 static inline void IterateBody(HeapObject* obj,
1503 template<typename StaticVisitor>
1504 static inline void IterateBody(HeapObject* obj, int object_size) {
1505 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1506 HeapObject::RawField(obj, object_size));
1511 // The HeapNumber class describes heap allocated numbers that cannot be
1512 // represented in a Smi (small integer)
1513 class HeapNumber: public HeapObject {
1515 // [value]: number value.
1516 inline double value() const;
1517 inline void set_value(double value);
1519 DECLARE_CAST(HeapNumber)
1521 // Dispatched behavior.
1522 bool HeapNumberBooleanValue();
1524 void HeapNumberPrint(std::ostream& os); // NOLINT
1525 DECLARE_VERIFIER(HeapNumber)
1527 inline int get_exponent();
1528 inline int get_sign();
1530 // Layout description.
1531 static const int kValueOffset = HeapObject::kHeaderSize;
1532 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1533 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1534 // words within double numbers are endian dependent and they are set
1536 #if defined(V8_TARGET_LITTLE_ENDIAN)
1537 static const int kMantissaOffset = kValueOffset;
1538 static const int kExponentOffset = kValueOffset + 4;
1539 #elif defined(V8_TARGET_BIG_ENDIAN)
1540 static const int kMantissaOffset = kValueOffset + 4;
1541 static const int kExponentOffset = kValueOffset;
1543 #error Unknown byte ordering
1546 static const int kSize = kValueOffset + kDoubleSize;
1547 static const uint32_t kSignMask = 0x80000000u;
1548 static const uint32_t kExponentMask = 0x7ff00000u;
1549 static const uint32_t kMantissaMask = 0xfffffu;
1550 static const int kMantissaBits = 52;
1551 static const int kExponentBits = 11;
1552 static const int kExponentBias = 1023;
1553 static const int kExponentShift = 20;
1554 static const int kInfinityOrNanExponent =
1555 (kExponentMask >> kExponentShift) - kExponentBias;
1556 static const int kMantissaBitsInTopWord = 20;
1557 static const int kNonMantissaBitsInTopWord = 12;
1560 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1564 // The Simd128Value class describes heap allocated 128 bit SIMD values.
1565 class Simd128Value : public HeapObject {
1567 DECLARE_CAST(Simd128Value)
1569 DECLARE_PRINTER(Simd128Value)
1570 DECLARE_VERIFIER(Simd128Value)
1572 // Equality operations.
1573 inline bool Equals(Simd128Value* that);
1575 // Checks that another instance is bit-wise equal.
1576 bool BitwiseEquals(const Simd128Value* other) const;
1577 // Computes a hash from the 128 bit value, viewed as 4 32-bit integers.
1578 uint32_t Hash() const;
1579 // Copies the 16 bytes of SIMD data to the destination address.
1580 void CopyBits(void* destination) const;
1582 // Layout description.
1583 static const int kValueOffset = HeapObject::kHeaderSize;
1584 static const int kSize = kValueOffset + kSimd128Size;
1587 DISALLOW_IMPLICIT_CONSTRUCTORS(Simd128Value);
1591 // V has parameters (TYPE, Type, type, lane count, lane type)
1592 #define SIMD128_TYPES(V) \
1593 V(FLOAT32X4, Float32x4, float32x4, 4, float) \
1594 V(INT32X4, Int32x4, int32x4, 4, int32_t) \
1595 V(BOOL32X4, Bool32x4, bool32x4, 4, bool) \
1596 V(INT16X8, Int16x8, int16x8, 8, int16_t) \
1597 V(BOOL16X8, Bool16x8, bool16x8, 8, bool) \
1598 V(INT8X16, Int8x16, int8x16, 16, int8_t) \
1599 V(BOOL8X16, Bool8x16, bool8x16, 16, bool)
1601 #define SIMD128_VALUE_CLASS(TYPE, Type, type, lane_count, lane_type) \
1602 class Type final : public Simd128Value { \
1604 inline lane_type get_lane(int lane) const; \
1605 inline void set_lane(int lane, lane_type value); \
1607 DECLARE_CAST(Type) \
1609 DECLARE_PRINTER(Type) \
1611 inline bool Equals(Type* that); \
1614 DISALLOW_IMPLICIT_CONSTRUCTORS(Type); \
1616 SIMD128_TYPES(SIMD128_VALUE_CLASS)
1617 #undef SIMD128_VALUE_CLASS
1620 enum EnsureElementsMode {
1621 DONT_ALLOW_DOUBLE_ELEMENTS,
1622 ALLOW_COPIED_DOUBLE_ELEMENTS,
1623 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1627 // Indicator for one component of an AccessorPair.
1628 enum AccessorComponent {
1634 // JSReceiver includes types on which properties can be defined, i.e.,
1635 // JSObject and JSProxy.
1636 class JSReceiver: public HeapObject {
1638 DECLARE_CAST(JSReceiver)
1640 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1641 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1642 Handle<JSReceiver> object, Handle<Name> name);
1643 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1645 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1646 Handle<JSReceiver> object, uint32_t index);
1647 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1648 Handle<JSReceiver> object, uint32_t index);
1650 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1651 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1652 Handle<JSReceiver> object, Handle<Name> name,
1653 LanguageMode language_mode = SLOPPY);
1654 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1655 Handle<JSReceiver> object, Handle<Name> name,
1656 LanguageMode language_mode = SLOPPY);
1657 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1658 LookupIterator* it, LanguageMode language_mode);
1659 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1660 Handle<JSReceiver> object, uint32_t index,
1661 LanguageMode language_mode = SLOPPY);
1663 // Tests for the fast common case for property enumeration.
1664 bool IsSimpleEnum();
1666 // Returns the class name ([[Class]] property in the specification).
1667 String* class_name();
1669 // Returns the constructor name (the name (possibly, inferred name) of the
1670 // function that was used to instantiate the object).
1671 String* constructor_name();
1673 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1674 Handle<JSReceiver> object, Handle<Name> name);
1675 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1676 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1678 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1679 Handle<JSReceiver> object, uint32_t index);
1680 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1681 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1683 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1684 LookupIterator* it);
1687 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1689 static Handle<Object> GetDataProperty(LookupIterator* it);
1692 // Retrieves a permanent object identity hash code. The undefined value might
1693 // be returned in case no hash was created yet.
1694 inline Object* GetIdentityHash();
1696 // Retrieves a permanent object identity hash code. May create and store a
1697 // hash code if needed and none exists.
1698 inline static Handle<Smi> GetOrCreateIdentityHash(
1699 Handle<JSReceiver> object);
1701 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1703 // Computes the enumerable keys for a JSObject. Used for implementing
1704 // "for (n in object) { }".
1705 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1706 Handle<JSReceiver> object,
1707 KeyCollectionType type);
1710 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1714 // The JSObject describes real heap allocated JavaScript objects with
1716 // Note that the map of JSObject changes during execution to enable inline
1718 class JSObject: public JSReceiver {
1720 // [properties]: Backing storage for properties.
1721 // properties is a FixedArray in the fast case and a Dictionary in the
1723 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1724 inline void initialize_properties();
1725 inline bool HasFastProperties();
1726 // Gets slow properties for non-global objects.
1727 inline NameDictionary* property_dictionary();
1728 // Gets global object properties.
1729 inline GlobalDictionary* global_dictionary();
1731 // [elements]: The elements (properties with names that are integers).
1733 // Elements can be in two general modes: fast and slow. Each mode
1734 // corrensponds to a set of object representations of elements that
1735 // have something in common.
1737 // In the fast mode elements is a FixedArray and so each element can
1738 // be quickly accessed. This fact is used in the generated code. The
1739 // elements array can have one of three maps in this mode:
1740 // fixed_array_map, sloppy_arguments_elements_map or
1741 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1742 // the elements array may be shared by a few objects and so before
1743 // writing to any element the array must be copied. Use
1744 // EnsureWritableFastElements in this case.
1746 // In the slow mode the elements is either a NumberDictionary, a
1747 // FixedArray parameter map for a (sloppy) arguments object.
1748 DECL_ACCESSORS(elements, FixedArrayBase)
1749 inline void initialize_elements();
1750 static void ResetElements(Handle<JSObject> object);
1751 static inline void SetMapAndElements(Handle<JSObject> object,
1753 Handle<FixedArrayBase> elements);
1754 inline ElementsKind GetElementsKind();
1755 ElementsAccessor* GetElementsAccessor();
1756 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1757 inline bool HasFastSmiElements();
1758 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1759 inline bool HasFastObjectElements();
1760 // Returns true if an object has elements of FAST_ELEMENTS or
1761 // FAST_SMI_ONLY_ELEMENTS.
1762 inline bool HasFastSmiOrObjectElements();
1763 // Returns true if an object has any of the fast elements kinds.
1764 inline bool HasFastElements();
1765 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1767 inline bool HasFastDoubleElements();
1768 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1770 inline bool HasFastHoleyElements();
1771 inline bool HasSloppyArgumentsElements();
1772 inline bool HasDictionaryElements();
1774 inline bool HasFixedTypedArrayElements();
1776 inline bool HasFixedUint8ClampedElements();
1777 inline bool HasFixedArrayElements();
1778 inline bool HasFixedInt8Elements();
1779 inline bool HasFixedUint8Elements();
1780 inline bool HasFixedInt16Elements();
1781 inline bool HasFixedUint16Elements();
1782 inline bool HasFixedInt32Elements();
1783 inline bool HasFixedUint32Elements();
1784 inline bool HasFixedFloat32Elements();
1785 inline bool HasFixedFloat64Elements();
1787 inline bool HasFastArgumentsElements();
1788 inline bool HasSlowArgumentsElements();
1789 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1791 // Requires: HasFastElements().
1792 static Handle<FixedArray> EnsureWritableFastElements(
1793 Handle<JSObject> object);
1795 // Collects elements starting at index 0.
1796 // Undefined values are placed after non-undefined values.
1797 // Returns the number of non-undefined values.
1798 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1800 // As PrepareElementsForSort, but only on objects where elements is
1801 // a dictionary, and it will stay a dictionary. Collates undefined and
1802 // unexisting elements below limit from position zero of the elements.
1803 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1806 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1807 LookupIterator* it, Handle<Object> value);
1809 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1810 // grant an exemption to ExecutableAccessor callbacks in some cases.
1811 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1813 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1814 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1815 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1817 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1818 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1819 PropertyAttributes attributes,
1820 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1822 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1823 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1824 PropertyAttributes attributes,
1825 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1827 // Equivalent to one of the above depending on whether |name| can be converted
1828 // to an array index.
1829 MUST_USE_RESULT static MaybeHandle<Object>
1830 DefinePropertyOrElementIgnoreAttributes(
1831 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1832 PropertyAttributes attributes = NONE,
1833 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1835 // Adds or reconfigures a property to attributes NONE. It will fail when it
1837 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1838 Handle<Object> value);
1840 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1841 Handle<Object> value, PropertyAttributes attributes);
1843 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1844 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1845 PropertyAttributes attributes);
1847 // Extend the receiver with a single fast property appeared first in the
1848 // passed map. This also extends the property backing store if necessary.
1849 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1851 // Migrates the given object to a map whose field representations are the
1852 // lowest upper bound of all known representations for that field.
1853 static void MigrateInstance(Handle<JSObject> instance);
1855 // Migrates the given object only if the target map is already available,
1856 // or returns false if such a map is not yet available.
1857 static bool TryMigrateInstance(Handle<JSObject> instance);
1859 // Sets the property value in a normalized object given (key, value, details).
1860 // Handles the special representation of JS global objects.
1861 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1862 Handle<Object> value,
1863 PropertyDetails details);
1864 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1865 Handle<Object> value,
1866 PropertyAttributes attributes);
1867 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1869 Handle<Object> value,
1870 PropertyAttributes attributes);
1872 static void OptimizeAsPrototype(Handle<JSObject> object,
1873 PrototypeOptimizationMode mode);
1874 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1875 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1876 static bool UnregisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1877 static void InvalidatePrototypeChains(Map* map);
1879 // Alternative implementation of WeakFixedArray::NullCallback.
1880 class PrototypeRegistryCompactionCallback {
1882 static void Callback(Object* value, int old_index, int new_index);
1885 // Retrieve interceptors.
1886 InterceptorInfo* GetNamedInterceptor();
1887 InterceptorInfo* GetIndexedInterceptor();
1889 // Used from JSReceiver.
1890 MUST_USE_RESULT static Maybe<PropertyAttributes>
1891 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1892 MUST_USE_RESULT static Maybe<PropertyAttributes>
1893 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1895 // Retrieves an AccessorPair property from the given object. Might return
1896 // undefined if the property doesn't exist or is of a different kind.
1897 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1898 Handle<JSObject> object,
1900 AccessorComponent component);
1902 // Defines an AccessorPair property on the given object.
1903 // TODO(mstarzinger): Rename to SetAccessor().
1904 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1906 Handle<Object> getter,
1907 Handle<Object> setter,
1908 PropertyAttributes attributes);
1910 // Defines an AccessorInfo property on the given object.
1911 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1912 Handle<JSObject> object,
1913 Handle<AccessorInfo> info);
1915 // The result must be checked first for exceptions. If there's no exception,
1916 // the output parameter |done| indicates whether the interceptor has a result
1918 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1919 LookupIterator* it, bool* done);
1921 // Accessors for hidden properties object.
1923 // Hidden properties are not own properties of the object itself.
1924 // Instead they are stored in an auxiliary structure kept as an own
1925 // property with a special name Heap::hidden_string(). But if the
1926 // receiver is a JSGlobalProxy then the auxiliary object is a property
1927 // of its prototype, and if it's a detached proxy, then you can't have
1928 // hidden properties.
1930 // Sets a hidden property on this object. Returns this object if successful,
1931 // undefined if called on a detached proxy.
1932 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1934 Handle<Object> value);
1935 // Gets the value of a hidden property with the given key. Returns the hole
1936 // if the property doesn't exist (or if called on a detached proxy),
1937 // otherwise returns the value set for the key.
1938 Object* GetHiddenProperty(Handle<Name> key);
1939 // Deletes a hidden property. Deleting a non-existing property is
1940 // considered successful.
1941 static void DeleteHiddenProperty(Handle<JSObject> object,
1943 // Returns true if the object has a property with the hidden string as name.
1944 static bool HasHiddenProperties(Handle<JSObject> object);
1946 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1948 static void ValidateElements(Handle<JSObject> object);
1950 // Makes sure that this object can contain HeapObject as elements.
1951 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1953 // Makes sure that this object can contain the specified elements.
1954 static inline void EnsureCanContainElements(
1955 Handle<JSObject> object,
1958 EnsureElementsMode mode);
1959 static inline void EnsureCanContainElements(
1960 Handle<JSObject> object,
1961 Handle<FixedArrayBase> elements,
1963 EnsureElementsMode mode);
1964 static void EnsureCanContainElements(
1965 Handle<JSObject> object,
1966 Arguments* arguments,
1969 EnsureElementsMode mode);
1971 // Would we convert a fast elements array to dictionary mode given
1972 // an access at key?
1973 bool WouldConvertToSlowElements(uint32_t index);
1975 // Computes the new capacity when expanding the elements of a JSObject.
1976 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
1977 // (old_capacity + 50%) + 16
1978 return old_capacity + (old_capacity >> 1) + 16;
1981 // These methods do not perform access checks!
1982 static void UpdateAllocationSite(Handle<JSObject> object,
1983 ElementsKind to_kind);
1985 // Lookup interceptors are used for handling properties controlled by host
1987 inline bool HasNamedInterceptor();
1988 inline bool HasIndexedInterceptor();
1990 // Computes the enumerable keys from interceptors. Used for debug mirrors and
1991 // by JSReceiver::GetKeys.
1992 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
1993 Handle<JSObject> object,
1994 Handle<JSReceiver> receiver);
1995 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
1996 Handle<JSObject> object,
1997 Handle<JSReceiver> receiver);
1999 // Support functions for v8 api (needed for correct interceptor behavior).
2000 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2001 Handle<JSObject> object, Handle<Name> name);
2002 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2003 Handle<JSObject> object, uint32_t index);
2004 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2005 Handle<JSObject> object, Handle<Name> name);
2007 // Get the header size for a JSObject. Used to compute the index of
2008 // internal fields as well as the number of internal fields.
2009 inline int GetHeaderSize();
2011 inline int GetInternalFieldCount();
2012 inline int GetInternalFieldOffset(int index);
2013 inline Object* GetInternalField(int index);
2014 inline void SetInternalField(int index, Object* value);
2015 inline void SetInternalField(int index, Smi* value);
2017 // Returns the number of properties on this object filtering out properties
2018 // with the specified attributes (ignoring interceptors).
2019 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2020 // Fill in details for properties into storage starting at the specified
2021 // index. Returns the number of properties added.
2022 int GetOwnPropertyNames(FixedArray* storage, int index,
2023 PropertyAttributes filter = NONE);
2025 // Returns the number of properties on this object filtering out properties
2026 // with the specified attributes (ignoring interceptors).
2027 int NumberOfOwnElements(PropertyAttributes filter);
2028 // Returns the number of enumerable elements (ignoring interceptors).
2029 int NumberOfEnumElements();
2030 // Returns the number of elements on this object filtering out elements
2031 // with the specified attributes (ignoring interceptors).
2032 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2033 // Count and fill in the enumerable elements into storage.
2034 // (storage->length() == NumberOfEnumElements()).
2035 // If storage is NULL, will count the elements without adding
2036 // them to any storage.
2037 // Returns the number of enumerable elements.
2038 int GetEnumElementKeys(FixedArray* storage);
2040 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2043 // Returns a new map with all transitions dropped from the object's current
2044 // map and the ElementsKind set.
2045 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2046 ElementsKind to_kind);
2047 static void TransitionElementsKind(Handle<JSObject> object,
2048 ElementsKind to_kind);
2050 // Always use this to migrate an object to a new map.
2051 // |expected_additional_properties| is only used for fast-to-slow transitions
2052 // and ignored otherwise.
2053 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2054 int expected_additional_properties = 0);
2056 // Convert the object to use the canonical dictionary
2057 // representation. If the object is expected to have additional properties
2058 // added this number can be indicated to have the backing store allocated to
2059 // an initial capacity for holding these properties.
2060 static void NormalizeProperties(Handle<JSObject> object,
2061 PropertyNormalizationMode mode,
2062 int expected_additional_properties,
2063 const char* reason);
2065 // Convert and update the elements backing store to be a
2066 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2067 static Handle<SeededNumberDictionary> NormalizeElements(
2068 Handle<JSObject> object);
2070 void RequireSlowElements(SeededNumberDictionary* dictionary);
2072 // Transform slow named properties to fast variants.
2073 static void MigrateSlowToFast(Handle<JSObject> object,
2074 int unused_property_fields, const char* reason);
2076 inline bool IsUnboxedDoubleField(FieldIndex index);
2078 // Access fast-case object properties at index.
2079 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2080 Representation representation,
2082 inline Object* RawFastPropertyAt(FieldIndex index);
2083 inline double RawFastDoublePropertyAt(FieldIndex index);
2085 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2086 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2087 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2088 inline void WriteToField(int descriptor, Object* value);
2090 // Access to in object properties.
2091 inline int GetInObjectPropertyOffset(int index);
2092 inline Object* InObjectPropertyAt(int index);
2093 inline Object* InObjectPropertyAtPut(int index,
2095 WriteBarrierMode mode
2096 = UPDATE_WRITE_BARRIER);
2098 // Set the object's prototype (only JSReceiver and null are allowed values).
2099 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2100 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2102 // Initializes the body after properties slot, properties slot is
2103 // initialized by set_properties. Fill the pre-allocated fields with
2104 // pre_allocated_value and the rest with filler_value.
2105 // Note: this call does not update write barrier, the caller is responsible
2106 // to ensure that |filler_value| can be collected without WB here.
2107 inline void InitializeBody(Map* map,
2108 Object* pre_allocated_value,
2109 Object* filler_value);
2111 // Check whether this object references another object
2112 bool ReferencesObject(Object* obj);
2114 // Disalow further properties to be added to the oject.
2115 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2116 Handle<JSObject> object);
2118 bool IsExtensible();
2121 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2123 // ES5 Object.freeze
2124 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2126 // Called the first time an object is observed with ES7 Object.observe.
2127 static void SetObserved(Handle<JSObject> object);
2130 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2132 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2133 Handle<JSObject> object,
2134 AllocationSiteUsageContext* site_context,
2135 DeepCopyHints hints = kNoHints);
2136 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2137 Handle<JSObject> object,
2138 AllocationSiteCreationContext* site_context);
2140 DECLARE_CAST(JSObject)
2142 // Dispatched behavior.
2143 void JSObjectShortPrint(StringStream* accumulator);
2144 DECLARE_PRINTER(JSObject)
2145 DECLARE_VERIFIER(JSObject)
2147 void PrintProperties(std::ostream& os); // NOLINT
2148 void PrintElements(std::ostream& os); // NOLINT
2150 #if defined(DEBUG) || defined(OBJECT_PRINT)
2151 void PrintTransitions(std::ostream& os); // NOLINT
2154 static void PrintElementsTransition(
2155 FILE* file, Handle<JSObject> object,
2156 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2157 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2159 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2162 // Structure for collecting spill information about JSObjects.
2163 class SpillInformation {
2167 int number_of_objects_;
2168 int number_of_objects_with_fast_properties_;
2169 int number_of_objects_with_fast_elements_;
2170 int number_of_fast_used_fields_;
2171 int number_of_fast_unused_fields_;
2172 int number_of_slow_used_properties_;
2173 int number_of_slow_unused_properties_;
2174 int number_of_fast_used_elements_;
2175 int number_of_fast_unused_elements_;
2176 int number_of_slow_used_elements_;
2177 int number_of_slow_unused_elements_;
2180 void IncrementSpillStatistics(SpillInformation* info);
2184 // If a GC was caused while constructing this object, the elements pointer
2185 // may point to a one pointer filler map. The object won't be rooted, but
2186 // our heap verification code could stumble across it.
2187 bool ElementsAreSafeToExamine();
2190 Object* SlowReverseLookup(Object* value);
2192 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2193 // Also maximal value of JSArray's length property.
2194 static const uint32_t kMaxElementCount = 0xffffffffu;
2196 // Constants for heuristics controlling conversion of fast elements
2197 // to slow elements.
2199 // Maximal gap that can be introduced by adding an element beyond
2200 // the current elements length.
2201 static const uint32_t kMaxGap = 1024;
2203 // Maximal length of fast elements array that won't be checked for
2204 // being dense enough on expansion.
2205 static const int kMaxUncheckedFastElementsLength = 5000;
2207 // Same as above but for old arrays. This limit is more strict. We
2208 // don't want to be wasteful with long lived objects.
2209 static const int kMaxUncheckedOldFastElementsLength = 500;
2211 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2212 // permissible values (see the DCHECK in heap.cc).
2213 static const int kInitialMaxFastElementArray = 100000;
2215 // This constant applies only to the initial map of "global.Object" and
2216 // not to arbitrary other JSObject maps.
2217 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2219 static const int kMaxInstanceSize = 255 * kPointerSize;
2220 // When extending the backing storage for property values, we increase
2221 // its size by more than the 1 entry necessary, so sequentially adding fields
2222 // to the same object requires fewer allocations and copies.
2223 static const int kFieldsAdded = 3;
2225 // Layout description.
2226 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2227 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2228 static const int kHeaderSize = kElementsOffset + kPointerSize;
2230 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2232 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2234 static inline int SizeOf(Map* map, HeapObject* object);
2237 Context* GetCreationContext();
2239 // Enqueue change record for Object.observe. May cause GC.
2240 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2241 Handle<JSObject> object, const char* type, Handle<Name> name,
2242 Handle<Object> old_value);
2244 // Gets the number of currently used elements.
2245 int GetFastElementsUsage();
2247 // Deletes an existing named property in a normalized object.
2248 static void DeleteNormalizedProperty(Handle<JSObject> object,
2249 Handle<Name> name, int entry);
2251 static bool AllCanRead(LookupIterator* it);
2252 static bool AllCanWrite(LookupIterator* it);
2255 friend class JSReceiver;
2256 friend class Object;
2258 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2259 static void MigrateFastToSlow(Handle<JSObject> object,
2260 Handle<Map> new_map,
2261 int expected_additional_properties);
2263 // Used from Object::GetProperty().
2264 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2265 LookupIterator* it);
2267 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2268 LookupIterator* it, Handle<Object> value);
2270 // Add a property to a slow-case object.
2271 static void AddSlowProperty(Handle<JSObject> object,
2273 Handle<Object> value,
2274 PropertyAttributes attributes);
2276 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2277 LookupIterator* it);
2279 bool ReferencesObjectFromElements(FixedArray* elements,
2283 // Return the hash table backing store or the inline stored identity hash,
2284 // whatever is found.
2285 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2287 // Return the hash table backing store for hidden properties. If there is no
2288 // backing store, allocate one.
2289 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2290 Handle<JSObject> object);
2292 // Set the hidden property backing store to either a hash table or
2293 // the inline-stored identity hash.
2294 static Handle<Object> SetHiddenPropertiesHashTable(
2295 Handle<JSObject> object,
2296 Handle<Object> value);
2298 MUST_USE_RESULT Object* GetIdentityHash();
2300 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2302 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2303 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2305 // Helper for fast versions of preventExtensions, seal, and freeze.
2306 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2307 template <PropertyAttributes attrs>
2308 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2309 Handle<JSObject> object);
2311 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2315 // Common superclass for FixedArrays that allow implementations to share
2316 // common accessors and some code paths.
2317 class FixedArrayBase: public HeapObject {
2319 // [length]: length of the array.
2320 inline int length() const;
2321 inline void set_length(int value);
2323 // Get and set the length using acquire loads and release stores.
2324 inline int synchronized_length() const;
2325 inline void synchronized_set_length(int value);
2327 DECLARE_CAST(FixedArrayBase)
2329 // Layout description.
2330 // Length is smi tagged when it is stored.
2331 static const int kLengthOffset = HeapObject::kHeaderSize;
2332 static const int kHeaderSize = kLengthOffset + kPointerSize;
2336 class FixedDoubleArray;
2337 class IncrementalMarking;
2340 // FixedArray describes fixed-sized arrays with element type Object*.
2341 class FixedArray: public FixedArrayBase {
2343 // Setter and getter for elements.
2344 inline Object* get(int index) const;
2345 void SetValue(uint32_t index, Object* value);
2346 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2347 // Setter that uses write barrier.
2348 inline void set(int index, Object* value);
2349 inline bool is_the_hole(int index);
2351 // Setter that doesn't need write barrier.
2352 inline void set(int index, Smi* value);
2353 // Setter with explicit barrier mode.
2354 inline void set(int index, Object* value, WriteBarrierMode mode);
2356 // Setters for frequently used oddballs located in old space.
2357 inline void set_undefined(int index);
2358 inline void set_null(int index);
2359 inline void set_the_hole(int index);
2361 inline Object** GetFirstElementAddress();
2362 inline bool ContainsOnlySmisOrHoles();
2364 // Gives access to raw memory which stores the array's data.
2365 inline Object** data_start();
2367 inline void FillWithHoles(int from, int to);
2369 // Shrink length and insert filler objects.
2370 void Shrink(int length);
2372 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2374 // Add the elements of a JSArray to this FixedArray.
2375 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2376 Handle<FixedArray> content, Handle<JSObject> array,
2377 KeyFilter filter = ALL_KEYS);
2379 // Computes the union of keys and return the result.
2380 // Used for implementing "for (n in object) { }"
2381 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2382 Handle<FixedArray> first,
2383 Handle<FixedArray> second);
2385 // Copy a sub array from the receiver to dest.
2386 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2388 // Garbage collection support.
2389 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2391 // Code Generation support.
2392 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2394 // Garbage collection support.
2395 inline Object** RawFieldOfElementAt(int index);
2397 DECLARE_CAST(FixedArray)
2399 // Maximal allowed size, in bytes, of a single FixedArray.
2400 // Prevents overflowing size computations, as well as extreme memory
2402 static const int kMaxSize = 128 * MB * kPointerSize;
2403 // Maximally allowed length of a FixedArray.
2404 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2406 // Dispatched behavior.
2407 DECLARE_PRINTER(FixedArray)
2408 DECLARE_VERIFIER(FixedArray)
2410 // Checks if two FixedArrays have identical contents.
2411 bool IsEqualTo(FixedArray* other);
2414 // Swap two elements in a pair of arrays. If this array and the
2415 // numbers array are the same object, the elements are only swapped
2417 void SwapPairs(FixedArray* numbers, int i, int j);
2419 // Sort prefix of this array and the numbers array as pairs wrt. the
2420 // numbers. If the numbers array and the this array are the same
2421 // object, the prefix of this array is sorted.
2422 void SortPairs(FixedArray* numbers, uint32_t len);
2424 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2426 static inline int SizeOf(Map* map, HeapObject* object);
2430 // Set operation on FixedArray without using write barriers. Can
2431 // only be used for storing old space objects or smis.
2432 static inline void NoWriteBarrierSet(FixedArray* array,
2436 // Set operation on FixedArray without incremental write barrier. Can
2437 // only be used if the object is guaranteed to be white (whiteness witness
2439 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2444 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2446 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2450 // FixedDoubleArray describes fixed-sized arrays with element type double.
2451 class FixedDoubleArray: public FixedArrayBase {
2453 // Setter and getter for elements.
2454 inline double get_scalar(int index);
2455 inline uint64_t get_representation(int index);
2456 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2457 // This accessor has to get a Number as |value|.
2458 void SetValue(uint32_t index, Object* value);
2459 inline void set(int index, double value);
2460 inline void set_the_hole(int index);
2462 // Checking for the hole.
2463 inline bool is_the_hole(int index);
2465 // Garbage collection support.
2466 inline static int SizeFor(int length) {
2467 return kHeaderSize + length * kDoubleSize;
2470 // Gives access to raw memory which stores the array's data.
2471 inline double* data_start();
2473 inline void FillWithHoles(int from, int to);
2475 // Code Generation support.
2476 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2478 DECLARE_CAST(FixedDoubleArray)
2480 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2481 // Prevents overflowing size computations, as well as extreme memory
2483 static const int kMaxSize = 512 * MB;
2484 // Maximally allowed length of a FixedArray.
2485 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2487 // Dispatched behavior.
2488 DECLARE_PRINTER(FixedDoubleArray)
2489 DECLARE_VERIFIER(FixedDoubleArray)
2492 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2496 class WeakFixedArray : public FixedArray {
2498 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2499 // This function does not check if the value exists already, callers must
2500 // ensure this themselves if necessary.
2501 static Handle<WeakFixedArray> Add(Handle<Object> maybe_array,
2502 Handle<HeapObject> value,
2503 int* assigned_index = NULL);
2505 // Returns true if an entry was found and removed.
2506 bool Remove(Handle<HeapObject> value);
2508 class NullCallback {
2510 static void Callback(Object* value, int old_index, int new_index) {}
2513 template <class CompactionCallback>
2516 inline Object* Get(int index) const;
2517 inline void Clear(int index);
2518 inline int Length() const;
2520 inline bool IsEmptySlot(int index) const;
2521 static Object* Empty() { return Smi::FromInt(0); }
2525 explicit Iterator(Object* maybe_array) : list_(NULL) { Reset(maybe_array); }
2526 void Reset(Object* maybe_array);
2533 WeakFixedArray* list_;
2535 int last_used_index_;
2536 DisallowHeapAllocation no_gc_;
2538 DISALLOW_COPY_AND_ASSIGN(Iterator);
2541 DECLARE_CAST(WeakFixedArray)
2544 static const int kLastUsedIndexIndex = 0;
2545 static const int kFirstIndex = 1;
2547 static Handle<WeakFixedArray> Allocate(
2548 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2550 static void Set(Handle<WeakFixedArray> array, int index,
2551 Handle<HeapObject> value);
2552 inline void clear(int index);
2554 inline int last_used_index() const;
2555 inline void set_last_used_index(int index);
2557 // Disallow inherited setters.
2558 void set(int index, Smi* value);
2559 void set(int index, Object* value);
2560 void set(int index, Object* value, WriteBarrierMode mode);
2561 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2565 // Generic array grows dynamically with O(1) amortized insertion.
2566 class ArrayList : public FixedArray {
2570 // Use this if GC can delete elements from the array.
2571 kReloadLengthAfterAllocation,
2573 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2574 AddMode mode = kNone);
2575 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2576 Handle<Object> obj2, AddMode = kNone);
2577 inline int Length();
2578 inline void SetLength(int length);
2579 inline Object* Get(int index);
2580 inline Object** Slot(int index);
2581 inline void Set(int index, Object* obj);
2582 inline void Clear(int index, Object* undefined);
2583 DECLARE_CAST(ArrayList)
2586 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2587 static const int kLengthIndex = 0;
2588 static const int kFirstIndex = 1;
2589 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2593 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2594 // The format of the these objects is:
2595 // [0]: Number of descriptors
2596 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2597 // [0]: pointer to fixed array with enum cache
2598 // [1]: either Smi(0) or pointer to fixed array with indices
2600 // [2 + number of descriptors * kDescriptorSize]: start of slack
2601 class DescriptorArray: public FixedArray {
2603 // Returns true for both shared empty_descriptor_array and for smis, which the
2604 // map uses to encode additional bit fields when the descriptor array is not
2606 inline bool IsEmpty();
2608 // Returns the number of descriptors in the array.
2609 inline int number_of_descriptors();
2611 inline int number_of_descriptors_storage();
2613 inline int NumberOfSlackDescriptors();
2615 inline void SetNumberOfDescriptors(int number_of_descriptors);
2616 inline int number_of_entries();
2618 inline bool HasEnumCache();
2620 inline void CopyEnumCacheFrom(DescriptorArray* array);
2622 inline FixedArray* GetEnumCache();
2624 inline bool HasEnumIndicesCache();
2626 inline FixedArray* GetEnumIndicesCache();
2628 inline Object** GetEnumCacheSlot();
2630 void ClearEnumCache();
2632 // Initialize or change the enum cache,
2633 // using the supplied storage for the small "bridge".
2634 void SetEnumCache(FixedArray* bridge_storage,
2635 FixedArray* new_cache,
2636 Object* new_index_cache);
2638 bool CanHoldValue(int descriptor, Object* value);
2640 // Accessors for fetching instance descriptor at descriptor number.
2641 inline Name* GetKey(int descriptor_number);
2642 inline Object** GetKeySlot(int descriptor_number);
2643 inline Object* GetValue(int descriptor_number);
2644 inline void SetValue(int descriptor_number, Object* value);
2645 inline Object** GetValueSlot(int descriptor_number);
2646 static inline int GetValueOffset(int descriptor_number);
2647 inline Object** GetDescriptorStartSlot(int descriptor_number);
2648 inline Object** GetDescriptorEndSlot(int descriptor_number);
2649 inline PropertyDetails GetDetails(int descriptor_number);
2650 inline PropertyType GetType(int descriptor_number);
2651 inline int GetFieldIndex(int descriptor_number);
2652 inline HeapType* GetFieldType(int descriptor_number);
2653 inline Object* GetConstant(int descriptor_number);
2654 inline Object* GetCallbacksObject(int descriptor_number);
2655 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2657 inline Name* GetSortedKey(int descriptor_number);
2658 inline int GetSortedKeyIndex(int descriptor_number);
2659 inline void SetSortedKey(int pointer, int descriptor_number);
2660 inline void SetRepresentation(int descriptor_number,
2661 Representation representation);
2663 // Accessor for complete descriptor.
2664 inline void Get(int descriptor_number, Descriptor* desc);
2665 inline void Set(int descriptor_number, Descriptor* desc);
2666 void Replace(int descriptor_number, Descriptor* descriptor);
2668 // Append automatically sets the enumeration index. This should only be used
2669 // to add descriptors in bulk at the end, followed by sorting the descriptor
2671 inline void Append(Descriptor* desc);
2673 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2674 int enumeration_index,
2677 static Handle<DescriptorArray> CopyUpToAddAttributes(
2678 Handle<DescriptorArray> desc,
2679 int enumeration_index,
2680 PropertyAttributes attributes,
2683 // Sort the instance descriptors by the hash codes of their keys.
2686 // Search the instance descriptors for given name.
2687 INLINE(int Search(Name* name, int number_of_own_descriptors));
2689 // As the above, but uses DescriptorLookupCache and updates it when
2691 INLINE(int SearchWithCache(Name* name, Map* map));
2693 // Allocates a DescriptorArray, but returns the singleton
2694 // empty descriptor array object if number_of_descriptors is 0.
2695 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2696 int number_of_descriptors,
2699 DECLARE_CAST(DescriptorArray)
2701 // Constant for denoting key was not found.
2702 static const int kNotFound = -1;
2704 static const int kDescriptorLengthIndex = 0;
2705 static const int kEnumCacheIndex = 1;
2706 static const int kFirstIndex = 2;
2708 // The length of the "bridge" to the enum cache.
2709 static const int kEnumCacheBridgeLength = 2;
2710 static const int kEnumCacheBridgeCacheIndex = 0;
2711 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2713 // Layout description.
2714 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2715 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2716 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2718 // Layout description for the bridge array.
2719 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2721 // Layout of descriptor.
2722 static const int kDescriptorKey = 0;
2723 static const int kDescriptorDetails = 1;
2724 static const int kDescriptorValue = 2;
2725 static const int kDescriptorSize = 3;
2727 #if defined(DEBUG) || defined(OBJECT_PRINT)
2728 // For our gdb macros, we should perhaps change these in the future.
2731 // Print all the descriptors.
2732 void PrintDescriptors(std::ostream& os); // NOLINT
2736 // Is the descriptor array sorted and without duplicates?
2737 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2739 // Is the descriptor array consistent with the back pointers in targets?
2740 bool IsConsistentWithBackPointers(Map* current_map);
2742 // Are two DescriptorArrays equal?
2743 bool IsEqualTo(DescriptorArray* other);
2746 // Returns the fixed array length required to hold number_of_descriptors
2748 static int LengthFor(int number_of_descriptors) {
2749 return ToKeyIndex(number_of_descriptors);
2753 // WhitenessWitness is used to prove that a descriptor array is white
2754 // (unmarked), so incremental write barriers can be skipped because the
2755 // marking invariant cannot be broken and slots pointing into evacuation
2756 // candidates will be discovered when the object is scanned. A witness is
2757 // always stack-allocated right after creating an array. By allocating a
2758 // witness, incremental marking is globally disabled. The witness is then
2759 // passed along wherever needed to statically prove that the array is known to
2761 class WhitenessWitness {
2763 inline explicit WhitenessWitness(DescriptorArray* array);
2764 inline ~WhitenessWitness();
2767 IncrementalMarking* marking_;
2770 // An entry in a DescriptorArray, represented as an (array, index) pair.
2773 inline explicit Entry(DescriptorArray* descs, int index) :
2774 descs_(descs), index_(index) { }
2776 inline PropertyType type();
2777 inline Object* GetCallbackObject();
2780 DescriptorArray* descs_;
2784 // Conversion from descriptor number to array indices.
2785 static int ToKeyIndex(int descriptor_number) {
2786 return kFirstIndex +
2787 (descriptor_number * kDescriptorSize) +
2791 static int ToDetailsIndex(int descriptor_number) {
2792 return kFirstIndex +
2793 (descriptor_number * kDescriptorSize) +
2797 static int ToValueIndex(int descriptor_number) {
2798 return kFirstIndex +
2799 (descriptor_number * kDescriptorSize) +
2803 // Transfer a complete descriptor from the src descriptor array to this
2804 // descriptor array.
2805 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2807 inline void Set(int descriptor_number,
2809 const WhitenessWitness&);
2811 // Swap first and second descriptor.
2812 inline void SwapSortedKeys(int first, int second);
2814 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2818 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2820 template <SearchMode search_mode, typename T>
2821 inline int Search(T* array, Name* name, int valid_entries = 0,
2822 int* out_insertion_index = NULL);
2825 // HashTable is a subclass of FixedArray that implements a hash table
2826 // that uses open addressing and quadratic probing.
2828 // In order for the quadratic probing to work, elements that have not
2829 // yet been used and elements that have been deleted are
2830 // distinguished. Probing continues when deleted elements are
2831 // encountered and stops when unused elements are encountered.
2833 // - Elements with key == undefined have not been used yet.
2834 // - Elements with key == the_hole have been deleted.
2836 // The hash table class is parameterized with a Shape and a Key.
2837 // Shape must be a class with the following interface:
2838 // class ExampleShape {
2840 // // Tells whether key matches other.
2841 // static bool IsMatch(Key key, Object* other);
2842 // // Returns the hash value for key.
2843 // static uint32_t Hash(Key key);
2844 // // Returns the hash value for object.
2845 // static uint32_t HashForObject(Key key, Object* object);
2846 // // Convert key to an object.
2847 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2848 // // The prefix size indicates number of elements in the beginning
2849 // // of the backing storage.
2850 // static const int kPrefixSize = ..;
2851 // // The Element size indicates number of elements per entry.
2852 // static const int kEntrySize = ..;
2854 // The prefix size indicates an amount of memory in the
2855 // beginning of the backing storage that can be used for non-element
2856 // information by subclasses.
2858 template<typename Key>
2861 static const bool UsesSeed = false;
2862 static uint32_t Hash(Key key) { return 0; }
2863 static uint32_t SeededHash(Key key, uint32_t seed) {
2867 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2868 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2870 return HashForObject(key, object);
2875 class HashTableBase : public FixedArray {
2877 // Returns the number of elements in the hash table.
2878 inline int NumberOfElements();
2880 // Returns the number of deleted elements in the hash table.
2881 inline int NumberOfDeletedElements();
2883 // Returns the capacity of the hash table.
2884 inline int Capacity();
2886 // ElementAdded should be called whenever an element is added to a
2888 inline void ElementAdded();
2890 // ElementRemoved should be called whenever an element is removed from
2892 inline void ElementRemoved();
2893 inline void ElementsRemoved(int n);
2895 // Computes the required capacity for a table holding the given
2896 // number of elements. May be more than HashTable::kMaxCapacity.
2897 static inline int ComputeCapacity(int at_least_space_for);
2899 // Tells whether k is a real key. The hole and undefined are not allowed
2900 // as keys and can be used to indicate missing or deleted elements.
2901 inline bool IsKey(Object* k);
2903 // Compute the probe offset (quadratic probing).
2904 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2905 return (n + n * n) >> 1;
2908 static const int kNumberOfElementsIndex = 0;
2909 static const int kNumberOfDeletedElementsIndex = 1;
2910 static const int kCapacityIndex = 2;
2911 static const int kPrefixStartIndex = 3;
2913 // Constant used for denoting a absent entry.
2914 static const int kNotFound = -1;
2917 // Update the number of elements in the hash table.
2918 inline void SetNumberOfElements(int nof);
2920 // Update the number of deleted elements in the hash table.
2921 inline void SetNumberOfDeletedElements(int nod);
2923 // Returns probe entry.
2924 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2925 DCHECK(base::bits::IsPowerOfTwo32(size));
2926 return (hash + GetProbeOffset(number)) & (size - 1);
2929 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2930 return hash & (size - 1);
2933 inline static uint32_t NextProbe(
2934 uint32_t last, uint32_t number, uint32_t size) {
2935 return (last + number) & (size - 1);
2940 template <typename Derived, typename Shape, typename Key>
2941 class HashTable : public HashTableBase {
2944 inline uint32_t Hash(Key key) {
2945 if (Shape::UsesSeed) {
2946 return Shape::SeededHash(key, GetHeap()->HashSeed());
2948 return Shape::Hash(key);
2952 inline uint32_t HashForObject(Key key, Object* object) {
2953 if (Shape::UsesSeed) {
2954 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
2956 return Shape::HashForObject(key, object);
2960 // Returns a new HashTable object.
2961 MUST_USE_RESULT static Handle<Derived> New(
2962 Isolate* isolate, int at_least_space_for,
2963 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
2964 PretenureFlag pretenure = NOT_TENURED);
2966 DECLARE_CAST(HashTable)
2968 // Garbage collection support.
2969 void IteratePrefix(ObjectVisitor* visitor);
2970 void IterateElements(ObjectVisitor* visitor);
2972 // Find entry for key otherwise return kNotFound.
2973 inline int FindEntry(Key key);
2974 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
2975 int FindEntry(Isolate* isolate, Key key);
2977 // Rehashes the table in-place.
2978 void Rehash(Key key);
2980 // Returns the key at entry.
2981 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2983 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
2984 static const int kEntrySize = Shape::kEntrySize;
2985 static const int kElementsStartOffset =
2986 kHeaderSize + kElementsStartIndex * kPointerSize;
2987 static const int kCapacityOffset =
2988 kHeaderSize + kCapacityIndex * kPointerSize;
2990 // Returns the index for an entry (of the key)
2991 static inline int EntryToIndex(int entry) {
2992 return (entry * kEntrySize) + kElementsStartIndex;
2996 friend class ObjectHashTable;
2998 // Find the entry at which to insert element with the given key that
2999 // has the given hash value.
3000 uint32_t FindInsertionEntry(uint32_t hash);
3002 // Attempt to shrink hash table after removal of key.
3003 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3005 // Ensure enough space for n additional elements.
3006 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3007 Handle<Derived> table,
3010 PretenureFlag pretenure = NOT_TENURED);
3012 // Sets the capacity of the hash table.
3013 void SetCapacity(int capacity) {
3014 // To scale a computed hash code to fit within the hash table, we
3015 // use bit-wise AND with a mask, so the capacity must be positive
3017 DCHECK(capacity > 0);
3018 DCHECK(capacity <= kMaxCapacity);
3019 set(kCapacityIndex, Smi::FromInt(capacity));
3022 // Maximal capacity of HashTable. Based on maximal length of underlying
3023 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3025 static const int kMaxCapacity =
3026 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3029 // Returns _expected_ if one of entries given by the first _probe_ probes is
3030 // equal to _expected_. Otherwise, returns the entry given by the probe
3032 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3034 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3036 // Rehashes this hash-table into the new table.
3037 void Rehash(Handle<Derived> new_table, Key key);
3041 // HashTableKey is an abstract superclass for virtual key behavior.
3042 class HashTableKey {
3044 // Returns whether the other object matches this key.
3045 virtual bool IsMatch(Object* other) = 0;
3046 // Returns the hash value for this key.
3047 virtual uint32_t Hash() = 0;
3048 // Returns the hash value for object.
3049 virtual uint32_t HashForObject(Object* key) = 0;
3050 // Returns the key object for storing into the hash table.
3051 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3053 virtual ~HashTableKey() {}
3057 class StringTableShape : public BaseShape<HashTableKey*> {
3059 static inline bool IsMatch(HashTableKey* key, Object* value) {
3060 return key->IsMatch(value);
3063 static inline uint32_t Hash(HashTableKey* key) {
3067 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3068 return key->HashForObject(object);
3071 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3073 static const int kPrefixSize = 0;
3074 static const int kEntrySize = 1;
3077 class SeqOneByteString;
3081 // No special elements in the prefix and the element size is 1
3082 // because only the string itself (the key) needs to be stored.
3083 class StringTable: public HashTable<StringTable,
3087 // Find string in the string table. If it is not there yet, it is
3088 // added. The return value is the string found.
3089 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3090 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3091 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3093 // Tries to internalize given string and returns string handle on success
3094 // or an empty handle otherwise.
3095 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3097 Handle<String> string);
3099 // Looks up a string that is equal to the given string and returns
3100 // string handle if it is found, or an empty handle otherwise.
3101 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3103 Handle<String> str);
3104 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3109 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3111 DECLARE_CAST(StringTable)
3114 template <bool seq_one_byte>
3115 friend class JsonParser;
3117 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3121 template <typename Derived, typename Shape, typename Key>
3122 class Dictionary: public HashTable<Derived, Shape, Key> {
3123 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3126 // Returns the value at entry.
3127 Object* ValueAt(int entry) {
3128 return this->get(Derived::EntryToIndex(entry) + 1);
3131 // Set the value for entry.
3132 void ValueAtPut(int entry, Object* value) {
3133 this->set(Derived::EntryToIndex(entry) + 1, value);
3136 // Returns the property details for the property at entry.
3137 PropertyDetails DetailsAt(int entry) {
3138 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3141 // Set the details for entry.
3142 void DetailsAtPut(int entry, PropertyDetails value) {
3143 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3146 // Returns true if property at given entry is deleted.
3147 bool IsDeleted(int entry) {
3148 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3151 // Delete a property from the dictionary.
3152 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3154 // Attempt to shrink the dictionary after deletion of key.
3155 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3156 Handle<Derived> dictionary,
3158 return DerivedHashTable::Shrink(dictionary, key);
3162 // TODO(dcarney): templatize or move to SeededNumberDictionary
3163 void CopyValuesTo(FixedArray* elements);
3165 // Returns the number of elements in the dictionary filtering out properties
3166 // with the specified attributes.
3167 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3169 // Returns the number of enumerable elements in the dictionary.
3170 int NumberOfEnumElements() {
3171 return NumberOfElementsFilterAttributes(
3172 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3175 // Returns true if the dictionary contains any elements that are non-writable,
3176 // non-configurable, non-enumerable, or have getters/setters.
3177 bool HasComplexElements();
3179 enum SortMode { UNSORTED, SORTED };
3181 // Fill in details for properties into storage.
3182 // Returns the number of properties added.
3183 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3184 SortMode sort_mode);
3186 // Copies enumerable keys to preallocated fixed array.
3187 void CopyEnumKeysTo(FixedArray* storage);
3189 // Accessors for next enumeration index.
3190 void SetNextEnumerationIndex(int index) {
3192 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3195 int NextEnumerationIndex() {
3196 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3199 // Creates a new dictionary.
3200 MUST_USE_RESULT static Handle<Derived> New(
3202 int at_least_space_for,
3203 PretenureFlag pretenure = NOT_TENURED);
3205 // Ensure enough space for n additional elements.
3206 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3209 void Print(std::ostream& os); // NOLINT
3211 // Returns the key (slow).
3212 Object* SlowReverseLookup(Object* value);
3214 // Sets the entry to (key, value) pair.
3215 inline void SetEntry(int entry,
3217 Handle<Object> value);
3218 inline void SetEntry(int entry,
3220 Handle<Object> value,
3221 PropertyDetails details);
3223 MUST_USE_RESULT static Handle<Derived> Add(
3224 Handle<Derived> dictionary,
3226 Handle<Object> value,
3227 PropertyDetails details);
3229 // Returns iteration indices array for the |dictionary|.
3230 // Values are direct indices in the |HashTable| array.
3231 static Handle<FixedArray> BuildIterationIndicesArray(
3232 Handle<Derived> dictionary);
3235 // Generic at put operation.
3236 MUST_USE_RESULT static Handle<Derived> AtPut(
3237 Handle<Derived> dictionary,
3239 Handle<Object> value);
3241 // Add entry to dictionary.
3242 static void AddEntry(
3243 Handle<Derived> dictionary,
3245 Handle<Object> value,
3246 PropertyDetails details,
3249 // Generate new enumeration indices to avoid enumeration index overflow.
3250 // Returns iteration indices array for the |dictionary|.
3251 static Handle<FixedArray> GenerateNewEnumerationIndices(
3252 Handle<Derived> dictionary);
3253 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3254 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3258 template <typename Derived, typename Shape>
3259 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3260 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3263 // Find entry for key, otherwise return kNotFound. Optimized version of
3264 // HashTable::FindEntry.
3265 int FindEntry(Handle<Name> key);
3269 template <typename Key>
3270 class BaseDictionaryShape : public BaseShape<Key> {
3272 template <typename Dictionary>
3273 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3274 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3275 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3276 return PropertyDetails(
3277 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3280 template <typename Dictionary>
3281 static inline void DetailsAtPut(Dictionary* dict, int entry,
3282 PropertyDetails value) {
3283 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3284 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3287 template <typename Dictionary>
3288 static bool IsDeleted(Dictionary* dict, int entry) {
3292 template <typename Dictionary>
3293 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3294 Handle<Object> value, PropertyDetails details);
3298 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3300 static inline bool IsMatch(Handle<Name> key, Object* other);
3301 static inline uint32_t Hash(Handle<Name> key);
3302 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3303 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3304 static const int kPrefixSize = 2;
3305 static const int kEntrySize = 3;
3306 static const bool kIsEnumerable = true;
3310 class NameDictionary
3311 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3312 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3316 DECLARE_CAST(NameDictionary)
3318 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3319 Handle<NameDictionary> dictionary);
3323 class GlobalDictionaryShape : public NameDictionaryShape {
3325 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3327 template <typename Dictionary>
3328 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3330 template <typename Dictionary>
3331 static inline void DetailsAtPut(Dictionary* dict, int entry,
3332 PropertyDetails value);
3334 template <typename Dictionary>
3335 static bool IsDeleted(Dictionary* dict, int entry);
3337 template <typename Dictionary>
3338 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3339 Handle<Object> value, PropertyDetails details);
3343 class GlobalDictionary
3344 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3346 DECLARE_CAST(GlobalDictionary)
3350 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3352 static inline bool IsMatch(uint32_t key, Object* other);
3353 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3354 static const int kEntrySize = 3;
3355 static const bool kIsEnumerable = false;
3359 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3361 static const bool UsesSeed = true;
3362 static const int kPrefixSize = 2;
3364 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3365 static inline uint32_t SeededHashForObject(uint32_t key,
3371 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3373 static const int kPrefixSize = 0;
3375 static inline uint32_t Hash(uint32_t key);
3376 static inline uint32_t HashForObject(uint32_t key, Object* object);
3380 class SeededNumberDictionary
3381 : public Dictionary<SeededNumberDictionary,
3382 SeededNumberDictionaryShape,
3385 DECLARE_CAST(SeededNumberDictionary)
3387 // Type specific at put (default NONE attributes is used when adding).
3388 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3389 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3390 Handle<Object> value, bool used_as_prototype);
3391 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3392 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3393 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3395 // Set an existing entry or add a new one if needed.
3396 // Return the updated dictionary.
3397 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3398 Handle<SeededNumberDictionary> dictionary, uint32_t key,
3399 Handle<Object> value, PropertyDetails details, bool used_as_prototype);
3401 void UpdateMaxNumberKey(uint32_t key, bool used_as_prototype);
3403 // If slow elements are required we will never go back to fast-case
3404 // for the elements kept in this dictionary. We require slow
3405 // elements if an element has been added at an index larger than
3406 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3407 // when defining a getter or setter with a number key.
3408 inline bool requires_slow_elements();
3409 inline void set_requires_slow_elements();
3411 // Get the value of the max number key that has been added to this
3412 // dictionary. max_number_key can only be called if
3413 // requires_slow_elements returns false.
3414 inline uint32_t max_number_key();
3417 static const int kRequiresSlowElementsMask = 1;
3418 static const int kRequiresSlowElementsTagSize = 1;
3419 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3423 class UnseededNumberDictionary
3424 : public Dictionary<UnseededNumberDictionary,
3425 UnseededNumberDictionaryShape,
3428 DECLARE_CAST(UnseededNumberDictionary)
3430 // Type specific at put (default NONE attributes is used when adding).
3431 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3432 Handle<UnseededNumberDictionary> dictionary,
3434 Handle<Object> value);
3435 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3436 Handle<UnseededNumberDictionary> dictionary,
3438 Handle<Object> value);
3440 // Set an existing entry or add a new one if needed.
3441 // Return the updated dictionary.
3442 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3443 Handle<UnseededNumberDictionary> dictionary,
3445 Handle<Object> value);
3449 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3451 static inline bool IsMatch(Handle<Object> key, Object* other);
3452 static inline uint32_t Hash(Handle<Object> key);
3453 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3454 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3455 static const int kPrefixSize = 0;
3456 static const int kEntrySize = 2;
3460 // ObjectHashTable maps keys that are arbitrary objects to object values by
3461 // using the identity hash of the key for hashing purposes.
3462 class ObjectHashTable: public HashTable<ObjectHashTable,
3463 ObjectHashTableShape,
3466 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3468 DECLARE_CAST(ObjectHashTable)
3470 // Attempt to shrink hash table after removal of key.
3471 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3472 Handle<ObjectHashTable> table,
3473 Handle<Object> key);
3475 // Looks up the value associated with the given key. The hole value is
3476 // returned in case the key is not present.
3477 Object* Lookup(Handle<Object> key);
3478 Object* Lookup(Handle<Object> key, int32_t hash);
3479 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3481 // Adds (or overwrites) the value associated with the given key.
3482 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3484 Handle<Object> value);
3485 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3486 Handle<Object> key, Handle<Object> value,
3489 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3490 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3493 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3494 Handle<Object> key, bool* was_present,
3498 friend class MarkCompactCollector;
3500 void AddEntry(int entry, Object* key, Object* value);
3501 void RemoveEntry(int entry);
3503 // Returns the index to the value of an entry.
3504 static inline int EntryToValueIndex(int entry) {
3505 return EntryToIndex(entry) + 1;
3510 // OrderedHashTable is a HashTable with Object keys that preserves
3511 // insertion order. There are Map and Set interfaces (OrderedHashMap
3512 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3514 // Only Object* keys are supported, with Object::SameValueZero() used as the
3515 // equality operator and Object::GetHash() for the hash function.
3517 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3518 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3519 // Originally attributed to Tyler Close.
3522 // [0]: bucket count
3523 // [1]: element count
3524 // [2]: deleted element count
3525 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3526 // offset into the data table (see below) where the
3527 // first item in this bucket is stored.
3528 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3529 // Capacity() * kEntrySize, where the first entrysize
3530 // items are handled by the derived class and the
3531 // item at kChainOffset is another entry into the
3532 // data table indicating the next entry in this hash
3535 // When we transition the table to a new version we obsolete it and reuse parts
3536 // of the memory to store information how to transition an iterator to the new
3539 // Memory layout for obsolete table:
3540 // [0]: bucket count
3541 // [1]: Next newer table
3542 // [2]: Number of removed holes or -1 when the table was cleared.
3543 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3544 // [3 + NumberOfRemovedHoles()..length]: Not used
3546 template<class Derived, class Iterator, int entrysize>
3547 class OrderedHashTable: public FixedArray {
3549 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3550 static Handle<Derived> Allocate(
3551 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3553 // Returns an OrderedHashTable (possibly |table|) with enough space
3554 // to add at least one new element.
3555 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3557 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3559 static Handle<Derived> Shrink(Handle<Derived> table);
3561 // Returns a new empty OrderedHashTable and records the clearing so that
3562 // exisiting iterators can be updated.
3563 static Handle<Derived> Clear(Handle<Derived> table);
3565 int NumberOfElements() {
3566 return Smi::cast(get(kNumberOfElementsIndex))->value();
3569 int NumberOfDeletedElements() {
3570 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3573 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3575 int NumberOfBuckets() {
3576 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3579 // Returns an index into |this| for the given entry.
3580 int EntryToIndex(int entry) {
3581 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3584 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3587 return !get(kNextTableIndex)->IsSmi();
3590 // The next newer table. This is only valid if the table is obsolete.
3591 Derived* NextTable() {
3592 return Derived::cast(get(kNextTableIndex));
3595 // When the table is obsolete we store the indexes of the removed holes.
3596 int RemovedIndexAt(int index) {
3597 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3600 static const int kNotFound = -1;
3601 static const int kMinCapacity = 4;
3603 static const int kNumberOfBucketsIndex = 0;
3604 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3605 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3606 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3607 static const int kNextTableIndex = kNumberOfElementsIndex;
3609 static const int kNumberOfBucketsOffset =
3610 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3611 static const int kNumberOfElementsOffset =
3612 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3613 static const int kNumberOfDeletedElementsOffset =
3614 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3615 static const int kHashTableStartOffset =
3616 kHeaderSize + kHashTableStartIndex * kPointerSize;
3617 static const int kNextTableOffset =
3618 kHeaderSize + kNextTableIndex * kPointerSize;
3620 static const int kEntrySize = entrysize + 1;
3621 static const int kChainOffset = entrysize;
3623 static const int kLoadFactor = 2;
3625 // NumberOfDeletedElements is set to kClearedTableSentinel when
3626 // the table is cleared, which allows iterator transitions to
3627 // optimize that case.
3628 static const int kClearedTableSentinel = -1;
3631 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3633 void SetNumberOfBuckets(int num) {
3634 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3637 void SetNumberOfElements(int num) {
3638 set(kNumberOfElementsIndex, Smi::FromInt(num));
3641 void SetNumberOfDeletedElements(int num) {
3642 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3646 return NumberOfBuckets() * kLoadFactor;
3649 void SetNextTable(Derived* next_table) {
3650 set(kNextTableIndex, next_table);
3653 void SetRemovedIndexAt(int index, int removed_index) {
3654 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3657 static const int kRemovedHolesIndex = kHashTableStartIndex;
3659 static const int kMaxCapacity =
3660 (FixedArray::kMaxLength - kHashTableStartIndex)
3661 / (1 + (kEntrySize * kLoadFactor));
3665 class JSSetIterator;
3668 class OrderedHashSet: public OrderedHashTable<
3669 OrderedHashSet, JSSetIterator, 1> {
3671 DECLARE_CAST(OrderedHashSet)
3675 class JSMapIterator;
3678 class OrderedHashMap
3679 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3681 DECLARE_CAST(OrderedHashMap)
3683 inline Object* ValueAt(int entry);
3685 static const int kValueOffset = 1;
3689 template <int entrysize>
3690 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3692 static inline bool IsMatch(Handle<Object> key, Object* other);
3693 static inline uint32_t Hash(Handle<Object> key);
3694 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3695 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3696 static const int kPrefixSize = 0;
3697 static const int kEntrySize = entrysize;
3701 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3702 // values. The table wraps the keys in weak cells and store values directly.
3703 // Thus it references keys weakly and values strongly.
3704 class WeakHashTable: public HashTable<WeakHashTable,
3705 WeakHashTableShape<2>,
3708 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3710 DECLARE_CAST(WeakHashTable)
3712 // Looks up the value associated with the given key. The hole value is
3713 // returned in case the key is not present.
3714 Object* Lookup(Handle<HeapObject> key);
3716 // Adds (or overwrites) the value associated with the given key. Mapping a
3717 // key to the hole value causes removal of the whole entry.
3718 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3719 Handle<HeapObject> key,
3720 Handle<HeapObject> value);
3722 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3725 friend class MarkCompactCollector;
3727 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3729 // Returns the index to the value of an entry.
3730 static inline int EntryToValueIndex(int entry) {
3731 return EntryToIndex(entry) + 1;
3736 // ScopeInfo represents information about different scopes of a source
3737 // program and the allocation of the scope's variables. Scope information
3738 // is stored in a compressed form in ScopeInfo objects and is used
3739 // at runtime (stack dumps, deoptimization, etc.).
3741 // This object provides quick access to scope info details for runtime
3743 class ScopeInfo : public FixedArray {
3745 DECLARE_CAST(ScopeInfo)
3747 // Return the type of this scope.
3748 ScopeType scope_type();
3750 // Does this scope call eval?
3753 // Return the language mode of this scope.
3754 LanguageMode language_mode();
3756 // True if this scope is a (var) declaration scope.
3757 bool is_declaration_scope();
3759 // Does this scope make a sloppy eval call?
3760 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3762 // Return the total number of locals allocated on the stack and in the
3763 // context. This includes the parameters that are allocated in the context.
3766 // Return the number of stack slots for code. This number consists of two
3768 // 1. One stack slot per stack allocated local.
3769 // 2. One stack slot for the function name if it is stack allocated.
3770 int StackSlotCount();
3772 // Return the number of context slots for code if a context is allocated. This
3773 // number consists of three parts:
3774 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3775 // 2. One context slot per context allocated local.
3776 // 3. One context slot for the function name if it is context allocated.
3777 // Parameters allocated in the context count as context allocated locals. If
3778 // no contexts are allocated for this scope ContextLength returns 0.
3779 int ContextLength();
3781 // Does this scope declare a "this" binding?
3784 // Does this scope declare a "this" binding, and the "this" binding is stack-
3785 // or context-allocated?
3786 bool HasAllocatedReceiver();
3788 // Is this scope the scope of a named function expression?
3789 bool HasFunctionName();
3791 // Return if this has context allocated locals.
3792 bool HasHeapAllocatedLocals();
3794 // Return if contexts are allocated for this scope.
3797 // Return if this is a function scope with "use asm".
3798 inline bool IsAsmModule();
3800 // Return if this is a nested function within an asm module scope.
3801 inline bool IsAsmFunction();
3803 inline bool HasSimpleParameters();
3805 // Return the function_name if present.
3806 String* FunctionName();
3808 // Return the name of the given parameter.
3809 String* ParameterName(int var);
3811 // Return the name of the given local.
3812 String* LocalName(int var);
3814 // Return the name of the given stack local.
3815 String* StackLocalName(int var);
3817 // Return the name of the given stack local.
3818 int StackLocalIndex(int var);
3820 // Return the name of the given context local.
3821 String* ContextLocalName(int var);
3823 // Return the mode of the given context local.
3824 VariableMode ContextLocalMode(int var);
3826 // Return the initialization flag of the given context local.
3827 InitializationFlag ContextLocalInitFlag(int var);
3829 // Return the initialization flag of the given context local.
3830 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3832 // Return true if this local was introduced by the compiler, and should not be
3833 // exposed to the user in a debugger.
3834 bool LocalIsSynthetic(int var);
3836 String* StrongModeFreeVariableName(int var);
3837 int StrongModeFreeVariableStartPosition(int var);
3838 int StrongModeFreeVariableEndPosition(int var);
3840 // Lookup support for serialized scope info. Returns the
3841 // the stack slot index for a given slot name if the slot is
3842 // present; otherwise returns a value < 0. The name must be an internalized
3844 int StackSlotIndex(String* name);
3846 // Lookup support for serialized scope info. Returns the
3847 // context slot index for a given slot name if the slot is present; otherwise
3848 // returns a value < 0. The name must be an internalized string.
3849 // If the slot is present and mode != NULL, sets *mode to the corresponding
3850 // mode for that variable.
3851 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3852 VariableMode* mode, VariableLocation* location,
3853 InitializationFlag* init_flag,
3854 MaybeAssignedFlag* maybe_assigned_flag);
3856 // Lookup the name of a certain context slot by its index.
3857 String* ContextSlotName(int slot_index);
3859 // Lookup support for serialized scope info. Returns the
3860 // parameter index for a given parameter name if the parameter is present;
3861 // otherwise returns a value < 0. The name must be an internalized string.
3862 int ParameterIndex(String* name);
3864 // Lookup support for serialized scope info. Returns the function context
3865 // slot index if the function name is present and context-allocated (named
3866 // function expressions, only), otherwise returns a value < 0. The name
3867 // must be an internalized string.
3868 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3870 // Lookup support for serialized scope info. Returns the receiver context
3871 // slot index if scope has a "this" binding, and the binding is
3872 // context-allocated. Otherwise returns a value < 0.
3873 int ReceiverContextSlotIndex();
3875 FunctionKind function_kind();
3877 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
3878 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
3880 // Serializes empty scope info.
3881 static ScopeInfo* Empty(Isolate* isolate);
3887 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3888 // numeric and occupies one array slot.
3889 // 1. A set of properties of the scope
3890 // 2. The number of parameters. This only applies to function scopes. For
3891 // non-function scopes this is 0.
3892 // 3. The number of non-parameter variables allocated on the stack.
3893 // 4. The number of non-parameter and parameter variables allocated in the
3895 #define FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(V) \
3898 V(StackLocalCount) \
3899 V(ContextLocalCount) \
3900 V(ContextGlobalCount) \
3901 V(StrongModeFreeVariableCount)
3903 #define FIELD_ACCESSORS(name) \
3904 inline void Set##name(int value); \
3906 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(FIELD_ACCESSORS)
3907 #undef FIELD_ACCESSORS
3911 #define DECL_INDEX(name) k##name,
3912 FOR_EACH_SCOPE_INFO_NUMERIC_FIELD(DECL_INDEX)
3917 // The layout of the variable part of a ScopeInfo is as follows:
3918 // 1. ParameterEntries:
3919 // This part stores the names of the parameters for function scopes. One
3920 // slot is used per parameter, so in total this part occupies
3921 // ParameterCount() slots in the array. For other scopes than function
3922 // scopes ParameterCount() is 0.
3923 // 2. StackLocalFirstSlot:
3924 // Index of a first stack slot for stack local. Stack locals belonging to
3925 // this scope are located on a stack at slots starting from this index.
3926 // 3. StackLocalEntries:
3927 // Contains the names of local variables that are allocated on the stack,
3928 // in increasing order of the stack slot index. First local variable has
3929 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
3930 // One slot is used per stack local, so in total this part occupies
3931 // StackLocalCount() slots in the array.
3932 // 4. ContextLocalNameEntries:
3933 // Contains the names of local variables and parameters that are allocated
3934 // in the context. They are stored in increasing order of the context slot
3935 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3936 // context local, so in total this part occupies ContextLocalCount() slots
3938 // 5. ContextLocalInfoEntries:
3939 // Contains the variable modes and initialization flags corresponding to
3940 // the context locals in ContextLocalNameEntries. One slot is used per
3941 // context local, so in total this part occupies ContextLocalCount()
3942 // slots in the array.
3943 // 6. StrongModeFreeVariableNameEntries:
3944 // Stores the names of strong mode free variables.
3945 // 7. StrongModeFreeVariablePositionEntries:
3946 // Stores the locations (start and end position) of strong mode free
3948 // 8. RecieverEntryIndex:
3949 // If the scope binds a "this" value, one slot is reserved to hold the
3950 // context or stack slot index for the variable.
3951 // 9. FunctionNameEntryIndex:
3952 // If the scope belongs to a named function expression this part contains
3953 // information about the function variable. It always occupies two array
3954 // slots: a. The name of the function variable.
3955 // b. The context or stack slot index for the variable.
3956 int ParameterEntriesIndex();
3957 int StackLocalFirstSlotIndex();
3958 int StackLocalEntriesIndex();
3959 int ContextLocalNameEntriesIndex();
3960 int ContextGlobalNameEntriesIndex();
3961 int ContextLocalInfoEntriesIndex();
3962 int ContextGlobalInfoEntriesIndex();
3963 int StrongModeFreeVariableNameEntriesIndex();
3964 int StrongModeFreeVariablePositionEntriesIndex();
3965 int ReceiverEntryIndex();
3966 int FunctionNameEntryIndex();
3968 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
3969 VariableLocation* location, InitializationFlag* init_flag,
3970 MaybeAssignedFlag* maybe_assigned_flag);
3972 // Used for the function name variable for named function expressions, and for
3974 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
3976 // Properties of scopes.
3977 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
3978 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
3979 STATIC_ASSERT(LANGUAGE_END == 3);
3980 class LanguageModeField
3981 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
3982 class DeclarationScopeField
3983 : public BitField<bool, LanguageModeField::kNext, 1> {};
3984 class ReceiverVariableField
3985 : public BitField<VariableAllocationInfo, DeclarationScopeField::kNext,
3987 class FunctionVariableField
3988 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
3990 class FunctionVariableMode
3991 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
3992 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
3994 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
3995 class HasSimpleParametersField
3996 : public BitField<bool, AsmFunctionField::kNext, 1> {};
3997 class FunctionKindField
3998 : public BitField<FunctionKind, HasSimpleParametersField::kNext, 8> {};
4000 // BitFields representing the encoded information for context locals in the
4001 // ContextLocalInfoEntries part.
4002 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4003 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4004 class ContextLocalMaybeAssignedFlag
4005 : public BitField<MaybeAssignedFlag, 4, 1> {};
4007 friend class ScopeIterator;
4011 // The cache for maps used by normalized (dictionary mode) objects.
4012 // Such maps do not have property descriptors, so a typical program
4013 // needs very limited number of distinct normalized maps.
4014 class NormalizedMapCache: public FixedArray {
4016 static Handle<NormalizedMapCache> New(Isolate* isolate);
4018 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4019 PropertyNormalizationMode mode);
4020 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4024 DECLARE_CAST(NormalizedMapCache)
4026 static inline bool IsNormalizedMapCache(const Object* obj);
4028 DECLARE_VERIFIER(NormalizedMapCache)
4030 static const int kEntries = 64;
4032 static inline int GetIndex(Handle<Map> map);
4034 // The following declarations hide base class methods.
4035 Object* get(int index);
4036 void set(int index, Object* value);
4040 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4041 // that is attached to code objects.
4042 class ByteArray: public FixedArrayBase {
4046 // Setter and getter.
4047 inline byte get(int index);
4048 inline void set(int index, byte value);
4050 // Treat contents as an int array.
4051 inline int get_int(int index);
4053 static int SizeFor(int length) {
4054 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4056 // We use byte arrays for free blocks in the heap. Given a desired size in
4057 // bytes that is a multiple of the word size and big enough to hold a byte
4058 // array, this function returns the number of elements a byte array should
4060 static int LengthFor(int size_in_bytes) {
4061 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4062 DCHECK(size_in_bytes >= kHeaderSize);
4063 return size_in_bytes - kHeaderSize;
4066 // Returns data start address.
4067 inline Address GetDataStartAddress();
4069 // Returns a pointer to the ByteArray object for a given data start address.
4070 static inline ByteArray* FromDataStartAddress(Address address);
4072 DECLARE_CAST(ByteArray)
4074 // Dispatched behavior.
4075 inline int ByteArraySize();
4076 DECLARE_PRINTER(ByteArray)
4077 DECLARE_VERIFIER(ByteArray)
4079 // Layout description.
4080 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4082 // Maximal memory consumption for a single ByteArray.
4083 static const int kMaxSize = 512 * MB;
4084 // Maximal length of a single ByteArray.
4085 static const int kMaxLength = kMaxSize - kHeaderSize;
4088 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4092 // BytecodeArray represents a sequence of interpreter bytecodes.
4093 class BytecodeArray : public FixedArrayBase {
4095 static int SizeFor(int length) {
4096 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4099 // Setter and getter
4100 inline byte get(int index);
4101 inline void set(int index, byte value);
4103 // Returns data start address.
4104 inline Address GetFirstBytecodeAddress();
4106 // Accessors for frame size and the number of locals
4107 inline int frame_size() const;
4108 inline void set_frame_size(int value);
4110 DECLARE_CAST(BytecodeArray)
4112 // Dispatched behavior.
4113 inline int BytecodeArraySize();
4115 DECLARE_PRINTER(BytecodeArray)
4116 DECLARE_VERIFIER(BytecodeArray)
4118 void Disassemble(std::ostream& os);
4120 // Layout description.
4121 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4122 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4124 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4126 // Maximal memory consumption for a single BytecodeArray.
4127 static const int kMaxSize = 512 * MB;
4128 // Maximal length of a single BytecodeArray.
4129 static const int kMaxLength = kMaxSize - kHeaderSize;
4132 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4136 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4137 // They look like heap objects (are heap object tagged and have a map) so that
4138 // the heap remains iterable. They have a size and a next pointer.
4139 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4140 // in the free list.
4141 class FreeSpace: public HeapObject {
4143 // [size]: size of the free space including the header.
4144 inline int size() const;
4145 inline void set_size(int value);
4147 inline int nobarrier_size() const;
4148 inline void nobarrier_set_size(int value);
4152 // Accessors for the next field.
4153 inline FreeSpace* next();
4154 inline FreeSpace** next_address();
4155 inline void set_next(FreeSpace* next);
4157 inline static FreeSpace* cast(HeapObject* obj);
4159 // Dispatched behavior.
4160 DECLARE_PRINTER(FreeSpace)
4161 DECLARE_VERIFIER(FreeSpace)
4163 // Layout description.
4164 // Size is smi tagged when it is stored.
4165 static const int kSizeOffset = HeapObject::kHeaderSize;
4166 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4169 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4173 // V has parameters (Type, type, TYPE, C type, element_size)
4174 #define TYPED_ARRAYS(V) \
4175 V(Uint8, uint8, UINT8, uint8_t, 1) \
4176 V(Int8, int8, INT8, int8_t, 1) \
4177 V(Uint16, uint16, UINT16, uint16_t, 2) \
4178 V(Int16, int16, INT16, int16_t, 2) \
4179 V(Uint32, uint32, UINT32, uint32_t, 4) \
4180 V(Int32, int32, INT32, int32_t, 4) \
4181 V(Float32, float32, FLOAT32, float, 4) \
4182 V(Float64, float64, FLOAT64, double, 8) \
4183 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4186 class FixedTypedArrayBase: public FixedArrayBase {
4188 // [base_pointer]: Either points to the FixedTypedArrayBase itself or nullptr.
4189 DECL_ACCESSORS(base_pointer, Object)
4191 // [external_pointer]: Contains the offset between base_pointer and the start
4192 // of the data. If the base_pointer is a nullptr, the external_pointer
4193 // therefore points to the actual backing store.
4194 DECL_ACCESSORS(external_pointer, void)
4196 // Dispatched behavior.
4197 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4199 template <typename StaticVisitor>
4200 inline void FixedTypedArrayBaseIterateBody();
4202 DECLARE_CAST(FixedTypedArrayBase)
4204 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4205 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4206 static const int kHeaderSize =
4207 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4209 static const int kDataOffset = kHeaderSize;
4213 static inline int TypedArraySize(InstanceType type, int length);
4214 inline int TypedArraySize(InstanceType type);
4216 // Use with care: returns raw pointer into heap.
4217 inline void* DataPtr();
4219 inline int DataSize();
4222 static inline int ElementSize(InstanceType type);
4224 inline int DataSize(InstanceType type);
4226 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4230 template <class Traits>
4231 class FixedTypedArray: public FixedTypedArrayBase {
4233 typedef typename Traits::ElementType ElementType;
4234 static const InstanceType kInstanceType = Traits::kInstanceType;
4236 DECLARE_CAST(FixedTypedArray<Traits>)
4238 inline ElementType get_scalar(int index);
4239 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4240 inline void set(int index, ElementType value);
4242 static inline ElementType from_int(int value);
4243 static inline ElementType from_double(double value);
4245 // This accessor applies the correct conversion from Smi, HeapNumber
4247 void SetValue(uint32_t index, Object* value);
4249 DECLARE_PRINTER(FixedTypedArray)
4250 DECLARE_VERIFIER(FixedTypedArray)
4253 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4256 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4257 class Type##ArrayTraits { \
4258 public: /* NOLINT */ \
4259 typedef elementType ElementType; \
4260 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4261 static const char* Designator() { return #type " array"; } \
4262 static inline Handle<Object> ToHandle(Isolate* isolate, \
4263 elementType scalar); \
4264 static inline elementType defaultValue(); \
4267 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4269 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4271 #undef FIXED_TYPED_ARRAY_TRAITS
4274 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4275 // data for code generated by the Hydrogen/Lithium compiler. It also
4276 // contains information about functions that were inlined. If N different
4277 // functions were inlined then first N elements of the literal array will
4278 // contain these functions.
4281 class DeoptimizationInputData: public FixedArray {
4283 // Layout description. Indices in the array.
4284 static const int kTranslationByteArrayIndex = 0;
4285 static const int kInlinedFunctionCountIndex = 1;
4286 static const int kLiteralArrayIndex = 2;
4287 static const int kOsrAstIdIndex = 3;
4288 static const int kOsrPcOffsetIndex = 4;
4289 static const int kOptimizationIdIndex = 5;
4290 static const int kSharedFunctionInfoIndex = 6;
4291 static const int kWeakCellCacheIndex = 7;
4292 static const int kFirstDeoptEntryIndex = 8;
4294 // Offsets of deopt entry elements relative to the start of the entry.
4295 static const int kAstIdRawOffset = 0;
4296 static const int kTranslationIndexOffset = 1;
4297 static const int kArgumentsStackHeightOffset = 2;
4298 static const int kPcOffset = 3;
4299 static const int kDeoptEntrySize = 4;
4301 // Simple element accessors.
4302 #define DECLARE_ELEMENT_ACCESSORS(name, type) \
4303 inline type* name(); \
4304 inline void Set##name(type* value);
4306 DECLARE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4307 DECLARE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4308 DECLARE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4309 DECLARE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4310 DECLARE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4311 DECLARE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4312 DECLARE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4313 DECLARE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4315 #undef DECLARE_ELEMENT_ACCESSORS
4317 // Accessors for elements of the ith deoptimization entry.
4318 #define DECLARE_ENTRY_ACCESSORS(name, type) \
4319 inline type* name(int i); \
4320 inline void Set##name(int i, type* value);
4322 DECLARE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4323 DECLARE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4324 DECLARE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4325 DECLARE_ENTRY_ACCESSORS(Pc, Smi)
4327 #undef DECLARE_ENTRY_ACCESSORS
4329 inline BailoutId AstId(int i);
4331 inline void SetAstId(int i, BailoutId value);
4333 inline int DeoptCount();
4335 // Allocates a DeoptimizationInputData.
4336 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4337 int deopt_entry_count,
4338 PretenureFlag pretenure);
4340 DECLARE_CAST(DeoptimizationInputData)
4342 #ifdef ENABLE_DISASSEMBLER
4343 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4347 static int IndexForEntry(int i) {
4348 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4352 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4356 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4357 // data for code generated by the full compiler.
4358 // The format of the these objects is
4359 // [i * 2]: Ast ID for ith deoptimization.
4360 // [i * 2 + 1]: PC and state of ith deoptimization
4361 class DeoptimizationOutputData: public FixedArray {
4363 inline int DeoptPoints();
4365 inline BailoutId AstId(int index);
4367 inline void SetAstId(int index, BailoutId id);
4369 inline Smi* PcAndState(int index);
4370 inline void SetPcAndState(int index, Smi* offset);
4372 static int LengthOfFixedArray(int deopt_points) {
4373 return deopt_points * 2;
4376 // Allocates a DeoptimizationOutputData.
4377 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4378 int number_of_deopt_points,
4379 PretenureFlag pretenure);
4381 DECLARE_CAST(DeoptimizationOutputData)
4383 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4384 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4389 // HandlerTable is a fixed array containing entries for exception handlers in
4390 // the code object it is associated with. The tables comes in two flavors:
4391 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4392 // exception handler and a range representing the try-block covered by that
4393 // handler. Layout looks as follows:
4394 // [ range-start , range-end , handler-offset , stack-depth ]
4395 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4396 // per call-site that could throw an exception. Layout looks as follows:
4397 // [ return-address-offset , handler-offset ]
4398 class HandlerTable : public FixedArray {
4400 // Conservative prediction whether a given handler will locally catch an
4401 // exception or cause a re-throw to outside the code boundary. Since this is
4402 // undecidable it is merely an approximation (e.g. useful for debugger).
4403 enum CatchPrediction { UNCAUGHT, CAUGHT };
4405 // Accessors for handler table based on ranges.
4406 inline void SetRangeStart(int index, int value);
4407 inline void SetRangeEnd(int index, int value);
4408 inline void SetRangeHandler(int index, int offset, CatchPrediction pred);
4409 inline void SetRangeDepth(int index, int value);
4411 // Accessors for handler table based on return addresses.
4412 inline void SetReturnOffset(int index, int value);
4413 inline void SetReturnHandler(int index, int offset, CatchPrediction pred);
4415 // Lookup handler in a table based on ranges.
4416 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4418 // Lookup handler in a table based on return addresses.
4419 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4421 // Returns the required length of the underlying fixed array.
4422 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4423 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4425 DECLARE_CAST(HandlerTable)
4427 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4428 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4429 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4433 // Layout description for handler table based on ranges.
4434 static const int kRangeStartIndex = 0;
4435 static const int kRangeEndIndex = 1;
4436 static const int kRangeHandlerIndex = 2;
4437 static const int kRangeDepthIndex = 3;
4438 static const int kRangeEntrySize = 4;
4440 // Layout description for handler table based on return addresses.
4441 static const int kReturnOffsetIndex = 0;
4442 static const int kReturnHandlerIndex = 1;
4443 static const int kReturnEntrySize = 2;
4445 // Encoding of the {handler} field.
4446 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4447 class HandlerOffsetField : public BitField<int, 1, 30> {};
4451 // Code describes objects with on-the-fly generated machine code.
4452 class Code: public HeapObject {
4454 // Opaque data type for encapsulating code flags like kind, inline
4455 // cache state, and arguments count.
4456 typedef uint32_t Flags;
4458 #define NON_IC_KIND_LIST(V) \
4460 V(OPTIMIZED_FUNCTION) \
4466 #define IC_KIND_LIST(V) \
4477 #define CODE_KIND_LIST(V) \
4478 NON_IC_KIND_LIST(V) \
4482 #define DEFINE_CODE_KIND_ENUM(name) name,
4483 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4484 #undef DEFINE_CODE_KIND_ENUM
4488 // No more than 16 kinds. The value is currently encoded in four bits in
4490 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4492 static const char* Kind2String(Kind kind);
4500 static const int kPrologueOffsetNotSet = -1;
4502 #ifdef ENABLE_DISASSEMBLER
4504 static const char* ICState2String(InlineCacheState state);
4505 static const char* StubType2String(StubType type);
4506 static void PrintExtraICState(std::ostream& os, // NOLINT
4507 Kind kind, ExtraICState extra);
4508 void Disassemble(const char* name, std::ostream& os); // NOLINT
4509 #endif // ENABLE_DISASSEMBLER
4511 // [instruction_size]: Size of the native instructions
4512 inline int instruction_size() const;
4513 inline void set_instruction_size(int value);
4515 // [relocation_info]: Code relocation information
4516 DECL_ACCESSORS(relocation_info, ByteArray)
4517 void InvalidateRelocation();
4518 void InvalidateEmbeddedObjects();
4520 // [handler_table]: Fixed array containing offsets of exception handlers.
4521 DECL_ACCESSORS(handler_table, FixedArray)
4523 // [deoptimization_data]: Array containing data for deopt.
4524 DECL_ACCESSORS(deoptimization_data, FixedArray)
4526 // [raw_type_feedback_info]: This field stores various things, depending on
4527 // the kind of the code object.
4528 // FUNCTION => type feedback information.
4529 // STUB and ICs => major/minor key as Smi.
4530 DECL_ACCESSORS(raw_type_feedback_info, Object)
4531 inline Object* type_feedback_info();
4532 inline void set_type_feedback_info(
4533 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4534 inline uint32_t stub_key();
4535 inline void set_stub_key(uint32_t key);
4537 // [next_code_link]: Link for lists of optimized or deoptimized code.
4538 // Note that storage for this field is overlapped with typefeedback_info.
4539 DECL_ACCESSORS(next_code_link, Object)
4541 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4542 // field does not have to be traced during garbage collection since
4543 // it is only used by the garbage collector itself.
4544 DECL_ACCESSORS(gc_metadata, Object)
4546 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4547 // at the moment when this object was created.
4548 inline void set_ic_age(int count);
4549 inline int ic_age() const;
4551 // [prologue_offset]: Offset of the function prologue, used for aging
4552 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4553 inline int prologue_offset() const;
4554 inline void set_prologue_offset(int offset);
4556 // [constant_pool offset]: Offset of the constant pool.
4557 // Valid for FLAG_enable_embedded_constant_pool only
4558 inline int constant_pool_offset() const;
4559 inline void set_constant_pool_offset(int offset);
4561 // Unchecked accessors to be used during GC.
4562 inline ByteArray* unchecked_relocation_info();
4564 inline int relocation_size();
4566 // [flags]: Various code flags.
4567 inline Flags flags();
4568 inline void set_flags(Flags flags);
4570 // [flags]: Access to specific code flags.
4572 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4573 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4575 inline StubType type(); // Only valid for monomorphic IC stubs.
4577 // Testers for IC stub kinds.
4578 inline bool is_inline_cache_stub();
4579 inline bool is_debug_stub();
4580 inline bool is_handler();
4581 inline bool is_load_stub();
4582 inline bool is_keyed_load_stub();
4583 inline bool is_store_stub();
4584 inline bool is_keyed_store_stub();
4585 inline bool is_call_stub();
4586 inline bool is_binary_op_stub();
4587 inline bool is_compare_ic_stub();
4588 inline bool is_compare_nil_ic_stub();
4589 inline bool is_to_boolean_ic_stub();
4590 inline bool is_keyed_stub();
4591 inline bool is_optimized_code();
4592 inline bool embeds_maps_weakly();
4594 inline bool IsCodeStubOrIC();
4595 inline bool IsJavaScriptCode();
4597 inline void set_raw_kind_specific_flags1(int value);
4598 inline void set_raw_kind_specific_flags2(int value);
4600 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4601 // object was generated by either the hydrogen or the TurboFan optimizing
4602 // compiler (but it may not be an optimized function).
4603 inline bool is_crankshafted();
4604 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4605 inline void set_is_crankshafted(bool value);
4607 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4608 // code object was generated by the TurboFan optimizing compiler.
4609 inline bool is_turbofanned();
4610 inline void set_is_turbofanned(bool value);
4612 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4613 // embedded objects in code should be treated weakly.
4614 inline bool can_have_weak_objects();
4615 inline void set_can_have_weak_objects(bool value);
4617 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4618 // deoptimization support.
4619 inline bool has_deoptimization_support();
4620 inline void set_has_deoptimization_support(bool value);
4622 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4623 // been compiled with debug break slots.
4624 inline bool has_debug_break_slots();
4625 inline void set_has_debug_break_slots(bool value);
4627 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
4628 // reloc info includes runtime and external references to support
4629 // serialization/deserialization.
4630 inline bool has_reloc_info_for_serialization();
4631 inline void set_has_reloc_info_for_serialization(bool value);
4633 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4634 // how long the function has been marked for OSR and therefore which
4635 // level of loop nesting we are willing to do on-stack replacement
4637 inline void set_allow_osr_at_loop_nesting_level(int level);
4638 inline int allow_osr_at_loop_nesting_level();
4640 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4641 // the code object was seen on the stack with no IC patching going on.
4642 inline int profiler_ticks();
4643 inline void set_profiler_ticks(int ticks);
4645 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
4646 // For builtins, tells which builtin index it has.
4647 // Note that builtins can have a code kind other than BUILTIN, which means
4648 // that for arbitrary code objects, this index value may be random garbage.
4649 // To verify in that case, compare the code object to the indexed builtin.
4650 inline int builtin_index();
4651 inline void set_builtin_index(int id);
4653 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4654 // reserved in the code prologue.
4655 inline unsigned stack_slots();
4656 inline void set_stack_slots(unsigned slots);
4658 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
4659 // the instruction stream where the safepoint table starts.
4660 inline unsigned safepoint_table_offset();
4661 inline void set_safepoint_table_offset(unsigned offset);
4663 // [back_edge_table_start]: For kind FUNCTION, the offset in the
4664 // instruction stream where the back edge table starts.
4665 inline unsigned back_edge_table_offset();
4666 inline void set_back_edge_table_offset(unsigned offset);
4668 inline bool back_edges_patched_for_osr();
4670 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4671 inline uint16_t to_boolean_state();
4673 // [has_function_cache]: For kind STUB tells whether there is a function
4674 // cache is passed to the stub.
4675 inline bool has_function_cache();
4676 inline void set_has_function_cache(bool flag);
4679 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
4680 // the code is going to be deoptimized because of dead embedded maps.
4681 inline bool marked_for_deoptimization();
4682 inline void set_marked_for_deoptimization(bool flag);
4684 // [constant_pool]: The constant pool for this function.
4685 inline Address constant_pool();
4687 // Get the safepoint entry for the given pc.
4688 SafepointEntry GetSafepointEntry(Address pc);
4690 // Find an object in a stub with a specified map
4691 Object* FindNthObject(int n, Map* match_map);
4693 // Find the first allocation site in an IC stub.
4694 AllocationSite* FindFirstAllocationSite();
4696 // Find the first map in an IC stub.
4697 Map* FindFirstMap();
4698 void FindAllMaps(MapHandleList* maps);
4700 // Find the first handler in an IC stub.
4701 Code* FindFirstHandler();
4703 // Find |length| handlers and put them into |code_list|. Returns false if not
4704 // enough handlers can be found.
4705 bool FindHandlers(CodeHandleList* code_list, int length = -1);
4707 // Find the handler for |map|.
4708 MaybeHandle<Code> FindHandlerForMap(Map* map);
4710 // Find the first name in an IC stub.
4711 Name* FindFirstName();
4713 class FindAndReplacePattern;
4714 // For each (map-to-find, object-to-replace) pair in the pattern, this
4715 // function replaces the corresponding placeholder in the code with the
4716 // object-to-replace. The function assumes that pairs in the pattern come in
4717 // the same order as the placeholders in the code.
4718 // If the placeholder is a weak cell, then the value of weak cell is matched
4719 // against the map-to-find.
4720 void FindAndReplace(const FindAndReplacePattern& pattern);
4722 // The entire code object including its header is copied verbatim to the
4723 // snapshot so that it can be written in one, fast, memcpy during
4724 // deserialization. The deserializer will overwrite some pointers, rather
4725 // like a runtime linker, but the random allocation addresses used in the
4726 // mksnapshot process would still be present in the unlinked snapshot data,
4727 // which would make snapshot production non-reproducible. This method wipes
4728 // out the to-be-overwritten header data for reproducible snapshots.
4729 inline void WipeOutHeader();
4731 // Flags operations.
4732 static inline Flags ComputeFlags(
4733 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
4734 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
4735 CacheHolderFlag holder = kCacheOnReceiver);
4737 static inline Flags ComputeMonomorphicFlags(
4738 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
4739 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
4741 static inline Flags ComputeHandlerFlags(
4742 Kind handler_kind, StubType type = NORMAL,
4743 CacheHolderFlag holder = kCacheOnReceiver);
4745 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4746 static inline StubType ExtractTypeFromFlags(Flags flags);
4747 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4748 static inline Kind ExtractKindFromFlags(Flags flags);
4749 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4751 static inline Flags RemoveTypeFromFlags(Flags flags);
4752 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
4754 // Convert a target address into a code object.
4755 static inline Code* GetCodeFromTargetAddress(Address address);
4757 // Convert an entry address into an object.
4758 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4760 // Returns the address of the first instruction.
4761 inline byte* instruction_start();
4763 // Returns the address right after the last instruction.
4764 inline byte* instruction_end();
4766 // Returns the size of the instructions, padding, and relocation information.
4767 inline int body_size();
4769 // Returns the address of the first relocation info (read backwards!).
4770 inline byte* relocation_start();
4772 // Code entry point.
4773 inline byte* entry();
4775 // Returns true if pc is inside this object's instructions.
4776 inline bool contains(byte* pc);
4778 // Relocate the code by delta bytes. Called to signal that this code
4779 // object has been moved by delta bytes.
4780 void Relocate(intptr_t delta);
4782 // Migrate code described by desc.
4783 void CopyFrom(const CodeDesc& desc);
4785 // Returns the object size for a given body (used for allocation).
4786 static int SizeFor(int body_size) {
4787 DCHECK_SIZE_TAG_ALIGNED(body_size);
4788 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4791 // Calculate the size of the code object to report for log events. This takes
4792 // the layout of the code object into account.
4793 inline int ExecutableSize();
4795 // Locating source position.
4796 int SourcePosition(Address pc);
4797 int SourceStatementPosition(Address pc);
4801 // Dispatched behavior.
4802 inline int CodeSize();
4803 inline void CodeIterateBody(ObjectVisitor* v);
4805 template<typename StaticVisitor>
4806 inline void CodeIterateBody(Heap* heap);
4808 DECLARE_PRINTER(Code)
4809 DECLARE_VERIFIER(Code)
4811 void ClearInlineCaches();
4812 void ClearInlineCaches(Kind kind);
4814 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
4815 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
4817 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
4819 kToBeExecutedOnceCodeAge = -3,
4820 kNotExecutedCodeAge = -2,
4821 kExecutedOnceCodeAge = -1,
4823 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
4825 kFirstCodeAge = kToBeExecutedOnceCodeAge,
4826 kLastCodeAge = kAfterLastCodeAge - 1,
4827 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
4828 kIsOldCodeAge = kSexagenarianCodeAge,
4829 kPreAgedCodeAge = kIsOldCodeAge - 1
4831 #undef DECLARE_CODE_AGE_ENUM
4833 // Code aging. Indicates how many full GCs this code has survived without
4834 // being entered through the prologue. Used to determine when it is
4835 // relatively safe to flush this code object and replace it with the lazy
4836 // compilation stub.
4837 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
4838 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
4839 void MakeYoung(Isolate* isolate);
4840 void MarkToBeExecutedOnce(Isolate* isolate);
4841 void MakeOlder(MarkingParity);
4842 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
4845 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
4846 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
4849 void PrintDeoptLocation(FILE* out, Address pc);
4850 bool CanDeoptAt(Address pc);
4853 void VerifyEmbeddedObjectsDependency();
4857 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
4858 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
4859 static void VerifyRecompiledCode(Code* old_code, Code* new_code);
4862 inline bool CanContainWeakObjects();
4864 inline bool IsWeakObject(Object* object);
4866 static inline bool IsWeakObjectInOptimizedCode(Object* object);
4868 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
4869 WeakCell* CachedWeakCell();
4871 // Max loop nesting marker used to postpose OSR. We don't take loop
4872 // nesting that is deeper than 5 levels into account.
4873 static const int kMaxLoopNestingMarker = 6;
4875 static const int kConstantPoolSize =
4876 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
4878 // Layout description.
4879 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
4880 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4881 static const int kDeoptimizationDataOffset =
4882 kHandlerTableOffset + kPointerSize;
4883 // For FUNCTION kind, we store the type feedback info here.
4884 static const int kTypeFeedbackInfoOffset =
4885 kDeoptimizationDataOffset + kPointerSize;
4886 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
4887 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
4888 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
4889 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
4890 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4891 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
4892 static const int kKindSpecificFlags2Offset =
4893 kKindSpecificFlags1Offset + kIntSize;
4894 // Note: We might be able to squeeze this into the flags above.
4895 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
4896 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
4897 static const int kHeaderPaddingStart =
4898 kConstantPoolOffset + kConstantPoolSize;
4900 // Add padding to align the instruction start following right after
4901 // the Code object header.
4902 static const int kHeaderSize =
4903 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4905 // Byte offsets within kKindSpecificFlags1Offset.
4906 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
4907 class FullCodeFlagsHasDeoptimizationSupportField:
4908 public BitField<bool, 0, 1> {}; // NOLINT
4909 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4910 class FullCodeFlagsHasRelocInfoForSerialization
4911 : public BitField<bool, 2, 1> {};
4912 // Bit 3 in this bitfield is unused.
4913 class ProfilerTicksField : public BitField<int, 4, 28> {};
4915 // Flags layout. BitField<type, shift, size>.
4916 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
4917 class TypeField : public BitField<StubType, 4, 1> {};
4918 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
4919 class KindField : public BitField<Kind, 7, 4> {};
4920 class ExtraICStateField: public BitField<ExtraICState, 11,
4921 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
4923 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
4924 static const int kStackSlotsFirstBit = 0;
4925 static const int kStackSlotsBitCount = 24;
4926 static const int kHasFunctionCacheBit =
4927 kStackSlotsFirstBit + kStackSlotsBitCount;
4928 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
4929 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
4930 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
4932 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
4933 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
4935 class StackSlotsField: public BitField<int,
4936 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
4937 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
4939 class MarkedForDeoptimizationField
4940 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
4941 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
4943 class CanHaveWeakObjectsField
4944 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
4946 // KindSpecificFlags2 layout (ALL)
4947 static const int kIsCrankshaftedBit = 0;
4948 class IsCrankshaftedField: public BitField<bool,
4949 kIsCrankshaftedBit, 1> {}; // NOLINT
4951 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
4952 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
4953 static const int kSafepointTableOffsetBitCount = 30;
4955 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
4956 kSafepointTableOffsetBitCount <= 32);
4957 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
4959 class SafepointTableOffsetField: public BitField<int,
4960 kSafepointTableOffsetFirstBit,
4961 kSafepointTableOffsetBitCount> {}; // NOLINT
4963 // KindSpecificFlags2 layout (FUNCTION)
4964 class BackEdgeTableOffsetField: public BitField<int,
4965 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
4966 class AllowOSRAtLoopNestingLevelField: public BitField<int,
4967 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
4968 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
4970 static const int kArgumentsBits = 16;
4971 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
4973 // This constant should be encodable in an ARM instruction.
4974 static const int kFlagsNotUsedInLookup =
4975 TypeField::kMask | CacheHolderField::kMask;
4978 friend class RelocIterator;
4979 friend class Deoptimizer; // For FindCodeAgeSequence.
4981 void ClearInlineCaches(Kind* kind);
4984 byte* FindCodeAgeSequence();
4985 static void GetCodeAgeAndParity(Code* code, Age* age,
4986 MarkingParity* parity);
4987 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
4988 MarkingParity* parity);
4989 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
4991 // Code aging -- platform-specific
4992 static void PatchPlatformCodeAge(Isolate* isolate,
4993 byte* sequence, Age age,
4994 MarkingParity parity);
4996 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5000 // This class describes the layout of dependent codes array of a map. The
5001 // array is partitioned into several groups of dependent codes. Each group
5002 // contains codes with the same dependency on the map. The array has the
5003 // following layout for n dependency groups:
5005 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5006 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5007 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5009 // The first n elements are Smis, each of them specifies the number of codes
5010 // in the corresponding group. The subsequent elements contain grouped code
5011 // objects in weak cells. The suffix of the array can be filled with the
5012 // undefined value if the number of codes is less than the length of the
5013 // array. The order of the code objects within a group is not preserved.
5015 // All code indexes used in the class are counted starting from the first
5016 // code object of the first group. In other words, code index 0 corresponds
5017 // to array index n = kCodesStartIndex.
5019 class DependentCode: public FixedArray {
5021 enum DependencyGroup {
5022 // Group of code that weakly embed this map and depend on being
5023 // deoptimized when the map is garbage collected.
5025 // Group of code that embed a transition to this map, and depend on being
5026 // deoptimized when the transition is replaced by a new version.
5028 // Group of code that omit run-time prototype checks for prototypes
5029 // described by this map. The group is deoptimized whenever an object
5030 // described by this map changes shape (and transitions to a new map),
5031 // possibly invalidating the assumptions embedded in the code.
5032 kPrototypeCheckGroup,
5033 // Group of code that depends on global property values in property cells
5034 // not being changed.
5035 kPropertyCellChangedGroup,
5036 // Group of code that omit run-time type checks for the field(s) introduced
5039 // Group of code that omit run-time type checks for initial maps of
5041 kInitialMapChangedGroup,
5042 // Group of code that depends on tenuring information in AllocationSites
5043 // not being changed.
5044 kAllocationSiteTenuringChangedGroup,
5045 // Group of code that depends on element transition information in
5046 // AllocationSites not being changed.
5047 kAllocationSiteTransitionChangedGroup
5050 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5052 // Array for holding the index of the first code object of each group.
5053 // The last element stores the total number of code objects.
5054 class GroupStartIndexes {
5056 explicit GroupStartIndexes(DependentCode* entries);
5057 void Recompute(DependentCode* entries);
5058 int at(int i) { return start_indexes_[i]; }
5059 int number_of_entries() { return start_indexes_[kGroupCount]; }
5061 int start_indexes_[kGroupCount + 1];
5064 bool Contains(DependencyGroup group, WeakCell* code_cell);
5066 static Handle<DependentCode> InsertCompilationDependencies(
5067 Handle<DependentCode> entries, DependencyGroup group,
5068 Handle<Foreign> info);
5070 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5071 DependencyGroup group,
5072 Handle<WeakCell> code_cell);
5074 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5075 WeakCell* code_cell);
5077 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5080 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5081 DependentCode::DependencyGroup group);
5083 bool MarkCodeForDeoptimization(Isolate* isolate,
5084 DependentCode::DependencyGroup group);
5086 // The following low-level accessors should only be used by this class
5087 // and the mark compact collector.
5088 inline int number_of_entries(DependencyGroup group);
5089 inline void set_number_of_entries(DependencyGroup group, int value);
5090 inline Object* object_at(int i);
5091 inline void set_object_at(int i, Object* object);
5092 inline void clear_at(int i);
5093 inline void copy(int from, int to);
5094 DECLARE_CAST(DependentCode)
5096 static const char* DependencyGroupName(DependencyGroup group);
5097 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5100 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5101 DependencyGroup group,
5102 Handle<Object> object);
5103 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5104 // Make a room at the end of the given group by moving out the first
5105 // code objects of the subsequent groups.
5106 inline void ExtendGroup(DependencyGroup group);
5107 // Compact by removing cleared weak cells and return true if there was
5108 // any cleared weak cell.
5110 static int Grow(int number_of_entries) {
5111 if (number_of_entries < 5) return number_of_entries + 1;
5112 return number_of_entries * 5 / 4;
5114 static const int kCodesStartIndex = kGroupCount;
5118 class PrototypeInfo;
5121 // All heap objects have a Map that describes their structure.
5122 // A Map contains information about:
5123 // - Size information about the object
5124 // - How to iterate over an object (for garbage collection)
5125 class Map: public HeapObject {
5128 // Size in bytes or kVariableSizeSentinel if instances do not have
5130 inline int instance_size();
5131 inline void set_instance_size(int value);
5133 // Only to clear an unused byte, remove once byte is used.
5134 inline void clear_unused();
5136 // [inobject_properties_or_constructor_function_index]: Provides access
5137 // to the inobject properties in case of JSObject maps, or the constructor
5138 // function index in case of primitive maps.
5139 inline int inobject_properties_or_constructor_function_index();
5140 inline void set_inobject_properties_or_constructor_function_index(int value);
5141 // Count of properties allocated in the object (JSObject only).
5142 inline int GetInObjectProperties();
5143 inline void SetInObjectProperties(int value);
5144 // Index of the constructor function in the native context (primitives only),
5145 // or the special sentinel value to indicate that there is no object wrapper
5146 // for the primitive (i.e. in case of null or undefined).
5147 static const int kNoConstructorFunctionIndex = 0;
5148 inline int GetConstructorFunctionIndex();
5149 inline void SetConstructorFunctionIndex(int value);
5152 inline InstanceType instance_type();
5153 inline void set_instance_type(InstanceType value);
5155 // Tells how many unused property fields are available in the
5156 // instance (only used for JSObject in fast mode).
5157 inline int unused_property_fields();
5158 inline void set_unused_property_fields(int value);
5161 inline byte bit_field() const;
5162 inline void set_bit_field(byte value);
5165 inline byte bit_field2() const;
5166 inline void set_bit_field2(byte value);
5169 inline uint32_t bit_field3() const;
5170 inline void set_bit_field3(uint32_t bits);
5172 class EnumLengthBits: public BitField<int,
5173 0, kDescriptorIndexBitCount> {}; // NOLINT
5174 class NumberOfOwnDescriptorsBits: public BitField<int,
5175 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5176 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5177 class DictionaryMap : public BitField<bool, 20, 1> {};
5178 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5179 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5180 class Deprecated : public BitField<bool, 23, 1> {};
5181 class IsUnstable : public BitField<bool, 24, 1> {};
5182 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5183 class IsStrong : public BitField<bool, 26, 1> {};
5186 // Keep this bit field at the very end for better code in
5187 // Builtins::kJSConstructStubGeneric stub.
5188 // This counter is used for in-object slack tracking and for map aging.
5189 // The in-object slack tracking is considered enabled when the counter is
5190 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5191 class Counter : public BitField<int, 28, 4> {};
5192 static const int kSlackTrackingCounterStart = 14;
5193 static const int kSlackTrackingCounterEnd = 8;
5194 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5195 static const int kRetainingCounterEnd = 0;
5197 // Tells whether the object in the prototype property will be used
5198 // for instances created from this function. If the prototype
5199 // property is set to a value that is not a JSObject, the prototype
5200 // property will not be used to create instances of the function.
5201 // See ECMA-262, 13.2.2.
5202 inline void set_non_instance_prototype(bool value);
5203 inline bool has_non_instance_prototype();
5205 // Tells whether function has special prototype property. If not, prototype
5206 // property will not be created when accessed (will return undefined),
5207 // and construction from this function will not be allowed.
5208 inline void set_function_with_prototype(bool value);
5209 inline bool function_with_prototype();
5211 // Tells whether the instance with this map should be ignored by the
5212 // Object.getPrototypeOf() function and the __proto__ accessor.
5213 inline void set_is_hidden_prototype();
5214 inline bool is_hidden_prototype();
5216 // Records and queries whether the instance has a named interceptor.
5217 inline void set_has_named_interceptor();
5218 inline bool has_named_interceptor();
5220 // Records and queries whether the instance has an indexed interceptor.
5221 inline void set_has_indexed_interceptor();
5222 inline bool has_indexed_interceptor();
5224 // Tells whether the instance is undetectable.
5225 // An undetectable object is a special class of JSObject: 'typeof' operator
5226 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5227 // a normal JS object. It is useful for implementing undetectable
5228 // document.all in Firefox & Safari.
5229 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5230 inline void set_is_undetectable();
5231 inline bool is_undetectable();
5233 // Tells whether the instance has a call-as-function handler.
5234 inline void set_is_observed();
5235 inline bool is_observed();
5237 inline void set_is_strong();
5238 inline bool is_strong();
5239 inline void set_is_extensible(bool value);
5240 inline bool is_extensible();
5241 inline void set_is_prototype_map(bool value);
5242 inline bool is_prototype_map() const;
5244 inline void set_elements_kind(ElementsKind elements_kind);
5245 inline ElementsKind elements_kind();
5247 // Tells whether the instance has fast elements that are only Smis.
5248 inline bool has_fast_smi_elements();
5250 // Tells whether the instance has fast elements.
5251 inline bool has_fast_object_elements();
5252 inline bool has_fast_smi_or_object_elements();
5253 inline bool has_fast_double_elements();
5254 inline bool has_fast_elements();
5255 inline bool has_sloppy_arguments_elements();
5256 inline bool has_fixed_typed_array_elements();
5257 inline bool has_dictionary_elements();
5259 static bool IsValidElementsTransition(ElementsKind from_kind,
5260 ElementsKind to_kind);
5262 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5263 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5264 bool DictionaryElementsInPrototypeChainOnly();
5266 inline Map* ElementsTransitionMap();
5268 inline FixedArrayBase* GetInitialElements();
5270 // [raw_transitions]: Provides access to the transitions storage field.
5271 // Don't call set_raw_transitions() directly to overwrite transitions, use
5272 // the TransitionArray::ReplaceTransitions() wrapper instead!
5273 DECL_ACCESSORS(raw_transitions, Object)
5274 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5275 // (which prototype maps don't have).
5276 DECL_ACCESSORS(prototype_info, Object)
5277 // PrototypeInfo is created lazily using this helper (which installs it on
5278 // the given prototype's map).
5279 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5280 Handle<JSObject> prototype, Isolate* isolate);
5281 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5282 Handle<Map> prototype_map, Isolate* isolate);
5284 // [prototype chain validity cell]: Associated with a prototype object,
5285 // stored in that object's map's PrototypeInfo, indicates that prototype
5286 // chains through this object are currently valid. The cell will be
5287 // invalidated and replaced when the prototype chain changes.
5288 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5290 static const int kPrototypeChainValid = 0;
5291 static const int kPrototypeChainInvalid = 1;
5294 Map* FindFieldOwner(int descriptor);
5296 inline int GetInObjectPropertyOffset(int index);
5298 int NumberOfFields();
5300 // TODO(ishell): candidate with JSObject::MigrateToMap().
5301 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5302 int target_inobject, int target_unused,
5303 int* old_number_of_fields);
5304 // TODO(ishell): moveit!
5305 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5306 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5307 Handle<HeapType> type1,
5308 Handle<HeapType> type2,
5310 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5311 Representation new_representation,
5312 Handle<HeapType> new_field_type);
5313 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5314 PropertyKind new_kind,
5315 PropertyAttributes new_attributes,
5316 Representation new_representation,
5317 Handle<HeapType> new_field_type,
5318 StoreMode store_mode);
5319 static Handle<Map> CopyGeneralizeAllRepresentations(
5320 Handle<Map> map, int modify_index, StoreMode store_mode,
5321 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5323 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5324 int descriptor_number,
5325 Handle<Object> value);
5327 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5328 const char* reason);
5330 // Returns the constructor name (the name (possibly, inferred name) of the
5331 // function that was used to instantiate the object).
5332 String* constructor_name();
5334 // Tells whether the map is used for JSObjects in dictionary mode (ie
5335 // normalized objects, ie objects for which HasFastProperties returns false).
5336 // A map can never be used for both dictionary mode and fast mode JSObjects.
5337 // False by default and for HeapObjects that are not JSObjects.
5338 inline void set_dictionary_map(bool value);
5339 inline bool is_dictionary_map();
5341 // Tells whether the instance needs security checks when accessing its
5343 inline void set_is_access_check_needed(bool access_check_needed);
5344 inline bool is_access_check_needed();
5346 // Returns true if map has a non-empty stub code cache.
5347 inline bool has_code_cache();
5349 // [prototype]: implicit prototype object.
5350 DECL_ACCESSORS(prototype, Object)
5351 // TODO(jkummerow): make set_prototype private.
5352 static void SetPrototype(
5353 Handle<Map> map, Handle<Object> prototype,
5354 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5356 // [constructor]: points back to the function responsible for this map.
5357 // The field overlaps with the back pointer. All maps in a transition tree
5358 // have the same constructor, so maps with back pointers can walk the
5359 // back pointer chain until they find the map holding their constructor.
5360 DECL_ACCESSORS(constructor_or_backpointer, Object)
5361 inline Object* GetConstructor() const;
5362 inline void SetConstructor(Object* constructor,
5363 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5364 // [back pointer]: points back to the parent map from which a transition
5365 // leads to this map. The field overlaps with the constructor (see above).
5366 inline Object* GetBackPointer();
5367 inline void SetBackPointer(Object* value,
5368 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5370 // [instance descriptors]: describes the object.
5371 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5373 // [layout descriptor]: describes the object layout.
5374 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5375 // |layout descriptor| accessor which can be used from GC.
5376 inline LayoutDescriptor* layout_descriptor_gc_safe();
5377 inline bool HasFastPointerLayout() const;
5379 // |layout descriptor| accessor that is safe to call even when
5380 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5381 // |layout_descriptor| field at all).
5382 inline LayoutDescriptor* GetLayoutDescriptor();
5384 inline void UpdateDescriptors(DescriptorArray* descriptors,
5385 LayoutDescriptor* layout_descriptor);
5386 inline void InitializeDescriptors(DescriptorArray* descriptors,
5387 LayoutDescriptor* layout_descriptor);
5389 // [stub cache]: contains stubs compiled for this map.
5390 DECL_ACCESSORS(code_cache, Object)
5392 // [dependent code]: list of optimized codes that weakly embed this map.
5393 DECL_ACCESSORS(dependent_code, DependentCode)
5395 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5396 DECL_ACCESSORS(weak_cell_cache, Object)
5398 inline PropertyDetails GetLastDescriptorDetails();
5400 inline int LastAdded();
5402 inline int NumberOfOwnDescriptors();
5403 inline void SetNumberOfOwnDescriptors(int number);
5405 inline Cell* RetrieveDescriptorsPointer();
5407 inline int EnumLength();
5408 inline void SetEnumLength(int length);
5410 inline bool owns_descriptors();
5411 inline void set_owns_descriptors(bool owns_descriptors);
5412 inline bool has_instance_call_handler();
5413 inline void set_has_instance_call_handler();
5414 inline void mark_unstable();
5415 inline bool is_stable();
5416 inline void set_migration_target(bool value);
5417 inline bool is_migration_target();
5418 inline void set_counter(int value);
5419 inline int counter();
5420 inline void deprecate();
5421 inline bool is_deprecated();
5422 inline bool CanBeDeprecated();
5423 // Returns a non-deprecated version of the input. If the input was not
5424 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5425 // is found by re-transitioning from the root of the transition tree using the
5426 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5428 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5430 // Returns a non-deprecated version of the input. This method may deprecate
5431 // existing maps along the way if encodings conflict. Not for use while
5432 // gathering type feedback. Use TryUpdate in those cases instead.
5433 static Handle<Map> Update(Handle<Map> map);
5435 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5436 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5437 Descriptor* descriptor,
5438 TransitionFlag flag);
5440 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5443 Handle<HeapType> type,
5444 PropertyAttributes attributes,
5445 Representation representation,
5446 TransitionFlag flag);
5448 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5451 Handle<Object> constant,
5452 PropertyAttributes attributes,
5453 TransitionFlag flag);
5455 // Returns a new map with all transitions dropped from the given map and
5456 // the ElementsKind set.
5457 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5458 ElementsKind to_kind);
5460 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5462 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5464 TransitionFlag flag);
5466 static Handle<Map> CopyForObserved(Handle<Map> map);
5468 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5469 PropertyAttributes attrs_to_add,
5470 Handle<Symbol> transition_marker,
5471 const char* reason);
5473 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5476 // Maximal number of fast properties. Used to restrict the number of map
5477 // transitions to avoid an explosion in the number of maps for objects used as
5479 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5480 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5482 Handle<Object> value,
5483 PropertyAttributes attributes,
5484 StoreFromKeyed store_mode);
5485 static Handle<Map> TransitionToAccessorProperty(
5486 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5487 Handle<Object> accessor, PropertyAttributes attributes);
5488 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5491 PropertyAttributes attributes);
5493 inline void AppendDescriptor(Descriptor* desc);
5495 // Returns a copy of the map, prepared for inserting into the transition
5496 // tree (if the |map| owns descriptors then the new one will share
5497 // descriptors with |map|).
5498 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5500 // Returns a copy of the map, with all transitions dropped from the
5501 // instance descriptors.
5502 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5503 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5505 // Returns the next free property index (only valid for FAST MODE).
5506 int NextFreePropertyIndex();
5508 // Returns the number of properties described in instance_descriptors
5509 // filtering out properties with the specified attributes.
5510 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5511 PropertyAttributes filter = NONE);
5515 // Code cache operations.
5517 // Clears the code cache.
5518 inline void ClearCodeCache(Heap* heap);
5520 // Update code cache.
5521 static void UpdateCodeCache(Handle<Map> map,
5525 // Extend the descriptor array of the map with the list of descriptors.
5526 // In case of duplicates, the latest descriptor is used.
5527 static void AppendCallbackDescriptors(Handle<Map> map,
5528 Handle<Object> descriptors);
5530 static inline int SlackForArraySize(int old_size, int size_limit);
5532 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5534 // Returns the found code or undefined if absent.
5535 Object* FindInCodeCache(Name* name, Code::Flags flags);
5537 // Returns the non-negative index of the code object if it is in the
5538 // cache and -1 otherwise.
5539 int IndexInCodeCache(Object* name, Code* code);
5541 // Removes a code object from the code cache at the given index.
5542 void RemoveFromCodeCache(Name* name, Code* code, int index);
5544 // Computes a hash value for this map, to be used in HashTables and such.
5547 // Returns the map that this map transitions to if its elements_kind
5548 // is changed to |elements_kind|, or NULL if no such map is cached yet.
5549 // |safe_to_add_transitions| is set to false if adding transitions is not
5551 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
5553 // Returns the transitioned map for this map with the most generic
5554 // elements_kind that's found in |candidates|, or null handle if no match is
5556 static Handle<Map> FindTransitionedMap(Handle<Map> map,
5557 MapHandleList* candidates);
5559 inline bool CanTransition();
5561 inline bool IsPrimitiveMap();
5562 inline bool IsJSObjectMap();
5563 inline bool IsJSArrayMap();
5564 inline bool IsStringMap();
5565 inline bool IsJSProxyMap();
5566 inline bool IsJSGlobalProxyMap();
5567 inline bool IsJSGlobalObjectMap();
5568 inline bool IsGlobalObjectMap();
5570 inline bool CanOmitMapChecks();
5572 static void AddDependentCode(Handle<Map> map,
5573 DependentCode::DependencyGroup group,
5576 bool IsMapInArrayPrototypeChain();
5578 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
5580 // Dispatched behavior.
5581 DECLARE_PRINTER(Map)
5582 DECLARE_VERIFIER(Map)
5585 void DictionaryMapVerify();
5586 void VerifyOmittedMapChecks();
5589 inline int visitor_id();
5590 inline void set_visitor_id(int visitor_id);
5592 static Handle<Map> TransitionToPrototype(Handle<Map> map,
5593 Handle<Object> prototype,
5594 PrototypeOptimizationMode mode);
5596 static const int kMaxPreAllocatedPropertyFields = 255;
5598 // Layout description.
5599 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
5600 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
5601 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
5602 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
5603 static const int kConstructorOrBackPointerOffset =
5604 kPrototypeOffset + kPointerSize;
5605 // When there is only one transition, it is stored directly in this field;
5606 // otherwise a transition array is used.
5607 // For prototype maps, this slot is used to store this map's PrototypeInfo
5609 static const int kTransitionsOrPrototypeInfoOffset =
5610 kConstructorOrBackPointerOffset + kPointerSize;
5611 static const int kDescriptorsOffset =
5612 kTransitionsOrPrototypeInfoOffset + kPointerSize;
5613 #if V8_DOUBLE_FIELDS_UNBOXING
5614 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
5615 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
5617 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
5618 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
5620 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
5621 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
5622 static const int kSize = kWeakCellCacheOffset + kPointerSize;
5624 // Layout of pointer fields. Heap iteration code relies on them
5625 // being continuously allocated.
5626 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
5627 static const int kPointerFieldsEndOffset = kSize;
5629 // Byte offsets within kInstanceSizesOffset.
5630 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
5631 static const int kInObjectPropertiesOrConstructorFunctionIndexByte = 1;
5632 static const int kInObjectPropertiesOrConstructorFunctionIndexOffset =
5633 kInstanceSizesOffset + kInObjectPropertiesOrConstructorFunctionIndexByte;
5634 // Note there is one byte available for use here.
5635 static const int kUnusedByte = 2;
5636 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
5637 static const int kVisitorIdByte = 3;
5638 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
5640 // Byte offsets within kInstanceAttributesOffset attributes.
5641 #if V8_TARGET_LITTLE_ENDIAN
5642 // Order instance type and bit field together such that they can be loaded
5643 // together as a 16-bit word with instance type in the lower 8 bits regardless
5644 // of endianess. Also provide endian-independent offset to that 16-bit word.
5645 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
5646 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
5648 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
5649 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
5651 static const int kInstanceTypeAndBitFieldOffset =
5652 kInstanceAttributesOffset + 0;
5653 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
5654 static const int kUnusedPropertyFieldsByte = 3;
5655 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
5657 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
5658 Internals::kMapInstanceTypeAndBitFieldOffset);
5660 // Bit positions for bit field.
5661 static const int kHasNonInstancePrototype = 0;
5662 static const int kIsHiddenPrototype = 1;
5663 static const int kHasNamedInterceptor = 2;
5664 static const int kHasIndexedInterceptor = 3;
5665 static const int kIsUndetectable = 4;
5666 static const int kIsObserved = 5;
5667 static const int kIsAccessCheckNeeded = 6;
5668 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
5670 // Bit positions for bit field 2
5671 static const int kIsExtensible = 0;
5672 static const int kStringWrapperSafeForDefaultValueOf = 1;
5673 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
5674 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
5676 // Derived values from bit field 2
5677 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
5678 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
5679 static const int8_t kMaximumBitField2FastSmiElementValue =
5680 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
5681 Map::ElementsKindBits::kShift) - 1;
5682 static const int8_t kMaximumBitField2FastHoleyElementValue =
5683 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
5684 Map::ElementsKindBits::kShift) - 1;
5685 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
5686 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
5687 Map::ElementsKindBits::kShift) - 1;
5689 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
5690 kPointerFieldsEndOffset,
5691 kSize> BodyDescriptor;
5693 // Compares this map to another to see if they describe equivalent objects.
5694 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
5695 // it had exactly zero inobject properties.
5696 // The "shared" flags of both this map and |other| are ignored.
5697 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
5699 // Returns true if given field is unboxed double.
5700 inline bool IsUnboxedDoubleField(FieldIndex index);
5703 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
5704 static void TraceAllTransitions(Map* map);
5707 static inline Handle<Map> CopyInstallDescriptorsForTesting(
5708 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5709 Handle<LayoutDescriptor> layout_descriptor);
5712 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
5713 Handle<Name> name, SimpleTransitionFlag flag);
5715 bool EquivalentToForTransition(Map* other);
5716 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
5717 static Handle<Map> ShareDescriptor(Handle<Map> map,
5718 Handle<DescriptorArray> descriptors,
5719 Descriptor* descriptor);
5720 static Handle<Map> CopyInstallDescriptors(
5721 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
5722 Handle<LayoutDescriptor> layout_descriptor);
5723 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
5724 Descriptor* descriptor,
5725 TransitionFlag flag);
5726 static Handle<Map> CopyReplaceDescriptors(
5727 Handle<Map> map, Handle<DescriptorArray> descriptors,
5728 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
5729 MaybeHandle<Name> maybe_name, const char* reason,
5730 SimpleTransitionFlag simple_flag);
5732 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
5733 Handle<DescriptorArray> descriptors,
5734 Descriptor* descriptor,
5736 TransitionFlag flag);
5737 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
5738 Handle<Map> map, int descriptor, PropertyKind kind,
5739 PropertyAttributes attributes, const char** reason);
5741 static Handle<Map> CopyNormalized(Handle<Map> map,
5742 PropertyNormalizationMode mode);
5744 // Fires when the layout of an object with a leaf map changes.
5745 // This includes adding transitions to the leaf map or changing
5746 // the descriptor array.
5747 inline void NotifyLeafMapLayoutChange();
5749 void DeprecateTransitionTree();
5750 bool DeprecateTarget(PropertyKind kind, Name* key,
5751 PropertyAttributes attributes,
5752 DescriptorArray* new_descriptors,
5753 LayoutDescriptor* new_layout_descriptor);
5755 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
5757 // Update field type of the given descriptor to new representation and new
5758 // type. The type must be prepared for storing in descriptor array:
5759 // it must be either a simple type or a map wrapped in a weak cell.
5760 void UpdateFieldType(int descriptor_number, Handle<Name> name,
5761 Representation new_representation,
5762 Handle<Object> new_wrapped_type);
5764 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
5765 PropertyAttributes attributes);
5766 void PrintGeneralization(FILE* file,
5771 bool constant_to_field,
5772 Representation old_representation,
5773 Representation new_representation,
5774 HeapType* old_field_type,
5775 HeapType* new_field_type);
5777 static const int kFastPropertiesSoftLimit = 12;
5778 static const int kMaxFastProperties = 128;
5780 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
5784 // An abstract superclass, a marker class really, for simple structure classes.
5785 // It doesn't carry much functionality but allows struct classes to be
5786 // identified in the type system.
5787 class Struct: public HeapObject {
5789 inline void InitializeBody(int object_size);
5790 DECLARE_CAST(Struct)
5794 // A simple one-element struct, useful where smis need to be boxed.
5795 class Box : public Struct {
5797 // [value]: the boxed contents.
5798 DECL_ACCESSORS(value, Object)
5802 // Dispatched behavior.
5803 DECLARE_PRINTER(Box)
5804 DECLARE_VERIFIER(Box)
5806 static const int kValueOffset = HeapObject::kHeaderSize;
5807 static const int kSize = kValueOffset + kPointerSize;
5810 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
5814 // Container for metadata stored on each prototype map.
5815 class PrototypeInfo : public Struct {
5817 static const int UNREGISTERED = -1;
5819 // [prototype_users]: WeakFixedArray containing maps using this prototype,
5820 // or Smi(0) if uninitialized.
5821 DECL_ACCESSORS(prototype_users, Object)
5822 // [registry_slot]: Slot in prototype's user registry where this user
5823 // is stored. Returns UNREGISTERED if this prototype has not been registered.
5824 inline int registry_slot() const;
5825 inline void set_registry_slot(int slot);
5826 // [validity_cell]: Cell containing the validity bit for prototype chains
5827 // going through this object, or Smi(0) if uninitialized.
5828 DECL_ACCESSORS(validity_cell, Object)
5829 // [constructor_name]: User-friendly name of the original constructor.
5830 DECL_ACCESSORS(constructor_name, Object)
5832 DECLARE_CAST(PrototypeInfo)
5834 // Dispatched behavior.
5835 DECLARE_PRINTER(PrototypeInfo)
5836 DECLARE_VERIFIER(PrototypeInfo)
5838 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
5839 static const int kRegistrySlotOffset = kPrototypeUsersOffset + kPointerSize;
5840 static const int kValidityCellOffset = kRegistrySlotOffset + kPointerSize;
5841 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
5842 static const int kSize = kConstructorNameOffset + kPointerSize;
5845 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
5849 // Pair used to store both a ScopeInfo and an extension object in the extension
5850 // slot of a block context. Needed in the rare case where a declaration block
5851 // scope (a "varblock" as used to desugar parameter destructuring) also contains
5852 // a sloppy direct eval. (In no other case both are needed at the same time.)
5853 class SloppyBlockWithEvalContextExtension : public Struct {
5855 // [scope_info]: Scope info.
5856 DECL_ACCESSORS(scope_info, ScopeInfo)
5857 // [extension]: Extension object.
5858 DECL_ACCESSORS(extension, JSObject)
5860 DECLARE_CAST(SloppyBlockWithEvalContextExtension)
5862 // Dispatched behavior.
5863 DECLARE_PRINTER(SloppyBlockWithEvalContextExtension)
5864 DECLARE_VERIFIER(SloppyBlockWithEvalContextExtension)
5866 static const int kScopeInfoOffset = HeapObject::kHeaderSize;
5867 static const int kExtensionOffset = kScopeInfoOffset + kPointerSize;
5868 static const int kSize = kExtensionOffset + kPointerSize;
5871 DISALLOW_IMPLICIT_CONSTRUCTORS(SloppyBlockWithEvalContextExtension);
5875 // Script describes a script which has been added to the VM.
5876 class Script: public Struct {
5885 // Script compilation types.
5886 enum CompilationType {
5887 COMPILATION_TYPE_HOST = 0,
5888 COMPILATION_TYPE_EVAL = 1
5891 // Script compilation state.
5892 enum CompilationState {
5893 COMPILATION_STATE_INITIAL = 0,
5894 COMPILATION_STATE_COMPILED = 1
5897 // [source]: the script source.
5898 DECL_ACCESSORS(source, Object)
5900 // [name]: the script name.
5901 DECL_ACCESSORS(name, Object)
5903 // [id]: the script id.
5904 DECL_ACCESSORS(id, Smi)
5906 // [line_offset]: script line offset in resource from where it was extracted.
5907 DECL_ACCESSORS(line_offset, Smi)
5909 // [column_offset]: script column offset in resource from where it was
5911 DECL_ACCESSORS(column_offset, Smi)
5913 // [context_data]: context data for the context this script was compiled in.
5914 DECL_ACCESSORS(context_data, Object)
5916 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
5917 DECL_ACCESSORS(wrapper, HeapObject)
5919 // [type]: the script type.
5920 DECL_ACCESSORS(type, Smi)
5922 // [line_ends]: FixedArray of line ends positions.
5923 DECL_ACCESSORS(line_ends, Object)
5925 // [eval_from_shared]: for eval scripts the shared funcion info for the
5926 // function from which eval was called.
5927 DECL_ACCESSORS(eval_from_shared, Object)
5929 // [eval_from_instructions_offset]: the instruction offset in the code for the
5930 // function from which eval was called where eval was called.
5931 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5933 // [shared_function_infos]: weak fixed array containing all shared
5934 // function infos created from this script.
5935 DECL_ACCESSORS(shared_function_infos, Object)
5937 // [flags]: Holds an exciting bitfield.
5938 DECL_ACCESSORS(flags, Smi)
5940 // [source_url]: sourceURL from magic comment
5941 DECL_ACCESSORS(source_url, Object)
5943 // [source_url]: sourceMappingURL magic comment
5944 DECL_ACCESSORS(source_mapping_url, Object)
5946 // [compilation_type]: how the the script was compiled. Encoded in the
5948 inline CompilationType compilation_type();
5949 inline void set_compilation_type(CompilationType type);
5951 // [compilation_state]: determines whether the script has already been
5952 // compiled. Encoded in the 'flags' field.
5953 inline CompilationState compilation_state();
5954 inline void set_compilation_state(CompilationState state);
5956 // [hide_source]: determines whether the script source can be exposed as
5957 // function source. Encoded in the 'flags' field.
5958 inline bool hide_source();
5959 inline void set_hide_source(bool value);
5961 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
5962 // and used by the embedder to make decisions about the script. V8 just passes
5963 // this through. Encoded in the 'flags' field.
5964 inline v8::ScriptOriginOptions origin_options();
5965 inline void set_origin_options(ScriptOriginOptions origin_options);
5967 DECLARE_CAST(Script)
5969 // If script source is an external string, check that the underlying
5970 // resource is accessible. Otherwise, always return true.
5971 inline bool HasValidSource();
5973 // Convert code position into column number.
5974 static int GetColumnNumber(Handle<Script> script, int code_pos);
5976 // Convert code position into (zero-based) line number.
5977 // The non-handlified version does not allocate, but may be much slower.
5978 static int GetLineNumber(Handle<Script> script, int code_pos);
5979 int GetLineNumber(int code_pos);
5981 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
5983 // Init line_ends array with code positions of line ends inside script source.
5984 static void InitLineEnds(Handle<Script> script);
5986 // Get the JS object wrapping the given script; create it if none exists.
5987 static Handle<JSObject> GetWrapper(Handle<Script> script);
5989 // Look through the list of existing shared function infos to find one
5990 // that matches the function literal. Return empty handle if not found.
5991 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
5993 // Iterate over all script objects on the heap.
5996 explicit Iterator(Isolate* isolate);
6000 WeakFixedArray::Iterator iterator_;
6001 DISALLOW_COPY_AND_ASSIGN(Iterator);
6004 // Dispatched behavior.
6005 DECLARE_PRINTER(Script)
6006 DECLARE_VERIFIER(Script)
6008 static const int kSourceOffset = HeapObject::kHeaderSize;
6009 static const int kNameOffset = kSourceOffset + kPointerSize;
6010 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6011 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6012 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6013 static const int kWrapperOffset = kContextOffset + kPointerSize;
6014 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6015 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6016 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6017 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6018 static const int kEvalFrominstructionsOffsetOffset =
6019 kEvalFromSharedOffset + kPointerSize;
6020 static const int kSharedFunctionInfosOffset =
6021 kEvalFrominstructionsOffsetOffset + kPointerSize;
6022 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6023 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6024 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6025 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6028 int GetLineNumberWithArray(int code_pos);
6030 // Bit positions in the flags field.
6031 static const int kCompilationTypeBit = 0;
6032 static const int kCompilationStateBit = 1;
6033 static const int kHideSourceBit = 2;
6034 static const int kOriginOptionsShift = 3;
6035 static const int kOriginOptionsSize = 3;
6036 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6037 << kOriginOptionsShift;
6039 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6043 // List of builtin functions we want to identify to improve code
6046 // Each entry has a name of a global object property holding an object
6047 // optionally followed by ".prototype", a name of a builtin function
6048 // on the object (the one the id is set for), and a label.
6050 // Installation of ids for the selected builtin functions is handled
6051 // by the bootstrapper.
6052 #define FUNCTIONS_WITH_ID_LIST(V) \
6053 V(Array.prototype, indexOf, ArrayIndexOf) \
6054 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6055 V(Array.prototype, push, ArrayPush) \
6056 V(Array.prototype, pop, ArrayPop) \
6057 V(Array.prototype, shift, ArrayShift) \
6058 V(Function.prototype, apply, FunctionApply) \
6059 V(Function.prototype, call, FunctionCall) \
6060 V(String.prototype, charCodeAt, StringCharCodeAt) \
6061 V(String.prototype, charAt, StringCharAt) \
6062 V(String, fromCharCode, StringFromCharCode) \
6063 V(Math, random, MathRandom) \
6064 V(Math, floor, MathFloor) \
6065 V(Math, round, MathRound) \
6066 V(Math, ceil, MathCeil) \
6067 V(Math, abs, MathAbs) \
6068 V(Math, log, MathLog) \
6069 V(Math, exp, MathExp) \
6070 V(Math, sqrt, MathSqrt) \
6071 V(Math, pow, MathPow) \
6072 V(Math, max, MathMax) \
6073 V(Math, min, MathMin) \
6074 V(Math, cos, MathCos) \
6075 V(Math, sin, MathSin) \
6076 V(Math, tan, MathTan) \
6077 V(Math, acos, MathAcos) \
6078 V(Math, asin, MathAsin) \
6079 V(Math, atan, MathAtan) \
6080 V(Math, atan2, MathAtan2) \
6081 V(Math, imul, MathImul) \
6082 V(Math, clz32, MathClz32) \
6083 V(Math, fround, MathFround)
6085 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6086 V(Atomics, load, AtomicsLoad) \
6087 V(Atomics, store, AtomicsStore)
6089 enum BuiltinFunctionId {
6091 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6093 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6094 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6095 #undef DECLARE_FUNCTION_ID
6096 // Fake id for a special case of Math.pow. Note, it continues the
6097 // list of math functions.
6102 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6103 // that both {code} and {literals} can be NULL to pass search result status.
6104 struct CodeAndLiterals {
6105 Code* code; // Cached optimized code.
6106 FixedArray* literals; // Cached literals array.
6110 // SharedFunctionInfo describes the JSFunction information that can be
6111 // shared by multiple instances of the function.
6112 class SharedFunctionInfo: public HeapObject {
6114 // [name]: Function name.
6115 DECL_ACCESSORS(name, Object)
6117 // [code]: Function code.
6118 DECL_ACCESSORS(code, Code)
6119 inline void ReplaceCode(Code* code);
6121 // [optimized_code_map]: Map from native context to optimized code
6122 // and a shared literals array or Smi(0) if none.
6123 DECL_ACCESSORS(optimized_code_map, Object)
6125 // Returns entry from optimized code map for specified context and OSR entry.
6126 // Note that {code == nullptr} indicates no matching entry has been found,
6127 // whereas {literals == nullptr} indicates the code is context-independent.
6128 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6129 BailoutId osr_ast_id);
6131 // Clear optimized code map.
6132 void ClearOptimizedCodeMap();
6134 // Removed a specific optimized code object from the optimized code map.
6135 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6137 // Trims the optimized code map after entries have been removed.
6138 void TrimOptimizedCodeMap(int shrink_by);
6140 // Add a new entry to the optimized code map for context-independent code.
6141 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6144 // Add a new entry to the optimized code map for context-dependent code.
6145 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6146 Handle<Context> native_context,
6148 Handle<FixedArray> literals,
6149 BailoutId osr_ast_id);
6151 // Set up the link between shared function info and the script. The shared
6152 // function info is added to the list on the script.
6153 static void SetScript(Handle<SharedFunctionInfo> shared,
6154 Handle<Object> script_object);
6156 // Layout description of the optimized code map.
6157 static const int kNextMapIndex = 0;
6158 static const int kSharedCodeIndex = 1;
6159 static const int kEntriesStart = 2;
6160 static const int kContextOffset = 0;
6161 static const int kCachedCodeOffset = 1;
6162 static const int kLiteralsOffset = 2;
6163 static const int kOsrAstIdOffset = 3;
6164 static const int kEntryLength = 4;
6165 static const int kInitialLength = kEntriesStart + kEntryLength;
6167 // [scope_info]: Scope info.
6168 DECL_ACCESSORS(scope_info, ScopeInfo)
6170 // [construct stub]: Code stub for constructing instances of this function.
6171 DECL_ACCESSORS(construct_stub, Code)
6173 // Returns if this function has been compiled to native code yet.
6174 inline bool is_compiled();
6176 // [length]: The function length - usually the number of declared parameters.
6177 // Use up to 2^30 parameters.
6178 inline int length() const;
6179 inline void set_length(int value);
6181 // [internal formal parameter count]: The declared number of parameters.
6182 // For subclass constructors, also includes new.target.
6183 // The size of function's frame is internal_formal_parameter_count + 1.
6184 inline int internal_formal_parameter_count() const;
6185 inline void set_internal_formal_parameter_count(int value);
6187 // Set the formal parameter count so the function code will be
6188 // called without using argument adaptor frames.
6189 inline void DontAdaptArguments();
6191 // [expected_nof_properties]: Expected number of properties for the function.
6192 inline int expected_nof_properties() const;
6193 inline void set_expected_nof_properties(int value);
6195 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6196 // (increasingly) from crankshafted code where sufficient feedback isn't
6198 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6200 // Unconditionally clear the type feedback vector (including vector ICs).
6201 void ClearTypeFeedbackInfo();
6203 // Clear the type feedback vector with a more subtle policy at GC time.
6204 void ClearTypeFeedbackInfoAtGCTime();
6207 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6208 // even if the GC moves this SharedFunctionInfo.
6209 inline int unique_id() const;
6210 inline void set_unique_id(int value);
6213 // [instance class name]: class name for instances.
6214 DECL_ACCESSORS(instance_class_name, Object)
6216 // [function data]: This field holds some additional data for function.
6217 // Currently it has one of:
6218 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6219 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6220 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6221 // In the long run we don't want all functions to have this field but
6222 // we can fix that when we have a better model for storing hidden data
6224 DECL_ACCESSORS(function_data, Object)
6226 inline bool IsApiFunction();
6227 inline FunctionTemplateInfo* get_api_func_data();
6228 inline bool HasBuiltinFunctionId();
6229 inline BuiltinFunctionId builtin_function_id();
6230 inline bool HasBytecodeArray();
6231 inline BytecodeArray* bytecode_array();
6233 // [script info]: Script from which the function originates.
6234 DECL_ACCESSORS(script, Object)
6236 // [num_literals]: Number of literals used by this function.
6237 inline int num_literals() const;
6238 inline void set_num_literals(int value);
6240 // [start_position_and_type]: Field used to store both the source code
6241 // position, whether or not the function is a function expression,
6242 // and whether or not the function is a toplevel function. The two
6243 // least significants bit indicates whether the function is an
6244 // expression and the rest contains the source code position.
6245 inline int start_position_and_type() const;
6246 inline void set_start_position_and_type(int value);
6248 // The function is subject to debugging if a debug info is attached.
6249 inline bool HasDebugInfo();
6250 inline DebugInfo* GetDebugInfo();
6252 // A function has debug code if the compiled code has debug break slots.
6253 inline bool HasDebugCode();
6255 // [debug info]: Debug information.
6256 DECL_ACCESSORS(debug_info, Object)
6258 // [inferred name]: Name inferred from variable or property
6259 // assignment of this function. Used to facilitate debugging and
6260 // profiling of JavaScript code written in OO style, where almost
6261 // all functions are anonymous but are assigned to object
6263 DECL_ACCESSORS(inferred_name, String)
6265 // The function's name if it is non-empty, otherwise the inferred name.
6266 String* DebugName();
6268 // Position of the 'function' token in the script source.
6269 inline int function_token_position() const;
6270 inline void set_function_token_position(int function_token_position);
6272 // Position of this function in the script source.
6273 inline int start_position() const;
6274 inline void set_start_position(int start_position);
6276 // End position of this function in the script source.
6277 inline int end_position() const;
6278 inline void set_end_position(int end_position);
6280 // Is this function a function expression in the source code.
6281 DECL_BOOLEAN_ACCESSORS(is_expression)
6283 // Is this function a top-level function (scripts, evals).
6284 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6286 // Bit field containing various information collected by the compiler to
6287 // drive optimization.
6288 inline int compiler_hints() const;
6289 inline void set_compiler_hints(int value);
6291 inline int ast_node_count() const;
6292 inline void set_ast_node_count(int count);
6294 inline int profiler_ticks() const;
6295 inline void set_profiler_ticks(int ticks);
6297 // Inline cache age is used to infer whether the function survived a context
6298 // disposal or not. In the former case we reset the opt_count.
6299 inline int ic_age();
6300 inline void set_ic_age(int age);
6302 // Indicates if this function can be lazy compiled.
6303 // This is used to determine if we can safely flush code from a function
6304 // when doing GC if we expect that the function will no longer be used.
6305 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6307 // Indicates if this function can be lazy compiled without a context.
6308 // This is used to determine if we can force compilation without reaching
6309 // the function through program execution but through other means (e.g. heap
6310 // iteration by the debugger).
6311 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6313 // Indicates whether optimizations have been disabled for this
6314 // shared function info. If a function is repeatedly optimized or if
6315 // we cannot optimize the function we disable optimization to avoid
6316 // spending time attempting to optimize it again.
6317 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6319 // Indicates the language mode.
6320 inline LanguageMode language_mode();
6321 inline void set_language_mode(LanguageMode language_mode);
6323 // False if the function definitely does not allocate an arguments object.
6324 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6326 // Indicates that this function uses a super property (or an eval that may
6327 // use a super property).
6328 // This is needed to set up the [[HomeObject]] on the function instance.
6329 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6331 // True if the function has any duplicated parameter names.
6332 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6334 // Indicates whether the function is a native function.
6335 // These needs special treatment in .call and .apply since
6336 // null passed as the receiver should not be translated to the
6338 DECL_BOOLEAN_ACCESSORS(native)
6340 // Indicate that this function should always be inlined in optimized code.
6341 DECL_BOOLEAN_ACCESSORS(force_inline)
6343 // Indicates that the function was created by the Function function.
6344 // Though it's anonymous, toString should treat it as if it had the name
6345 // "anonymous". We don't set the name itself so that the system does not
6346 // see a binding for it.
6347 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6349 // Indicates whether the function is a bound function created using
6350 // the bind function.
6351 DECL_BOOLEAN_ACCESSORS(bound)
6353 // Indicates that the function is anonymous (the name field can be set
6354 // through the API, which does not change this flag).
6355 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6357 // Is this a function or top-level/eval code.
6358 DECL_BOOLEAN_ACCESSORS(is_function)
6360 // Indicates that code for this function cannot be compiled with Crankshaft.
6361 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6363 // Indicates that code for this function cannot be flushed.
6364 DECL_BOOLEAN_ACCESSORS(dont_flush)
6366 // Indicates that this function is a generator.
6367 DECL_BOOLEAN_ACCESSORS(is_generator)
6369 // Indicates that this function is an arrow function.
6370 DECL_BOOLEAN_ACCESSORS(is_arrow)
6372 // Indicates that this function is a concise method.
6373 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6375 // Indicates that this function is an accessor (getter or setter).
6376 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6378 // Indicates that this function is a default constructor.
6379 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6381 // Indicates that this function is an asm function.
6382 DECL_BOOLEAN_ACCESSORS(asm_function)
6384 // Indicates that the the shared function info is deserialized from cache.
6385 DECL_BOOLEAN_ACCESSORS(deserialized)
6387 // Indicates that the the shared function info has never been compiled before.
6388 DECL_BOOLEAN_ACCESSORS(never_compiled)
6390 inline FunctionKind kind();
6391 inline void set_kind(FunctionKind kind);
6393 // Indicates whether or not the code in the shared function support
6395 inline bool has_deoptimization_support();
6397 // Enable deoptimization support through recompiled code.
6398 void EnableDeoptimizationSupport(Code* recompiled);
6400 // Disable (further) attempted optimization of all functions sharing this
6401 // shared function info.
6402 void DisableOptimization(BailoutReason reason);
6404 inline BailoutReason disable_optimization_reason();
6406 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6407 // code, returns whether it asserted (i.e., always true if assertions are
6409 bool VerifyBailoutId(BailoutId id);
6411 // [source code]: Source code for the function.
6412 bool HasSourceCode() const;
6413 Handle<Object> GetSourceCode();
6415 // Number of times the function was optimized.
6416 inline int opt_count();
6417 inline void set_opt_count(int opt_count);
6419 // Number of times the function was deoptimized.
6420 inline void set_deopt_count(int value);
6421 inline int deopt_count();
6422 inline void increment_deopt_count();
6424 // Number of time we tried to re-enable optimization after it
6425 // was disabled due to high number of deoptimizations.
6426 inline void set_opt_reenable_tries(int value);
6427 inline int opt_reenable_tries();
6429 inline void TryReenableOptimization();
6431 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6432 inline void set_counters(int value);
6433 inline int counters() const;
6435 // Stores opt_count and bailout_reason as bit-fields.
6436 inline void set_opt_count_and_bailout_reason(int value);
6437 inline int opt_count_and_bailout_reason() const;
6439 inline void set_disable_optimization_reason(BailoutReason reason);
6441 // Tells whether this function should be subject to debugging.
6442 inline bool IsSubjectToDebugging();
6444 // Whether this function is defined in native code or extensions.
6445 inline bool IsBuiltin();
6447 // Check whether or not this function is inlineable.
6448 bool IsInlineable();
6450 // Source size of this function.
6453 // Calculate the instance size.
6454 int CalculateInstanceSize();
6456 // Calculate the number of in-object properties.
6457 int CalculateInObjectProperties();
6459 inline bool has_simple_parameters();
6461 // Initialize a SharedFunctionInfo from a parsed function literal.
6462 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6463 FunctionLiteral* lit);
6465 // Dispatched behavior.
6466 DECLARE_PRINTER(SharedFunctionInfo)
6467 DECLARE_VERIFIER(SharedFunctionInfo)
6469 void ResetForNewContext(int new_ic_age);
6471 // Iterate over all shared function infos that are created from a script.
6472 // That excludes shared function infos created for API functions and C++
6476 explicit Iterator(Isolate* isolate);
6477 SharedFunctionInfo* Next();
6482 Script::Iterator script_iterator_;
6483 WeakFixedArray::Iterator sfi_iterator_;
6484 DisallowHeapAllocation no_gc_;
6485 DISALLOW_COPY_AND_ASSIGN(Iterator);
6488 DECLARE_CAST(SharedFunctionInfo)
6491 static const int kDontAdaptArgumentsSentinel = -1;
6493 // Layout description.
6495 static const int kNameOffset = HeapObject::kHeaderSize;
6496 static const int kCodeOffset = kNameOffset + kPointerSize;
6497 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6498 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6499 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6500 static const int kInstanceClassNameOffset =
6501 kConstructStubOffset + kPointerSize;
6502 static const int kFunctionDataOffset =
6503 kInstanceClassNameOffset + kPointerSize;
6504 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6505 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6506 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6507 static const int kFeedbackVectorOffset =
6508 kInferredNameOffset + kPointerSize;
6510 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6511 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6513 // Just to not break the postmortrem support with conditional offsets
6514 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6515 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6518 #if V8_HOST_ARCH_32_BIT
6520 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6521 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6522 static const int kExpectedNofPropertiesOffset =
6523 kFormalParameterCountOffset + kPointerSize;
6524 static const int kNumLiteralsOffset =
6525 kExpectedNofPropertiesOffset + kPointerSize;
6526 static const int kStartPositionAndTypeOffset =
6527 kNumLiteralsOffset + kPointerSize;
6528 static const int kEndPositionOffset =
6529 kStartPositionAndTypeOffset + kPointerSize;
6530 static const int kFunctionTokenPositionOffset =
6531 kEndPositionOffset + kPointerSize;
6532 static const int kCompilerHintsOffset =
6533 kFunctionTokenPositionOffset + kPointerSize;
6534 static const int kOptCountAndBailoutReasonOffset =
6535 kCompilerHintsOffset + kPointerSize;
6536 static const int kCountersOffset =
6537 kOptCountAndBailoutReasonOffset + kPointerSize;
6538 static const int kAstNodeCountOffset =
6539 kCountersOffset + kPointerSize;
6540 static const int kProfilerTicksOffset =
6541 kAstNodeCountOffset + kPointerSize;
6544 static const int kSize = kProfilerTicksOffset + kPointerSize;
6546 // The only reason to use smi fields instead of int fields
6547 // is to allow iteration without maps decoding during
6548 // garbage collections.
6549 // To avoid wasting space on 64-bit architectures we use
6550 // the following trick: we group integer fields into pairs
6551 // The least significant integer in each pair is shifted left by 1.
6552 // By doing this we guarantee that LSB of each kPointerSize aligned
6553 // word is not set and thus this word cannot be treated as pointer
6554 // to HeapObject during old space traversal.
6555 #if V8_TARGET_LITTLE_ENDIAN
6556 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6557 static const int kFormalParameterCountOffset =
6558 kLengthOffset + kIntSize;
6560 static const int kExpectedNofPropertiesOffset =
6561 kFormalParameterCountOffset + kIntSize;
6562 static const int kNumLiteralsOffset =
6563 kExpectedNofPropertiesOffset + kIntSize;
6565 static const int kEndPositionOffset =
6566 kNumLiteralsOffset + kIntSize;
6567 static const int kStartPositionAndTypeOffset =
6568 kEndPositionOffset + kIntSize;
6570 static const int kFunctionTokenPositionOffset =
6571 kStartPositionAndTypeOffset + kIntSize;
6572 static const int kCompilerHintsOffset =
6573 kFunctionTokenPositionOffset + kIntSize;
6575 static const int kOptCountAndBailoutReasonOffset =
6576 kCompilerHintsOffset + kIntSize;
6577 static const int kCountersOffset =
6578 kOptCountAndBailoutReasonOffset + kIntSize;
6580 static const int kAstNodeCountOffset =
6581 kCountersOffset + kIntSize;
6582 static const int kProfilerTicksOffset =
6583 kAstNodeCountOffset + kIntSize;
6586 static const int kSize = kProfilerTicksOffset + kIntSize;
6588 #elif V8_TARGET_BIG_ENDIAN
6589 static const int kFormalParameterCountOffset =
6590 kLastPointerFieldOffset + kPointerSize;
6591 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6593 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6594 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6596 static const int kStartPositionAndTypeOffset =
6597 kExpectedNofPropertiesOffset + kIntSize;
6598 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6600 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6601 static const int kFunctionTokenPositionOffset =
6602 kCompilerHintsOffset + kIntSize;
6604 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
6605 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
6607 static const int kProfilerTicksOffset =
6608 kOptCountAndBailoutReasonOffset + kIntSize;
6609 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
6612 static const int kSize = kAstNodeCountOffset + kIntSize;
6615 #error Unknown byte ordering
6616 #endif // Big endian
6620 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
6622 typedef FixedBodyDescriptor<kNameOffset,
6623 kLastPointerFieldOffset + kPointerSize,
6624 kSize> BodyDescriptor;
6626 // Bit positions in start_position_and_type.
6627 // The source code start position is in the 30 most significant bits of
6628 // the start_position_and_type field.
6629 static const int kIsExpressionBit = 0;
6630 static const int kIsTopLevelBit = 1;
6631 static const int kStartPositionShift = 2;
6632 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
6634 // Bit positions in compiler_hints.
6635 enum CompilerHints {
6636 kAllowLazyCompilation,
6637 kAllowLazyCompilationWithoutContext,
6638 kOptimizationDisabled,
6639 kStrictModeFunction,
6640 kStrongModeFunction,
6643 kHasDuplicateParameters,
6648 kNameShouldPrintAsAnonymous,
6655 kIsAccessorFunction,
6656 kIsDefaultConstructor,
6657 kIsSubclassConstructor,
6663 kCompilerHintsCount // Pseudo entry
6665 // Add hints for other modes when they're added.
6666 STATIC_ASSERT(LANGUAGE_END == 3);
6668 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
6670 class DeoptCountBits : public BitField<int, 0, 4> {};
6671 class OptReenableTriesBits : public BitField<int, 4, 18> {};
6672 class ICAgeBits : public BitField<int, 22, 8> {};
6674 class OptCountBits : public BitField<int, 0, 22> {};
6675 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
6678 #if V8_HOST_ARCH_32_BIT
6679 // On 32 bit platforms, compiler hints is a smi.
6680 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
6681 static const int kCompilerHintsSize = kPointerSize;
6683 // On 64 bit platforms, compiler hints is not a smi, see comment above.
6684 static const int kCompilerHintsSmiTagSize = 0;
6685 static const int kCompilerHintsSize = kIntSize;
6688 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
6689 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
6692 // Constants for optimizing codegen for strict mode function and
6694 // Allows to use byte-width instructions.
6695 static const int kStrictModeBitWithinByte =
6696 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6697 static const int kStrongModeBitWithinByte =
6698 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
6700 static const int kNativeBitWithinByte =
6701 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
6703 #if defined(V8_TARGET_LITTLE_ENDIAN)
6704 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6705 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6706 static const int kStrongModeByteOffset =
6707 kCompilerHintsOffset +
6708 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
6709 static const int kNativeByteOffset = kCompilerHintsOffset +
6710 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
6711 #elif defined(V8_TARGET_BIG_ENDIAN)
6712 static const int kStrictModeByteOffset = kCompilerHintsOffset +
6713 (kCompilerHintsSize - 1) -
6714 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6715 static const int kStrongModeByteOffset =
6716 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
6717 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
6718 static const int kNativeByteOffset = kCompilerHintsOffset +
6719 (kCompilerHintsSize - 1) -
6720 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
6722 #error Unknown byte ordering
6726 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
6730 // Printing support.
6731 struct SourceCodeOf {
6732 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
6733 : value(v), max_length(max) {}
6734 const SharedFunctionInfo* value;
6739 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
6742 class JSGeneratorObject: public JSObject {
6744 // [function]: The function corresponding to this generator object.
6745 DECL_ACCESSORS(function, JSFunction)
6747 // [context]: The context of the suspended computation.
6748 DECL_ACCESSORS(context, Context)
6750 // [receiver]: The receiver of the suspended computation.
6751 DECL_ACCESSORS(receiver, Object)
6753 // [continuation]: Offset into code of continuation.
6755 // A positive offset indicates a suspended generator. The special
6756 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
6757 // cannot be resumed.
6758 inline int continuation() const;
6759 inline void set_continuation(int continuation);
6760 inline bool is_closed();
6761 inline bool is_executing();
6762 inline bool is_suspended();
6764 // [operand_stack]: Saved operand stack.
6765 DECL_ACCESSORS(operand_stack, FixedArray)
6767 DECLARE_CAST(JSGeneratorObject)
6769 // Dispatched behavior.
6770 DECLARE_PRINTER(JSGeneratorObject)
6771 DECLARE_VERIFIER(JSGeneratorObject)
6773 // Magic sentinel values for the continuation.
6774 static const int kGeneratorExecuting = -1;
6775 static const int kGeneratorClosed = 0;
6777 // Layout description.
6778 static const int kFunctionOffset = JSObject::kHeaderSize;
6779 static const int kContextOffset = kFunctionOffset + kPointerSize;
6780 static const int kReceiverOffset = kContextOffset + kPointerSize;
6781 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
6782 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
6783 static const int kSize = kOperandStackOffset + kPointerSize;
6785 // Resume mode, for use by runtime functions.
6786 enum ResumeMode { NEXT, THROW };
6788 // Yielding from a generator returns an object with the following inobject
6789 // properties. See Context::iterator_result_map() for the map.
6790 static const int kResultValuePropertyIndex = 0;
6791 static const int kResultDonePropertyIndex = 1;
6792 static const int kResultPropertyCount = 2;
6794 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
6795 static const int kResultDonePropertyOffset =
6796 kResultValuePropertyOffset + kPointerSize;
6797 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
6800 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
6804 // Representation for module instance objects.
6805 class JSModule: public JSObject {
6807 // [context]: the context holding the module's locals, or undefined if none.
6808 DECL_ACCESSORS(context, Object)
6810 // [scope_info]: Scope info.
6811 DECL_ACCESSORS(scope_info, ScopeInfo)
6813 DECLARE_CAST(JSModule)
6815 // Dispatched behavior.
6816 DECLARE_PRINTER(JSModule)
6817 DECLARE_VERIFIER(JSModule)
6819 // Layout description.
6820 static const int kContextOffset = JSObject::kHeaderSize;
6821 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
6822 static const int kSize = kScopeInfoOffset + kPointerSize;
6825 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
6829 // JSFunction describes JavaScript functions.
6830 class JSFunction: public JSObject {
6832 // [prototype_or_initial_map]:
6833 DECL_ACCESSORS(prototype_or_initial_map, Object)
6835 // [shared]: The information about the function that
6836 // can be shared by instances.
6837 DECL_ACCESSORS(shared, SharedFunctionInfo)
6839 // [context]: The context for this function.
6840 inline Context* context();
6841 inline void set_context(Object* context);
6842 inline JSObject* global_proxy();
6844 // [code]: The generated code object for this function. Executed
6845 // when the function is invoked, e.g. foo() or new foo(). See
6846 // [[Call]] and [[Construct]] description in ECMA-262, section
6848 inline Code* code();
6849 inline void set_code(Code* code);
6850 inline void set_code_no_write_barrier(Code* code);
6851 inline void ReplaceCode(Code* code);
6853 // Tells whether this function is builtin.
6854 inline bool IsBuiltin();
6856 // Tells whether this function inlines the given shared function info.
6857 bool Inlines(SharedFunctionInfo* candidate);
6859 // Tells whether this function should be subject to debugging.
6860 inline bool IsSubjectToDebugging();
6862 // Tells whether or not the function needs arguments adaption.
6863 inline bool NeedsArgumentsAdaption();
6865 // Tells whether or not this function has been optimized.
6866 inline bool IsOptimized();
6868 // Mark this function for lazy recompilation. The function will be
6869 // recompiled the next time it is executed.
6870 void MarkForOptimization();
6871 void AttemptConcurrentOptimization();
6873 // Tells whether or not the function is already marked for lazy
6875 inline bool IsMarkedForOptimization();
6876 inline bool IsMarkedForConcurrentOptimization();
6878 // Tells whether or not the function is on the concurrent recompilation queue.
6879 inline bool IsInOptimizationQueue();
6881 // Inobject slack tracking is the way to reclaim unused inobject space.
6883 // The instance size is initially determined by adding some slack to
6884 // expected_nof_properties (to allow for a few extra properties added
6885 // after the constructor). There is no guarantee that the extra space
6886 // will not be wasted.
6888 // Here is the algorithm to reclaim the unused inobject space:
6889 // - Detect the first constructor call for this JSFunction.
6890 // When it happens enter the "in progress" state: initialize construction
6891 // counter in the initial_map.
6892 // - While the tracking is in progress create objects filled with
6893 // one_pointer_filler_map instead of undefined_value. This way they can be
6894 // resized quickly and safely.
6895 // - Once enough objects have been created compute the 'slack'
6896 // (traverse the map transition tree starting from the
6897 // initial_map and find the lowest value of unused_property_fields).
6898 // - Traverse the transition tree again and decrease the instance size
6899 // of every map. Existing objects will resize automatically (they are
6900 // filled with one_pointer_filler_map). All further allocations will
6901 // use the adjusted instance size.
6902 // - SharedFunctionInfo's expected_nof_properties left unmodified since
6903 // allocations made using different closures could actually create different
6904 // kind of objects (see prototype inheritance pattern).
6906 // Important: inobject slack tracking is not attempted during the snapshot
6909 // True if the initial_map is set and the object constructions countdown
6910 // counter is not zero.
6911 static const int kGenerousAllocationCount =
6912 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
6913 inline bool IsInobjectSlackTrackingInProgress();
6915 // Starts the tracking.
6916 // Initializes object constructions countdown counter in the initial map.
6917 void StartInobjectSlackTracking();
6919 // Completes the tracking.
6920 void CompleteInobjectSlackTracking();
6922 // [literals_or_bindings]: Fixed array holding either
6923 // the materialized literals or the bindings of a bound function.
6925 // If the function contains object, regexp or array literals, the
6926 // literals array prefix contains the object, regexp, and array
6927 // function to be used when creating these literals. This is
6928 // necessary so that we do not dynamically lookup the object, regexp
6929 // or array functions. Performing a dynamic lookup, we might end up
6930 // using the functions from a new context that we should not have
6933 // On bound functions, the array is a (copy-on-write) fixed-array containing
6934 // the function that was bound, bound this-value and any bound
6935 // arguments. Bound functions never contain literals.
6936 DECL_ACCESSORS(literals_or_bindings, FixedArray)
6938 inline FixedArray* literals();
6939 inline void set_literals(FixedArray* literals);
6941 inline FixedArray* function_bindings();
6942 inline void set_function_bindings(FixedArray* bindings);
6944 // The initial map for an object created by this constructor.
6945 inline Map* initial_map();
6946 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
6947 Handle<Object> prototype);
6948 inline bool has_initial_map();
6949 static void EnsureHasInitialMap(Handle<JSFunction> function);
6951 // Get and set the prototype property on a JSFunction. If the
6952 // function has an initial map the prototype is set on the initial
6953 // map. Otherwise, the prototype is put in the initial map field
6954 // until an initial map is needed.
6955 inline bool has_prototype();
6956 inline bool has_instance_prototype();
6957 inline Object* prototype();
6958 inline Object* instance_prototype();
6959 static void SetPrototype(Handle<JSFunction> function,
6960 Handle<Object> value);
6961 static void SetInstancePrototype(Handle<JSFunction> function,
6962 Handle<Object> value);
6964 // Creates a new closure for the fucntion with the same bindings,
6965 // bound values, and prototype. An equivalent of spec operations
6966 // ``CloneMethod`` and ``CloneBoundFunction``.
6967 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
6969 // After prototype is removed, it will not be created when accessed, and
6970 // [[Construct]] from this function will not be allowed.
6971 bool RemovePrototype();
6972 inline bool should_have_prototype();
6974 // Accessor for this function's initial map's [[class]]
6975 // property. This is primarily used by ECMA native functions. This
6976 // method sets the class_name field of this function's initial map
6977 // to a given value. It creates an initial map if this function does
6978 // not have one. Note that this method does not copy the initial map
6979 // if it has one already, but simply replaces it with the new value.
6980 // Instances created afterwards will have a map whose [[class]] is
6981 // set to 'value', but there is no guarantees on instances created
6983 void SetInstanceClassName(String* name);
6985 // Returns if this function has been compiled to native code yet.
6986 inline bool is_compiled();
6988 // Returns `false` if formal parameters include rest parameters, optional
6989 // parameters, or destructuring parameters.
6990 // TODO(caitp): make this a flag set during parsing
6991 inline bool has_simple_parameters();
6993 // [next_function_link]: Links functions into various lists, e.g. the list
6994 // of optimized functions hanging off the native_context. The CodeFlusher
6995 // uses this link to chain together flushing candidates. Treated weakly
6996 // by the garbage collector.
6997 DECL_ACCESSORS(next_function_link, Object)
6999 // Prints the name of the function using PrintF.
7000 void PrintName(FILE* out = stdout);
7002 DECLARE_CAST(JSFunction)
7004 // Iterates the objects, including code objects indirectly referenced
7005 // through pointers to the first instruction in the code object.
7006 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7008 // Dispatched behavior.
7009 DECLARE_PRINTER(JSFunction)
7010 DECLARE_VERIFIER(JSFunction)
7012 // Returns the number of allocated literals.
7013 inline int NumberOfLiterals();
7015 // Used for flags such as --hydrogen-filter.
7016 bool PassesFilter(const char* raw_filter);
7018 // The function's name if it is configured, otherwise shared function info
7020 static Handle<String> GetDebugName(Handle<JSFunction> function);
7022 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7023 // kSize) is weak and has special handling during garbage collection.
7024 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7025 static const int kPrototypeOrInitialMapOffset =
7026 kCodeEntryOffset + kPointerSize;
7027 static const int kSharedFunctionInfoOffset =
7028 kPrototypeOrInitialMapOffset + kPointerSize;
7029 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7030 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7031 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7032 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7033 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7035 // Layout of the bound-function binding array.
7036 static const int kBoundFunctionIndex = 0;
7037 static const int kBoundThisIndex = 1;
7038 static const int kBoundArgumentsStartIndex = 2;
7041 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7045 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7046 // and the prototype is hidden. JSGlobalProxy always delegates
7047 // property accesses to its prototype if the prototype is not null.
7049 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7051 // Accessing a JSGlobalProxy requires security check.
7053 class JSGlobalProxy : public JSObject {
7055 // [native_context]: the owner native context of this global proxy object.
7056 // It is null value if this object is not used by any context.
7057 DECL_ACCESSORS(native_context, Object)
7059 // [hash]: The hash code property (undefined if not initialized yet).
7060 DECL_ACCESSORS(hash, Object)
7062 DECLARE_CAST(JSGlobalProxy)
7064 inline bool IsDetachedFrom(GlobalObject* global) const;
7066 // Dispatched behavior.
7067 DECLARE_PRINTER(JSGlobalProxy)
7068 DECLARE_VERIFIER(JSGlobalProxy)
7070 // Layout description.
7071 static const int kNativeContextOffset = JSObject::kHeaderSize;
7072 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7073 static const int kSize = kHashOffset + kPointerSize;
7076 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7080 // Common super class for JavaScript global objects and the special
7081 // builtins global objects.
7082 class GlobalObject: public JSObject {
7084 // [builtins]: the object holding the runtime routines written in JS.
7085 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7087 // [native context]: the natives corresponding to this global object.
7088 DECL_ACCESSORS(native_context, Context)
7090 // [global proxy]: the global proxy object of the context
7091 DECL_ACCESSORS(global_proxy, JSObject)
7093 DECLARE_CAST(GlobalObject)
7095 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7097 // Ensure that the global object has a cell for the given property name.
7098 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7101 // Layout description.
7102 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7103 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7104 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7105 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7108 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7112 // JavaScript global object.
7113 class JSGlobalObject: public GlobalObject {
7115 DECLARE_CAST(JSGlobalObject)
7117 inline bool IsDetached();
7119 // Dispatched behavior.
7120 DECLARE_PRINTER(JSGlobalObject)
7121 DECLARE_VERIFIER(JSGlobalObject)
7123 // Layout description.
7124 static const int kSize = GlobalObject::kHeaderSize;
7127 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7131 // Builtins global object which holds the runtime routines written in
7133 class JSBuiltinsObject: public GlobalObject {
7135 // Accessors for the runtime routines written in JavaScript.
7136 inline Object* javascript_builtin(Builtins::JavaScript id);
7137 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7139 DECLARE_CAST(JSBuiltinsObject)
7141 // Dispatched behavior.
7142 DECLARE_PRINTER(JSBuiltinsObject)
7143 DECLARE_VERIFIER(JSBuiltinsObject)
7145 // Layout description. The size of the builtins object includes
7146 // room for two pointers per runtime routine written in javascript
7147 // (function and code object).
7148 static const int kJSBuiltinsCount = Builtins::id_count;
7149 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7150 static const int kSize =
7151 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7153 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7154 return kJSBuiltinsOffset + id * kPointerSize;
7158 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7162 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7163 class JSValue: public JSObject {
7165 // [value]: the object being wrapped.
7166 DECL_ACCESSORS(value, Object)
7168 DECLARE_CAST(JSValue)
7170 // Dispatched behavior.
7171 DECLARE_PRINTER(JSValue)
7172 DECLARE_VERIFIER(JSValue)
7174 // Layout description.
7175 static const int kValueOffset = JSObject::kHeaderSize;
7176 static const int kSize = kValueOffset + kPointerSize;
7179 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7185 // Representation for JS date objects.
7186 class JSDate: public JSObject {
7188 // If one component is NaN, all of them are, indicating a NaN time value.
7189 // [value]: the time value.
7190 DECL_ACCESSORS(value, Object)
7191 // [year]: caches year. Either undefined, smi, or NaN.
7192 DECL_ACCESSORS(year, Object)
7193 // [month]: caches month. Either undefined, smi, or NaN.
7194 DECL_ACCESSORS(month, Object)
7195 // [day]: caches day. Either undefined, smi, or NaN.
7196 DECL_ACCESSORS(day, Object)
7197 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7198 DECL_ACCESSORS(weekday, Object)
7199 // [hour]: caches hours. Either undefined, smi, or NaN.
7200 DECL_ACCESSORS(hour, Object)
7201 // [min]: caches minutes. Either undefined, smi, or NaN.
7202 DECL_ACCESSORS(min, Object)
7203 // [sec]: caches seconds. Either undefined, smi, or NaN.
7204 DECL_ACCESSORS(sec, Object)
7205 // [cache stamp]: sample of the date cache stamp at the
7206 // moment when chached fields were cached.
7207 DECL_ACCESSORS(cache_stamp, Object)
7209 DECLARE_CAST(JSDate)
7211 // Returns the date field with the specified index.
7212 // See FieldIndex for the list of date fields.
7213 static Object* GetField(Object* date, Smi* index);
7215 void SetValue(Object* value, bool is_value_nan);
7218 // Dispatched behavior.
7219 DECLARE_PRINTER(JSDate)
7220 DECLARE_VERIFIER(JSDate)
7222 // The order is important. It must be kept in sync with date macros
7233 kFirstUncachedField,
7234 kMillisecond = kFirstUncachedField,
7238 kYearUTC = kFirstUTCField,
7251 // Layout description.
7252 static const int kValueOffset = JSObject::kHeaderSize;
7253 static const int kYearOffset = kValueOffset + kPointerSize;
7254 static const int kMonthOffset = kYearOffset + kPointerSize;
7255 static const int kDayOffset = kMonthOffset + kPointerSize;
7256 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7257 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7258 static const int kMinOffset = kHourOffset + kPointerSize;
7259 static const int kSecOffset = kMinOffset + kPointerSize;
7260 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7261 static const int kSize = kCacheStampOffset + kPointerSize;
7264 inline Object* DoGetField(FieldIndex index);
7266 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7268 // Computes and caches the cacheable fields of the date.
7269 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7272 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7276 // Representation of message objects used for error reporting through
7277 // the API. The messages are formatted in JavaScript so this object is
7278 // a real JavaScript object. The information used for formatting the
7279 // error messages are not directly accessible from JavaScript to
7280 // prevent leaking information to user code called during error
7282 class JSMessageObject: public JSObject {
7284 // [type]: the type of error message.
7285 inline int type() const;
7286 inline void set_type(int value);
7288 // [arguments]: the arguments for formatting the error message.
7289 DECL_ACCESSORS(argument, Object)
7291 // [script]: the script from which the error message originated.
7292 DECL_ACCESSORS(script, Object)
7294 // [stack_frames]: an array of stack frames for this error object.
7295 DECL_ACCESSORS(stack_frames, Object)
7297 // [start_position]: the start position in the script for the error message.
7298 inline int start_position() const;
7299 inline void set_start_position(int value);
7301 // [end_position]: the end position in the script for the error message.
7302 inline int end_position() const;
7303 inline void set_end_position(int value);
7305 DECLARE_CAST(JSMessageObject)
7307 // Dispatched behavior.
7308 DECLARE_PRINTER(JSMessageObject)
7309 DECLARE_VERIFIER(JSMessageObject)
7311 // Layout description.
7312 static const int kTypeOffset = JSObject::kHeaderSize;
7313 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7314 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7315 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7316 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7317 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7318 static const int kSize = kEndPositionOffset + kPointerSize;
7320 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7321 kStackFramesOffset + kPointerSize,
7322 kSize> BodyDescriptor;
7326 // Regular expressions
7327 // The regular expression holds a single reference to a FixedArray in
7328 // the kDataOffset field.
7329 // The FixedArray contains the following data:
7330 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7331 // - reference to the original source string
7332 // - reference to the original flag string
7333 // If it is an atom regexp
7334 // - a reference to a literal string to search for
7335 // If it is an irregexp regexp:
7336 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7337 // used for tracking the last usage (used for code flushing).
7338 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7339 // used for tracking the last usage (used for code flushing)..
7340 // - max number of registers used by irregexp implementations.
7341 // - number of capture registers (output values) of the regexp.
7342 class JSRegExp: public JSObject {
7345 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7346 // ATOM: A simple string to match against using an indexOf operation.
7347 // IRREGEXP: Compiled with Irregexp.
7348 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7349 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7356 UNICODE_ESCAPES = 16
7361 explicit Flags(uint32_t value) : value_(value) { }
7362 bool is_global() { return (value_ & GLOBAL) != 0; }
7363 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7364 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7365 bool is_sticky() { return (value_ & STICKY) != 0; }
7366 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7367 uint32_t value() { return value_; }
7372 DECL_ACCESSORS(data, Object)
7374 inline Type TypeTag();
7375 inline int CaptureCount();
7376 inline Flags GetFlags();
7377 inline String* Pattern();
7378 inline Object* DataAt(int index);
7379 // Set implementation data after the object has been prepared.
7380 inline void SetDataAt(int index, Object* value);
7382 static int code_index(bool is_latin1) {
7384 return kIrregexpLatin1CodeIndex;
7386 return kIrregexpUC16CodeIndex;
7390 static int saved_code_index(bool is_latin1) {
7392 return kIrregexpLatin1CodeSavedIndex;
7394 return kIrregexpUC16CodeSavedIndex;
7398 DECLARE_CAST(JSRegExp)
7400 // Dispatched behavior.
7401 DECLARE_VERIFIER(JSRegExp)
7403 static const int kDataOffset = JSObject::kHeaderSize;
7404 static const int kSize = kDataOffset + kPointerSize;
7406 // Indices in the data array.
7407 static const int kTagIndex = 0;
7408 static const int kSourceIndex = kTagIndex + 1;
7409 static const int kFlagsIndex = kSourceIndex + 1;
7410 static const int kDataIndex = kFlagsIndex + 1;
7411 // The data fields are used in different ways depending on the
7412 // value of the tag.
7413 // Atom regexps (literal strings).
7414 static const int kAtomPatternIndex = kDataIndex;
7416 static const int kAtomDataSize = kAtomPatternIndex + 1;
7418 // Irregexp compiled code or bytecode for Latin1. If compilation
7419 // fails, this fields hold an exception object that should be
7420 // thrown if the regexp is used again.
7421 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7422 // Irregexp compiled code or bytecode for UC16. If compilation
7423 // fails, this fields hold an exception object that should be
7424 // thrown if the regexp is used again.
7425 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7427 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7428 // is a potential candidate for flushing.
7429 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7430 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7431 // a potential candidate for flushing.
7432 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7434 // Maximal number of registers used by either Latin1 or UC16.
7435 // Only used to check that there is enough stack space
7436 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7437 // Number of captures in the compiled regexp.
7438 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7440 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7442 // Offsets directly into the data fixed array.
7443 static const int kDataTagOffset =
7444 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7445 static const int kDataOneByteCodeOffset =
7446 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7447 static const int kDataUC16CodeOffset =
7448 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7449 static const int kIrregexpCaptureCountOffset =
7450 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7452 // In-object fields.
7453 static const int kSourceFieldIndex = 0;
7454 static const int kGlobalFieldIndex = 1;
7455 static const int kIgnoreCaseFieldIndex = 2;
7456 static const int kMultilineFieldIndex = 3;
7457 static const int kLastIndexFieldIndex = 4;
7458 static const int kInObjectFieldCount = 5;
7460 // The uninitialized value for a regexp code object.
7461 static const int kUninitializedValue = -1;
7463 // The compilation error value for the regexp code object. The real error
7464 // object is in the saved code field.
7465 static const int kCompilationErrorValue = -2;
7467 // When we store the sweep generation at which we moved the code from the
7468 // code index to the saved code index we mask it of to be in the [0:255]
7470 static const int kCodeAgeMask = 0xff;
7474 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7476 static inline bool IsMatch(HashTableKey* key, Object* value) {
7477 return key->IsMatch(value);
7480 static inline uint32_t Hash(HashTableKey* key) {
7484 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7485 return key->HashForObject(object);
7488 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7490 static const int kPrefixSize = 0;
7491 static const int kEntrySize = 2;
7495 // This cache is used in two different variants. For regexp caching, it simply
7496 // maps identifying info of the regexp to the cached regexp object. Scripts and
7497 // eval code only gets cached after a second probe for the code object. To do
7498 // so, on first "put" only a hash identifying the source is entered into the
7499 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7500 // such lifetimes get reduced, and removed once they reach zero. If a second put
7501 // is called while such a hash is live in the cache, the hash gets replaced by
7502 // an actual cache entry. Age also removes stale live entries from the cache.
7503 // Such entries are identified by SharedFunctionInfos pointing to either the
7504 // recompilation stub, or to "old" code. This avoids memory leaks due to
7505 // premature caching of scripts and eval strings that are never needed later.
7506 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7507 CompilationCacheShape,
7510 // Find cached value for a string key, otherwise return null.
7511 Handle<Object> Lookup(
7512 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7513 Handle<Object> LookupEval(
7514 Handle<String> src, Handle<SharedFunctionInfo> shared,
7515 LanguageMode language_mode, int scope_position);
7516 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7517 static Handle<CompilationCacheTable> Put(
7518 Handle<CompilationCacheTable> cache, Handle<String> src,
7519 Handle<Context> context, LanguageMode language_mode,
7520 Handle<Object> value);
7521 static Handle<CompilationCacheTable> PutEval(
7522 Handle<CompilationCacheTable> cache, Handle<String> src,
7523 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7524 int scope_position);
7525 static Handle<CompilationCacheTable> PutRegExp(
7526 Handle<CompilationCacheTable> cache, Handle<String> src,
7527 JSRegExp::Flags flags, Handle<FixedArray> value);
7528 void Remove(Object* value);
7530 static const int kHashGenerations = 10;
7532 DECLARE_CAST(CompilationCacheTable)
7535 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7539 class CodeCache: public Struct {
7541 DECL_ACCESSORS(default_cache, FixedArray)
7542 DECL_ACCESSORS(normal_type_cache, Object)
7544 // Add the code object to the cache.
7546 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7548 // Lookup code object in the cache. Returns code object if found and undefined
7550 Object* Lookup(Name* name, Code::Flags flags);
7552 // Get the internal index of a code object in the cache. Returns -1 if the
7553 // code object is not in that cache. This index can be used to later call
7554 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7556 int GetIndex(Object* name, Code* code);
7558 // Remove an object from the cache with the provided internal index.
7559 void RemoveByIndex(Object* name, Code* code, int index);
7561 DECLARE_CAST(CodeCache)
7563 // Dispatched behavior.
7564 DECLARE_PRINTER(CodeCache)
7565 DECLARE_VERIFIER(CodeCache)
7567 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7568 static const int kNormalTypeCacheOffset =
7569 kDefaultCacheOffset + kPointerSize;
7570 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7573 static void UpdateDefaultCache(
7574 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7575 static void UpdateNormalTypeCache(
7576 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7577 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7578 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7580 // Code cache layout of the default cache. Elements are alternating name and
7581 // code objects for non normal load/store/call IC's.
7582 static const int kCodeCacheEntrySize = 2;
7583 static const int kCodeCacheEntryNameOffset = 0;
7584 static const int kCodeCacheEntryCodeOffset = 1;
7586 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7590 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7592 static inline bool IsMatch(HashTableKey* key, Object* value) {
7593 return key->IsMatch(value);
7596 static inline uint32_t Hash(HashTableKey* key) {
7600 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7601 return key->HashForObject(object);
7604 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7606 static const int kPrefixSize = 0;
7607 static const int kEntrySize = 2;
7611 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
7612 CodeCacheHashTableShape,
7615 Object* Lookup(Name* name, Code::Flags flags);
7616 static Handle<CodeCacheHashTable> Put(
7617 Handle<CodeCacheHashTable> table,
7621 int GetIndex(Name* name, Code::Flags flags);
7622 void RemoveByIndex(int index);
7624 DECLARE_CAST(CodeCacheHashTable)
7626 // Initial size of the fixed array backing the hash table.
7627 static const int kInitialSize = 64;
7630 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
7634 class PolymorphicCodeCache: public Struct {
7636 DECL_ACCESSORS(cache, Object)
7638 static void Update(Handle<PolymorphicCodeCache> cache,
7639 MapHandleList* maps,
7644 // Returns an undefined value if the entry is not found.
7645 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
7647 DECLARE_CAST(PolymorphicCodeCache)
7649 // Dispatched behavior.
7650 DECLARE_PRINTER(PolymorphicCodeCache)
7651 DECLARE_VERIFIER(PolymorphicCodeCache)
7653 static const int kCacheOffset = HeapObject::kHeaderSize;
7654 static const int kSize = kCacheOffset + kPointerSize;
7657 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
7661 class PolymorphicCodeCacheHashTable
7662 : public HashTable<PolymorphicCodeCacheHashTable,
7663 CodeCacheHashTableShape,
7666 Object* Lookup(MapHandleList* maps, int code_kind);
7668 static Handle<PolymorphicCodeCacheHashTable> Put(
7669 Handle<PolymorphicCodeCacheHashTable> hash_table,
7670 MapHandleList* maps,
7674 DECLARE_CAST(PolymorphicCodeCacheHashTable)
7676 static const int kInitialSize = 64;
7678 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
7682 class TypeFeedbackInfo: public Struct {
7684 inline int ic_total_count();
7685 inline void set_ic_total_count(int count);
7687 inline int ic_with_type_info_count();
7688 inline void change_ic_with_type_info_count(int delta);
7690 inline int ic_generic_count();
7691 inline void change_ic_generic_count(int delta);
7693 inline void initialize_storage();
7695 inline void change_own_type_change_checksum();
7696 inline int own_type_change_checksum();
7698 inline void set_inlined_type_change_checksum(int checksum);
7699 inline bool matches_inlined_type_change_checksum(int checksum);
7701 DECLARE_CAST(TypeFeedbackInfo)
7703 // Dispatched behavior.
7704 DECLARE_PRINTER(TypeFeedbackInfo)
7705 DECLARE_VERIFIER(TypeFeedbackInfo)
7707 static const int kStorage1Offset = HeapObject::kHeaderSize;
7708 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
7709 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
7710 static const int kSize = kStorage3Offset + kPointerSize;
7713 static const int kTypeChangeChecksumBits = 7;
7715 class ICTotalCountField: public BitField<int, 0,
7716 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7717 class OwnTypeChangeChecksum: public BitField<int,
7718 kSmiValueSize - kTypeChangeChecksumBits,
7719 kTypeChangeChecksumBits> {}; // NOLINT
7720 class ICsWithTypeInfoCountField: public BitField<int, 0,
7721 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
7722 class InlinedTypeChangeChecksum: public BitField<int,
7723 kSmiValueSize - kTypeChangeChecksumBits,
7724 kTypeChangeChecksumBits> {}; // NOLINT
7726 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
7730 enum AllocationSiteMode {
7731 DONT_TRACK_ALLOCATION_SITE,
7732 TRACK_ALLOCATION_SITE,
7733 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
7737 class AllocationSite: public Struct {
7739 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
7740 static const double kPretenureRatio;
7741 static const int kPretenureMinimumCreated = 100;
7743 // Values for pretenure decision field.
7744 enum PretenureDecision {
7750 kLastPretenureDecisionValue = kZombie
7753 const char* PretenureDecisionName(PretenureDecision decision);
7755 DECL_ACCESSORS(transition_info, Object)
7756 // nested_site threads a list of sites that represent nested literals
7757 // walked in a particular order. So [[1, 2], 1, 2] will have one
7758 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
7759 DECL_ACCESSORS(nested_site, Object)
7760 DECL_ACCESSORS(pretenure_data, Smi)
7761 DECL_ACCESSORS(pretenure_create_count, Smi)
7762 DECL_ACCESSORS(dependent_code, DependentCode)
7763 DECL_ACCESSORS(weak_next, Object)
7765 inline void Initialize();
7767 // This method is expensive, it should only be called for reporting.
7768 bool IsNestedSite();
7770 // transition_info bitfields, for constructed array transition info.
7771 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
7772 class UnusedBits: public BitField<int, 15, 14> {};
7773 class DoNotInlineBit: public BitField<bool, 29, 1> {};
7775 // Bitfields for pretenure_data
7776 class MementoFoundCountBits: public BitField<int, 0, 26> {};
7777 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
7778 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
7779 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
7781 // Increments the mementos found counter and returns true when the first
7782 // memento was found for a given allocation site.
7783 inline bool IncrementMementoFoundCount();
7785 inline void IncrementMementoCreateCount();
7787 PretenureFlag GetPretenureMode();
7789 void ResetPretenureDecision();
7791 inline PretenureDecision pretenure_decision();
7792 inline void set_pretenure_decision(PretenureDecision decision);
7794 inline bool deopt_dependent_code();
7795 inline void set_deopt_dependent_code(bool deopt);
7797 inline int memento_found_count();
7798 inline void set_memento_found_count(int count);
7800 inline int memento_create_count();
7801 inline void set_memento_create_count(int count);
7803 // The pretenuring decision is made during gc, and the zombie state allows
7804 // us to recognize when an allocation site is just being kept alive because
7805 // a later traversal of new space may discover AllocationMementos that point
7806 // to this AllocationSite.
7807 inline bool IsZombie();
7809 inline bool IsMaybeTenure();
7811 inline void MarkZombie();
7813 inline bool MakePretenureDecision(PretenureDecision current_decision,
7815 bool maximum_size_scavenge);
7817 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
7819 inline ElementsKind GetElementsKind();
7820 inline void SetElementsKind(ElementsKind kind);
7822 inline bool CanInlineCall();
7823 inline void SetDoNotInlineCall();
7825 inline bool SitePointsToLiteral();
7827 static void DigestTransitionFeedback(Handle<AllocationSite> site,
7828 ElementsKind to_kind);
7830 DECLARE_PRINTER(AllocationSite)
7831 DECLARE_VERIFIER(AllocationSite)
7833 DECLARE_CAST(AllocationSite)
7834 static inline AllocationSiteMode GetMode(
7835 ElementsKind boilerplate_elements_kind);
7836 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
7837 static inline bool CanTrack(InstanceType type);
7839 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
7840 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
7841 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
7842 static const int kPretenureCreateCountOffset =
7843 kPretenureDataOffset + kPointerSize;
7844 static const int kDependentCodeOffset =
7845 kPretenureCreateCountOffset + kPointerSize;
7846 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
7847 static const int kSize = kWeakNextOffset + kPointerSize;
7849 // During mark compact we need to take special care for the dependent code
7851 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
7852 static const int kPointerFieldsEndOffset = kWeakNextOffset;
7854 // For other visitors, use the fixed body descriptor below.
7855 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
7856 kDependentCodeOffset + kPointerSize,
7857 kSize> BodyDescriptor;
7860 inline bool PretenuringDecisionMade();
7862 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
7866 class AllocationMemento: public Struct {
7868 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
7869 static const int kSize = kAllocationSiteOffset + kPointerSize;
7871 DECL_ACCESSORS(allocation_site, Object)
7873 inline bool IsValid();
7874 inline AllocationSite* GetAllocationSite();
7876 DECLARE_PRINTER(AllocationMemento)
7877 DECLARE_VERIFIER(AllocationMemento)
7879 DECLARE_CAST(AllocationMemento)
7882 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
7886 // Representation of a slow alias as part of a sloppy arguments objects.
7887 // For fast aliases (if HasSloppyArgumentsElements()):
7888 // - the parameter map contains an index into the context
7889 // - all attributes of the element have default values
7890 // For slow aliases (if HasDictionaryArgumentsElements()):
7891 // - the parameter map contains no fast alias mapping (i.e. the hole)
7892 // - this struct (in the slow backing store) contains an index into the context
7893 // - all attributes are available as part if the property details
7894 class AliasedArgumentsEntry: public Struct {
7896 inline int aliased_context_slot() const;
7897 inline void set_aliased_context_slot(int count);
7899 DECLARE_CAST(AliasedArgumentsEntry)
7901 // Dispatched behavior.
7902 DECLARE_PRINTER(AliasedArgumentsEntry)
7903 DECLARE_VERIFIER(AliasedArgumentsEntry)
7905 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
7906 static const int kSize = kAliasedContextSlot + kPointerSize;
7909 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
7913 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
7914 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
7917 class StringHasher {
7919 explicit inline StringHasher(int length, uint32_t seed);
7921 template <typename schar>
7922 static inline uint32_t HashSequentialString(const schar* chars,
7926 // Reads all the data, even for long strings and computes the utf16 length.
7927 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
7929 int* utf16_length_out);
7931 // Calculated hash value for a string consisting of 1 to
7932 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
7933 // value is represented decimal value.
7934 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
7936 // No string is allowed to have a hash of zero. That value is reserved
7937 // for internal properties. If the hash calculation yields zero then we
7939 static const int kZeroHash = 27;
7941 // Reusable parts of the hashing algorithm.
7942 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
7943 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
7944 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
7945 const uc16* chars, int length));
7946 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
7951 // Returns the value to store in the hash field of a string with
7952 // the given length and contents.
7953 uint32_t GetHashField();
7954 // Returns true if the hash of this string can be computed without
7955 // looking at the contents.
7956 inline bool has_trivial_hash();
7957 // Adds a block of characters to the hash.
7958 template<typename Char>
7959 inline void AddCharacters(const Char* chars, int len);
7962 // Add a character to the hash.
7963 inline void AddCharacter(uint16_t c);
7964 // Update index. Returns true if string is still an index.
7965 inline bool UpdateIndex(uint16_t c);
7968 uint32_t raw_running_hash_;
7969 uint32_t array_index_;
7970 bool is_array_index_;
7971 bool is_first_char_;
7972 DISALLOW_COPY_AND_ASSIGN(StringHasher);
7976 class IteratingStringHasher : public StringHasher {
7978 static inline uint32_t Hash(String* string, uint32_t seed);
7979 inline void VisitOneByteString(const uint8_t* chars, int length);
7980 inline void VisitTwoByteString(const uint16_t* chars, int length);
7983 inline IteratingStringHasher(int len, uint32_t seed);
7984 void VisitConsString(ConsString* cons_string);
7985 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
7989 // The characteristics of a string are stored in its map. Retrieving these
7990 // few bits of information is moderately expensive, involving two memory
7991 // loads where the second is dependent on the first. To improve efficiency
7992 // the shape of the string is given its own class so that it can be retrieved
7993 // once and used for several string operations. A StringShape is small enough
7994 // to be passed by value and is immutable, but be aware that flattening a
7995 // string can potentially alter its shape. Also be aware that a GC caused by
7996 // something else can alter the shape of a string due to ConsString
7997 // shortcutting. Keeping these restrictions in mind has proven to be error-
7998 // prone and so we no longer put StringShapes in variables unless there is a
7999 // concrete performance benefit at that particular point in the code.
8000 class StringShape BASE_EMBEDDED {
8002 inline explicit StringShape(const String* s);
8003 inline explicit StringShape(Map* s);
8004 inline explicit StringShape(InstanceType t);
8005 inline bool IsSequential();
8006 inline bool IsExternal();
8007 inline bool IsCons();
8008 inline bool IsSliced();
8009 inline bool IsIndirect();
8010 inline bool IsExternalOneByte();
8011 inline bool IsExternalTwoByte();
8012 inline bool IsSequentialOneByte();
8013 inline bool IsSequentialTwoByte();
8014 inline bool IsInternalized();
8015 inline StringRepresentationTag representation_tag();
8016 inline uint32_t encoding_tag();
8017 inline uint32_t full_representation_tag();
8018 inline uint32_t size_tag();
8020 inline uint32_t type() { return type_; }
8021 inline void invalidate() { valid_ = false; }
8022 inline bool valid() { return valid_; }
8024 inline void invalidate() { }
8030 inline void set_valid() { valid_ = true; }
8033 inline void set_valid() { }
8038 // The Name abstract class captures anything that can be used as a property
8039 // name, i.e., strings and symbols. All names store a hash value.
8040 class Name: public HeapObject {
8042 // Get and set the hash field of the name.
8043 inline uint32_t hash_field();
8044 inline void set_hash_field(uint32_t value);
8046 // Tells whether the hash code has been computed.
8047 inline bool HasHashCode();
8049 // Returns a hash value used for the property table
8050 inline uint32_t Hash();
8052 // Equality operations.
8053 inline bool Equals(Name* other);
8054 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8057 inline bool AsArrayIndex(uint32_t* index);
8059 // If the name is private, it can only name own properties.
8060 inline bool IsPrivate();
8062 // If the name is a non-flat string, this method returns a flat version of the
8063 // string. Otherwise it'll just return the input.
8064 static inline Handle<Name> Flatten(Handle<Name> name,
8065 PretenureFlag pretenure = NOT_TENURED);
8069 DECLARE_PRINTER(Name)
8071 void NameShortPrint();
8072 int NameShortPrint(Vector<char> str);
8075 // Layout description.
8076 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8077 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8078 static const int kHashFieldOffset = kHashFieldSlot;
8080 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8082 static const int kSize = kHashFieldSlot + kPointerSize;
8084 // Mask constant for checking if a name has a computed hash code
8085 // and if it is a string that is an array index. The least significant bit
8086 // indicates whether a hash code has been computed. If the hash code has
8087 // been computed the 2nd bit tells whether the string can be used as an
8089 static const int kHashNotComputedMask = 1;
8090 static const int kIsNotArrayIndexMask = 1 << 1;
8091 static const int kNofHashBitFields = 2;
8093 // Shift constant retrieving hash code from hash field.
8094 static const int kHashShift = kNofHashBitFields;
8096 // Only these bits are relevant in the hash, since the top two are shifted
8098 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8100 // Array index strings this short can keep their index in the hash field.
8101 static const int kMaxCachedArrayIndexLength = 7;
8103 // For strings which are array indexes the hash value has the string length
8104 // mixed into the hash, mainly to avoid a hash value of zero which would be
8105 // the case for the string '0'. 24 bits are used for the array index value.
8106 static const int kArrayIndexValueBits = 24;
8107 static const int kArrayIndexLengthBits =
8108 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8110 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8112 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8113 kArrayIndexValueBits> {}; // NOLINT
8114 class ArrayIndexLengthBits : public BitField<unsigned int,
8115 kNofHashBitFields + kArrayIndexValueBits,
8116 kArrayIndexLengthBits> {}; // NOLINT
8118 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8119 // could use a mask to test if the length of string is less than or equal to
8120 // kMaxCachedArrayIndexLength.
8121 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8123 static const unsigned int kContainsCachedArrayIndexMask =
8124 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8125 << ArrayIndexLengthBits::kShift) |
8126 kIsNotArrayIndexMask;
8128 // Value of empty hash field indicating that the hash is not computed.
8129 static const int kEmptyHashField =
8130 kIsNotArrayIndexMask | kHashNotComputedMask;
8133 static inline bool IsHashFieldComputed(uint32_t field);
8136 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8141 class Symbol: public Name {
8143 // [name]: The print name of a symbol, or undefined if none.
8144 DECL_ACCESSORS(name, Object)
8146 DECL_ACCESSORS(flags, Smi)
8148 // [is_private]: Whether this is a private symbol. Private symbols can only
8149 // be used to designate own properties of objects.
8150 DECL_BOOLEAN_ACCESSORS(is_private)
8152 DECLARE_CAST(Symbol)
8154 // Dispatched behavior.
8155 DECLARE_PRINTER(Symbol)
8156 DECLARE_VERIFIER(Symbol)
8158 // Layout description.
8159 static const int kNameOffset = Name::kSize;
8160 static const int kFlagsOffset = kNameOffset + kPointerSize;
8161 static const int kSize = kFlagsOffset + kPointerSize;
8163 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8165 void SymbolShortPrint(std::ostream& os);
8168 static const int kPrivateBit = 0;
8170 const char* PrivateSymbolToName() const;
8173 friend class Name; // For PrivateSymbolToName.
8176 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8182 // The String abstract class captures JavaScript string values:
8185 // 4.3.16 String Value
8186 // A string value is a member of the type String and is a finite
8187 // ordered sequence of zero or more 16-bit unsigned integer values.
8189 // All string values have a length field.
8190 class String: public Name {
8192 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8194 // Array index strings this short can keep their index in the hash field.
8195 static const int kMaxCachedArrayIndexLength = 7;
8197 // For strings which are array indexes the hash value has the string length
8198 // mixed into the hash, mainly to avoid a hash value of zero which would be
8199 // the case for the string '0'. 24 bits are used for the array index value.
8200 static const int kArrayIndexValueBits = 24;
8201 static const int kArrayIndexLengthBits =
8202 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8204 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8206 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8207 kArrayIndexValueBits> {}; // NOLINT
8208 class ArrayIndexLengthBits : public BitField<unsigned int,
8209 kNofHashBitFields + kArrayIndexValueBits,
8210 kArrayIndexLengthBits> {}; // NOLINT
8212 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8213 // could use a mask to test if the length of string is less than or equal to
8214 // kMaxCachedArrayIndexLength.
8215 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8217 static const unsigned int kContainsCachedArrayIndexMask =
8218 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8219 << ArrayIndexLengthBits::kShift) |
8220 kIsNotArrayIndexMask;
8222 class SubStringRange {
8224 explicit inline SubStringRange(String* string, int first = 0,
8227 inline iterator begin();
8228 inline iterator end();
8236 // Representation of the flat content of a String.
8237 // A non-flat string doesn't have flat content.
8238 // A flat string has content that's encoded as a sequence of either
8239 // one-byte chars or two-byte UC16.
8240 // Returned by String::GetFlatContent().
8243 // Returns true if the string is flat and this structure contains content.
8244 bool IsFlat() { return state_ != NON_FLAT; }
8245 // Returns true if the structure contains one-byte content.
8246 bool IsOneByte() { return state_ == ONE_BYTE; }
8247 // Returns true if the structure contains two-byte content.
8248 bool IsTwoByte() { return state_ == TWO_BYTE; }
8250 // Return the one byte content of the string. Only use if IsOneByte()
8252 Vector<const uint8_t> ToOneByteVector() {
8253 DCHECK_EQ(ONE_BYTE, state_);
8254 return Vector<const uint8_t>(onebyte_start, length_);
8256 // Return the two-byte content of the string. Only use if IsTwoByte()
8258 Vector<const uc16> ToUC16Vector() {
8259 DCHECK_EQ(TWO_BYTE, state_);
8260 return Vector<const uc16>(twobyte_start, length_);
8264 DCHECK(i < length_);
8265 DCHECK(state_ != NON_FLAT);
8266 if (state_ == ONE_BYTE) return onebyte_start[i];
8267 return twobyte_start[i];
8270 bool UsesSameString(const FlatContent& other) const {
8271 return onebyte_start == other.onebyte_start;
8275 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8277 // Constructors only used by String::GetFlatContent().
8278 explicit FlatContent(const uint8_t* start, int length)
8279 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8280 explicit FlatContent(const uc16* start, int length)
8281 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8282 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8285 const uint8_t* onebyte_start;
8286 const uc16* twobyte_start;
8291 friend class String;
8292 friend class IterableSubString;
8295 template <typename Char>
8296 INLINE(Vector<const Char> GetCharVector());
8298 // Get and set the length of the string.
8299 inline int length() const;
8300 inline void set_length(int value);
8302 // Get and set the length of the string using acquire loads and release
8304 inline int synchronized_length() const;
8305 inline void synchronized_set_length(int value);
8307 // Returns whether this string has only one-byte chars, i.e. all of them can
8308 // be one-byte encoded. This might be the case even if the string is
8309 // two-byte. Such strings may appear when the embedder prefers
8310 // two-byte external representations even for one-byte data.
8311 inline bool IsOneByteRepresentation() const;
8312 inline bool IsTwoByteRepresentation() const;
8314 // Cons and slices have an encoding flag that may not represent the actual
8315 // encoding of the underlying string. This is taken into account here.
8316 // Requires: this->IsFlat()
8317 inline bool IsOneByteRepresentationUnderneath();
8318 inline bool IsTwoByteRepresentationUnderneath();
8320 // NOTE: this should be considered only a hint. False negatives are
8322 inline bool HasOnlyOneByteChars();
8324 // Get and set individual two byte chars in the string.
8325 inline void Set(int index, uint16_t value);
8326 // Get individual two byte char in the string. Repeated calls
8327 // to this method are not efficient unless the string is flat.
8328 INLINE(uint16_t Get(int index));
8330 // Flattens the string. Checks first inline to see if it is
8331 // necessary. Does nothing if the string is not a cons string.
8332 // Flattening allocates a sequential string with the same data as
8333 // the given string and mutates the cons string to a degenerate
8334 // form, where the first component is the new sequential string and
8335 // the second component is the empty string. If allocation fails,
8336 // this function returns a failure. If flattening succeeds, this
8337 // function returns the sequential string that is now the first
8338 // component of the cons string.
8340 // Degenerate cons strings are handled specially by the garbage
8341 // collector (see IsShortcutCandidate).
8343 static inline Handle<String> Flatten(Handle<String> string,
8344 PretenureFlag pretenure = NOT_TENURED);
8346 // Tries to return the content of a flat string as a structure holding either
8347 // a flat vector of char or of uc16.
8348 // If the string isn't flat, and therefore doesn't have flat content, the
8349 // returned structure will report so, and can't provide a vector of either
8351 FlatContent GetFlatContent();
8353 // Returns the parent of a sliced string or first part of a flat cons string.
8354 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8355 inline String* GetUnderlying();
8357 // String equality operations.
8358 inline bool Equals(String* other);
8359 inline static bool Equals(Handle<String> one, Handle<String> two);
8360 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8361 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8362 bool IsTwoByteEqualTo(Vector<const uc16> str);
8364 // Return a UTF8 representation of the string. The string is null
8365 // terminated but may optionally contain nulls. Length is returned
8366 // in length_output if length_output is not a null pointer The string
8367 // should be nearly flat, otherwise the performance of this method may
8368 // be very slow (quadratic in the length). Setting robustness_flag to
8369 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8370 // handles unexpected data without causing assert failures and it does not
8371 // do any heap allocations. This is useful when printing stack traces.
8372 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8373 RobustnessFlag robustness_flag,
8374 int offset, int length,
8375 int* length_output = 0);
8376 base::SmartArrayPointer<char> ToCString(
8377 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8378 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8379 int* length_output = 0);
8381 // Return a 16 bit Unicode representation of the string.
8382 // The string should be nearly flat, otherwise the performance of
8383 // of this method may be very bad. Setting robustness_flag to
8384 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8385 // handles unexpected data without causing assert failures and it does not
8386 // do any heap allocations. This is useful when printing stack traces.
8387 base::SmartArrayPointer<uc16> ToWideCString(
8388 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8390 bool ComputeArrayIndex(uint32_t* index);
8393 bool MakeExternal(v8::String::ExternalStringResource* resource);
8394 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8397 inline bool AsArrayIndex(uint32_t* index);
8399 DECLARE_CAST(String)
8401 void PrintOn(FILE* out);
8403 // For use during stack traces. Performs rudimentary sanity check.
8406 // Dispatched behavior.
8407 void StringShortPrint(StringStream* accumulator);
8408 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8409 #if defined(DEBUG) || defined(OBJECT_PRINT)
8410 char* ToAsciiArray();
8412 DECLARE_PRINTER(String)
8413 DECLARE_VERIFIER(String)
8415 inline bool IsFlat();
8417 // Layout description.
8418 static const int kLengthOffset = Name::kSize;
8419 static const int kSize = kLengthOffset + kPointerSize;
8421 // Maximum number of characters to consider when trying to convert a string
8422 // value into an array index.
8423 static const int kMaxArrayIndexSize = 10;
8424 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8427 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8428 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8429 static const int kMaxUtf16CodeUnit = 0xffff;
8430 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8432 // Value of hash field containing computed hash equal to zero.
8433 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8435 // Maximal string length.
8436 static const int kMaxLength = (1 << 28) - 16;
8438 // Max length for computing hash. For strings longer than this limit the
8439 // string length is used as the hash value.
8440 static const int kMaxHashCalcLength = 16383;
8442 // Limit for truncation in short printing.
8443 static const int kMaxShortPrintLength = 1024;
8445 // Support for regular expressions.
8446 const uc16* GetTwoByteData(unsigned start);
8448 // Helper function for flattening strings.
8449 template <typename sinkchar>
8450 static void WriteToFlat(String* source,
8455 // The return value may point to the first aligned word containing the first
8456 // non-one-byte character, rather than directly to the non-one-byte character.
8457 // If the return value is >= the passed length, the entire string was
8459 static inline int NonAsciiStart(const char* chars, int length) {
8460 const char* start = chars;
8461 const char* limit = chars + length;
8463 if (length >= kIntptrSize) {
8464 // Check unaligned bytes.
8465 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8466 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8467 return static_cast<int>(chars - start);
8471 // Check aligned words.
8472 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8473 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8474 while (chars + sizeof(uintptr_t) <= limit) {
8475 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8476 return static_cast<int>(chars - start);
8478 chars += sizeof(uintptr_t);
8481 // Check remaining unaligned bytes.
8482 while (chars < limit) {
8483 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8484 return static_cast<int>(chars - start);
8489 return static_cast<int>(chars - start);
8492 static inline bool IsAscii(const char* chars, int length) {
8493 return NonAsciiStart(chars, length) >= length;
8496 static inline bool IsAscii(const uint8_t* chars, int length) {
8498 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8501 static inline int NonOneByteStart(const uc16* chars, int length) {
8502 const uc16* limit = chars + length;
8503 const uc16* start = chars;
8504 while (chars < limit) {
8505 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8508 return static_cast<int>(chars - start);
8511 static inline bool IsOneByte(const uc16* chars, int length) {
8512 return NonOneByteStart(chars, length) >= length;
8515 template<class Visitor>
8516 static inline ConsString* VisitFlat(Visitor* visitor,
8520 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8521 bool include_ending_line);
8523 // Use the hash field to forward to the canonical internalized string
8524 // when deserializing an internalized string.
8525 inline void SetForwardedInternalizedString(String* string);
8526 inline String* GetForwardedInternalizedString();
8530 friend class StringTableInsertionKey;
8532 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8533 PretenureFlag tenure);
8535 // Slow case of String::Equals. This implementation works on any strings
8536 // but it is most efficient on strings that are almost flat.
8537 bool SlowEquals(String* other);
8539 static bool SlowEquals(Handle<String> one, Handle<String> two);
8541 // Slow case of AsArrayIndex.
8542 bool SlowAsArrayIndex(uint32_t* index);
8544 // Compute and set the hash code.
8545 uint32_t ComputeAndSetHash();
8547 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8551 // The SeqString abstract class captures sequential string values.
8552 class SeqString: public String {
8554 DECLARE_CAST(SeqString)
8556 // Layout description.
8557 static const int kHeaderSize = String::kSize;
8559 // Truncate the string in-place if possible and return the result.
8560 // In case of new_length == 0, the empty string is returned without
8561 // truncating the original string.
8562 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8565 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8569 // The OneByteString class captures sequential one-byte string objects.
8570 // Each character in the OneByteString is an one-byte character.
8571 class SeqOneByteString: public SeqString {
8573 static const bool kHasOneByteEncoding = true;
8575 // Dispatched behavior.
8576 inline uint16_t SeqOneByteStringGet(int index);
8577 inline void SeqOneByteStringSet(int index, uint16_t value);
8579 // Get the address of the characters in this string.
8580 inline Address GetCharsAddress();
8582 inline uint8_t* GetChars();
8584 DECLARE_CAST(SeqOneByteString)
8586 // Garbage collection support. This method is called by the
8587 // garbage collector to compute the actual size of an OneByteString
8589 inline int SeqOneByteStringSize(InstanceType instance_type);
8591 // Computes the size for an OneByteString instance of a given length.
8592 static int SizeFor(int length) {
8593 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
8596 // Maximal memory usage for a single sequential one-byte string.
8597 static const int kMaxSize = 512 * MB - 1;
8598 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
8601 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
8605 // The TwoByteString class captures sequential unicode string objects.
8606 // Each character in the TwoByteString is a two-byte uint16_t.
8607 class SeqTwoByteString: public SeqString {
8609 static const bool kHasOneByteEncoding = false;
8611 // Dispatched behavior.
8612 inline uint16_t SeqTwoByteStringGet(int index);
8613 inline void SeqTwoByteStringSet(int index, uint16_t value);
8615 // Get the address of the characters in this string.
8616 inline Address GetCharsAddress();
8618 inline uc16* GetChars();
8621 const uint16_t* SeqTwoByteStringGetData(unsigned start);
8623 DECLARE_CAST(SeqTwoByteString)
8625 // Garbage collection support. This method is called by the
8626 // garbage collector to compute the actual size of a TwoByteString
8628 inline int SeqTwoByteStringSize(InstanceType instance_type);
8630 // Computes the size for a TwoByteString instance of a given length.
8631 static int SizeFor(int length) {
8632 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
8635 // Maximal memory usage for a single sequential two-byte string.
8636 static const int kMaxSize = 512 * MB - 1;
8637 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
8638 String::kMaxLength);
8641 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
8645 // The ConsString class describes string values built by using the
8646 // addition operator on strings. A ConsString is a pair where the
8647 // first and second components are pointers to other string values.
8648 // One or both components of a ConsString can be pointers to other
8649 // ConsStrings, creating a binary tree of ConsStrings where the leaves
8650 // are non-ConsString string values. The string value represented by
8651 // a ConsString can be obtained by concatenating the leaf string
8652 // values in a left-to-right depth-first traversal of the tree.
8653 class ConsString: public String {
8655 // First string of the cons cell.
8656 inline String* first();
8657 // Doesn't check that the result is a string, even in debug mode. This is
8658 // useful during GC where the mark bits confuse the checks.
8659 inline Object* unchecked_first();
8660 inline void set_first(String* first,
8661 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8663 // Second string of the cons cell.
8664 inline String* second();
8665 // Doesn't check that the result is a string, even in debug mode. This is
8666 // useful during GC where the mark bits confuse the checks.
8667 inline Object* unchecked_second();
8668 inline void set_second(String* second,
8669 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8671 // Dispatched behavior.
8672 uint16_t ConsStringGet(int index);
8674 DECLARE_CAST(ConsString)
8676 // Layout description.
8677 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
8678 static const int kSecondOffset = kFirstOffset + kPointerSize;
8679 static const int kSize = kSecondOffset + kPointerSize;
8681 // Minimum length for a cons string.
8682 static const int kMinLength = 13;
8684 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
8687 DECLARE_VERIFIER(ConsString)
8690 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
8694 // The Sliced String class describes strings that are substrings of another
8695 // sequential string. The motivation is to save time and memory when creating
8696 // a substring. A Sliced String is described as a pointer to the parent,
8697 // the offset from the start of the parent string and the length. Using
8698 // a Sliced String therefore requires unpacking of the parent string and
8699 // adding the offset to the start address. A substring of a Sliced String
8700 // are not nested since the double indirection is simplified when creating
8701 // such a substring.
8702 // Currently missing features are:
8703 // - handling externalized parent strings
8704 // - external strings as parent
8705 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
8706 class SlicedString: public String {
8708 inline String* parent();
8709 inline void set_parent(String* parent,
8710 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
8711 inline int offset() const;
8712 inline void set_offset(int offset);
8714 // Dispatched behavior.
8715 uint16_t SlicedStringGet(int index);
8717 DECLARE_CAST(SlicedString)
8719 // Layout description.
8720 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
8721 static const int kOffsetOffset = kParentOffset + kPointerSize;
8722 static const int kSize = kOffsetOffset + kPointerSize;
8724 // Minimum length for a sliced string.
8725 static const int kMinLength = 13;
8727 typedef FixedBodyDescriptor<kParentOffset,
8728 kOffsetOffset + kPointerSize, kSize>
8731 DECLARE_VERIFIER(SlicedString)
8734 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
8738 // The ExternalString class describes string values that are backed by
8739 // a string resource that lies outside the V8 heap. ExternalStrings
8740 // consist of the length field common to all strings, a pointer to the
8741 // external resource. It is important to ensure (externally) that the
8742 // resource is not deallocated while the ExternalString is live in the
8745 // The API expects that all ExternalStrings are created through the
8746 // API. Therefore, ExternalStrings should not be used internally.
8747 class ExternalString: public String {
8749 DECLARE_CAST(ExternalString)
8751 // Layout description.
8752 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
8753 static const int kShortSize = kResourceOffset + kPointerSize;
8754 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
8755 static const int kSize = kResourceDataOffset + kPointerSize;
8757 static const int kMaxShortLength =
8758 (kShortSize - SeqString::kHeaderSize) / kCharSize;
8760 // Return whether external string is short (data pointer is not cached).
8761 inline bool is_short();
8763 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
8766 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
8770 // The ExternalOneByteString class is an external string backed by an
8772 class ExternalOneByteString : public ExternalString {
8774 static const bool kHasOneByteEncoding = true;
8776 typedef v8::String::ExternalOneByteStringResource Resource;
8778 // The underlying resource.
8779 inline const Resource* resource();
8780 inline void set_resource(const Resource* buffer);
8782 // Update the pointer cache to the external character array.
8783 // The cached pointer is always valid, as the external character array does =
8784 // not move during lifetime. Deserialization is the only exception, after
8785 // which the pointer cache has to be refreshed.
8786 inline void update_data_cache();
8788 inline const uint8_t* GetChars();
8790 // Dispatched behavior.
8791 inline uint16_t ExternalOneByteStringGet(int index);
8793 DECLARE_CAST(ExternalOneByteString)
8795 // Garbage collection support.
8796 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
8798 template <typename StaticVisitor>
8799 inline void ExternalOneByteStringIterateBody();
8802 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
8806 // The ExternalTwoByteString class is an external string backed by a UTF-16
8808 class ExternalTwoByteString: public ExternalString {
8810 static const bool kHasOneByteEncoding = false;
8812 typedef v8::String::ExternalStringResource Resource;
8814 // The underlying string resource.
8815 inline const Resource* resource();
8816 inline void set_resource(const Resource* buffer);
8818 // Update the pointer cache to the external character array.
8819 // The cached pointer is always valid, as the external character array does =
8820 // not move during lifetime. Deserialization is the only exception, after
8821 // which the pointer cache has to be refreshed.
8822 inline void update_data_cache();
8824 inline const uint16_t* GetChars();
8826 // Dispatched behavior.
8827 inline uint16_t ExternalTwoByteStringGet(int index);
8830 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
8832 DECLARE_CAST(ExternalTwoByteString)
8834 // Garbage collection support.
8835 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
8837 template<typename StaticVisitor>
8838 inline void ExternalTwoByteStringIterateBody();
8841 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
8845 // Utility superclass for stack-allocated objects that must be updated
8846 // on gc. It provides two ways for the gc to update instances, either
8847 // iterating or updating after gc.
8848 class Relocatable BASE_EMBEDDED {
8850 explicit inline Relocatable(Isolate* isolate);
8851 inline virtual ~Relocatable();
8852 virtual void IterateInstance(ObjectVisitor* v) { }
8853 virtual void PostGarbageCollection() { }
8855 static void PostGarbageCollectionProcessing(Isolate* isolate);
8856 static int ArchiveSpacePerThread();
8857 static char* ArchiveState(Isolate* isolate, char* to);
8858 static char* RestoreState(Isolate* isolate, char* from);
8859 static void Iterate(Isolate* isolate, ObjectVisitor* v);
8860 static void Iterate(ObjectVisitor* v, Relocatable* top);
8861 static char* Iterate(ObjectVisitor* v, char* t);
8869 // A flat string reader provides random access to the contents of a
8870 // string independent of the character width of the string. The handle
8871 // must be valid as long as the reader is being used.
8872 class FlatStringReader : public Relocatable {
8874 FlatStringReader(Isolate* isolate, Handle<String> str);
8875 FlatStringReader(Isolate* isolate, Vector<const char> input);
8876 void PostGarbageCollection();
8877 inline uc32 Get(int index);
8878 template <typename Char>
8879 inline Char Get(int index);
8880 int length() { return length_; }
8889 // This maintains an off-stack representation of the stack frames required
8890 // to traverse a ConsString, allowing an entirely iterative and restartable
8891 // traversal of the entire string
8892 class ConsStringIterator {
8894 inline ConsStringIterator() {}
8895 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
8896 Reset(cons_string, offset);
8898 inline void Reset(ConsString* cons_string, int offset = 0) {
8900 // Next will always return NULL.
8901 if (cons_string == NULL) return;
8902 Initialize(cons_string, offset);
8904 // Returns NULL when complete.
8905 inline String* Next(int* offset_out) {
8907 if (depth_ == 0) return NULL;
8908 return Continue(offset_out);
8912 static const int kStackSize = 32;
8913 // Use a mask instead of doing modulo operations for stack wrapping.
8914 static const int kDepthMask = kStackSize-1;
8915 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
8916 static inline int OffsetForDepth(int depth);
8918 inline void PushLeft(ConsString* string);
8919 inline void PushRight(ConsString* string);
8920 inline void AdjustMaximumDepth();
8922 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
8923 void Initialize(ConsString* cons_string, int offset);
8924 String* Continue(int* offset_out);
8925 String* NextLeaf(bool* blew_stack);
8926 String* Search(int* offset_out);
8928 // Stack must always contain only frames for which right traversal
8929 // has not yet been performed.
8930 ConsString* frames_[kStackSize];
8935 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
8939 class StringCharacterStream {
8941 inline StringCharacterStream(String* string,
8943 inline uint16_t GetNext();
8944 inline bool HasMore();
8945 inline void Reset(String* string, int offset = 0);
8946 inline void VisitOneByteString(const uint8_t* chars, int length);
8947 inline void VisitTwoByteString(const uint16_t* chars, int length);
8950 ConsStringIterator iter_;
8953 const uint8_t* buffer8_;
8954 const uint16_t* buffer16_;
8956 const uint8_t* end_;
8957 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
8961 template <typename T>
8962 class VectorIterator {
8964 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
8965 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
8966 T GetNext() { return data_[index_++]; }
8967 bool has_more() { return index_ < data_.length(); }
8969 Vector<const T> data_;
8974 // The Oddball describes objects null, undefined, true, and false.
8975 class Oddball: public HeapObject {
8977 // [to_string]: Cached to_string computed at startup.
8978 DECL_ACCESSORS(to_string, String)
8980 // [to_number]: Cached to_number computed at startup.
8981 DECL_ACCESSORS(to_number, Object)
8983 // [typeof]: Cached type_of computed at startup.
8984 DECL_ACCESSORS(type_of, String)
8986 inline byte kind() const;
8987 inline void set_kind(byte kind);
8989 DECLARE_CAST(Oddball)
8991 // Dispatched behavior.
8992 DECLARE_VERIFIER(Oddball)
8994 // Initialize the fields.
8995 static void Initialize(Isolate* isolate, Handle<Oddball> oddball,
8996 const char* to_string, Handle<Object> to_number,
8997 const char* type_of, byte kind);
8999 // Layout description.
9000 static const int kToStringOffset = HeapObject::kHeaderSize;
9001 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9002 static const int kTypeOfOffset = kToNumberOffset + kPointerSize;
9003 static const int kKindOffset = kTypeOfOffset + kPointerSize;
9004 static const int kSize = kKindOffset + kPointerSize;
9006 static const byte kFalse = 0;
9007 static const byte kTrue = 1;
9008 static const byte kNotBooleanMask = ~1;
9009 static const byte kTheHole = 2;
9010 static const byte kNull = 3;
9011 static const byte kArgumentMarker = 4;
9012 static const byte kUndefined = 5;
9013 static const byte kUninitialized = 6;
9014 static const byte kOther = 7;
9015 static const byte kException = 8;
9017 typedef FixedBodyDescriptor<kToStringOffset, kTypeOfOffset + kPointerSize,
9018 kSize> BodyDescriptor;
9020 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9021 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9022 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9025 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9029 class Cell: public HeapObject {
9031 // [value]: value of the cell.
9032 DECL_ACCESSORS(value, Object)
9036 static inline Cell* FromValueAddress(Address value) {
9037 Object* result = FromAddress(value - kValueOffset);
9038 return static_cast<Cell*>(result);
9041 inline Address ValueAddress() {
9042 return address() + kValueOffset;
9045 // Dispatched behavior.
9046 DECLARE_PRINTER(Cell)
9047 DECLARE_VERIFIER(Cell)
9049 // Layout description.
9050 static const int kValueOffset = HeapObject::kHeaderSize;
9051 static const int kSize = kValueOffset + kPointerSize;
9053 typedef FixedBodyDescriptor<kValueOffset,
9054 kValueOffset + kPointerSize,
9055 kSize> BodyDescriptor;
9058 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9062 class PropertyCell : public HeapObject {
9064 // [property_details]: details of the global property.
9065 DECL_ACCESSORS(property_details_raw, Object)
9066 // [value]: value of the global property.
9067 DECL_ACCESSORS(value, Object)
9068 // [dependent_code]: dependent code that depends on the type of the global
9070 DECL_ACCESSORS(dependent_code, DependentCode)
9072 inline PropertyDetails property_details();
9073 inline void set_property_details(PropertyDetails details);
9075 PropertyCellConstantType GetConstantType();
9077 // Computes the new type of the cell's contents for the given value, but
9078 // without actually modifying the details.
9079 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9080 Handle<Object> value,
9081 PropertyDetails details);
9082 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9083 Handle<Object> value, PropertyDetails details);
9085 static Handle<PropertyCell> InvalidateEntry(
9086 Handle<GlobalDictionary> dictionary, int entry);
9088 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9089 Handle<Object> new_value);
9091 DECLARE_CAST(PropertyCell)
9093 // Dispatched behavior.
9094 DECLARE_PRINTER(PropertyCell)
9095 DECLARE_VERIFIER(PropertyCell)
9097 // Layout description.
9098 static const int kDetailsOffset = HeapObject::kHeaderSize;
9099 static const int kValueOffset = kDetailsOffset + kPointerSize;
9100 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9101 static const int kSize = kDependentCodeOffset + kPointerSize;
9103 static const int kPointerFieldsBeginOffset = kValueOffset;
9104 static const int kPointerFieldsEndOffset = kSize;
9106 typedef FixedBodyDescriptor<kValueOffset,
9108 kSize> BodyDescriptor;
9111 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9115 class WeakCell : public HeapObject {
9117 inline Object* value() const;
9119 // This should not be called by anyone except GC.
9120 inline void clear();
9122 // This should not be called by anyone except allocator.
9123 inline void initialize(HeapObject* value);
9125 inline bool cleared() const;
9127 DECL_ACCESSORS(next, Object)
9129 inline void clear_next(Heap* heap);
9131 inline bool next_cleared();
9133 DECLARE_CAST(WeakCell)
9135 DECLARE_PRINTER(WeakCell)
9136 DECLARE_VERIFIER(WeakCell)
9138 // Layout description.
9139 static const int kValueOffset = HeapObject::kHeaderSize;
9140 static const int kNextOffset = kValueOffset + kPointerSize;
9141 static const int kSize = kNextOffset + kPointerSize;
9143 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9146 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9150 // The JSProxy describes EcmaScript Harmony proxies
9151 class JSProxy: public JSReceiver {
9153 // [handler]: The handler property.
9154 DECL_ACCESSORS(handler, Object)
9156 // [hash]: The hash code property (undefined if not initialized yet).
9157 DECL_ACCESSORS(hash, Object)
9159 DECLARE_CAST(JSProxy)
9161 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9162 Handle<JSProxy> proxy,
9163 Handle<Object> receiver,
9166 // If the handler defines an accessor property with a setter, invoke it.
9167 // If it defines an accessor property without a setter, or a data property
9168 // that is read-only, throw. In all these cases set '*done' to true,
9169 // otherwise set it to false.
9171 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9172 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9173 Handle<Object> value, LanguageMode language_mode, bool* done);
9175 MUST_USE_RESULT static Maybe<PropertyAttributes>
9176 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9177 Handle<Object> receiver,
9179 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9180 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9181 Handle<Object> value, LanguageMode language_mode);
9183 // Turn the proxy into an (empty) JSObject.
9184 static void Fix(Handle<JSProxy> proxy);
9186 // Initializes the body after the handler slot.
9187 inline void InitializeBody(int object_size, Object* value);
9189 // Invoke a trap by name. If the trap does not exist on this's handler,
9190 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9191 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9192 Handle<JSProxy> proxy,
9194 Handle<Object> derived_trap,
9196 Handle<Object> args[]);
9198 // Dispatched behavior.
9199 DECLARE_PRINTER(JSProxy)
9200 DECLARE_VERIFIER(JSProxy)
9202 // Layout description. We add padding so that a proxy has the same
9203 // size as a virgin JSObject. This is essential for becoming a JSObject
9205 static const int kHandlerOffset = HeapObject::kHeaderSize;
9206 static const int kHashOffset = kHandlerOffset + kPointerSize;
9207 static const int kPaddingOffset = kHashOffset + kPointerSize;
9208 static const int kSize = JSObject::kHeaderSize;
9209 static const int kHeaderSize = kPaddingOffset;
9210 static const int kPaddingSize = kSize - kPaddingOffset;
9212 STATIC_ASSERT(kPaddingSize >= 0);
9214 typedef FixedBodyDescriptor<kHandlerOffset,
9216 kSize> BodyDescriptor;
9219 friend class JSReceiver;
9221 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9222 Handle<JSProxy> proxy, Handle<Name> name);
9224 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9225 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9227 MUST_USE_RESULT Object* GetIdentityHash();
9229 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9231 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9235 class JSFunctionProxy: public JSProxy {
9237 // [call_trap]: The call trap.
9238 DECL_ACCESSORS(call_trap, Object)
9240 // [construct_trap]: The construct trap.
9241 DECL_ACCESSORS(construct_trap, Object)
9243 DECLARE_CAST(JSFunctionProxy)
9245 // Dispatched behavior.
9246 DECLARE_PRINTER(JSFunctionProxy)
9247 DECLARE_VERIFIER(JSFunctionProxy)
9249 // Layout description.
9250 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9251 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9252 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9253 static const int kSize = JSFunction::kSize;
9254 static const int kPaddingSize = kSize - kPaddingOffset;
9256 STATIC_ASSERT(kPaddingSize >= 0);
9258 typedef FixedBodyDescriptor<kHandlerOffset,
9259 kConstructTrapOffset + kPointerSize,
9260 kSize> BodyDescriptor;
9263 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9267 class JSCollection : public JSObject {
9269 // [table]: the backing hash table
9270 DECL_ACCESSORS(table, Object)
9272 static const int kTableOffset = JSObject::kHeaderSize;
9273 static const int kSize = kTableOffset + kPointerSize;
9276 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9280 // The JSSet describes EcmaScript Harmony sets
9281 class JSSet : public JSCollection {
9285 // Dispatched behavior.
9286 DECLARE_PRINTER(JSSet)
9287 DECLARE_VERIFIER(JSSet)
9290 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9294 // The JSMap describes EcmaScript Harmony maps
9295 class JSMap : public JSCollection {
9299 // Dispatched behavior.
9300 DECLARE_PRINTER(JSMap)
9301 DECLARE_VERIFIER(JSMap)
9304 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9308 // OrderedHashTableIterator is an iterator that iterates over the keys and
9309 // values of an OrderedHashTable.
9311 // The iterator has a reference to the underlying OrderedHashTable data,
9312 // [table], as well as the current [index] the iterator is at.
9314 // When the OrderedHashTable is rehashed it adds a reference from the old table
9315 // to the new table as well as storing enough data about the changes so that the
9316 // iterator [index] can be adjusted accordingly.
9318 // When the [Next] result from the iterator is requested, the iterator checks if
9319 // there is a newer table that it needs to transition to.
9320 template<class Derived, class TableType>
9321 class OrderedHashTableIterator: public JSObject {
9323 // [table]: the backing hash table mapping keys to values.
9324 DECL_ACCESSORS(table, Object)
9326 // [index]: The index into the data table.
9327 DECL_ACCESSORS(index, Object)
9329 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9330 DECL_ACCESSORS(kind, Object)
9333 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9336 static const int kTableOffset = JSObject::kHeaderSize;
9337 static const int kIndexOffset = kTableOffset + kPointerSize;
9338 static const int kKindOffset = kIndexOffset + kPointerSize;
9339 static const int kSize = kKindOffset + kPointerSize;
9347 // Whether the iterator has more elements. This needs to be called before
9348 // calling |CurrentKey| and/or |CurrentValue|.
9351 // Move the index forward one.
9353 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9356 // Populates the array with the next key and value and then moves the iterator
9358 // This returns the |kind| or 0 if the iterator is already at the end.
9359 Smi* Next(JSArray* value_array);
9361 // Returns the current key of the iterator. This should only be called when
9362 // |HasMore| returns true.
9363 inline Object* CurrentKey();
9366 // Transitions the iterator to the non obsolete backing store. This is a NOP
9367 // if the [table] is not obsolete.
9370 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9374 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9377 // Dispatched behavior.
9378 DECLARE_PRINTER(JSSetIterator)
9379 DECLARE_VERIFIER(JSSetIterator)
9381 DECLARE_CAST(JSSetIterator)
9383 // Called by |Next| to populate the array. This allows the subclasses to
9384 // populate the array differently.
9385 inline void PopulateValueArray(FixedArray* array);
9388 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9392 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9395 // Dispatched behavior.
9396 DECLARE_PRINTER(JSMapIterator)
9397 DECLARE_VERIFIER(JSMapIterator)
9399 DECLARE_CAST(JSMapIterator)
9401 // Called by |Next| to populate the array. This allows the subclasses to
9402 // populate the array differently.
9403 inline void PopulateValueArray(FixedArray* array);
9406 // Returns the current value of the iterator. This should only be called when
9407 // |HasMore| returns true.
9408 inline Object* CurrentValue();
9410 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9414 // Base class for both JSWeakMap and JSWeakSet
9415 class JSWeakCollection: public JSObject {
9417 // [table]: the backing hash table mapping keys to values.
9418 DECL_ACCESSORS(table, Object)
9420 // [next]: linked list of encountered weak maps during GC.
9421 DECL_ACCESSORS(next, Object)
9423 static const int kTableOffset = JSObject::kHeaderSize;
9424 static const int kNextOffset = kTableOffset + kPointerSize;
9425 static const int kSize = kNextOffset + kPointerSize;
9428 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9432 // The JSWeakMap describes EcmaScript Harmony weak maps
9433 class JSWeakMap: public JSWeakCollection {
9435 DECLARE_CAST(JSWeakMap)
9437 // Dispatched behavior.
9438 DECLARE_PRINTER(JSWeakMap)
9439 DECLARE_VERIFIER(JSWeakMap)
9442 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9446 // The JSWeakSet describes EcmaScript Harmony weak sets
9447 class JSWeakSet: public JSWeakCollection {
9449 DECLARE_CAST(JSWeakSet)
9451 // Dispatched behavior.
9452 DECLARE_PRINTER(JSWeakSet)
9453 DECLARE_VERIFIER(JSWeakSet)
9456 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9460 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9461 enum class SharedFlag { kNotShared, kShared };
9464 class JSArrayBuffer: public JSObject {
9466 // [backing_store]: backing memory for this array
9467 DECL_ACCESSORS(backing_store, void)
9469 // [byte_length]: length in bytes
9470 DECL_ACCESSORS(byte_length, Object)
9472 inline uint32_t bit_field() const;
9473 inline void set_bit_field(uint32_t bits);
9475 inline bool is_external();
9476 inline void set_is_external(bool value);
9478 inline bool is_neuterable();
9479 inline void set_is_neuterable(bool value);
9481 inline bool was_neutered();
9482 inline void set_was_neutered(bool value);
9484 inline bool is_shared();
9485 inline void set_is_shared(bool value);
9487 DECLARE_CAST(JSArrayBuffer)
9491 // Dispatched behavior.
9492 DECLARE_PRINTER(JSArrayBuffer)
9493 DECLARE_VERIFIER(JSArrayBuffer)
9495 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9496 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9497 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9498 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9499 static const int kBitFieldOffset = kBitFieldSlot;
9501 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9503 static const int kSize = kBitFieldSlot + kPointerSize;
9505 static const int kSizeWithInternalFields =
9506 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9508 class IsExternal : public BitField<bool, 1, 1> {};
9509 class IsNeuterable : public BitField<bool, 2, 1> {};
9510 class WasNeutered : public BitField<bool, 3, 1> {};
9511 class IsShared : public BitField<bool, 4, 1> {};
9514 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9518 class JSArrayBufferView: public JSObject {
9520 // [buffer]: ArrayBuffer that this typed array views.
9521 DECL_ACCESSORS(buffer, Object)
9523 // [byte_offset]: offset of typed array in bytes.
9524 DECL_ACCESSORS(byte_offset, Object)
9526 // [byte_length]: length of typed array in bytes.
9527 DECL_ACCESSORS(byte_length, Object)
9529 DECLARE_CAST(JSArrayBufferView)
9531 DECLARE_VERIFIER(JSArrayBufferView)
9533 inline bool WasNeutered() const;
9535 static const int kBufferOffset = JSObject::kHeaderSize;
9536 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9537 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9538 static const int kViewSize = kByteLengthOffset + kPointerSize;
9542 DECL_ACCESSORS(raw_byte_offset, Object)
9543 DECL_ACCESSORS(raw_byte_length, Object)
9546 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9550 class JSTypedArray: public JSArrayBufferView {
9552 // [length]: length of typed array in elements.
9553 DECL_ACCESSORS(length, Object)
9554 inline uint32_t length_value() const;
9556 DECLARE_CAST(JSTypedArray)
9558 ExternalArrayType type();
9559 size_t element_size();
9561 Handle<JSArrayBuffer> GetBuffer();
9563 // Dispatched behavior.
9564 DECLARE_PRINTER(JSTypedArray)
9565 DECLARE_VERIFIER(JSTypedArray)
9567 static const int kLengthOffset = kViewSize + kPointerSize;
9568 static const int kSize = kLengthOffset + kPointerSize;
9570 static const int kSizeWithInternalFields =
9571 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9574 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9575 Handle<JSTypedArray> typed_array);
9577 DECL_ACCESSORS(raw_length, Object)
9580 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
9584 class JSDataView: public JSArrayBufferView {
9586 DECLARE_CAST(JSDataView)
9588 // Dispatched behavior.
9589 DECLARE_PRINTER(JSDataView)
9590 DECLARE_VERIFIER(JSDataView)
9592 static const int kSize = kViewSize;
9594 static const int kSizeWithInternalFields =
9595 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9598 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
9602 // Foreign describes objects pointing from JavaScript to C structures.
9603 class Foreign: public HeapObject {
9605 // [address]: field containing the address.
9606 inline Address foreign_address();
9607 inline void set_foreign_address(Address value);
9609 DECLARE_CAST(Foreign)
9611 // Dispatched behavior.
9612 inline void ForeignIterateBody(ObjectVisitor* v);
9614 template<typename StaticVisitor>
9615 inline void ForeignIterateBody();
9617 // Dispatched behavior.
9618 DECLARE_PRINTER(Foreign)
9619 DECLARE_VERIFIER(Foreign)
9621 // Layout description.
9623 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
9624 static const int kSize = kForeignAddressOffset + kPointerSize;
9626 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
9629 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
9633 // The JSArray describes JavaScript Arrays
9634 // Such an array can be in one of two modes:
9635 // - fast, backing storage is a FixedArray and length <= elements.length();
9636 // Please note: push and pop can be used to grow and shrink the array.
9637 // - slow, backing storage is a HashTable with numbers as keys.
9638 class JSArray: public JSObject {
9640 // [length]: The length property.
9641 DECL_ACCESSORS(length, Object)
9643 // Overload the length setter to skip write barrier when the length
9644 // is set to a smi. This matches the set function on FixedArray.
9645 inline void set_length(Smi* length);
9647 static bool HasReadOnlyLength(Handle<JSArray> array);
9648 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
9649 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
9651 // Initialize the array with the given capacity. The function may
9652 // fail due to out-of-memory situations, but only if the requested
9653 // capacity is non-zero.
9654 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
9656 // If the JSArray has fast elements, and new_length would result in
9657 // normalization, returns true.
9658 bool SetLengthWouldNormalize(uint32_t new_length);
9659 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
9661 // Initializes the array to a certain length.
9662 inline bool AllowsSetLength();
9664 static void SetLength(Handle<JSArray> array, uint32_t length);
9665 // Same as above but will also queue splice records if |array| is observed.
9666 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
9669 // Set the content of the array to the content of storage.
9670 static inline void SetContent(Handle<JSArray> array,
9671 Handle<FixedArrayBase> storage);
9673 DECLARE_CAST(JSArray)
9675 // Dispatched behavior.
9676 DECLARE_PRINTER(JSArray)
9677 DECLARE_VERIFIER(JSArray)
9679 // Number of element slots to pre-allocate for an empty array.
9680 static const int kPreallocatedArrayElements = 4;
9682 // Layout description.
9683 static const int kLengthOffset = JSObject::kHeaderSize;
9684 static const int kSize = kLengthOffset + kPointerSize;
9687 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
9691 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
9692 Handle<Map> initial_map);
9695 // JSRegExpResult is just a JSArray with a specific initial map.
9696 // This initial map adds in-object properties for "index" and "input"
9697 // properties, as assigned by RegExp.prototype.exec, which allows
9698 // faster creation of RegExp exec results.
9699 // This class just holds constants used when creating the result.
9700 // After creation the result must be treated as a JSArray in all regards.
9701 class JSRegExpResult: public JSArray {
9703 // Offsets of object fields.
9704 static const int kIndexOffset = JSArray::kSize;
9705 static const int kInputOffset = kIndexOffset + kPointerSize;
9706 static const int kSize = kInputOffset + kPointerSize;
9707 // Indices of in-object properties.
9708 static const int kIndexIndex = 0;
9709 static const int kInputIndex = 1;
9711 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
9715 class AccessorInfo: public Struct {
9717 DECL_ACCESSORS(name, Object)
9718 DECL_ACCESSORS(flag, Smi)
9719 DECL_ACCESSORS(expected_receiver_type, Object)
9721 inline bool all_can_read();
9722 inline void set_all_can_read(bool value);
9724 inline bool all_can_write();
9725 inline void set_all_can_write(bool value);
9727 inline bool is_special_data_property();
9728 inline void set_is_special_data_property(bool value);
9730 inline PropertyAttributes property_attributes();
9731 inline void set_property_attributes(PropertyAttributes attributes);
9733 // Checks whether the given receiver is compatible with this accessor.
9734 static bool IsCompatibleReceiverMap(Isolate* isolate,
9735 Handle<AccessorInfo> info,
9737 inline bool IsCompatibleReceiver(Object* receiver);
9739 DECLARE_CAST(AccessorInfo)
9741 // Dispatched behavior.
9742 DECLARE_VERIFIER(AccessorInfo)
9744 // Append all descriptors to the array that are not already there.
9745 // Return number added.
9746 static int AppendUnique(Handle<Object> descriptors,
9747 Handle<FixedArray> array,
9748 int valid_descriptors);
9750 static const int kNameOffset = HeapObject::kHeaderSize;
9751 static const int kFlagOffset = kNameOffset + kPointerSize;
9752 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
9753 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
9756 inline bool HasExpectedReceiverType();
9758 // Bit positions in flag.
9759 static const int kAllCanReadBit = 0;
9760 static const int kAllCanWriteBit = 1;
9761 static const int kSpecialDataProperty = 2;
9762 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
9764 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
9768 // An accessor must have a getter, but can have no setter.
9770 // When setting a property, V8 searches accessors in prototypes.
9771 // If an accessor was found and it does not have a setter,
9772 // the request is ignored.
9774 // If the accessor in the prototype has the READ_ONLY property attribute, then
9775 // a new value is added to the derived object when the property is set.
9776 // This shadows the accessor in the prototype.
9777 class ExecutableAccessorInfo: public AccessorInfo {
9779 DECL_ACCESSORS(getter, Object)
9780 DECL_ACCESSORS(setter, Object)
9781 DECL_ACCESSORS(data, Object)
9783 DECLARE_CAST(ExecutableAccessorInfo)
9785 // Dispatched behavior.
9786 DECLARE_PRINTER(ExecutableAccessorInfo)
9787 DECLARE_VERIFIER(ExecutableAccessorInfo)
9789 static const int kGetterOffset = AccessorInfo::kSize;
9790 static const int kSetterOffset = kGetterOffset + kPointerSize;
9791 static const int kDataOffset = kSetterOffset + kPointerSize;
9792 static const int kSize = kDataOffset + kPointerSize;
9794 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
9797 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
9801 // Support for JavaScript accessors: A pair of a getter and a setter. Each
9802 // accessor can either be
9803 // * a pointer to a JavaScript function or proxy: a real accessor
9804 // * undefined: considered an accessor by the spec, too, strangely enough
9805 // * the hole: an accessor which has not been set
9806 // * a pointer to a map: a transition used to ensure map sharing
9807 class AccessorPair: public Struct {
9809 DECL_ACCESSORS(getter, Object)
9810 DECL_ACCESSORS(setter, Object)
9812 DECLARE_CAST(AccessorPair)
9814 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
9816 inline Object* get(AccessorComponent component);
9817 inline void set(AccessorComponent component, Object* value);
9819 // Note: Returns undefined instead in case of a hole.
9820 Object* GetComponent(AccessorComponent component);
9822 // Set both components, skipping arguments which are a JavaScript null.
9823 inline void SetComponents(Object* getter, Object* setter);
9825 inline bool Equals(AccessorPair* pair);
9826 inline bool Equals(Object* getter_value, Object* setter_value);
9828 inline bool ContainsAccessor();
9830 // Dispatched behavior.
9831 DECLARE_PRINTER(AccessorPair)
9832 DECLARE_VERIFIER(AccessorPair)
9834 static const int kGetterOffset = HeapObject::kHeaderSize;
9835 static const int kSetterOffset = kGetterOffset + kPointerSize;
9836 static const int kSize = kSetterOffset + kPointerSize;
9839 // Strangely enough, in addition to functions and harmony proxies, the spec
9840 // requires us to consider undefined as a kind of accessor, too:
9842 // Object.defineProperty(obj, "foo", {get: undefined});
9843 // assertTrue("foo" in obj);
9844 inline bool IsJSAccessor(Object* obj);
9846 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
9850 class AccessCheckInfo: public Struct {
9852 DECL_ACCESSORS(named_callback, Object)
9853 DECL_ACCESSORS(indexed_callback, Object)
9854 DECL_ACCESSORS(data, Object)
9856 DECLARE_CAST(AccessCheckInfo)
9858 // Dispatched behavior.
9859 DECLARE_PRINTER(AccessCheckInfo)
9860 DECLARE_VERIFIER(AccessCheckInfo)
9862 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
9863 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
9864 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
9865 static const int kSize = kDataOffset + kPointerSize;
9868 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
9872 class InterceptorInfo: public Struct {
9874 DECL_ACCESSORS(getter, Object)
9875 DECL_ACCESSORS(setter, Object)
9876 DECL_ACCESSORS(query, Object)
9877 DECL_ACCESSORS(deleter, Object)
9878 DECL_ACCESSORS(enumerator, Object)
9879 DECL_ACCESSORS(data, Object)
9880 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
9881 DECL_BOOLEAN_ACCESSORS(all_can_read)
9882 DECL_BOOLEAN_ACCESSORS(non_masking)
9884 inline int flags() const;
9885 inline void set_flags(int flags);
9887 DECLARE_CAST(InterceptorInfo)
9889 // Dispatched behavior.
9890 DECLARE_PRINTER(InterceptorInfo)
9891 DECLARE_VERIFIER(InterceptorInfo)
9893 static const int kGetterOffset = HeapObject::kHeaderSize;
9894 static const int kSetterOffset = kGetterOffset + kPointerSize;
9895 static const int kQueryOffset = kSetterOffset + kPointerSize;
9896 static const int kDeleterOffset = kQueryOffset + kPointerSize;
9897 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
9898 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
9899 static const int kFlagsOffset = kDataOffset + kPointerSize;
9900 static const int kSize = kFlagsOffset + kPointerSize;
9902 static const int kCanInterceptSymbolsBit = 0;
9903 static const int kAllCanReadBit = 1;
9904 static const int kNonMasking = 2;
9907 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
9911 class CallHandlerInfo: public Struct {
9913 DECL_ACCESSORS(callback, Object)
9914 DECL_ACCESSORS(data, Object)
9916 DECLARE_CAST(CallHandlerInfo)
9918 // Dispatched behavior.
9919 DECLARE_PRINTER(CallHandlerInfo)
9920 DECLARE_VERIFIER(CallHandlerInfo)
9922 static const int kCallbackOffset = HeapObject::kHeaderSize;
9923 static const int kDataOffset = kCallbackOffset + kPointerSize;
9924 static const int kSize = kDataOffset + kPointerSize;
9927 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
9931 class TemplateInfo: public Struct {
9933 DECL_ACCESSORS(tag, Object)
9934 inline int number_of_properties() const;
9935 inline void set_number_of_properties(int value);
9936 DECL_ACCESSORS(property_list, Object)
9937 DECL_ACCESSORS(property_accessors, Object)
9939 DECLARE_VERIFIER(TemplateInfo)
9941 static const int kTagOffset = HeapObject::kHeaderSize;
9942 static const int kNumberOfProperties = kTagOffset + kPointerSize;
9943 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
9944 static const int kPropertyAccessorsOffset =
9945 kPropertyListOffset + kPointerSize;
9946 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
9949 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
9953 class FunctionTemplateInfo: public TemplateInfo {
9955 DECL_ACCESSORS(serial_number, Object)
9956 DECL_ACCESSORS(call_code, Object)
9957 DECL_ACCESSORS(prototype_template, Object)
9958 DECL_ACCESSORS(parent_template, Object)
9959 DECL_ACCESSORS(named_property_handler, Object)
9960 DECL_ACCESSORS(indexed_property_handler, Object)
9961 DECL_ACCESSORS(instance_template, Object)
9962 DECL_ACCESSORS(class_name, Object)
9963 DECL_ACCESSORS(signature, Object)
9964 DECL_ACCESSORS(instance_call_handler, Object)
9965 DECL_ACCESSORS(access_check_info, Object)
9966 DECL_ACCESSORS(flag, Smi)
9968 inline int length() const;
9969 inline void set_length(int value);
9971 // Following properties use flag bits.
9972 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
9973 DECL_BOOLEAN_ACCESSORS(undetectable)
9974 // If the bit is set, object instances created by this function
9975 // requires access check.
9976 DECL_BOOLEAN_ACCESSORS(needs_access_check)
9977 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
9978 DECL_BOOLEAN_ACCESSORS(remove_prototype)
9979 DECL_BOOLEAN_ACCESSORS(do_not_cache)
9980 DECL_BOOLEAN_ACCESSORS(instantiated)
9981 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
9983 DECLARE_CAST(FunctionTemplateInfo)
9985 // Dispatched behavior.
9986 DECLARE_PRINTER(FunctionTemplateInfo)
9987 DECLARE_VERIFIER(FunctionTemplateInfo)
9989 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
9990 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
9991 static const int kPrototypeTemplateOffset =
9992 kCallCodeOffset + kPointerSize;
9993 static const int kParentTemplateOffset =
9994 kPrototypeTemplateOffset + kPointerSize;
9995 static const int kNamedPropertyHandlerOffset =
9996 kParentTemplateOffset + kPointerSize;
9997 static const int kIndexedPropertyHandlerOffset =
9998 kNamedPropertyHandlerOffset + kPointerSize;
9999 static const int kInstanceTemplateOffset =
10000 kIndexedPropertyHandlerOffset + kPointerSize;
10001 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10002 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10003 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10004 static const int kAccessCheckInfoOffset =
10005 kInstanceCallHandlerOffset + kPointerSize;
10006 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10007 static const int kLengthOffset = kFlagOffset + kPointerSize;
10008 static const int kSize = kLengthOffset + kPointerSize;
10010 // Returns true if |object| is an instance of this function template.
10011 bool IsTemplateFor(Object* object);
10012 bool IsTemplateFor(Map* map);
10014 // Returns the holder JSObject if the function can legally be called with this
10015 // receiver. Returns Heap::null_value() if the call is illegal.
10016 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10019 // Bit position in the flag, from least significant bit position.
10020 static const int kHiddenPrototypeBit = 0;
10021 static const int kUndetectableBit = 1;
10022 static const int kNeedsAccessCheckBit = 2;
10023 static const int kReadOnlyPrototypeBit = 3;
10024 static const int kRemovePrototypeBit = 4;
10025 static const int kDoNotCacheBit = 5;
10026 static const int kInstantiatedBit = 6;
10027 static const int kAcceptAnyReceiver = 7;
10029 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10033 class ObjectTemplateInfo: public TemplateInfo {
10035 DECL_ACCESSORS(constructor, Object)
10036 DECL_ACCESSORS(internal_field_count, Object)
10038 DECLARE_CAST(ObjectTemplateInfo)
10040 // Dispatched behavior.
10041 DECLARE_PRINTER(ObjectTemplateInfo)
10042 DECLARE_VERIFIER(ObjectTemplateInfo)
10044 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10045 static const int kInternalFieldCountOffset =
10046 kConstructorOffset + kPointerSize;
10047 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10051 class TypeSwitchInfo: public Struct {
10053 DECL_ACCESSORS(types, Object)
10055 DECLARE_CAST(TypeSwitchInfo)
10057 // Dispatched behavior.
10058 DECLARE_PRINTER(TypeSwitchInfo)
10059 DECLARE_VERIFIER(TypeSwitchInfo)
10061 static const int kTypesOffset = Struct::kHeaderSize;
10062 static const int kSize = kTypesOffset + kPointerSize;
10066 // The DebugInfo class holds additional information for a function being
10068 class DebugInfo: public Struct {
10070 // The shared function info for the source being debugged.
10071 DECL_ACCESSORS(shared, SharedFunctionInfo)
10072 // Code object for the patched code. This code object is the code object
10073 // currently active for the function.
10074 DECL_ACCESSORS(code, Code)
10075 // Fixed array holding status information for each active break point.
10076 DECL_ACCESSORS(break_points, FixedArray)
10078 // Check if there is a break point at a code position.
10079 bool HasBreakPoint(int code_position);
10080 // Get the break point info object for a code position.
10081 Object* GetBreakPointInfo(int code_position);
10082 // Clear a break point.
10083 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10085 Handle<Object> break_point_object);
10086 // Set a break point.
10087 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10088 int source_position, int statement_position,
10089 Handle<Object> break_point_object);
10090 // Get the break point objects for a code position.
10091 Handle<Object> GetBreakPointObjects(int code_position);
10092 // Find the break point info holding this break point object.
10093 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10094 Handle<Object> break_point_object);
10095 // Get the number of break points for this function.
10096 int GetBreakPointCount();
10098 DECLARE_CAST(DebugInfo)
10100 // Dispatched behavior.
10101 DECLARE_PRINTER(DebugInfo)
10102 DECLARE_VERIFIER(DebugInfo)
10104 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10105 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10106 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10107 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10109 static const int kEstimatedNofBreakPointsInFunction = 16;
10112 static const int kNoBreakPointInfo = -1;
10114 // Lookup the index in the break_points array for a code position.
10115 int GetBreakPointInfoIndex(int code_position);
10117 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10121 // The BreakPointInfo class holds information for break points set in a
10122 // function. The DebugInfo object holds a BreakPointInfo object for each code
10123 // position with one or more break points.
10124 class BreakPointInfo: public Struct {
10126 // The position in the code for the break point.
10127 DECL_ACCESSORS(code_position, Smi)
10128 // The position in the source for the break position.
10129 DECL_ACCESSORS(source_position, Smi)
10130 // The position in the source for the last statement before this break
10132 DECL_ACCESSORS(statement_position, Smi)
10133 // List of related JavaScript break points.
10134 DECL_ACCESSORS(break_point_objects, Object)
10136 // Removes a break point.
10137 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10138 Handle<Object> break_point_object);
10139 // Set a break point.
10140 static void SetBreakPoint(Handle<BreakPointInfo> info,
10141 Handle<Object> break_point_object);
10142 // Check if break point info has this break point object.
10143 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10144 Handle<Object> break_point_object);
10145 // Get the number of break points for this code position.
10146 int GetBreakPointCount();
10148 DECLARE_CAST(BreakPointInfo)
10150 // Dispatched behavior.
10151 DECLARE_PRINTER(BreakPointInfo)
10152 DECLARE_VERIFIER(BreakPointInfo)
10154 static const int kCodePositionIndex = Struct::kHeaderSize;
10155 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10156 static const int kStatementPositionIndex =
10157 kSourcePositionIndex + kPointerSize;
10158 static const int kBreakPointObjectsIndex =
10159 kStatementPositionIndex + kPointerSize;
10160 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10163 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10167 #undef DECL_BOOLEAN_ACCESSORS
10168 #undef DECL_ACCESSORS
10169 #undef DECLARE_CAST
10170 #undef DECLARE_VERIFIER
10172 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10173 V(kStringTable, "string_table", "(Internalized strings)") \
10174 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10175 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10176 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10177 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10178 V(kTop, "top", "(Isolate)") \
10179 V(kRelocatable, "relocatable", "(Relocatable)") \
10180 V(kDebug, "debug", "(Debugger)") \
10181 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10182 V(kHandleScope, "handlescope", "(Handle scope)") \
10183 V(kBuiltins, "builtins", "(Builtins)") \
10184 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10185 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10186 V(kThreadManager, "threadmanager", "(Thread manager)") \
10187 V(kStrongRoots, "strong roots", "(Strong roots)") \
10188 V(kExtensions, "Extensions", "(Extensions)")
10190 class VisitorSynchronization : public AllStatic {
10192 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10194 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10197 #undef DECLARE_ENUM
10199 static const char* const kTags[kNumberOfSyncTags];
10200 static const char* const kTagNames[kNumberOfSyncTags];
10203 // Abstract base class for visiting, and optionally modifying, the
10204 // pointers contained in Objects. Used in GC and serialization/deserialization.
10205 class ObjectVisitor BASE_EMBEDDED {
10207 virtual ~ObjectVisitor() {}
10209 // Visits a contiguous arrays of pointers in the half-open range
10210 // [start, end). Any or all of the values may be modified on return.
10211 virtual void VisitPointers(Object** start, Object** end) = 0;
10213 // Handy shorthand for visiting a single pointer.
10214 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10216 // Visit weak next_code_link in Code object.
10217 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10219 // To allow lazy clearing of inline caches the visitor has
10220 // a rich interface for iterating over Code objects..
10222 // Visits a code target in the instruction stream.
10223 virtual void VisitCodeTarget(RelocInfo* rinfo);
10225 // Visits a code entry in a JS function.
10226 virtual void VisitCodeEntry(Address entry_address);
10228 // Visits a global property cell reference in the instruction stream.
10229 virtual void VisitCell(RelocInfo* rinfo);
10231 // Visits a runtime entry in the instruction stream.
10232 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10234 // Visits the resource of an one-byte or two-byte string.
10235 virtual void VisitExternalOneByteString(
10236 v8::String::ExternalOneByteStringResource** resource) {}
10237 virtual void VisitExternalTwoByteString(
10238 v8::String::ExternalStringResource** resource) {}
10240 // Visits a debug call target in the instruction stream.
10241 virtual void VisitDebugTarget(RelocInfo* rinfo);
10243 // Visits the byte sequence in a function's prologue that contains information
10244 // about the code's age.
10245 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10247 // Visit pointer embedded into a code object.
10248 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10250 // Visits an external reference embedded into a code object.
10251 virtual void VisitExternalReference(RelocInfo* rinfo);
10253 // Visits an external reference.
10254 virtual void VisitExternalReference(Address* p) {}
10256 // Visits an (encoded) internal reference.
10257 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10259 // Visits a handle that has an embedder-assigned class ID.
10260 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10262 // Intended for serialization/deserialization checking: insert, or
10263 // check for the presence of, a tag at this position in the stream.
10264 // Also used for marking up GC roots in heap snapshots.
10265 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10269 class StructBodyDescriptor : public
10270 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10272 static inline int SizeOf(Map* map, HeapObject* object);
10276 // BooleanBit is a helper class for setting and getting a bit in an
10278 class BooleanBit : public AllStatic {
10280 static inline bool get(Smi* smi, int bit_position) {
10281 return get(smi->value(), bit_position);
10284 static inline bool get(int value, int bit_position) {
10285 return (value & (1 << bit_position)) != 0;
10288 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10289 return Smi::FromInt(set(smi->value(), bit_position, v));
10292 static inline int set(int value, int bit_position, bool v) {
10294 value |= (1 << bit_position);
10296 value &= ~(1 << bit_position);
10302 } } // namespace v8::internal
10304 #endif // V8_OBJECTS_H_