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.
8 #include "src/allocation.h"
9 #include "src/assert-scope.h"
10 #include "src/bailout-reason.h"
11 #include "src/base/bits.h"
12 #include "src/builtins.h"
13 #include "src/checks.h"
14 #include "src/elements-kind.h"
15 #include "src/field-index.h"
16 #include "src/flags.h"
18 #include "src/property-details.h"
19 #include "src/smart-pointers.h"
20 #include "src/unicode-inl.h"
23 #if V8_TARGET_ARCH_ARM
24 #include "src/arm/constants-arm.h" // NOLINT
25 #elif V8_TARGET_ARCH_ARM64
26 #include "src/arm64/constants-arm64.h" // NOLINT
27 #elif V8_TARGET_ARCH_MIPS
28 #include "src/mips/constants-mips.h" // NOLINT
29 #elif V8_TARGET_ARCH_MIPS64
30 #include "src/mips64/constants-mips64.h" // NOLINT
35 // Most object types in the V8 JavaScript are described in this file.
37 // Inheritance hierarchy:
39 // - Smi (immediate small integer)
40 // - HeapObject (superclass for everything allocated in the heap)
41 // - JSReceiver (suitable for property access)
45 // - JSArrayBufferView
61 // - JSGeneratorObject
79 // - CompilationCacheTable
80 // - CodeCacheHashTable
86 // - TypeFeedbackVector
87 // - JSFunctionResultCache
92 // - ExternalUint8ClampedArray
93 // - ExternalInt8Array
94 // - ExternalUint8Array
95 // - ExternalInt16Array
96 // - ExternalUint16Array
97 // - ExternalInt32Array
98 // - ExternalUint32Array
99 // - ExternalFloat32Array
100 // - ExternalFloat32x4Array
101 // - ExternalFloat64x2Array
102 // - ExternalInt32x4Array
106 // - SeqOneByteString
107 // - SeqTwoByteString
111 // - ExternalOneByteString
112 // - ExternalTwoByteString
113 // - InternalizedString
114 // - SeqInternalizedString
115 // - SeqOneByteInternalizedString
116 // - SeqTwoByteInternalizedString
117 // - ConsInternalizedString
118 // - ExternalInternalizedString
119 // - ExternalOneByteInternalizedString
120 // - ExternalTwoByteInternalizedString
129 // - SharedFunctionInfo
132 // - DeclaredAccessorDescriptor
134 // - DeclaredAccessorInfo
135 // - ExecutableAccessorInfo
141 // - FunctionTemplateInfo
142 // - ObjectTemplateInfo
150 // Formats of Object*:
151 // Smi: [31 bit signed int] 0
152 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
159 enum KeyedAccessStoreMode {
161 STORE_TRANSITION_SMI_TO_OBJECT,
162 STORE_TRANSITION_SMI_TO_DOUBLE,
163 STORE_TRANSITION_DOUBLE_TO_OBJECT,
164 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
165 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
166 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
167 STORE_AND_GROW_NO_TRANSITION,
168 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
169 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
170 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
171 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
172 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
173 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
174 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
175 STORE_NO_TRANSITION_HANDLE_COW
179 enum ContextualMode {
191 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
193 STATIC_ASSERT(STANDARD_STORE == 0);
194 STATIC_ASSERT(kGrowICDelta ==
195 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
196 STORE_TRANSITION_SMI_TO_OBJECT);
197 STATIC_ASSERT(kGrowICDelta ==
198 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
199 STORE_TRANSITION_SMI_TO_DOUBLE);
200 STATIC_ASSERT(kGrowICDelta ==
201 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
202 STORE_TRANSITION_DOUBLE_TO_OBJECT);
205 static inline KeyedAccessStoreMode GetGrowStoreMode(
206 KeyedAccessStoreMode store_mode) {
207 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
208 store_mode = static_cast<KeyedAccessStoreMode>(
209 static_cast<int>(store_mode) + kGrowICDelta);
215 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
216 return store_mode > STANDARD_STORE &&
217 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
218 store_mode != STORE_AND_GROW_NO_TRANSITION;
222 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
223 KeyedAccessStoreMode store_mode) {
224 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
227 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
228 return STORE_AND_GROW_NO_TRANSITION;
230 return STANDARD_STORE;
234 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
235 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
236 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
240 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
241 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
244 // Indicates whether a value can be loaded as a constant.
251 // PropertyNormalizationMode is used to specify whether to keep
252 // inobject properties when normalizing properties of a JSObject.
253 enum PropertyNormalizationMode {
254 CLEAR_INOBJECT_PROPERTIES,
255 KEEP_INOBJECT_PROPERTIES
259 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
260 // will give the fastest result by tailoring the map to the prototype, but that
261 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
262 // (at least for now) when dynamically modifying the prototype chain of an
263 // object using __proto__ or Object.setPrototypeOf.
264 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
267 // Indicates whether transitions can be added to a source map or not.
268 enum TransitionFlag {
274 enum DebugExtraICState {
276 DEBUG_PREPARE_STEP_IN
280 // Indicates whether the transition is simple: the target map of the transition
281 // either extends the current map with a new property, or it modifies the
282 // property that was added last to the current map.
283 enum SimpleTransitionFlag {
289 // Indicates whether we are only interested in the descriptors of a particular
290 // map, or in all descriptors in the descriptor array.
291 enum DescriptorFlag {
296 // The GC maintains a bit of information, the MarkingParity, which toggles
297 // from odd to even and back every time marking is completed. Incremental
298 // marking can visit an object twice during a marking phase, so algorithms that
299 // that piggy-back on marking can use the parity to ensure that they only
300 // perform an operation on an object once per marking phase: they record the
301 // MarkingParity when they visit an object, and only re-visit the object when it
302 // is marked again and the MarkingParity changes.
309 // ICs store extra state in a Code object. The default extra state is
311 typedef int ExtraICState;
312 static const ExtraICState kNoExtraICState = 0;
314 // Instance size sentinel for objects of variable size.
315 const int kVariableSizeSentinel = 0;
317 // We may store the unsigned bit field as signed Smi value and do not
319 const int kStubMajorKeyBits = 7;
320 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
322 // All Maps have a field instance_type containing a InstanceType.
323 // It describes the type of the instances.
325 // As an example, a JavaScript object is a heap object and its map
326 // instance_type is JS_OBJECT_TYPE.
328 // The names of the string instance types are intended to systematically
329 // mirror their encoding in the instance_type field of the map. The default
330 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
331 // encoding is mentioned explicitly in the name. Likewise, the default
332 // representation is considered sequential. It is not mentioned in the
333 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
334 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
335 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
337 // NOTE: The following things are some that depend on the string types having
338 // instance_types that are less than those of all other types:
339 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
342 // NOTE: Everything following JS_VALUE_TYPE is considered a
343 // JSObject for GC purposes. The first four entries here have typeof
344 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
345 #define INSTANCE_TYPE_LIST(V) \
347 V(ONE_BYTE_STRING_TYPE) \
348 V(CONS_STRING_TYPE) \
349 V(CONS_ONE_BYTE_STRING_TYPE) \
350 V(SLICED_STRING_TYPE) \
351 V(SLICED_ONE_BYTE_STRING_TYPE) \
352 V(EXTERNAL_STRING_TYPE) \
353 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
354 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
355 V(SHORT_EXTERNAL_STRING_TYPE) \
356 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
357 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
359 V(INTERNALIZED_STRING_TYPE) \
360 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
361 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
362 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
363 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
364 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
365 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
366 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
374 V(PROPERTY_CELL_TYPE) \
376 V(HEAP_NUMBER_TYPE) \
377 V(MUTABLE_HEAP_NUMBER_TYPE) \
381 /* Note: the order of these external array */ \
382 /* types is relied upon in */ \
383 /* Object::IsExternalArray(). */ \
384 V(EXTERNAL_INT8_ARRAY_TYPE) \
385 V(EXTERNAL_UINT8_ARRAY_TYPE) \
386 V(EXTERNAL_INT16_ARRAY_TYPE) \
387 V(EXTERNAL_UINT16_ARRAY_TYPE) \
388 V(EXTERNAL_INT32_ARRAY_TYPE) \
389 V(EXTERNAL_UINT32_ARRAY_TYPE) \
390 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
391 V(EXTERNAL_FLOAT32x4_ARRAY_TYPE) \
392 V(EXTERNAL_FLOAT64x2_ARRAY_TYPE) \
393 V(EXTERNAL_INT32x4_ARRAY_TYPE) \
394 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
395 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
397 V(FIXED_INT8_ARRAY_TYPE) \
398 V(FIXED_UINT8_ARRAY_TYPE) \
399 V(FIXED_INT16_ARRAY_TYPE) \
400 V(FIXED_UINT16_ARRAY_TYPE) \
401 V(FIXED_INT32_ARRAY_TYPE) \
402 V(FIXED_UINT32_ARRAY_TYPE) \
403 V(FIXED_FLOAT32_ARRAY_TYPE) \
404 V(FIXED_FLOAT32x4_ARRAY_TYPE) \
405 V(FIXED_INT32x4_ARRAY_TYPE) \
406 V(FIXED_FLOAT64x2_ARRAY_TYPE) \
407 V(FIXED_FLOAT64_ARRAY_TYPE) \
408 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
412 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
413 V(DECLARED_ACCESSOR_INFO_TYPE) \
414 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
415 V(ACCESSOR_PAIR_TYPE) \
416 V(ACCESS_CHECK_INFO_TYPE) \
417 V(INTERCEPTOR_INFO_TYPE) \
418 V(CALL_HANDLER_INFO_TYPE) \
419 V(FUNCTION_TEMPLATE_INFO_TYPE) \
420 V(OBJECT_TEMPLATE_INFO_TYPE) \
421 V(SIGNATURE_INFO_TYPE) \
422 V(TYPE_SWITCH_INFO_TYPE) \
423 V(ALLOCATION_MEMENTO_TYPE) \
424 V(ALLOCATION_SITE_TYPE) \
427 V(POLYMORPHIC_CODE_CACHE_TYPE) \
428 V(TYPE_FEEDBACK_INFO_TYPE) \
429 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
432 V(FIXED_ARRAY_TYPE) \
433 V(FIXED_DOUBLE_ARRAY_TYPE) \
434 V(CONSTANT_POOL_ARRAY_TYPE) \
435 V(SHARED_FUNCTION_INFO_TYPE) \
437 V(JS_MESSAGE_OBJECT_TYPE) \
442 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
443 V(JS_GENERATOR_OBJECT_TYPE) \
445 V(JS_GLOBAL_OBJECT_TYPE) \
446 V(JS_BUILTINS_OBJECT_TYPE) \
447 V(JS_GLOBAL_PROXY_TYPE) \
449 V(JS_ARRAY_BUFFER_TYPE) \
450 V(JS_TYPED_ARRAY_TYPE) \
451 V(JS_DATA_VIEW_TYPE) \
458 V(JS_SET_ITERATOR_TYPE) \
459 V(JS_MAP_ITERATOR_TYPE) \
460 V(JS_WEAK_MAP_TYPE) \
461 V(JS_WEAK_SET_TYPE) \
464 V(JS_FUNCTION_TYPE) \
465 V(JS_FUNCTION_PROXY_TYPE) \
467 V(BREAK_POINT_INFO_TYPE)
470 // Since string types are not consecutive, this macro is used to
471 // iterate over them.
472 #define STRING_TYPE_LIST(V) \
473 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
474 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
476 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
477 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
479 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
480 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
481 SlicedOneByteString) \
482 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
484 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
485 external_one_byte_string, ExternalOneByteString) \
486 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
487 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
488 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
489 short_external_string, ShortExternalString) \
490 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
491 short_external_one_byte_string, ShortExternalOneByteString) \
492 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
493 ExternalTwoByteString::kShortSize, \
494 short_external_string_with_one_byte_data, \
495 ShortExternalStringWithOneByteData) \
497 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
498 InternalizedString) \
499 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
500 one_byte_internalized_string, OneByteInternalizedString) \
501 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
502 external_internalized_string, ExternalInternalizedString) \
503 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
504 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
505 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
506 ExternalTwoByteString::kSize, \
507 external_internalized_string_with_one_byte_data, \
508 ExternalInternalizedStringWithOneByteData) \
509 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
510 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
511 ShortExternalInternalizedString) \
512 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
513 ExternalOneByteString::kShortSize, \
514 short_external_one_byte_internalized_string, \
515 ShortExternalOneByteInternalizedString) \
516 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
517 ExternalTwoByteString::kShortSize, \
518 short_external_internalized_string_with_one_byte_data, \
519 ShortExternalInternalizedStringWithOneByteData)
521 // A struct is a simple object a set of object-valued fields. Including an
522 // object type in this causes the compiler to generate most of the boilerplate
523 // code for the class including allocation and garbage collection routines,
524 // casts and predicates. All you need to define is the class, methods and
525 // object verification routines. Easy, no?
527 // Note that for subtle reasons related to the ordering or numerical values of
528 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
530 #define STRUCT_LIST(V) \
532 V(DECLARED_ACCESSOR_DESCRIPTOR, \
533 DeclaredAccessorDescriptor, \
534 declared_accessor_descriptor) \
535 V(DECLARED_ACCESSOR_INFO, DeclaredAccessorInfo, declared_accessor_info) \
536 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
537 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
538 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
539 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
540 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
541 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
542 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
543 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
544 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
545 V(SCRIPT, Script, script) \
546 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
547 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
548 V(CODE_CACHE, CodeCache, code_cache) \
549 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
550 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
551 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
552 V(DEBUG_INFO, DebugInfo, debug_info) \
553 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
555 // We use the full 8 bits of the instance_type field to encode heap object
556 // instance types. The high-order bit (bit 7) is set if the object is not a
557 // string, and cleared if it is a string.
558 const uint32_t kIsNotStringMask = 0x80;
559 const uint32_t kStringTag = 0x0;
560 const uint32_t kNotStringTag = 0x80;
562 // Bit 6 indicates that the object is an internalized string (if set) or not.
563 // Bit 7 has to be clear as well.
564 const uint32_t kIsNotInternalizedMask = 0x40;
565 const uint32_t kNotInternalizedTag = 0x40;
566 const uint32_t kInternalizedTag = 0x0;
568 // If bit 7 is clear then bit 2 indicates whether the string consists of
569 // two-byte characters or one-byte characters.
570 const uint32_t kStringEncodingMask = 0x4;
571 const uint32_t kTwoByteStringTag = 0x0;
572 const uint32_t kOneByteStringTag = 0x4;
574 // If bit 7 is clear, the low-order 2 bits indicate the representation
576 const uint32_t kStringRepresentationMask = 0x03;
577 enum StringRepresentationTag {
579 kConsStringTag = 0x1,
580 kExternalStringTag = 0x2,
581 kSlicedStringTag = 0x3
583 const uint32_t kIsIndirectStringMask = 0x1;
584 const uint32_t kIsIndirectStringTag = 0x1;
585 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
586 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
587 STATIC_ASSERT((kConsStringTag &
588 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
589 STATIC_ASSERT((kSlicedStringTag &
590 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
592 // Use this mask to distinguish between cons and slice only after making
593 // sure that the string is one of the two (an indirect string).
594 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
595 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
597 // If bit 7 is clear, then bit 3 indicates whether this two-byte
598 // string actually contains one byte data.
599 const uint32_t kOneByteDataHintMask = 0x08;
600 const uint32_t kOneByteDataHintTag = 0x08;
602 // If bit 7 is clear and string representation indicates an external string,
603 // then bit 4 indicates whether the data pointer is cached.
604 const uint32_t kShortExternalStringMask = 0x10;
605 const uint32_t kShortExternalStringTag = 0x10;
608 // A ConsString with an empty string as the right side is a candidate
609 // for being shortcut by the garbage collector. We don't allocate any
610 // non-flat internalized strings, so we do not shortcut them thereby
611 // avoiding turning internalized strings into strings. The bit-masks
612 // below contain the internalized bit as additional safety.
613 // See heap.cc, mark-compact.cc and objects-visiting.cc.
614 const uint32_t kShortcutTypeMask =
616 kIsNotInternalizedMask |
617 kStringRepresentationMask;
618 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
620 static inline bool IsShortcutCandidate(int type) {
621 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
627 INTERNALIZED_STRING_TYPE =
628 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
629 ONE_BYTE_INTERNALIZED_STRING_TYPE =
630 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
631 EXTERNAL_INTERNALIZED_STRING_TYPE =
632 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
633 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
634 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
635 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
636 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
638 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
639 kShortExternalStringTag |
641 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
642 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
644 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
645 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
646 kShortExternalStringTag | kInternalizedTag,
647 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
648 ONE_BYTE_STRING_TYPE =
649 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
650 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
651 CONS_ONE_BYTE_STRING_TYPE =
652 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
654 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
655 SLICED_ONE_BYTE_STRING_TYPE =
656 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
657 EXTERNAL_STRING_TYPE =
658 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
659 EXTERNAL_ONE_BYTE_STRING_TYPE =
660 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
661 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
662 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
664 SHORT_EXTERNAL_STRING_TYPE =
665 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
666 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
667 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
668 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
669 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
673 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
675 // Objects allocated in their own spaces (never in new space).
682 // "Data", objects that cannot contain non-map-word pointers to heap
685 MUTABLE_HEAP_NUMBER_TYPE,
689 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
690 EXTERNAL_UINT8_ARRAY_TYPE,
691 EXTERNAL_INT16_ARRAY_TYPE,
692 EXTERNAL_UINT16_ARRAY_TYPE,
693 EXTERNAL_INT32_ARRAY_TYPE,
694 EXTERNAL_UINT32_ARRAY_TYPE,
695 EXTERNAL_FLOAT32_ARRAY_TYPE,
696 EXTERNAL_FLOAT32x4_ARRAY_TYPE,
697 EXTERNAL_FLOAT64x2_ARRAY_TYPE,
698 EXTERNAL_INT32x4_ARRAY_TYPE,
699 EXTERNAL_FLOAT64_ARRAY_TYPE,
700 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
701 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
702 FIXED_UINT8_ARRAY_TYPE,
703 FIXED_INT16_ARRAY_TYPE,
704 FIXED_UINT16_ARRAY_TYPE,
705 FIXED_INT32_ARRAY_TYPE,
706 FIXED_INT32x4_ARRAY_TYPE,
707 FIXED_UINT32_ARRAY_TYPE,
708 FIXED_FLOAT32_ARRAY_TYPE,
709 FIXED_FLOAT32x4_ARRAY_TYPE,
710 FIXED_FLOAT64x2_ARRAY_TYPE,
711 FIXED_FLOAT64_ARRAY_TYPE,
712 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
713 FIXED_DOUBLE_ARRAY_TYPE,
714 FILLER_TYPE, // LAST_DATA_TYPE
717 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
718 DECLARED_ACCESSOR_INFO_TYPE,
719 EXECUTABLE_ACCESSOR_INFO_TYPE,
721 ACCESS_CHECK_INFO_TYPE,
722 INTERCEPTOR_INFO_TYPE,
723 CALL_HANDLER_INFO_TYPE,
724 FUNCTION_TEMPLATE_INFO_TYPE,
725 OBJECT_TEMPLATE_INFO_TYPE,
727 TYPE_SWITCH_INFO_TYPE,
728 ALLOCATION_SITE_TYPE,
729 ALLOCATION_MEMENTO_TYPE,
732 POLYMORPHIC_CODE_CACHE_TYPE,
733 TYPE_FEEDBACK_INFO_TYPE,
734 ALIASED_ARGUMENTS_ENTRY_TYPE,
737 BREAK_POINT_INFO_TYPE,
739 CONSTANT_POOL_ARRAY_TYPE,
740 SHARED_FUNCTION_INFO_TYPE,
742 // All the following types are subtypes of JSReceiver, which corresponds to
743 // objects in the JS sense. The first and the last type in this range are
744 // the two forms of function. This organization enables using the same
745 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
746 // NONCALLABLE_JS_OBJECT range.
747 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
748 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
749 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
750 JS_MESSAGE_OBJECT_TYPE,
753 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
754 JS_GENERATOR_OBJECT_TYPE,
756 JS_GLOBAL_OBJECT_TYPE,
757 JS_BUILTINS_OBJECT_TYPE,
758 JS_GLOBAL_PROXY_TYPE,
760 JS_ARRAY_BUFFER_TYPE,
768 JS_SET_ITERATOR_TYPE,
769 JS_MAP_ITERATOR_TYPE,
773 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
777 LAST_TYPE = JS_FUNCTION_TYPE,
778 FIRST_NAME_TYPE = FIRST_TYPE,
779 LAST_NAME_TYPE = SYMBOL_TYPE,
780 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
781 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
782 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
783 // Boundaries for testing for an external array.
784 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
785 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
786 // Boundaries for testing for a fixed typed array.
787 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
788 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
789 // Boundary for promotion to old data space/old pointer space.
790 LAST_DATA_TYPE = FILLER_TYPE,
791 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
792 // Note that there is no range for JSObject or JSProxy, since their subtypes
793 // are not continuous in this enum! The enum ranges instead reflect the
794 // external class names, where proxies are treated as either ordinary objects,
796 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
797 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
798 // Boundaries for testing the types represented as JSObject
799 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
800 LAST_JS_OBJECT_TYPE = LAST_TYPE,
801 // Boundaries for testing the types represented as JSProxy
802 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
803 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
804 // Boundaries for testing whether the type is a JavaScript object.
805 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
806 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
807 // Boundaries for testing the types for which typeof is "object".
808 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
809 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
810 // Note that the types for which typeof is "function" are not continuous.
811 // Define this so that we can put assertions on discrete checks.
812 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
815 const int kExternalArrayTypeCount =
816 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
818 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
819 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
820 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
821 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
824 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
825 V(FAST_ELEMENTS_SUB_TYPE) \
826 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
827 V(FAST_PROPERTIES_SUB_TYPE) \
828 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
829 V(MAP_CODE_CACHE_SUB_TYPE) \
830 V(SCOPE_INFO_SUB_TYPE) \
831 V(STRING_TABLE_SUB_TYPE) \
832 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
833 V(TRANSITION_ARRAY_SUB_TYPE)
835 enum FixedArraySubInstanceType {
836 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
837 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
838 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
839 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
852 #define DECL_BOOLEAN_ACCESSORS(name) \
853 inline bool name() const; \
854 inline void set_##name(bool value); \
857 #define DECL_ACCESSORS(name, type) \
858 inline type* name() const; \
859 inline void set_##name(type* value, \
860 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
863 #define DECLARE_CAST(type) \
864 INLINE(static type* cast(Object* object)); \
865 INLINE(static const type* cast(const Object* object));
869 class AllocationSite;
870 class AllocationSiteCreationContext;
871 class AllocationSiteUsageContext;
872 class DictionaryElementsAccessor;
873 class ElementsAccessor;
874 class FixedArrayBase;
877 class LookupIterator;
879 class TypeFeedbackVector;
880 // We cannot just say "class HeapType;" if it is created from a template... =8-?
881 template<class> class TypeImpl;
882 struct HeapTypeConfig;
883 typedef TypeImpl<HeapTypeConfig> HeapType;
886 // A template-ized version of the IsXXX functions.
887 template <class C> inline bool Is(Object* obj);
890 #define DECLARE_VERIFIER(Name) void Name##Verify();
892 #define DECLARE_VERIFIER(Name)
896 #define DECLARE_PRINTER(Name) void Name##Print(OStream& os); // NOLINT
898 #define DECLARE_PRINTER(Name)
902 #define OBJECT_TYPE_LIST(V) \
907 #define HEAP_OBJECT_TYPE_LIST(V) \
909 V(MutableHeapNumber) \
917 V(ExternalTwoByteString) \
918 V(ExternalOneByteString) \
919 V(SeqTwoByteString) \
920 V(SeqOneByteString) \
921 V(InternalizedString) \
925 V(ExternalInt8Array) \
926 V(ExternalUint8Array) \
927 V(ExternalInt16Array) \
928 V(ExternalUint16Array) \
929 V(ExternalInt32Array) \
930 V(ExternalUint32Array) \
931 V(ExternalFloat32Array) \
932 V(ExternalFloat32x4Array) \
933 V(ExternalFloat64x2Array) \
934 V(ExternalInt32x4Array) \
935 V(ExternalFloat64Array) \
936 V(ExternalUint8ClampedArray) \
937 V(FixedTypedArrayBase) \
940 V(FixedUint16Array) \
942 V(FixedUint32Array) \
944 V(FixedFloat32Array) \
945 V(FixedFloat32x4Array) \
946 V(FixedFloat64x2Array) \
947 V(FixedInt32x4Array) \
948 V(FixedFloat64Array) \
949 V(FixedUint8ClampedArray) \
954 V(JSContextExtensionObject) \
955 V(JSGeneratorObject) \
960 V(TypeFeedbackVector) \
961 V(DeoptimizationInputData) \
962 V(DeoptimizationOutputData) \
965 V(FixedDoubleArray) \
966 V(ConstantPoolArray) \
973 V(SharedFunctionInfo) \
982 V(JSArrayBufferView) \
994 V(JSWeakCollection) \
1001 V(JSFunctionResultCache) \
1002 V(NormalizedMapCache) \
1003 V(CompilationCacheTable) \
1004 V(CodeCacheHashTable) \
1005 V(PolymorphicCodeCacheHashTable) \
1010 V(JSBuiltinsObject) \
1012 V(UndetectableObject) \
1013 V(AccessCheckNeeded) \
1016 V(ObjectHashTable) \
1020 // Object is the abstract superclass for all classes in the
1021 // object hierarchy.
1022 // Object does not use any virtual functions to avoid the
1023 // allocation of the C++ vtable.
1024 // Since both Smi and HeapObject are subclasses of Object no
1025 // data members can be present in Object.
1029 bool IsObject() const { return true; }
1031 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1032 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1033 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1034 #undef IS_TYPE_FUNCTION_DECL
1036 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1037 // a keyed store is of the form a[expression] = foo.
1038 enum StoreFromKeyed {
1039 MAY_BE_STORE_FROM_KEYED,
1040 CERTAINLY_NOT_STORE_FROM_KEYED
1043 INLINE(bool IsFixedArrayBase() const);
1044 INLINE(bool IsExternal() const);
1045 INLINE(bool IsAccessorInfo() const);
1047 INLINE(bool IsStruct() const);
1048 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1049 INLINE(bool Is##Name() const);
1050 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1051 #undef DECLARE_STRUCT_PREDICATE
1053 INLINE(bool IsSpecObject()) const;
1054 INLINE(bool IsSpecFunction()) const;
1055 INLINE(bool IsTemplateInfo()) const;
1056 INLINE(bool IsNameDictionary() const);
1057 INLINE(bool IsSeededNumberDictionary() const);
1058 INLINE(bool IsUnseededNumberDictionary() const);
1059 INLINE(bool IsOrderedHashSet() const);
1060 INLINE(bool IsOrderedHashMap() const);
1061 bool IsCallable() const;
1064 INLINE(bool IsUndefined() const);
1065 INLINE(bool IsNull() const);
1066 INLINE(bool IsTheHole() const);
1067 INLINE(bool IsException() const);
1068 INLINE(bool IsUninitialized() const);
1069 INLINE(bool IsTrue() const);
1070 INLINE(bool IsFalse() const);
1071 INLINE(bool IsArgumentsMarker() const);
1073 // Filler objects (fillers and free space objects).
1074 INLINE(bool IsFiller() const);
1076 // Extract the number.
1077 inline double Number();
1078 INLINE(bool IsNaN() const);
1079 INLINE(bool IsMinusZero() const);
1080 bool ToInt32(int32_t* value);
1081 bool ToUint32(uint32_t* value);
1083 inline Representation OptimalRepresentation() {
1084 if (!FLAG_track_fields) return Representation::Tagged();
1086 return Representation::Smi();
1087 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1088 return Representation::Double();
1089 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1090 return Representation::None();
1091 } else if (FLAG_track_heap_object_fields) {
1092 DCHECK(IsHeapObject());
1093 return Representation::HeapObject();
1095 return Representation::Tagged();
1099 inline bool FitsRepresentation(Representation representation) {
1100 if (FLAG_track_fields && representation.IsNone()) {
1102 } else if (FLAG_track_fields && representation.IsSmi()) {
1104 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1105 return IsMutableHeapNumber() || IsNumber();
1106 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1107 return IsHeapObject();
1112 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1114 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1115 Handle<Object> object,
1116 Representation representation);
1118 inline static Handle<Object> WrapForRead(Isolate* isolate,
1119 Handle<Object> object,
1120 Representation representation);
1122 // Returns true if the object is of the correct type to be used as a
1123 // implementation of a JSObject's elements.
1124 inline bool HasValidElements();
1126 inline bool HasSpecificClassOf(String* name);
1128 bool BooleanValue(); // ECMA-262 9.2.
1130 // Convert to a JSObject if needed.
1131 // native_context is used when creating wrapper object.
1132 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1133 Handle<Object> object);
1134 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1135 Handle<Object> object,
1136 Handle<Context> context);
1138 // Converts this to a Smi if possible.
1139 static MUST_USE_RESULT inline MaybeHandle<Smi> ToSmi(Isolate* isolate,
1140 Handle<Object> object);
1142 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(LookupIterator* it);
1144 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1145 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1146 Handle<Object> object, Handle<Name> key, Handle<Object> value,
1147 StrictMode strict_mode,
1148 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1150 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1151 LookupIterator* it, Handle<Object> value, StrictMode strict_mode,
1152 StoreFromKeyed store_mode);
1153 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1154 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
1155 static Handle<Object> SetDataProperty(LookupIterator* it,
1156 Handle<Object> value);
1157 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1158 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1159 StrictMode strict_mode, StoreFromKeyed store_mode);
1160 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1161 Handle<Object> object,
1163 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1165 Handle<Object> object,
1167 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1168 Handle<Object> object,
1171 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1172 Handle<Object> receiver,
1174 Handle<JSObject> holder,
1175 Handle<Object> structure);
1176 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1177 Handle<Object> receiver, Handle<Name> name, Handle<Object> value,
1178 Handle<JSObject> holder, Handle<Object> structure,
1179 StrictMode strict_mode);
1181 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1182 Handle<Object> receiver,
1183 Handle<JSReceiver> getter);
1184 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1185 Handle<Object> receiver,
1186 Handle<JSReceiver> setter,
1187 Handle<Object> value);
1189 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1191 Handle<Object> object,
1194 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithReceiver(
1196 Handle<Object> object,
1197 Handle<Object> receiver,
1200 // Returns the permanent hash code associated with this object. May return
1201 // undefined if not yet created.
1204 // Returns the permanent hash code associated with this object depending on
1205 // the actual object type. May create and store a hash code if needed and none
1207 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1209 // Checks whether this object has the same value as the given one. This
1210 // function is implemented according to ES5, section 9.12 and can be used
1211 // to implement the Harmony "egal" function.
1212 bool SameValue(Object* other);
1214 // Checks whether this object has the same value as the given one.
1215 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1216 // This function is implemented according to ES6, section 7.2.4 and is used
1217 // by ES6 Map and Set.
1218 bool SameValueZero(Object* other);
1220 // Tries to convert an object to an array index. Returns true and sets
1221 // the output parameter if it succeeds.
1222 inline bool ToArrayIndex(uint32_t* index);
1224 // Returns true if this is a JSValue containing a string and the index is
1225 // < the length of the string. Used to implement [] on strings.
1226 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1228 DECLARE_VERIFIER(Object)
1230 // Verify a pointer is a valid object pointer.
1231 static void VerifyPointer(Object* p);
1234 inline void VerifyApiCallResultType();
1236 // Prints this object without details.
1237 void ShortPrint(FILE* out = stdout);
1239 // Prints this object without details to a message accumulator.
1240 void ShortPrint(StringStream* accumulator);
1242 DECLARE_CAST(Object)
1244 // Layout description.
1245 static const int kHeaderSize = 0; // Object does not take up any space.
1248 // For our gdb macros, we should perhaps change these in the future.
1251 // Prints this object with details.
1252 void Print(OStream& os); // NOLINT
1256 friend class LookupIterator;
1257 friend class PrototypeIterator;
1259 // Return the map of the root of object's prototype chain.
1260 Map* GetRootMap(Isolate* isolate);
1262 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1267 explicit Brief(const Object* const v) : value(v) {}
1268 const Object* value;
1272 OStream& operator<<(OStream& os, const Brief& v);
1275 // Smi represents integer Numbers that can be stored in 31 bits.
1276 // Smis are immediate which means they are NOT allocated in the heap.
1277 // The this pointer has the following format: [31 bit signed int] 0
1278 // For long smis it has the following format:
1279 // [32 bit signed int] [31 bits zero padding] 0
1280 // Smi stands for small integer.
1281 class Smi: public Object {
1283 // Returns the integer value.
1284 inline int value() const;
1286 // Convert a value to a Smi object.
1287 static inline Smi* FromInt(int value);
1289 static inline Smi* FromIntptr(intptr_t value);
1291 // Returns whether value can be represented in a Smi.
1292 static inline bool IsValid(intptr_t value);
1296 // Dispatched behavior.
1297 void SmiPrint(OStream& os) const; // NOLINT
1298 DECLARE_VERIFIER(Smi)
1300 static const int kMinValue =
1301 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1302 static const int kMaxValue = -(kMinValue + 1);
1305 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1309 // Heap objects typically have a map pointer in their first word. However,
1310 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1311 // encoded in the first word. The class MapWord is an abstraction of the
1312 // value in a heap object's first word.
1313 class MapWord BASE_EMBEDDED {
1315 // Normal state: the map word contains a map pointer.
1317 // Create a map word from a map pointer.
1318 static inline MapWord FromMap(const Map* map);
1320 // View this map word as a map pointer.
1321 inline Map* ToMap();
1324 // Scavenge collection: the map word of live objects in the from space
1325 // contains a forwarding address (a heap object pointer in the to space).
1327 // True if this map word is a forwarding address for a scavenge
1328 // collection. Only valid during a scavenge collection (specifically,
1329 // when all map words are heap object pointers, i.e. not during a full GC).
1330 inline bool IsForwardingAddress();
1332 // Create a map word from a forwarding address.
1333 static inline MapWord FromForwardingAddress(HeapObject* object);
1335 // View this map word as a forwarding address.
1336 inline HeapObject* ToForwardingAddress();
1338 static inline MapWord FromRawValue(uintptr_t value) {
1339 return MapWord(value);
1342 inline uintptr_t ToRawValue() {
1347 // HeapObject calls the private constructor and directly reads the value.
1348 friend class HeapObject;
1350 explicit MapWord(uintptr_t value) : value_(value) {}
1356 // HeapObject is the superclass for all classes describing heap allocated
1358 class HeapObject: public Object {
1360 // [map]: Contains a map which contains the object's reflective
1362 inline Map* map() const;
1363 inline void set_map(Map* value);
1364 // The no-write-barrier version. This is OK if the object is white and in
1365 // new space, or if the value is an immortal immutable object, like the maps
1366 // of primitive (non-JS) objects like strings, heap numbers etc.
1367 inline void set_map_no_write_barrier(Map* value);
1369 // Get the map using acquire load.
1370 inline Map* synchronized_map();
1371 inline MapWord synchronized_map_word() const;
1373 // Set the map using release store
1374 inline void synchronized_set_map(Map* value);
1375 inline void synchronized_set_map_no_write_barrier(Map* value);
1376 inline void synchronized_set_map_word(MapWord map_word);
1378 // During garbage collection, the map word of a heap object does not
1379 // necessarily contain a map pointer.
1380 inline MapWord map_word() const;
1381 inline void set_map_word(MapWord map_word);
1383 // The Heap the object was allocated in. Used also to access Isolate.
1384 inline Heap* GetHeap() const;
1386 // Convenience method to get current isolate.
1387 inline Isolate* GetIsolate() const;
1389 // Converts an address to a HeapObject pointer.
1390 static inline HeapObject* FromAddress(Address address);
1392 // Returns the address of this HeapObject.
1393 inline Address address();
1395 // Iterates over pointers contained in the object (including the Map)
1396 void Iterate(ObjectVisitor* v);
1398 // Iterates over all pointers contained in the object except the
1399 // first map pointer. The object type is given in the first
1400 // parameter. This function does not access the map pointer in the
1401 // object, and so is safe to call while the map pointer is modified.
1402 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1404 // Returns the heap object's size in bytes
1407 // Returns true if this heap object may contain raw values, i.e., values that
1408 // look like pointers to heap objects.
1409 inline bool MayContainRawValues();
1411 // Given a heap object's map pointer, returns the heap size in bytes
1412 // Useful when the map pointer field is used for other purposes.
1414 inline int SizeFromMap(Map* map);
1416 // Returns the field at offset in obj, as a read/write Object* reference.
1417 // Does no checking, and is safe to use during GC, while maps are invalid.
1418 // Does not invoke write barrier, so should only be assigned to
1419 // during marking GC.
1420 static inline Object** RawField(HeapObject* obj, int offset);
1422 // Adds the |code| object related to |name| to the code cache of this map. If
1423 // this map is a dictionary map that is shared, the map copied and installed
1425 static void UpdateMapCodeCache(Handle<HeapObject> object,
1429 DECLARE_CAST(HeapObject)
1431 // Return the write barrier mode for this. Callers of this function
1432 // must be able to present a reference to an DisallowHeapAllocation
1433 // object as a sign that they are not going to use this function
1434 // from code that allocates and thus invalidates the returned write
1436 inline WriteBarrierMode GetWriteBarrierMode(
1437 const DisallowHeapAllocation& promise);
1439 // Dispatched behavior.
1440 void HeapObjectShortPrint(OStream& os); // NOLINT
1442 void PrintHeader(OStream& os, const char* id); // NOLINT
1444 DECLARE_PRINTER(HeapObject)
1445 DECLARE_VERIFIER(HeapObject)
1447 inline void VerifyObjectField(int offset);
1448 inline void VerifySmiField(int offset);
1450 // Verify a pointer is a valid HeapObject pointer that points to object
1451 // areas in the heap.
1452 static void VerifyHeapPointer(Object* p);
1455 // Layout description.
1456 // First field in a heap object is map.
1457 static const int kMapOffset = Object::kHeaderSize;
1458 static const int kHeaderSize = kMapOffset + kPointerSize;
1460 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1463 // helpers for calling an ObjectVisitor to iterate over pointers in the
1464 // half-open range [start, end) specified as integer offsets
1465 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1466 // as above, for the single element at "offset"
1467 inline void IteratePointer(ObjectVisitor* v, int offset);
1468 // as above, for the next code link of a code object.
1469 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1472 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1476 // This class describes a body of an object of a fixed size
1477 // in which all pointer fields are located in the [start_offset, end_offset)
1479 template<int start_offset, int end_offset, int size>
1480 class FixedBodyDescriptor {
1482 static const int kStartOffset = start_offset;
1483 static const int kEndOffset = end_offset;
1484 static const int kSize = size;
1486 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1488 template<typename StaticVisitor>
1489 static inline void IterateBody(HeapObject* obj) {
1490 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1491 HeapObject::RawField(obj, end_offset));
1496 // This class describes a body of an object of a variable size
1497 // in which all pointer fields are located in the [start_offset, object_size)
1499 template<int start_offset>
1500 class FlexibleBodyDescriptor {
1502 static const int kStartOffset = start_offset;
1504 static inline void IterateBody(HeapObject* obj,
1508 template<typename StaticVisitor>
1509 static inline void IterateBody(HeapObject* obj, int object_size) {
1510 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1511 HeapObject::RawField(obj, object_size));
1516 // The HeapNumber class describes heap allocated numbers that cannot be
1517 // represented in a Smi (small integer)
1518 class HeapNumber: public HeapObject {
1520 // [value]: number value.
1521 inline double value() const;
1522 inline void set_value(double value);
1524 DECLARE_CAST(HeapNumber)
1526 // Dispatched behavior.
1527 bool HeapNumberBooleanValue();
1529 void HeapNumberPrint(OStream& os); // NOLINT
1530 DECLARE_VERIFIER(HeapNumber)
1532 inline int get_exponent();
1533 inline int get_sign();
1535 // Layout description.
1536 static const int kValueOffset = HeapObject::kHeaderSize;
1537 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1538 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1539 // words within double numbers are endian dependent and they are set
1541 #if defined(V8_TARGET_LITTLE_ENDIAN)
1542 static const int kMantissaOffset = kValueOffset;
1543 static const int kExponentOffset = kValueOffset + 4;
1544 #elif defined(V8_TARGET_BIG_ENDIAN)
1545 static const int kMantissaOffset = kValueOffset + 4;
1546 static const int kExponentOffset = kValueOffset;
1548 #error Unknown byte ordering
1551 static const int kSize = kValueOffset + kDoubleSize;
1552 static const uint32_t kSignMask = 0x80000000u;
1553 static const uint32_t kExponentMask = 0x7ff00000u;
1554 static const uint32_t kMantissaMask = 0xfffffu;
1555 static const int kMantissaBits = 52;
1556 static const int kExponentBits = 11;
1557 static const int kExponentBias = 1023;
1558 static const int kExponentShift = 20;
1559 static const int kInfinityOrNanExponent =
1560 (kExponentMask >> kExponentShift) - kExponentBias;
1561 static const int kMantissaBitsInTopWord = 20;
1562 static const int kNonMantissaBitsInTopWord = 12;
1565 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1569 enum EnsureElementsMode {
1570 DONT_ALLOW_DOUBLE_ELEMENTS,
1571 ALLOW_COPIED_DOUBLE_ELEMENTS,
1572 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1576 // Indicates whether a property should be set or (re)defined. Setting of a
1577 // property causes attributes to remain unchanged, writability to be checked
1578 // and callbacks to be called. Defining of a property causes attributes to
1579 // be updated and callbacks to be overridden.
1580 enum SetPropertyMode {
1586 // Indicator for one component of an AccessorPair.
1587 enum AccessorComponent {
1593 // JSReceiver includes types on which properties can be defined, i.e.,
1594 // JSObject and JSProxy.
1595 class JSReceiver: public HeapObject {
1603 DECLARE_CAST(JSReceiver)
1605 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1606 Handle<JSReceiver> object,
1608 Handle<Object> value,
1609 PropertyAttributes attributes,
1610 StrictMode strict_mode);
1612 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1613 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1614 Handle<JSReceiver> object, Handle<Name> name);
1615 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1617 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1618 Handle<JSReceiver> object, uint32_t index);
1619 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1620 Handle<JSReceiver> object, uint32_t index);
1622 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1623 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1624 Handle<JSReceiver> object,
1626 DeleteMode mode = NORMAL_DELETION);
1627 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1628 Handle<JSReceiver> object,
1630 DeleteMode mode = NORMAL_DELETION);
1632 // Tests for the fast common case for property enumeration.
1633 bool IsSimpleEnum();
1635 // Returns the class name ([[Class]] property in the specification).
1636 String* class_name();
1638 // Returns the constructor name (the name (possibly, inferred name) of the
1639 // function that was used to instantiate the object).
1640 String* constructor_name();
1642 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1643 Handle<JSReceiver> object, Handle<Name> name);
1644 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1645 LookupIterator* it);
1646 MUST_USE_RESULT static Maybe<PropertyAttributes> GetOwnPropertyAttributes(
1647 Handle<JSReceiver> object, Handle<Name> name);
1649 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttribute(
1650 Handle<JSReceiver> object, uint32_t index);
1651 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1652 GetOwnElementAttribute(Handle<JSReceiver> object, uint32_t index);
1654 // Return the constructor function (may be Heap::null_value()).
1655 inline Object* GetConstructor();
1657 // Retrieves a permanent object identity hash code. The undefined value might
1658 // be returned in case no hash was created yet.
1659 inline Object* GetIdentityHash();
1661 // Retrieves a permanent object identity hash code. May create and store a
1662 // hash code if needed and none exists.
1663 inline static Handle<Smi> GetOrCreateIdentityHash(
1664 Handle<JSReceiver> object);
1666 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1668 // Computes the enumerable keys for a JSObject. Used for implementing
1669 // "for (n in object) { }".
1670 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1671 Handle<JSReceiver> object,
1672 KeyCollectionType type);
1675 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1678 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
1679 class ObjectHashTable;
1681 // Forward declaration for JSObject::Copy.
1682 class AllocationSite;
1685 // The JSObject describes real heap allocated JavaScript objects with
1687 // Note that the map of JSObject changes during execution to enable inline
1689 class JSObject: public JSReceiver {
1691 // [properties]: Backing storage for properties.
1692 // properties is a FixedArray in the fast case and a Dictionary in the
1694 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1695 inline void initialize_properties();
1696 inline bool HasFastProperties();
1697 inline NameDictionary* property_dictionary(); // Gets slow properties.
1699 // [elements]: The elements (properties with names that are integers).
1701 // Elements can be in two general modes: fast and slow. Each mode
1702 // corrensponds to a set of object representations of elements that
1703 // have something in common.
1705 // In the fast mode elements is a FixedArray and so each element can
1706 // be quickly accessed. This fact is used in the generated code. The
1707 // elements array can have one of three maps in this mode:
1708 // fixed_array_map, sloppy_arguments_elements_map or
1709 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1710 // the elements array may be shared by a few objects and so before
1711 // writing to any element the array must be copied. Use
1712 // EnsureWritableFastElements in this case.
1714 // In the slow mode the elements is either a NumberDictionary, an
1715 // ExternalArray, or a FixedArray parameter map for a (sloppy)
1716 // arguments object.
1717 DECL_ACCESSORS(elements, FixedArrayBase)
1718 inline void initialize_elements();
1719 static void ResetElements(Handle<JSObject> object);
1720 static inline void SetMapAndElements(Handle<JSObject> object,
1722 Handle<FixedArrayBase> elements);
1723 inline ElementsKind GetElementsKind();
1724 inline ElementsAccessor* GetElementsAccessor();
1725 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1726 inline bool HasFastSmiElements();
1727 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1728 inline bool HasFastObjectElements();
1729 // Returns true if an object has elements of FAST_ELEMENTS or
1730 // FAST_SMI_ONLY_ELEMENTS.
1731 inline bool HasFastSmiOrObjectElements();
1732 // Returns true if an object has any of the fast elements kinds.
1733 inline bool HasFastElements();
1734 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1736 inline bool HasFastDoubleElements();
1737 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1739 inline bool HasFastHoleyElements();
1740 inline bool HasSloppyArgumentsElements();
1741 inline bool HasDictionaryElements();
1743 inline bool HasExternalUint8ClampedElements();
1744 inline bool HasExternalArrayElements();
1745 inline bool HasExternalInt8Elements();
1746 inline bool HasExternalUint8Elements();
1747 inline bool HasExternalInt16Elements();
1748 inline bool HasExternalUint16Elements();
1749 inline bool HasExternalInt32Elements();
1750 inline bool HasExternalUint32Elements();
1751 inline bool HasExternalFloat32Elements();
1752 inline bool HasExternalFloat32x4Elements();
1753 inline bool HasExternalFloat64x2Elements();
1754 inline bool HasExternalInt32x4Elements();
1755 inline bool HasExternalFloat64Elements();
1757 inline bool HasFixedTypedArrayElements();
1759 inline bool HasFixedUint8ClampedElements();
1760 inline bool HasFixedArrayElements();
1761 inline bool HasFixedInt8Elements();
1762 inline bool HasFixedUint8Elements();
1763 inline bool HasFixedInt16Elements();
1764 inline bool HasFixedUint16Elements();
1765 inline bool HasFixedInt32Elements();
1766 inline bool HasFixedUint32Elements();
1767 inline bool HasFixedFloat32Elements();
1768 inline bool HasFixedFloat64Elements();
1769 inline bool HasFixedFloat32x4Elements();
1770 inline bool HasFixedFloat64x2Elements();
1771 inline bool HasFixedInt32x4Elements();
1773 bool HasFastArgumentsElements();
1774 bool HasDictionaryArgumentsElements();
1775 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1777 // Requires: HasFastElements().
1778 static Handle<FixedArray> EnsureWritableFastElements(
1779 Handle<JSObject> object);
1781 // Collects elements starting at index 0.
1782 // Undefined values are placed after non-undefined values.
1783 // Returns the number of non-undefined values.
1784 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1786 // As PrepareElementsForSort, but only on objects where elements is
1787 // a dictionary, and it will stay a dictionary. Collates undefined and
1788 // unexisting elements below limit from position zero of the elements.
1789 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1792 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1793 LookupIterator* it, Handle<Object> value);
1795 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1796 // grant an exemption to ExecutableAccessor callbacks in some cases.
1797 enum ExecutableAccessorInfoHandling {
1802 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1803 Handle<JSObject> object,
1805 Handle<Object> value,
1806 PropertyAttributes attributes,
1807 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1809 static void AddProperty(Handle<JSObject> object, Handle<Name> key,
1810 Handle<Object> value, PropertyAttributes attributes);
1812 // Extend the receiver with a single fast property appeared first in the
1813 // passed map. This also extends the property backing store if necessary.
1814 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1816 // Migrates the given object to a map whose field representations are the
1817 // lowest upper bound of all known representations for that field.
1818 static void MigrateInstance(Handle<JSObject> instance);
1820 // Migrates the given object only if the target map is already available,
1821 // or returns false if such a map is not yet available.
1822 static bool TryMigrateInstance(Handle<JSObject> instance);
1824 // Sets the property value in a normalized object given (key, value, details).
1825 // Handles the special representation of JS global objects.
1826 static void SetNormalizedProperty(Handle<JSObject> object,
1828 Handle<Object> value,
1829 PropertyDetails details);
1831 static void OptimizeAsPrototype(Handle<JSObject> object,
1832 PrototypeOptimizationMode mode);
1833 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1835 // Retrieve interceptors.
1836 InterceptorInfo* GetNamedInterceptor();
1837 InterceptorInfo* GetIndexedInterceptor();
1839 // Used from JSReceiver.
1840 MUST_USE_RESULT static Maybe<PropertyAttributes>
1841 GetPropertyAttributesWithInterceptor(Handle<JSObject> holder,
1842 Handle<Object> receiver,
1844 MUST_USE_RESULT static Maybe<PropertyAttributes>
1845 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1846 MUST_USE_RESULT static Maybe<PropertyAttributes>
1847 GetElementAttributeWithReceiver(Handle<JSObject> object,
1848 Handle<JSReceiver> receiver,
1849 uint32_t index, bool check_prototype);
1851 // Retrieves an AccessorPair property from the given object. Might return
1852 // undefined if the property doesn't exist or is of a different kind.
1853 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1854 Handle<JSObject> object,
1856 AccessorComponent component);
1858 // Defines an AccessorPair property on the given object.
1859 // TODO(mstarzinger): Rename to SetAccessor().
1860 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1862 Handle<Object> getter,
1863 Handle<Object> setter,
1864 PropertyAttributes attributes);
1866 // Defines an AccessorInfo property on the given object.
1867 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1868 Handle<JSObject> object,
1869 Handle<AccessorInfo> info);
1871 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1872 Handle<JSObject> object,
1873 Handle<Object> receiver,
1876 // Returns true if this is an instance of an api function and has
1877 // been modified since it was created. May give false positives.
1880 // Accessors for hidden properties object.
1882 // Hidden properties are not own properties of the object itself.
1883 // Instead they are stored in an auxiliary structure kept as an own
1884 // property with a special name Heap::hidden_string(). But if the
1885 // receiver is a JSGlobalProxy then the auxiliary object is a property
1886 // of its prototype, and if it's a detached proxy, then you can't have
1887 // hidden properties.
1889 // Sets a hidden property on this object. Returns this object if successful,
1890 // undefined if called on a detached proxy.
1891 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1893 Handle<Object> value);
1894 // Gets the value of a hidden property with the given key. Returns the hole
1895 // if the property doesn't exist (or if called on a detached proxy),
1896 // otherwise returns the value set for the key.
1897 Object* GetHiddenProperty(Handle<Name> key);
1898 // Deletes a hidden property. Deleting a non-existing property is
1899 // considered successful.
1900 static void DeleteHiddenProperty(Handle<JSObject> object,
1902 // Returns true if the object has a property with the hidden string as name.
1903 static bool HasHiddenProperties(Handle<JSObject> object);
1905 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1907 static inline void ValidateElements(Handle<JSObject> object);
1909 // Makes sure that this object can contain HeapObject as elements.
1910 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1912 // Makes sure that this object can contain the specified elements.
1913 static inline void EnsureCanContainElements(
1914 Handle<JSObject> object,
1917 EnsureElementsMode mode);
1918 static inline void EnsureCanContainElements(
1919 Handle<JSObject> object,
1920 Handle<FixedArrayBase> elements,
1922 EnsureElementsMode mode);
1923 static void EnsureCanContainElements(
1924 Handle<JSObject> object,
1925 Arguments* arguments,
1928 EnsureElementsMode mode);
1930 // Would we convert a fast elements array to dictionary mode given
1931 // an access at key?
1932 bool WouldConvertToSlowElements(Handle<Object> key);
1933 // Do we want to keep the elements in fast case when increasing the
1935 bool ShouldConvertToSlowElements(int new_capacity);
1936 // Returns true if the backing storage for the slow-case elements of
1937 // this object takes up nearly as much space as a fast-case backing
1938 // storage would. In that case the JSObject should have fast
1940 bool ShouldConvertToFastElements();
1941 // Returns true if the elements of JSObject contains only values that can be
1942 // represented in a FixedDoubleArray and has at least one value that can only
1943 // be represented as a double and not a Smi.
1944 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
1946 // Computes the new capacity when expanding the elements of a JSObject.
1947 static int NewElementsCapacity(int old_capacity) {
1948 // (old_capacity + 50%) + 16
1949 return old_capacity + (old_capacity >> 1) + 16;
1952 // These methods do not perform access checks!
1953 MUST_USE_RESULT static MaybeHandle<AccessorPair> GetOwnElementAccessorPair(
1954 Handle<JSObject> object,
1957 MUST_USE_RESULT static MaybeHandle<Object> SetFastElement(
1958 Handle<JSObject> object,
1960 Handle<Object> value,
1961 StrictMode strict_mode,
1962 bool check_prototype);
1964 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElement(
1965 Handle<JSObject> object,
1967 Handle<Object> value,
1968 StrictMode strict_mode);
1970 // Empty handle is returned if the element cannot be set to the given value.
1971 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1972 Handle<JSObject> object,
1974 Handle<Object> value,
1975 PropertyAttributes attributes,
1976 StrictMode strict_mode,
1977 bool check_prototype = true,
1978 SetPropertyMode set_mode = SET_PROPERTY);
1980 // Returns the index'th element.
1981 // The undefined object if index is out of bounds.
1982 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithInterceptor(
1983 Handle<JSObject> object,
1984 Handle<Object> receiver,
1987 enum SetFastElementsCapacitySmiMode {
1990 kDontAllowSmiElements
1993 // Replace the elements' backing store with fast elements of the given
1994 // capacity. Update the length for JSArrays. Returns the new backing
1996 static Handle<FixedArray> SetFastElementsCapacityAndLength(
1997 Handle<JSObject> object,
2000 SetFastElementsCapacitySmiMode smi_mode);
2001 static void SetFastDoubleElementsCapacityAndLength(
2002 Handle<JSObject> object,
2006 // Lookup interceptors are used for handling properties controlled by host
2008 inline bool HasNamedInterceptor();
2009 inline bool HasIndexedInterceptor();
2011 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2012 // by JSReceiver::GetKeys.
2013 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2014 Handle<JSObject> object,
2015 Handle<JSReceiver> receiver);
2016 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2017 Handle<JSObject> object,
2018 Handle<JSReceiver> receiver);
2020 // Support functions for v8 api (needed for correct interceptor behavior).
2021 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2022 Handle<JSObject> object, Handle<Name> key);
2023 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2024 Handle<JSObject> object, uint32_t index);
2025 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2026 Handle<JSObject> object, Handle<Name> key);
2028 // Get the header size for a JSObject. Used to compute the index of
2029 // internal fields as well as the number of internal fields.
2030 inline int GetHeaderSize();
2032 inline int GetInternalFieldCount();
2033 inline int GetInternalFieldOffset(int index);
2034 inline Object* GetInternalField(int index);
2035 inline void SetInternalField(int index, Object* value);
2036 inline void SetInternalField(int index, Smi* value);
2038 // Returns the number of properties on this object filtering out properties
2039 // with the specified attributes (ignoring interceptors).
2040 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2041 // Fill in details for properties into storage starting at the specified
2043 void GetOwnPropertyNames(
2044 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2046 // Returns the number of properties on this object filtering out properties
2047 // with the specified attributes (ignoring interceptors).
2048 int NumberOfOwnElements(PropertyAttributes filter);
2049 // Returns the number of enumerable elements (ignoring interceptors).
2050 int NumberOfEnumElements();
2051 // Returns the number of elements on this object filtering out elements
2052 // with the specified attributes (ignoring interceptors).
2053 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2054 // Count and fill in the enumerable elements into storage.
2055 // (storage->length() == NumberOfEnumElements()).
2056 // If storage is NULL, will count the elements without adding
2057 // them to any storage.
2058 // Returns the number of enumerable elements.
2059 int GetEnumElementKeys(FixedArray* storage);
2061 // Returns a new map with all transitions dropped from the object's current
2062 // map and the ElementsKind set.
2063 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2064 ElementsKind to_kind);
2065 static void TransitionElementsKind(Handle<JSObject> object,
2066 ElementsKind to_kind);
2068 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2070 // Convert the object to use the canonical dictionary
2071 // representation. If the object is expected to have additional properties
2072 // added this number can be indicated to have the backing store allocated to
2073 // an initial capacity for holding these properties.
2074 static void NormalizeProperties(Handle<JSObject> object,
2075 PropertyNormalizationMode mode,
2076 int expected_additional_properties);
2078 // Convert and update the elements backing store to be a
2079 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2080 static Handle<SeededNumberDictionary> NormalizeElements(
2081 Handle<JSObject> object);
2083 // Transform slow named properties to fast variants.
2084 static void MigrateSlowToFast(Handle<JSObject> object,
2085 int unused_property_fields);
2087 // Access fast-case object properties at index.
2088 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2089 Representation representation,
2091 inline Object* RawFastPropertyAt(FieldIndex index);
2092 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2093 void WriteToField(int descriptor, Object* value);
2095 // Access to in object properties.
2096 inline int GetInObjectPropertyOffset(int index);
2097 inline Object* InObjectPropertyAt(int index);
2098 inline Object* InObjectPropertyAtPut(int index,
2100 WriteBarrierMode mode
2101 = UPDATE_WRITE_BARRIER);
2103 // Set the object's prototype (only JSReceiver and null are allowed values).
2104 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2105 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2107 // Initializes the body after properties slot, properties slot is
2108 // initialized by set_properties. Fill the pre-allocated fields with
2109 // pre_allocated_value and the rest with filler_value.
2110 // Note: this call does not update write barrier, the caller is responsible
2111 // to ensure that |filler_value| can be collected without WB here.
2112 inline void InitializeBody(Map* map,
2113 Object* pre_allocated_value,
2114 Object* filler_value);
2116 // Check whether this object references another object
2117 bool ReferencesObject(Object* obj);
2119 // Disalow further properties to be added to the object.
2120 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2121 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 static Handle<JSObject> Copy(Handle<JSObject> object);
2133 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2134 Handle<JSObject> object,
2135 AllocationSiteUsageContext* site_context,
2136 DeepCopyHints hints = kNoHints);
2137 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2138 Handle<JSObject> object,
2139 AllocationSiteCreationContext* site_context);
2141 static Handle<Object> GetDataProperty(Handle<JSObject> object,
2143 static Handle<Object> GetDataProperty(LookupIterator* it);
2145 DECLARE_CAST(JSObject)
2147 // Dispatched behavior.
2148 void JSObjectShortPrint(StringStream* accumulator);
2149 DECLARE_PRINTER(JSObject)
2150 DECLARE_VERIFIER(JSObject)
2152 void PrintProperties(OStream& os); // NOLINT
2153 void PrintElements(OStream& os); // NOLINT
2154 void PrintTransitions(OStream& os); // NOLINT
2157 static void PrintElementsTransition(
2158 FILE* file, Handle<JSObject> object,
2159 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2160 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2162 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2165 // Structure for collecting spill information about JSObjects.
2166 class SpillInformation {
2170 int number_of_objects_;
2171 int number_of_objects_with_fast_properties_;
2172 int number_of_objects_with_fast_elements_;
2173 int number_of_fast_used_fields_;
2174 int number_of_fast_unused_fields_;
2175 int number_of_slow_used_properties_;
2176 int number_of_slow_unused_properties_;
2177 int number_of_fast_used_elements_;
2178 int number_of_fast_unused_elements_;
2179 int number_of_slow_used_elements_;
2180 int number_of_slow_unused_elements_;
2183 void IncrementSpillStatistics(SpillInformation* info);
2187 // If a GC was caused while constructing this object, the elements pointer
2188 // may point to a one pointer filler map. The object won't be rooted, but
2189 // our heap verification code could stumble across it.
2190 bool ElementsAreSafeToExamine();
2193 Object* SlowReverseLookup(Object* value);
2195 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2196 // Also maximal value of JSArray's length property.
2197 static const uint32_t kMaxElementCount = 0xffffffffu;
2199 // Constants for heuristics controlling conversion of fast elements
2200 // to slow elements.
2202 // Maximal gap that can be introduced by adding an element beyond
2203 // the current elements length.
2204 static const uint32_t kMaxGap = 1024;
2206 // Maximal length of fast elements array that won't be checked for
2207 // being dense enough on expansion.
2208 static const int kMaxUncheckedFastElementsLength = 5000;
2210 // Same as above but for old arrays. This limit is more strict. We
2211 // don't want to be wasteful with long lived objects.
2212 static const int kMaxUncheckedOldFastElementsLength = 500;
2214 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2215 // permissible values (see the DCHECK in heap.cc).
2216 static const int kInitialMaxFastElementArray = 100000;
2218 // This constant applies only to the initial map of "$Object" aka
2219 // "global.Object" and not to arbitrary other JSObject maps.
2220 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2222 static const int kMaxInstanceSize = 255 * kPointerSize;
2223 // When extending the backing storage for property values, we increase
2224 // its size by more than the 1 entry necessary, so sequentially adding fields
2225 // to the same object requires fewer allocations and copies.
2226 static const int kFieldsAdded = 3;
2228 // Layout description.
2229 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2230 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2231 static const int kHeaderSize = kElementsOffset + kPointerSize;
2233 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2235 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2237 static inline int SizeOf(Map* map, HeapObject* object);
2240 Context* GetCreationContext();
2242 // Enqueue change record for Object.observe. May cause GC.
2243 static void EnqueueChangeRecord(Handle<JSObject> object,
2246 Handle<Object> old_value);
2248 static void MigrateToNewProperty(Handle<JSObject> object,
2249 Handle<Map> transition,
2250 Handle<Object> value);
2253 friend class DictionaryElementsAccessor;
2254 friend class JSReceiver;
2255 friend class Object;
2257 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2258 static void MigrateFastToSlow(Handle<JSObject> object,
2259 Handle<Map> new_map,
2260 int expected_additional_properties);
2262 static void GeneralizeFieldRepresentation(Handle<JSObject> object,
2264 Representation new_representation,
2265 Handle<HeapType> new_field_type);
2267 static void UpdateAllocationSite(Handle<JSObject> object,
2268 ElementsKind to_kind);
2270 // Used from Object::GetProperty().
2271 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2272 LookupIterator* it);
2274 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithCallback(
2275 Handle<JSObject> object,
2276 Handle<Object> receiver,
2277 Handle<Object> structure,
2279 Handle<Object> holder);
2281 MUST_USE_RESULT static Maybe<PropertyAttributes>
2282 GetElementAttributeWithInterceptor(Handle<JSObject> object,
2283 Handle<JSReceiver> receiver,
2284 uint32_t index, bool continue_search);
2285 MUST_USE_RESULT static Maybe<PropertyAttributes>
2286 GetElementAttributeWithoutInterceptor(Handle<JSObject> object,
2287 Handle<JSReceiver> receiver,
2289 bool continue_search);
2290 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithCallback(
2291 Handle<JSObject> object,
2292 Handle<Object> structure,
2294 Handle<Object> value,
2295 Handle<JSObject> holder,
2296 StrictMode strict_mode);
2297 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithInterceptor(
2298 Handle<JSObject> object,
2300 Handle<Object> value,
2301 PropertyAttributes attributes,
2302 StrictMode strict_mode,
2303 bool check_prototype,
2304 SetPropertyMode set_mode);
2305 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithoutInterceptor(
2306 Handle<JSObject> object,
2308 Handle<Object> value,
2309 PropertyAttributes attributes,
2310 StrictMode strict_mode,
2311 bool check_prototype,
2312 SetPropertyMode set_mode);
2314 static MaybeHandle<Object> SetElementWithCallbackSetterInPrototypes(
2315 Handle<JSObject> object,
2317 Handle<Object> value,
2319 StrictMode strict_mode);
2320 MUST_USE_RESULT static MaybeHandle<Object> SetDictionaryElement(
2321 Handle<JSObject> object,
2323 Handle<Object> value,
2324 PropertyAttributes attributes,
2325 StrictMode strict_mode,
2326 bool check_prototype,
2327 SetPropertyMode set_mode = SET_PROPERTY);
2328 MUST_USE_RESULT static MaybeHandle<Object> SetFastDoubleElement(
2329 Handle<JSObject> object,
2331 Handle<Object> value,
2332 StrictMode strict_mode,
2333 bool check_prototype = true);
2335 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2336 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
2338 // Add a property to a slow-case object.
2339 static void AddSlowProperty(Handle<JSObject> object,
2341 Handle<Object> value,
2342 PropertyAttributes attributes);
2344 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
2345 Handle<JSObject> object,
2348 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2349 Handle<JSObject> holder, Handle<JSObject> receiver, Handle<Name> name);
2351 // Deletes the named property in a normalized object.
2352 static Handle<Object> DeleteNormalizedProperty(Handle<JSObject> object,
2356 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
2357 Handle<JSObject> object,
2360 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithInterceptor(
2361 Handle<JSObject> object,
2364 bool ReferencesObjectFromElements(FixedArray* elements,
2368 // Returns true if most of the elements backing storage is used.
2369 bool HasDenseElements();
2371 // Gets the current elements capacity and the number of used elements.
2372 void GetElementsCapacityAndUsage(int* capacity, int* used);
2374 static bool CanSetCallback(Handle<JSObject> object, Handle<Name> name);
2375 static void SetElementCallback(Handle<JSObject> object,
2377 Handle<Object> structure,
2378 PropertyAttributes attributes);
2379 static void SetPropertyCallback(Handle<JSObject> object,
2381 Handle<Object> structure,
2382 PropertyAttributes attributes);
2383 static void DefineElementAccessor(Handle<JSObject> object,
2385 Handle<Object> getter,
2386 Handle<Object> setter,
2387 PropertyAttributes attributes);
2389 // Return the hash table backing store or the inline stored identity hash,
2390 // whatever is found.
2391 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2393 // Return the hash table backing store for hidden properties. If there is no
2394 // backing store, allocate one.
2395 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2396 Handle<JSObject> object);
2398 // Set the hidden property backing store to either a hash table or
2399 // the inline-stored identity hash.
2400 static Handle<Object> SetHiddenPropertiesHashTable(
2401 Handle<JSObject> object,
2402 Handle<Object> value);
2404 MUST_USE_RESULT Object* GetIdentityHash();
2406 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2408 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2412 // Common superclass for FixedArrays that allow implementations to share
2413 // common accessors and some code paths.
2414 class FixedArrayBase: public HeapObject {
2416 // [length]: length of the array.
2417 inline int length() const;
2418 inline void set_length(int value);
2420 // Get and set the length using acquire loads and release stores.
2421 inline int synchronized_length() const;
2422 inline void synchronized_set_length(int value);
2424 DECLARE_CAST(FixedArrayBase)
2426 // Layout description.
2427 // Length is smi tagged when it is stored.
2428 static const int kLengthOffset = HeapObject::kHeaderSize;
2429 static const int kHeaderSize = kLengthOffset + kPointerSize;
2433 class FixedDoubleArray;
2434 class IncrementalMarking;
2437 // FixedArray describes fixed-sized arrays with element type Object*.
2438 class FixedArray: public FixedArrayBase {
2440 // Setter and getter for elements.
2441 inline Object* get(int index);
2442 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2443 // Setter that uses write barrier.
2444 inline void set(int index, Object* value);
2445 inline bool is_the_hole(int index);
2447 // Setter that doesn't need write barrier.
2448 inline void set(int index, Smi* value);
2449 // Setter with explicit barrier mode.
2450 inline void set(int index, Object* value, WriteBarrierMode mode);
2452 // Setters for frequently used oddballs located in old space.
2453 inline void set_undefined(int index);
2454 inline void set_null(int index);
2455 inline void set_the_hole(int index);
2457 inline Object** GetFirstElementAddress();
2458 inline bool ContainsOnlySmisOrHoles();
2460 // Gives access to raw memory which stores the array's data.
2461 inline Object** data_start();
2463 inline void FillWithHoles(int from, int to);
2465 // Shrink length and insert filler objects.
2466 void Shrink(int length);
2469 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2471 PretenureFlag pretenure = NOT_TENURED);
2473 // Add the elements of a JSArray to this FixedArray.
2474 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2475 Handle<FixedArray> content,
2476 Handle<JSObject> array);
2478 // Computes the union of keys and return the result.
2479 // Used for implementing "for (n in object) { }"
2480 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2481 Handle<FixedArray> first,
2482 Handle<FixedArray> second);
2484 // Copy a sub array from the receiver to dest.
2485 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2487 // Garbage collection support.
2488 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2490 // Code Generation support.
2491 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2493 // Garbage collection support.
2494 Object** RawFieldOfElementAt(int index) {
2495 return HeapObject::RawField(this, OffsetOfElementAt(index));
2498 DECLARE_CAST(FixedArray)
2500 // Maximal allowed size, in bytes, of a single FixedArray.
2501 // Prevents overflowing size computations, as well as extreme memory
2503 static const int kMaxSize = 128 * MB * kPointerSize;
2504 // Maximally allowed length of a FixedArray.
2505 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2507 // Dispatched behavior.
2508 DECLARE_PRINTER(FixedArray)
2509 DECLARE_VERIFIER(FixedArray)
2511 // Checks if two FixedArrays have identical contents.
2512 bool IsEqualTo(FixedArray* other);
2515 // Swap two elements in a pair of arrays. If this array and the
2516 // numbers array are the same object, the elements are only swapped
2518 void SwapPairs(FixedArray* numbers, int i, int j);
2520 // Sort prefix of this array and the numbers array as pairs wrt. the
2521 // numbers. If the numbers array and the this array are the same
2522 // object, the prefix of this array is sorted.
2523 void SortPairs(FixedArray* numbers, uint32_t len);
2525 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2527 static inline int SizeOf(Map* map, HeapObject* object) {
2528 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2533 // Set operation on FixedArray without using write barriers. Can
2534 // only be used for storing old space objects or smis.
2535 static inline void NoWriteBarrierSet(FixedArray* array,
2539 // Set operation on FixedArray without incremental write barrier. Can
2540 // only be used if the object is guaranteed to be white (whiteness witness
2542 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2547 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2549 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2553 // FixedDoubleArray describes fixed-sized arrays with element type double.
2554 class FixedDoubleArray: public FixedArrayBase {
2556 // Setter and getter for elements.
2557 inline double get_scalar(int index);
2558 inline int64_t get_representation(int index);
2559 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2560 inline void set(int index, double value);
2561 inline void set_the_hole(int index);
2563 // Checking for the hole.
2564 inline bool is_the_hole(int index);
2566 // Garbage collection support.
2567 inline static int SizeFor(int length) {
2568 return kHeaderSize + length * kDoubleSize;
2571 // Gives access to raw memory which stores the array's data.
2572 inline double* data_start();
2574 inline void FillWithHoles(int from, int to);
2576 // Code Generation support.
2577 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2579 inline static bool is_the_hole_nan(double value);
2580 inline static double hole_nan_as_double();
2581 inline static double canonical_not_the_hole_nan_as_double();
2583 DECLARE_CAST(FixedDoubleArray)
2585 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2586 // Prevents overflowing size computations, as well as extreme memory
2588 static const int kMaxSize = 512 * MB;
2589 // Maximally allowed length of a FixedArray.
2590 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2592 // Dispatched behavior.
2593 DECLARE_PRINTER(FixedDoubleArray)
2594 DECLARE_VERIFIER(FixedDoubleArray)
2597 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2601 // ConstantPoolArray describes a fixed-sized array containing constant pool
2604 // A ConstantPoolArray can be structured in two different ways depending upon
2605 // whether it is extended or small. The is_extended_layout() method can be used
2606 // to discover which layout the constant pool has.
2608 // The format of a small constant pool is:
2609 // [kSmallLayout1Offset] : Small section layout bitmap 1
2610 // [kSmallLayout2Offset] : Small section layout bitmap 2
2611 // [first_index(INT64, SMALL_SECTION)] : 64 bit entries
2613 // [first_index(CODE_PTR, SMALL_SECTION)] : code pointer entries
2615 // [first_index(HEAP_PTR, SMALL_SECTION)] : heap pointer entries
2617 // [first_index(INT32, SMALL_SECTION)] : 32 bit entries
2620 // If the constant pool has an extended layout, the extended section constant
2621 // pool also contains an extended section, which has the following format at
2622 // location get_extended_section_header_offset():
2623 // [kExtendedInt64CountOffset] : count of extended 64 bit entries
2624 // [kExtendedCodePtrCountOffset] : count of extended code pointers
2625 // [kExtendedHeapPtrCountOffset] : count of extended heap pointers
2626 // [kExtendedInt32CountOffset] : count of extended 32 bit entries
2627 // [first_index(INT64, EXTENDED_SECTION)] : 64 bit entries
2629 // [first_index(CODE_PTR, EXTENDED_SECTION)]: code pointer entries
2631 // [first_index(HEAP_PTR, EXTENDED_SECTION)]: heap pointer entries
2633 // [first_index(INT32, EXTENDED_SECTION)] : 32 bit entries
2636 class ConstantPoolArray: public HeapObject {
2638 enum WeakObjectState {
2640 WEAK_OBJECTS_IN_OPTIMIZED_CODE,
2649 // Number of types stored by the ConstantPoolArrays.
2655 enum LayoutSection {
2658 NUMBER_OF_LAYOUT_SECTIONS
2661 class NumberOfEntries BASE_EMBEDDED {
2663 inline NumberOfEntries() {
2664 for (int i = 0; i < NUMBER_OF_TYPES; i++) {
2665 element_counts_[i] = 0;
2669 inline NumberOfEntries(int int64_count, int code_ptr_count,
2670 int heap_ptr_count, int int32_count) {
2671 element_counts_[INT64] = int64_count;
2672 element_counts_[CODE_PTR] = code_ptr_count;
2673 element_counts_[HEAP_PTR] = heap_ptr_count;
2674 element_counts_[INT32] = int32_count;
2677 inline NumberOfEntries(ConstantPoolArray* array, LayoutSection section) {
2678 element_counts_[INT64] = array->number_of_entries(INT64, section);
2679 element_counts_[CODE_PTR] = array->number_of_entries(CODE_PTR, section);
2680 element_counts_[HEAP_PTR] = array->number_of_entries(HEAP_PTR, section);
2681 element_counts_[INT32] = array->number_of_entries(INT32, section);
2684 inline void increment(Type type);
2685 inline int equals(const NumberOfEntries& other) const;
2686 inline bool is_empty() const;
2687 inline int count_of(Type type) const;
2688 inline int base_of(Type type) const;
2689 inline int total_count() const;
2690 inline int are_in_range(int min, int max) const;
2693 int element_counts_[NUMBER_OF_TYPES];
2696 class Iterator BASE_EMBEDDED {
2698 inline Iterator(ConstantPoolArray* array, Type type)
2701 final_section_(array->final_section()),
2702 current_section_(SMALL_SECTION),
2703 next_index_(array->first_index(type, SMALL_SECTION)) {
2707 inline Iterator(ConstantPoolArray* array, Type type, LayoutSection section)
2710 final_section_(section),
2711 current_section_(section),
2712 next_index_(array->first_index(type, section)) {
2716 inline int next_index();
2717 inline bool is_finished();
2720 inline void update_section();
2721 ConstantPoolArray* array_;
2723 const LayoutSection final_section_;
2725 LayoutSection current_section_;
2729 // Getters for the first index, the last index and the count of entries of
2730 // a given type for a given layout section.
2731 inline int first_index(Type type, LayoutSection layout_section);
2732 inline int last_index(Type type, LayoutSection layout_section);
2733 inline int number_of_entries(Type type, LayoutSection layout_section);
2735 // Returns the type of the entry at the given index.
2736 inline Type get_type(int index);
2737 inline bool offset_is_type(int offset, Type type);
2739 // Setter and getter for pool elements.
2740 inline Address get_code_ptr_entry(int index);
2741 inline Object* get_heap_ptr_entry(int index);
2742 inline int64_t get_int64_entry(int index);
2743 inline int32_t get_int32_entry(int index);
2744 inline double get_int64_entry_as_double(int index);
2746 inline void set(int index, Address value);
2747 inline void set(int index, Object* value);
2748 inline void set(int index, int64_t value);
2749 inline void set(int index, double value);
2750 inline void set(int index, int32_t value);
2752 // Setters which take a raw offset rather than an index (for code generation).
2753 inline void set_at_offset(int offset, int32_t value);
2754 inline void set_at_offset(int offset, int64_t value);
2755 inline void set_at_offset(int offset, double value);
2756 inline void set_at_offset(int offset, Address value);
2757 inline void set_at_offset(int offset, Object* value);
2759 // Setter and getter for weak objects state
2760 inline void set_weak_object_state(WeakObjectState state);
2761 inline WeakObjectState get_weak_object_state();
2763 // Returns true if the constant pool has an extended layout, false if it has
2764 // only the small layout.
2765 inline bool is_extended_layout();
2767 // Returns the last LayoutSection in this constant pool array.
2768 inline LayoutSection final_section();
2770 // Set up initial state for a small layout constant pool array.
2771 inline void Init(const NumberOfEntries& small);
2773 // Set up initial state for an extended layout constant pool array.
2774 inline void InitExtended(const NumberOfEntries& small,
2775 const NumberOfEntries& extended);
2777 // Clears the pointer entries with GC safe values.
2778 void ClearPtrEntries(Isolate* isolate);
2780 // returns the total number of entries in the constant pool array.
2781 inline int length();
2783 // Garbage collection support.
2787 inline static int MaxInt64Offset(int number_of_int64) {
2788 return kFirstEntryOffset + (number_of_int64 * kInt64Size);
2791 inline static int SizeFor(const NumberOfEntries& small) {
2792 int size = kFirstEntryOffset +
2793 (small.count_of(INT64) * kInt64Size) +
2794 (small.count_of(CODE_PTR) * kPointerSize) +
2795 (small.count_of(HEAP_PTR) * kPointerSize) +
2796 (small.count_of(INT32) * kInt32Size);
2797 return RoundUp(size, kPointerSize);
2800 inline static int SizeForExtended(const NumberOfEntries& small,
2801 const NumberOfEntries& extended) {
2802 int size = SizeFor(small);
2803 size = RoundUp(size, kInt64Size); // Align extended header to 64 bits.
2804 size += kExtendedFirstOffset +
2805 (extended.count_of(INT64) * kInt64Size) +
2806 (extended.count_of(CODE_PTR) * kPointerSize) +
2807 (extended.count_of(HEAP_PTR) * kPointerSize) +
2808 (extended.count_of(INT32) * kInt32Size);
2809 return RoundUp(size, kPointerSize);
2812 inline static int entry_size(Type type) {
2820 return kPointerSize;
2827 // Code Generation support.
2828 inline int OffsetOfElementAt(int index) {
2830 LayoutSection section;
2831 if (is_extended_layout() && index >= first_extended_section_index()) {
2832 section = EXTENDED_SECTION;
2833 offset = get_extended_section_header_offset() + kExtendedFirstOffset;
2835 section = SMALL_SECTION;
2836 offset = kFirstEntryOffset;
2839 // Add offsets for the preceding type sections.
2840 DCHECK(index <= last_index(LAST_TYPE, section));
2841 for (Type type = FIRST_TYPE; index > last_index(type, section);
2842 type = next_type(type)) {
2843 offset += entry_size(type) * number_of_entries(type, section);
2846 // Add offset for the index in it's type.
2847 Type type = get_type(index);
2848 offset += entry_size(type) * (index - first_index(type, section));
2852 DECLARE_CAST(ConstantPoolArray)
2854 // Garbage collection support.
2855 Object** RawFieldOfElementAt(int index) {
2856 return HeapObject::RawField(this, OffsetOfElementAt(index));
2859 // Small Layout description.
2860 static const int kSmallLayout1Offset = HeapObject::kHeaderSize;
2861 static const int kSmallLayout2Offset = kSmallLayout1Offset + kInt32Size;
2862 static const int kHeaderSize = kSmallLayout2Offset + kInt32Size;
2863 static const int kFirstEntryOffset = ROUND_UP(kHeaderSize, kInt64Size);
2865 static const int kSmallLayoutCountBits = 10;
2866 static const int kMaxSmallEntriesPerType = (1 << kSmallLayoutCountBits) - 1;
2868 // Fields in kSmallLayout1Offset.
2869 class Int64CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2870 class CodePtrCountField: public BitField<int, 11, kSmallLayoutCountBits> {};
2871 class HeapPtrCountField: public BitField<int, 21, kSmallLayoutCountBits> {};
2872 class IsExtendedField: public BitField<bool, 31, 1> {};
2874 // Fields in kSmallLayout2Offset.
2875 class Int32CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2876 class TotalCountField: public BitField<int, 11, 12> {};
2877 class WeakObjectStateField: public BitField<WeakObjectState, 23, 2> {};
2879 // Extended layout description, which starts at
2880 // get_extended_section_header_offset().
2881 static const int kExtendedInt64CountOffset = 0;
2882 static const int kExtendedCodePtrCountOffset =
2883 kExtendedInt64CountOffset + kPointerSize;
2884 static const int kExtendedHeapPtrCountOffset =
2885 kExtendedCodePtrCountOffset + kPointerSize;
2886 static const int kExtendedInt32CountOffset =
2887 kExtendedHeapPtrCountOffset + kPointerSize;
2888 static const int kExtendedFirstOffset =
2889 kExtendedInt32CountOffset + kPointerSize;
2891 // Dispatched behavior.
2892 void ConstantPoolIterateBody(ObjectVisitor* v);
2894 DECLARE_PRINTER(ConstantPoolArray)
2895 DECLARE_VERIFIER(ConstantPoolArray)
2898 inline int first_extended_section_index();
2899 inline int get_extended_section_header_offset();
2901 inline static Type next_type(Type type) {
2902 DCHECK(type >= FIRST_TYPE && type < NUMBER_OF_TYPES);
2903 int type_int = static_cast<int>(type);
2904 return static_cast<Type>(++type_int);
2907 DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
2911 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2912 // The format of the these objects is:
2913 // [0]: Number of descriptors
2914 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2915 // [0]: pointer to fixed array with enum cache
2916 // [1]: either Smi(0) or pointer to fixed array with indices
2918 // [2 + number of descriptors * kDescriptorSize]: start of slack
2919 class DescriptorArray: public FixedArray {
2921 // Returns true for both shared empty_descriptor_array and for smis, which the
2922 // map uses to encode additional bit fields when the descriptor array is not
2924 inline bool IsEmpty();
2926 // Returns the number of descriptors in the array.
2927 int number_of_descriptors() {
2928 DCHECK(length() >= kFirstIndex || IsEmpty());
2930 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2933 int number_of_descriptors_storage() {
2935 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2938 int NumberOfSlackDescriptors() {
2939 return number_of_descriptors_storage() - number_of_descriptors();
2942 inline void SetNumberOfDescriptors(int number_of_descriptors);
2943 inline int number_of_entries() { return number_of_descriptors(); }
2945 bool HasEnumCache() {
2946 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2949 void CopyEnumCacheFrom(DescriptorArray* array) {
2950 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2953 FixedArray* GetEnumCache() {
2954 DCHECK(HasEnumCache());
2955 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2956 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2959 bool HasEnumIndicesCache() {
2960 if (IsEmpty()) return false;
2961 Object* object = get(kEnumCacheIndex);
2962 if (object->IsSmi()) return false;
2963 FixedArray* bridge = FixedArray::cast(object);
2964 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2967 FixedArray* GetEnumIndicesCache() {
2968 DCHECK(HasEnumIndicesCache());
2969 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2970 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2973 Object** GetEnumCacheSlot() {
2974 DCHECK(HasEnumCache());
2975 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2979 void ClearEnumCache();
2981 // Initialize or change the enum cache,
2982 // using the supplied storage for the small "bridge".
2983 void SetEnumCache(FixedArray* bridge_storage,
2984 FixedArray* new_cache,
2985 Object* new_index_cache);
2987 bool CanHoldValue(int descriptor, Object* value);
2989 // Accessors for fetching instance descriptor at descriptor number.
2990 inline Name* GetKey(int descriptor_number);
2991 inline Object** GetKeySlot(int descriptor_number);
2992 inline Object* GetValue(int descriptor_number);
2993 inline void SetValue(int descriptor_number, Object* value);
2994 inline Object** GetValueSlot(int descriptor_number);
2995 static inline int GetValueOffset(int descriptor_number);
2996 inline Object** GetDescriptorStartSlot(int descriptor_number);
2997 inline Object** GetDescriptorEndSlot(int descriptor_number);
2998 inline PropertyDetails GetDetails(int descriptor_number);
2999 inline PropertyType GetType(int descriptor_number);
3000 inline int GetFieldIndex(int descriptor_number);
3001 inline HeapType* GetFieldType(int descriptor_number);
3002 inline Object* GetConstant(int descriptor_number);
3003 inline Object* GetCallbacksObject(int descriptor_number);
3004 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
3006 inline Name* GetSortedKey(int descriptor_number);
3007 inline int GetSortedKeyIndex(int descriptor_number);
3008 inline void SetSortedKey(int pointer, int descriptor_number);
3009 inline void SetRepresentation(int descriptor_number,
3010 Representation representation);
3012 // Accessor for complete descriptor.
3013 inline void Get(int descriptor_number, Descriptor* desc);
3014 inline void Set(int descriptor_number, Descriptor* desc);
3015 void Replace(int descriptor_number, Descriptor* descriptor);
3017 // Append automatically sets the enumeration index. This should only be used
3018 // to add descriptors in bulk at the end, followed by sorting the descriptor
3020 inline void Append(Descriptor* desc);
3022 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
3023 int enumeration_index,
3026 static Handle<DescriptorArray> CopyUpToAddAttributes(
3027 Handle<DescriptorArray> desc,
3028 int enumeration_index,
3029 PropertyAttributes attributes,
3032 // Sort the instance descriptors by the hash codes of their keys.
3035 // Search the instance descriptors for given name.
3036 INLINE(int Search(Name* name, int number_of_own_descriptors));
3038 // As the above, but uses DescriptorLookupCache and updates it when
3040 INLINE(int SearchWithCache(Name* name, Map* map));
3042 // Allocates a DescriptorArray, but returns the singleton
3043 // empty descriptor array object if number_of_descriptors is 0.
3044 static Handle<DescriptorArray> Allocate(Isolate* isolate,
3045 int number_of_descriptors,
3048 DECLARE_CAST(DescriptorArray)
3050 // Constant for denoting key was not found.
3051 static const int kNotFound = -1;
3053 static const int kDescriptorLengthIndex = 0;
3054 static const int kEnumCacheIndex = 1;
3055 static const int kFirstIndex = 2;
3057 // The length of the "bridge" to the enum cache.
3058 static const int kEnumCacheBridgeLength = 2;
3059 static const int kEnumCacheBridgeCacheIndex = 0;
3060 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3062 // Layout description.
3063 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3064 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3065 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3067 // Layout description for the bridge array.
3068 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3070 // Layout of descriptor.
3071 static const int kDescriptorKey = 0;
3072 static const int kDescriptorDetails = 1;
3073 static const int kDescriptorValue = 2;
3074 static const int kDescriptorSize = 3;
3077 // Print all the descriptors.
3078 void PrintDescriptors(OStream& os); // NOLINT
3082 // Is the descriptor array sorted and without duplicates?
3083 bool IsSortedNoDuplicates(int valid_descriptors = -1);
3085 // Is the descriptor array consistent with the back pointers in targets?
3086 bool IsConsistentWithBackPointers(Map* current_map);
3088 // Are two DescriptorArrays equal?
3089 bool IsEqualTo(DescriptorArray* other);
3092 // Returns the fixed array length required to hold number_of_descriptors
3094 static int LengthFor(int number_of_descriptors) {
3095 return ToKeyIndex(number_of_descriptors);
3099 // WhitenessWitness is used to prove that a descriptor array is white
3100 // (unmarked), so incremental write barriers can be skipped because the
3101 // marking invariant cannot be broken and slots pointing into evacuation
3102 // candidates will be discovered when the object is scanned. A witness is
3103 // always stack-allocated right after creating an array. By allocating a
3104 // witness, incremental marking is globally disabled. The witness is then
3105 // passed along wherever needed to statically prove that the array is known to
3107 class WhitenessWitness {
3109 inline explicit WhitenessWitness(DescriptorArray* array);
3110 inline ~WhitenessWitness();
3113 IncrementalMarking* marking_;
3116 // An entry in a DescriptorArray, represented as an (array, index) pair.
3119 inline explicit Entry(DescriptorArray* descs, int index) :
3120 descs_(descs), index_(index) { }
3122 inline PropertyType type() { return descs_->GetType(index_); }
3123 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3126 DescriptorArray* descs_;
3130 // Conversion from descriptor number to array indices.
3131 static int ToKeyIndex(int descriptor_number) {
3132 return kFirstIndex +
3133 (descriptor_number * kDescriptorSize) +
3137 static int ToDetailsIndex(int descriptor_number) {
3138 return kFirstIndex +
3139 (descriptor_number * kDescriptorSize) +
3143 static int ToValueIndex(int descriptor_number) {
3144 return kFirstIndex +
3145 (descriptor_number * kDescriptorSize) +
3149 // Transfer a complete descriptor from the src descriptor array to this
3150 // descriptor array.
3151 void CopyFrom(int index,
3152 DescriptorArray* src,
3153 const WhitenessWitness&);
3155 inline void Set(int descriptor_number,
3157 const WhitenessWitness&);
3159 // Swap first and second descriptor.
3160 inline void SwapSortedKeys(int first, int second);
3162 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3166 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3168 template<SearchMode search_mode, typename T>
3169 inline int LinearSearch(T* array, Name* name, int len, int valid_entries);
3172 template<SearchMode search_mode, typename T>
3173 inline int Search(T* array, Name* name, int valid_entries = 0);
3176 // HashTable is a subclass of FixedArray that implements a hash table
3177 // that uses open addressing and quadratic probing.
3179 // In order for the quadratic probing to work, elements that have not
3180 // yet been used and elements that have been deleted are
3181 // distinguished. Probing continues when deleted elements are
3182 // encountered and stops when unused elements are encountered.
3184 // - Elements with key == undefined have not been used yet.
3185 // - Elements with key == the_hole have been deleted.
3187 // The hash table class is parameterized with a Shape and a Key.
3188 // Shape must be a class with the following interface:
3189 // class ExampleShape {
3191 // // Tells whether key matches other.
3192 // static bool IsMatch(Key key, Object* other);
3193 // // Returns the hash value for key.
3194 // static uint32_t Hash(Key key);
3195 // // Returns the hash value for object.
3196 // static uint32_t HashForObject(Key key, Object* object);
3197 // // Convert key to an object.
3198 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
3199 // // The prefix size indicates number of elements in the beginning
3200 // // of the backing storage.
3201 // static const int kPrefixSize = ..;
3202 // // The Element size indicates number of elements per entry.
3203 // static const int kEntrySize = ..;
3205 // The prefix size indicates an amount of memory in the
3206 // beginning of the backing storage that can be used for non-element
3207 // information by subclasses.
3209 template<typename Key>
3212 static const bool UsesSeed = false;
3213 static uint32_t Hash(Key key) { return 0; }
3214 static uint32_t SeededHash(Key key, uint32_t seed) {
3218 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3219 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3221 return HashForObject(key, object);
3225 template<typename Derived, typename Shape, typename Key>
3226 class HashTable: public FixedArray {
3229 inline uint32_t Hash(Key key) {
3230 if (Shape::UsesSeed) {
3231 return Shape::SeededHash(key, GetHeap()->HashSeed());
3233 return Shape::Hash(key);
3237 inline uint32_t HashForObject(Key key, Object* object) {
3238 if (Shape::UsesSeed) {
3239 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3241 return Shape::HashForObject(key, object);
3245 // Returns the number of elements in the hash table.
3246 int NumberOfElements() {
3247 return Smi::cast(get(kNumberOfElementsIndex))->value();
3250 // Returns the number of deleted elements in the hash table.
3251 int NumberOfDeletedElements() {
3252 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3255 // Returns the capacity of the hash table.
3257 return Smi::cast(get(kCapacityIndex))->value();
3260 // ElementAdded should be called whenever an element is added to a
3262 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3264 // ElementRemoved should be called whenever an element is removed from
3266 void ElementRemoved() {
3267 SetNumberOfElements(NumberOfElements() - 1);
3268 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3270 void ElementsRemoved(int n) {
3271 SetNumberOfElements(NumberOfElements() - n);
3272 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3275 // Returns a new HashTable object.
3276 MUST_USE_RESULT static Handle<Derived> New(
3278 int at_least_space_for,
3279 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3280 PretenureFlag pretenure = NOT_TENURED);
3282 // Computes the required capacity for a table holding the given
3283 // number of elements. May be more than HashTable::kMaxCapacity.
3284 static int ComputeCapacity(int at_least_space_for);
3286 // Returns the key at entry.
3287 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3289 // Tells whether k is a real key. The hole and undefined are not allowed
3290 // as keys and can be used to indicate missing or deleted elements.
3291 bool IsKey(Object* k) {
3292 return !k->IsTheHole() && !k->IsUndefined();
3295 // Garbage collection support.
3296 void IteratePrefix(ObjectVisitor* visitor);
3297 void IterateElements(ObjectVisitor* visitor);
3299 DECLARE_CAST(HashTable)
3301 // Compute the probe offset (quadratic probing).
3302 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3303 return (n + n * n) >> 1;
3306 static const int kNumberOfElementsIndex = 0;
3307 static const int kNumberOfDeletedElementsIndex = 1;
3308 static const int kCapacityIndex = 2;
3309 static const int kPrefixStartIndex = 3;
3310 static const int kElementsStartIndex =
3311 kPrefixStartIndex + Shape::kPrefixSize;
3312 static const int kEntrySize = Shape::kEntrySize;
3313 static const int kElementsStartOffset =
3314 kHeaderSize + kElementsStartIndex * kPointerSize;
3315 static const int kCapacityOffset =
3316 kHeaderSize + kCapacityIndex * kPointerSize;
3318 // Constant used for denoting a absent entry.
3319 static const int kNotFound = -1;
3321 // Maximal capacity of HashTable. Based on maximal length of underlying
3322 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3324 static const int kMaxCapacity =
3325 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3327 // Find entry for key otherwise return kNotFound.
3328 inline int FindEntry(Key key);
3329 int FindEntry(Isolate* isolate, Key key);
3331 // Rehashes the table in-place.
3332 void Rehash(Key key);
3335 friend class ObjectHashTable;
3337 // Find the entry at which to insert element with the given key that
3338 // has the given hash value.
3339 uint32_t FindInsertionEntry(uint32_t hash);
3341 // Returns the index for an entry (of the key)
3342 static inline int EntryToIndex(int entry) {
3343 return (entry * kEntrySize) + kElementsStartIndex;
3346 // Update the number of elements in the hash table.
3347 void SetNumberOfElements(int nof) {
3348 set(kNumberOfElementsIndex, Smi::FromInt(nof));
3351 // Update the number of deleted elements in the hash table.
3352 void SetNumberOfDeletedElements(int nod) {
3353 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3356 // Sets the capacity of the hash table.
3357 void SetCapacity(int capacity) {
3358 // To scale a computed hash code to fit within the hash table, we
3359 // use bit-wise AND with a mask, so the capacity must be positive
3361 DCHECK(capacity > 0);
3362 DCHECK(capacity <= kMaxCapacity);
3363 set(kCapacityIndex, Smi::FromInt(capacity));
3367 // Returns probe entry.
3368 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3369 DCHECK(base::bits::IsPowerOfTwo32(size));
3370 return (hash + GetProbeOffset(number)) & (size - 1);
3373 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3374 return hash & (size - 1);
3377 inline static uint32_t NextProbe(
3378 uint32_t last, uint32_t number, uint32_t size) {
3379 return (last + number) & (size - 1);
3382 // Attempt to shrink hash table after removal of key.
3383 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3385 // Ensure enough space for n additional elements.
3386 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3387 Handle<Derived> table,
3390 PretenureFlag pretenure = NOT_TENURED);
3393 // Returns _expected_ if one of entries given by the first _probe_ probes is
3394 // equal to _expected_. Otherwise, returns the entry given by the probe
3396 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3398 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3400 // Rehashes this hash-table into the new table.
3401 void Rehash(Handle<Derived> new_table, Key key);
3405 // HashTableKey is an abstract superclass for virtual key behavior.
3406 class HashTableKey {
3408 // Returns whether the other object matches this key.
3409 virtual bool IsMatch(Object* other) = 0;
3410 // Returns the hash value for this key.
3411 virtual uint32_t Hash() = 0;
3412 // Returns the hash value for object.
3413 virtual uint32_t HashForObject(Object* key) = 0;
3414 // Returns the key object for storing into the hash table.
3415 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3417 virtual ~HashTableKey() {}
3421 class StringTableShape : public BaseShape<HashTableKey*> {
3423 static inline bool IsMatch(HashTableKey* key, Object* value) {
3424 return key->IsMatch(value);
3427 static inline uint32_t Hash(HashTableKey* key) {
3431 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3432 return key->HashForObject(object);
3435 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3437 static const int kPrefixSize = 0;
3438 static const int kEntrySize = 1;
3441 class SeqOneByteString;
3445 // No special elements in the prefix and the element size is 1
3446 // because only the string itself (the key) needs to be stored.
3447 class StringTable: public HashTable<StringTable,
3451 // Find string in the string table. If it is not there yet, it is
3452 // added. The return value is the string found.
3453 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3454 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3456 // Tries to internalize given string and returns string handle on success
3457 // or an empty handle otherwise.
3458 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3460 Handle<String> string);
3462 // Looks up a string that is equal to the given string and returns
3463 // string handle if it is found, or an empty handle otherwise.
3464 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3466 Handle<String> str);
3467 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3472 DECLARE_CAST(StringTable)
3475 template <bool seq_one_byte>
3476 friend class JsonParser;
3478 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3482 class MapCacheShape : public BaseShape<HashTableKey*> {
3484 static inline bool IsMatch(HashTableKey* key, Object* value) {
3485 return key->IsMatch(value);
3488 static inline uint32_t Hash(HashTableKey* key) {
3492 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3493 return key->HashForObject(object);
3496 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3498 static const int kPrefixSize = 0;
3499 static const int kEntrySize = 2;
3505 // Maps keys that are a fixed array of unique names to a map.
3506 // Used for canonicalize maps for object literals.
3507 class MapCache: public HashTable<MapCache, MapCacheShape, HashTableKey*> {
3509 // Find cached value for a name key, otherwise return null.
3510 Object* Lookup(FixedArray* key);
3511 static Handle<MapCache> Put(
3512 Handle<MapCache> map_cache, Handle<FixedArray> key, Handle<Map> value);
3513 DECLARE_CAST(MapCache)
3516 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
3520 template <typename Derived, typename Shape, typename Key>
3521 class Dictionary: public HashTable<Derived, Shape, Key> {
3523 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3526 // Returns the value at entry.
3527 Object* ValueAt(int entry) {
3528 return this->get(DerivedHashTable::EntryToIndex(entry) + 1);
3531 // Set the value for entry.
3532 void ValueAtPut(int entry, Object* value) {
3533 this->set(DerivedHashTable::EntryToIndex(entry) + 1, value);
3536 // Returns the property details for the property at entry.
3537 PropertyDetails DetailsAt(int entry) {
3538 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3539 return PropertyDetails(
3540 Smi::cast(this->get(DerivedHashTable::EntryToIndex(entry) + 2)));
3543 // Set the details for entry.
3544 void DetailsAtPut(int entry, PropertyDetails value) {
3545 this->set(DerivedHashTable::EntryToIndex(entry) + 2, value.AsSmi());
3549 void CopyValuesTo(FixedArray* elements);
3551 // Delete a property from the dictionary.
3552 static Handle<Object> DeleteProperty(
3553 Handle<Derived> dictionary,
3555 JSObject::DeleteMode mode);
3557 // Attempt to shrink the dictionary after deletion of key.
3558 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3559 Handle<Derived> dictionary,
3561 return DerivedHashTable::Shrink(dictionary, key);
3564 // Returns the number of elements in the dictionary filtering out properties
3565 // with the specified attributes.
3566 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3568 // Returns the number of enumerable elements in the dictionary.
3569 int NumberOfEnumElements();
3571 enum SortMode { UNSORTED, SORTED };
3572 // Copies keys to preallocated fixed array.
3573 void CopyKeysTo(FixedArray* storage,
3574 PropertyAttributes filter,
3575 SortMode sort_mode);
3576 // Fill in details for properties into storage.
3577 void CopyKeysTo(FixedArray* storage,
3579 PropertyAttributes filter,
3580 SortMode sort_mode);
3582 // Accessors for next enumeration index.
3583 void SetNextEnumerationIndex(int index) {
3585 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3588 int NextEnumerationIndex() {
3589 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3592 // Creates a new dictionary.
3593 MUST_USE_RESULT static Handle<Derived> New(
3595 int at_least_space_for,
3596 PretenureFlag pretenure = NOT_TENURED);
3598 // Ensure enough space for n additional elements.
3599 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3602 void Print(OStream& os); // NOLINT
3604 // Returns the key (slow).
3605 Object* SlowReverseLookup(Object* value);
3607 // Sets the entry to (key, value) pair.
3608 inline void SetEntry(int entry,
3610 Handle<Object> value);
3611 inline void SetEntry(int entry,
3613 Handle<Object> value,
3614 PropertyDetails details);
3616 MUST_USE_RESULT static Handle<Derived> Add(
3617 Handle<Derived> dictionary,
3619 Handle<Object> value,
3620 PropertyDetails details);
3623 // Generic at put operation.
3624 MUST_USE_RESULT static Handle<Derived> AtPut(
3625 Handle<Derived> dictionary,
3627 Handle<Object> value);
3629 // Add entry to dictionary.
3630 static void AddEntry(
3631 Handle<Derived> dictionary,
3633 Handle<Object> value,
3634 PropertyDetails details,
3637 // Generate new enumeration indices to avoid enumeration index overflow.
3638 static void GenerateNewEnumerationIndices(Handle<Derived> dictionary);
3639 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3640 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3644 class NameDictionaryShape : public BaseShape<Handle<Name> > {
3646 static inline bool IsMatch(Handle<Name> key, Object* other);
3647 static inline uint32_t Hash(Handle<Name> key);
3648 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3649 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3650 static const int kPrefixSize = 2;
3651 static const int kEntrySize = 3;
3652 static const bool kIsEnumerable = true;
3656 class NameDictionary: public Dictionary<NameDictionary,
3657 NameDictionaryShape,
3660 NameDictionary, NameDictionaryShape, Handle<Name> > DerivedDictionary;
3663 DECLARE_CAST(NameDictionary)
3665 // Copies enumerable keys to preallocated fixed array.
3666 void CopyEnumKeysTo(FixedArray* storage);
3667 inline static void DoGenerateNewEnumerationIndices(
3668 Handle<NameDictionary> dictionary);
3670 // Find entry for key, otherwise return kNotFound. Optimized version of
3671 // HashTable::FindEntry.
3672 int FindEntry(Handle<Name> key);
3676 class NumberDictionaryShape : public BaseShape<uint32_t> {
3678 static inline bool IsMatch(uint32_t key, Object* other);
3679 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3680 static const int kEntrySize = 3;
3681 static const bool kIsEnumerable = false;
3685 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3687 static const bool UsesSeed = true;
3688 static const int kPrefixSize = 2;
3690 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3691 static inline uint32_t SeededHashForObject(uint32_t key,
3697 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3699 static const int kPrefixSize = 0;
3701 static inline uint32_t Hash(uint32_t key);
3702 static inline uint32_t HashForObject(uint32_t key, Object* object);
3706 class SeededNumberDictionary
3707 : public Dictionary<SeededNumberDictionary,
3708 SeededNumberDictionaryShape,
3711 DECLARE_CAST(SeededNumberDictionary)
3713 // Type specific at put (default NONE attributes is used when adding).
3714 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3715 Handle<SeededNumberDictionary> dictionary,
3717 Handle<Object> value);
3718 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3719 Handle<SeededNumberDictionary> dictionary,
3721 Handle<Object> value,
3722 PropertyDetails details);
3724 // Set an existing entry or add a new one if needed.
3725 // Return the updated dictionary.
3726 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3727 Handle<SeededNumberDictionary> dictionary,
3729 Handle<Object> value,
3730 PropertyDetails details);
3732 void UpdateMaxNumberKey(uint32_t key);
3734 // If slow elements are required we will never go back to fast-case
3735 // for the elements kept in this dictionary. We require slow
3736 // elements if an element has been added at an index larger than
3737 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3738 // when defining a getter or setter with a number key.
3739 inline bool requires_slow_elements();
3740 inline void set_requires_slow_elements();
3742 // Get the value of the max number key that has been added to this
3743 // dictionary. max_number_key can only be called if
3744 // requires_slow_elements returns false.
3745 inline uint32_t max_number_key();
3748 static const int kRequiresSlowElementsMask = 1;
3749 static const int kRequiresSlowElementsTagSize = 1;
3750 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3754 class UnseededNumberDictionary
3755 : public Dictionary<UnseededNumberDictionary,
3756 UnseededNumberDictionaryShape,
3759 DECLARE_CAST(UnseededNumberDictionary)
3761 // Type specific at put (default NONE attributes is used when adding).
3762 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3763 Handle<UnseededNumberDictionary> dictionary,
3765 Handle<Object> value);
3766 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3767 Handle<UnseededNumberDictionary> dictionary,
3769 Handle<Object> value);
3771 // Set an existing entry or add a new one if needed.
3772 // Return the updated dictionary.
3773 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3774 Handle<UnseededNumberDictionary> dictionary,
3776 Handle<Object> value);
3780 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3782 static inline bool IsMatch(Handle<Object> key, Object* other);
3783 static inline uint32_t Hash(Handle<Object> key);
3784 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3785 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3786 static const int kPrefixSize = 0;
3787 static const int kEntrySize = 2;
3791 // ObjectHashTable maps keys that are arbitrary objects to object values by
3792 // using the identity hash of the key for hashing purposes.
3793 class ObjectHashTable: public HashTable<ObjectHashTable,
3794 ObjectHashTableShape,
3797 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3799 DECLARE_CAST(ObjectHashTable)
3801 // Attempt to shrink hash table after removal of key.
3802 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3803 Handle<ObjectHashTable> table,
3804 Handle<Object> key);
3806 // Looks up the value associated with the given key. The hole value is
3807 // returned in case the key is not present.
3808 Object* Lookup(Handle<Object> key);
3810 // Adds (or overwrites) the value associated with the given key.
3811 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3813 Handle<Object> value);
3815 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3816 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3821 friend class MarkCompactCollector;
3823 void AddEntry(int entry, Object* key, Object* value);
3824 void RemoveEntry(int entry);
3826 // Returns the index to the value of an entry.
3827 static inline int EntryToValueIndex(int entry) {
3828 return EntryToIndex(entry) + 1;
3833 // OrderedHashTable is a HashTable with Object keys that preserves
3834 // insertion order. There are Map and Set interfaces (OrderedHashMap
3835 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3837 // Only Object* keys are supported, with Object::SameValueZero() used as the
3838 // equality operator and Object::GetHash() for the hash function.
3840 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3841 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3842 // Originally attributed to Tyler Close.
3845 // [0]: bucket count
3846 // [1]: element count
3847 // [2]: deleted element count
3848 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3849 // offset into the data table (see below) where the
3850 // first item in this bucket is stored.
3851 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3852 // Capacity() * kEntrySize, where the first entrysize
3853 // items are handled by the derived class and the
3854 // item at kChainOffset is another entry into the
3855 // data table indicating the next entry in this hash
3858 // When we transition the table to a new version we obsolete it and reuse parts
3859 // of the memory to store information how to transition an iterator to the new
3862 // Memory layout for obsolete table:
3863 // [0]: bucket count
3864 // [1]: Next newer table
3865 // [2]: Number of removed holes or -1 when the table was cleared.
3866 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3867 // [3 + NumberOfRemovedHoles()..length]: Not used
3869 template<class Derived, class Iterator, int entrysize>
3870 class OrderedHashTable: public FixedArray {
3872 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3873 static Handle<Derived> Allocate(
3874 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3876 // Returns an OrderedHashTable (possibly |table|) with enough space
3877 // to add at least one new element.
3878 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3880 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3882 static Handle<Derived> Shrink(Handle<Derived> table);
3884 // Returns a new empty OrderedHashTable and records the clearing so that
3885 // exisiting iterators can be updated.
3886 static Handle<Derived> Clear(Handle<Derived> table);
3888 // Returns an OrderedHashTable (possibly |table|) where |key| has been
3890 static Handle<Derived> Remove(Handle<Derived> table, Handle<Object> key,
3893 // Returns kNotFound if the key isn't present.
3894 int FindEntry(Handle<Object> key, int hash);
3896 // Like the above, but doesn't require the caller to provide a hash.
3897 int FindEntry(Handle<Object> key);
3899 int NumberOfElements() {
3900 return Smi::cast(get(kNumberOfElementsIndex))->value();
3903 int NumberOfDeletedElements() {
3904 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3907 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3909 int NumberOfBuckets() {
3910 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3913 // Returns the index into the data table where the new entry
3914 // should be placed. The table is assumed to have enough space
3916 int AddEntry(int hash);
3918 // Removes the entry, and puts the_hole in entrysize pointers
3919 // (leaving the hash table chain intact).
3920 void RemoveEntry(int entry);
3922 // Returns an index into |this| for the given entry.
3923 int EntryToIndex(int entry) {
3924 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3927 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3930 return !get(kNextTableIndex)->IsSmi();
3933 // The next newer table. This is only valid if the table is obsolete.
3934 Derived* NextTable() {
3935 return Derived::cast(get(kNextTableIndex));
3938 // When the table is obsolete we store the indexes of the removed holes.
3939 int RemovedIndexAt(int index) {
3940 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3943 static const int kNotFound = -1;
3944 static const int kMinCapacity = 4;
3947 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3949 void SetNumberOfBuckets(int num) {
3950 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3953 void SetNumberOfElements(int num) {
3954 set(kNumberOfElementsIndex, Smi::FromInt(num));
3957 void SetNumberOfDeletedElements(int num) {
3958 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3962 return NumberOfBuckets() * kLoadFactor;
3965 // Returns the next entry for the given entry.
3966 int ChainAt(int entry) {
3967 return Smi::cast(get(EntryToIndex(entry) + kChainOffset))->value();
3970 int HashToBucket(int hash) {
3971 return hash & (NumberOfBuckets() - 1);
3974 int HashToEntry(int hash) {
3975 int bucket = HashToBucket(hash);
3976 return Smi::cast(get(kHashTableStartIndex + bucket))->value();
3979 void SetNextTable(Derived* next_table) {
3980 set(kNextTableIndex, next_table);
3983 void SetRemovedIndexAt(int index, int removed_index) {
3984 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3987 static const int kNumberOfBucketsIndex = 0;
3988 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3989 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3990 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3992 static const int kNextTableIndex = kNumberOfElementsIndex;
3993 static const int kRemovedHolesIndex = kHashTableStartIndex;
3995 static const int kEntrySize = entrysize + 1;
3996 static const int kChainOffset = entrysize;
3998 static const int kLoadFactor = 2;
3999 static const int kMaxCapacity =
4000 (FixedArray::kMaxLength - kHashTableStartIndex)
4001 / (1 + (kEntrySize * kLoadFactor));
4005 class JSSetIterator;
4008 class OrderedHashSet: public OrderedHashTable<
4009 OrderedHashSet, JSSetIterator, 1> {
4011 DECLARE_CAST(OrderedHashSet)
4013 bool Contains(Handle<Object> key);
4014 static Handle<OrderedHashSet> Add(
4015 Handle<OrderedHashSet> table, Handle<Object> key);
4019 class JSMapIterator;
4022 class OrderedHashMap:public OrderedHashTable<
4023 OrderedHashMap, JSMapIterator, 2> {
4025 DECLARE_CAST(OrderedHashMap)
4027 Object* Lookup(Handle<Object> key);
4028 static Handle<OrderedHashMap> Put(
4029 Handle<OrderedHashMap> table,
4031 Handle<Object> value);
4033 Object* ValueAt(int entry) {
4034 return get(EntryToIndex(entry) + kValueOffset);
4038 static const int kValueOffset = 1;
4042 template <int entrysize>
4043 class WeakHashTableShape : public BaseShape<Handle<Object> > {
4045 static inline bool IsMatch(Handle<Object> key, Object* other);
4046 static inline uint32_t Hash(Handle<Object> key);
4047 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
4048 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
4049 static const int kPrefixSize = 0;
4050 static const int kEntrySize = entrysize;
4054 // WeakHashTable maps keys that are arbitrary objects to object values.
4055 // It is used for the global weak hash table that maps objects
4056 // embedded in optimized code to dependent code lists.
4057 class WeakHashTable: public HashTable<WeakHashTable,
4058 WeakHashTableShape<2>,
4061 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
4063 DECLARE_CAST(WeakHashTable)
4065 // Looks up the value associated with the given key. The hole value is
4066 // returned in case the key is not present.
4067 Object* Lookup(Handle<Object> key);
4069 // Adds (or overwrites) the value associated with the given key. Mapping a
4070 // key to the hole value causes removal of the whole entry.
4071 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
4073 Handle<Object> value);
4075 // This function is called when heap verification is turned on.
4076 void Zap(Object* value) {
4077 int capacity = Capacity();
4078 for (int i = 0; i < capacity; i++) {
4079 set(EntryToIndex(i), value);
4080 set(EntryToValueIndex(i), value);
4085 friend class MarkCompactCollector;
4087 void AddEntry(int entry, Handle<Object> key, Handle<Object> value);
4089 // Returns the index to the value of an entry.
4090 static inline int EntryToValueIndex(int entry) {
4091 return EntryToIndex(entry) + 1;
4096 // JSFunctionResultCache caches results of some JSFunction invocation.
4097 // It is a fixed array with fixed structure:
4098 // [0]: factory function
4099 // [1]: finger index
4100 // [2]: current cache size
4101 // [3]: dummy field.
4102 // The rest of array are key/value pairs.
4103 class JSFunctionResultCache: public FixedArray {
4105 static const int kFactoryIndex = 0;
4106 static const int kFingerIndex = kFactoryIndex + 1;
4107 static const int kCacheSizeIndex = kFingerIndex + 1;
4108 static const int kDummyIndex = kCacheSizeIndex + 1;
4109 static const int kEntriesIndex = kDummyIndex + 1;
4111 static const int kEntrySize = 2; // key + value
4113 static const int kFactoryOffset = kHeaderSize;
4114 static const int kFingerOffset = kFactoryOffset + kPointerSize;
4115 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4117 inline void MakeZeroSize();
4118 inline void Clear();
4121 inline void set_size(int size);
4122 inline int finger_index();
4123 inline void set_finger_index(int finger_index);
4125 DECLARE_CAST(JSFunctionResultCache)
4127 DECLARE_VERIFIER(JSFunctionResultCache)
4131 // ScopeInfo represents information about different scopes of a source
4132 // program and the allocation of the scope's variables. Scope information
4133 // is stored in a compressed form in ScopeInfo objects and is used
4134 // at runtime (stack dumps, deoptimization, etc.).
4136 // This object provides quick access to scope info details for runtime
4138 class ScopeInfo : public FixedArray {
4140 DECLARE_CAST(ScopeInfo)
4142 // Return the type of this scope.
4143 ScopeType scope_type();
4145 // Does this scope call eval?
4148 // Return the strict mode of this scope.
4149 StrictMode strict_mode();
4151 // Does this scope make a sloppy eval call?
4152 bool CallsSloppyEval() { return CallsEval() && strict_mode() == SLOPPY; }
4154 // Return the total number of locals allocated on the stack and in the
4155 // context. This includes the parameters that are allocated in the context.
4158 // Return the number of stack slots for code. This number consists of two
4160 // 1. One stack slot per stack allocated local.
4161 // 2. One stack slot for the function name if it is stack allocated.
4162 int StackSlotCount();
4164 // Return the number of context slots for code if a context is allocated. This
4165 // number consists of three parts:
4166 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4167 // 2. One context slot per context allocated local.
4168 // 3. One context slot for the function name if it is context allocated.
4169 // Parameters allocated in the context count as context allocated locals. If
4170 // no contexts are allocated for this scope ContextLength returns 0.
4171 int ContextLength();
4173 // Is this scope the scope of a named function expression?
4174 bool HasFunctionName();
4176 // Return if this has context allocated locals.
4177 bool HasHeapAllocatedLocals();
4179 // Return if contexts are allocated for this scope.
4182 // Return if this is a function scope with "use asm".
4183 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
4185 // Return if this is a nested function within an asm module scope.
4186 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
4188 // Return the function_name if present.
4189 String* FunctionName();
4191 // Return the name of the given parameter.
4192 String* ParameterName(int var);
4194 // Return the name of the given local.
4195 String* LocalName(int var);
4197 // Return the name of the given stack local.
4198 String* StackLocalName(int var);
4200 // Return the name of the given context local.
4201 String* ContextLocalName(int var);
4203 // Return the mode of the given context local.
4204 VariableMode ContextLocalMode(int var);
4206 // Return the initialization flag of the given context local.
4207 InitializationFlag ContextLocalInitFlag(int var);
4209 // Return the initialization flag of the given context local.
4210 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
4212 // Return true if this local was introduced by the compiler, and should not be
4213 // exposed to the user in a debugger.
4214 bool LocalIsSynthetic(int var);
4216 // Lookup support for serialized scope info. Returns the
4217 // the stack slot index for a given slot name if the slot is
4218 // present; otherwise returns a value < 0. The name must be an internalized
4220 int StackSlotIndex(String* name);
4222 // Lookup support for serialized scope info. Returns the
4223 // context slot index for a given slot name if the slot is present; otherwise
4224 // returns a value < 0. The name must be an internalized string.
4225 // If the slot is present and mode != NULL, sets *mode to the corresponding
4226 // mode for that variable.
4227 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
4228 VariableMode* mode, InitializationFlag* init_flag,
4229 MaybeAssignedFlag* maybe_assigned_flag);
4231 // Lookup support for serialized scope info. Returns the
4232 // parameter index for a given parameter name if the parameter is present;
4233 // otherwise returns a value < 0. The name must be an internalized string.
4234 int ParameterIndex(String* name);
4236 // Lookup support for serialized scope info. Returns the function context
4237 // slot index if the function name is present and context-allocated (named
4238 // function expressions, only), otherwise returns a value < 0. The name
4239 // must be an internalized string.
4240 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4243 // Copies all the context locals into an object used to materialize a scope.
4244 static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4245 Handle<Context> context,
4246 Handle<JSObject> scope_object);
4249 static Handle<ScopeInfo> Create(Scope* scope, Zone* zone);
4251 // Serializes empty scope info.
4252 static ScopeInfo* Empty(Isolate* isolate);
4258 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4259 // numeric and occupies one array slot.
4260 // 1. A set of properties of the scope
4261 // 2. The number of parameters. This only applies to function scopes. For
4262 // non-function scopes this is 0.
4263 // 3. The number of non-parameter variables allocated on the stack.
4264 // 4. The number of non-parameter and parameter variables allocated in the
4266 #define FOR_EACH_NUMERIC_FIELD(V) \
4269 V(StackLocalCount) \
4270 V(ContextLocalCount)
4272 #define FIELD_ACCESSORS(name) \
4273 void Set##name(int value) { \
4274 set(k##name, Smi::FromInt(value)); \
4277 if (length() > 0) { \
4278 return Smi::cast(get(k##name))->value(); \
4283 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4284 #undef FIELD_ACCESSORS
4288 #define DECL_INDEX(name) k##name,
4289 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4291 #undef FOR_EACH_NUMERIC_FIELD
4295 // The layout of the variable part of a ScopeInfo is as follows:
4296 // 1. ParameterEntries:
4297 // This part stores the names of the parameters for function scopes. One
4298 // slot is used per parameter, so in total this part occupies
4299 // ParameterCount() slots in the array. For other scopes than function
4300 // scopes ParameterCount() is 0.
4301 // 2. StackLocalEntries:
4302 // Contains the names of local variables that are allocated on the stack,
4303 // in increasing order of the stack slot index. One slot is used per stack
4304 // local, so in total this part occupies StackLocalCount() slots in the
4306 // 3. ContextLocalNameEntries:
4307 // Contains the names of local variables and parameters that are allocated
4308 // in the context. They are stored in increasing order of the context slot
4309 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4310 // context local, so in total this part occupies ContextLocalCount() slots
4312 // 4. ContextLocalInfoEntries:
4313 // Contains the variable modes and initialization flags corresponding to
4314 // the context locals in ContextLocalNameEntries. One slot is used per
4315 // context local, so in total this part occupies ContextLocalCount()
4316 // slots in the array.
4317 // 5. FunctionNameEntryIndex:
4318 // If the scope belongs to a named function expression this part contains
4319 // information about the function variable. It always occupies two array
4320 // slots: a. The name of the function variable.
4321 // b. The context or stack slot index for the variable.
4322 int ParameterEntriesIndex();
4323 int StackLocalEntriesIndex();
4324 int ContextLocalNameEntriesIndex();
4325 int ContextLocalInfoEntriesIndex();
4326 int FunctionNameEntryIndex();
4328 // Location of the function variable for named function expressions.
4329 enum FunctionVariableInfo {
4330 NONE, // No function name present.
4336 // Properties of scopes.
4337 class ScopeTypeField: public BitField<ScopeType, 0, 3> {};
4338 class CallsEvalField: public BitField<bool, 3, 1> {};
4339 class StrictModeField: public BitField<StrictMode, 4, 1> {};
4340 class FunctionVariableField: public BitField<FunctionVariableInfo, 5, 2> {};
4341 class FunctionVariableMode: public BitField<VariableMode, 7, 3> {};
4342 class AsmModuleField : public BitField<bool, 10, 1> {};
4343 class AsmFunctionField : public BitField<bool, 11, 1> {};
4345 // BitFields representing the encoded information for context locals in the
4346 // ContextLocalInfoEntries part.
4347 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4348 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4349 class ContextLocalMaybeAssignedFlag
4350 : public BitField<MaybeAssignedFlag, 4, 1> {};
4354 // The cache for maps used by normalized (dictionary mode) objects.
4355 // Such maps do not have property descriptors, so a typical program
4356 // needs very limited number of distinct normalized maps.
4357 class NormalizedMapCache: public FixedArray {
4359 static Handle<NormalizedMapCache> New(Isolate* isolate);
4361 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4362 PropertyNormalizationMode mode);
4363 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4367 DECLARE_CAST(NormalizedMapCache)
4369 static inline bool IsNormalizedMapCache(const Object* obj);
4371 DECLARE_VERIFIER(NormalizedMapCache)
4373 static const int kEntries = 64;
4375 static inline int GetIndex(Handle<Map> map);
4377 // The following declarations hide base class methods.
4378 Object* get(int index);
4379 void set(int index, Object* value);
4383 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4384 // that is attached to code objects.
4385 class ByteArray: public FixedArrayBase {
4387 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4389 // Setter and getter.
4390 inline byte get(int index);
4391 inline void set(int index, byte value);
4393 // Treat contents as an int array.
4394 inline int get_int(int index);
4396 static int SizeFor(int length) {
4397 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4399 // We use byte arrays for free blocks in the heap. Given a desired size in
4400 // bytes that is a multiple of the word size and big enough to hold a byte
4401 // array, this function returns the number of elements a byte array should
4403 static int LengthFor(int size_in_bytes) {
4404 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4405 DCHECK(size_in_bytes >= kHeaderSize);
4406 return size_in_bytes - kHeaderSize;
4409 // Returns data start address.
4410 inline Address GetDataStartAddress();
4412 // Returns a pointer to the ByteArray object for a given data start address.
4413 static inline ByteArray* FromDataStartAddress(Address address);
4415 DECLARE_CAST(ByteArray)
4417 // Dispatched behavior.
4418 inline int ByteArraySize() {
4419 return SizeFor(this->length());
4421 DECLARE_PRINTER(ByteArray)
4422 DECLARE_VERIFIER(ByteArray)
4424 // Layout description.
4425 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4427 // Maximal memory consumption for a single ByteArray.
4428 static const int kMaxSize = 512 * MB;
4429 // Maximal length of a single ByteArray.
4430 static const int kMaxLength = kMaxSize - kHeaderSize;
4433 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4437 // FreeSpace represents fixed sized areas of the heap that are not currently in
4438 // use. Used by the heap and GC.
4439 class FreeSpace: public HeapObject {
4441 // [size]: size of the free space including the header.
4442 inline int size() const;
4443 inline void set_size(int value);
4445 inline int nobarrier_size() const;
4446 inline void nobarrier_set_size(int value);
4448 inline int Size() { return size(); }
4450 DECLARE_CAST(FreeSpace)
4452 // Dispatched behavior.
4453 DECLARE_PRINTER(FreeSpace)
4454 DECLARE_VERIFIER(FreeSpace)
4456 // Layout description.
4457 // Size is smi tagged when it is stored.
4458 static const int kSizeOffset = HeapObject::kHeaderSize;
4459 static const int kHeaderSize = kSizeOffset + kPointerSize;
4461 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4464 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4468 // V has parameters (Type, type, TYPE, C type, element_size)
4469 #define BUILTIN_TYPED_ARRAY(V) \
4470 V(Uint8, uint8, UINT8, uint8_t, 1) \
4471 V(Int8, int8, INT8, int8_t, 1) \
4472 V(Uint16, uint16, UINT16, uint16_t, 2) \
4473 V(Int16, int16, INT16, int16_t, 2) \
4474 V(Uint32, uint32, UINT32, uint32_t, 4) \
4475 V(Int32, int32, INT32, int32_t, 4) \
4476 V(Float32, float32, FLOAT32, float, 4) \
4477 V(Float64, float64, FLOAT64, double, 8) \
4478 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4481 #define SIMD128_TYPED_ARRAY(V) \
4482 V(Float32x4, float32x4, FLOAT32x4, v8::internal::float32x4_value_t, 16) \
4483 V(Float64x2, float64x2, FLOAT64x2, v8::internal::float64x2_value_t, 16) \
4484 V(Int32x4, int32x4, INT32x4, v8::internal::int32x4_value_t, 16)
4487 #define TYPED_ARRAYS(V) \
4488 BUILTIN_TYPED_ARRAY(V) \
4489 SIMD128_TYPED_ARRAY(V)
4492 // An ExternalArray represents a fixed-size array of primitive values
4493 // which live outside the JavaScript heap. Its subclasses are used to
4494 // implement the CanvasArray types being defined in the WebGL
4495 // specification. As of this writing the first public draft is not yet
4496 // available, but Khronos members can access the draft at:
4497 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4499 // The semantics of these arrays differ from CanvasPixelArray.
4500 // Out-of-range values passed to the setter are converted via a C
4501 // cast, not clamping. Out-of-range indices cause exceptions to be
4502 // raised rather than being silently ignored.
4503 class ExternalArray: public FixedArrayBase {
4505 inline bool is_the_hole(int index) { return false; }
4507 // [external_pointer]: The pointer to the external memory area backing this
4509 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4511 DECLARE_CAST(ExternalArray)
4513 // Maximal acceptable length for an external array.
4514 static const int kMaxLength = 0x3fffffff;
4516 // ExternalArray headers are not quadword aligned.
4517 static const int kExternalPointerOffset =
4518 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4519 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4520 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4523 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4527 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4528 // semantics used for implementing the CanvasPixelArray object. Please see the
4529 // specification at:
4531 // http://www.whatwg.org/specs/web-apps/current-work/
4532 // multipage/the-canvas-element.html#canvaspixelarray
4533 // In particular, write access clamps the value written to 0 or 255 if the
4534 // value written is outside this range.
4535 class ExternalUint8ClampedArray: public ExternalArray {
4537 inline uint8_t* external_uint8_clamped_pointer();
4539 // Setter and getter.
4540 inline uint8_t get_scalar(int index);
4541 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4543 inline void set(int index, uint8_t value);
4545 // This accessor applies the correct conversion from Smi, HeapNumber
4546 // and undefined and clamps the converted value between 0 and 255.
4547 static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4549 Handle<Object> value);
4551 DECLARE_CAST(ExternalUint8ClampedArray)
4553 // Dispatched behavior.
4554 DECLARE_PRINTER(ExternalUint8ClampedArray)
4555 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4558 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4562 class ExternalInt8Array: public ExternalArray {
4564 // Setter and getter.
4565 inline int8_t get_scalar(int index);
4566 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4567 inline void set(int index, int8_t value);
4569 // This accessor applies the correct conversion from Smi, HeapNumber
4571 static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4573 Handle<Object> value);
4575 DECLARE_CAST(ExternalInt8Array)
4577 // Dispatched behavior.
4578 DECLARE_PRINTER(ExternalInt8Array)
4579 DECLARE_VERIFIER(ExternalInt8Array)
4582 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4586 class ExternalUint8Array: public ExternalArray {
4588 // Setter and getter.
4589 inline uint8_t get_scalar(int index);
4590 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4591 inline void set(int index, uint8_t value);
4593 // This accessor applies the correct conversion from Smi, HeapNumber
4595 static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
4597 Handle<Object> value);
4599 DECLARE_CAST(ExternalUint8Array)
4601 // Dispatched behavior.
4602 DECLARE_PRINTER(ExternalUint8Array)
4603 DECLARE_VERIFIER(ExternalUint8Array)
4606 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4610 class ExternalInt16Array: public ExternalArray {
4612 // Setter and getter.
4613 inline int16_t get_scalar(int index);
4614 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4615 inline void set(int index, int16_t value);
4617 // This accessor applies the correct conversion from Smi, HeapNumber
4619 static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
4621 Handle<Object> value);
4623 DECLARE_CAST(ExternalInt16Array)
4625 // Dispatched behavior.
4626 DECLARE_PRINTER(ExternalInt16Array)
4627 DECLARE_VERIFIER(ExternalInt16Array)
4630 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4634 class ExternalUint16Array: public ExternalArray {
4636 // Setter and getter.
4637 inline uint16_t get_scalar(int index);
4638 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4640 inline void set(int index, uint16_t value);
4642 // This accessor applies the correct conversion from Smi, HeapNumber
4644 static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
4646 Handle<Object> value);
4648 DECLARE_CAST(ExternalUint16Array)
4650 // Dispatched behavior.
4651 DECLARE_PRINTER(ExternalUint16Array)
4652 DECLARE_VERIFIER(ExternalUint16Array)
4655 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4659 class ExternalInt32Array: public ExternalArray {
4661 // Setter and getter.
4662 inline int32_t get_scalar(int index);
4663 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4664 inline void set(int index, int32_t value);
4666 // This accessor applies the correct conversion from Smi, HeapNumber
4668 static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
4670 Handle<Object> value);
4672 DECLARE_CAST(ExternalInt32Array)
4674 // Dispatched behavior.
4675 DECLARE_PRINTER(ExternalInt32Array)
4676 DECLARE_VERIFIER(ExternalInt32Array)
4679 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4683 class ExternalUint32Array: public ExternalArray {
4685 // Setter and getter.
4686 inline uint32_t get_scalar(int index);
4687 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4689 inline void set(int index, uint32_t value);
4691 // This accessor applies the correct conversion from Smi, HeapNumber
4693 static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
4695 Handle<Object> value);
4697 DECLARE_CAST(ExternalUint32Array)
4699 // Dispatched behavior.
4700 DECLARE_PRINTER(ExternalUint32Array)
4701 DECLARE_VERIFIER(ExternalUint32Array)
4704 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4708 class ExternalFloat32Array: public ExternalArray {
4710 // Setter and getter.
4711 inline float get_scalar(int index);
4712 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4714 inline void set(int index, float value);
4716 // This accessor applies the correct conversion from Smi, HeapNumber
4718 static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
4720 Handle<Object> value);
4722 DECLARE_CAST(ExternalFloat32Array)
4724 // Dispatched behavior.
4725 DECLARE_PRINTER(ExternalFloat32Array)
4726 DECLARE_VERIFIER(ExternalFloat32Array)
4729 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4733 class ExternalFloat32x4Array: public ExternalArray {
4735 // Setter and getter.
4736 inline float32x4_value_t get_scalar(int index);
4737 static inline Handle<Object> get(Handle<ExternalFloat32x4Array> array,
4739 inline void set(int index, const float32x4_value_t& value);
4741 // This accessor applies the correct conversion from Smi, HeapNumber
4743 static Handle<Object> SetValue(Handle<ExternalFloat32x4Array> array,
4745 Handle<Object> value);
4748 DECLARE_CAST(ExternalFloat32x4Array)
4750 // Dispatched behavior.
4751 DECLARE_PRINTER(ExternalFloat32x4Array)
4752 DECLARE_VERIFIER(ExternalFloat32x4Array)
4755 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32x4Array);
4759 class ExternalFloat64x2Array: public ExternalArray {
4761 // Setter and getter.
4762 inline float64x2_value_t get_scalar(int index);
4763 static inline Handle<Object> get(Handle<ExternalFloat64x2Array> array,
4765 inline void set(int index, const float64x2_value_t& value);
4767 // This accessor applies the correct conversion from Smi, HeapNumber
4769 static Handle<Object> SetValue(Handle<ExternalFloat64x2Array> array,
4771 Handle<Object> value);
4774 DECLARE_CAST(ExternalFloat64x2Array)
4776 // Dispatched behavior.
4777 DECLARE_PRINTER(ExternalFloat64x2Array)
4778 DECLARE_VERIFIER(ExternalFloat64x2Array)
4781 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64x2Array);
4785 class ExternalInt32x4Array: public ExternalArray {
4787 // Setter and getter.
4788 inline int32x4_value_t get_scalar(int index);
4789 static inline Handle<Object> get(Handle<ExternalInt32x4Array> array,
4791 inline void set(int index, const int32x4_value_t& value);
4793 // This accessor applies the correct conversion from Smi, HeapNumber
4795 static Handle<Object> SetValue(Handle<ExternalInt32x4Array> array,
4797 Handle<Object> value);
4800 DECLARE_CAST(ExternalInt32x4Array)
4802 // Dispatched behavior.
4803 DECLARE_PRINTER(ExternalInt32x4Array)
4804 DECLARE_VERIFIER(ExternalInt32x4Array)
4807 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32x4Array);
4811 class ExternalFloat64Array: public ExternalArray {
4813 // Setter and getter.
4814 inline double get_scalar(int index);
4815 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4817 inline void set(int index, double value);
4819 // This accessor applies the correct conversion from Smi, HeapNumber
4821 static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
4823 Handle<Object> value);
4825 DECLARE_CAST(ExternalFloat64Array)
4827 // Dispatched behavior.
4828 DECLARE_PRINTER(ExternalFloat64Array)
4829 DECLARE_VERIFIER(ExternalFloat64Array)
4832 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4836 class FixedTypedArrayBase: public FixedArrayBase {
4838 DECLARE_CAST(FixedTypedArrayBase)
4840 static const int kDataOffset = kHeaderSize;
4844 inline int TypedArraySize(InstanceType type);
4846 // Use with care: returns raw pointer into heap.
4847 inline void* DataPtr();
4849 inline int DataSize();
4852 inline int DataSize(InstanceType type);
4854 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4858 template <class Traits>
4859 class FixedTypedArray: public FixedTypedArrayBase {
4861 typedef typename Traits::ElementType ElementType;
4862 static const InstanceType kInstanceType = Traits::kInstanceType;
4864 DECLARE_CAST(FixedTypedArray<Traits>)
4866 static inline int ElementOffset(int index) {
4867 return kDataOffset + index * sizeof(ElementType);
4870 static inline int SizeFor(int length) {
4871 return ElementOffset(length);
4874 inline ElementType get_scalar(int index);
4875 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4876 inline void set(int index, ElementType value);
4878 static inline ElementType from_int(int value);
4879 static inline ElementType from_double(double value);
4881 // This accessor applies the correct conversion from Smi, HeapNumber
4883 static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
4885 Handle<Object> value);
4887 DECLARE_PRINTER(FixedTypedArray)
4888 DECLARE_VERIFIER(FixedTypedArray)
4891 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4894 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4895 class Type##ArrayTraits { \
4896 public: /* NOLINT */ \
4897 typedef elementType ElementType; \
4898 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4899 static const char* Designator() { return #type " array"; } \
4900 static inline Handle<Object> ToHandle(Isolate* isolate, \
4901 elementType scalar); \
4902 static inline elementType defaultValue(); \
4905 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4907 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4909 #undef FIXED_TYPED_ARRAY_TRAITS
4911 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4912 // data for code generated by the Hydrogen/Lithium compiler. It also
4913 // contains information about functions that were inlined. If N different
4914 // functions were inlined then first N elements of the literal array will
4915 // contain these functions.
4918 class DeoptimizationInputData: public FixedArray {
4920 // Layout description. Indices in the array.
4921 static const int kTranslationByteArrayIndex = 0;
4922 static const int kInlinedFunctionCountIndex = 1;
4923 static const int kLiteralArrayIndex = 2;
4924 static const int kOsrAstIdIndex = 3;
4925 static const int kOsrPcOffsetIndex = 4;
4926 static const int kOptimizationIdIndex = 5;
4927 static const int kSharedFunctionInfoIndex = 6;
4928 static const int kFirstDeoptEntryIndex = 7;
4930 // Offsets of deopt entry elements relative to the start of the entry.
4931 static const int kAstIdRawOffset = 0;
4932 static const int kTranslationIndexOffset = 1;
4933 static const int kArgumentsStackHeightOffset = 2;
4934 static const int kPcOffset = 3;
4935 static const int kDeoptEntrySize = 4;
4937 // Simple element accessors.
4938 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4940 return type::cast(get(k##name##Index)); \
4942 void Set##name(type* value) { \
4943 set(k##name##Index, value); \
4946 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4947 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4948 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4949 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4950 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4951 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4952 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4954 #undef DEFINE_ELEMENT_ACCESSORS
4956 // Accessors for elements of the ith deoptimization entry.
4957 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4958 type* name(int i) { \
4959 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4961 void Set##name(int i, type* value) { \
4962 set(IndexForEntry(i) + k##name##Offset, value); \
4965 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4966 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4967 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4968 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4970 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4972 BailoutId AstId(int i) {
4973 return BailoutId(AstIdRaw(i)->value());
4976 void SetAstId(int i, BailoutId value) {
4977 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4981 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4984 // Allocates a DeoptimizationInputData.
4985 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4986 int deopt_entry_count,
4987 PretenureFlag pretenure);
4989 DECLARE_CAST(DeoptimizationInputData)
4991 #ifdef ENABLE_DISASSEMBLER
4992 void DeoptimizationInputDataPrint(OStream& os); // NOLINT
4996 static int IndexForEntry(int i) {
4997 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
5001 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
5005 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
5006 // data for code generated by the full compiler.
5007 // The format of the these objects is
5008 // [i * 2]: Ast ID for ith deoptimization.
5009 // [i * 2 + 1]: PC and state of ith deoptimization
5010 class DeoptimizationOutputData: public FixedArray {
5012 int DeoptPoints() { return length() / 2; }
5014 BailoutId AstId(int index) {
5015 return BailoutId(Smi::cast(get(index * 2))->value());
5018 void SetAstId(int index, BailoutId id) {
5019 set(index * 2, Smi::FromInt(id.ToInt()));
5022 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
5023 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
5025 static int LengthOfFixedArray(int deopt_points) {
5026 return deopt_points * 2;
5029 // Allocates a DeoptimizationOutputData.
5030 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
5031 int number_of_deopt_points,
5032 PretenureFlag pretenure);
5034 DECLARE_CAST(DeoptimizationOutputData)
5036 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
5037 void DeoptimizationOutputDataPrint(OStream& os); // NOLINT
5042 // Forward declaration.
5045 class SafepointEntry;
5046 class TypeFeedbackInfo;
5048 // Code describes objects with on-the-fly generated machine code.
5049 class Code: public HeapObject {
5051 // Opaque data type for encapsulating code flags like kind, inline
5052 // cache state, and arguments count.
5053 typedef uint32_t Flags;
5055 #define NON_IC_KIND_LIST(V) \
5057 V(OPTIMIZED_FUNCTION) \
5063 #define IC_KIND_LIST(V) \
5074 #define CODE_KIND_LIST(V) \
5075 NON_IC_KIND_LIST(V) \
5079 #define DEFINE_CODE_KIND_ENUM(name) name,
5080 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
5081 #undef DEFINE_CODE_KIND_ENUM
5085 // No more than 16 kinds. The value is currently encoded in four bits in
5087 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
5089 static const char* Kind2String(Kind kind);
5097 static const int kPrologueOffsetNotSet = -1;
5099 #ifdef ENABLE_DISASSEMBLER
5101 static const char* ICState2String(InlineCacheState state);
5102 static const char* StubType2String(StubType type);
5103 static void PrintExtraICState(OStream& os, // NOLINT
5104 Kind kind, ExtraICState extra);
5105 void Disassemble(const char* name, OStream& os); // NOLINT
5106 #endif // ENABLE_DISASSEMBLER
5108 // [instruction_size]: Size of the native instructions
5109 inline int instruction_size() const;
5110 inline void set_instruction_size(int value);
5112 // [relocation_info]: Code relocation information
5113 DECL_ACCESSORS(relocation_info, ByteArray)
5114 void InvalidateRelocation();
5115 void InvalidateEmbeddedObjects();
5117 // [handler_table]: Fixed array containing offsets of exception handlers.
5118 DECL_ACCESSORS(handler_table, FixedArray)
5120 // [deoptimization_data]: Array containing data for deopt.
5121 DECL_ACCESSORS(deoptimization_data, FixedArray)
5123 // [raw_type_feedback_info]: This field stores various things, depending on
5124 // the kind of the code object.
5125 // FUNCTION => type feedback information.
5126 // STUB and ICs => major/minor key as Smi.
5127 DECL_ACCESSORS(raw_type_feedback_info, Object)
5128 inline Object* type_feedback_info();
5129 inline void set_type_feedback_info(
5130 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5131 inline uint32_t stub_key();
5132 inline void set_stub_key(uint32_t key);
5134 // [next_code_link]: Link for lists of optimized or deoptimized code.
5135 // Note that storage for this field is overlapped with typefeedback_info.
5136 DECL_ACCESSORS(next_code_link, Object)
5138 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5139 // field does not have to be traced during garbage collection since
5140 // it is only used by the garbage collector itself.
5141 DECL_ACCESSORS(gc_metadata, Object)
5143 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5144 // at the moment when this object was created.
5145 inline void set_ic_age(int count);
5146 inline int ic_age() const;
5148 // [prologue_offset]: Offset of the function prologue, used for aging
5149 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5150 inline int prologue_offset() const;
5151 inline void set_prologue_offset(int offset);
5153 // Unchecked accessors to be used during GC.
5154 inline ByteArray* unchecked_relocation_info();
5156 inline int relocation_size();
5158 // [flags]: Various code flags.
5159 inline Flags flags();
5160 inline void set_flags(Flags flags);
5162 // [flags]: Access to specific code flags.
5164 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5165 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5167 inline StubType type(); // Only valid for monomorphic IC stubs.
5169 // Testers for IC stub kinds.
5170 inline bool is_inline_cache_stub();
5171 inline bool is_debug_stub();
5172 inline bool is_handler() { return kind() == HANDLER; }
5173 inline bool is_load_stub() { return kind() == LOAD_IC; }
5174 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5175 inline bool is_store_stub() { return kind() == STORE_IC; }
5176 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5177 inline bool is_call_stub() { return kind() == CALL_IC; }
5178 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5179 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5180 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5181 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5182 inline bool is_keyed_stub();
5183 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5184 inline bool is_weak_stub();
5185 inline void mark_as_weak_stub();
5186 inline bool is_invalidated_weak_stub();
5187 inline void mark_as_invalidated_weak_stub();
5189 inline bool CanBeWeakStub() {
5191 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
5192 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
5193 ic_state() == MONOMORPHIC;
5196 inline bool IsCodeStubOrIC();
5198 inline void set_raw_kind_specific_flags1(int value);
5199 inline void set_raw_kind_specific_flags2(int value);
5201 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
5202 // object was generated by either the hydrogen or the TurboFan optimizing
5203 // compiler (but it may not be an optimized function).
5204 inline bool is_crankshafted();
5205 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
5206 inline void set_is_crankshafted(bool value);
5208 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
5209 // code object was generated by the TurboFan optimizing compiler.
5210 inline bool is_turbofanned();
5211 inline void set_is_turbofanned(bool value);
5213 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5214 inline bool optimizable();
5215 inline void set_optimizable(bool value);
5217 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5218 // deoptimization support.
5219 inline bool has_deoptimization_support();
5220 inline void set_has_deoptimization_support(bool value);
5222 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5223 // been compiled with debug break slots.
5224 inline bool has_debug_break_slots();
5225 inline void set_has_debug_break_slots(bool value);
5227 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5228 // been compiled with IsOptimizing set to true.
5229 inline bool is_compiled_optimizable();
5230 inline void set_compiled_optimizable(bool value);
5232 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5233 // how long the function has been marked for OSR and therefore which
5234 // level of loop nesting we are willing to do on-stack replacement
5236 inline void set_allow_osr_at_loop_nesting_level(int level);
5237 inline int allow_osr_at_loop_nesting_level();
5239 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5240 // the code object was seen on the stack with no IC patching going on.
5241 inline int profiler_ticks();
5242 inline void set_profiler_ticks(int ticks);
5244 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5245 inline int builtin_index();
5246 inline void set_builtin_index(int id);
5248 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5249 // reserved in the code prologue.
5250 inline unsigned stack_slots();
5251 inline void set_stack_slots(unsigned slots);
5253 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5254 // the instruction stream where the safepoint table starts.
5255 inline unsigned safepoint_table_offset();
5256 inline void set_safepoint_table_offset(unsigned offset);
5258 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5259 // instruction stream where the back edge table starts.
5260 inline unsigned back_edge_table_offset();
5261 inline void set_back_edge_table_offset(unsigned offset);
5263 inline bool back_edges_patched_for_osr();
5265 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5266 inline byte to_boolean_state();
5268 // [has_function_cache]: For kind STUB tells whether there is a function
5269 // cache is passed to the stub.
5270 inline bool has_function_cache();
5271 inline void set_has_function_cache(bool flag);
5274 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5275 // the code is going to be deoptimized because of dead embedded maps.
5276 inline bool marked_for_deoptimization();
5277 inline void set_marked_for_deoptimization(bool flag);
5279 // [constant_pool]: The constant pool for this function.
5280 inline ConstantPoolArray* constant_pool();
5281 inline void set_constant_pool(Object* constant_pool);
5283 // Get the safepoint entry for the given pc.
5284 SafepointEntry GetSafepointEntry(Address pc);
5286 // Find an object in a stub with a specified map
5287 Object* FindNthObject(int n, Map* match_map);
5289 // Find the first allocation site in an IC stub.
5290 AllocationSite* FindFirstAllocationSite();
5292 // Find the first map in an IC stub.
5293 Map* FindFirstMap();
5294 void FindAllMaps(MapHandleList* maps);
5296 // Find the first handler in an IC stub.
5297 Code* FindFirstHandler();
5299 // Find |length| handlers and put them into |code_list|. Returns false if not
5300 // enough handlers can be found.
5301 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5303 // Find the handler for |map|.
5304 MaybeHandle<Code> FindHandlerForMap(Map* map);
5306 // Find the first name in an IC stub.
5307 Name* FindFirstName();
5309 class FindAndReplacePattern;
5310 // For each (map-to-find, object-to-replace) pair in the pattern, this
5311 // function replaces the corresponding placeholder in the code with the
5312 // object-to-replace. The function assumes that pairs in the pattern come in
5313 // the same order as the placeholders in the code.
5314 void FindAndReplace(const FindAndReplacePattern& pattern);
5316 // The entire code object including its header is copied verbatim to the
5317 // snapshot so that it can be written in one, fast, memcpy during
5318 // deserialization. The deserializer will overwrite some pointers, rather
5319 // like a runtime linker, but the random allocation addresses used in the
5320 // mksnapshot process would still be present in the unlinked snapshot data,
5321 // which would make snapshot production non-reproducible. This method wipes
5322 // out the to-be-overwritten header data for reproducible snapshots.
5323 inline void WipeOutHeader();
5325 // Flags operations.
5326 static inline Flags ComputeFlags(
5327 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5328 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5329 CacheHolderFlag holder = kCacheOnReceiver);
5331 static inline Flags ComputeMonomorphicFlags(
5332 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5333 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5335 static inline Flags ComputeHandlerFlags(
5336 Kind handler_kind, StubType type = NORMAL,
5337 CacheHolderFlag holder = kCacheOnReceiver);
5339 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5340 static inline StubType ExtractTypeFromFlags(Flags flags);
5341 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5342 static inline Kind ExtractKindFromFlags(Flags flags);
5343 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5345 static inline Flags RemoveTypeFromFlags(Flags flags);
5346 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5348 // Convert a target address into a code object.
5349 static inline Code* GetCodeFromTargetAddress(Address address);
5351 // Convert an entry address into an object.
5352 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5354 // Returns the address of the first instruction.
5355 inline byte* instruction_start();
5357 // Returns the address right after the last instruction.
5358 inline byte* instruction_end();
5360 // Returns the size of the instructions, padding, and relocation information.
5361 inline int body_size();
5363 // Returns the address of the first relocation info (read backwards!).
5364 inline byte* relocation_start();
5366 // Code entry point.
5367 inline byte* entry();
5369 // Returns true if pc is inside this object's instructions.
5370 inline bool contains(byte* pc);
5372 // Relocate the code by delta bytes. Called to signal that this code
5373 // object has been moved by delta bytes.
5374 void Relocate(intptr_t delta);
5376 // Migrate code described by desc.
5377 void CopyFrom(const CodeDesc& desc);
5379 // Returns the object size for a given body (used for allocation).
5380 static int SizeFor(int body_size) {
5381 DCHECK_SIZE_TAG_ALIGNED(body_size);
5382 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5385 // Calculate the size of the code object to report for log events. This takes
5386 // the layout of the code object into account.
5387 int ExecutableSize() {
5388 // Check that the assumptions about the layout of the code object holds.
5389 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5391 return instruction_size() + Code::kHeaderSize;
5394 // Locating source position.
5395 int SourcePosition(Address pc);
5396 int SourceStatementPosition(Address pc);
5400 // Dispatched behavior.
5401 int CodeSize() { return SizeFor(body_size()); }
5402 inline void CodeIterateBody(ObjectVisitor* v);
5404 template<typename StaticVisitor>
5405 inline void CodeIterateBody(Heap* heap);
5407 DECLARE_PRINTER(Code)
5408 DECLARE_VERIFIER(Code)
5410 void ClearInlineCaches();
5411 void ClearInlineCaches(Kind kind);
5413 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5414 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5416 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5418 kNotExecutedCodeAge = -2,
5419 kExecutedOnceCodeAge = -1,
5421 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5423 kFirstCodeAge = kNotExecutedCodeAge,
5424 kLastCodeAge = kAfterLastCodeAge - 1,
5425 kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5426 kIsOldCodeAge = kSexagenarianCodeAge,
5427 kPreAgedCodeAge = kIsOldCodeAge - 1
5429 #undef DECLARE_CODE_AGE_ENUM
5431 // Code aging. Indicates how many full GCs this code has survived without
5432 // being entered through the prologue. Used to determine when it is
5433 // relatively safe to flush this code object and replace it with the lazy
5434 // compilation stub.
5435 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5436 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5437 void MakeOlder(MarkingParity);
5438 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5441 // Gets the raw code age, including psuedo code-age values such as
5442 // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5444 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5445 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5448 void PrintDeoptLocation(FILE* out, int bailout_id);
5449 bool CanDeoptAt(Address pc);
5452 void VerifyEmbeddedObjectsDependency();
5455 inline bool CanContainWeakObjects() {
5456 return is_optimized_code() || is_weak_stub();
5459 inline bool IsWeakObject(Object* object) {
5460 return (is_optimized_code() && !is_turbofanned() &&
5461 IsWeakObjectInOptimizedCode(object)) ||
5462 (is_weak_stub() && IsWeakObjectInIC(object));
5465 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5466 static inline bool IsWeakObjectInIC(Object* object);
5468 // Max loop nesting marker used to postpose OSR. We don't take loop
5469 // nesting that is deeper than 5 levels into account.
5470 static const int kMaxLoopNestingMarker = 6;
5472 // Layout description.
5473 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
5474 static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
5475 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5476 static const int kDeoptimizationDataOffset =
5477 kHandlerTableOffset + kPointerSize;
5478 // For FUNCTION kind, we store the type feedback info here.
5479 static const int kTypeFeedbackInfoOffset =
5480 kDeoptimizationDataOffset + kPointerSize;
5481 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5482 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5483 static const int kICAgeOffset =
5484 kGCMetadataOffset + kPointerSize;
5485 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5486 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5487 static const int kKindSpecificFlags2Offset =
5488 kKindSpecificFlags1Offset + kIntSize;
5489 // Note: We might be able to squeeze this into the flags above.
5490 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5491 static const int kConstantPoolOffset = kPrologueOffset + kPointerSize;
5493 static const int kHeaderPaddingStart = kConstantPoolOffset + kIntSize;
5495 // Add padding to align the instruction start following right after
5496 // the Code object header.
5497 static const int kHeaderSize =
5498 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5500 // Byte offsets within kKindSpecificFlags1Offset.
5501 static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5503 static const int kFullCodeFlags = kOptimizableOffset + 1;
5504 class FullCodeFlagsHasDeoptimizationSupportField:
5505 public BitField<bool, 0, 1> {}; // NOLINT
5506 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5507 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5509 static const int kProfilerTicksOffset = kFullCodeFlags + 1;
5511 // Flags layout. BitField<type, shift, size>.
5512 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5513 class TypeField : public BitField<StubType, 4, 1> {};
5514 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5515 class KindField : public BitField<Kind, 7, 4> {};
5516 class ExtraICStateField: public BitField<ExtraICState, 11,
5517 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5519 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5520 static const int kStackSlotsFirstBit = 0;
5521 static const int kStackSlotsBitCount = 24;
5522 static const int kHasFunctionCacheBit =
5523 kStackSlotsFirstBit + kStackSlotsBitCount;
5524 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5525 static const int kWeakStubBit = kMarkedForDeoptimizationBit + 1;
5526 static const int kInvalidatedWeakStubBit = kWeakStubBit + 1;
5527 static const int kIsTurbofannedBit = kInvalidatedWeakStubBit + 1;
5529 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5530 STATIC_ASSERT(kIsTurbofannedBit + 1 <= 32);
5532 class StackSlotsField: public BitField<int,
5533 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5534 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5536 class MarkedForDeoptimizationField
5537 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5538 class WeakStubField : public BitField<bool, kWeakStubBit, 1> {}; // NOLINT
5539 class InvalidatedWeakStubField
5540 : public BitField<bool, kInvalidatedWeakStubBit, 1> {}; // NOLINT
5541 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5544 // KindSpecificFlags2 layout (ALL)
5545 static const int kIsCrankshaftedBit = 0;
5546 class IsCrankshaftedField: public BitField<bool,
5547 kIsCrankshaftedBit, 1> {}; // NOLINT
5549 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5550 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5551 static const int kSafepointTableOffsetBitCount = 24;
5553 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5554 kSafepointTableOffsetBitCount <= 32);
5555 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5557 class SafepointTableOffsetField: public BitField<int,
5558 kSafepointTableOffsetFirstBit,
5559 kSafepointTableOffsetBitCount> {}; // NOLINT
5561 // KindSpecificFlags2 layout (FUNCTION)
5562 class BackEdgeTableOffsetField: public BitField<int,
5563 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5564 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5565 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5566 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5568 static const int kArgumentsBits = 16;
5569 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5571 // This constant should be encodable in an ARM instruction.
5572 static const int kFlagsNotUsedInLookup =
5573 TypeField::kMask | CacheHolderField::kMask;
5576 friend class RelocIterator;
5577 friend class Deoptimizer; // For FindCodeAgeSequence.
5579 void ClearInlineCaches(Kind* kind);
5582 byte* FindCodeAgeSequence();
5583 static void GetCodeAgeAndParity(Code* code, Age* age,
5584 MarkingParity* parity);
5585 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5586 MarkingParity* parity);
5587 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5589 // Code aging -- platform-specific
5590 static void PatchPlatformCodeAge(Isolate* isolate,
5591 byte* sequence, Age age,
5592 MarkingParity parity);
5594 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5598 class CompilationInfo;
5600 // This class describes the layout of dependent codes array of a map. The
5601 // array is partitioned into several groups of dependent codes. Each group
5602 // contains codes with the same dependency on the map. The array has the
5603 // following layout for n dependency groups:
5605 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5606 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5607 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5609 // The first n elements are Smis, each of them specifies the number of codes
5610 // in the corresponding group. The subsequent elements contain grouped code
5611 // objects. The suffix of the array can be filled with the undefined value if
5612 // the number of codes is less than the length of the array. The order of the
5613 // code objects within a group is not preserved.
5615 // All code indexes used in the class are counted starting from the first
5616 // code object of the first group. In other words, code index 0 corresponds
5617 // to array index n = kCodesStartIndex.
5619 class DependentCode: public FixedArray {
5621 enum DependencyGroup {
5622 // Group of IC stubs that weakly embed this map and depend on being
5623 // invalidated when the map is garbage collected. Dependent IC stubs form
5624 // a linked list. This group stores only the head of the list. This means
5625 // that the number_of_entries(kWeakICGroup) is 0 or 1.
5627 // Group of code that weakly embed this map and depend on being
5628 // deoptimized when the map is garbage collected.
5630 // Group of code that embed a transition to this map, and depend on being
5631 // deoptimized when the transition is replaced by a new version.
5633 // Group of code that omit run-time prototype checks for prototypes
5634 // described by this map. The group is deoptimized whenever an object
5635 // described by this map changes shape (and transitions to a new map),
5636 // possibly invalidating the assumptions embedded in the code.
5637 kPrototypeCheckGroup,
5638 // Group of code that depends on elements not being added to objects with
5640 kElementsCantBeAddedGroup,
5641 // Group of code that depends on global property values in property cells
5642 // not being changed.
5643 kPropertyCellChangedGroup,
5644 // Group of code that omit run-time type checks for the field(s) introduced
5647 // Group of code that omit run-time type checks for initial maps of
5649 kInitialMapChangedGroup,
5650 // Group of code that depends on tenuring information in AllocationSites
5651 // not being changed.
5652 kAllocationSiteTenuringChangedGroup,
5653 // Group of code that depends on element transition information in
5654 // AllocationSites not being changed.
5655 kAllocationSiteTransitionChangedGroup
5658 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5660 // Array for holding the index of the first code object of each group.
5661 // The last element stores the total number of code objects.
5662 class GroupStartIndexes {
5664 explicit GroupStartIndexes(DependentCode* entries);
5665 void Recompute(DependentCode* entries);
5666 int at(int i) { return start_indexes_[i]; }
5667 int number_of_entries() { return start_indexes_[kGroupCount]; }
5669 int start_indexes_[kGroupCount + 1];
5672 bool Contains(DependencyGroup group, Code* code);
5673 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5674 DependencyGroup group,
5675 Handle<Object> object);
5676 void UpdateToFinishedCode(DependencyGroup group,
5677 CompilationInfo* info,
5679 void RemoveCompilationInfo(DependentCode::DependencyGroup group,
5680 CompilationInfo* info);
5682 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5683 DependentCode::DependencyGroup group);
5685 bool MarkCodeForDeoptimization(Isolate* isolate,
5686 DependentCode::DependencyGroup group);
5687 void AddToDependentICList(Handle<Code> stub);
5689 // The following low-level accessors should only be used by this class
5690 // and the mark compact collector.
5691 inline int number_of_entries(DependencyGroup group);
5692 inline void set_number_of_entries(DependencyGroup group, int value);
5693 inline bool is_code_at(int i);
5694 inline Code* code_at(int i);
5695 inline CompilationInfo* compilation_info_at(int i);
5696 inline void set_object_at(int i, Object* object);
5697 inline Object** slot_at(int i);
5698 inline Object* object_at(int i);
5699 inline void clear_at(int i);
5700 inline void copy(int from, int to);
5701 DECLARE_CAST(DependentCode)
5703 static DependentCode* ForObject(Handle<HeapObject> object,
5704 DependencyGroup group);
5706 static const char* DependencyGroupName(DependencyGroup group);
5707 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5710 // Make a room at the end of the given group by moving out the first
5711 // code objects of the subsequent groups.
5712 inline void ExtendGroup(DependencyGroup group);
5713 static const int kCodesStartIndex = kGroupCount;
5717 // All heap objects have a Map that describes their structure.
5718 // A Map contains information about:
5719 // - Size information about the object
5720 // - How to iterate over an object (for garbage collection)
5721 class Map: public HeapObject {
5724 // Size in bytes or kVariableSizeSentinel if instances do not have
5726 inline int instance_size();
5727 inline void set_instance_size(int value);
5729 // Count of properties allocated in the object.
5730 inline int inobject_properties();
5731 inline void set_inobject_properties(int value);
5733 // Count of property fields pre-allocated in the object when first allocated.
5734 inline int pre_allocated_property_fields();
5735 inline void set_pre_allocated_property_fields(int value);
5738 inline InstanceType instance_type();
5739 inline void set_instance_type(InstanceType value);
5741 // Tells how many unused property fields are available in the
5742 // instance (only used for JSObject in fast mode).
5743 inline int unused_property_fields();
5744 inline void set_unused_property_fields(int value);
5747 inline byte bit_field();
5748 inline void set_bit_field(byte value);
5751 inline byte bit_field2();
5752 inline void set_bit_field2(byte value);
5755 inline uint32_t bit_field3();
5756 inline void set_bit_field3(uint32_t bits);
5758 class EnumLengthBits: public BitField<int,
5759 0, kDescriptorIndexBitCount> {}; // NOLINT
5760 class NumberOfOwnDescriptorsBits: public BitField<int,
5761 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5762 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5763 class DictionaryMap : public BitField<bool, 20, 1> {};
5764 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5765 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5766 class Deprecated : public BitField<bool, 23, 1> {};
5767 class IsFrozen : public BitField<bool, 24, 1> {};
5768 class IsUnstable : public BitField<bool, 25, 1> {};
5769 class IsMigrationTarget : public BitField<bool, 26, 1> {};
5770 class DoneInobjectSlackTracking : public BitField<bool, 27, 1> {};
5773 // Keep this bit field at the very end for better code in
5774 // Builtins::kJSConstructStubGeneric stub.
5775 class ConstructionCount: public BitField<int, 29, 3> {};
5777 // Tells whether the object in the prototype property will be used
5778 // for instances created from this function. If the prototype
5779 // property is set to a value that is not a JSObject, the prototype
5780 // property will not be used to create instances of the function.
5781 // See ECMA-262, 13.2.2.
5782 inline void set_non_instance_prototype(bool value);
5783 inline bool has_non_instance_prototype();
5785 // Tells whether function has special prototype property. If not, prototype
5786 // property will not be created when accessed (will return undefined),
5787 // and construction from this function will not be allowed.
5788 inline void set_function_with_prototype(bool value);
5789 inline bool function_with_prototype();
5791 // Tells whether the instance with this map should be ignored by the
5792 // Object.getPrototypeOf() function and the __proto__ accessor.
5793 inline void set_is_hidden_prototype() {
5794 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5797 inline bool is_hidden_prototype() {
5798 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5801 // Records and queries whether the instance has a named interceptor.
5802 inline void set_has_named_interceptor() {
5803 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5806 inline bool has_named_interceptor() {
5807 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5810 // Records and queries whether the instance has an indexed interceptor.
5811 inline void set_has_indexed_interceptor() {
5812 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5815 inline bool has_indexed_interceptor() {
5816 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5819 // Tells whether the instance is undetectable.
5820 // An undetectable object is a special class of JSObject: 'typeof' operator
5821 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5822 // a normal JS object. It is useful for implementing undetectable
5823 // document.all in Firefox & Safari.
5824 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5825 inline void set_is_undetectable() {
5826 set_bit_field(bit_field() | (1 << kIsUndetectable));
5829 inline bool is_undetectable() {
5830 return ((1 << kIsUndetectable) & bit_field()) != 0;
5833 // Tells whether the instance has a call-as-function handler.
5834 inline void set_is_observed() {
5835 set_bit_field(bit_field() | (1 << kIsObserved));
5838 inline bool is_observed() {
5839 return ((1 << kIsObserved) & bit_field()) != 0;
5842 inline void set_is_extensible(bool value);
5843 inline bool is_extensible();
5844 inline void set_is_prototype_map(bool value);
5845 inline bool is_prototype_map();
5847 inline void set_elements_kind(ElementsKind elements_kind) {
5848 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5849 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5850 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5851 DCHECK(this->elements_kind() == elements_kind);
5854 inline ElementsKind elements_kind() {
5855 return Map::ElementsKindBits::decode(bit_field2());
5858 // Tells whether the instance has fast elements that are only Smis.
5859 inline bool has_fast_smi_elements() {
5860 return IsFastSmiElementsKind(elements_kind());
5863 // Tells whether the instance has fast elements.
5864 inline bool has_fast_object_elements() {
5865 return IsFastObjectElementsKind(elements_kind());
5868 inline bool has_fast_smi_or_object_elements() {
5869 return IsFastSmiOrObjectElementsKind(elements_kind());
5872 inline bool has_fast_double_elements() {
5873 return IsFastDoubleElementsKind(elements_kind());
5876 inline bool has_fast_elements() {
5877 return IsFastElementsKind(elements_kind());
5880 inline bool has_sloppy_arguments_elements() {
5881 return elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5884 inline bool has_external_array_elements() {
5885 return IsExternalArrayElementsKind(elements_kind());
5888 inline bool has_fixed_typed_array_elements() {
5889 return IsFixedTypedArrayElementsKind(elements_kind());
5892 inline bool has_dictionary_elements() {
5893 return IsDictionaryElementsKind(elements_kind());
5896 inline bool has_slow_elements_kind() {
5897 return elements_kind() == DICTIONARY_ELEMENTS
5898 || elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5901 static bool IsValidElementsTransition(ElementsKind from_kind,
5902 ElementsKind to_kind);
5904 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5905 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5906 bool DictionaryElementsInPrototypeChainOnly();
5908 inline bool HasTransitionArray() const;
5909 inline bool HasElementsTransition();
5910 inline Map* elements_transition_map();
5912 inline Map* GetTransition(int transition_index);
5913 inline int SearchTransition(Name* name);
5914 inline FixedArrayBase* GetInitialElements();
5916 DECL_ACCESSORS(transitions, TransitionArray)
5918 static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
5919 static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
5921 // Try to follow an existing transition to a field with attributes NONE. The
5922 // return value indicates whether the transition was successful.
5923 static inline Handle<Map> FindTransitionToField(Handle<Map> map,
5927 Map* FindFieldOwner(int descriptor);
5929 inline int GetInObjectPropertyOffset(int index);
5931 int NumberOfFields();
5933 // TODO(ishell): candidate with JSObject::MigrateToMap().
5934 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5935 int target_inobject, int target_unused,
5936 int* old_number_of_fields);
5937 // TODO(ishell): moveit!
5938 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5939 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5940 Handle<HeapType> type1,
5941 Handle<HeapType> type2,
5943 static void GeneralizeFieldType(Handle<Map> map,
5945 Handle<HeapType> new_field_type);
5946 static Handle<Map> GeneralizeRepresentation(
5949 Representation new_representation,
5950 Handle<HeapType> new_field_type,
5951 StoreMode store_mode);
5952 static Handle<Map> CopyGeneralizeAllRepresentations(
5955 StoreMode store_mode,
5956 PropertyAttributes attributes,
5957 const char* reason);
5958 static Handle<Map> CopyGeneralizeAllRepresentations(
5961 StoreMode store_mode,
5962 const char* reason);
5964 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5965 int descriptor_number,
5966 Handle<Object> value);
5968 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode);
5970 // Returns the constructor name (the name (possibly, inferred name) of the
5971 // function that was used to instantiate the object).
5972 String* constructor_name();
5974 // Tells whether the map is used for JSObjects in dictionary mode (ie
5975 // normalized objects, ie objects for which HasFastProperties returns false).
5976 // A map can never be used for both dictionary mode and fast mode JSObjects.
5977 // False by default and for HeapObjects that are not JSObjects.
5978 inline void set_dictionary_map(bool value);
5979 inline bool is_dictionary_map();
5981 // Tells whether the instance needs security checks when accessing its
5983 inline void set_is_access_check_needed(bool access_check_needed);
5984 inline bool is_access_check_needed();
5986 // Returns true if map has a non-empty stub code cache.
5987 inline bool has_code_cache();
5989 // [prototype]: implicit prototype object.
5990 DECL_ACCESSORS(prototype, Object)
5992 // [constructor]: points back to the function responsible for this map.
5993 DECL_ACCESSORS(constructor, Object)
5995 // [instance descriptors]: describes the object.
5996 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5997 inline void InitializeDescriptors(DescriptorArray* descriptors);
5999 // [stub cache]: contains stubs compiled for this map.
6000 DECL_ACCESSORS(code_cache, Object)
6002 // [dependent code]: list of optimized codes that weakly embed this map.
6003 DECL_ACCESSORS(dependent_code, DependentCode)
6005 // [back pointer]: points back to the parent map from which a transition
6006 // leads to this map. The field overlaps with prototype transitions and the
6007 // back pointer will be moved into the prototype transitions array if
6009 inline Object* GetBackPointer();
6010 inline void SetBackPointer(Object* value,
6011 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
6012 inline void init_back_pointer(Object* undefined);
6014 // [prototype transitions]: cache of prototype transitions.
6015 // Prototype transition is a transition that happens
6016 // when we change object's prototype to a new one.
6018 // 0: finger - index of the first free cell in the cache
6019 // 1: back pointer that overlaps with prototype transitions field.
6020 // 2 + 2 * i: prototype
6021 // 3 + 2 * i: target map
6022 inline FixedArray* GetPrototypeTransitions();
6023 inline bool HasPrototypeTransitions();
6025 static const int kProtoTransitionHeaderSize = 1;
6026 static const int kProtoTransitionNumberOfEntriesOffset = 0;
6027 static const int kProtoTransitionElementsPerEntry = 2;
6028 static const int kProtoTransitionPrototypeOffset = 0;
6029 static const int kProtoTransitionMapOffset = 1;
6031 inline int NumberOfProtoTransitions() {
6032 FixedArray* cache = GetPrototypeTransitions();
6033 if (cache->length() == 0) return 0;
6035 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
6038 inline void SetNumberOfProtoTransitions(int value) {
6039 FixedArray* cache = GetPrototypeTransitions();
6040 DCHECK(cache->length() != 0);
6041 cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
6044 // Lookup in the map's instance descriptors and fill out the result
6045 // with the given holder if the name is found. The holder may be
6046 // NULL when this function is used from the compiler.
6047 inline void LookupDescriptor(JSObject* holder,
6049 LookupResult* result);
6051 inline void LookupTransition(JSObject* holder,
6053 LookupResult* result);
6055 inline PropertyDetails GetLastDescriptorDetails();
6057 // The size of transition arrays are limited so they do not end up in large
6058 // object space. Otherwise ClearNonLiveTransitions would leak memory while
6059 // applying in-place right trimming.
6060 inline bool CanHaveMoreTransitions();
6063 int number_of_own_descriptors = NumberOfOwnDescriptors();
6064 DCHECK(number_of_own_descriptors > 0);
6065 return number_of_own_descriptors - 1;
6068 int NumberOfOwnDescriptors() {
6069 return NumberOfOwnDescriptorsBits::decode(bit_field3());
6072 void SetNumberOfOwnDescriptors(int number) {
6073 DCHECK(number <= instance_descriptors()->number_of_descriptors());
6074 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
6077 inline Cell* RetrieveDescriptorsPointer();
6080 return EnumLengthBits::decode(bit_field3());
6083 void SetEnumLength(int length) {
6084 if (length != kInvalidEnumCacheSentinel) {
6085 DCHECK(length >= 0);
6086 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
6087 DCHECK(length <= NumberOfOwnDescriptors());
6089 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
6092 inline bool owns_descriptors();
6093 inline void set_owns_descriptors(bool owns_descriptors);
6094 inline bool has_instance_call_handler();
6095 inline void set_has_instance_call_handler();
6096 inline void freeze();
6097 inline bool is_frozen();
6098 inline void mark_unstable();
6099 inline bool is_stable();
6100 inline void set_migration_target(bool value);
6101 inline bool is_migration_target();
6102 inline void set_done_inobject_slack_tracking(bool value);
6103 inline bool done_inobject_slack_tracking();
6104 inline void set_construction_count(int value);
6105 inline int construction_count();
6106 inline void deprecate();
6107 inline bool is_deprecated();
6108 inline bool CanBeDeprecated();
6109 // Returns a non-deprecated version of the input. If the input was not
6110 // deprecated, it is directly returned. Otherwise, the non-deprecated version
6111 // is found by re-transitioning from the root of the transition tree using the
6112 // descriptor array of the map. Returns NULL if no updated map is found.
6113 // This method also applies any pending migrations along the prototype chain.
6114 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
6115 // Same as above, but does not touch the prototype chain.
6116 static MaybeHandle<Map> TryUpdateInternal(Handle<Map> map)
6119 // Returns a non-deprecated version of the input. This method may deprecate
6120 // existing maps along the way if encodings conflict. Not for use while
6121 // gathering type feedback. Use TryUpdate in those cases instead.
6122 static Handle<Map> Update(Handle<Map> map);
6124 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6125 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
6126 Descriptor* descriptor,
6127 TransitionFlag flag);
6129 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
6132 Handle<HeapType> type,
6133 PropertyAttributes attributes,
6134 Representation representation,
6135 TransitionFlag flag);
6137 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
6140 Handle<Object> constant,
6141 PropertyAttributes attributes,
6142 TransitionFlag flag);
6144 // Returns a new map with all transitions dropped from the given map and
6145 // the ElementsKind set.
6146 static Handle<Map> TransitionElementsTo(Handle<Map> map,
6147 ElementsKind to_kind);
6149 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
6151 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
6153 TransitionFlag flag);
6155 static Handle<Map> CopyForObserved(Handle<Map> map);
6157 static Handle<Map> CopyForFreeze(Handle<Map> map);
6158 // Maximal number of fast properties. Used to restrict the number of map
6159 // transitions to avoid an explosion in the number of maps for objects used as
6161 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
6162 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
6164 Handle<Object> value,
6165 PropertyAttributes attributes,
6166 StoreFromKeyed store_mode);
6167 static Handle<Map> TransitionToAccessorProperty(
6168 Handle<Map> map, Handle<Name> name, AccessorComponent component,
6169 Handle<Object> accessor, PropertyAttributes attributes);
6170 static Handle<Map> ReconfigureDataProperty(Handle<Map> map, int descriptor,
6171 PropertyAttributes attributes);
6173 inline void AppendDescriptor(Descriptor* desc);
6175 // Returns a copy of the map, with all transitions dropped from the
6176 // instance descriptors.
6177 static Handle<Map> Copy(Handle<Map> map);
6178 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
6180 // Returns the next free property index (only valid for FAST MODE).
6181 int NextFreePropertyIndex();
6183 // Returns the number of properties described in instance_descriptors
6184 // filtering out properties with the specified attributes.
6185 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6186 PropertyAttributes filter = NONE);
6188 // Returns the number of slots allocated for the initial properties
6189 // backing storage for instances of this map.
6190 int InitialPropertiesLength() {
6191 return pre_allocated_property_fields() + unused_property_fields() -
6192 inobject_properties();
6197 // Code cache operations.
6199 // Clears the code cache.
6200 inline void ClearCodeCache(Heap* heap);
6202 // Update code cache.
6203 static void UpdateCodeCache(Handle<Map> map,
6207 // Extend the descriptor array of the map with the list of descriptors.
6208 // In case of duplicates, the latest descriptor is used.
6209 static void AppendCallbackDescriptors(Handle<Map> map,
6210 Handle<Object> descriptors);
6212 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6214 // Returns the found code or undefined if absent.
6215 Object* FindInCodeCache(Name* name, Code::Flags flags);
6217 // Returns the non-negative index of the code object if it is in the
6218 // cache and -1 otherwise.
6219 int IndexInCodeCache(Object* name, Code* code);
6221 // Removes a code object from the code cache at the given index.
6222 void RemoveFromCodeCache(Name* name, Code* code, int index);
6224 // Set all map transitions from this map to dead maps to null. Also clear
6225 // back pointers in transition targets so that we do not process this map
6226 // again while following back pointers.
6227 void ClearNonLiveTransitions(Heap* heap);
6229 // Computes a hash value for this map, to be used in HashTables and such.
6232 // Returns the map that this map transitions to if its elements_kind
6233 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6234 // |safe_to_add_transitions| is set to false if adding transitions is not
6236 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6238 // Returns the transitioned map for this map with the most generic
6239 // elements_kind that's found in |candidates|, or null handle if no match is
6241 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6243 bool CanTransition() {
6244 // Only JSObject and subtypes have map transitions and back pointers.
6245 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6246 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6249 bool IsJSObjectMap() {
6250 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6252 bool IsJSProxyMap() {
6253 InstanceType type = instance_type();
6254 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6256 bool IsJSGlobalProxyMap() {
6257 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6259 bool IsJSGlobalObjectMap() {
6260 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6262 bool IsGlobalObjectMap() {
6263 const InstanceType type = instance_type();
6264 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6267 inline bool CanOmitMapChecks();
6269 static void AddDependentCompilationInfo(Handle<Map> map,
6270 DependentCode::DependencyGroup group,
6271 CompilationInfo* info);
6273 static void AddDependentCode(Handle<Map> map,
6274 DependentCode::DependencyGroup group,
6276 static void AddDependentIC(Handle<Map> map,
6279 bool IsMapInArrayPrototypeChain();
6281 // Dispatched behavior.
6282 DECLARE_PRINTER(Map)
6283 DECLARE_VERIFIER(Map)
6286 void DictionaryMapVerify();
6287 void VerifyOmittedMapChecks();
6290 inline int visitor_id();
6291 inline void set_visitor_id(int visitor_id);
6293 typedef void (*TraverseCallback)(Map* map, void* data);
6295 void TraverseTransitionTree(TraverseCallback callback, void* data);
6297 // When you set the prototype of an object using the __proto__ accessor you
6298 // need a new map for the object (the prototype is stored in the map). In
6299 // order not to multiply maps unnecessarily we store these as transitions in
6300 // the original map. That way we can transition to the same map if the same
6301 // prototype is set, rather than creating a new map every time. The
6302 // transitions are in the form of a map where the keys are prototype objects
6303 // and the values are the maps the are transitioned to.
6304 static const int kMaxCachedPrototypeTransitions = 256;
6305 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6306 Handle<Object> prototype);
6308 static const int kMaxPreAllocatedPropertyFields = 255;
6310 // Layout description.
6311 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6312 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6313 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6314 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6315 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6316 // Storage for the transition array is overloaded to directly contain a back
6317 // pointer if unused. When the map has transitions, the back pointer is
6318 // transferred to the transition array and accessed through an extra
6320 static const int kTransitionsOrBackPointerOffset =
6321 kConstructorOffset + kPointerSize;
6322 static const int kDescriptorsOffset =
6323 kTransitionsOrBackPointerOffset + kPointerSize;
6324 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6325 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6326 static const int kSize = kDependentCodeOffset + kPointerSize;
6328 // Layout of pointer fields. Heap iteration code relies on them
6329 // being continuously allocated.
6330 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6331 static const int kPointerFieldsEndOffset = kSize;
6333 // Byte offsets within kInstanceSizesOffset.
6334 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6335 static const int kInObjectPropertiesByte = 1;
6336 static const int kInObjectPropertiesOffset =
6337 kInstanceSizesOffset + kInObjectPropertiesByte;
6338 static const int kPreAllocatedPropertyFieldsByte = 2;
6339 static const int kPreAllocatedPropertyFieldsOffset =
6340 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6341 static const int kVisitorIdByte = 3;
6342 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6344 // Byte offsets within kInstanceAttributesOffset attributes.
6345 #if V8_TARGET_LITTLE_ENDIAN
6346 // Order instance type and bit field together such that they can be loaded
6347 // together as a 16-bit word with instance type in the lower 8 bits regardless
6348 // of endianess. Also provide endian-independent offset to that 16-bit word.
6349 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6350 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6352 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6353 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6355 static const int kInstanceTypeAndBitFieldOffset =
6356 kInstanceAttributesOffset + 0;
6357 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6358 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6360 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6361 Internals::kMapInstanceTypeAndBitFieldOffset);
6363 // Bit positions for bit field.
6364 static const int kHasNonInstancePrototype = 0;
6365 static const int kIsHiddenPrototype = 1;
6366 static const int kHasNamedInterceptor = 2;
6367 static const int kHasIndexedInterceptor = 3;
6368 static const int kIsUndetectable = 4;
6369 static const int kIsObserved = 5;
6370 static const int kIsAccessCheckNeeded = 6;
6371 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6373 // Bit positions for bit field 2
6374 static const int kIsExtensible = 0;
6375 static const int kStringWrapperSafeForDefaultValueOf = 1;
6376 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6377 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6379 // Derived values from bit field 2
6380 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6381 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6382 static const int8_t kMaximumBitField2FastSmiElementValue =
6383 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6384 Map::ElementsKindBits::kShift) - 1;
6385 static const int8_t kMaximumBitField2FastHoleyElementValue =
6386 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6387 Map::ElementsKindBits::kShift) - 1;
6388 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6389 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6390 Map::ElementsKindBits::kShift) - 1;
6392 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6393 kPointerFieldsEndOffset,
6394 kSize> BodyDescriptor;
6396 // Compares this map to another to see if they describe equivalent objects.
6397 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6398 // it had exactly zero inobject properties.
6399 // The "shared" flags of both this map and |other| are ignored.
6400 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6403 static void ConnectElementsTransition(Handle<Map> parent, Handle<Map> child);
6404 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6405 Handle<Name> name, SimpleTransitionFlag flag);
6407 bool EquivalentToForTransition(Map* other);
6408 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6409 static Handle<Map> ShareDescriptor(Handle<Map> map,
6410 Handle<DescriptorArray> descriptors,
6411 Descriptor* descriptor);
6412 static Handle<Map> CopyInstallDescriptors(
6415 Handle<DescriptorArray> descriptors);
6416 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6417 Descriptor* descriptor,
6418 TransitionFlag flag);
6419 static Handle<Map> CopyReplaceDescriptors(
6421 Handle<DescriptorArray> descriptors,
6422 TransitionFlag flag,
6423 MaybeHandle<Name> maybe_name,
6424 SimpleTransitionFlag simple_flag = FULL_TRANSITION);
6425 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6426 Handle<DescriptorArray> descriptors,
6427 Descriptor* descriptor,
6429 TransitionFlag flag);
6431 static Handle<Map> CopyNormalized(Handle<Map> map,
6432 PropertyNormalizationMode mode);
6434 // Fires when the layout of an object with a leaf map changes.
6435 // This includes adding transitions to the leaf map or changing
6436 // the descriptor array.
6437 inline void NotifyLeafMapLayoutChange();
6439 static Handle<Map> TransitionElementsToSlow(Handle<Map> object,
6440 ElementsKind to_kind);
6442 // Zaps the contents of backing data structures. Note that the
6443 // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6444 // holding weak references when incremental marking is used, because it also
6445 // iterates over objects that are otherwise unreachable.
6446 // In general we only want to call these functions in release mode when
6447 // heap verification is turned on.
6448 void ZapPrototypeTransitions();
6449 void ZapTransitions();
6451 void DeprecateTransitionTree();
6452 void DeprecateTarget(Name* key, DescriptorArray* new_descriptors);
6454 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6456 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6457 Handle<HeapType> new_type);
6459 void PrintGeneralization(FILE* file,
6464 bool constant_to_field,
6465 Representation old_representation,
6466 Representation new_representation,
6467 HeapType* old_field_type,
6468 HeapType* new_field_type);
6470 static inline void SetPrototypeTransitions(
6472 Handle<FixedArray> prototype_transitions);
6474 static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6475 Handle<Object> prototype);
6476 static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6477 Handle<Object> prototype,
6478 Handle<Map> target_map);
6480 static const int kFastPropertiesSoftLimit = 12;
6481 static const int kMaxFastProperties = 128;
6483 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6487 // An abstract superclass, a marker class really, for simple structure classes.
6488 // It doesn't carry much functionality but allows struct classes to be
6489 // identified in the type system.
6490 class Struct: public HeapObject {
6492 inline void InitializeBody(int object_size);
6493 DECLARE_CAST(Struct)
6497 // A simple one-element struct, useful where smis need to be boxed.
6498 class Box : public Struct {
6500 // [value]: the boxed contents.
6501 DECL_ACCESSORS(value, Object)
6505 // Dispatched behavior.
6506 DECLARE_PRINTER(Box)
6507 DECLARE_VERIFIER(Box)
6509 static const int kValueOffset = HeapObject::kHeaderSize;
6510 static const int kSize = kValueOffset + kPointerSize;
6513 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6517 // Script describes a script which has been added to the VM.
6518 class Script: public Struct {
6527 // Script compilation types.
6528 enum CompilationType {
6529 COMPILATION_TYPE_HOST = 0,
6530 COMPILATION_TYPE_EVAL = 1
6533 // Script compilation state.
6534 enum CompilationState {
6535 COMPILATION_STATE_INITIAL = 0,
6536 COMPILATION_STATE_COMPILED = 1
6539 // [source]: the script source.
6540 DECL_ACCESSORS(source, Object)
6542 // [name]: the script name.
6543 DECL_ACCESSORS(name, Object)
6545 // [id]: the script id.
6546 DECL_ACCESSORS(id, Smi)
6548 // [line_offset]: script line offset in resource from where it was extracted.
6549 DECL_ACCESSORS(line_offset, Smi)
6551 // [column_offset]: script column offset in resource from where it was
6553 DECL_ACCESSORS(column_offset, Smi)
6555 // [context_data]: context data for the context this script was compiled in.
6556 DECL_ACCESSORS(context_data, Object)
6558 // [wrapper]: the wrapper cache.
6559 DECL_ACCESSORS(wrapper, Foreign)
6561 // [type]: the script type.
6562 DECL_ACCESSORS(type, Smi)
6564 // [line_ends]: FixedArray of line ends positions.
6565 DECL_ACCESSORS(line_ends, Object)
6567 // [eval_from_shared]: for eval scripts the shared funcion info for the
6568 // function from which eval was called.
6569 DECL_ACCESSORS(eval_from_shared, Object)
6571 // [eval_from_instructions_offset]: the instruction offset in the code for the
6572 // function from which eval was called where eval was called.
6573 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6575 // [flags]: Holds an exciting bitfield.
6576 DECL_ACCESSORS(flags, Smi)
6578 // [source_url]: sourceURL from magic comment
6579 DECL_ACCESSORS(source_url, Object)
6581 // [source_url]: sourceMappingURL magic comment
6582 DECL_ACCESSORS(source_mapping_url, Object)
6584 // [compilation_type]: how the the script was compiled. Encoded in the
6586 inline CompilationType compilation_type();
6587 inline void set_compilation_type(CompilationType type);
6589 // [compilation_state]: determines whether the script has already been
6590 // compiled. Encoded in the 'flags' field.
6591 inline CompilationState compilation_state();
6592 inline void set_compilation_state(CompilationState state);
6594 // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6595 // ScriptOrigin, and used by the embedder to make decisions about the
6596 // script's level of privilege. V8 just passes this through. Encoded in
6597 // the 'flags' field.
6598 DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6600 DECLARE_CAST(Script)
6602 // If script source is an external string, check that the underlying
6603 // resource is accessible. Otherwise, always return true.
6604 inline bool HasValidSource();
6606 // Convert code position into column number.
6607 static int GetColumnNumber(Handle<Script> script, int code_pos);
6609 // Convert code position into (zero-based) line number.
6610 // The non-handlified version does not allocate, but may be much slower.
6611 static int GetLineNumber(Handle<Script> script, int code_pos);
6612 int GetLineNumber(int code_pos);
6614 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6616 // Init line_ends array with code positions of line ends inside script source.
6617 static void InitLineEnds(Handle<Script> script);
6619 // Get the JS object wrapping the given script; create it if none exists.
6620 static Handle<JSObject> GetWrapper(Handle<Script> script);
6621 void ClearWrapperCache();
6623 // Dispatched behavior.
6624 DECLARE_PRINTER(Script)
6625 DECLARE_VERIFIER(Script)
6627 static const int kSourceOffset = HeapObject::kHeaderSize;
6628 static const int kNameOffset = kSourceOffset + kPointerSize;
6629 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6630 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6631 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6632 static const int kWrapperOffset = kContextOffset + kPointerSize;
6633 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6634 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6635 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6636 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6637 static const int kEvalFrominstructionsOffsetOffset =
6638 kEvalFromSharedOffset + kPointerSize;
6639 static const int kFlagsOffset =
6640 kEvalFrominstructionsOffsetOffset + kPointerSize;
6641 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6642 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6643 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6646 int GetLineNumberWithArray(int code_pos);
6648 // Bit positions in the flags field.
6649 static const int kCompilationTypeBit = 0;
6650 static const int kCompilationStateBit = 1;
6651 static const int kIsSharedCrossOriginBit = 2;
6653 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6657 // List of builtin functions we want to identify to improve code
6660 // Each entry has a name of a global object property holding an object
6661 // optionally followed by ".prototype", a name of a builtin function
6662 // on the object (the one the id is set for), and a label.
6664 // Installation of ids for the selected builtin functions is handled
6665 // by the bootstrapper.
6666 #define FUNCTIONS_WITH_ID_LIST(V) \
6667 V(Array.prototype, indexOf, ArrayIndexOf) \
6668 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6669 V(Array.prototype, push, ArrayPush) \
6670 V(Array.prototype, pop, ArrayPop) \
6671 V(Array.prototype, shift, ArrayShift) \
6672 V(Function.prototype, apply, FunctionApply) \
6673 V(String.prototype, charCodeAt, StringCharCodeAt) \
6674 V(String.prototype, charAt, StringCharAt) \
6675 V(String, fromCharCode, StringFromCharCode) \
6676 V(Math, floor, MathFloor) \
6677 V(Math, round, MathRound) \
6678 V(Math, ceil, MathCeil) \
6679 V(Math, abs, MathAbs) \
6680 V(Math, log, MathLog) \
6681 V(Math, exp, MathExp) \
6682 V(Math, sqrt, MathSqrt) \
6683 V(Math, pow, MathPow) \
6684 V(Math, max, MathMax) \
6685 V(Math, min, MathMin) \
6686 V(Math, imul, MathImul) \
6687 V(Math, clz32, MathClz32) \
6688 V(Math, fround, MathFround)
6690 #define SIMD_NULLARY_OPERATIONS(V) \
6691 V(SIMD.float32x4, zero, Float32x4Zero, Float32x4) \
6692 V(SIMD.float64x2, zero, Float64x2Zero, Float64x2) \
6693 V(SIMD.int32x4, zero, Int32x4Zero, Int32x4)
6695 #define SIMD_UNARY_OPERATIONS(V) \
6696 V(SIMD, float32x4, Float32x4Coercion, Float32x4, Float32x4) \
6697 V(SIMD, float64x2, Float64x2Coercion, Float64x2, Float64x2) \
6698 V(SIMD, int32x4, Int32x4Coercion, Int32x4, Int32x4) \
6699 V(SIMD.float32x4, abs, Float32x4Abs, Float32x4, Float32x4) \
6700 V(SIMD.float32x4, fromInt32x4, Int32x4ToFloat32x4, Float32x4, Int32x4) \
6701 V(SIMD.float32x4, fromInt32x4Bits, Int32x4BitsToFloat32x4, Float32x4, \
6703 V(SIMD.float32x4, neg, Float32x4Neg, Float32x4, Float32x4) \
6704 V(SIMD.float32x4, reciprocal, Float32x4Reciprocal, Float32x4, Float32x4) \
6705 V(SIMD.float32x4, reciprocalSqrt, Float32x4ReciprocalSqrt, \
6706 Float32x4, Float32x4) \
6707 V(SIMD.float32x4, splat, Float32x4Splat, Float32x4, Double) \
6708 V(SIMD.float32x4, sqrt, Float32x4Sqrt, Float32x4, Float32x4) \
6709 V(SIMD.float64x2, abs, Float64x2Abs, Float64x2, Float64x2) \
6710 V(SIMD.float64x2, neg, Float64x2Neg, Float64x2, Float64x2) \
6711 V(SIMD.float64x2, sqrt, Float64x2Sqrt, Float64x2, Float64x2) \
6712 V(SIMD.int32x4, fromFloat32x4, Float32x4ToInt32x4, Int32x4, Float32x4) \
6713 V(SIMD.int32x4, fromFloat32x4Bits, Float32x4BitsToInt32x4, Int32x4, \
6715 V(SIMD.int32x4, neg, Int32x4Neg, Int32x4, Int32x4) \
6716 V(SIMD.int32x4, not, Int32x4Not, Int32x4, Int32x4) \
6717 V(SIMD.int32x4, splat, Int32x4Splat, Int32x4, Integer32)
6719 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6720 #define SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(V) \
6721 V(SIMD.float32x4.prototype, signMask, Float32x4GetSignMask, Integer32, \
6723 V(SIMD.float32x4.prototype, x, Float32x4GetX, Double, Float32x4) \
6724 V(SIMD.float32x4.prototype, y, Float32x4GetY, Double, Float32x4) \
6725 V(SIMD.float32x4.prototype, z, Float32x4GetZ, Double, Float32x4) \
6726 V(SIMD.float32x4.prototype, w, Float32x4GetW, Double, Float32x4) \
6727 V(SIMD.float64x2.prototype, signMask, Float64x2GetSignMask, Integer32, \
6729 V(SIMD.float64x2.prototype, x, Float64x2GetX, Double, Float64x2) \
6730 V(SIMD.float64x2.prototype, y, Float64x2GetY, Double, Float64x2) \
6731 V(SIMD.int32x4.prototype, signMask, Int32x4GetSignMask, Integer32, Int32x4) \
6732 V(SIMD.int32x4.prototype, x, Int32x4GetX, Integer32, Int32x4) \
6733 V(SIMD.int32x4.prototype, y, Int32x4GetY, Integer32, Int32x4) \
6734 V(SIMD.int32x4.prototype, z, Int32x4GetZ, Integer32, Int32x4) \
6735 V(SIMD.int32x4.prototype, w, Int32x4GetW, Integer32, Int32x4) \
6736 V(SIMD.int32x4.prototype, flagX, Int32x4GetFlagX, Tagged, Int32x4) \
6737 V(SIMD.int32x4.prototype, flagY, Int32x4GetFlagY, Tagged, Int32x4) \
6738 V(SIMD.int32x4.prototype, flagZ, Int32x4GetFlagZ, Tagged, Int32x4) \
6739 V(SIMD.int32x4.prototype, flagW, Int32x4GetFlagW, Tagged, Int32x4)
6741 #define SIMD_BINARY_OPERATIONS(V) \
6742 V(SIMD.float32x4, add, Float32x4Add, Float32x4, Float32x4, Float32x4) \
6743 V(SIMD.float32x4, div, Float32x4Div, Float32x4, Float32x4, Float32x4) \
6744 V(SIMD.float32x4, max, Float32x4Max, Float32x4, Float32x4, Float32x4) \
6745 V(SIMD.float32x4, min, Float32x4Min, Float32x4, Float32x4, Float32x4) \
6746 V(SIMD.float32x4, mul, Float32x4Mul, Float32x4, Float32x4, Float32x4) \
6747 V(SIMD.float32x4, sub, Float32x4Sub, Float32x4, Float32x4, Float32x4) \
6748 V(SIMD.float32x4, equal, Float32x4Equal, Int32x4, Float32x4, Float32x4) \
6749 V(SIMD.float32x4, notEqual, Float32x4NotEqual, Int32x4, Float32x4, \
6751 V(SIMD.float32x4, greaterThan, Float32x4GreaterThan, Int32x4, Float32x4, \
6753 V(SIMD.float32x4, greaterThanOrEqual, Float32x4GreaterThanOrEqual, Int32x4, \
6754 Float32x4, Float32x4) \
6755 V(SIMD.float32x4, lessThan, Float32x4LessThan, Int32x4, Float32x4, \
6757 V(SIMD.float32x4, lessThanOrEqual, Float32x4LessThanOrEqual, Int32x4, \
6758 Float32x4, Float32x4) \
6759 V(SIMD.float32x4, shuffle, Float32x4Shuffle, Float32x4, Float32x4, \
6761 V(SIMD.float32x4, scale, Float32x4Scale, Float32x4, Float32x4, Double) \
6762 V(SIMD.float32x4, withX, Float32x4WithX, Float32x4, Float32x4, Double) \
6763 V(SIMD.float32x4, withY, Float32x4WithY, Float32x4, Float32x4, Double) \
6764 V(SIMD.float32x4, withZ, Float32x4WithZ, Float32x4, Float32x4, Double) \
6765 V(SIMD.float32x4, withW, Float32x4WithW, Float32x4, Float32x4, Double) \
6766 V(SIMD.float64x2, add, Float64x2Add, Float64x2, Float64x2, Float64x2) \
6767 V(SIMD.float64x2, div, Float64x2Div, Float64x2, Float64x2, Float64x2) \
6768 V(SIMD.float64x2, max, Float64x2Max, Float64x2, Float64x2, Float64x2) \
6769 V(SIMD.float64x2, min, Float64x2Min, Float64x2, Float64x2, Float64x2) \
6770 V(SIMD.float64x2, mul, Float64x2Mul, Float64x2, Float64x2, Float64x2) \
6771 V(SIMD.float64x2, sub, Float64x2Sub, Float64x2, Float64x2, Float64x2) \
6772 V(SIMD.float64x2, scale, Float64x2Scale, Float64x2, Float64x2, Double) \
6773 V(SIMD.float64x2, withX, Float64x2WithX, Float64x2, Float64x2, Double) \
6774 V(SIMD.float64x2, withY, Float64x2WithY, Float64x2, Float64x2, Double) \
6775 V(SIMD, float64x2, Float64x2Constructor, Float64x2, Double, Double) \
6776 V(SIMD.int32x4, add, Int32x4Add, Int32x4, Int32x4, Int32x4) \
6777 V(SIMD.int32x4, and, Int32x4And, Int32x4, Int32x4, Int32x4) \
6778 V(SIMD.int32x4, mul, Int32x4Mul, Int32x4, Int32x4, Int32x4) \
6779 V(SIMD.int32x4, or, Int32x4Or, Int32x4, Int32x4, Int32x4) \
6780 V(SIMD.int32x4, sub, Int32x4Sub, Int32x4, Int32x4, Int32x4) \
6781 V(SIMD.int32x4, xor, Int32x4Xor, Int32x4, Int32x4, Int32x4) \
6782 V(SIMD.int32x4, shuffle, Int32x4Shuffle, Int32x4, Int32x4, Integer32) \
6783 V(SIMD.int32x4, withX, Int32x4WithX, Int32x4, Int32x4, Integer32) \
6784 V(SIMD.int32x4, withY, Int32x4WithY, Int32x4, Int32x4, Integer32) \
6785 V(SIMD.int32x4, withZ, Int32x4WithZ, Int32x4, Int32x4, Integer32) \
6786 V(SIMD.int32x4, withW, Int32x4WithW, Int32x4, Int32x4, Integer32) \
6787 V(SIMD.int32x4, withFlagX, Int32x4WithFlagX, Int32x4, Int32x4, Tagged) \
6788 V(SIMD.int32x4, withFlagY, Int32x4WithFlagY, Int32x4, Int32x4, Tagged) \
6789 V(SIMD.int32x4, withFlagZ, Int32x4WithFlagZ, Int32x4, Int32x4, Tagged) \
6790 V(SIMD.int32x4, withFlagW, Int32x4WithFlagW, Int32x4, Int32x4, Tagged) \
6791 V(SIMD.int32x4, greaterThan, Int32x4GreaterThan, Int32x4, Int32x4, Int32x4) \
6792 V(SIMD.int32x4, equal, Int32x4Equal, Int32x4, Int32x4, Int32x4) \
6793 V(SIMD.int32x4, lessThan, Int32x4LessThan, Int32x4, Int32x4, Int32x4) \
6794 V(SIMD.int32x4, shiftLeft, Int32x4ShiftLeft, Int32x4, Int32x4, Integer32) \
6795 V(SIMD.int32x4, shiftRight, Int32x4ShiftRight, Int32x4, Int32x4, Integer32) \
6796 V(SIMD.int32x4, shiftRightArithmetic, Int32x4ShiftRightArithmetic, Int32x4, \
6799 #define SIMD_TERNARY_OPERATIONS(V) \
6800 V(SIMD.float32x4, clamp, Float32x4Clamp, Float32x4, Float32x4, Float32x4, \
6802 V(SIMD.float32x4, shuffleMix, Float32x4ShuffleMix, Float32x4, Float32x4, \
6803 Float32x4, Integer32) \
6804 V(SIMD.float32x4, select, Float32x4Select, Float32x4, Int32x4, Float32x4, \
6806 V(SIMD.float64x2, clamp, Float64x2Clamp, Float64x2, Float64x2, Float64x2, \
6808 V(SIMD.int32x4, select, Int32x4Select, Int32x4, Int32x4, Int32x4, Int32x4)
6810 #define SIMD_QUARTERNARY_OPERATIONS(V) \
6811 V(SIMD, float32x4, Float32x4Constructor, Float32x4, Double, Double, Double, \
6813 V(SIMD, int32x4, Int32x4Constructor, Int32x4, Integer32, Integer32, \
6814 Integer32, Integer32) \
6815 V(SIMD.int32x4, bool, Int32x4Bool, Int32x4, Tagged, Tagged, Tagged, Tagged)
6817 #define SIMD_ARRAY_OPERATIONS(V) \
6818 V(Float32x4Array.prototype, getAt, Float32x4ArrayGetAt) \
6819 V(Float32x4Array.prototype, setAt, Float32x4ArraySetAt) \
6820 V(Float64x2Array.prototype, getAt, Float64x2ArrayGetAt) \
6821 V(Float64x2Array.prototype, setAt, Float64x2ArraySetAt) \
6822 V(Int32x4Array.prototype, getAt, Int32x4ArrayGetAt) \
6823 V(Int32x4Array.prototype, setAt, Int32x4ArraySetAt)
6825 #define TYPED_ARRAYS_SIMD_LOAD_OPERATIONS(V) \
6826 V(Float32Array.prototype, _getFloat32x4XYZW, Float32ArrayGetFloat32x4XYZW) \
6827 V(Float32Array.prototype, _getFloat32x4XYZ, Float32ArrayGetFloat32x4XYZ) \
6828 V(Float32Array.prototype, _getFloat32x4XY, Float32ArrayGetFloat32x4XY) \
6829 V(Float32Array.prototype, _getFloat32x4X, Float32ArrayGetFloat32x4X) \
6830 V(Float64Array.prototype, _getFloat64x2XY, Float64ArrayGetFloat64x2XY) \
6831 V(Float64Array.prototype, _getFloat64x2X, Float64ArrayGetFloat64x2X) \
6832 V(Int32Array.prototype, _getInt32x4XYZW, Int32ArrayGetInt32x4XYZW) \
6833 V(Int32Array.prototype, _getInt32x4XYZ, Int32ArrayGetInt32x4XYZ) \
6834 V(Int32Array.prototype, _getInt32x4XY, Int32ArrayGetInt32x4XY) \
6835 V(Int32Array.prototype, _getInt32x4X, Int32ArrayGetInt32x4X) \
6836 V(Int8Array.prototype, _getFloat32x4XYZW, Int8ArrayGetFloat32x4XYZW) \
6837 V(Int8Array.prototype, _getFloat32x4XYZ, Int8ArrayGetFloat32x4XYZ) \
6838 V(Int8Array.prototype, _getFloat32x4XY, Int8ArrayGetFloat32x4XY) \
6839 V(Int8Array.prototype, _getFloat32x4X, Int8ArrayGetFloat32x4X) \
6840 V(Int8Array.prototype, _getFloat64x2XY, Int8ArrayGetFloat64x2XY) \
6841 V(Int8Array.prototype, _getFloat64x2X, Int8ArrayGetFloat64x2X) \
6842 V(Int8Array.prototype, _getInt32x4XYZW, Int8ArrayGetInt32x4XYZW) \
6843 V(Int8Array.prototype, _getInt32x4XYZ, Int8ArrayGetInt32x4XYZ) \
6844 V(Int8Array.prototype, _getInt32x4XY, Int8ArrayGetInt32x4XY) \
6845 V(Int8Array.prototype, _getInt32x4X, Int8ArrayGetInt32x4X)
6847 #define TYPED_ARRAYS_SIMD_STORE_OPERATIONS(V) \
6848 V(Float32Array.prototype, _setFloat32x4XYZW, Float32ArraySetFloat32x4XYZW) \
6849 V(Float32Array.prototype, _setFloat32x4XYZ, Float32ArraySetFloat32x4XYZ) \
6850 V(Float32Array.prototype, _setFloat32x4XY, Float32ArraySetFloat32x4XY) \
6851 V(Float32Array.prototype, _setFloat32x4X, Float32ArraySetFloat32x4X) \
6852 V(Float64Array.prototype, _setFloat64x2XY, Float64ArraySetFloat64x2XY) \
6853 V(Float64Array.prototype, _setFloat64x2X, Float64ArraySetFloat64x2X) \
6854 V(Int32Array.prototype, _setInt32x4XYZW, Int32ArraySetInt32x4XYZW) \
6855 V(Int32Array.prototype, _setInt32x4XYZ, Int32ArraySetInt32x4XYZ) \
6856 V(Int32Array.prototype, _setInt32x4XY, Int32ArraySetInt32x4XY) \
6857 V(Int32Array.prototype, _setInt32x4X, Int32ArraySetInt32x4X) \
6858 V(Int8Array.prototype, _setFloat32x4XYZW, Int8ArraySetFloat32x4XYZW) \
6859 V(Int8Array.prototype, _setFloat32x4XYZ, Int8ArraySetFloat32x4XYZ) \
6860 V(Int8Array.prototype, _setFloat32x4XY, Int8ArraySetFloat32x4XY) \
6861 V(Int8Array.prototype, _setFloat32x4X, Int8ArraySetFloat32x4X) \
6862 V(Int8Array.prototype, _setFloat64x2XY, Int8ArraySetFloat64x2XY) \
6863 V(Int8Array.prototype, _setFloat64x2X, Int8ArraySetFloat64x2X) \
6864 V(Int8Array.prototype, _setInt32x4XYZW, Int8ArraySetInt32x4XYZW) \
6865 V(Int8Array.prototype, _setInt32x4XYZ, Int8ArraySetInt32x4XYZ) \
6866 V(Int8Array.prototype, _setInt32x4XY, Int8ArraySetInt32x4XY) \
6867 V(Int8Array.prototype, _setInt32x4X, Int8ArraySetInt32x4X)
6869 // Do not need to install them in InstallExperimentalSIMDBuiltinFunctionIds.
6870 #define SIMD_FAKE_ID_LISTS(V) \
6871 V(SIMD, unreachable, SIMD128Unreachable) \
6872 V(SIMD, change, SIMD128Change)
6874 enum BuiltinFunctionId {
6876 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6878 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6879 // Fake id for a special case of Math.pow. Note, it continues the
6880 // list of math functions.
6882 SIMD_FAKE_ID_LISTS(DECLARE_FUNCTION_ID)
6883 SIMD_ARRAY_OPERATIONS(DECLARE_FUNCTION_ID)
6884 TYPED_ARRAYS_SIMD_LOAD_OPERATIONS(DECLARE_FUNCTION_ID)
6885 TYPED_ARRAYS_SIMD_STORE_OPERATIONS(DECLARE_FUNCTION_ID)
6886 #undef DECLARE_FUNCTION_ID
6887 #define DECLARE_SIMD_NULLARY_FUNCTION_ID(i1, i2, name, i3) \
6889 SIMD_NULLARY_OPERATIONS(DECLARE_SIMD_NULLARY_FUNCTION_ID)
6890 #undef DECLARE_SIMD_NULLARY_FUNCTION_ID
6891 #define DECLARE_SIMD_UNARY_FUNCTION_ID(i1, i2, name, i3, i4) \
6893 SIMD_UNARY_OPERATIONS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6894 SIMD_UNARY_OPERATIONS_FOR_PROPERTY_ACCESS(DECLARE_SIMD_UNARY_FUNCTION_ID)
6895 #undef DECLARE_SIMD_UNARY_FUNCTION_ID
6896 #define DECLARE_SIMD_BINARY_FUNCTION_ID(i1, i2, name, i3, i4, i5) \
6898 SIMD_BINARY_OPERATIONS(DECLARE_SIMD_BINARY_FUNCTION_ID)
6899 #undef DECLARE_SIMD_BINARY_FUNCTION_ID
6900 #define DECLARE_SIMD_TERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6) \
6902 SIMD_TERNARY_OPERATIONS(DECLARE_SIMD_TERNARY_FUNCTION_ID)
6903 #undef DECLARE_SIMD_TERNARY_FUNCTION_ID
6904 #define DECLARE_SIMD_QUARTERNARY_FUNCTION_ID(i1, i2, name, i3, i4, i5, i6, i7) \
6906 SIMD_QUARTERNARY_OPERATIONS(DECLARE_SIMD_QUARTERNARY_FUNCTION_ID)
6907 #undef DECLARE_SIMD_QUARTERNARY_FUNCTION_ID
6908 kNumberOfBuiltinFunction
6912 // SharedFunctionInfo describes the JSFunction information that can be
6913 // shared by multiple instances of the function.
6914 class SharedFunctionInfo: public HeapObject {
6916 // [name]: Function name.
6917 DECL_ACCESSORS(name, Object)
6919 // [code]: Function code.
6920 DECL_ACCESSORS(code, Code)
6921 inline void ReplaceCode(Code* code);
6923 // [optimized_code_map]: Map from native context to optimized code
6924 // and a shared literals array or Smi(0) if none.
6925 DECL_ACCESSORS(optimized_code_map, Object)
6927 // Returns index i of the entry with the specified context and OSR entry.
6928 // At position i - 1 is the context, position i the code, and i + 1 the
6929 // literals array. Returns -1 when no matching entry is found.
6930 int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
6932 // Installs optimized code from the code map on the given closure. The
6933 // index has to be consistent with a search result as defined above.
6934 FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
6936 Code* GetCodeFromOptimizedCodeMap(int index);
6938 // Clear optimized code map.
6939 void ClearOptimizedCodeMap();
6941 // Removed a specific optimized code object from the optimized code map.
6942 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6944 void ClearTypeFeedbackInfo();
6946 // Trims the optimized code map after entries have been removed.
6947 void TrimOptimizedCodeMap(int shrink_by);
6949 // Add a new entry to the optimized code map.
6950 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6951 Handle<Context> native_context,
6953 Handle<FixedArray> literals,
6954 BailoutId osr_ast_id);
6956 // Layout description of the optimized code map.
6957 static const int kNextMapIndex = 0;
6958 static const int kEntriesStart = 1;
6959 static const int kContextOffset = 0;
6960 static const int kCachedCodeOffset = 1;
6961 static const int kLiteralsOffset = 2;
6962 static const int kOsrAstIdOffset = 3;
6963 static const int kEntryLength = 4;
6964 static const int kInitialLength = kEntriesStart + kEntryLength;
6966 // [scope_info]: Scope info.
6967 DECL_ACCESSORS(scope_info, ScopeInfo)
6969 // [construct stub]: Code stub for constructing instances of this function.
6970 DECL_ACCESSORS(construct_stub, Code)
6972 // Returns if this function has been compiled to native code yet.
6973 inline bool is_compiled();
6975 // [length]: The function length - usually the number of declared parameters.
6976 // Use up to 2^30 parameters.
6977 inline int length() const;
6978 inline void set_length(int value);
6980 // [formal parameter count]: The declared number of parameters.
6981 inline int formal_parameter_count() const;
6982 inline void set_formal_parameter_count(int value);
6984 // Set the formal parameter count so the function code will be
6985 // called without using argument adaptor frames.
6986 inline void DontAdaptArguments();
6988 // [expected_nof_properties]: Expected number of properties for the function.
6989 inline int expected_nof_properties() const;
6990 inline void set_expected_nof_properties(int value);
6992 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6993 // (increasingly) from crankshafted code where sufficient feedback isn't
6995 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6997 // [instance class name]: class name for instances.
6998 DECL_ACCESSORS(instance_class_name, Object)
7000 // [function data]: This field holds some additional data for function.
7001 // Currently it either has FunctionTemplateInfo to make benefit the API
7002 // or Smi identifying a builtin function.
7003 // In the long run we don't want all functions to have this field but
7004 // we can fix that when we have a better model for storing hidden data
7006 DECL_ACCESSORS(function_data, Object)
7008 inline bool IsApiFunction();
7009 inline FunctionTemplateInfo* get_api_func_data();
7010 inline bool HasBuiltinFunctionId();
7011 inline BuiltinFunctionId builtin_function_id();
7013 // [script info]: Script from which the function originates.
7014 DECL_ACCESSORS(script, Object)
7016 // [num_literals]: Number of literals used by this function.
7017 inline int num_literals() const;
7018 inline void set_num_literals(int value);
7020 // [start_position_and_type]: Field used to store both the source code
7021 // position, whether or not the function is a function expression,
7022 // and whether or not the function is a toplevel function. The two
7023 // least significants bit indicates whether the function is an
7024 // expression and the rest contains the source code position.
7025 inline int start_position_and_type() const;
7026 inline void set_start_position_and_type(int value);
7028 // [debug info]: Debug information.
7029 DECL_ACCESSORS(debug_info, Object)
7031 // [inferred name]: Name inferred from variable or property
7032 // assignment of this function. Used to facilitate debugging and
7033 // profiling of JavaScript code written in OO style, where almost
7034 // all functions are anonymous but are assigned to object
7036 DECL_ACCESSORS(inferred_name, String)
7038 // The function's name if it is non-empty, otherwise the inferred name.
7039 String* DebugName();
7041 // Position of the 'function' token in the script source.
7042 inline int function_token_position() const;
7043 inline void set_function_token_position(int function_token_position);
7045 // Position of this function in the script source.
7046 inline int start_position() const;
7047 inline void set_start_position(int start_position);
7049 // End position of this function in the script source.
7050 inline int end_position() const;
7051 inline void set_end_position(int end_position);
7053 // Is this function a function expression in the source code.
7054 DECL_BOOLEAN_ACCESSORS(is_expression)
7056 // Is this function a top-level function (scripts, evals).
7057 DECL_BOOLEAN_ACCESSORS(is_toplevel)
7059 // Bit field containing various information collected by the compiler to
7060 // drive optimization.
7061 inline int compiler_hints() const;
7062 inline void set_compiler_hints(int value);
7064 inline int ast_node_count() const;
7065 inline void set_ast_node_count(int count);
7067 inline int profiler_ticks() const;
7068 inline void set_profiler_ticks(int ticks);
7070 // Inline cache age is used to infer whether the function survived a context
7071 // disposal or not. In the former case we reset the opt_count.
7072 inline int ic_age();
7073 inline void set_ic_age(int age);
7075 // Indicates if this function can be lazy compiled.
7076 // This is used to determine if we can safely flush code from a function
7077 // when doing GC if we expect that the function will no longer be used.
7078 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
7080 // Indicates if this function can be lazy compiled without a context.
7081 // This is used to determine if we can force compilation without reaching
7082 // the function through program execution but through other means (e.g. heap
7083 // iteration by the debugger).
7084 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
7086 // Indicates whether optimizations have been disabled for this
7087 // shared function info. If a function is repeatedly optimized or if
7088 // we cannot optimize the function we disable optimization to avoid
7089 // spending time attempting to optimize it again.
7090 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
7092 // Indicates the language mode.
7093 inline StrictMode strict_mode();
7094 inline void set_strict_mode(StrictMode strict_mode);
7096 // False if the function definitely does not allocate an arguments object.
7097 DECL_BOOLEAN_ACCESSORS(uses_arguments)
7099 // True if the function has any duplicated parameter names.
7100 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
7102 // Indicates whether the function is a native function.
7103 // These needs special treatment in .call and .apply since
7104 // null passed as the receiver should not be translated to the
7106 DECL_BOOLEAN_ACCESSORS(native)
7108 // Indicate that this builtin needs to be inlined in crankshaft.
7109 DECL_BOOLEAN_ACCESSORS(inline_builtin)
7111 // Indicates that the function was created by the Function function.
7112 // Though it's anonymous, toString should treat it as if it had the name
7113 // "anonymous". We don't set the name itself so that the system does not
7114 // see a binding for it.
7115 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
7117 // Indicates whether the function is a bound function created using
7118 // the bind function.
7119 DECL_BOOLEAN_ACCESSORS(bound)
7121 // Indicates that the function is anonymous (the name field can be set
7122 // through the API, which does not change this flag).
7123 DECL_BOOLEAN_ACCESSORS(is_anonymous)
7125 // Is this a function or top-level/eval code.
7126 DECL_BOOLEAN_ACCESSORS(is_function)
7128 // Indicates that code for this function cannot be cached.
7129 DECL_BOOLEAN_ACCESSORS(dont_cache)
7131 // Indicates that code for this function cannot be flushed.
7132 DECL_BOOLEAN_ACCESSORS(dont_flush)
7134 // Indicates that this function is a generator.
7135 DECL_BOOLEAN_ACCESSORS(is_generator)
7137 // Indicates that this function is an arrow function.
7138 DECL_BOOLEAN_ACCESSORS(is_arrow)
7140 // Indicates that this function is a concise method.
7141 DECL_BOOLEAN_ACCESSORS(is_concise_method)
7143 // Indicates that this function is an asm function.
7144 DECL_BOOLEAN_ACCESSORS(asm_function)
7146 inline FunctionKind kind();
7147 inline void set_kind(FunctionKind kind);
7149 // Indicates whether or not the code in the shared function support
7151 inline bool has_deoptimization_support();
7153 // Enable deoptimization support through recompiled code.
7154 void EnableDeoptimizationSupport(Code* recompiled);
7156 // Disable (further) attempted optimization of all functions sharing this
7157 // shared function info.
7158 void DisableOptimization(BailoutReason reason);
7160 inline BailoutReason DisableOptimizationReason();
7162 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
7163 // code, returns whether it asserted (i.e., always true if assertions are
7165 bool VerifyBailoutId(BailoutId id);
7167 // [source code]: Source code for the function.
7168 bool HasSourceCode() const;
7169 Handle<Object> GetSourceCode();
7171 // Number of times the function was optimized.
7172 inline int opt_count();
7173 inline void set_opt_count(int opt_count);
7175 // Number of times the function was deoptimized.
7176 inline void set_deopt_count(int value);
7177 inline int deopt_count();
7178 inline void increment_deopt_count();
7180 // Number of time we tried to re-enable optimization after it
7181 // was disabled due to high number of deoptimizations.
7182 inline void set_opt_reenable_tries(int value);
7183 inline int opt_reenable_tries();
7185 inline void TryReenableOptimization();
7187 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
7188 inline void set_counters(int value);
7189 inline int counters() const;
7191 // Stores opt_count and bailout_reason as bit-fields.
7192 inline void set_opt_count_and_bailout_reason(int value);
7193 inline int opt_count_and_bailout_reason() const;
7195 void set_bailout_reason(BailoutReason reason) {
7196 set_opt_count_and_bailout_reason(
7197 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
7201 // Check whether or not this function is inlineable.
7202 bool IsInlineable();
7204 // Source size of this function.
7207 // Calculate the instance size.
7208 int CalculateInstanceSize();
7210 // Calculate the number of in-object properties.
7211 int CalculateInObjectProperties();
7213 // Dispatched behavior.
7214 DECLARE_PRINTER(SharedFunctionInfo)
7215 DECLARE_VERIFIER(SharedFunctionInfo)
7217 void ResetForNewContext(int new_ic_age);
7219 DECLARE_CAST(SharedFunctionInfo)
7222 static const int kDontAdaptArgumentsSentinel = -1;
7224 // Layout description.
7226 static const int kNameOffset = HeapObject::kHeaderSize;
7227 static const int kCodeOffset = kNameOffset + kPointerSize;
7228 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
7229 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
7230 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
7231 static const int kInstanceClassNameOffset =
7232 kConstructStubOffset + kPointerSize;
7233 static const int kFunctionDataOffset =
7234 kInstanceClassNameOffset + kPointerSize;
7235 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
7236 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
7237 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
7238 static const int kFeedbackVectorOffset =
7239 kInferredNameOffset + kPointerSize;
7240 #if V8_HOST_ARCH_32_BIT
7242 static const int kLengthOffset =
7243 kFeedbackVectorOffset + kPointerSize;
7244 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
7245 static const int kExpectedNofPropertiesOffset =
7246 kFormalParameterCountOffset + kPointerSize;
7247 static const int kNumLiteralsOffset =
7248 kExpectedNofPropertiesOffset + kPointerSize;
7249 static const int kStartPositionAndTypeOffset =
7250 kNumLiteralsOffset + kPointerSize;
7251 static const int kEndPositionOffset =
7252 kStartPositionAndTypeOffset + kPointerSize;
7253 static const int kFunctionTokenPositionOffset =
7254 kEndPositionOffset + kPointerSize;
7255 static const int kCompilerHintsOffset =
7256 kFunctionTokenPositionOffset + kPointerSize;
7257 static const int kOptCountAndBailoutReasonOffset =
7258 kCompilerHintsOffset + kPointerSize;
7259 static const int kCountersOffset =
7260 kOptCountAndBailoutReasonOffset + kPointerSize;
7261 static const int kAstNodeCountOffset =
7262 kCountersOffset + kPointerSize;
7263 static const int kProfilerTicksOffset =
7264 kAstNodeCountOffset + kPointerSize;
7267 static const int kSize = kProfilerTicksOffset + kPointerSize;
7269 // The only reason to use smi fields instead of int fields
7270 // is to allow iteration without maps decoding during
7271 // garbage collections.
7272 // To avoid wasting space on 64-bit architectures we use
7273 // the following trick: we group integer fields into pairs
7274 // First integer in each pair is shifted left by 1.
7275 // By doing this we guarantee that LSB of each kPointerSize aligned
7276 // word is not set and thus this word cannot be treated as pointer
7277 // to HeapObject during old space traversal.
7278 static const int kLengthOffset =
7279 kFeedbackVectorOffset + kPointerSize;
7280 static const int kFormalParameterCountOffset =
7281 kLengthOffset + kIntSize;
7283 static const int kExpectedNofPropertiesOffset =
7284 kFormalParameterCountOffset + kIntSize;
7285 static const int kNumLiteralsOffset =
7286 kExpectedNofPropertiesOffset + kIntSize;
7288 static const int kEndPositionOffset =
7289 kNumLiteralsOffset + kIntSize;
7290 static const int kStartPositionAndTypeOffset =
7291 kEndPositionOffset + kIntSize;
7293 static const int kFunctionTokenPositionOffset =
7294 kStartPositionAndTypeOffset + kIntSize;
7295 static const int kCompilerHintsOffset =
7296 kFunctionTokenPositionOffset + kIntSize;
7298 static const int kOptCountAndBailoutReasonOffset =
7299 kCompilerHintsOffset + kIntSize;
7300 static const int kCountersOffset =
7301 kOptCountAndBailoutReasonOffset + kIntSize;
7303 static const int kAstNodeCountOffset =
7304 kCountersOffset + kIntSize;
7305 static const int kProfilerTicksOffset =
7306 kAstNodeCountOffset + kIntSize;
7309 static const int kSize = kProfilerTicksOffset + kIntSize;
7313 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7315 typedef FixedBodyDescriptor<kNameOffset,
7316 kFeedbackVectorOffset + kPointerSize,
7317 kSize> BodyDescriptor;
7319 // Bit positions in start_position_and_type.
7320 // The source code start position is in the 30 most significant bits of
7321 // the start_position_and_type field.
7322 static const int kIsExpressionBit = 0;
7323 static const int kIsTopLevelBit = 1;
7324 static const int kStartPositionShift = 2;
7325 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7327 // Bit positions in compiler_hints.
7328 enum CompilerHints {
7329 kAllowLazyCompilation,
7330 kAllowLazyCompilationWithoutContext,
7331 kOptimizationDisabled,
7332 kStrictModeFunction,
7334 kHasDuplicateParameters,
7339 kNameShouldPrintAsAnonymous,
7347 kCompilerHintsCount // Pseudo entry
7350 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 3> {};
7352 class DeoptCountBits : public BitField<int, 0, 4> {};
7353 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7354 class ICAgeBits : public BitField<int, 22, 8> {};
7356 class OptCountBits : public BitField<int, 0, 22> {};
7357 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7360 #if V8_HOST_ARCH_32_BIT
7361 // On 32 bit platforms, compiler hints is a smi.
7362 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7363 static const int kCompilerHintsSize = kPointerSize;
7365 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7366 static const int kCompilerHintsSmiTagSize = 0;
7367 static const int kCompilerHintsSize = kIntSize;
7370 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7371 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7374 // Constants for optimizing codegen for strict mode function and
7376 // Allows to use byte-width instructions.
7377 static const int kStrictModeBitWithinByte =
7378 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7380 static const int kNativeBitWithinByte =
7381 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7383 #if defined(V8_TARGET_LITTLE_ENDIAN)
7384 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7385 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7386 static const int kNativeByteOffset = kCompilerHintsOffset +
7387 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7388 #elif defined(V8_TARGET_BIG_ENDIAN)
7389 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7390 (kCompilerHintsSize - 1) -
7391 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7392 static const int kNativeByteOffset = kCompilerHintsOffset +
7393 (kCompilerHintsSize - 1) -
7394 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7396 #error Unknown byte ordering
7400 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7404 // Printing support.
7405 struct SourceCodeOf {
7406 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7407 : value(v), max_length(max) {}
7408 const SharedFunctionInfo* value;
7413 OStream& operator<<(OStream& os, const SourceCodeOf& v);
7416 class JSGeneratorObject: public JSObject {
7418 // [function]: The function corresponding to this generator object.
7419 DECL_ACCESSORS(function, JSFunction)
7421 // [context]: The context of the suspended computation.
7422 DECL_ACCESSORS(context, Context)
7424 // [receiver]: The receiver of the suspended computation.
7425 DECL_ACCESSORS(receiver, Object)
7427 // [continuation]: Offset into code of continuation.
7429 // A positive offset indicates a suspended generator. The special
7430 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7431 // cannot be resumed.
7432 inline int continuation() const;
7433 inline void set_continuation(int continuation);
7434 inline bool is_closed();
7435 inline bool is_executing();
7436 inline bool is_suspended();
7438 // [operand_stack]: Saved operand stack.
7439 DECL_ACCESSORS(operand_stack, FixedArray)
7441 // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7442 // if the captured activation had no stack handler.
7443 inline int stack_handler_index() const;
7444 inline void set_stack_handler_index(int stack_handler_index);
7446 DECLARE_CAST(JSGeneratorObject)
7448 // Dispatched behavior.
7449 DECLARE_PRINTER(JSGeneratorObject)
7450 DECLARE_VERIFIER(JSGeneratorObject)
7452 // Magic sentinel values for the continuation.
7453 static const int kGeneratorExecuting = -1;
7454 static const int kGeneratorClosed = 0;
7456 // Layout description.
7457 static const int kFunctionOffset = JSObject::kHeaderSize;
7458 static const int kContextOffset = kFunctionOffset + kPointerSize;
7459 static const int kReceiverOffset = kContextOffset + kPointerSize;
7460 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7461 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7462 static const int kStackHandlerIndexOffset =
7463 kOperandStackOffset + kPointerSize;
7464 static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7466 // Resume mode, for use by runtime functions.
7467 enum ResumeMode { NEXT, THROW };
7469 // Yielding from a generator returns an object with the following inobject
7470 // properties. See Context::iterator_result_map() for the map.
7471 static const int kResultValuePropertyIndex = 0;
7472 static const int kResultDonePropertyIndex = 1;
7473 static const int kResultPropertyCount = 2;
7475 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7476 static const int kResultDonePropertyOffset =
7477 kResultValuePropertyOffset + kPointerSize;
7478 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7481 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7485 // Representation for module instance objects.
7486 class JSModule: public JSObject {
7488 // [context]: the context holding the module's locals, or undefined if none.
7489 DECL_ACCESSORS(context, Object)
7491 // [scope_info]: Scope info.
7492 DECL_ACCESSORS(scope_info, ScopeInfo)
7494 DECLARE_CAST(JSModule)
7496 // Dispatched behavior.
7497 DECLARE_PRINTER(JSModule)
7498 DECLARE_VERIFIER(JSModule)
7500 // Layout description.
7501 static const int kContextOffset = JSObject::kHeaderSize;
7502 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7503 static const int kSize = kScopeInfoOffset + kPointerSize;
7506 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7510 // JSFunction describes JavaScript functions.
7511 class JSFunction: public JSObject {
7513 // [prototype_or_initial_map]:
7514 DECL_ACCESSORS(prototype_or_initial_map, Object)
7516 // [shared]: The information about the function that
7517 // can be shared by instances.
7518 DECL_ACCESSORS(shared, SharedFunctionInfo)
7520 // [context]: The context for this function.
7521 inline Context* context();
7522 inline void set_context(Object* context);
7523 inline JSObject* global_proxy();
7525 // [code]: The generated code object for this function. Executed
7526 // when the function is invoked, e.g. foo() or new foo(). See
7527 // [[Call]] and [[Construct]] description in ECMA-262, section
7529 inline Code* code();
7530 inline void set_code(Code* code);
7531 inline void set_code_no_write_barrier(Code* code);
7532 inline void ReplaceCode(Code* code);
7534 // Tells whether this function is builtin.
7535 inline bool IsBuiltin();
7537 // Tells whether this function is defined in a native script.
7538 inline bool IsFromNativeScript();
7540 // Tells whether this function is defined in an extension script.
7541 inline bool IsFromExtensionScript();
7543 // Tells whether or not the function needs arguments adaption.
7544 inline bool NeedsArgumentsAdaption();
7546 // Tells whether or not this function has been optimized.
7547 inline bool IsOptimized();
7549 // Tells whether or not this function can be optimized.
7550 inline bool IsOptimizable();
7552 // Mark this function for lazy recompilation. The function will be
7553 // recompiled the next time it is executed.
7554 void MarkForOptimization();
7555 void MarkForConcurrentOptimization();
7556 void MarkInOptimizationQueue();
7558 // Tells whether or not the function is already marked for lazy
7560 inline bool IsMarkedForOptimization();
7561 inline bool IsMarkedForConcurrentOptimization();
7563 // Tells whether or not the function is on the concurrent recompilation queue.
7564 inline bool IsInOptimizationQueue();
7566 // Inobject slack tracking is the way to reclaim unused inobject space.
7568 // The instance size is initially determined by adding some slack to
7569 // expected_nof_properties (to allow for a few extra properties added
7570 // after the constructor). There is no guarantee that the extra space
7571 // will not be wasted.
7573 // Here is the algorithm to reclaim the unused inobject space:
7574 // - Detect the first constructor call for this JSFunction.
7575 // When it happens enter the "in progress" state: initialize construction
7576 // counter in the initial_map and set the |done_inobject_slack_tracking|
7578 // - While the tracking is in progress create objects filled with
7579 // one_pointer_filler_map instead of undefined_value. This way they can be
7580 // resized quickly and safely.
7581 // - Once enough (kGenerousAllocationCount) objects have been created
7582 // compute the 'slack' (traverse the map transition tree starting from the
7583 // initial_map and find the lowest value of unused_property_fields).
7584 // - Traverse the transition tree again and decrease the instance size
7585 // of every map. Existing objects will resize automatically (they are
7586 // filled with one_pointer_filler_map). All further allocations will
7587 // use the adjusted instance size.
7588 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7589 // allocations made using different closures could actually create different
7590 // kind of objects (see prototype inheritance pattern).
7592 // Important: inobject slack tracking is not attempted during the snapshot
7595 static const int kGenerousAllocationCount = Map::ConstructionCount::kMax;
7596 static const int kFinishSlackTracking = 1;
7597 static const int kNoSlackTracking = 0;
7599 // True if the initial_map is set and the object constructions countdown
7600 // counter is not zero.
7601 inline bool IsInobjectSlackTrackingInProgress();
7603 // Starts the tracking.
7604 // Initializes object constructions countdown counter in the initial map.
7605 // IsInobjectSlackTrackingInProgress is normally true after this call,
7606 // except when tracking have not been started (e.g. the map has no unused
7607 // properties or the snapshot is being built).
7608 void StartInobjectSlackTracking();
7610 // Completes the tracking.
7611 // IsInobjectSlackTrackingInProgress is false after this call.
7612 void CompleteInobjectSlackTracking();
7614 // [literals_or_bindings]: Fixed array holding either
7615 // the materialized literals or the bindings of a bound function.
7617 // If the function contains object, regexp or array literals, the
7618 // literals array prefix contains the object, regexp, and array
7619 // function to be used when creating these literals. This is
7620 // necessary so that we do not dynamically lookup the object, regexp
7621 // or array functions. Performing a dynamic lookup, we might end up
7622 // using the functions from a new context that we should not have
7625 // On bound functions, the array is a (copy-on-write) fixed-array containing
7626 // the function that was bound, bound this-value and any bound
7627 // arguments. Bound functions never contain literals.
7628 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7630 inline FixedArray* literals();
7631 inline void set_literals(FixedArray* literals);
7633 inline FixedArray* function_bindings();
7634 inline void set_function_bindings(FixedArray* bindings);
7636 // The initial map for an object created by this constructor.
7637 inline Map* initial_map();
7638 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7639 Handle<Object> prototype);
7640 inline bool has_initial_map();
7641 static void EnsureHasInitialMap(Handle<JSFunction> function);
7643 // Get and set the prototype property on a JSFunction. If the
7644 // function has an initial map the prototype is set on the initial
7645 // map. Otherwise, the prototype is put in the initial map field
7646 // until an initial map is needed.
7647 inline bool has_prototype();
7648 inline bool has_instance_prototype();
7649 inline Object* prototype();
7650 inline Object* instance_prototype();
7651 static void SetPrototype(Handle<JSFunction> function,
7652 Handle<Object> value);
7653 static void SetInstancePrototype(Handle<JSFunction> function,
7654 Handle<Object> value);
7656 // Creates a new closure for the fucntion with the same bindings,
7657 // bound values, and prototype. An equivalent of spec operations
7658 // ``CloneMethod`` and ``CloneBoundFunction``.
7659 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7661 // After prototype is removed, it will not be created when accessed, and
7662 // [[Construct]] from this function will not be allowed.
7663 bool RemovePrototype();
7664 inline bool should_have_prototype();
7666 // Accessor for this function's initial map's [[class]]
7667 // property. This is primarily used by ECMA native functions. This
7668 // method sets the class_name field of this function's initial map
7669 // to a given value. It creates an initial map if this function does
7670 // not have one. Note that this method does not copy the initial map
7671 // if it has one already, but simply replaces it with the new value.
7672 // Instances created afterwards will have a map whose [[class]] is
7673 // set to 'value', but there is no guarantees on instances created
7675 void SetInstanceClassName(String* name);
7677 // Returns if this function has been compiled to native code yet.
7678 inline bool is_compiled();
7680 // [next_function_link]: Links functions into various lists, e.g. the list
7681 // of optimized functions hanging off the native_context. The CodeFlusher
7682 // uses this link to chain together flushing candidates. Treated weakly
7683 // by the garbage collector.
7684 DECL_ACCESSORS(next_function_link, Object)
7686 // Prints the name of the function using PrintF.
7687 void PrintName(FILE* out = stdout);
7689 DECLARE_CAST(JSFunction)
7691 // Iterates the objects, including code objects indirectly referenced
7692 // through pointers to the first instruction in the code object.
7693 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7695 // Dispatched behavior.
7696 DECLARE_PRINTER(JSFunction)
7697 DECLARE_VERIFIER(JSFunction)
7699 // Returns the number of allocated literals.
7700 inline int NumberOfLiterals();
7702 // Retrieve the native context from a function's literal array.
7703 static Context* NativeContextFromLiterals(FixedArray* literals);
7705 // Used for flags such as --hydrogen-filter.
7706 bool PassesFilter(const char* raw_filter);
7708 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7709 // kSize) is weak and has special handling during garbage collection.
7710 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7711 static const int kPrototypeOrInitialMapOffset =
7712 kCodeEntryOffset + kPointerSize;
7713 static const int kSharedFunctionInfoOffset =
7714 kPrototypeOrInitialMapOffset + kPointerSize;
7715 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7716 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7717 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7718 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7719 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7721 // Layout of the literals array.
7722 static const int kLiteralsPrefixSize = 1;
7723 static const int kLiteralNativeContextIndex = 0;
7725 // Layout of the bound-function binding array.
7726 static const int kBoundFunctionIndex = 0;
7727 static const int kBoundThisIndex = 1;
7728 static const int kBoundArgumentsStartIndex = 2;
7731 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7735 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7736 // and the prototype is hidden. JSGlobalProxy always delegates
7737 // property accesses to its prototype if the prototype is not null.
7739 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7741 // Accessing a JSGlobalProxy requires security check.
7743 class JSGlobalProxy : public JSObject {
7745 // [native_context]: the owner native context of this global proxy object.
7746 // It is null value if this object is not used by any context.
7747 DECL_ACCESSORS(native_context, Object)
7749 // [hash]: The hash code property (undefined if not initialized yet).
7750 DECL_ACCESSORS(hash, Object)
7752 DECLARE_CAST(JSGlobalProxy)
7754 inline bool IsDetachedFrom(GlobalObject* global) const;
7756 // Dispatched behavior.
7757 DECLARE_PRINTER(JSGlobalProxy)
7758 DECLARE_VERIFIER(JSGlobalProxy)
7760 // Layout description.
7761 static const int kNativeContextOffset = JSObject::kHeaderSize;
7762 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7763 static const int kSize = kHashOffset + kPointerSize;
7766 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7770 // Forward declaration.
7771 class JSBuiltinsObject;
7773 // Common super class for JavaScript global objects and the special
7774 // builtins global objects.
7775 class GlobalObject: public JSObject {
7777 // [builtins]: the object holding the runtime routines written in JS.
7778 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7780 // [native context]: the natives corresponding to this global object.
7781 DECL_ACCESSORS(native_context, Context)
7783 // [global context]: the most recent (i.e. innermost) global context.
7784 DECL_ACCESSORS(global_context, Context)
7786 // [global proxy]: the global proxy object of the context
7787 DECL_ACCESSORS(global_proxy, JSObject)
7789 DECLARE_CAST(GlobalObject)
7791 // Layout description.
7792 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7793 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7794 static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7795 static const int kGlobalProxyOffset = kGlobalContextOffset + kPointerSize;
7796 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7799 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7803 // JavaScript global object.
7804 class JSGlobalObject: public GlobalObject {
7806 DECLARE_CAST(JSGlobalObject)
7808 // Ensure that the global object has a cell for the given property name.
7809 static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7812 inline bool IsDetached();
7814 // Dispatched behavior.
7815 DECLARE_PRINTER(JSGlobalObject)
7816 DECLARE_VERIFIER(JSGlobalObject)
7818 // Layout description.
7819 static const int kSize = GlobalObject::kHeaderSize;
7822 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7826 // Builtins global object which holds the runtime routines written in
7828 class JSBuiltinsObject: public GlobalObject {
7830 // Accessors for the runtime routines written in JavaScript.
7831 inline Object* javascript_builtin(Builtins::JavaScript id);
7832 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7834 // Accessors for code of the runtime routines written in JavaScript.
7835 inline Code* javascript_builtin_code(Builtins::JavaScript id);
7836 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7838 DECLARE_CAST(JSBuiltinsObject)
7840 // Dispatched behavior.
7841 DECLARE_PRINTER(JSBuiltinsObject)
7842 DECLARE_VERIFIER(JSBuiltinsObject)
7844 // Layout description. The size of the builtins object includes
7845 // room for two pointers per runtime routine written in javascript
7846 // (function and code object).
7847 static const int kJSBuiltinsCount = Builtins::id_count;
7848 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7849 static const int kJSBuiltinsCodeOffset =
7850 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7851 static const int kSize =
7852 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7854 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7855 return kJSBuiltinsOffset + id * kPointerSize;
7858 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7859 return kJSBuiltinsCodeOffset + id * kPointerSize;
7863 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7867 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7868 class JSValue: public JSObject {
7870 // [value]: the object being wrapped.
7871 DECL_ACCESSORS(value, Object)
7873 DECLARE_CAST(JSValue)
7875 // Dispatched behavior.
7876 DECLARE_PRINTER(JSValue)
7877 DECLARE_VERIFIER(JSValue)
7879 // Layout description.
7880 static const int kValueOffset = JSObject::kHeaderSize;
7881 static const int kSize = kValueOffset + kPointerSize;
7884 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7890 // Representation for JS date objects.
7891 class JSDate: public JSObject {
7893 // If one component is NaN, all of them are, indicating a NaN time value.
7894 // [value]: the time value.
7895 DECL_ACCESSORS(value, Object)
7896 // [year]: caches year. Either undefined, smi, or NaN.
7897 DECL_ACCESSORS(year, Object)
7898 // [month]: caches month. Either undefined, smi, or NaN.
7899 DECL_ACCESSORS(month, Object)
7900 // [day]: caches day. Either undefined, smi, or NaN.
7901 DECL_ACCESSORS(day, Object)
7902 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7903 DECL_ACCESSORS(weekday, Object)
7904 // [hour]: caches hours. Either undefined, smi, or NaN.
7905 DECL_ACCESSORS(hour, Object)
7906 // [min]: caches minutes. Either undefined, smi, or NaN.
7907 DECL_ACCESSORS(min, Object)
7908 // [sec]: caches seconds. Either undefined, smi, or NaN.
7909 DECL_ACCESSORS(sec, Object)
7910 // [cache stamp]: sample of the date cache stamp at the
7911 // moment when chached fields were cached.
7912 DECL_ACCESSORS(cache_stamp, Object)
7914 DECLARE_CAST(JSDate)
7916 // Returns the date field with the specified index.
7917 // See FieldIndex for the list of date fields.
7918 static Object* GetField(Object* date, Smi* index);
7920 void SetValue(Object* value, bool is_value_nan);
7923 // Dispatched behavior.
7924 DECLARE_PRINTER(JSDate)
7925 DECLARE_VERIFIER(JSDate)
7927 // The order is important. It must be kept in sync with date macros
7938 kFirstUncachedField,
7939 kMillisecond = kFirstUncachedField,
7943 kYearUTC = kFirstUTCField,
7956 // Layout description.
7957 static const int kValueOffset = JSObject::kHeaderSize;
7958 static const int kYearOffset = kValueOffset + kPointerSize;
7959 static const int kMonthOffset = kYearOffset + kPointerSize;
7960 static const int kDayOffset = kMonthOffset + kPointerSize;
7961 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7962 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7963 static const int kMinOffset = kHourOffset + kPointerSize;
7964 static const int kSecOffset = kMinOffset + kPointerSize;
7965 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7966 static const int kSize = kCacheStampOffset + kPointerSize;
7969 inline Object* DoGetField(FieldIndex index);
7971 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7973 // Computes and caches the cacheable fields of the date.
7974 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7977 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7981 // Representation of message objects used for error reporting through
7982 // the API. The messages are formatted in JavaScript so this object is
7983 // a real JavaScript object. The information used for formatting the
7984 // error messages are not directly accessible from JavaScript to
7985 // prevent leaking information to user code called during error
7987 class JSMessageObject: public JSObject {
7989 // [type]: the type of error message.
7990 DECL_ACCESSORS(type, String)
7992 // [arguments]: the arguments for formatting the error message.
7993 DECL_ACCESSORS(arguments, JSArray)
7995 // [script]: the script from which the error message originated.
7996 DECL_ACCESSORS(script, Object)
7998 // [stack_frames]: an array of stack frames for this error object.
7999 DECL_ACCESSORS(stack_frames, Object)
8001 // [start_position]: the start position in the script for the error message.
8002 inline int start_position() const;
8003 inline void set_start_position(int value);
8005 // [end_position]: the end position in the script for the error message.
8006 inline int end_position() const;
8007 inline void set_end_position(int value);
8009 DECLARE_CAST(JSMessageObject)
8011 // Dispatched behavior.
8012 DECLARE_PRINTER(JSMessageObject)
8013 DECLARE_VERIFIER(JSMessageObject)
8015 // Layout description.
8016 static const int kTypeOffset = JSObject::kHeaderSize;
8017 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
8018 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
8019 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
8020 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
8021 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
8022 static const int kSize = kEndPositionOffset + kPointerSize;
8024 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
8025 kStackFramesOffset + kPointerSize,
8026 kSize> BodyDescriptor;
8030 // Regular expressions
8031 // The regular expression holds a single reference to a FixedArray in
8032 // the kDataOffset field.
8033 // The FixedArray contains the following data:
8034 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
8035 // - reference to the original source string
8036 // - reference to the original flag string
8037 // If it is an atom regexp
8038 // - a reference to a literal string to search for
8039 // If it is an irregexp regexp:
8040 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
8041 // used for tracking the last usage (used for code flushing).
8042 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
8043 // used for tracking the last usage (used for code flushing)..
8044 // - max number of registers used by irregexp implementations.
8045 // - number of capture registers (output values) of the regexp.
8046 class JSRegExp: public JSObject {
8049 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
8050 // ATOM: A simple string to match against using an indexOf operation.
8051 // IRREGEXP: Compiled with Irregexp.
8052 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
8053 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
8064 explicit Flags(uint32_t value) : value_(value) { }
8065 bool is_global() { return (value_ & GLOBAL) != 0; }
8066 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
8067 bool is_multiline() { return (value_ & MULTILINE) != 0; }
8068 bool is_sticky() { return (value_ & STICKY) != 0; }
8069 uint32_t value() { return value_; }
8074 DECL_ACCESSORS(data, Object)
8076 inline Type TypeTag();
8077 inline int CaptureCount();
8078 inline Flags GetFlags();
8079 inline String* Pattern();
8080 inline Object* DataAt(int index);
8081 // Set implementation data after the object has been prepared.
8082 inline void SetDataAt(int index, Object* value);
8084 static int code_index(bool is_latin1) {
8086 return kIrregexpLatin1CodeIndex;
8088 return kIrregexpUC16CodeIndex;
8092 static int saved_code_index(bool is_latin1) {
8094 return kIrregexpLatin1CodeSavedIndex;
8096 return kIrregexpUC16CodeSavedIndex;
8100 DECLARE_CAST(JSRegExp)
8102 // Dispatched behavior.
8103 DECLARE_VERIFIER(JSRegExp)
8105 static const int kDataOffset = JSObject::kHeaderSize;
8106 static const int kSize = kDataOffset + kPointerSize;
8108 // Indices in the data array.
8109 static const int kTagIndex = 0;
8110 static const int kSourceIndex = kTagIndex + 1;
8111 static const int kFlagsIndex = kSourceIndex + 1;
8112 static const int kDataIndex = kFlagsIndex + 1;
8113 // The data fields are used in different ways depending on the
8114 // value of the tag.
8115 // Atom regexps (literal strings).
8116 static const int kAtomPatternIndex = kDataIndex;
8118 static const int kAtomDataSize = kAtomPatternIndex + 1;
8120 // Irregexp compiled code or bytecode for Latin1. If compilation
8121 // fails, this fields hold an exception object that should be
8122 // thrown if the regexp is used again.
8123 static const int kIrregexpLatin1CodeIndex = kDataIndex;
8124 // Irregexp compiled code or bytecode for UC16. If compilation
8125 // fails, this fields hold an exception object that should be
8126 // thrown if the regexp is used again.
8127 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
8129 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
8130 // is a potential candidate for flushing.
8131 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
8132 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
8133 // a potential candidate for flushing.
8134 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
8136 // Maximal number of registers used by either Latin1 or UC16.
8137 // Only used to check that there is enough stack space
8138 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
8139 // Number of captures in the compiled regexp.
8140 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
8142 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
8144 // Offsets directly into the data fixed array.
8145 static const int kDataTagOffset =
8146 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
8147 static const int kDataOneByteCodeOffset =
8148 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
8149 static const int kDataUC16CodeOffset =
8150 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
8151 static const int kIrregexpCaptureCountOffset =
8152 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
8154 // In-object fields.
8155 static const int kSourceFieldIndex = 0;
8156 static const int kGlobalFieldIndex = 1;
8157 static const int kIgnoreCaseFieldIndex = 2;
8158 static const int kMultilineFieldIndex = 3;
8159 static const int kLastIndexFieldIndex = 4;
8160 static const int kInObjectFieldCount = 5;
8162 // The uninitialized value for a regexp code object.
8163 static const int kUninitializedValue = -1;
8165 // The compilation error value for the regexp code object. The real error
8166 // object is in the saved code field.
8167 static const int kCompilationErrorValue = -2;
8169 // When we store the sweep generation at which we moved the code from the
8170 // code index to the saved code index we mask it of to be in the [0:255]
8172 static const int kCodeAgeMask = 0xff;
8176 class CompilationCacheShape : public BaseShape<HashTableKey*> {
8178 static inline bool IsMatch(HashTableKey* key, Object* value) {
8179 return key->IsMatch(value);
8182 static inline uint32_t Hash(HashTableKey* key) {
8186 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8187 return key->HashForObject(object);
8190 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8192 static const int kPrefixSize = 0;
8193 static const int kEntrySize = 2;
8197 class CompilationCacheTable: public HashTable<CompilationCacheTable,
8198 CompilationCacheShape,
8201 // Find cached value for a string key, otherwise return null.
8202 Handle<Object> Lookup(Handle<String> src, Handle<Context> context);
8203 Handle<Object> LookupEval(Handle<String> src,
8204 Handle<SharedFunctionInfo> shared,
8205 StrictMode strict_mode, int scope_position);
8206 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
8207 static Handle<CompilationCacheTable> Put(
8208 Handle<CompilationCacheTable> cache, Handle<String> src,
8209 Handle<Context> context, Handle<Object> value);
8210 static Handle<CompilationCacheTable> PutEval(
8211 Handle<CompilationCacheTable> cache, Handle<String> src,
8212 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
8213 int scope_position);
8214 static Handle<CompilationCacheTable> PutRegExp(
8215 Handle<CompilationCacheTable> cache, Handle<String> src,
8216 JSRegExp::Flags flags, Handle<FixedArray> value);
8217 void Remove(Object* value);
8219 DECLARE_CAST(CompilationCacheTable)
8222 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8226 class CodeCache: public Struct {
8228 DECL_ACCESSORS(default_cache, FixedArray)
8229 DECL_ACCESSORS(normal_type_cache, Object)
8231 // Add the code object to the cache.
8233 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
8235 // Lookup code object in the cache. Returns code object if found and undefined
8237 Object* Lookup(Name* name, Code::Flags flags);
8239 // Get the internal index of a code object in the cache. Returns -1 if the
8240 // code object is not in that cache. This index can be used to later call
8241 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8243 int GetIndex(Object* name, Code* code);
8245 // Remove an object from the cache with the provided internal index.
8246 void RemoveByIndex(Object* name, Code* code, int index);
8248 DECLARE_CAST(CodeCache)
8250 // Dispatched behavior.
8251 DECLARE_PRINTER(CodeCache)
8252 DECLARE_VERIFIER(CodeCache)
8254 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8255 static const int kNormalTypeCacheOffset =
8256 kDefaultCacheOffset + kPointerSize;
8257 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8260 static void UpdateDefaultCache(
8261 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8262 static void UpdateNormalTypeCache(
8263 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8264 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8265 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8267 // Code cache layout of the default cache. Elements are alternating name and
8268 // code objects for non normal load/store/call IC's.
8269 static const int kCodeCacheEntrySize = 2;
8270 static const int kCodeCacheEntryNameOffset = 0;
8271 static const int kCodeCacheEntryCodeOffset = 1;
8273 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8277 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8279 static inline bool IsMatch(HashTableKey* key, Object* value) {
8280 return key->IsMatch(value);
8283 static inline uint32_t Hash(HashTableKey* key) {
8287 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8288 return key->HashForObject(object);
8291 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8293 static const int kPrefixSize = 0;
8294 static const int kEntrySize = 2;
8298 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8299 CodeCacheHashTableShape,
8302 Object* Lookup(Name* name, Code::Flags flags);
8303 static Handle<CodeCacheHashTable> Put(
8304 Handle<CodeCacheHashTable> table,
8308 int GetIndex(Name* name, Code::Flags flags);
8309 void RemoveByIndex(int index);
8311 DECLARE_CAST(CodeCacheHashTable)
8313 // Initial size of the fixed array backing the hash table.
8314 static const int kInitialSize = 64;
8317 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8321 class PolymorphicCodeCache: public Struct {
8323 DECL_ACCESSORS(cache, Object)
8325 static void Update(Handle<PolymorphicCodeCache> cache,
8326 MapHandleList* maps,
8331 // Returns an undefined value if the entry is not found.
8332 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8334 DECLARE_CAST(PolymorphicCodeCache)
8336 // Dispatched behavior.
8337 DECLARE_PRINTER(PolymorphicCodeCache)
8338 DECLARE_VERIFIER(PolymorphicCodeCache)
8340 static const int kCacheOffset = HeapObject::kHeaderSize;
8341 static const int kSize = kCacheOffset + kPointerSize;
8344 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8348 class PolymorphicCodeCacheHashTable
8349 : public HashTable<PolymorphicCodeCacheHashTable,
8350 CodeCacheHashTableShape,
8353 Object* Lookup(MapHandleList* maps, int code_kind);
8355 static Handle<PolymorphicCodeCacheHashTable> Put(
8356 Handle<PolymorphicCodeCacheHashTable> hash_table,
8357 MapHandleList* maps,
8361 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8363 static const int kInitialSize = 64;
8365 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8369 class TypeFeedbackInfo: public Struct {
8371 inline int ic_total_count();
8372 inline void set_ic_total_count(int count);
8374 inline int ic_with_type_info_count();
8375 inline void change_ic_with_type_info_count(int delta);
8377 inline int ic_generic_count();
8378 inline void change_ic_generic_count(int delta);
8380 inline void initialize_storage();
8382 inline void change_own_type_change_checksum();
8383 inline int own_type_change_checksum();
8385 inline void set_inlined_type_change_checksum(int checksum);
8386 inline bool matches_inlined_type_change_checksum(int checksum);
8389 DECLARE_CAST(TypeFeedbackInfo)
8391 // Dispatched behavior.
8392 DECLARE_PRINTER(TypeFeedbackInfo)
8393 DECLARE_VERIFIER(TypeFeedbackInfo)
8395 static const int kStorage1Offset = HeapObject::kHeaderSize;
8396 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8397 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8398 static const int kSize = kStorage3Offset + kPointerSize;
8401 static const int kTypeChangeChecksumBits = 7;
8403 class ICTotalCountField: public BitField<int, 0,
8404 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8405 class OwnTypeChangeChecksum: public BitField<int,
8406 kSmiValueSize - kTypeChangeChecksumBits,
8407 kTypeChangeChecksumBits> {}; // NOLINT
8408 class ICsWithTypeInfoCountField: public BitField<int, 0,
8409 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8410 class InlinedTypeChangeChecksum: public BitField<int,
8411 kSmiValueSize - kTypeChangeChecksumBits,
8412 kTypeChangeChecksumBits> {}; // NOLINT
8414 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8418 enum AllocationSiteMode {
8419 DONT_TRACK_ALLOCATION_SITE,
8420 TRACK_ALLOCATION_SITE,
8421 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8425 class AllocationSite: public Struct {
8427 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8428 static const double kPretenureRatio;
8429 static const int kPretenureMinimumCreated = 100;
8431 // Values for pretenure decision field.
8432 enum PretenureDecision {
8438 kLastPretenureDecisionValue = kZombie
8441 const char* PretenureDecisionName(PretenureDecision decision);
8443 DECL_ACCESSORS(transition_info, Object)
8444 // nested_site threads a list of sites that represent nested literals
8445 // walked in a particular order. So [[1, 2], 1, 2] will have one
8446 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8447 DECL_ACCESSORS(nested_site, Object)
8448 DECL_ACCESSORS(pretenure_data, Smi)
8449 DECL_ACCESSORS(pretenure_create_count, Smi)
8450 DECL_ACCESSORS(dependent_code, DependentCode)
8451 DECL_ACCESSORS(weak_next, Object)
8453 inline void Initialize();
8455 // This method is expensive, it should only be called for reporting.
8456 bool IsNestedSite();
8458 // transition_info bitfields, for constructed array transition info.
8459 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8460 class UnusedBits: public BitField<int, 15, 14> {};
8461 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8463 // Bitfields for pretenure_data
8464 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8465 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8466 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8467 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8469 // Increments the mementos found counter and returns true when the first
8470 // memento was found for a given allocation site.
8471 inline bool IncrementMementoFoundCount();
8473 inline void IncrementMementoCreateCount();
8475 PretenureFlag GetPretenureMode();
8477 void ResetPretenureDecision();
8479 PretenureDecision pretenure_decision() {
8480 int value = pretenure_data()->value();
8481 return PretenureDecisionBits::decode(value);
8484 void set_pretenure_decision(PretenureDecision decision) {
8485 int value = pretenure_data()->value();
8487 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8488 SKIP_WRITE_BARRIER);
8491 bool deopt_dependent_code() {
8492 int value = pretenure_data()->value();
8493 return DeoptDependentCodeBit::decode(value);
8496 void set_deopt_dependent_code(bool deopt) {
8497 int value = pretenure_data()->value();
8499 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8500 SKIP_WRITE_BARRIER);
8503 int memento_found_count() {
8504 int value = pretenure_data()->value();
8505 return MementoFoundCountBits::decode(value);
8508 inline void set_memento_found_count(int count);
8510 int memento_create_count() {
8511 return pretenure_create_count()->value();
8514 void set_memento_create_count(int count) {
8515 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8518 // The pretenuring decision is made during gc, and the zombie state allows
8519 // us to recognize when an allocation site is just being kept alive because
8520 // a later traversal of new space may discover AllocationMementos that point
8521 // to this AllocationSite.
8523 return pretenure_decision() == kZombie;
8526 bool IsMaybeTenure() {
8527 return pretenure_decision() == kMaybeTenure;
8530 inline void MarkZombie();
8532 inline bool MakePretenureDecision(PretenureDecision current_decision,
8534 bool maximum_size_scavenge);
8536 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8538 ElementsKind GetElementsKind() {
8539 DCHECK(!SitePointsToLiteral());
8540 int value = Smi::cast(transition_info())->value();
8541 return ElementsKindBits::decode(value);
8544 void SetElementsKind(ElementsKind kind) {
8545 int value = Smi::cast(transition_info())->value();
8546 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8547 SKIP_WRITE_BARRIER);
8550 bool CanInlineCall() {
8551 int value = Smi::cast(transition_info())->value();
8552 return DoNotInlineBit::decode(value) == 0;
8555 void SetDoNotInlineCall() {
8556 int value = Smi::cast(transition_info())->value();
8557 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8558 SKIP_WRITE_BARRIER);
8561 bool SitePointsToLiteral() {
8562 // If transition_info is a smi, then it represents an ElementsKind
8563 // for a constructed array. Otherwise, it must be a boilerplate
8564 // for an object or array literal.
8565 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8568 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8569 ElementsKind to_kind);
8576 static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8578 CompilationInfo* info);
8580 DECLARE_PRINTER(AllocationSite)
8581 DECLARE_VERIFIER(AllocationSite)
8583 DECLARE_CAST(AllocationSite)
8584 static inline AllocationSiteMode GetMode(
8585 ElementsKind boilerplate_elements_kind);
8586 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8587 static inline bool CanTrack(InstanceType type);
8589 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8590 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8591 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8592 static const int kPretenureCreateCountOffset =
8593 kPretenureDataOffset + kPointerSize;
8594 static const int kDependentCodeOffset =
8595 kPretenureCreateCountOffset + kPointerSize;
8596 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8597 static const int kSize = kWeakNextOffset + kPointerSize;
8599 // During mark compact we need to take special care for the dependent code
8601 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8602 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8604 // For other visitors, use the fixed body descriptor below.
8605 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8606 kDependentCodeOffset + kPointerSize,
8607 kSize> BodyDescriptor;
8610 inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8611 bool PretenuringDecisionMade() {
8612 return pretenure_decision() != kUndecided;
8615 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8619 class AllocationMemento: public Struct {
8621 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8622 static const int kSize = kAllocationSiteOffset + kPointerSize;
8624 DECL_ACCESSORS(allocation_site, Object)
8627 return allocation_site()->IsAllocationSite() &&
8628 !AllocationSite::cast(allocation_site())->IsZombie();
8630 AllocationSite* GetAllocationSite() {
8632 return AllocationSite::cast(allocation_site());
8635 DECLARE_PRINTER(AllocationMemento)
8636 DECLARE_VERIFIER(AllocationMemento)
8638 DECLARE_CAST(AllocationMemento)
8641 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8645 // Representation of a slow alias as part of a sloppy arguments objects.
8646 // For fast aliases (if HasSloppyArgumentsElements()):
8647 // - the parameter map contains an index into the context
8648 // - all attributes of the element have default values
8649 // For slow aliases (if HasDictionaryArgumentsElements()):
8650 // - the parameter map contains no fast alias mapping (i.e. the hole)
8651 // - this struct (in the slow backing store) contains an index into the context
8652 // - all attributes are available as part if the property details
8653 class AliasedArgumentsEntry: public Struct {
8655 inline int aliased_context_slot() const;
8656 inline void set_aliased_context_slot(int count);
8658 DECLARE_CAST(AliasedArgumentsEntry)
8660 // Dispatched behavior.
8661 DECLARE_PRINTER(AliasedArgumentsEntry)
8662 DECLARE_VERIFIER(AliasedArgumentsEntry)
8664 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8665 static const int kSize = kAliasedContextSlot + kPointerSize;
8668 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8672 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8673 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8676 class StringHasher {
8678 explicit inline StringHasher(int length, uint32_t seed);
8680 template <typename schar>
8681 static inline uint32_t HashSequentialString(const schar* chars,
8685 // Reads all the data, even for long strings and computes the utf16 length.
8686 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8688 int* utf16_length_out);
8690 // Calculated hash value for a string consisting of 1 to
8691 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8692 // value is represented decimal value.
8693 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8695 // No string is allowed to have a hash of zero. That value is reserved
8696 // for internal properties. If the hash calculation yields zero then we
8698 static const int kZeroHash = 27;
8700 // Reusable parts of the hashing algorithm.
8701 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8702 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8705 // Returns the value to store in the hash field of a string with
8706 // the given length and contents.
8707 uint32_t GetHashField();
8708 // Returns true if the hash of this string can be computed without
8709 // looking at the contents.
8710 inline bool has_trivial_hash();
8711 // Adds a block of characters to the hash.
8712 template<typename Char>
8713 inline void AddCharacters(const Char* chars, int len);
8716 // Add a character to the hash.
8717 inline void AddCharacter(uint16_t c);
8718 // Update index. Returns true if string is still an index.
8719 inline bool UpdateIndex(uint16_t c);
8722 uint32_t raw_running_hash_;
8723 uint32_t array_index_;
8724 bool is_array_index_;
8725 bool is_first_char_;
8726 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8730 class IteratingStringHasher : public StringHasher {
8732 static inline uint32_t Hash(String* string, uint32_t seed);
8733 inline void VisitOneByteString(const uint8_t* chars, int length);
8734 inline void VisitTwoByteString(const uint16_t* chars, int length);
8737 inline IteratingStringHasher(int len, uint32_t seed)
8738 : StringHasher(len, seed) {}
8739 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8743 // The characteristics of a string are stored in its map. Retrieving these
8744 // few bits of information is moderately expensive, involving two memory
8745 // loads where the second is dependent on the first. To improve efficiency
8746 // the shape of the string is given its own class so that it can be retrieved
8747 // once and used for several string operations. A StringShape is small enough
8748 // to be passed by value and is immutable, but be aware that flattening a
8749 // string can potentially alter its shape. Also be aware that a GC caused by
8750 // something else can alter the shape of a string due to ConsString
8751 // shortcutting. Keeping these restrictions in mind has proven to be error-
8752 // prone and so we no longer put StringShapes in variables unless there is a
8753 // concrete performance benefit at that particular point in the code.
8754 class StringShape BASE_EMBEDDED {
8756 inline explicit StringShape(const String* s);
8757 inline explicit StringShape(Map* s);
8758 inline explicit StringShape(InstanceType t);
8759 inline bool IsSequential();
8760 inline bool IsExternal();
8761 inline bool IsCons();
8762 inline bool IsSliced();
8763 inline bool IsIndirect();
8764 inline bool IsExternalOneByte();
8765 inline bool IsExternalTwoByte();
8766 inline bool IsSequentialOneByte();
8767 inline bool IsSequentialTwoByte();
8768 inline bool IsInternalized();
8769 inline StringRepresentationTag representation_tag();
8770 inline uint32_t encoding_tag();
8771 inline uint32_t full_representation_tag();
8772 inline uint32_t size_tag();
8774 inline uint32_t type() { return type_; }
8775 inline void invalidate() { valid_ = false; }
8776 inline bool valid() { return valid_; }
8778 inline void invalidate() { }
8784 inline void set_valid() { valid_ = true; }
8787 inline void set_valid() { }
8792 // The Name abstract class captures anything that can be used as a property
8793 // name, i.e., strings and symbols. All names store a hash value.
8794 class Name: public HeapObject {
8796 // Get and set the hash field of the name.
8797 inline uint32_t hash_field();
8798 inline void set_hash_field(uint32_t value);
8800 // Tells whether the hash code has been computed.
8801 inline bool HasHashCode();
8803 // Returns a hash value used for the property table
8804 inline uint32_t Hash();
8806 // Equality operations.
8807 inline bool Equals(Name* other);
8808 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8811 inline bool AsArrayIndex(uint32_t* index);
8813 // Whether name can only name own properties.
8814 inline bool IsOwn();
8818 DECLARE_PRINTER(Name)
8820 // Layout description.
8821 static const int kHashFieldOffset = HeapObject::kHeaderSize;
8822 static const int kSize = kHashFieldOffset + kPointerSize;
8824 // Mask constant for checking if a name has a computed hash code
8825 // and if it is a string that is an array index. The least significant bit
8826 // indicates whether a hash code has been computed. If the hash code has
8827 // been computed the 2nd bit tells whether the string can be used as an
8829 static const int kHashNotComputedMask = 1;
8830 static const int kIsNotArrayIndexMask = 1 << 1;
8831 static const int kNofHashBitFields = 2;
8833 // Shift constant retrieving hash code from hash field.
8834 static const int kHashShift = kNofHashBitFields;
8836 // Only these bits are relevant in the hash, since the top two are shifted
8838 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8840 // Array index strings this short can keep their index in the hash field.
8841 static const int kMaxCachedArrayIndexLength = 7;
8843 // For strings which are array indexes the hash value has the string length
8844 // mixed into the hash, mainly to avoid a hash value of zero which would be
8845 // the case for the string '0'. 24 bits are used for the array index value.
8846 static const int kArrayIndexValueBits = 24;
8847 static const int kArrayIndexLengthBits =
8848 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8850 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8852 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8853 kArrayIndexValueBits> {}; // NOLINT
8854 class ArrayIndexLengthBits : public BitField<unsigned int,
8855 kNofHashBitFields + kArrayIndexValueBits,
8856 kArrayIndexLengthBits> {}; // NOLINT
8858 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8859 // could use a mask to test if the length of string is less than or equal to
8860 // kMaxCachedArrayIndexLength.
8861 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8863 static const unsigned int kContainsCachedArrayIndexMask =
8864 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8865 << ArrayIndexLengthBits::kShift) |
8866 kIsNotArrayIndexMask;
8868 // Value of empty hash field indicating that the hash is not computed.
8869 static const int kEmptyHashField =
8870 kIsNotArrayIndexMask | kHashNotComputedMask;
8873 static inline bool IsHashFieldComputed(uint32_t field);
8876 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8881 class Symbol: public Name {
8883 // [name]: the print name of a symbol, or undefined if none.
8884 DECL_ACCESSORS(name, Object)
8886 DECL_ACCESSORS(flags, Smi)
8888 // [is_private]: whether this is a private symbol.
8889 DECL_BOOLEAN_ACCESSORS(is_private)
8891 // [is_own]: whether this is an own symbol, that is, only used to designate
8892 // own properties of objects.
8893 DECL_BOOLEAN_ACCESSORS(is_own)
8895 DECLARE_CAST(Symbol)
8897 // Dispatched behavior.
8898 DECLARE_PRINTER(Symbol)
8899 DECLARE_VERIFIER(Symbol)
8901 // Layout description.
8902 static const int kNameOffset = Name::kSize;
8903 static const int kFlagsOffset = kNameOffset + kPointerSize;
8904 static const int kSize = kFlagsOffset + kPointerSize;
8906 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8909 static const int kPrivateBit = 0;
8910 static const int kOwnBit = 1;
8912 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8918 // The String abstract class captures JavaScript string values:
8921 // 4.3.16 String Value
8922 // A string value is a member of the type String and is a finite
8923 // ordered sequence of zero or more 16-bit unsigned integer values.
8925 // All string values have a length field.
8926 class String: public Name {
8928 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8930 // Array index strings this short can keep their index in the hash field.
8931 static const int kMaxCachedArrayIndexLength = 7;
8933 // For strings which are array indexes the hash value has the string length
8934 // mixed into the hash, mainly to avoid a hash value of zero which would be
8935 // the case for the string '0'. 24 bits are used for the array index value.
8936 static const int kArrayIndexValueBits = 24;
8937 static const int kArrayIndexLengthBits =
8938 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8940 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8942 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8943 kArrayIndexValueBits> {}; // NOLINT
8944 class ArrayIndexLengthBits : public BitField<unsigned int,
8945 kNofHashBitFields + kArrayIndexValueBits,
8946 kArrayIndexLengthBits> {}; // NOLINT
8948 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8949 // could use a mask to test if the length of string is less than or equal to
8950 // kMaxCachedArrayIndexLength.
8951 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8953 static const unsigned int kContainsCachedArrayIndexMask =
8954 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8955 << ArrayIndexLengthBits::kShift) |
8956 kIsNotArrayIndexMask;
8958 // Representation of the flat content of a String.
8959 // A non-flat string doesn't have flat content.
8960 // A flat string has content that's encoded as a sequence of either
8961 // one-byte chars or two-byte UC16.
8962 // Returned by String::GetFlatContent().
8965 // Returns true if the string is flat and this structure contains content.
8966 bool IsFlat() { return state_ != NON_FLAT; }
8967 // Returns true if the structure contains one-byte content.
8968 bool IsOneByte() { return state_ == ONE_BYTE; }
8969 // Returns true if the structure contains two-byte content.
8970 bool IsTwoByte() { return state_ == TWO_BYTE; }
8972 // Return the one byte content of the string. Only use if IsOneByte()
8974 Vector<const uint8_t> ToOneByteVector() {
8975 DCHECK_EQ(ONE_BYTE, state_);
8976 return Vector<const uint8_t>(onebyte_start, length_);
8978 // Return the two-byte content of the string. Only use if IsTwoByte()
8980 Vector<const uc16> ToUC16Vector() {
8981 DCHECK_EQ(TWO_BYTE, state_);
8982 return Vector<const uc16>(twobyte_start, length_);
8986 DCHECK(i < length_);
8987 DCHECK(state_ != NON_FLAT);
8988 if (state_ == ONE_BYTE) return onebyte_start[i];
8989 return twobyte_start[i];
8993 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8995 // Constructors only used by String::GetFlatContent().
8996 explicit FlatContent(const uint8_t* start, int length)
8997 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8998 explicit FlatContent(const uc16* start, int length)
8999 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
9000 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
9003 const uint8_t* onebyte_start;
9004 const uc16* twobyte_start;
9009 friend class String;
9012 // Get and set the length of the string.
9013 inline int length() const;
9014 inline void set_length(int value);
9016 // Get and set the length of the string using acquire loads and release
9018 inline int synchronized_length() const;
9019 inline void synchronized_set_length(int value);
9021 // Returns whether this string has only one-byte chars, i.e. all of them can
9022 // be one-byte encoded. This might be the case even if the string is
9023 // two-byte. Such strings may appear when the embedder prefers
9024 // two-byte external representations even for one-byte data.
9025 inline bool IsOneByteRepresentation() const;
9026 inline bool IsTwoByteRepresentation() const;
9028 // Cons and slices have an encoding flag that may not represent the actual
9029 // encoding of the underlying string. This is taken into account here.
9030 // Requires: this->IsFlat()
9031 inline bool IsOneByteRepresentationUnderneath();
9032 inline bool IsTwoByteRepresentationUnderneath();
9034 // NOTE: this should be considered only a hint. False negatives are
9036 inline bool HasOnlyOneByteChars();
9038 // Get and set individual two byte chars in the string.
9039 inline void Set(int index, uint16_t value);
9040 // Get individual two byte char in the string. Repeated calls
9041 // to this method are not efficient unless the string is flat.
9042 INLINE(uint16_t Get(int index));
9044 // Flattens the string. Checks first inline to see if it is
9045 // necessary. Does nothing if the string is not a cons string.
9046 // Flattening allocates a sequential string with the same data as
9047 // the given string and mutates the cons string to a degenerate
9048 // form, where the first component is the new sequential string and
9049 // the second component is the empty string. If allocation fails,
9050 // this function returns a failure. If flattening succeeds, this
9051 // function returns the sequential string that is now the first
9052 // component of the cons string.
9054 // Degenerate cons strings are handled specially by the garbage
9055 // collector (see IsShortcutCandidate).
9057 static inline Handle<String> Flatten(Handle<String> string,
9058 PretenureFlag pretenure = NOT_TENURED);
9060 // Tries to return the content of a flat string as a structure holding either
9061 // a flat vector of char or of uc16.
9062 // If the string isn't flat, and therefore doesn't have flat content, the
9063 // returned structure will report so, and can't provide a vector of either
9065 FlatContent GetFlatContent();
9067 // Returns the parent of a sliced string or first part of a flat cons string.
9068 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
9069 inline String* GetUnderlying();
9071 // Mark the string as an undetectable object. It only applies to
9072 // one-byte and two-byte string types.
9073 bool MarkAsUndetectable();
9075 // String equality operations.
9076 inline bool Equals(String* other);
9077 inline static bool Equals(Handle<String> one, Handle<String> two);
9078 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
9079 bool IsOneByteEqualTo(Vector<const uint8_t> str);
9080 bool IsTwoByteEqualTo(Vector<const uc16> str);
9082 // Return a UTF8 representation of the string. The string is null
9083 // terminated but may optionally contain nulls. Length is returned
9084 // in length_output if length_output is not a null pointer The string
9085 // should be nearly flat, otherwise the performance of this method may
9086 // be very slow (quadratic in the length). Setting robustness_flag to
9087 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9088 // handles unexpected data without causing assert failures and it does not
9089 // do any heap allocations. This is useful when printing stack traces.
9090 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
9091 RobustnessFlag robustness_flag,
9094 int* length_output = 0);
9095 SmartArrayPointer<char> ToCString(
9096 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
9097 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
9098 int* length_output = 0);
9100 // Return a 16 bit Unicode representation of the string.
9101 // The string should be nearly flat, otherwise the performance of
9102 // of this method may be very bad. Setting robustness_flag to
9103 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
9104 // handles unexpected data without causing assert failures and it does not
9105 // do any heap allocations. This is useful when printing stack traces.
9106 SmartArrayPointer<uc16> ToWideCString(
9107 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
9109 bool ComputeArrayIndex(uint32_t* index);
9112 bool MakeExternal(v8::String::ExternalStringResource* resource);
9113 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
9116 inline bool AsArrayIndex(uint32_t* index);
9118 DECLARE_CAST(String)
9120 void PrintOn(FILE* out);
9122 // For use during stack traces. Performs rudimentary sanity check.
9125 // Dispatched behavior.
9126 void StringShortPrint(StringStream* accumulator);
9127 void PrintUC16(OStream& os, int start = 0, int end = -1); // NOLINT
9129 char* ToAsciiArray();
9131 DECLARE_PRINTER(String)
9132 DECLARE_VERIFIER(String)
9134 inline bool IsFlat();
9136 // Layout description.
9137 static const int kLengthOffset = Name::kSize;
9138 static const int kSize = kLengthOffset + kPointerSize;
9140 // Maximum number of characters to consider when trying to convert a string
9141 // value into an array index.
9142 static const int kMaxArrayIndexSize = 10;
9143 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
9146 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
9147 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
9148 static const int kMaxUtf16CodeUnit = 0xffff;
9149 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
9151 // Value of hash field containing computed hash equal to zero.
9152 static const int kEmptyStringHash = kIsNotArrayIndexMask;
9154 // Maximal string length.
9155 static const int kMaxLength = (1 << 28) - 16;
9157 // Max length for computing hash. For strings longer than this limit the
9158 // string length is used as the hash value.
9159 static const int kMaxHashCalcLength = 16383;
9161 // Limit for truncation in short printing.
9162 static const int kMaxShortPrintLength = 1024;
9164 // Support for regular expressions.
9165 const uc16* GetTwoByteData(unsigned start);
9167 // Helper function for flattening strings.
9168 template <typename sinkchar>
9169 static void WriteToFlat(String* source,
9174 // The return value may point to the first aligned word containing the first
9175 // non-one-byte character, rather than directly to the non-one-byte character.
9176 // If the return value is >= the passed length, the entire string was
9178 static inline int NonAsciiStart(const char* chars, int length) {
9179 const char* start = chars;
9180 const char* limit = chars + length;
9182 if (length >= kIntptrSize) {
9183 // Check unaligned bytes.
9184 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
9185 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9186 return static_cast<int>(chars - start);
9190 // Check aligned words.
9191 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9192 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9193 while (chars + sizeof(uintptr_t) <= limit) {
9194 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
9195 return static_cast<int>(chars - start);
9197 chars += sizeof(uintptr_t);
9200 // Check remaining unaligned bytes.
9201 while (chars < limit) {
9202 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9203 return static_cast<int>(chars - start);
9208 return static_cast<int>(chars - start);
9211 static inline bool IsAscii(const char* chars, int length) {
9212 return NonAsciiStart(chars, length) >= length;
9215 static inline bool IsAscii(const uint8_t* chars, int length) {
9217 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9220 static inline int NonOneByteStart(const uc16* chars, int length) {
9221 const uc16* limit = chars + length;
9222 const uc16* start = chars;
9223 while (chars < limit) {
9224 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9227 return static_cast<int>(chars - start);
9230 static inline bool IsOneByte(const uc16* chars, int length) {
9231 return NonOneByteStart(chars, length) >= length;
9234 template<class Visitor>
9235 static inline ConsString* VisitFlat(Visitor* visitor,
9239 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9240 bool include_ending_line);
9242 // Use the hash field to forward to the canonical internalized string
9243 // when deserializing an internalized string.
9244 inline void SetForwardedInternalizedString(String* string);
9245 inline String* GetForwardedInternalizedString();
9249 friend class StringTableInsertionKey;
9251 static Handle<String> SlowFlatten(Handle<ConsString> cons,
9252 PretenureFlag tenure);
9254 // Slow case of String::Equals. This implementation works on any strings
9255 // but it is most efficient on strings that are almost flat.
9256 bool SlowEquals(String* other);
9258 static bool SlowEquals(Handle<String> one, Handle<String> two);
9260 // Slow case of AsArrayIndex.
9261 bool SlowAsArrayIndex(uint32_t* index);
9263 // Compute and set the hash code.
9264 uint32_t ComputeAndSetHash();
9266 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9270 // The SeqString abstract class captures sequential string values.
9271 class SeqString: public String {
9273 DECLARE_CAST(SeqString)
9275 // Layout description.
9276 static const int kHeaderSize = String::kSize;
9278 // Truncate the string in-place if possible and return the result.
9279 // In case of new_length == 0, the empty string is returned without
9280 // truncating the original string.
9281 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9284 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9288 // The OneByteString class captures sequential one-byte string objects.
9289 // Each character in the OneByteString is an one-byte character.
9290 class SeqOneByteString: public SeqString {
9292 static const bool kHasOneByteEncoding = true;
9294 // Dispatched behavior.
9295 inline uint16_t SeqOneByteStringGet(int index);
9296 inline void SeqOneByteStringSet(int index, uint16_t value);
9298 // Get the address of the characters in this string.
9299 inline Address GetCharsAddress();
9301 inline uint8_t* GetChars();
9303 DECLARE_CAST(SeqOneByteString)
9305 // Garbage collection support. This method is called by the
9306 // garbage collector to compute the actual size of an OneByteString
9308 inline int SeqOneByteStringSize(InstanceType instance_type);
9310 // Computes the size for an OneByteString instance of a given length.
9311 static int SizeFor(int length) {
9312 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9315 // Maximal memory usage for a single sequential one-byte string.
9316 static const int kMaxSize = 512 * MB - 1;
9317 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9320 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9324 // The TwoByteString class captures sequential unicode string objects.
9325 // Each character in the TwoByteString is a two-byte uint16_t.
9326 class SeqTwoByteString: public SeqString {
9328 static const bool kHasOneByteEncoding = false;
9330 // Dispatched behavior.
9331 inline uint16_t SeqTwoByteStringGet(int index);
9332 inline void SeqTwoByteStringSet(int index, uint16_t value);
9334 // Get the address of the characters in this string.
9335 inline Address GetCharsAddress();
9337 inline uc16* GetChars();
9340 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9342 DECLARE_CAST(SeqTwoByteString)
9344 // Garbage collection support. This method is called by the
9345 // garbage collector to compute the actual size of a TwoByteString
9347 inline int SeqTwoByteStringSize(InstanceType instance_type);
9349 // Computes the size for a TwoByteString instance of a given length.
9350 static int SizeFor(int length) {
9351 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9354 // Maximal memory usage for a single sequential two-byte string.
9355 static const int kMaxSize = 512 * MB - 1;
9356 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9357 String::kMaxLength);
9360 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9364 // The ConsString class describes string values built by using the
9365 // addition operator on strings. A ConsString is a pair where the
9366 // first and second components are pointers to other string values.
9367 // One or both components of a ConsString can be pointers to other
9368 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9369 // are non-ConsString string values. The string value represented by
9370 // a ConsString can be obtained by concatenating the leaf string
9371 // values in a left-to-right depth-first traversal of the tree.
9372 class ConsString: public String {
9374 // First string of the cons cell.
9375 inline String* first();
9376 // Doesn't check that the result is a string, even in debug mode. This is
9377 // useful during GC where the mark bits confuse the checks.
9378 inline Object* unchecked_first();
9379 inline void set_first(String* first,
9380 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9382 // Second string of the cons cell.
9383 inline String* second();
9384 // Doesn't check that the result is a string, even in debug mode. This is
9385 // useful during GC where the mark bits confuse the checks.
9386 inline Object* unchecked_second();
9387 inline void set_second(String* second,
9388 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9390 // Dispatched behavior.
9391 uint16_t ConsStringGet(int index);
9393 DECLARE_CAST(ConsString)
9395 // Layout description.
9396 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9397 static const int kSecondOffset = kFirstOffset + kPointerSize;
9398 static const int kSize = kSecondOffset + kPointerSize;
9400 // Minimum length for a cons string.
9401 static const int kMinLength = 13;
9403 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9406 DECLARE_VERIFIER(ConsString)
9409 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9413 // The Sliced String class describes strings that are substrings of another
9414 // sequential string. The motivation is to save time and memory when creating
9415 // a substring. A Sliced String is described as a pointer to the parent,
9416 // the offset from the start of the parent string and the length. Using
9417 // a Sliced String therefore requires unpacking of the parent string and
9418 // adding the offset to the start address. A substring of a Sliced String
9419 // are not nested since the double indirection is simplified when creating
9420 // such a substring.
9421 // Currently missing features are:
9422 // - handling externalized parent strings
9423 // - external strings as parent
9424 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9425 class SlicedString: public String {
9427 inline String* parent();
9428 inline void set_parent(String* parent,
9429 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9430 inline int offset() const;
9431 inline void set_offset(int offset);
9433 // Dispatched behavior.
9434 uint16_t SlicedStringGet(int index);
9436 DECLARE_CAST(SlicedString)
9438 // Layout description.
9439 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9440 static const int kOffsetOffset = kParentOffset + kPointerSize;
9441 static const int kSize = kOffsetOffset + kPointerSize;
9443 // Minimum length for a sliced string.
9444 static const int kMinLength = 13;
9446 typedef FixedBodyDescriptor<kParentOffset,
9447 kOffsetOffset + kPointerSize, kSize>
9450 DECLARE_VERIFIER(SlicedString)
9453 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9457 // The ExternalString class describes string values that are backed by
9458 // a string resource that lies outside the V8 heap. ExternalStrings
9459 // consist of the length field common to all strings, a pointer to the
9460 // external resource. It is important to ensure (externally) that the
9461 // resource is not deallocated while the ExternalString is live in the
9464 // The API expects that all ExternalStrings are created through the
9465 // API. Therefore, ExternalStrings should not be used internally.
9466 class ExternalString: public String {
9468 DECLARE_CAST(ExternalString)
9470 // Layout description.
9471 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9472 static const int kShortSize = kResourceOffset + kPointerSize;
9473 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9474 static const int kSize = kResourceDataOffset + kPointerSize;
9476 static const int kMaxShortLength =
9477 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9479 // Return whether external string is short (data pointer is not cached).
9480 inline bool is_short();
9482 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9485 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9489 // The ExternalOneByteString class is an external string backed by an
9491 class ExternalOneByteString : public ExternalString {
9493 static const bool kHasOneByteEncoding = true;
9495 typedef v8::String::ExternalOneByteStringResource Resource;
9497 // The underlying resource.
9498 inline const Resource* resource();
9499 inline void set_resource(const Resource* buffer);
9501 // Update the pointer cache to the external character array.
9502 // The cached pointer is always valid, as the external character array does =
9503 // not move during lifetime. Deserialization is the only exception, after
9504 // which the pointer cache has to be refreshed.
9505 inline void update_data_cache();
9507 inline const uint8_t* GetChars();
9509 // Dispatched behavior.
9510 inline uint16_t ExternalOneByteStringGet(int index);
9512 DECLARE_CAST(ExternalOneByteString)
9514 // Garbage collection support.
9515 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9517 template <typename StaticVisitor>
9518 inline void ExternalOneByteStringIterateBody();
9521 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9525 // The ExternalTwoByteString class is an external string backed by a UTF-16
9527 class ExternalTwoByteString: public ExternalString {
9529 static const bool kHasOneByteEncoding = false;
9531 typedef v8::String::ExternalStringResource Resource;
9533 // The underlying string resource.
9534 inline const Resource* resource();
9535 inline void set_resource(const Resource* buffer);
9537 // Update the pointer cache to the external character array.
9538 // The cached pointer is always valid, as the external character array does =
9539 // not move during lifetime. Deserialization is the only exception, after
9540 // which the pointer cache has to be refreshed.
9541 inline void update_data_cache();
9543 inline const uint16_t* GetChars();
9545 // Dispatched behavior.
9546 inline uint16_t ExternalTwoByteStringGet(int index);
9549 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9551 DECLARE_CAST(ExternalTwoByteString)
9553 // Garbage collection support.
9554 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9556 template<typename StaticVisitor>
9557 inline void ExternalTwoByteStringIterateBody();
9560 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9564 // Utility superclass for stack-allocated objects that must be updated
9565 // on gc. It provides two ways for the gc to update instances, either
9566 // iterating or updating after gc.
9567 class Relocatable BASE_EMBEDDED {
9569 explicit inline Relocatable(Isolate* isolate);
9570 inline virtual ~Relocatable();
9571 virtual void IterateInstance(ObjectVisitor* v) { }
9572 virtual void PostGarbageCollection() { }
9574 static void PostGarbageCollectionProcessing(Isolate* isolate);
9575 static int ArchiveSpacePerThread();
9576 static char* ArchiveState(Isolate* isolate, char* to);
9577 static char* RestoreState(Isolate* isolate, char* from);
9578 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9579 static void Iterate(ObjectVisitor* v, Relocatable* top);
9580 static char* Iterate(ObjectVisitor* v, char* t);
9588 // A flat string reader provides random access to the contents of a
9589 // string independent of the character width of the string. The handle
9590 // must be valid as long as the reader is being used.
9591 class FlatStringReader : public Relocatable {
9593 FlatStringReader(Isolate* isolate, Handle<String> str);
9594 FlatStringReader(Isolate* isolate, Vector<const char> input);
9595 void PostGarbageCollection();
9596 inline uc32 Get(int index);
9597 int length() { return length_; }
9606 // A ConsStringOp that returns null.
9607 // Useful when the operation to apply on a ConsString
9608 // requires an expensive data structure.
9609 class ConsStringNullOp {
9611 inline ConsStringNullOp() {}
9612 static inline String* Operate(String*, unsigned*, int32_t*, unsigned*);
9614 DISALLOW_COPY_AND_ASSIGN(ConsStringNullOp);
9618 // This maintains an off-stack representation of the stack frames required
9619 // to traverse a ConsString, allowing an entirely iterative and restartable
9620 // traversal of the entire string
9621 class ConsStringIteratorOp {
9623 inline ConsStringIteratorOp() {}
9624 inline explicit ConsStringIteratorOp(ConsString* cons_string,
9626 Reset(cons_string, offset);
9628 inline void Reset(ConsString* cons_string, int offset = 0) {
9630 // Next will always return NULL.
9631 if (cons_string == NULL) return;
9632 Initialize(cons_string, offset);
9634 // Returns NULL when complete.
9635 inline String* Next(int* offset_out) {
9637 if (depth_ == 0) return NULL;
9638 return Continue(offset_out);
9642 static const int kStackSize = 32;
9643 // Use a mask instead of doing modulo operations for stack wrapping.
9644 static const int kDepthMask = kStackSize-1;
9645 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9646 static inline int OffsetForDepth(int depth);
9648 inline void PushLeft(ConsString* string);
9649 inline void PushRight(ConsString* string);
9650 inline void AdjustMaximumDepth();
9652 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9653 void Initialize(ConsString* cons_string, int offset);
9654 String* Continue(int* offset_out);
9655 String* NextLeaf(bool* blew_stack);
9656 String* Search(int* offset_out);
9658 // Stack must always contain only frames for which right traversal
9659 // has not yet been performed.
9660 ConsString* frames_[kStackSize];
9665 DISALLOW_COPY_AND_ASSIGN(ConsStringIteratorOp);
9669 class StringCharacterStream {
9671 inline StringCharacterStream(String* string,
9672 ConsStringIteratorOp* op,
9674 inline uint16_t GetNext();
9675 inline bool HasMore();
9676 inline void Reset(String* string, int offset = 0);
9677 inline void VisitOneByteString(const uint8_t* chars, int length);
9678 inline void VisitTwoByteString(const uint16_t* chars, int length);
9683 const uint8_t* buffer8_;
9684 const uint16_t* buffer16_;
9686 const uint8_t* end_;
9687 ConsStringIteratorOp* op_;
9688 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9692 template <typename T>
9693 class VectorIterator {
9695 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9696 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9697 T GetNext() { return data_[index_++]; }
9698 bool has_more() { return index_ < data_.length(); }
9700 Vector<const T> data_;
9705 // The Oddball describes objects null, undefined, true, and false.
9706 class Oddball: public HeapObject {
9708 // [to_string]: Cached to_string computed at startup.
9709 DECL_ACCESSORS(to_string, String)
9711 // [to_number]: Cached to_number computed at startup.
9712 DECL_ACCESSORS(to_number, Object)
9714 inline byte kind() const;
9715 inline void set_kind(byte kind);
9717 DECLARE_CAST(Oddball)
9719 // Dispatched behavior.
9720 DECLARE_VERIFIER(Oddball)
9722 // Initialize the fields.
9723 static void Initialize(Isolate* isolate,
9724 Handle<Oddball> oddball,
9725 const char* to_string,
9726 Handle<Object> to_number,
9729 // Layout description.
9730 static const int kToStringOffset = HeapObject::kHeaderSize;
9731 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9732 static const int kKindOffset = kToNumberOffset + kPointerSize;
9733 static const int kSize = kKindOffset + kPointerSize;
9735 static const byte kFalse = 0;
9736 static const byte kTrue = 1;
9737 static const byte kNotBooleanMask = ~1;
9738 static const byte kTheHole = 2;
9739 static const byte kNull = 3;
9740 static const byte kArgumentMarker = 4;
9741 static const byte kUndefined = 5;
9742 static const byte kUninitialized = 6;
9743 static const byte kOther = 7;
9744 static const byte kException = 8;
9746 typedef FixedBodyDescriptor<kToStringOffset,
9747 kToNumberOffset + kPointerSize,
9748 kSize> BodyDescriptor;
9750 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9751 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9752 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9755 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9759 class Cell: public HeapObject {
9761 // [value]: value of the global property.
9762 DECL_ACCESSORS(value, Object)
9766 static inline Cell* FromValueAddress(Address value) {
9767 Object* result = FromAddress(value - kValueOffset);
9768 DCHECK(result->IsCell() || result->IsPropertyCell());
9769 return static_cast<Cell*>(result);
9772 inline Address ValueAddress() {
9773 return address() + kValueOffset;
9776 // Dispatched behavior.
9777 DECLARE_PRINTER(Cell)
9778 DECLARE_VERIFIER(Cell)
9780 // Layout description.
9781 static const int kValueOffset = HeapObject::kHeaderSize;
9782 static const int kSize = kValueOffset + kPointerSize;
9784 typedef FixedBodyDescriptor<kValueOffset,
9785 kValueOffset + kPointerSize,
9786 kSize> BodyDescriptor;
9789 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9793 class PropertyCell: public Cell {
9795 // [type]: type of the global property.
9797 void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9799 // [dependent_code]: dependent code that depends on the type of the global
9801 DECL_ACCESSORS(dependent_code, DependentCode)
9803 // Sets the value of the cell and updates the type field to be the union
9804 // of the cell's current type and the value's type. If the change causes
9805 // a change of the type of the cell's contents, code dependent on the cell
9806 // will be deoptimized.
9807 static void SetValueInferType(Handle<PropertyCell> cell,
9808 Handle<Object> value);
9810 // Computes the new type of the cell's contents for the given value, but
9811 // without actually modifying the 'type' field.
9812 static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9813 Handle<Object> value);
9815 static void AddDependentCompilationInfo(Handle<PropertyCell> cell,
9816 CompilationInfo* info);
9818 DECLARE_CAST(PropertyCell)
9820 inline Address TypeAddress() {
9821 return address() + kTypeOffset;
9824 // Dispatched behavior.
9825 DECLARE_PRINTER(PropertyCell)
9826 DECLARE_VERIFIER(PropertyCell)
9828 // Layout description.
9829 static const int kTypeOffset = kValueOffset + kPointerSize;
9830 static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9831 static const int kSize = kDependentCodeOffset + kPointerSize;
9833 static const int kPointerFieldsBeginOffset = kValueOffset;
9834 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9836 typedef FixedBodyDescriptor<kValueOffset,
9838 kSize> BodyDescriptor;
9841 DECL_ACCESSORS(type_raw, Object)
9842 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9846 // The JSProxy describes EcmaScript Harmony proxies
9847 class JSProxy: public JSReceiver {
9849 // [handler]: The handler property.
9850 DECL_ACCESSORS(handler, Object)
9852 // [hash]: The hash code property (undefined if not initialized yet).
9853 DECL_ACCESSORS(hash, Object)
9855 DECLARE_CAST(JSProxy)
9857 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9858 Handle<JSProxy> proxy,
9859 Handle<Object> receiver,
9861 MUST_USE_RESULT static inline MaybeHandle<Object> GetElementWithHandler(
9862 Handle<JSProxy> proxy,
9863 Handle<Object> receiver,
9866 // If the handler defines an accessor property with a setter, invoke it.
9867 // If it defines an accessor property without a setter, or a data property
9868 // that is read-only, throw. In all these cases set '*done' to true,
9869 // otherwise set it to false.
9871 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9872 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9873 Handle<Object> value, StrictMode strict_mode, bool* done);
9875 MUST_USE_RESULT static Maybe<PropertyAttributes>
9876 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9877 Handle<Object> receiver,
9879 MUST_USE_RESULT static Maybe<PropertyAttributes>
9880 GetElementAttributeWithHandler(Handle<JSProxy> proxy,
9881 Handle<JSReceiver> receiver,
9883 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9884 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9885 Handle<Object> value, StrictMode strict_mode);
9887 // Turn the proxy into an (empty) JSObject.
9888 static void Fix(Handle<JSProxy> proxy);
9890 // Initializes the body after the handler slot.
9891 inline void InitializeBody(int object_size, Object* value);
9893 // Invoke a trap by name. If the trap does not exist on this's handler,
9894 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9895 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9896 Handle<JSProxy> proxy,
9898 Handle<Object> derived_trap,
9900 Handle<Object> args[]);
9902 // Dispatched behavior.
9903 DECLARE_PRINTER(JSProxy)
9904 DECLARE_VERIFIER(JSProxy)
9906 // Layout description. We add padding so that a proxy has the same
9907 // size as a virgin JSObject. This is essential for becoming a JSObject
9909 static const int kHandlerOffset = HeapObject::kHeaderSize;
9910 static const int kHashOffset = kHandlerOffset + kPointerSize;
9911 static const int kPaddingOffset = kHashOffset + kPointerSize;
9912 static const int kSize = JSObject::kHeaderSize;
9913 static const int kHeaderSize = kPaddingOffset;
9914 static const int kPaddingSize = kSize - kPaddingOffset;
9916 STATIC_ASSERT(kPaddingSize >= 0);
9918 typedef FixedBodyDescriptor<kHandlerOffset,
9920 kSize> BodyDescriptor;
9923 friend class JSReceiver;
9925 MUST_USE_RESULT static inline MaybeHandle<Object> SetElementWithHandler(
9926 Handle<JSProxy> proxy,
9927 Handle<JSReceiver> receiver,
9929 Handle<Object> value,
9930 StrictMode strict_mode);
9932 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9933 Handle<JSProxy> proxy, Handle<Name> name);
9934 MUST_USE_RESULT static inline Maybe<bool> HasElementWithHandler(
9935 Handle<JSProxy> proxy, uint32_t index);
9937 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9938 Handle<JSProxy> proxy,
9941 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithHandler(
9942 Handle<JSProxy> proxy,
9946 MUST_USE_RESULT Object* GetIdentityHash();
9948 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9950 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9954 class JSFunctionProxy: public JSProxy {
9956 // [call_trap]: The call trap.
9957 DECL_ACCESSORS(call_trap, Object)
9959 // [construct_trap]: The construct trap.
9960 DECL_ACCESSORS(construct_trap, Object)
9962 DECLARE_CAST(JSFunctionProxy)
9964 // Dispatched behavior.
9965 DECLARE_PRINTER(JSFunctionProxy)
9966 DECLARE_VERIFIER(JSFunctionProxy)
9968 // Layout description.
9969 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9970 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9971 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9972 static const int kSize = JSFunction::kSize;
9973 static const int kPaddingSize = kSize - kPaddingOffset;
9975 STATIC_ASSERT(kPaddingSize >= 0);
9977 typedef FixedBodyDescriptor<kHandlerOffset,
9978 kConstructTrapOffset + kPointerSize,
9979 kSize> BodyDescriptor;
9982 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9986 class JSCollection : public JSObject {
9988 // [table]: the backing hash table
9989 DECL_ACCESSORS(table, Object)
9991 static const int kTableOffset = JSObject::kHeaderSize;
9992 static const int kSize = kTableOffset + kPointerSize;
9995 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9999 // The JSSet describes EcmaScript Harmony sets
10000 class JSSet : public JSCollection {
10002 DECLARE_CAST(JSSet)
10004 // Dispatched behavior.
10005 DECLARE_PRINTER(JSSet)
10006 DECLARE_VERIFIER(JSSet)
10009 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
10013 // The JSMap describes EcmaScript Harmony maps
10014 class JSMap : public JSCollection {
10016 DECLARE_CAST(JSMap)
10018 // Dispatched behavior.
10019 DECLARE_PRINTER(JSMap)
10020 DECLARE_VERIFIER(JSMap)
10023 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
10027 // OrderedHashTableIterator is an iterator that iterates over the keys and
10028 // values of an OrderedHashTable.
10030 // The iterator has a reference to the underlying OrderedHashTable data,
10031 // [table], as well as the current [index] the iterator is at.
10033 // When the OrderedHashTable is rehashed it adds a reference from the old table
10034 // to the new table as well as storing enough data about the changes so that the
10035 // iterator [index] can be adjusted accordingly.
10037 // When the [Next] result from the iterator is requested, the iterator checks if
10038 // there is a newer table that it needs to transition to.
10039 template<class Derived, class TableType>
10040 class OrderedHashTableIterator: public JSObject {
10042 // [table]: the backing hash table mapping keys to values.
10043 DECL_ACCESSORS(table, Object)
10045 // [index]: The index into the data table.
10046 DECL_ACCESSORS(index, Object)
10048 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
10049 DECL_ACCESSORS(kind, Object)
10051 #ifdef OBJECT_PRINT
10052 void OrderedHashTableIteratorPrint(OStream& os); // NOLINT
10055 static const int kTableOffset = JSObject::kHeaderSize;
10056 static const int kIndexOffset = kTableOffset + kPointerSize;
10057 static const int kKindOffset = kIndexOffset + kPointerSize;
10058 static const int kSize = kKindOffset + kPointerSize;
10066 // Whether the iterator has more elements. This needs to be called before
10067 // calling |CurrentKey| and/or |CurrentValue|.
10070 // Move the index forward one.
10072 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
10075 // Populates the array with the next key and value and then moves the iterator
10077 // This returns the |kind| or 0 if the iterator is already at the end.
10078 Smi* Next(JSArray* value_array);
10080 // Returns the current key of the iterator. This should only be called when
10081 // |HasMore| returns true.
10082 inline Object* CurrentKey();
10085 // Transitions the iterator to the non obsolete backing store. This is a NOP
10086 // if the [table] is not obsolete.
10089 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
10093 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
10096 // Dispatched behavior.
10097 DECLARE_PRINTER(JSSetIterator)
10098 DECLARE_VERIFIER(JSSetIterator)
10100 DECLARE_CAST(JSSetIterator)
10102 // Called by |Next| to populate the array. This allows the subclasses to
10103 // populate the array differently.
10104 inline void PopulateValueArray(FixedArray* array);
10107 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
10111 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
10114 // Dispatched behavior.
10115 DECLARE_PRINTER(JSMapIterator)
10116 DECLARE_VERIFIER(JSMapIterator)
10118 DECLARE_CAST(JSMapIterator)
10120 // Called by |Next| to populate the array. This allows the subclasses to
10121 // populate the array differently.
10122 inline void PopulateValueArray(FixedArray* array);
10125 // Returns the current value of the iterator. This should only be called when
10126 // |HasMore| returns true.
10127 inline Object* CurrentValue();
10129 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
10133 // Base class for both JSWeakMap and JSWeakSet
10134 class JSWeakCollection: public JSObject {
10136 // [table]: the backing hash table mapping keys to values.
10137 DECL_ACCESSORS(table, Object)
10139 // [next]: linked list of encountered weak maps during GC.
10140 DECL_ACCESSORS(next, Object)
10142 static const int kTableOffset = JSObject::kHeaderSize;
10143 static const int kNextOffset = kTableOffset + kPointerSize;
10144 static const int kSize = kNextOffset + kPointerSize;
10147 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
10151 // The JSWeakMap describes EcmaScript Harmony weak maps
10152 class JSWeakMap: public JSWeakCollection {
10154 DECLARE_CAST(JSWeakMap)
10156 // Dispatched behavior.
10157 DECLARE_PRINTER(JSWeakMap)
10158 DECLARE_VERIFIER(JSWeakMap)
10161 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
10165 // The JSWeakSet describes EcmaScript Harmony weak sets
10166 class JSWeakSet: public JSWeakCollection {
10168 DECLARE_CAST(JSWeakSet)
10170 // Dispatched behavior.
10171 DECLARE_PRINTER(JSWeakSet)
10172 DECLARE_VERIFIER(JSWeakSet)
10175 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
10179 class JSArrayBuffer: public JSObject {
10181 // [backing_store]: backing memory for this array
10182 DECL_ACCESSORS(backing_store, void)
10184 // [byte_length]: length in bytes
10185 DECL_ACCESSORS(byte_length, Object)
10188 DECL_ACCESSORS(flag, Smi)
10190 inline bool is_external();
10191 inline void set_is_external(bool value);
10193 inline bool should_be_freed();
10194 inline void set_should_be_freed(bool value);
10196 // [weak_next]: linked list of array buffers.
10197 DECL_ACCESSORS(weak_next, Object)
10199 // [weak_first_array]: weak linked list of views.
10200 DECL_ACCESSORS(weak_first_view, Object)
10202 DECLARE_CAST(JSArrayBuffer)
10204 // Neutering. Only neuters the buffer, not associated typed arrays.
10207 // Dispatched behavior.
10208 DECLARE_PRINTER(JSArrayBuffer)
10209 DECLARE_VERIFIER(JSArrayBuffer)
10211 static const int kBackingStoreOffset = JSObject::kHeaderSize;
10212 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10213 static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10214 static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10215 static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10216 static const int kSize = kWeakFirstViewOffset + kPointerSize;
10218 static const int kSizeWithInternalFields =
10219 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10222 // Bit position in a flag
10223 static const int kIsExternalBit = 0;
10224 static const int kShouldBeFreed = 1;
10226 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10230 class JSArrayBufferView: public JSObject {
10232 // [buffer]: ArrayBuffer that this typed array views.
10233 DECL_ACCESSORS(buffer, Object)
10235 // [byte_length]: offset of typed array in bytes.
10236 DECL_ACCESSORS(byte_offset, Object)
10238 // [byte_length]: length of typed array in bytes.
10239 DECL_ACCESSORS(byte_length, Object)
10241 // [weak_next]: linked list of typed arrays over the same array buffer.
10242 DECL_ACCESSORS(weak_next, Object)
10244 DECLARE_CAST(JSArrayBufferView)
10246 DECLARE_VERIFIER(JSArrayBufferView)
10248 static const int kBufferOffset = JSObject::kHeaderSize;
10249 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10250 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10251 static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10252 static const int kViewSize = kWeakNextOffset + kPointerSize;
10258 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10262 class JSTypedArray: public JSArrayBufferView {
10264 // [length]: length of typed array in elements.
10265 DECL_ACCESSORS(length, Object)
10267 // Neutering. Only neuters this typed array.
10270 DECLARE_CAST(JSTypedArray)
10272 ExternalArrayType type();
10273 size_t element_size();
10275 Handle<JSArrayBuffer> GetBuffer();
10277 // Dispatched behavior.
10278 DECLARE_PRINTER(JSTypedArray)
10279 DECLARE_VERIFIER(JSTypedArray)
10281 static const int kLengthOffset = kViewSize + kPointerSize;
10282 static const int kSize = kLengthOffset + kPointerSize;
10284 static const int kSizeWithInternalFields =
10285 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10288 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10289 Handle<JSTypedArray> typed_array);
10291 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10295 class JSDataView: public JSArrayBufferView {
10297 // Only neuters this DataView
10300 DECLARE_CAST(JSDataView)
10302 // Dispatched behavior.
10303 DECLARE_PRINTER(JSDataView)
10304 DECLARE_VERIFIER(JSDataView)
10306 static const int kSize = kViewSize;
10308 static const int kSizeWithInternalFields =
10309 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10312 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10316 class Float32x4: public JSObject {
10318 typedef float32x4_value_t value_t;
10319 static const int kValueSize = kFloat32x4Size;
10320 static const InstanceType kInstanceType = FLOAT32x4_TYPE;
10321 static inline const char* Name();
10322 static inline int kRuntimeAllocatorId();
10324 // [value]: the FixedFloat32x4Array with length 1.
10325 DECL_ACCESSORS(value, Object)
10328 DECLARE_CAST(Float32x4)
10330 // Dispatched behavior.
10331 void Float32x4Print(OStream& os);
10332 DECLARE_VERIFIER(Float32x4)
10335 static const int kLanes = 4;
10336 inline float getAt(int index);
10337 inline float x() { return getAt(0); }
10338 inline float y() { return getAt(1); }
10339 inline float z() { return getAt(2); }
10340 inline float w() { return getAt(3); }
10341 inline float32x4_value_t get();
10342 inline void set(float32x4_value_t f32x4);
10344 // Layout description.
10345 static const int kValueOffset = JSObject::kHeaderSize;
10346 static const int kSize = kValueOffset + kPointerSize;
10349 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
10353 class Float64x2: public JSObject {
10355 typedef float64x2_value_t value_t;
10356 static const int kValueSize = kFloat64x2Size;
10357 static const InstanceType kInstanceType = FLOAT64x2_TYPE;
10358 static inline const char* Name();
10359 static inline int kRuntimeAllocatorId();
10361 // [value]: the FixedFloat64x2Array with length 1.
10362 DECL_ACCESSORS(value, Object)
10365 DECLARE_CAST(Float64x2)
10367 // Dispatched behavior.
10368 void Float64x2Print(OStream& os);
10369 DECLARE_VERIFIER(Float64x2)
10372 static const int kLanes = 2;
10373 inline double getAt(int index);
10374 inline double x() { return getAt(0); }
10375 inline double y() { return getAt(1); }
10376 inline float64x2_value_t get();
10377 inline void set(float64x2_value_t f64x2);
10379 // Layout description.
10380 static const int kValueOffset = JSObject::kHeaderSize;
10381 static const int kSize = kValueOffset + kPointerSize;
10384 DISALLOW_IMPLICIT_CONSTRUCTORS(Float64x2);
10388 class Int32x4: public JSObject {
10390 typedef int32x4_value_t value_t;
10391 static const int kValueSize = kInt32x4Size;
10392 static const InstanceType kInstanceType = INT32x4_TYPE;
10393 static inline const char* Name();
10394 static inline int kRuntimeAllocatorId();
10396 // [value]: the FixedInt32x4Array with length 1.
10397 DECL_ACCESSORS(value, Object)
10400 DECLARE_CAST(Int32x4)
10402 // Dispatched behavior.
10403 void Int32x4Print(OStream& os);
10404 DECLARE_VERIFIER(Int32x4)
10407 static const int kLanes = 4;
10408 inline int32_t getAt(int32_t index);
10409 inline int32_t x() { return getAt(0); }
10410 inline int32_t y() { return getAt(1); }
10411 inline int32_t z() { return getAt(2); }
10412 inline int32_t w() { return getAt(3); }
10413 inline int32x4_value_t get();
10414 inline void set(int32x4_value_t i32x4);
10416 // Layout description.
10417 static const int kValueOffset = JSObject::kHeaderSize;
10418 static const int kSize = kValueOffset + kPointerSize;
10421 DISALLOW_IMPLICIT_CONSTRUCTORS(Int32x4);
10425 // Foreign describes objects pointing from JavaScript to C structures.
10426 // Since they cannot contain references to JS HeapObjects they can be
10427 // placed in old_data_space.
10428 class Foreign: public HeapObject {
10430 // [address]: field containing the address.
10431 inline Address foreign_address();
10432 inline void set_foreign_address(Address value);
10434 DECLARE_CAST(Foreign)
10436 // Dispatched behavior.
10437 inline void ForeignIterateBody(ObjectVisitor* v);
10439 template<typename StaticVisitor>
10440 inline void ForeignIterateBody();
10442 // Dispatched behavior.
10443 DECLARE_PRINTER(Foreign)
10444 DECLARE_VERIFIER(Foreign)
10446 // Layout description.
10448 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10449 static const int kSize = kForeignAddressOffset + kPointerSize;
10451 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10454 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10458 // The JSArray describes JavaScript Arrays
10459 // Such an array can be in one of two modes:
10460 // - fast, backing storage is a FixedArray and length <= elements.length();
10461 // Please note: push and pop can be used to grow and shrink the array.
10462 // - slow, backing storage is a HashTable with numbers as keys.
10463 class JSArray: public JSObject {
10465 // [length]: The length property.
10466 DECL_ACCESSORS(length, Object)
10468 // Overload the length setter to skip write barrier when the length
10469 // is set to a smi. This matches the set function on FixedArray.
10470 inline void set_length(Smi* length);
10472 static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10474 Handle<Object> value);
10476 static bool IsReadOnlyLengthDescriptor(Handle<Map> jsarray_map);
10477 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10478 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10480 // Initialize the array with the given capacity. The function may
10481 // fail due to out-of-memory situations, but only if the requested
10482 // capacity is non-zero.
10483 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10485 // Initializes the array to a certain length.
10486 inline bool AllowsSetElementsLength();
10488 MUST_USE_RESULT static MaybeHandle<Object> SetElementsLength(
10489 Handle<JSArray> array,
10490 Handle<Object> length);
10492 // Set the content of the array to the content of storage.
10493 static inline void SetContent(Handle<JSArray> array,
10494 Handle<FixedArrayBase> storage);
10496 DECLARE_CAST(JSArray)
10498 // Ensures that the fixed array backing the JSArray has at
10499 // least the stated size.
10500 static inline void EnsureSize(Handle<JSArray> array,
10501 int minimum_size_of_backing_fixed_array);
10503 // Expand the fixed array backing of a fast-case JSArray to at least
10504 // the requested size.
10505 static void Expand(Handle<JSArray> array,
10506 int minimum_size_of_backing_fixed_array);
10508 // Dispatched behavior.
10509 DECLARE_PRINTER(JSArray)
10510 DECLARE_VERIFIER(JSArray)
10512 // Number of element slots to pre-allocate for an empty array.
10513 static const int kPreallocatedArrayElements = 4;
10515 // Layout description.
10516 static const int kLengthOffset = JSObject::kHeaderSize;
10517 static const int kSize = kLengthOffset + kPointerSize;
10520 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10524 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10525 Handle<Map> initial_map);
10528 // JSRegExpResult is just a JSArray with a specific initial map.
10529 // This initial map adds in-object properties for "index" and "input"
10530 // properties, as assigned by RegExp.prototype.exec, which allows
10531 // faster creation of RegExp exec results.
10532 // This class just holds constants used when creating the result.
10533 // After creation the result must be treated as a JSArray in all regards.
10534 class JSRegExpResult: public JSArray {
10536 // Offsets of object fields.
10537 static const int kIndexOffset = JSArray::kSize;
10538 static const int kInputOffset = kIndexOffset + kPointerSize;
10539 static const int kSize = kInputOffset + kPointerSize;
10540 // Indices of in-object properties.
10541 static const int kIndexIndex = 0;
10542 static const int kInputIndex = 1;
10544 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10548 class AccessorInfo: public Struct {
10550 DECL_ACCESSORS(name, Object)
10551 DECL_ACCESSORS(flag, Smi)
10552 DECL_ACCESSORS(expected_receiver_type, Object)
10554 inline bool all_can_read();
10555 inline void set_all_can_read(bool value);
10557 inline bool all_can_write();
10558 inline void set_all_can_write(bool value);
10560 inline PropertyAttributes property_attributes();
10561 inline void set_property_attributes(PropertyAttributes attributes);
10563 // Checks whether the given receiver is compatible with this accessor.
10564 static bool IsCompatibleReceiverType(Isolate* isolate,
10565 Handle<AccessorInfo> info,
10566 Handle<HeapType> type);
10567 inline bool IsCompatibleReceiver(Object* receiver);
10569 DECLARE_CAST(AccessorInfo)
10571 // Dispatched behavior.
10572 DECLARE_VERIFIER(AccessorInfo)
10574 // Append all descriptors to the array that are not already there.
10575 // Return number added.
10576 static int AppendUnique(Handle<Object> descriptors,
10577 Handle<FixedArray> array,
10578 int valid_descriptors);
10580 static const int kNameOffset = HeapObject::kHeaderSize;
10581 static const int kFlagOffset = kNameOffset + kPointerSize;
10582 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10583 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10586 inline bool HasExpectedReceiverType() {
10587 return expected_receiver_type()->IsFunctionTemplateInfo();
10589 // Bit positions in flag.
10590 static const int kAllCanReadBit = 0;
10591 static const int kAllCanWriteBit = 1;
10592 class AttributesField: public BitField<PropertyAttributes, 2, 3> {};
10594 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10598 enum AccessorDescriptorType {
10599 kDescriptorBitmaskCompare,
10600 kDescriptorPointerCompare,
10601 kDescriptorPrimitiveValue,
10602 kDescriptorObjectDereference,
10603 kDescriptorPointerDereference,
10604 kDescriptorPointerShift,
10605 kDescriptorReturnObject
10609 struct BitmaskCompareDescriptor {
10611 uint32_t compare_value;
10612 uint8_t size; // Must be in {1,2,4}.
10616 struct PointerCompareDescriptor {
10617 void* compare_value;
10621 struct PrimitiveValueDescriptor {
10622 v8::DeclaredAccessorDescriptorDataType data_type;
10623 uint8_t bool_offset; // Must be in [0,7], used for kDescriptorBoolType.
10627 struct ObjectDerefenceDescriptor {
10628 uint8_t internal_field;
10632 struct PointerShiftDescriptor {
10633 int16_t byte_offset;
10637 struct DeclaredAccessorDescriptorData {
10638 AccessorDescriptorType type;
10640 struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10641 struct PointerCompareDescriptor pointer_compare_descriptor;
10642 struct PrimitiveValueDescriptor primitive_value_descriptor;
10643 struct ObjectDerefenceDescriptor object_dereference_descriptor;
10644 struct PointerShiftDescriptor pointer_shift_descriptor;
10649 class DeclaredAccessorDescriptor;
10652 class DeclaredAccessorDescriptorIterator {
10654 explicit DeclaredAccessorDescriptorIterator(
10655 DeclaredAccessorDescriptor* descriptor);
10656 const DeclaredAccessorDescriptorData* Next();
10657 bool Complete() const { return length_ == offset_; }
10662 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10666 class DeclaredAccessorDescriptor: public Struct {
10668 DECL_ACCESSORS(serialized_data, ByteArray)
10670 DECLARE_CAST(DeclaredAccessorDescriptor)
10672 static Handle<DeclaredAccessorDescriptor> Create(
10674 const DeclaredAccessorDescriptorData& data,
10675 Handle<DeclaredAccessorDescriptor> previous);
10677 // Dispatched behavior.
10678 DECLARE_PRINTER(DeclaredAccessorDescriptor)
10679 DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10681 static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10682 static const int kSize = kSerializedDataOffset + kPointerSize;
10685 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10689 class DeclaredAccessorInfo: public AccessorInfo {
10691 DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10693 DECLARE_CAST(DeclaredAccessorInfo)
10695 // Dispatched behavior.
10696 DECLARE_PRINTER(DeclaredAccessorInfo)
10697 DECLARE_VERIFIER(DeclaredAccessorInfo)
10699 static const int kDescriptorOffset = AccessorInfo::kSize;
10700 static const int kSize = kDescriptorOffset + kPointerSize;
10703 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10707 // An accessor must have a getter, but can have no setter.
10709 // When setting a property, V8 searches accessors in prototypes.
10710 // If an accessor was found and it does not have a setter,
10711 // the request is ignored.
10713 // If the accessor in the prototype has the READ_ONLY property attribute, then
10714 // a new value is added to the derived object when the property is set.
10715 // This shadows the accessor in the prototype.
10716 class ExecutableAccessorInfo: public AccessorInfo {
10718 DECL_ACCESSORS(getter, Object)
10719 DECL_ACCESSORS(setter, Object)
10720 DECL_ACCESSORS(data, Object)
10722 DECLARE_CAST(ExecutableAccessorInfo)
10724 // Dispatched behavior.
10725 DECLARE_PRINTER(ExecutableAccessorInfo)
10726 DECLARE_VERIFIER(ExecutableAccessorInfo)
10728 static const int kGetterOffset = AccessorInfo::kSize;
10729 static const int kSetterOffset = kGetterOffset + kPointerSize;
10730 static const int kDataOffset = kSetterOffset + kPointerSize;
10731 static const int kSize = kDataOffset + kPointerSize;
10733 inline void clear_setter();
10736 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10740 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10741 // accessor can either be
10742 // * a pointer to a JavaScript function or proxy: a real accessor
10743 // * undefined: considered an accessor by the spec, too, strangely enough
10744 // * the hole: an accessor which has not been set
10745 // * a pointer to a map: a transition used to ensure map sharing
10746 class AccessorPair: public Struct {
10748 DECL_ACCESSORS(getter, Object)
10749 DECL_ACCESSORS(setter, Object)
10751 DECLARE_CAST(AccessorPair)
10753 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10755 Object* get(AccessorComponent component) {
10756 return component == ACCESSOR_GETTER ? getter() : setter();
10759 void set(AccessorComponent component, Object* value) {
10760 if (component == ACCESSOR_GETTER) {
10767 // Note: Returns undefined instead in case of a hole.
10768 Object* GetComponent(AccessorComponent component);
10770 // Set both components, skipping arguments which are a JavaScript null.
10771 void SetComponents(Object* getter, Object* setter) {
10772 if (!getter->IsNull()) set_getter(getter);
10773 if (!setter->IsNull()) set_setter(setter);
10776 bool ContainsAccessor() {
10777 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10780 // Dispatched behavior.
10781 DECLARE_PRINTER(AccessorPair)
10782 DECLARE_VERIFIER(AccessorPair)
10784 static const int kGetterOffset = HeapObject::kHeaderSize;
10785 static const int kSetterOffset = kGetterOffset + kPointerSize;
10786 static const int kSize = kSetterOffset + kPointerSize;
10789 // Strangely enough, in addition to functions and harmony proxies, the spec
10790 // requires us to consider undefined as a kind of accessor, too:
10792 // Object.defineProperty(obj, "foo", {get: undefined});
10793 // assertTrue("foo" in obj);
10794 bool IsJSAccessor(Object* obj) {
10795 return obj->IsSpecFunction() || obj->IsUndefined();
10798 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10802 class AccessCheckInfo: public Struct {
10804 DECL_ACCESSORS(named_callback, Object)
10805 DECL_ACCESSORS(indexed_callback, Object)
10806 DECL_ACCESSORS(data, Object)
10808 DECLARE_CAST(AccessCheckInfo)
10810 // Dispatched behavior.
10811 DECLARE_PRINTER(AccessCheckInfo)
10812 DECLARE_VERIFIER(AccessCheckInfo)
10814 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10815 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10816 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10817 static const int kSize = kDataOffset + kPointerSize;
10820 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10824 class InterceptorInfo: public Struct {
10826 DECL_ACCESSORS(getter, Object)
10827 DECL_ACCESSORS(setter, Object)
10828 DECL_ACCESSORS(query, Object)
10829 DECL_ACCESSORS(deleter, Object)
10830 DECL_ACCESSORS(enumerator, Object)
10831 DECL_ACCESSORS(data, Object)
10833 DECLARE_CAST(InterceptorInfo)
10835 // Dispatched behavior.
10836 DECLARE_PRINTER(InterceptorInfo)
10837 DECLARE_VERIFIER(InterceptorInfo)
10839 static const int kGetterOffset = HeapObject::kHeaderSize;
10840 static const int kSetterOffset = kGetterOffset + kPointerSize;
10841 static const int kQueryOffset = kSetterOffset + kPointerSize;
10842 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10843 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10844 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10845 static const int kSize = kDataOffset + kPointerSize;
10848 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10852 class CallHandlerInfo: public Struct {
10854 DECL_ACCESSORS(callback, Object)
10855 DECL_ACCESSORS(data, Object)
10857 DECLARE_CAST(CallHandlerInfo)
10859 // Dispatched behavior.
10860 DECLARE_PRINTER(CallHandlerInfo)
10861 DECLARE_VERIFIER(CallHandlerInfo)
10863 static const int kCallbackOffset = HeapObject::kHeaderSize;
10864 static const int kDataOffset = kCallbackOffset + kPointerSize;
10865 static const int kSize = kDataOffset + kPointerSize;
10868 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10872 class TemplateInfo: public Struct {
10874 DECL_ACCESSORS(tag, Object)
10875 DECL_ACCESSORS(property_list, Object)
10876 DECL_ACCESSORS(property_accessors, Object)
10878 DECLARE_VERIFIER(TemplateInfo)
10880 static const int kTagOffset = HeapObject::kHeaderSize;
10881 static const int kPropertyListOffset = kTagOffset + kPointerSize;
10882 static const int kPropertyAccessorsOffset =
10883 kPropertyListOffset + kPointerSize;
10884 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10887 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10891 class FunctionTemplateInfo: public TemplateInfo {
10893 DECL_ACCESSORS(serial_number, Object)
10894 DECL_ACCESSORS(call_code, Object)
10895 DECL_ACCESSORS(prototype_template, Object)
10896 DECL_ACCESSORS(parent_template, Object)
10897 DECL_ACCESSORS(named_property_handler, Object)
10898 DECL_ACCESSORS(indexed_property_handler, Object)
10899 DECL_ACCESSORS(instance_template, Object)
10900 DECL_ACCESSORS(class_name, Object)
10901 DECL_ACCESSORS(signature, Object)
10902 DECL_ACCESSORS(instance_call_handler, Object)
10903 DECL_ACCESSORS(access_check_info, Object)
10904 DECL_ACCESSORS(flag, Smi)
10906 inline int length() const;
10907 inline void set_length(int value);
10909 // Following properties use flag bits.
10910 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10911 DECL_BOOLEAN_ACCESSORS(undetectable)
10912 // If the bit is set, object instances created by this function
10913 // requires access check.
10914 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10915 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10916 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10917 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10919 DECLARE_CAST(FunctionTemplateInfo)
10921 // Dispatched behavior.
10922 DECLARE_PRINTER(FunctionTemplateInfo)
10923 DECLARE_VERIFIER(FunctionTemplateInfo)
10925 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10926 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10927 static const int kPrototypeTemplateOffset =
10928 kCallCodeOffset + kPointerSize;
10929 static const int kParentTemplateOffset =
10930 kPrototypeTemplateOffset + kPointerSize;
10931 static const int kNamedPropertyHandlerOffset =
10932 kParentTemplateOffset + kPointerSize;
10933 static const int kIndexedPropertyHandlerOffset =
10934 kNamedPropertyHandlerOffset + kPointerSize;
10935 static const int kInstanceTemplateOffset =
10936 kIndexedPropertyHandlerOffset + kPointerSize;
10937 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10938 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10939 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10940 static const int kAccessCheckInfoOffset =
10941 kInstanceCallHandlerOffset + kPointerSize;
10942 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10943 static const int kLengthOffset = kFlagOffset + kPointerSize;
10944 static const int kSize = kLengthOffset + kPointerSize;
10946 // Returns true if |object| is an instance of this function template.
10947 bool IsTemplateFor(Object* object);
10948 bool IsTemplateFor(Map* map);
10951 // Bit position in the flag, from least significant bit position.
10952 static const int kHiddenPrototypeBit = 0;
10953 static const int kUndetectableBit = 1;
10954 static const int kNeedsAccessCheckBit = 2;
10955 static const int kReadOnlyPrototypeBit = 3;
10956 static const int kRemovePrototypeBit = 4;
10957 static const int kDoNotCacheBit = 5;
10959 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10963 class ObjectTemplateInfo: public TemplateInfo {
10965 DECL_ACCESSORS(constructor, Object)
10966 DECL_ACCESSORS(internal_field_count, Object)
10968 DECLARE_CAST(ObjectTemplateInfo)
10970 // Dispatched behavior.
10971 DECLARE_PRINTER(ObjectTemplateInfo)
10972 DECLARE_VERIFIER(ObjectTemplateInfo)
10974 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10975 static const int kInternalFieldCountOffset =
10976 kConstructorOffset + kPointerSize;
10977 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10981 class SignatureInfo: public Struct {
10983 DECL_ACCESSORS(receiver, Object)
10984 DECL_ACCESSORS(args, Object)
10986 DECLARE_CAST(SignatureInfo)
10988 // Dispatched behavior.
10989 DECLARE_PRINTER(SignatureInfo)
10990 DECLARE_VERIFIER(SignatureInfo)
10992 static const int kReceiverOffset = Struct::kHeaderSize;
10993 static const int kArgsOffset = kReceiverOffset + kPointerSize;
10994 static const int kSize = kArgsOffset + kPointerSize;
10997 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
11001 class TypeSwitchInfo: public Struct {
11003 DECL_ACCESSORS(types, Object)
11005 DECLARE_CAST(TypeSwitchInfo)
11007 // Dispatched behavior.
11008 DECLARE_PRINTER(TypeSwitchInfo)
11009 DECLARE_VERIFIER(TypeSwitchInfo)
11011 static const int kTypesOffset = Struct::kHeaderSize;
11012 static const int kSize = kTypesOffset + kPointerSize;
11016 // The DebugInfo class holds additional information for a function being
11018 class DebugInfo: public Struct {
11020 // The shared function info for the source being debugged.
11021 DECL_ACCESSORS(shared, SharedFunctionInfo)
11022 // Code object for the original code.
11023 DECL_ACCESSORS(original_code, Code)
11024 // Code object for the patched code. This code object is the code object
11025 // currently active for the function.
11026 DECL_ACCESSORS(code, Code)
11027 // Fixed array holding status information for each active break point.
11028 DECL_ACCESSORS(break_points, FixedArray)
11030 // Check if there is a break point at a code position.
11031 bool HasBreakPoint(int code_position);
11032 // Get the break point info object for a code position.
11033 Object* GetBreakPointInfo(int code_position);
11034 // Clear a break point.
11035 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
11037 Handle<Object> break_point_object);
11038 // Set a break point.
11039 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
11040 int source_position, int statement_position,
11041 Handle<Object> break_point_object);
11042 // Get the break point objects for a code position.
11043 Object* GetBreakPointObjects(int code_position);
11044 // Find the break point info holding this break point object.
11045 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
11046 Handle<Object> break_point_object);
11047 // Get the number of break points for this function.
11048 int GetBreakPointCount();
11050 DECLARE_CAST(DebugInfo)
11052 // Dispatched behavior.
11053 DECLARE_PRINTER(DebugInfo)
11054 DECLARE_VERIFIER(DebugInfo)
11056 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
11057 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
11058 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
11059 static const int kActiveBreakPointsCountIndex =
11060 kPatchedCodeIndex + kPointerSize;
11061 static const int kBreakPointsStateIndex =
11062 kActiveBreakPointsCountIndex + kPointerSize;
11063 static const int kSize = kBreakPointsStateIndex + kPointerSize;
11065 static const int kEstimatedNofBreakPointsInFunction = 16;
11068 static const int kNoBreakPointInfo = -1;
11070 // Lookup the index in the break_points array for a code position.
11071 int GetBreakPointInfoIndex(int code_position);
11073 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
11077 // The BreakPointInfo class holds information for break points set in a
11078 // function. The DebugInfo object holds a BreakPointInfo object for each code
11079 // position with one or more break points.
11080 class BreakPointInfo: public Struct {
11082 // The position in the code for the break point.
11083 DECL_ACCESSORS(code_position, Smi)
11084 // The position in the source for the break position.
11085 DECL_ACCESSORS(source_position, Smi)
11086 // The position in the source for the last statement before this break
11088 DECL_ACCESSORS(statement_position, Smi)
11089 // List of related JavaScript break points.
11090 DECL_ACCESSORS(break_point_objects, Object)
11092 // Removes a break point.
11093 static void ClearBreakPoint(Handle<BreakPointInfo> info,
11094 Handle<Object> break_point_object);
11095 // Set a break point.
11096 static void SetBreakPoint(Handle<BreakPointInfo> info,
11097 Handle<Object> break_point_object);
11098 // Check if break point info has this break point object.
11099 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
11100 Handle<Object> break_point_object);
11101 // Get the number of break points for this code position.
11102 int GetBreakPointCount();
11104 DECLARE_CAST(BreakPointInfo)
11106 // Dispatched behavior.
11107 DECLARE_PRINTER(BreakPointInfo)
11108 DECLARE_VERIFIER(BreakPointInfo)
11110 static const int kCodePositionIndex = Struct::kHeaderSize;
11111 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
11112 static const int kStatementPositionIndex =
11113 kSourcePositionIndex + kPointerSize;
11114 static const int kBreakPointObjectsIndex =
11115 kStatementPositionIndex + kPointerSize;
11116 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
11119 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
11123 #undef DECL_BOOLEAN_ACCESSORS
11124 #undef DECL_ACCESSORS
11125 #undef DECLARE_CAST
11126 #undef DECLARE_VERIFIER
11128 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
11129 V(kStringTable, "string_table", "(Internalized strings)") \
11130 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
11131 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
11132 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
11133 V(kInternalizedString, "internalized_string", "(Internal string)") \
11134 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
11135 V(kTop, "top", "(Isolate)") \
11136 V(kRelocatable, "relocatable", "(Relocatable)") \
11137 V(kDebug, "debug", "(Debugger)") \
11138 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
11139 V(kHandleScope, "handlescope", "(Handle scope)") \
11140 V(kBuiltins, "builtins", "(Builtins)") \
11141 V(kGlobalHandles, "globalhandles", "(Global handles)") \
11142 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
11143 V(kThreadManager, "threadmanager", "(Thread manager)") \
11144 V(kExtensions, "Extensions", "(Extensions)")
11146 class VisitorSynchronization : public AllStatic {
11148 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
11150 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
11153 #undef DECLARE_ENUM
11155 static const char* const kTags[kNumberOfSyncTags];
11156 static const char* const kTagNames[kNumberOfSyncTags];
11159 // Abstract base class for visiting, and optionally modifying, the
11160 // pointers contained in Objects. Used in GC and serialization/deserialization.
11161 class ObjectVisitor BASE_EMBEDDED {
11163 virtual ~ObjectVisitor() {}
11165 // Visits a contiguous arrays of pointers in the half-open range
11166 // [start, end). Any or all of the values may be modified on return.
11167 virtual void VisitPointers(Object** start, Object** end) = 0;
11169 // Handy shorthand for visiting a single pointer.
11170 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
11172 // Visit weak next_code_link in Code object.
11173 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
11175 // To allow lazy clearing of inline caches the visitor has
11176 // a rich interface for iterating over Code objects..
11178 // Visits a code target in the instruction stream.
11179 virtual void VisitCodeTarget(RelocInfo* rinfo);
11181 // Visits a code entry in a JS function.
11182 virtual void VisitCodeEntry(Address entry_address);
11184 // Visits a global property cell reference in the instruction stream.
11185 virtual void VisitCell(RelocInfo* rinfo);
11187 // Visits a runtime entry in the instruction stream.
11188 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
11190 // Visits the resource of an one-byte or two-byte string.
11191 virtual void VisitExternalOneByteString(
11192 v8::String::ExternalOneByteStringResource** resource) {}
11193 virtual void VisitExternalTwoByteString(
11194 v8::String::ExternalStringResource** resource) {}
11196 // Visits a debug call target in the instruction stream.
11197 virtual void VisitDebugTarget(RelocInfo* rinfo);
11199 // Visits the byte sequence in a function's prologue that contains information
11200 // about the code's age.
11201 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
11203 // Visit pointer embedded into a code object.
11204 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
11206 // Visits an external reference embedded into a code object.
11207 virtual void VisitExternalReference(RelocInfo* rinfo);
11209 // Visits an external reference. The value may be modified on return.
11210 virtual void VisitExternalReference(Address* p) {}
11212 // Visits a handle that has an embedder-assigned class ID.
11213 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
11215 // Intended for serialization/deserialization checking: insert, or
11216 // check for the presence of, a tag at this position in the stream.
11217 // Also used for marking up GC roots in heap snapshots.
11218 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
11222 class StructBodyDescriptor : public
11223 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
11225 static inline int SizeOf(Map* map, HeapObject* object) {
11226 return map->instance_size();
11231 // BooleanBit is a helper class for setting and getting a bit in an
11233 class BooleanBit : public AllStatic {
11235 static inline bool get(Smi* smi, int bit_position) {
11236 return get(smi->value(), bit_position);
11239 static inline bool get(int value, int bit_position) {
11240 return (value & (1 << bit_position)) != 0;
11243 static inline Smi* set(Smi* smi, int bit_position, bool v) {
11244 return Smi::FromInt(set(smi->value(), bit_position, v));
11247 static inline int set(int value, int bit_position, bool v) {
11249 value |= (1 << bit_position);
11251 value &= ~(1 << bit_position);
11257 } } // namespace v8::internal
11259 #endif // V8_OBJECTS_H_