1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/builtins.h"
15 #include "src/checks.h"
16 #include "src/elements-kind.h"
17 #include "src/field-index.h"
18 #include "src/flags.h"
20 #include "src/property-details.h"
21 #include "src/smart-pointers.h"
22 #include "src/unicode-inl.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
38 // Most object types in the V8 JavaScript are described in this file.
40 // Inheritance hierarchy:
42 // - Smi (immediate small integer)
43 // - HeapObject (superclass for everything allocated in the heap)
44 // - JSReceiver (suitable for property access)
48 // - 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
103 // - SeqOneByteString
104 // - SeqTwoByteString
108 // - ExternalOneByteString
109 // - ExternalTwoByteString
110 // - InternalizedString
111 // - SeqInternalizedString
112 // - SeqOneByteInternalizedString
113 // - SeqTwoByteInternalizedString
114 // - ConsInternalizedString
115 // - ExternalInternalizedString
116 // - ExternalOneByteInternalizedString
117 // - ExternalTwoByteInternalizedString
126 // - SharedFunctionInfo
129 // - DeclaredAccessorDescriptor
131 // - DeclaredAccessorInfo
132 // - ExecutableAccessorInfo
138 // - FunctionTemplateInfo
139 // - ObjectTemplateInfo
148 // Formats of Object*:
149 // Smi: [31 bit signed int] 0
150 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
155 enum KeyedAccessStoreMode {
157 STORE_TRANSITION_SMI_TO_OBJECT,
158 STORE_TRANSITION_SMI_TO_DOUBLE,
159 STORE_TRANSITION_DOUBLE_TO_OBJECT,
160 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
161 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
162 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
163 STORE_AND_GROW_NO_TRANSITION,
164 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
165 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
166 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
167 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
168 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
169 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
170 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
171 STORE_NO_TRANSITION_HANDLE_COW
175 enum ContextualMode {
187 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
189 STATIC_ASSERT(STANDARD_STORE == 0);
190 STATIC_ASSERT(kGrowICDelta ==
191 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
192 STORE_TRANSITION_SMI_TO_OBJECT);
193 STATIC_ASSERT(kGrowICDelta ==
194 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
195 STORE_TRANSITION_SMI_TO_DOUBLE);
196 STATIC_ASSERT(kGrowICDelta ==
197 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
198 STORE_TRANSITION_DOUBLE_TO_OBJECT);
201 static inline KeyedAccessStoreMode GetGrowStoreMode(
202 KeyedAccessStoreMode store_mode) {
203 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
204 store_mode = static_cast<KeyedAccessStoreMode>(
205 static_cast<int>(store_mode) + kGrowICDelta);
211 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
212 return store_mode > STANDARD_STORE &&
213 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
214 store_mode != STORE_AND_GROW_NO_TRANSITION;
218 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
219 KeyedAccessStoreMode store_mode) {
220 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
223 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
224 return STORE_AND_GROW_NO_TRANSITION;
226 return STANDARD_STORE;
230 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
231 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
232 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
236 enum IcCheckType { ELEMENT, PROPERTY };
239 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
240 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
243 // Indicates whether a value can be loaded as a constant.
250 // PropertyNormalizationMode is used to specify whether to keep
251 // inobject properties when normalizing properties of a JSObject.
252 enum PropertyNormalizationMode {
253 CLEAR_INOBJECT_PROPERTIES,
254 KEEP_INOBJECT_PROPERTIES
258 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
259 // will give the fastest result by tailoring the map to the prototype, but that
260 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
261 // (at least for now) when dynamically modifying the prototype chain of an
262 // object using __proto__ or Object.setPrototypeOf.
263 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
266 // Indicates whether transitions can be added to a source map or not.
267 enum TransitionFlag {
273 enum DebugExtraICState {
275 DEBUG_PREPARE_STEP_IN
279 // Indicates whether the transition is simple: the target map of the transition
280 // either extends the current map with a new property, or it modifies the
281 // property that was added last to the current map.
282 enum SimpleTransitionFlag {
288 // Indicates whether we are only interested in the descriptors of a particular
289 // map, or in all descriptors in the descriptor array.
290 enum DescriptorFlag {
295 // The GC maintains a bit of information, the MarkingParity, which toggles
296 // from odd to even and back every time marking is completed. Incremental
297 // marking can visit an object twice during a marking phase, so algorithms that
298 // that piggy-back on marking can use the parity to ensure that they only
299 // perform an operation on an object once per marking phase: they record the
300 // MarkingParity when they visit an object, and only re-visit the object when it
301 // is marked again and the MarkingParity changes.
308 // ICs store extra state in a Code object. The default extra state is
310 typedef int ExtraICState;
311 static const ExtraICState kNoExtraICState = 0;
313 // Instance size sentinel for objects of variable size.
314 const int kVariableSizeSentinel = 0;
316 // We may store the unsigned bit field as signed Smi value and do not
318 const int kStubMajorKeyBits = 7;
319 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
321 // All Maps have a field instance_type containing a InstanceType.
322 // It describes the type of the instances.
324 // As an example, a JavaScript object is a heap object and its map
325 // instance_type is JS_OBJECT_TYPE.
327 // The names of the string instance types are intended to systematically
328 // mirror their encoding in the instance_type field of the map. The default
329 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
330 // encoding is mentioned explicitly in the name. Likewise, the default
331 // representation is considered sequential. It is not mentioned in the
332 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
333 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
334 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
336 // NOTE: The following things are some that depend on the string types having
337 // instance_types that are less than those of all other types:
338 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
341 // NOTE: Everything following JS_VALUE_TYPE is considered a
342 // JSObject for GC purposes. The first four entries here have typeof
343 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
344 #define INSTANCE_TYPE_LIST(V) \
346 V(ONE_BYTE_STRING_TYPE) \
347 V(CONS_STRING_TYPE) \
348 V(CONS_ONE_BYTE_STRING_TYPE) \
349 V(SLICED_STRING_TYPE) \
350 V(SLICED_ONE_BYTE_STRING_TYPE) \
351 V(EXTERNAL_STRING_TYPE) \
352 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
353 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
354 V(SHORT_EXTERNAL_STRING_TYPE) \
355 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
356 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
358 V(INTERNALIZED_STRING_TYPE) \
359 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
360 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
361 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
362 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
363 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
364 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
365 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
373 V(PROPERTY_CELL_TYPE) \
375 V(HEAP_NUMBER_TYPE) \
376 V(MUTABLE_HEAP_NUMBER_TYPE) \
380 /* Note: the order of these external array */ \
381 /* types is relied upon in */ \
382 /* Object::IsExternalArray(). */ \
383 V(EXTERNAL_INT8_ARRAY_TYPE) \
384 V(EXTERNAL_UINT8_ARRAY_TYPE) \
385 V(EXTERNAL_INT16_ARRAY_TYPE) \
386 V(EXTERNAL_UINT16_ARRAY_TYPE) \
387 V(EXTERNAL_INT32_ARRAY_TYPE) \
388 V(EXTERNAL_UINT32_ARRAY_TYPE) \
389 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
390 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
391 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
393 V(FIXED_INT8_ARRAY_TYPE) \
394 V(FIXED_UINT8_ARRAY_TYPE) \
395 V(FIXED_INT16_ARRAY_TYPE) \
396 V(FIXED_UINT16_ARRAY_TYPE) \
397 V(FIXED_INT32_ARRAY_TYPE) \
398 V(FIXED_UINT32_ARRAY_TYPE) \
399 V(FIXED_FLOAT32_ARRAY_TYPE) \
400 V(FIXED_FLOAT64_ARRAY_TYPE) \
401 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
405 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
406 V(DECLARED_ACCESSOR_INFO_TYPE) \
407 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
408 V(ACCESSOR_PAIR_TYPE) \
409 V(ACCESS_CHECK_INFO_TYPE) \
410 V(INTERCEPTOR_INFO_TYPE) \
411 V(CALL_HANDLER_INFO_TYPE) \
412 V(FUNCTION_TEMPLATE_INFO_TYPE) \
413 V(OBJECT_TEMPLATE_INFO_TYPE) \
414 V(SIGNATURE_INFO_TYPE) \
415 V(TYPE_SWITCH_INFO_TYPE) \
416 V(ALLOCATION_MEMENTO_TYPE) \
417 V(ALLOCATION_SITE_TYPE) \
420 V(POLYMORPHIC_CODE_CACHE_TYPE) \
421 V(TYPE_FEEDBACK_INFO_TYPE) \
422 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
425 V(FIXED_ARRAY_TYPE) \
426 V(FIXED_DOUBLE_ARRAY_TYPE) \
427 V(CONSTANT_POOL_ARRAY_TYPE) \
428 V(SHARED_FUNCTION_INFO_TYPE) \
431 V(JS_MESSAGE_OBJECT_TYPE) \
436 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
437 V(JS_GENERATOR_OBJECT_TYPE) \
439 V(JS_GLOBAL_OBJECT_TYPE) \
440 V(JS_BUILTINS_OBJECT_TYPE) \
441 V(JS_GLOBAL_PROXY_TYPE) \
443 V(JS_ARRAY_BUFFER_TYPE) \
444 V(JS_TYPED_ARRAY_TYPE) \
445 V(JS_DATA_VIEW_TYPE) \
449 V(JS_SET_ITERATOR_TYPE) \
450 V(JS_MAP_ITERATOR_TYPE) \
451 V(JS_WEAK_MAP_TYPE) \
452 V(JS_WEAK_SET_TYPE) \
455 V(JS_FUNCTION_TYPE) \
456 V(JS_FUNCTION_PROXY_TYPE) \
458 V(BREAK_POINT_INFO_TYPE)
461 // Since string types are not consecutive, this macro is used to
462 // iterate over them.
463 #define STRING_TYPE_LIST(V) \
464 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
465 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
467 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
468 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
470 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
471 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
472 SlicedOneByteString) \
473 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
475 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
476 external_one_byte_string, ExternalOneByteString) \
477 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
478 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
479 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
480 short_external_string, ShortExternalString) \
481 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
482 short_external_one_byte_string, ShortExternalOneByteString) \
483 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
484 ExternalTwoByteString::kShortSize, \
485 short_external_string_with_one_byte_data, \
486 ShortExternalStringWithOneByteData) \
488 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
489 InternalizedString) \
490 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
491 one_byte_internalized_string, OneByteInternalizedString) \
492 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
493 external_internalized_string, ExternalInternalizedString) \
494 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
495 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
496 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
497 ExternalTwoByteString::kSize, \
498 external_internalized_string_with_one_byte_data, \
499 ExternalInternalizedStringWithOneByteData) \
500 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
501 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
502 ShortExternalInternalizedString) \
503 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
504 ExternalOneByteString::kShortSize, \
505 short_external_one_byte_internalized_string, \
506 ShortExternalOneByteInternalizedString) \
507 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
508 ExternalTwoByteString::kShortSize, \
509 short_external_internalized_string_with_one_byte_data, \
510 ShortExternalInternalizedStringWithOneByteData)
512 // A struct is a simple object a set of object-valued fields. Including an
513 // object type in this causes the compiler to generate most of the boilerplate
514 // code for the class including allocation and garbage collection routines,
515 // casts and predicates. All you need to define is the class, methods and
516 // object verification routines. Easy, no?
518 // Note that for subtle reasons related to the ordering or numerical values of
519 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
521 #define STRUCT_LIST(V) \
523 V(DECLARED_ACCESSOR_DESCRIPTOR, \
524 DeclaredAccessorDescriptor, \
525 declared_accessor_descriptor) \
526 V(DECLARED_ACCESSOR_INFO, DeclaredAccessorInfo, declared_accessor_info) \
527 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
528 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
529 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
530 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
531 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
532 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
533 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
534 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
535 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
536 V(SCRIPT, Script, script) \
537 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
538 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
539 V(CODE_CACHE, CodeCache, code_cache) \
540 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
541 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
542 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
543 V(DEBUG_INFO, DebugInfo, debug_info) \
544 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
546 // We use the full 8 bits of the instance_type field to encode heap object
547 // instance types. The high-order bit (bit 7) is set if the object is not a
548 // string, and cleared if it is a string.
549 const uint32_t kIsNotStringMask = 0x80;
550 const uint32_t kStringTag = 0x0;
551 const uint32_t kNotStringTag = 0x80;
553 // Bit 6 indicates that the object is an internalized string (if set) or not.
554 // Bit 7 has to be clear as well.
555 const uint32_t kIsNotInternalizedMask = 0x40;
556 const uint32_t kNotInternalizedTag = 0x40;
557 const uint32_t kInternalizedTag = 0x0;
559 // If bit 7 is clear then bit 2 indicates whether the string consists of
560 // two-byte characters or one-byte characters.
561 const uint32_t kStringEncodingMask = 0x4;
562 const uint32_t kTwoByteStringTag = 0x0;
563 const uint32_t kOneByteStringTag = 0x4;
565 // If bit 7 is clear, the low-order 2 bits indicate the representation
567 const uint32_t kStringRepresentationMask = 0x03;
568 enum StringRepresentationTag {
570 kConsStringTag = 0x1,
571 kExternalStringTag = 0x2,
572 kSlicedStringTag = 0x3
574 const uint32_t kIsIndirectStringMask = 0x1;
575 const uint32_t kIsIndirectStringTag = 0x1;
576 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
577 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
578 STATIC_ASSERT((kConsStringTag &
579 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
580 STATIC_ASSERT((kSlicedStringTag &
581 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
583 // Use this mask to distinguish between cons and slice only after making
584 // sure that the string is one of the two (an indirect string).
585 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
586 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
588 // If bit 7 is clear, then bit 3 indicates whether this two-byte
589 // string actually contains one byte data.
590 const uint32_t kOneByteDataHintMask = 0x08;
591 const uint32_t kOneByteDataHintTag = 0x08;
593 // If bit 7 is clear and string representation indicates an external string,
594 // then bit 4 indicates whether the data pointer is cached.
595 const uint32_t kShortExternalStringMask = 0x10;
596 const uint32_t kShortExternalStringTag = 0x10;
599 // A ConsString with an empty string as the right side is a candidate
600 // for being shortcut by the garbage collector. We don't allocate any
601 // non-flat internalized strings, so we do not shortcut them thereby
602 // avoiding turning internalized strings into strings. The bit-masks
603 // below contain the internalized bit as additional safety.
604 // See heap.cc, mark-compact.cc and objects-visiting.cc.
605 const uint32_t kShortcutTypeMask =
607 kIsNotInternalizedMask |
608 kStringRepresentationMask;
609 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
611 static inline bool IsShortcutCandidate(int type) {
612 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
618 INTERNALIZED_STRING_TYPE =
619 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
620 ONE_BYTE_INTERNALIZED_STRING_TYPE =
621 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
622 EXTERNAL_INTERNALIZED_STRING_TYPE =
623 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
624 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
625 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
626 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
627 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
629 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
630 kShortExternalStringTag |
632 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
633 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
635 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
636 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
637 kShortExternalStringTag | kInternalizedTag,
638 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
639 ONE_BYTE_STRING_TYPE =
640 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
641 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
642 CONS_ONE_BYTE_STRING_TYPE =
643 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
645 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
646 SLICED_ONE_BYTE_STRING_TYPE =
647 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
648 EXTERNAL_STRING_TYPE =
649 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
650 EXTERNAL_ONE_BYTE_STRING_TYPE =
651 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
652 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
653 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
655 SHORT_EXTERNAL_STRING_TYPE =
656 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
657 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
658 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
659 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
660 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
664 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
666 // Objects allocated in their own spaces (never in new space).
673 // "Data", objects that cannot contain non-map-word pointers to heap
676 MUTABLE_HEAP_NUMBER_TYPE,
680 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
681 EXTERNAL_UINT8_ARRAY_TYPE,
682 EXTERNAL_INT16_ARRAY_TYPE,
683 EXTERNAL_UINT16_ARRAY_TYPE,
684 EXTERNAL_INT32_ARRAY_TYPE,
685 EXTERNAL_UINT32_ARRAY_TYPE,
686 EXTERNAL_FLOAT32_ARRAY_TYPE,
687 EXTERNAL_FLOAT64_ARRAY_TYPE,
688 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
689 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
690 FIXED_UINT8_ARRAY_TYPE,
691 FIXED_INT16_ARRAY_TYPE,
692 FIXED_UINT16_ARRAY_TYPE,
693 FIXED_INT32_ARRAY_TYPE,
694 FIXED_UINT32_ARRAY_TYPE,
695 FIXED_FLOAT32_ARRAY_TYPE,
696 FIXED_FLOAT64_ARRAY_TYPE,
697 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
698 FIXED_DOUBLE_ARRAY_TYPE,
699 FILLER_TYPE, // LAST_DATA_TYPE
702 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
703 DECLARED_ACCESSOR_INFO_TYPE,
704 EXECUTABLE_ACCESSOR_INFO_TYPE,
706 ACCESS_CHECK_INFO_TYPE,
707 INTERCEPTOR_INFO_TYPE,
708 CALL_HANDLER_INFO_TYPE,
709 FUNCTION_TEMPLATE_INFO_TYPE,
710 OBJECT_TEMPLATE_INFO_TYPE,
712 TYPE_SWITCH_INFO_TYPE,
713 ALLOCATION_SITE_TYPE,
714 ALLOCATION_MEMENTO_TYPE,
717 POLYMORPHIC_CODE_CACHE_TYPE,
718 TYPE_FEEDBACK_INFO_TYPE,
719 ALIASED_ARGUMENTS_ENTRY_TYPE,
722 BREAK_POINT_INFO_TYPE,
724 CONSTANT_POOL_ARRAY_TYPE,
725 SHARED_FUNCTION_INFO_TYPE,
728 // All the following types are subtypes of JSReceiver, which corresponds to
729 // objects in the JS sense. The first and the last type in this range are
730 // the two forms of function. This organization enables using the same
731 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
732 // NONCALLABLE_JS_OBJECT range.
733 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
734 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
735 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
736 JS_MESSAGE_OBJECT_TYPE,
739 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
740 JS_GENERATOR_OBJECT_TYPE,
742 JS_GLOBAL_OBJECT_TYPE,
743 JS_BUILTINS_OBJECT_TYPE,
744 JS_GLOBAL_PROXY_TYPE,
746 JS_ARRAY_BUFFER_TYPE,
751 JS_SET_ITERATOR_TYPE,
752 JS_MAP_ITERATOR_TYPE,
756 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
760 LAST_TYPE = JS_FUNCTION_TYPE,
761 FIRST_NAME_TYPE = FIRST_TYPE,
762 LAST_NAME_TYPE = SYMBOL_TYPE,
763 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
764 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
765 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
766 // Boundaries for testing for an external array.
767 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
768 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
769 // Boundaries for testing for a fixed typed array.
770 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
771 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
772 // Boundary for promotion to old data space/old pointer space.
773 LAST_DATA_TYPE = FILLER_TYPE,
774 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
775 // Note that there is no range for JSObject or JSProxy, since their subtypes
776 // are not continuous in this enum! The enum ranges instead reflect the
777 // external class names, where proxies are treated as either ordinary objects,
779 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
780 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
781 // Boundaries for testing the types represented as JSObject
782 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
783 LAST_JS_OBJECT_TYPE = LAST_TYPE,
784 // Boundaries for testing the types represented as JSProxy
785 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
786 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
787 // Boundaries for testing whether the type is a JavaScript object.
788 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
789 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
790 // Boundaries for testing the types for which typeof is "object".
791 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
792 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
793 // Note that the types for which typeof is "function" are not continuous.
794 // Define this so that we can put assertions on discrete checks.
795 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
798 const int kExternalArrayTypeCount =
799 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
801 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
802 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
803 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
804 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
807 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
808 V(FAST_ELEMENTS_SUB_TYPE) \
809 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
810 V(FAST_PROPERTIES_SUB_TYPE) \
811 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
812 V(MAP_CODE_CACHE_SUB_TYPE) \
813 V(SCOPE_INFO_SUB_TYPE) \
814 V(STRING_TABLE_SUB_TYPE) \
815 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
816 V(TRANSITION_ARRAY_SUB_TYPE)
818 enum FixedArraySubInstanceType {
819 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
820 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
821 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
822 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
835 #define DECL_BOOLEAN_ACCESSORS(name) \
836 inline bool name() const; \
837 inline void set_##name(bool value); \
840 #define DECL_ACCESSORS(name, type) \
841 inline type* name() const; \
842 inline void set_##name(type* value, \
843 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
846 #define DECLARE_CAST(type) \
847 INLINE(static type* cast(Object* object)); \
848 INLINE(static const type* cast(const Object* object));
852 class AllocationSite;
853 class AllocationSiteCreationContext;
854 class AllocationSiteUsageContext;
855 class DictionaryElementsAccessor;
856 class ElementsAccessor;
857 class FixedArrayBase;
860 class LookupIterator;
862 class TypeFeedbackVector;
864 // We cannot just say "class HeapType;" if it is created from a template... =8-?
865 template<class> class TypeImpl;
866 struct HeapTypeConfig;
867 typedef TypeImpl<HeapTypeConfig> HeapType;
870 // A template-ized version of the IsXXX functions.
871 template <class C> inline bool Is(Object* obj);
874 #define DECLARE_VERIFIER(Name) void Name##Verify();
876 #define DECLARE_VERIFIER(Name)
880 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
882 #define DECLARE_PRINTER(Name)
886 #define OBJECT_TYPE_LIST(V) \
891 #define HEAP_OBJECT_TYPE_LIST(V) \
893 V(MutableHeapNumber) \
901 V(ExternalTwoByteString) \
902 V(ExternalOneByteString) \
903 V(SeqTwoByteString) \
904 V(SeqOneByteString) \
905 V(InternalizedString) \
909 V(ExternalInt8Array) \
910 V(ExternalUint8Array) \
911 V(ExternalInt16Array) \
912 V(ExternalUint16Array) \
913 V(ExternalInt32Array) \
914 V(ExternalUint32Array) \
915 V(ExternalFloat32Array) \
916 V(ExternalFloat64Array) \
917 V(ExternalUint8ClampedArray) \
918 V(FixedTypedArrayBase) \
921 V(FixedUint16Array) \
923 V(FixedUint32Array) \
925 V(FixedFloat32Array) \
926 V(FixedFloat64Array) \
927 V(FixedUint8ClampedArray) \
932 V(JSContextExtensionObject) \
933 V(JSGeneratorObject) \
938 V(TypeFeedbackVector) \
939 V(DeoptimizationInputData) \
940 V(DeoptimizationOutputData) \
943 V(FixedDoubleArray) \
944 V(ConstantPoolArray) \
951 V(SharedFunctionInfo) \
960 V(JSArrayBufferView) \
969 V(JSWeakCollection) \
976 V(JSFunctionResultCache) \
977 V(NormalizedMapCache) \
978 V(CompilationCacheTable) \
979 V(CodeCacheHashTable) \
980 V(PolymorphicCodeCacheHashTable) \
985 V(JSBuiltinsObject) \
987 V(UndetectableObject) \
988 V(AccessCheckNeeded) \
996 // Object is the abstract superclass for all classes in the
998 // Object does not use any virtual functions to avoid the
999 // allocation of the C++ vtable.
1000 // Since both Smi and HeapObject are subclasses of Object no
1001 // data members can be present in Object.
1005 bool IsObject() const { return true; }
1007 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1008 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1009 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1010 #undef IS_TYPE_FUNCTION_DECL
1012 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1013 // a keyed store is of the form a[expression] = foo.
1014 enum StoreFromKeyed {
1015 MAY_BE_STORE_FROM_KEYED,
1016 CERTAINLY_NOT_STORE_FROM_KEYED
1019 enum StorePropertyMode { NORMAL_PROPERTY, SUPER_PROPERTY };
1021 INLINE(bool IsFixedArrayBase() const);
1022 INLINE(bool IsExternal() const);
1023 INLINE(bool IsAccessorInfo() const);
1025 INLINE(bool IsStruct() const);
1026 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1027 INLINE(bool Is##Name() const);
1028 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1029 #undef DECLARE_STRUCT_PREDICATE
1031 INLINE(bool IsSpecObject()) const;
1032 INLINE(bool IsSpecFunction()) const;
1033 INLINE(bool IsTemplateInfo()) const;
1034 INLINE(bool IsNameDictionary() const);
1035 INLINE(bool IsSeededNumberDictionary() const);
1036 INLINE(bool IsUnseededNumberDictionary() const);
1037 INLINE(bool IsOrderedHashSet() const);
1038 INLINE(bool IsOrderedHashMap() const);
1039 bool IsCallable() const;
1042 INLINE(bool IsUndefined() const);
1043 INLINE(bool IsNull() const);
1044 INLINE(bool IsTheHole() const);
1045 INLINE(bool IsException() const);
1046 INLINE(bool IsUninitialized() const);
1047 INLINE(bool IsTrue() const);
1048 INLINE(bool IsFalse() const);
1049 INLINE(bool IsArgumentsMarker() const);
1051 // Filler objects (fillers and free space objects).
1052 INLINE(bool IsFiller() const);
1054 // Extract the number.
1055 inline double Number();
1056 INLINE(bool IsNaN() const);
1057 INLINE(bool IsMinusZero() const);
1058 bool ToInt32(int32_t* value);
1059 bool ToUint32(uint32_t* value);
1061 inline Representation OptimalRepresentation() {
1062 if (!FLAG_track_fields) return Representation::Tagged();
1064 return Representation::Smi();
1065 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1066 return Representation::Double();
1067 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1068 return Representation::None();
1069 } else if (FLAG_track_heap_object_fields) {
1070 DCHECK(IsHeapObject());
1071 return Representation::HeapObject();
1073 return Representation::Tagged();
1077 inline bool FitsRepresentation(Representation representation) {
1078 if (FLAG_track_fields && representation.IsNone()) {
1080 } else if (FLAG_track_fields && representation.IsSmi()) {
1082 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1083 return IsMutableHeapNumber() || IsNumber();
1084 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1085 return IsHeapObject();
1090 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1092 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1093 Handle<Object> object,
1094 Representation representation);
1096 inline static Handle<Object> WrapForRead(Isolate* isolate,
1097 Handle<Object> object,
1098 Representation representation);
1100 // Returns true if the object is of the correct type to be used as a
1101 // implementation of a JSObject's elements.
1102 inline bool HasValidElements();
1104 inline bool HasSpecificClassOf(String* name);
1106 bool BooleanValue(); // ECMA-262 9.2.
1108 // Convert to a JSObject if needed.
1109 // native_context is used when creating wrapper object.
1110 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1111 Handle<Object> object);
1112 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1113 Handle<Object> object,
1114 Handle<Context> context);
1116 // Converts this to a Smi if possible.
1117 static MUST_USE_RESULT inline MaybeHandle<Smi> ToSmi(Isolate* isolate,
1118 Handle<Object> object);
1120 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(LookupIterator* it);
1122 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1123 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1124 Handle<Object> object, Handle<Name> key, Handle<Object> value,
1125 StrictMode strict_mode,
1126 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1128 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1129 LookupIterator* it, Handle<Object> value, StrictMode strict_mode,
1130 StoreFromKeyed store_mode,
1131 StorePropertyMode data_store_mode = NORMAL_PROPERTY);
1132 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1133 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
1134 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyElement(
1135 Isolate* isolate, Handle<Object> receiver, uint32_t index,
1136 Handle<Object> value, StrictMode strict_mode);
1137 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1138 LookupIterator* it, Handle<Object> value);
1139 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1140 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1141 StrictMode strict_mode, StoreFromKeyed store_mode);
1142 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1143 Handle<Object> object,
1145 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1147 Handle<Object> object,
1149 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1150 Handle<Object> object,
1153 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1154 Handle<Object> receiver,
1156 Handle<JSObject> holder,
1157 Handle<Object> structure);
1158 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1159 Handle<Object> receiver, Handle<Name> name, Handle<Object> value,
1160 Handle<JSObject> holder, Handle<Object> structure,
1161 StrictMode strict_mode);
1163 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1164 Handle<Object> receiver,
1165 Handle<JSReceiver> getter);
1166 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1167 Handle<Object> receiver,
1168 Handle<JSReceiver> setter,
1169 Handle<Object> value);
1171 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1173 Handle<Object> object,
1176 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithReceiver(
1178 Handle<Object> object,
1179 Handle<Object> receiver,
1182 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithReceiver(
1183 Isolate* isolate, Handle<Object> object, Handle<Object> receiver,
1184 uint32_t index, Handle<Object> value, StrictMode strict_mode);
1186 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1187 Isolate* isolate, Handle<Object> receiver);
1189 // Returns the permanent hash code associated with this object. May return
1190 // undefined if not yet created.
1193 // Returns the permanent hash code associated with this object depending on
1194 // the actual object type. May create and store a hash code if needed and none
1196 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1198 // Checks whether this object has the same value as the given one. This
1199 // function is implemented according to ES5, section 9.12 and can be used
1200 // to implement the Harmony "egal" function.
1201 bool SameValue(Object* other);
1203 // Checks whether this object has the same value as the given one.
1204 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1205 // This function is implemented according to ES6, section 7.2.4 and is used
1206 // by ES6 Map and Set.
1207 bool SameValueZero(Object* other);
1209 // Tries to convert an object to an array index. Returns true and sets
1210 // the output parameter if it succeeds.
1211 inline bool ToArrayIndex(uint32_t* index);
1213 // Returns true if this is a JSValue containing a string and the index is
1214 // < the length of the string. Used to implement [] on strings.
1215 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1217 DECLARE_VERIFIER(Object)
1219 // Verify a pointer is a valid object pointer.
1220 static void VerifyPointer(Object* p);
1223 inline void VerifyApiCallResultType();
1225 // Prints this object without details.
1226 void ShortPrint(FILE* out = stdout);
1228 // Prints this object without details to a message accumulator.
1229 void ShortPrint(StringStream* accumulator);
1231 DECLARE_CAST(Object)
1233 // Layout description.
1234 static const int kHeaderSize = 0; // Object does not take up any space.
1237 // For our gdb macros, we should perhaps change these in the future.
1240 // Prints this object with details.
1241 void Print(std::ostream& os); // NOLINT
1245 friend class LookupIterator;
1246 friend class PrototypeIterator;
1248 // Return the map of the root of object's prototype chain.
1249 Map* GetRootMap(Isolate* isolate);
1251 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1256 explicit Brief(const Object* const v) : value(v) {}
1257 const Object* value;
1261 std::ostream& operator<<(std::ostream& os, const Brief& v);
1264 // Smi represents integer Numbers that can be stored in 31 bits.
1265 // Smis are immediate which means they are NOT allocated in the heap.
1266 // The this pointer has the following format: [31 bit signed int] 0
1267 // For long smis it has the following format:
1268 // [32 bit signed int] [31 bits zero padding] 0
1269 // Smi stands for small integer.
1270 class Smi: public Object {
1272 // Returns the integer value.
1273 inline int value() const;
1275 // Convert a value to a Smi object.
1276 static inline Smi* FromInt(int value);
1278 static inline Smi* FromIntptr(intptr_t value);
1280 // Returns whether value can be represented in a Smi.
1281 static inline bool IsValid(intptr_t value);
1285 // Dispatched behavior.
1286 void SmiPrint(std::ostream& os) const; // NOLINT
1287 DECLARE_VERIFIER(Smi)
1289 static const int kMinValue =
1290 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1291 static const int kMaxValue = -(kMinValue + 1);
1294 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1298 // Heap objects typically have a map pointer in their first word. However,
1299 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1300 // encoded in the first word. The class MapWord is an abstraction of the
1301 // value in a heap object's first word.
1302 class MapWord BASE_EMBEDDED {
1304 // Normal state: the map word contains a map pointer.
1306 // Create a map word from a map pointer.
1307 static inline MapWord FromMap(const Map* map);
1309 // View this map word as a map pointer.
1310 inline Map* ToMap();
1313 // Scavenge collection: the map word of live objects in the from space
1314 // contains a forwarding address (a heap object pointer in the to space).
1316 // True if this map word is a forwarding address for a scavenge
1317 // collection. Only valid during a scavenge collection (specifically,
1318 // when all map words are heap object pointers, i.e. not during a full GC).
1319 inline bool IsForwardingAddress();
1321 // Create a map word from a forwarding address.
1322 static inline MapWord FromForwardingAddress(HeapObject* object);
1324 // View this map word as a forwarding address.
1325 inline HeapObject* ToForwardingAddress();
1327 static inline MapWord FromRawValue(uintptr_t value) {
1328 return MapWord(value);
1331 inline uintptr_t ToRawValue() {
1336 // HeapObject calls the private constructor and directly reads the value.
1337 friend class HeapObject;
1339 explicit MapWord(uintptr_t value) : value_(value) {}
1345 // HeapObject is the superclass for all classes describing heap allocated
1347 class HeapObject: public Object {
1349 // [map]: Contains a map which contains the object's reflective
1351 inline Map* map() const;
1352 inline void set_map(Map* value);
1353 // The no-write-barrier version. This is OK if the object is white and in
1354 // new space, or if the value is an immortal immutable object, like the maps
1355 // of primitive (non-JS) objects like strings, heap numbers etc.
1356 inline void set_map_no_write_barrier(Map* value);
1358 // Get the map using acquire load.
1359 inline Map* synchronized_map();
1360 inline MapWord synchronized_map_word() const;
1362 // Set the map using release store
1363 inline void synchronized_set_map(Map* value);
1364 inline void synchronized_set_map_no_write_barrier(Map* value);
1365 inline void synchronized_set_map_word(MapWord map_word);
1367 // During garbage collection, the map word of a heap object does not
1368 // necessarily contain a map pointer.
1369 inline MapWord map_word() const;
1370 inline void set_map_word(MapWord map_word);
1372 // The Heap the object was allocated in. Used also to access Isolate.
1373 inline Heap* GetHeap() const;
1375 // Convenience method to get current isolate.
1376 inline Isolate* GetIsolate() const;
1378 // Converts an address to a HeapObject pointer.
1379 static inline HeapObject* FromAddress(Address address);
1381 // Returns the address of this HeapObject.
1382 inline Address address();
1384 // Iterates over pointers contained in the object (including the Map)
1385 void Iterate(ObjectVisitor* v);
1387 // Iterates over all pointers contained in the object except the
1388 // first map pointer. The object type is given in the first
1389 // parameter. This function does not access the map pointer in the
1390 // object, and so is safe to call while the map pointer is modified.
1391 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1393 // Returns the heap object's size in bytes
1396 // Returns true if this heap object may contain raw values, i.e., values that
1397 // look like pointers to heap objects.
1398 inline bool MayContainRawValues();
1400 // Given a heap object's map pointer, returns the heap size in bytes
1401 // Useful when the map pointer field is used for other purposes.
1403 inline int SizeFromMap(Map* map);
1405 // Returns the field at offset in obj, as a read/write Object* reference.
1406 // Does no checking, and is safe to use during GC, while maps are invalid.
1407 // Does not invoke write barrier, so should only be assigned to
1408 // during marking GC.
1409 static inline Object** RawField(HeapObject* obj, int offset);
1411 // Adds the |code| object related to |name| to the code cache of this map. If
1412 // this map is a dictionary map that is shared, the map copied and installed
1414 static void UpdateMapCodeCache(Handle<HeapObject> object,
1418 DECLARE_CAST(HeapObject)
1420 // Return the write barrier mode for this. Callers of this function
1421 // must be able to present a reference to an DisallowHeapAllocation
1422 // object as a sign that they are not going to use this function
1423 // from code that allocates and thus invalidates the returned write
1425 inline WriteBarrierMode GetWriteBarrierMode(
1426 const DisallowHeapAllocation& promise);
1428 // Dispatched behavior.
1429 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1431 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1433 DECLARE_PRINTER(HeapObject)
1434 DECLARE_VERIFIER(HeapObject)
1436 inline void VerifyObjectField(int offset);
1437 inline void VerifySmiField(int offset);
1439 // Verify a pointer is a valid HeapObject pointer that points to object
1440 // areas in the heap.
1441 static void VerifyHeapPointer(Object* p);
1444 // Layout description.
1445 // First field in a heap object is map.
1446 static const int kMapOffset = Object::kHeaderSize;
1447 static const int kHeaderSize = kMapOffset + kPointerSize;
1449 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1452 // helpers for calling an ObjectVisitor to iterate over pointers in the
1453 // half-open range [start, end) specified as integer offsets
1454 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1455 // as above, for the single element at "offset"
1456 inline void IteratePointer(ObjectVisitor* v, int offset);
1457 // as above, for the next code link of a code object.
1458 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1461 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1465 // This class describes a body of an object of a fixed size
1466 // in which all pointer fields are located in the [start_offset, end_offset)
1468 template<int start_offset, int end_offset, int size>
1469 class FixedBodyDescriptor {
1471 static const int kStartOffset = start_offset;
1472 static const int kEndOffset = end_offset;
1473 static const int kSize = size;
1475 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1477 template<typename StaticVisitor>
1478 static inline void IterateBody(HeapObject* obj) {
1479 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1480 HeapObject::RawField(obj, end_offset));
1485 // This class describes a body of an object of a variable size
1486 // in which all pointer fields are located in the [start_offset, object_size)
1488 template<int start_offset>
1489 class FlexibleBodyDescriptor {
1491 static const int kStartOffset = start_offset;
1493 static inline void IterateBody(HeapObject* obj,
1497 template<typename StaticVisitor>
1498 static inline void IterateBody(HeapObject* obj, int object_size) {
1499 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1500 HeapObject::RawField(obj, object_size));
1505 // The HeapNumber class describes heap allocated numbers that cannot be
1506 // represented in a Smi (small integer)
1507 class HeapNumber: public HeapObject {
1509 // [value]: number value.
1510 inline double value() const;
1511 inline void set_value(double value);
1513 DECLARE_CAST(HeapNumber)
1515 // Dispatched behavior.
1516 bool HeapNumberBooleanValue();
1518 void HeapNumberPrint(std::ostream& os); // NOLINT
1519 DECLARE_VERIFIER(HeapNumber)
1521 inline int get_exponent();
1522 inline int get_sign();
1524 // Layout description.
1525 static const int kValueOffset = HeapObject::kHeaderSize;
1526 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1527 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1528 // words within double numbers are endian dependent and they are set
1530 #if defined(V8_TARGET_LITTLE_ENDIAN)
1531 static const int kMantissaOffset = kValueOffset;
1532 static const int kExponentOffset = kValueOffset + 4;
1533 #elif defined(V8_TARGET_BIG_ENDIAN)
1534 static const int kMantissaOffset = kValueOffset + 4;
1535 static const int kExponentOffset = kValueOffset;
1537 #error Unknown byte ordering
1540 static const int kSize = kValueOffset + kDoubleSize;
1541 static const uint32_t kSignMask = 0x80000000u;
1542 static const uint32_t kExponentMask = 0x7ff00000u;
1543 static const uint32_t kMantissaMask = 0xfffffu;
1544 static const int kMantissaBits = 52;
1545 static const int kExponentBits = 11;
1546 static const int kExponentBias = 1023;
1547 static const int kExponentShift = 20;
1548 static const int kInfinityOrNanExponent =
1549 (kExponentMask >> kExponentShift) - kExponentBias;
1550 static const int kMantissaBitsInTopWord = 20;
1551 static const int kNonMantissaBitsInTopWord = 12;
1554 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1558 enum EnsureElementsMode {
1559 DONT_ALLOW_DOUBLE_ELEMENTS,
1560 ALLOW_COPIED_DOUBLE_ELEMENTS,
1561 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1565 // Indicates whether a property should be set or (re)defined. Setting of a
1566 // property causes attributes to remain unchanged, writability to be checked
1567 // and callbacks to be called. Defining of a property causes attributes to
1568 // be updated and callbacks to be overridden.
1569 enum SetPropertyMode {
1575 // Indicator for one component of an AccessorPair.
1576 enum AccessorComponent {
1582 // JSReceiver includes types on which properties can be defined, i.e.,
1583 // JSObject and JSProxy.
1584 class JSReceiver: public HeapObject {
1592 DECLARE_CAST(JSReceiver)
1594 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1595 Handle<JSReceiver> object,
1597 Handle<Object> value,
1598 PropertyAttributes attributes,
1599 StrictMode strict_mode);
1601 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1602 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1603 Handle<JSReceiver> object, Handle<Name> name);
1604 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1606 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1607 Handle<JSReceiver> object, uint32_t index);
1608 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1609 Handle<JSReceiver> object, uint32_t index);
1611 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1612 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1613 Handle<JSReceiver> object,
1615 DeleteMode mode = NORMAL_DELETION);
1616 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1617 Handle<JSReceiver> object,
1619 DeleteMode mode = NORMAL_DELETION);
1621 // Tests for the fast common case for property enumeration.
1622 bool IsSimpleEnum();
1624 // Returns the class name ([[Class]] property in the specification).
1625 String* class_name();
1627 // Returns the constructor name (the name (possibly, inferred name) of the
1628 // function that was used to instantiate the object).
1629 String* constructor_name();
1631 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1632 Handle<JSReceiver> object, Handle<Name> name);
1633 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1634 LookupIterator* it);
1635 MUST_USE_RESULT static Maybe<PropertyAttributes> GetOwnPropertyAttributes(
1636 Handle<JSReceiver> object, Handle<Name> name);
1638 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttribute(
1639 Handle<JSReceiver> object, uint32_t index);
1640 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1641 GetOwnElementAttribute(Handle<JSReceiver> object, uint32_t index);
1643 // Retrieves a permanent object identity hash code. The undefined value might
1644 // be returned in case no hash was created yet.
1645 inline Object* GetIdentityHash();
1647 // Retrieves a permanent object identity hash code. May create and store a
1648 // hash code if needed and none exists.
1649 inline static Handle<Smi> GetOrCreateIdentityHash(
1650 Handle<JSReceiver> object);
1652 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1654 // Computes the enumerable keys for a JSObject. Used for implementing
1655 // "for (n in object) { }".
1656 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1657 Handle<JSReceiver> object,
1658 KeyCollectionType type);
1661 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1664 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
1665 class ObjectHashTable;
1667 // Forward declaration for JSObject::Copy.
1668 class AllocationSite;
1671 // The JSObject describes real heap allocated JavaScript objects with
1673 // Note that the map of JSObject changes during execution to enable inline
1675 class JSObject: public JSReceiver {
1677 // [properties]: Backing storage for properties.
1678 // properties is a FixedArray in the fast case and a Dictionary in the
1680 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1681 inline void initialize_properties();
1682 inline bool HasFastProperties();
1683 inline NameDictionary* property_dictionary(); // Gets slow properties.
1685 // [elements]: The elements (properties with names that are integers).
1687 // Elements can be in two general modes: fast and slow. Each mode
1688 // corrensponds to a set of object representations of elements that
1689 // have something in common.
1691 // In the fast mode elements is a FixedArray and so each element can
1692 // be quickly accessed. This fact is used in the generated code. The
1693 // elements array can have one of three maps in this mode:
1694 // fixed_array_map, sloppy_arguments_elements_map or
1695 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1696 // the elements array may be shared by a few objects and so before
1697 // writing to any element the array must be copied. Use
1698 // EnsureWritableFastElements in this case.
1700 // In the slow mode the elements is either a NumberDictionary, an
1701 // ExternalArray, or a FixedArray parameter map for a (sloppy)
1702 // arguments object.
1703 DECL_ACCESSORS(elements, FixedArrayBase)
1704 inline void initialize_elements();
1705 static void ResetElements(Handle<JSObject> object);
1706 static inline void SetMapAndElements(Handle<JSObject> object,
1708 Handle<FixedArrayBase> elements);
1709 inline ElementsKind GetElementsKind();
1710 inline ElementsAccessor* GetElementsAccessor();
1711 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1712 inline bool HasFastSmiElements();
1713 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1714 inline bool HasFastObjectElements();
1715 // Returns true if an object has elements of FAST_ELEMENTS or
1716 // FAST_SMI_ONLY_ELEMENTS.
1717 inline bool HasFastSmiOrObjectElements();
1718 // Returns true if an object has any of the fast elements kinds.
1719 inline bool HasFastElements();
1720 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1722 inline bool HasFastDoubleElements();
1723 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1725 inline bool HasFastHoleyElements();
1726 inline bool HasSloppyArgumentsElements();
1727 inline bool HasDictionaryElements();
1729 inline bool HasExternalUint8ClampedElements();
1730 inline bool HasExternalArrayElements();
1731 inline bool HasExternalInt8Elements();
1732 inline bool HasExternalUint8Elements();
1733 inline bool HasExternalInt16Elements();
1734 inline bool HasExternalUint16Elements();
1735 inline bool HasExternalInt32Elements();
1736 inline bool HasExternalUint32Elements();
1737 inline bool HasExternalFloat32Elements();
1738 inline bool HasExternalFloat64Elements();
1740 inline bool HasFixedTypedArrayElements();
1742 inline bool HasFixedUint8ClampedElements();
1743 inline bool HasFixedArrayElements();
1744 inline bool HasFixedInt8Elements();
1745 inline bool HasFixedUint8Elements();
1746 inline bool HasFixedInt16Elements();
1747 inline bool HasFixedUint16Elements();
1748 inline bool HasFixedInt32Elements();
1749 inline bool HasFixedUint32Elements();
1750 inline bool HasFixedFloat32Elements();
1751 inline bool HasFixedFloat64Elements();
1753 bool HasFastArgumentsElements();
1754 bool HasDictionaryArgumentsElements();
1755 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1757 // Requires: HasFastElements().
1758 static Handle<FixedArray> EnsureWritableFastElements(
1759 Handle<JSObject> object);
1761 // Collects elements starting at index 0.
1762 // Undefined values are placed after non-undefined values.
1763 // Returns the number of non-undefined values.
1764 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1766 // As PrepareElementsForSort, but only on objects where elements is
1767 // a dictionary, and it will stay a dictionary. Collates undefined and
1768 // unexisting elements below limit from position zero of the elements.
1769 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1772 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1773 LookupIterator* it, Handle<Object> value);
1775 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1776 // grant an exemption to ExecutableAccessor callbacks in some cases.
1777 enum ExecutableAccessorInfoHandling {
1782 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1783 Handle<JSObject> object,
1785 Handle<Object> value,
1786 PropertyAttributes attributes,
1787 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1789 static void AddProperty(Handle<JSObject> object, Handle<Name> key,
1790 Handle<Object> value, PropertyAttributes attributes);
1792 // Extend the receiver with a single fast property appeared first in the
1793 // passed map. This also extends the property backing store if necessary.
1794 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1796 // Migrates the given object to a map whose field representations are the
1797 // lowest upper bound of all known representations for that field.
1798 static void MigrateInstance(Handle<JSObject> instance);
1800 // Migrates the given object only if the target map is already available,
1801 // or returns false if such a map is not yet available.
1802 static bool TryMigrateInstance(Handle<JSObject> instance);
1804 // Sets the property value in a normalized object given (key, value, details).
1805 // Handles the special representation of JS global objects.
1806 static void SetNormalizedProperty(Handle<JSObject> object,
1808 Handle<Object> value,
1809 PropertyDetails details);
1811 static void OptimizeAsPrototype(Handle<JSObject> object,
1812 PrototypeOptimizationMode mode);
1813 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1815 // Retrieve interceptors.
1816 InterceptorInfo* GetNamedInterceptor();
1817 InterceptorInfo* GetIndexedInterceptor();
1819 // Used from JSReceiver.
1820 MUST_USE_RESULT static Maybe<PropertyAttributes>
1821 GetPropertyAttributesWithInterceptor(Handle<JSObject> holder,
1822 Handle<Object> receiver,
1824 MUST_USE_RESULT static Maybe<PropertyAttributes>
1825 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1826 MUST_USE_RESULT static Maybe<PropertyAttributes>
1827 GetElementAttributeWithReceiver(Handle<JSObject> object,
1828 Handle<JSReceiver> receiver,
1829 uint32_t index, bool check_prototype);
1831 // Retrieves an AccessorPair property from the given object. Might return
1832 // undefined if the property doesn't exist or is of a different kind.
1833 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1834 Handle<JSObject> object,
1836 AccessorComponent component);
1838 // Defines an AccessorPair property on the given object.
1839 // TODO(mstarzinger): Rename to SetAccessor().
1840 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1842 Handle<Object> getter,
1843 Handle<Object> setter,
1844 PropertyAttributes attributes);
1846 // Defines an AccessorInfo property on the given object.
1847 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1848 Handle<JSObject> object,
1849 Handle<AccessorInfo> info);
1851 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1852 Handle<JSObject> object,
1853 Handle<Object> receiver,
1856 // Accessors for hidden properties object.
1858 // Hidden properties are not own properties of the object itself.
1859 // Instead they are stored in an auxiliary structure kept as an own
1860 // property with a special name Heap::hidden_string(). But if the
1861 // receiver is a JSGlobalProxy then the auxiliary object is a property
1862 // of its prototype, and if it's a detached proxy, then you can't have
1863 // hidden properties.
1865 // Sets a hidden property on this object. Returns this object if successful,
1866 // undefined if called on a detached proxy.
1867 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1869 Handle<Object> value);
1870 // Gets the value of a hidden property with the given key. Returns the hole
1871 // if the property doesn't exist (or if called on a detached proxy),
1872 // otherwise returns the value set for the key.
1873 Object* GetHiddenProperty(Handle<Name> key);
1874 // Deletes a hidden property. Deleting a non-existing property is
1875 // considered successful.
1876 static void DeleteHiddenProperty(Handle<JSObject> object,
1878 // Returns true if the object has a property with the hidden string as name.
1879 static bool HasHiddenProperties(Handle<JSObject> object);
1881 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1883 static inline void ValidateElements(Handle<JSObject> object);
1885 // Makes sure that this object can contain HeapObject as elements.
1886 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1888 // Makes sure that this object can contain the specified elements.
1889 static inline void EnsureCanContainElements(
1890 Handle<JSObject> object,
1893 EnsureElementsMode mode);
1894 static inline void EnsureCanContainElements(
1895 Handle<JSObject> object,
1896 Handle<FixedArrayBase> elements,
1898 EnsureElementsMode mode);
1899 static void EnsureCanContainElements(
1900 Handle<JSObject> object,
1901 Arguments* arguments,
1904 EnsureElementsMode mode);
1906 // Would we convert a fast elements array to dictionary mode given
1907 // an access at key?
1908 bool WouldConvertToSlowElements(Handle<Object> key);
1909 // Do we want to keep the elements in fast case when increasing the
1911 bool ShouldConvertToSlowElements(int new_capacity);
1912 // Returns true if the backing storage for the slow-case elements of
1913 // this object takes up nearly as much space as a fast-case backing
1914 // storage would. In that case the JSObject should have fast
1916 bool ShouldConvertToFastElements();
1917 // Returns true if the elements of JSObject contains only values that can be
1918 // represented in a FixedDoubleArray and has at least one value that can only
1919 // be represented as a double and not a Smi.
1920 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
1922 // Computes the new capacity when expanding the elements of a JSObject.
1923 static int NewElementsCapacity(int old_capacity) {
1924 // (old_capacity + 50%) + 16
1925 return old_capacity + (old_capacity >> 1) + 16;
1928 // These methods do not perform access checks!
1929 MUST_USE_RESULT static MaybeHandle<AccessorPair> GetOwnElementAccessorPair(
1930 Handle<JSObject> object, uint32_t index);
1932 MUST_USE_RESULT static MaybeHandle<Object> SetFastElement(
1933 Handle<JSObject> object,
1935 Handle<Object> value,
1936 StrictMode strict_mode,
1937 bool check_prototype);
1939 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElement(
1940 Handle<JSObject> object,
1942 Handle<Object> value,
1943 StrictMode strict_mode);
1945 // Empty handle is returned if the element cannot be set to the given value.
1946 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1947 Handle<JSObject> object,
1949 Handle<Object> value,
1950 PropertyAttributes attributes,
1951 StrictMode strict_mode,
1952 bool check_prototype = true,
1953 SetPropertyMode set_mode = SET_PROPERTY);
1955 // Returns the index'th element.
1956 // The undefined object if index is out of bounds.
1957 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithInterceptor(
1958 Handle<JSObject> object,
1959 Handle<Object> receiver,
1962 enum SetFastElementsCapacitySmiMode {
1965 kDontAllowSmiElements
1968 // Replace the elements' backing store with fast elements of the given
1969 // capacity. Update the length for JSArrays. Returns the new backing
1971 static Handle<FixedArray> SetFastElementsCapacityAndLength(
1972 Handle<JSObject> object,
1975 SetFastElementsCapacitySmiMode smi_mode);
1976 static void SetFastDoubleElementsCapacityAndLength(
1977 Handle<JSObject> object,
1981 // Lookup interceptors are used for handling properties controlled by host
1983 inline bool HasNamedInterceptor();
1984 inline bool HasIndexedInterceptor();
1986 // Computes the enumerable keys from interceptors. Used for debug mirrors and
1987 // by JSReceiver::GetKeys.
1988 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
1989 Handle<JSObject> object,
1990 Handle<JSReceiver> receiver);
1991 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
1992 Handle<JSObject> object,
1993 Handle<JSReceiver> receiver);
1995 // Support functions for v8 api (needed for correct interceptor behavior).
1996 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
1997 Handle<JSObject> object, Handle<Name> key);
1998 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
1999 Handle<JSObject> object, uint32_t index);
2000 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2001 Handle<JSObject> object, Handle<Name> key);
2003 // Get the header size for a JSObject. Used to compute the index of
2004 // internal fields as well as the number of internal fields.
2005 inline int GetHeaderSize();
2007 inline int GetInternalFieldCount();
2008 inline int GetInternalFieldOffset(int index);
2009 inline Object* GetInternalField(int index);
2010 inline void SetInternalField(int index, Object* value);
2011 inline void SetInternalField(int index, Smi* value);
2013 // Returns the number of properties on this object filtering out properties
2014 // with the specified attributes (ignoring interceptors).
2015 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2016 // Fill in details for properties into storage starting at the specified
2018 void GetOwnPropertyNames(
2019 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2021 // Returns the number of properties on this object filtering out properties
2022 // with the specified attributes (ignoring interceptors).
2023 int NumberOfOwnElements(PropertyAttributes filter);
2024 // Returns the number of enumerable elements (ignoring interceptors).
2025 int NumberOfEnumElements();
2026 // Returns the number of elements on this object filtering out elements
2027 // with the specified attributes (ignoring interceptors).
2028 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2029 // Count and fill in the enumerable elements into storage.
2030 // (storage->length() == NumberOfEnumElements()).
2031 // If storage is NULL, will count the elements without adding
2032 // them to any storage.
2033 // Returns the number of enumerable elements.
2034 int GetEnumElementKeys(FixedArray* storage);
2036 // Returns a new map with all transitions dropped from the object's current
2037 // map and the ElementsKind set.
2038 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2039 ElementsKind to_kind);
2040 static void TransitionElementsKind(Handle<JSObject> object,
2041 ElementsKind to_kind);
2043 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2045 // Convert the object to use the canonical dictionary
2046 // representation. If the object is expected to have additional properties
2047 // added this number can be indicated to have the backing store allocated to
2048 // an initial capacity for holding these properties.
2049 static void NormalizeProperties(Handle<JSObject> object,
2050 PropertyNormalizationMode mode,
2051 int expected_additional_properties);
2053 // Convert and update the elements backing store to be a
2054 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2055 static Handle<SeededNumberDictionary> NormalizeElements(
2056 Handle<JSObject> object);
2058 // Transform slow named properties to fast variants.
2059 static void MigrateSlowToFast(Handle<JSObject> object,
2060 int unused_property_fields);
2062 // Access fast-case object properties at index.
2063 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2064 Representation representation,
2066 inline Object* RawFastPropertyAt(FieldIndex index);
2067 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2068 void WriteToField(int descriptor, Object* value);
2070 // Access to in object properties.
2071 inline int GetInObjectPropertyOffset(int index);
2072 inline Object* InObjectPropertyAt(int index);
2073 inline Object* InObjectPropertyAtPut(int index,
2075 WriteBarrierMode mode
2076 = UPDATE_WRITE_BARRIER);
2078 // Set the object's prototype (only JSReceiver and null are allowed values).
2079 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2080 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2082 // Initializes the body after properties slot, properties slot is
2083 // initialized by set_properties. Fill the pre-allocated fields with
2084 // pre_allocated_value and the rest with filler_value.
2085 // Note: this call does not update write barrier, the caller is responsible
2086 // to ensure that |filler_value| can be collected without WB here.
2087 inline void InitializeBody(Map* map,
2088 Object* pre_allocated_value,
2089 Object* filler_value);
2091 // Check whether this object references another object
2092 bool ReferencesObject(Object* obj);
2094 // Disalow further properties to be added to the object.
2095 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2096 Handle<JSObject> object);
2098 // ES5 Object.freeze
2099 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2101 // Called the first time an object is observed with ES7 Object.observe.
2102 static void SetObserved(Handle<JSObject> object);
2105 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2107 static Handle<JSObject> Copy(Handle<JSObject> object);
2108 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2109 Handle<JSObject> object,
2110 AllocationSiteUsageContext* site_context,
2111 DeepCopyHints hints = kNoHints);
2112 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2113 Handle<JSObject> object,
2114 AllocationSiteCreationContext* site_context);
2116 static Handle<Object> GetDataProperty(Handle<JSObject> object,
2118 static Handle<Object> GetDataProperty(LookupIterator* it);
2120 DECLARE_CAST(JSObject)
2122 // Dispatched behavior.
2123 void JSObjectShortPrint(StringStream* accumulator);
2124 DECLARE_PRINTER(JSObject)
2125 DECLARE_VERIFIER(JSObject)
2127 void PrintProperties(std::ostream& os); // NOLINT
2128 void PrintElements(std::ostream& os); // NOLINT
2129 void PrintTransitions(std::ostream& os); // NOLINT
2132 static void PrintElementsTransition(
2133 FILE* file, Handle<JSObject> object,
2134 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2135 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2137 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2140 // Structure for collecting spill information about JSObjects.
2141 class SpillInformation {
2145 int number_of_objects_;
2146 int number_of_objects_with_fast_properties_;
2147 int number_of_objects_with_fast_elements_;
2148 int number_of_fast_used_fields_;
2149 int number_of_fast_unused_fields_;
2150 int number_of_slow_used_properties_;
2151 int number_of_slow_unused_properties_;
2152 int number_of_fast_used_elements_;
2153 int number_of_fast_unused_elements_;
2154 int number_of_slow_used_elements_;
2155 int number_of_slow_unused_elements_;
2158 void IncrementSpillStatistics(SpillInformation* info);
2162 // If a GC was caused while constructing this object, the elements pointer
2163 // may point to a one pointer filler map. The object won't be rooted, but
2164 // our heap verification code could stumble across it.
2165 bool ElementsAreSafeToExamine();
2168 Object* SlowReverseLookup(Object* value);
2170 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2171 // Also maximal value of JSArray's length property.
2172 static const uint32_t kMaxElementCount = 0xffffffffu;
2174 // Constants for heuristics controlling conversion of fast elements
2175 // to slow elements.
2177 // Maximal gap that can be introduced by adding an element beyond
2178 // the current elements length.
2179 static const uint32_t kMaxGap = 1024;
2181 // Maximal length of fast elements array that won't be checked for
2182 // being dense enough on expansion.
2183 static const int kMaxUncheckedFastElementsLength = 5000;
2185 // Same as above but for old arrays. This limit is more strict. We
2186 // don't want to be wasteful with long lived objects.
2187 static const int kMaxUncheckedOldFastElementsLength = 500;
2189 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2190 // permissible values (see the DCHECK in heap.cc).
2191 static const int kInitialMaxFastElementArray = 100000;
2193 // This constant applies only to the initial map of "$Object" aka
2194 // "global.Object" and not to arbitrary other JSObject maps.
2195 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2197 static const int kMaxInstanceSize = 255 * kPointerSize;
2198 // When extending the backing storage for property values, we increase
2199 // its size by more than the 1 entry necessary, so sequentially adding fields
2200 // to the same object requires fewer allocations and copies.
2201 static const int kFieldsAdded = 3;
2203 // Layout description.
2204 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2205 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2206 static const int kHeaderSize = kElementsOffset + kPointerSize;
2208 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2210 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2212 static inline int SizeOf(Map* map, HeapObject* object);
2215 Context* GetCreationContext();
2217 // Enqueue change record for Object.observe. May cause GC.
2218 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2219 Handle<JSObject> object, const char* type, Handle<Name> name,
2220 Handle<Object> old_value);
2223 friend class DictionaryElementsAccessor;
2224 friend class JSReceiver;
2225 friend class Object;
2227 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2228 static void MigrateFastToSlow(Handle<JSObject> object,
2229 Handle<Map> new_map,
2230 int expected_additional_properties);
2232 static void UpdateAllocationSite(Handle<JSObject> object,
2233 ElementsKind to_kind);
2235 // Used from Object::GetProperty().
2236 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2237 LookupIterator* it);
2239 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithCallback(
2240 Handle<JSObject> object,
2241 Handle<Object> receiver,
2242 Handle<Object> structure,
2244 Handle<Object> holder);
2246 MUST_USE_RESULT static Maybe<PropertyAttributes>
2247 GetElementAttributeWithInterceptor(Handle<JSObject> object,
2248 Handle<JSReceiver> receiver,
2249 uint32_t index, bool continue_search);
2251 // Queries indexed interceptor on an object for property attributes.
2253 // We determine property attributes as follows:
2254 // - if interceptor has a query callback, then the property attributes are
2255 // the result of query callback for index.
2256 // - otherwise if interceptor has a getter callback and it returns
2257 // non-empty value on index, then the property attributes is NONE
2258 // (property is present, and it is enumerable, configurable, writable)
2259 // - otherwise there are no property attributes that can be inferred for
2260 // interceptor, and this function returns ABSENT.
2261 MUST_USE_RESULT static Maybe<PropertyAttributes>
2262 GetElementAttributeFromInterceptor(Handle<JSObject> object,
2263 Handle<Object> receiver,
2266 MUST_USE_RESULT static Maybe<PropertyAttributes>
2267 GetElementAttributeWithoutInterceptor(Handle<JSObject> object,
2268 Handle<JSReceiver> receiver,
2270 bool continue_search);
2271 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithCallback(
2272 Handle<Object> object, Handle<Object> structure, uint32_t index,
2273 Handle<Object> value, Handle<JSObject> holder, StrictMode strict_mode);
2274 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithInterceptor(
2275 Handle<JSObject> object,
2277 Handle<Object> value,
2278 PropertyAttributes attributes,
2279 StrictMode strict_mode,
2280 bool check_prototype,
2281 SetPropertyMode set_mode);
2282 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithoutInterceptor(
2283 Handle<JSObject> object,
2285 Handle<Object> value,
2286 PropertyAttributes attributes,
2287 StrictMode strict_mode,
2288 bool check_prototype,
2289 SetPropertyMode set_mode);
2291 static MaybeHandle<Object> SetElementWithCallbackSetterInPrototypes(
2292 Handle<JSObject> object,
2294 Handle<Object> value,
2296 StrictMode strict_mode);
2297 MUST_USE_RESULT static MaybeHandle<Object> SetDictionaryElement(
2298 Handle<JSObject> object,
2300 Handle<Object> value,
2301 PropertyAttributes attributes,
2302 StrictMode strict_mode,
2303 bool check_prototype,
2304 SetPropertyMode set_mode = SET_PROPERTY);
2305 MUST_USE_RESULT static MaybeHandle<Object> SetFastDoubleElement(
2306 Handle<JSObject> object,
2308 Handle<Object> value,
2309 StrictMode strict_mode,
2310 bool check_prototype = true);
2312 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2313 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
2315 // Add a property to a slow-case object.
2316 static void AddSlowProperty(Handle<JSObject> object,
2318 Handle<Object> value,
2319 PropertyAttributes attributes);
2321 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
2322 Handle<JSObject> object,
2325 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2326 Handle<JSObject> holder, Handle<JSObject> receiver, Handle<Name> name);
2328 // Deletes the named property in a normalized object.
2329 static Handle<Object> DeleteNormalizedProperty(Handle<JSObject> object,
2333 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
2334 Handle<JSObject> object,
2337 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithInterceptor(
2338 Handle<JSObject> object,
2341 bool ReferencesObjectFromElements(FixedArray* elements,
2345 // Returns true if most of the elements backing storage is used.
2346 bool HasDenseElements();
2348 // Gets the current elements capacity and the number of used elements.
2349 void GetElementsCapacityAndUsage(int* capacity, int* used);
2351 static bool CanSetCallback(Handle<JSObject> object, Handle<Name> name);
2352 static void SetElementCallback(Handle<JSObject> object,
2354 Handle<Object> structure,
2355 PropertyAttributes attributes);
2356 static void SetPropertyCallback(Handle<JSObject> object,
2358 Handle<Object> structure,
2359 PropertyAttributes attributes);
2360 static void DefineElementAccessor(Handle<JSObject> object,
2362 Handle<Object> getter,
2363 Handle<Object> setter,
2364 PropertyAttributes attributes);
2366 // Return the hash table backing store or the inline stored identity hash,
2367 // whatever is found.
2368 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2370 // Return the hash table backing store for hidden properties. If there is no
2371 // backing store, allocate one.
2372 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2373 Handle<JSObject> object);
2375 // Set the hidden property backing store to either a hash table or
2376 // the inline-stored identity hash.
2377 static Handle<Object> SetHiddenPropertiesHashTable(
2378 Handle<JSObject> object,
2379 Handle<Object> value);
2381 MUST_USE_RESULT Object* GetIdentityHash();
2383 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2385 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2389 // Common superclass for FixedArrays that allow implementations to share
2390 // common accessors and some code paths.
2391 class FixedArrayBase: public HeapObject {
2393 // [length]: length of the array.
2394 inline int length() const;
2395 inline void set_length(int value);
2397 // Get and set the length using acquire loads and release stores.
2398 inline int synchronized_length() const;
2399 inline void synchronized_set_length(int value);
2401 DECLARE_CAST(FixedArrayBase)
2403 // Layout description.
2404 // Length is smi tagged when it is stored.
2405 static const int kLengthOffset = HeapObject::kHeaderSize;
2406 static const int kHeaderSize = kLengthOffset + kPointerSize;
2410 class FixedDoubleArray;
2411 class IncrementalMarking;
2414 // FixedArray describes fixed-sized arrays with element type Object*.
2415 class FixedArray: public FixedArrayBase {
2417 // Setter and getter for elements.
2418 inline Object* get(int index) const;
2419 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2420 // Setter that uses write barrier.
2421 inline void set(int index, Object* value);
2422 inline bool is_the_hole(int index);
2424 // Setter that doesn't need write barrier.
2425 inline void set(int index, Smi* value);
2426 // Setter with explicit barrier mode.
2427 inline void set(int index, Object* value, WriteBarrierMode mode);
2429 // Setters for frequently used oddballs located in old space.
2430 inline void set_undefined(int index);
2431 inline void set_null(int index);
2432 inline void set_the_hole(int index);
2434 inline Object** GetFirstElementAddress();
2435 inline bool ContainsOnlySmisOrHoles();
2437 // Gives access to raw memory which stores the array's data.
2438 inline Object** data_start();
2440 inline void FillWithHoles(int from, int to);
2442 // Shrink length and insert filler objects.
2443 void Shrink(int length);
2446 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2448 PretenureFlag pretenure = NOT_TENURED);
2450 // Add the elements of a JSArray to this FixedArray.
2451 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2452 Handle<FixedArray> content,
2453 Handle<JSObject> array);
2455 // Computes the union of keys and return the result.
2456 // Used for implementing "for (n in object) { }"
2457 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2458 Handle<FixedArray> first,
2459 Handle<FixedArray> second);
2461 // Copy a sub array from the receiver to dest.
2462 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2464 // Garbage collection support.
2465 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2467 // Code Generation support.
2468 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2470 // Garbage collection support.
2471 Object** RawFieldOfElementAt(int index) {
2472 return HeapObject::RawField(this, OffsetOfElementAt(index));
2475 DECLARE_CAST(FixedArray)
2477 // Maximal allowed size, in bytes, of a single FixedArray.
2478 // Prevents overflowing size computations, as well as extreme memory
2480 static const int kMaxSize = 128 * MB * kPointerSize;
2481 // Maximally allowed length of a FixedArray.
2482 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2484 // Dispatched behavior.
2485 DECLARE_PRINTER(FixedArray)
2486 DECLARE_VERIFIER(FixedArray)
2488 // Checks if two FixedArrays have identical contents.
2489 bool IsEqualTo(FixedArray* other);
2492 // Swap two elements in a pair of arrays. If this array and the
2493 // numbers array are the same object, the elements are only swapped
2495 void SwapPairs(FixedArray* numbers, int i, int j);
2497 // Sort prefix of this array and the numbers array as pairs wrt. the
2498 // numbers. If the numbers array and the this array are the same
2499 // object, the prefix of this array is sorted.
2500 void SortPairs(FixedArray* numbers, uint32_t len);
2502 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2504 static inline int SizeOf(Map* map, HeapObject* object) {
2505 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2510 // Set operation on FixedArray without using write barriers. Can
2511 // only be used for storing old space objects or smis.
2512 static inline void NoWriteBarrierSet(FixedArray* array,
2516 // Set operation on FixedArray without incremental write barrier. Can
2517 // only be used if the object is guaranteed to be white (whiteness witness
2519 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2524 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2526 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2530 // FixedDoubleArray describes fixed-sized arrays with element type double.
2531 class FixedDoubleArray: public FixedArrayBase {
2533 // Setter and getter for elements.
2534 inline double get_scalar(int index);
2535 inline int64_t get_representation(int index);
2536 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2537 inline void set(int index, double value);
2538 inline void set_the_hole(int index);
2540 // Checking for the hole.
2541 inline bool is_the_hole(int index);
2543 // Garbage collection support.
2544 inline static int SizeFor(int length) {
2545 return kHeaderSize + length * kDoubleSize;
2548 // Gives access to raw memory which stores the array's data.
2549 inline double* data_start();
2551 inline void FillWithHoles(int from, int to);
2553 // Code Generation support.
2554 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2556 inline static bool is_the_hole_nan(double value);
2557 inline static double hole_nan_as_double();
2558 inline static double canonical_not_the_hole_nan_as_double();
2560 DECLARE_CAST(FixedDoubleArray)
2562 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2563 // Prevents overflowing size computations, as well as extreme memory
2565 static const int kMaxSize = 512 * MB;
2566 // Maximally allowed length of a FixedArray.
2567 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2569 // Dispatched behavior.
2570 DECLARE_PRINTER(FixedDoubleArray)
2571 DECLARE_VERIFIER(FixedDoubleArray)
2574 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2578 // ConstantPoolArray describes a fixed-sized array containing constant pool
2581 // A ConstantPoolArray can be structured in two different ways depending upon
2582 // whether it is extended or small. The is_extended_layout() method can be used
2583 // to discover which layout the constant pool has.
2585 // The format of a small constant pool is:
2586 // [kSmallLayout1Offset] : Small section layout bitmap 1
2587 // [kSmallLayout2Offset] : Small section layout bitmap 2
2588 // [first_index(INT64, SMALL_SECTION)] : 64 bit entries
2590 // [first_index(CODE_PTR, SMALL_SECTION)] : code pointer entries
2592 // [first_index(HEAP_PTR, SMALL_SECTION)] : heap pointer entries
2594 // [first_index(INT32, SMALL_SECTION)] : 32 bit entries
2597 // If the constant pool has an extended layout, the extended section constant
2598 // pool also contains an extended section, which has the following format at
2599 // location get_extended_section_header_offset():
2600 // [kExtendedInt64CountOffset] : count of extended 64 bit entries
2601 // [kExtendedCodePtrCountOffset] : count of extended code pointers
2602 // [kExtendedHeapPtrCountOffset] : count of extended heap pointers
2603 // [kExtendedInt32CountOffset] : count of extended 32 bit entries
2604 // [first_index(INT64, EXTENDED_SECTION)] : 64 bit entries
2606 // [first_index(CODE_PTR, EXTENDED_SECTION)]: code pointer entries
2608 // [first_index(HEAP_PTR, EXTENDED_SECTION)]: heap pointer entries
2610 // [first_index(INT32, EXTENDED_SECTION)] : 32 bit entries
2613 class ConstantPoolArray: public HeapObject {
2615 enum WeakObjectState {
2617 WEAK_OBJECTS_IN_OPTIMIZED_CODE,
2626 // Number of types stored by the ConstantPoolArrays.
2632 enum LayoutSection {
2635 NUMBER_OF_LAYOUT_SECTIONS
2638 class NumberOfEntries BASE_EMBEDDED {
2640 inline NumberOfEntries() {
2641 for (int i = 0; i < NUMBER_OF_TYPES; i++) {
2642 element_counts_[i] = 0;
2646 inline NumberOfEntries(int int64_count, int code_ptr_count,
2647 int heap_ptr_count, int int32_count) {
2648 element_counts_[INT64] = int64_count;
2649 element_counts_[CODE_PTR] = code_ptr_count;
2650 element_counts_[HEAP_PTR] = heap_ptr_count;
2651 element_counts_[INT32] = int32_count;
2654 inline NumberOfEntries(ConstantPoolArray* array, LayoutSection section) {
2655 element_counts_[INT64] = array->number_of_entries(INT64, section);
2656 element_counts_[CODE_PTR] = array->number_of_entries(CODE_PTR, section);
2657 element_counts_[HEAP_PTR] = array->number_of_entries(HEAP_PTR, section);
2658 element_counts_[INT32] = array->number_of_entries(INT32, section);
2661 inline void increment(Type type);
2662 inline int equals(const NumberOfEntries& other) const;
2663 inline bool is_empty() const;
2664 inline int count_of(Type type) const;
2665 inline int base_of(Type type) const;
2666 inline int total_count() const;
2667 inline int are_in_range(int min, int max) const;
2670 int element_counts_[NUMBER_OF_TYPES];
2673 class Iterator BASE_EMBEDDED {
2675 inline Iterator(ConstantPoolArray* array, Type type)
2678 final_section_(array->final_section()),
2679 current_section_(SMALL_SECTION),
2680 next_index_(array->first_index(type, SMALL_SECTION)) {
2684 inline Iterator(ConstantPoolArray* array, Type type, LayoutSection section)
2687 final_section_(section),
2688 current_section_(section),
2689 next_index_(array->first_index(type, section)) {
2693 inline int next_index();
2694 inline bool is_finished();
2697 inline void update_section();
2698 ConstantPoolArray* array_;
2700 const LayoutSection final_section_;
2702 LayoutSection current_section_;
2706 // Getters for the first index, the last index and the count of entries of
2707 // a given type for a given layout section.
2708 inline int first_index(Type type, LayoutSection layout_section);
2709 inline int last_index(Type type, LayoutSection layout_section);
2710 inline int number_of_entries(Type type, LayoutSection layout_section);
2712 // Returns the type of the entry at the given index.
2713 inline Type get_type(int index);
2714 inline bool offset_is_type(int offset, Type type);
2716 // Setter and getter for pool elements.
2717 inline Address get_code_ptr_entry(int index);
2718 inline Object* get_heap_ptr_entry(int index);
2719 inline int64_t get_int64_entry(int index);
2720 inline int32_t get_int32_entry(int index);
2721 inline double get_int64_entry_as_double(int index);
2723 inline void set(int index, Address value);
2724 inline void set(int index, Object* value);
2725 inline void set(int index, int64_t value);
2726 inline void set(int index, double value);
2727 inline void set(int index, int32_t value);
2729 // Setters which take a raw offset rather than an index (for code generation).
2730 inline void set_at_offset(int offset, int32_t value);
2731 inline void set_at_offset(int offset, int64_t value);
2732 inline void set_at_offset(int offset, double value);
2733 inline void set_at_offset(int offset, Address value);
2734 inline void set_at_offset(int offset, Object* value);
2736 // Setter and getter for weak objects state
2737 inline void set_weak_object_state(WeakObjectState state);
2738 inline WeakObjectState get_weak_object_state();
2740 // Returns true if the constant pool has an extended layout, false if it has
2741 // only the small layout.
2742 inline bool is_extended_layout();
2744 // Returns the last LayoutSection in this constant pool array.
2745 inline LayoutSection final_section();
2747 // Set up initial state for a small layout constant pool array.
2748 inline void Init(const NumberOfEntries& small);
2750 // Set up initial state for an extended layout constant pool array.
2751 inline void InitExtended(const NumberOfEntries& small,
2752 const NumberOfEntries& extended);
2754 // Clears the pointer entries with GC safe values.
2755 void ClearPtrEntries(Isolate* isolate);
2757 // returns the total number of entries in the constant pool array.
2758 inline int length();
2760 // Garbage collection support.
2764 inline static int MaxInt64Offset(int number_of_int64) {
2765 return kFirstEntryOffset + (number_of_int64 * kInt64Size);
2768 inline static int SizeFor(const NumberOfEntries& small) {
2769 int size = kFirstEntryOffset +
2770 (small.count_of(INT64) * kInt64Size) +
2771 (small.count_of(CODE_PTR) * kPointerSize) +
2772 (small.count_of(HEAP_PTR) * kPointerSize) +
2773 (small.count_of(INT32) * kInt32Size);
2774 return RoundUp(size, kPointerSize);
2777 inline static int SizeForExtended(const NumberOfEntries& small,
2778 const NumberOfEntries& extended) {
2779 int size = SizeFor(small);
2780 size = RoundUp(size, kInt64Size); // Align extended header to 64 bits.
2781 size += kExtendedFirstOffset +
2782 (extended.count_of(INT64) * kInt64Size) +
2783 (extended.count_of(CODE_PTR) * kPointerSize) +
2784 (extended.count_of(HEAP_PTR) * kPointerSize) +
2785 (extended.count_of(INT32) * kInt32Size);
2786 return RoundUp(size, kPointerSize);
2789 inline static int entry_size(Type type) {
2797 return kPointerSize;
2804 // Code Generation support.
2805 inline int OffsetOfElementAt(int index) {
2807 LayoutSection section;
2808 if (is_extended_layout() && index >= first_extended_section_index()) {
2809 section = EXTENDED_SECTION;
2810 offset = get_extended_section_header_offset() + kExtendedFirstOffset;
2812 section = SMALL_SECTION;
2813 offset = kFirstEntryOffset;
2816 // Add offsets for the preceding type sections.
2817 DCHECK(index <= last_index(LAST_TYPE, section));
2818 for (Type type = FIRST_TYPE; index > last_index(type, section);
2819 type = next_type(type)) {
2820 offset += entry_size(type) * number_of_entries(type, section);
2823 // Add offset for the index in it's type.
2824 Type type = get_type(index);
2825 offset += entry_size(type) * (index - first_index(type, section));
2829 DECLARE_CAST(ConstantPoolArray)
2831 // Garbage collection support.
2832 Object** RawFieldOfElementAt(int index) {
2833 return HeapObject::RawField(this, OffsetOfElementAt(index));
2836 // Small Layout description.
2837 static const int kSmallLayout1Offset = HeapObject::kHeaderSize;
2838 static const int kSmallLayout2Offset = kSmallLayout1Offset + kInt32Size;
2839 static const int kHeaderSize = kSmallLayout2Offset + kInt32Size;
2840 static const int kFirstEntryOffset = ROUND_UP(kHeaderSize, kInt64Size);
2842 static const int kSmallLayoutCountBits = 10;
2843 static const int kMaxSmallEntriesPerType = (1 << kSmallLayoutCountBits) - 1;
2845 // Fields in kSmallLayout1Offset.
2846 class Int64CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2847 class CodePtrCountField: public BitField<int, 11, kSmallLayoutCountBits> {};
2848 class HeapPtrCountField: public BitField<int, 21, kSmallLayoutCountBits> {};
2849 class IsExtendedField: public BitField<bool, 31, 1> {};
2851 // Fields in kSmallLayout2Offset.
2852 class Int32CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2853 class TotalCountField: public BitField<int, 11, 12> {};
2854 class WeakObjectStateField: public BitField<WeakObjectState, 23, 2> {};
2856 // Extended layout description, which starts at
2857 // get_extended_section_header_offset().
2858 static const int kExtendedInt64CountOffset = 0;
2859 static const int kExtendedCodePtrCountOffset =
2860 kExtendedInt64CountOffset + kInt32Size;
2861 static const int kExtendedHeapPtrCountOffset =
2862 kExtendedCodePtrCountOffset + kInt32Size;
2863 static const int kExtendedInt32CountOffset =
2864 kExtendedHeapPtrCountOffset + kInt32Size;
2865 static const int kExtendedFirstOffset =
2866 kExtendedInt32CountOffset + kInt32Size;
2868 // Dispatched behavior.
2869 void ConstantPoolIterateBody(ObjectVisitor* v);
2871 DECLARE_PRINTER(ConstantPoolArray)
2872 DECLARE_VERIFIER(ConstantPoolArray)
2875 inline int first_extended_section_index();
2876 inline int get_extended_section_header_offset();
2878 inline static Type next_type(Type type) {
2879 DCHECK(type >= FIRST_TYPE && type < NUMBER_OF_TYPES);
2880 int type_int = static_cast<int>(type);
2881 return static_cast<Type>(++type_int);
2884 DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
2888 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2889 // The format of the these objects is:
2890 // [0]: Number of descriptors
2891 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2892 // [0]: pointer to fixed array with enum cache
2893 // [1]: either Smi(0) or pointer to fixed array with indices
2895 // [2 + number of descriptors * kDescriptorSize]: start of slack
2896 class DescriptorArray: public FixedArray {
2898 // Returns true for both shared empty_descriptor_array and for smis, which the
2899 // map uses to encode additional bit fields when the descriptor array is not
2901 inline bool IsEmpty();
2903 // Returns the number of descriptors in the array.
2904 int number_of_descriptors() {
2905 DCHECK(length() >= kFirstIndex || IsEmpty());
2907 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2910 int number_of_descriptors_storage() {
2912 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2915 int NumberOfSlackDescriptors() {
2916 return number_of_descriptors_storage() - number_of_descriptors();
2919 inline void SetNumberOfDescriptors(int number_of_descriptors);
2920 inline int number_of_entries() { return number_of_descriptors(); }
2922 bool HasEnumCache() {
2923 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2926 void CopyEnumCacheFrom(DescriptorArray* array) {
2927 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2930 FixedArray* GetEnumCache() {
2931 DCHECK(HasEnumCache());
2932 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2933 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2936 bool HasEnumIndicesCache() {
2937 if (IsEmpty()) return false;
2938 Object* object = get(kEnumCacheIndex);
2939 if (object->IsSmi()) return false;
2940 FixedArray* bridge = FixedArray::cast(object);
2941 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2944 FixedArray* GetEnumIndicesCache() {
2945 DCHECK(HasEnumIndicesCache());
2946 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2947 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2950 Object** GetEnumCacheSlot() {
2951 DCHECK(HasEnumCache());
2952 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2956 void ClearEnumCache();
2958 // Initialize or change the enum cache,
2959 // using the supplied storage for the small "bridge".
2960 void SetEnumCache(FixedArray* bridge_storage,
2961 FixedArray* new_cache,
2962 Object* new_index_cache);
2964 bool CanHoldValue(int descriptor, Object* value);
2966 // Accessors for fetching instance descriptor at descriptor number.
2967 inline Name* GetKey(int descriptor_number);
2968 inline Object** GetKeySlot(int descriptor_number);
2969 inline Object* GetValue(int descriptor_number);
2970 inline void SetValue(int descriptor_number, Object* value);
2971 inline Object** GetValueSlot(int descriptor_number);
2972 static inline int GetValueOffset(int descriptor_number);
2973 inline Object** GetDescriptorStartSlot(int descriptor_number);
2974 inline Object** GetDescriptorEndSlot(int descriptor_number);
2975 inline PropertyDetails GetDetails(int descriptor_number);
2976 inline PropertyType GetType(int descriptor_number);
2977 inline int GetFieldIndex(int descriptor_number);
2978 inline HeapType* GetFieldType(int descriptor_number);
2979 inline Object* GetConstant(int descriptor_number);
2980 inline Object* GetCallbacksObject(int descriptor_number);
2981 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2983 inline Name* GetSortedKey(int descriptor_number);
2984 inline int GetSortedKeyIndex(int descriptor_number);
2985 inline void SetSortedKey(int pointer, int descriptor_number);
2986 inline void SetRepresentation(int descriptor_number,
2987 Representation representation);
2989 // Accessor for complete descriptor.
2990 inline void Get(int descriptor_number, Descriptor* desc);
2991 inline void Set(int descriptor_number, Descriptor* desc);
2992 void Replace(int descriptor_number, Descriptor* descriptor);
2994 // Append automatically sets the enumeration index. This should only be used
2995 // to add descriptors in bulk at the end, followed by sorting the descriptor
2997 inline void Append(Descriptor* desc);
2999 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
3000 int enumeration_index,
3003 static Handle<DescriptorArray> CopyUpToAddAttributes(
3004 Handle<DescriptorArray> desc,
3005 int enumeration_index,
3006 PropertyAttributes attributes,
3009 // Sort the instance descriptors by the hash codes of their keys.
3012 // Search the instance descriptors for given name.
3013 INLINE(int Search(Name* name, int number_of_own_descriptors));
3015 // As the above, but uses DescriptorLookupCache and updates it when
3017 INLINE(int SearchWithCache(Name* name, Map* map));
3019 // Allocates a DescriptorArray, but returns the singleton
3020 // empty descriptor array object if number_of_descriptors is 0.
3021 static Handle<DescriptorArray> Allocate(Isolate* isolate,
3022 int number_of_descriptors,
3025 DECLARE_CAST(DescriptorArray)
3027 // Constant for denoting key was not found.
3028 static const int kNotFound = -1;
3030 static const int kDescriptorLengthIndex = 0;
3031 static const int kEnumCacheIndex = 1;
3032 static const int kFirstIndex = 2;
3034 // The length of the "bridge" to the enum cache.
3035 static const int kEnumCacheBridgeLength = 2;
3036 static const int kEnumCacheBridgeCacheIndex = 0;
3037 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3039 // Layout description.
3040 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3041 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3042 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3044 // Layout description for the bridge array.
3045 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3047 // Layout of descriptor.
3048 static const int kDescriptorKey = 0;
3049 static const int kDescriptorDetails = 1;
3050 static const int kDescriptorValue = 2;
3051 static const int kDescriptorSize = 3;
3054 // For our gdb macros, we should perhaps change these in the future.
3057 // Print all the descriptors.
3058 void PrintDescriptors(std::ostream& os); // NOLINT
3062 // Is the descriptor array sorted and without duplicates?
3063 bool IsSortedNoDuplicates(int valid_descriptors = -1);
3065 // Is the descriptor array consistent with the back pointers in targets?
3066 bool IsConsistentWithBackPointers(Map* current_map);
3068 // Are two DescriptorArrays equal?
3069 bool IsEqualTo(DescriptorArray* other);
3072 // Returns the fixed array length required to hold number_of_descriptors
3074 static int LengthFor(int number_of_descriptors) {
3075 return ToKeyIndex(number_of_descriptors);
3079 // WhitenessWitness is used to prove that a descriptor array is white
3080 // (unmarked), so incremental write barriers can be skipped because the
3081 // marking invariant cannot be broken and slots pointing into evacuation
3082 // candidates will be discovered when the object is scanned. A witness is
3083 // always stack-allocated right after creating an array. By allocating a
3084 // witness, incremental marking is globally disabled. The witness is then
3085 // passed along wherever needed to statically prove that the array is known to
3087 class WhitenessWitness {
3089 inline explicit WhitenessWitness(DescriptorArray* array);
3090 inline ~WhitenessWitness();
3093 IncrementalMarking* marking_;
3096 // An entry in a DescriptorArray, represented as an (array, index) pair.
3099 inline explicit Entry(DescriptorArray* descs, int index) :
3100 descs_(descs), index_(index) { }
3102 inline PropertyType type() { return descs_->GetType(index_); }
3103 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3106 DescriptorArray* descs_;
3110 // Conversion from descriptor number to array indices.
3111 static int ToKeyIndex(int descriptor_number) {
3112 return kFirstIndex +
3113 (descriptor_number * kDescriptorSize) +
3117 static int ToDetailsIndex(int descriptor_number) {
3118 return kFirstIndex +
3119 (descriptor_number * kDescriptorSize) +
3123 static int ToValueIndex(int descriptor_number) {
3124 return kFirstIndex +
3125 (descriptor_number * kDescriptorSize) +
3129 // Transfer a complete descriptor from the src descriptor array to this
3130 // descriptor array.
3131 void CopyFrom(int index,
3132 DescriptorArray* src,
3133 const WhitenessWitness&);
3135 inline void Set(int descriptor_number,
3137 const WhitenessWitness&);
3139 // Swap first and second descriptor.
3140 inline void SwapSortedKeys(int first, int second);
3142 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3146 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3148 template <SearchMode search_mode, typename T>
3149 inline int Search(T* array, Name* name, int valid_entries = 0,
3150 int* out_insertion_index = NULL);
3153 // HashTable is a subclass of FixedArray that implements a hash table
3154 // that uses open addressing and quadratic probing.
3156 // In order for the quadratic probing to work, elements that have not
3157 // yet been used and elements that have been deleted are
3158 // distinguished. Probing continues when deleted elements are
3159 // encountered and stops when unused elements are encountered.
3161 // - Elements with key == undefined have not been used yet.
3162 // - Elements with key == the_hole have been deleted.
3164 // The hash table class is parameterized with a Shape and a Key.
3165 // Shape must be a class with the following interface:
3166 // class ExampleShape {
3168 // // Tells whether key matches other.
3169 // static bool IsMatch(Key key, Object* other);
3170 // // Returns the hash value for key.
3171 // static uint32_t Hash(Key key);
3172 // // Returns the hash value for object.
3173 // static uint32_t HashForObject(Key key, Object* object);
3174 // // Convert key to an object.
3175 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
3176 // // The prefix size indicates number of elements in the beginning
3177 // // of the backing storage.
3178 // static const int kPrefixSize = ..;
3179 // // The Element size indicates number of elements per entry.
3180 // static const int kEntrySize = ..;
3182 // The prefix size indicates an amount of memory in the
3183 // beginning of the backing storage that can be used for non-element
3184 // information by subclasses.
3186 template<typename Key>
3189 static const bool UsesSeed = false;
3190 static uint32_t Hash(Key key) { return 0; }
3191 static uint32_t SeededHash(Key key, uint32_t seed) {
3195 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3196 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3198 return HashForObject(key, object);
3202 template<typename Derived, typename Shape, typename Key>
3203 class HashTable: public FixedArray {
3206 inline uint32_t Hash(Key key) {
3207 if (Shape::UsesSeed) {
3208 return Shape::SeededHash(key, GetHeap()->HashSeed());
3210 return Shape::Hash(key);
3214 inline uint32_t HashForObject(Key key, Object* object) {
3215 if (Shape::UsesSeed) {
3216 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3218 return Shape::HashForObject(key, object);
3222 // Returns the number of elements in the hash table.
3223 int NumberOfElements() {
3224 return Smi::cast(get(kNumberOfElementsIndex))->value();
3227 // Returns the number of deleted elements in the hash table.
3228 int NumberOfDeletedElements() {
3229 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3232 // Returns the capacity of the hash table.
3234 return Smi::cast(get(kCapacityIndex))->value();
3237 // ElementAdded should be called whenever an element is added to a
3239 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3241 // ElementRemoved should be called whenever an element is removed from
3243 void ElementRemoved() {
3244 SetNumberOfElements(NumberOfElements() - 1);
3245 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3247 void ElementsRemoved(int n) {
3248 SetNumberOfElements(NumberOfElements() - n);
3249 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3252 // Returns a new HashTable object.
3253 MUST_USE_RESULT static Handle<Derived> New(
3255 int at_least_space_for,
3256 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3257 PretenureFlag pretenure = NOT_TENURED);
3259 // Computes the required capacity for a table holding the given
3260 // number of elements. May be more than HashTable::kMaxCapacity.
3261 static int ComputeCapacity(int at_least_space_for);
3263 // Returns the key at entry.
3264 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3266 // Tells whether k is a real key. The hole and undefined are not allowed
3267 // as keys and can be used to indicate missing or deleted elements.
3268 bool IsKey(Object* k) {
3269 return !k->IsTheHole() && !k->IsUndefined();
3272 // Garbage collection support.
3273 void IteratePrefix(ObjectVisitor* visitor);
3274 void IterateElements(ObjectVisitor* visitor);
3276 DECLARE_CAST(HashTable)
3278 // Compute the probe offset (quadratic probing).
3279 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3280 return (n + n * n) >> 1;
3283 static const int kNumberOfElementsIndex = 0;
3284 static const int kNumberOfDeletedElementsIndex = 1;
3285 static const int kCapacityIndex = 2;
3286 static const int kPrefixStartIndex = 3;
3287 static const int kElementsStartIndex =
3288 kPrefixStartIndex + Shape::kPrefixSize;
3289 static const int kEntrySize = Shape::kEntrySize;
3290 static const int kElementsStartOffset =
3291 kHeaderSize + kElementsStartIndex * kPointerSize;
3292 static const int kCapacityOffset =
3293 kHeaderSize + kCapacityIndex * kPointerSize;
3295 // Constant used for denoting a absent entry.
3296 static const int kNotFound = -1;
3298 // Maximal capacity of HashTable. Based on maximal length of underlying
3299 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3301 static const int kMaxCapacity =
3302 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3304 // Find entry for key otherwise return kNotFound.
3305 inline int FindEntry(Key key);
3306 int FindEntry(Isolate* isolate, Key key);
3308 // Rehashes the table in-place.
3309 void Rehash(Key key);
3312 friend class ObjectHashTable;
3314 // Find the entry at which to insert element with the given key that
3315 // has the given hash value.
3316 uint32_t FindInsertionEntry(uint32_t hash);
3318 // Returns the index for an entry (of the key)
3319 static inline int EntryToIndex(int entry) {
3320 return (entry * kEntrySize) + kElementsStartIndex;
3323 // Update the number of elements in the hash table.
3324 void SetNumberOfElements(int nof) {
3325 set(kNumberOfElementsIndex, Smi::FromInt(nof));
3328 // Update the number of deleted elements in the hash table.
3329 void SetNumberOfDeletedElements(int nod) {
3330 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3333 // Sets the capacity of the hash table.
3334 void SetCapacity(int capacity) {
3335 // To scale a computed hash code to fit within the hash table, we
3336 // use bit-wise AND with a mask, so the capacity must be positive
3338 DCHECK(capacity > 0);
3339 DCHECK(capacity <= kMaxCapacity);
3340 set(kCapacityIndex, Smi::FromInt(capacity));
3344 // Returns probe entry.
3345 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3346 DCHECK(base::bits::IsPowerOfTwo32(size));
3347 return (hash + GetProbeOffset(number)) & (size - 1);
3350 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3351 return hash & (size - 1);
3354 inline static uint32_t NextProbe(
3355 uint32_t last, uint32_t number, uint32_t size) {
3356 return (last + number) & (size - 1);
3359 // Attempt to shrink hash table after removal of key.
3360 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3362 // Ensure enough space for n additional elements.
3363 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3364 Handle<Derived> table,
3367 PretenureFlag pretenure = NOT_TENURED);
3370 // Returns _expected_ if one of entries given by the first _probe_ probes is
3371 // equal to _expected_. Otherwise, returns the entry given by the probe
3373 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3375 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3377 // Rehashes this hash-table into the new table.
3378 void Rehash(Handle<Derived> new_table, Key key);
3382 // HashTableKey is an abstract superclass for virtual key behavior.
3383 class HashTableKey {
3385 // Returns whether the other object matches this key.
3386 virtual bool IsMatch(Object* other) = 0;
3387 // Returns the hash value for this key.
3388 virtual uint32_t Hash() = 0;
3389 // Returns the hash value for object.
3390 virtual uint32_t HashForObject(Object* key) = 0;
3391 // Returns the key object for storing into the hash table.
3392 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3394 virtual ~HashTableKey() {}
3398 class StringTableShape : public BaseShape<HashTableKey*> {
3400 static inline bool IsMatch(HashTableKey* key, Object* value) {
3401 return key->IsMatch(value);
3404 static inline uint32_t Hash(HashTableKey* key) {
3408 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3409 return key->HashForObject(object);
3412 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3414 static const int kPrefixSize = 0;
3415 static const int kEntrySize = 1;
3418 class SeqOneByteString;
3422 // No special elements in the prefix and the element size is 1
3423 // because only the string itself (the key) needs to be stored.
3424 class StringTable: public HashTable<StringTable,
3428 // Find string in the string table. If it is not there yet, it is
3429 // added. The return value is the string found.
3430 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3431 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3433 // Tries to internalize given string and returns string handle on success
3434 // or an empty handle otherwise.
3435 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3437 Handle<String> string);
3439 // Looks up a string that is equal to the given string and returns
3440 // string handle if it is found, or an empty handle otherwise.
3441 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3443 Handle<String> str);
3444 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3449 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3451 DECLARE_CAST(StringTable)
3454 template <bool seq_one_byte>
3455 friend class JsonParser;
3457 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3461 class MapCacheShape : public BaseShape<HashTableKey*> {
3463 static inline bool IsMatch(HashTableKey* key, Object* value) {
3464 return key->IsMatch(value);
3467 static inline uint32_t Hash(HashTableKey* key) {
3471 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3472 return key->HashForObject(object);
3475 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3477 static const int kPrefixSize = 0;
3478 static const int kEntrySize = 2;
3484 // Maps keys that are a fixed array of unique names to a map.
3485 // Used for canonicalize maps for object literals.
3486 class MapCache: public HashTable<MapCache, MapCacheShape, HashTableKey*> {
3488 // Find cached value for a name key, otherwise return null.
3489 Object* Lookup(FixedArray* key);
3490 static Handle<MapCache> Put(
3491 Handle<MapCache> map_cache, Handle<FixedArray> key, Handle<Map> value);
3492 DECLARE_CAST(MapCache)
3495 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
3499 template <typename Derived, typename Shape, typename Key>
3500 class Dictionary: public HashTable<Derived, Shape, Key> {
3502 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3505 // Returns the value at entry.
3506 Object* ValueAt(int entry) {
3507 return this->get(DerivedHashTable::EntryToIndex(entry) + 1);
3510 // Set the value for entry.
3511 void ValueAtPut(int entry, Object* value) {
3512 this->set(DerivedHashTable::EntryToIndex(entry) + 1, value);
3515 // Returns the property details for the property at entry.
3516 PropertyDetails DetailsAt(int entry) {
3517 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3518 return PropertyDetails(
3519 Smi::cast(this->get(DerivedHashTable::EntryToIndex(entry) + 2)));
3522 // Set the details for entry.
3523 void DetailsAtPut(int entry, PropertyDetails value) {
3524 this->set(DerivedHashTable::EntryToIndex(entry) + 2, value.AsSmi());
3528 void CopyValuesTo(FixedArray* elements);
3530 // Delete a property from the dictionary.
3531 static Handle<Object> DeleteProperty(
3532 Handle<Derived> dictionary,
3534 JSObject::DeleteMode mode);
3536 // Attempt to shrink the dictionary after deletion of key.
3537 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3538 Handle<Derived> dictionary,
3540 return DerivedHashTable::Shrink(dictionary, key);
3543 // Returns the number of elements in the dictionary filtering out properties
3544 // with the specified attributes.
3545 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3547 // Returns the number of enumerable elements in the dictionary.
3548 int NumberOfEnumElements();
3550 // Returns true if the dictionary contains any elements that are non-writable,
3551 // non-configurable, non-enumerable, or have getters/setters.
3552 bool HasComplexElements();
3554 enum SortMode { UNSORTED, SORTED };
3555 // Copies keys to preallocated fixed array.
3556 void CopyKeysTo(FixedArray* storage,
3557 PropertyAttributes filter,
3558 SortMode sort_mode);
3559 // Fill in details for properties into storage.
3560 void CopyKeysTo(FixedArray* storage,
3562 PropertyAttributes filter,
3563 SortMode sort_mode);
3565 // Accessors for next enumeration index.
3566 void SetNextEnumerationIndex(int index) {
3568 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3571 int NextEnumerationIndex() {
3572 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3575 // Creates a new dictionary.
3576 MUST_USE_RESULT static Handle<Derived> New(
3578 int at_least_space_for,
3579 PretenureFlag pretenure = NOT_TENURED);
3581 // Ensure enough space for n additional elements.
3582 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3585 void Print(std::ostream& os); // NOLINT
3587 // Returns the key (slow).
3588 Object* SlowReverseLookup(Object* value);
3590 // Sets the entry to (key, value) pair.
3591 inline void SetEntry(int entry,
3593 Handle<Object> value);
3594 inline void SetEntry(int entry,
3596 Handle<Object> value,
3597 PropertyDetails details);
3599 MUST_USE_RESULT static Handle<Derived> Add(
3600 Handle<Derived> dictionary,
3602 Handle<Object> value,
3603 PropertyDetails details);
3605 // Returns iteration indices array for the |dictionary|.
3606 // Values are direct indices in the |HashTable| array.
3607 static Handle<FixedArray> BuildIterationIndicesArray(
3608 Handle<Derived> dictionary);
3611 // Generic at put operation.
3612 MUST_USE_RESULT static Handle<Derived> AtPut(
3613 Handle<Derived> dictionary,
3615 Handle<Object> value);
3617 // Add entry to dictionary.
3618 static void AddEntry(
3619 Handle<Derived> dictionary,
3621 Handle<Object> value,
3622 PropertyDetails details,
3625 // Generate new enumeration indices to avoid enumeration index overflow.
3626 // Returns iteration indices array for the |dictionary|.
3627 static Handle<FixedArray> GenerateNewEnumerationIndices(
3628 Handle<Derived> dictionary);
3629 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3630 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3634 class NameDictionaryShape : public BaseShape<Handle<Name> > {
3636 static inline bool IsMatch(Handle<Name> key, Object* other);
3637 static inline uint32_t Hash(Handle<Name> key);
3638 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3639 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3640 static const int kPrefixSize = 2;
3641 static const int kEntrySize = 3;
3642 static const bool kIsEnumerable = true;
3646 class NameDictionary: public Dictionary<NameDictionary,
3647 NameDictionaryShape,
3650 NameDictionary, NameDictionaryShape, Handle<Name> > DerivedDictionary;
3653 DECLARE_CAST(NameDictionary)
3655 // Copies enumerable keys to preallocated fixed array.
3656 void CopyEnumKeysTo(FixedArray* storage);
3657 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3658 Handle<NameDictionary> dictionary);
3660 // Find entry for key, otherwise return kNotFound. Optimized version of
3661 // HashTable::FindEntry.
3662 int FindEntry(Handle<Name> key);
3666 class NumberDictionaryShape : public BaseShape<uint32_t> {
3668 static inline bool IsMatch(uint32_t key, Object* other);
3669 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3670 static const int kEntrySize = 3;
3671 static const bool kIsEnumerable = false;
3675 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3677 static const bool UsesSeed = true;
3678 static const int kPrefixSize = 2;
3680 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3681 static inline uint32_t SeededHashForObject(uint32_t key,
3687 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3689 static const int kPrefixSize = 0;
3691 static inline uint32_t Hash(uint32_t key);
3692 static inline uint32_t HashForObject(uint32_t key, Object* object);
3696 class SeededNumberDictionary
3697 : public Dictionary<SeededNumberDictionary,
3698 SeededNumberDictionaryShape,
3701 DECLARE_CAST(SeededNumberDictionary)
3703 // Type specific at put (default NONE attributes is used when adding).
3704 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3705 Handle<SeededNumberDictionary> dictionary,
3707 Handle<Object> value);
3708 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3709 Handle<SeededNumberDictionary> dictionary,
3711 Handle<Object> value,
3712 PropertyDetails details);
3714 // Set an existing entry or add a new one if needed.
3715 // Return the updated dictionary.
3716 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3717 Handle<SeededNumberDictionary> dictionary,
3719 Handle<Object> value,
3720 PropertyDetails details);
3722 void UpdateMaxNumberKey(uint32_t key);
3724 // If slow elements are required we will never go back to fast-case
3725 // for the elements kept in this dictionary. We require slow
3726 // elements if an element has been added at an index larger than
3727 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3728 // when defining a getter or setter with a number key.
3729 inline bool requires_slow_elements();
3730 inline void set_requires_slow_elements();
3732 // Get the value of the max number key that has been added to this
3733 // dictionary. max_number_key can only be called if
3734 // requires_slow_elements returns false.
3735 inline uint32_t max_number_key();
3738 static const int kRequiresSlowElementsMask = 1;
3739 static const int kRequiresSlowElementsTagSize = 1;
3740 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3744 class UnseededNumberDictionary
3745 : public Dictionary<UnseededNumberDictionary,
3746 UnseededNumberDictionaryShape,
3749 DECLARE_CAST(UnseededNumberDictionary)
3751 // Type specific at put (default NONE attributes is used when adding).
3752 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3753 Handle<UnseededNumberDictionary> dictionary,
3755 Handle<Object> value);
3756 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3757 Handle<UnseededNumberDictionary> dictionary,
3759 Handle<Object> value);
3761 // Set an existing entry or add a new one if needed.
3762 // Return the updated dictionary.
3763 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3764 Handle<UnseededNumberDictionary> dictionary,
3766 Handle<Object> value);
3770 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3772 static inline bool IsMatch(Handle<Object> key, Object* other);
3773 static inline uint32_t Hash(Handle<Object> key);
3774 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3775 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3776 static const int kPrefixSize = 0;
3777 static const int kEntrySize = 2;
3781 // ObjectHashTable maps keys that are arbitrary objects to object values by
3782 // using the identity hash of the key for hashing purposes.
3783 class ObjectHashTable: public HashTable<ObjectHashTable,
3784 ObjectHashTableShape,
3787 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3789 DECLARE_CAST(ObjectHashTable)
3791 // Attempt to shrink hash table after removal of key.
3792 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3793 Handle<ObjectHashTable> table,
3794 Handle<Object> key);
3796 // Looks up the value associated with the given key. The hole value is
3797 // returned in case the key is not present.
3798 Object* Lookup(Handle<Object> key);
3800 // Adds (or overwrites) the value associated with the given key.
3801 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3803 Handle<Object> value);
3805 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3806 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3811 friend class MarkCompactCollector;
3813 void AddEntry(int entry, Object* key, Object* value);
3814 void RemoveEntry(int entry);
3816 // Returns the index to the value of an entry.
3817 static inline int EntryToValueIndex(int entry) {
3818 return EntryToIndex(entry) + 1;
3823 // OrderedHashTable is a HashTable with Object keys that preserves
3824 // insertion order. There are Map and Set interfaces (OrderedHashMap
3825 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3827 // Only Object* keys are supported, with Object::SameValueZero() used as the
3828 // equality operator and Object::GetHash() for the hash function.
3830 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3831 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3832 // Originally attributed to Tyler Close.
3835 // [0]: bucket count
3836 // [1]: element count
3837 // [2]: deleted element count
3838 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3839 // offset into the data table (see below) where the
3840 // first item in this bucket is stored.
3841 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3842 // Capacity() * kEntrySize, where the first entrysize
3843 // items are handled by the derived class and the
3844 // item at kChainOffset is another entry into the
3845 // data table indicating the next entry in this hash
3848 // When we transition the table to a new version we obsolete it and reuse parts
3849 // of the memory to store information how to transition an iterator to the new
3852 // Memory layout for obsolete table:
3853 // [0]: bucket count
3854 // [1]: Next newer table
3855 // [2]: Number of removed holes or -1 when the table was cleared.
3856 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3857 // [3 + NumberOfRemovedHoles()..length]: Not used
3859 template<class Derived, class Iterator, int entrysize>
3860 class OrderedHashTable: public FixedArray {
3862 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3863 static Handle<Derived> Allocate(
3864 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3866 // Returns an OrderedHashTable (possibly |table|) with enough space
3867 // to add at least one new element.
3868 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3870 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3872 static Handle<Derived> Shrink(Handle<Derived> table);
3874 // Returns a new empty OrderedHashTable and records the clearing so that
3875 // exisiting iterators can be updated.
3876 static Handle<Derived> Clear(Handle<Derived> table);
3878 // Returns an OrderedHashTable (possibly |table|) where |key| has been
3880 static Handle<Derived> Remove(Handle<Derived> table, Handle<Object> key,
3883 // Returns kNotFound if the key isn't present.
3884 int FindEntry(Handle<Object> key, int hash);
3886 // Like the above, but doesn't require the caller to provide a hash.
3887 int FindEntry(Handle<Object> key);
3889 int NumberOfElements() {
3890 return Smi::cast(get(kNumberOfElementsIndex))->value();
3893 int NumberOfDeletedElements() {
3894 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3897 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3899 int NumberOfBuckets() {
3900 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3903 // Returns the index into the data table where the new entry
3904 // should be placed. The table is assumed to have enough space
3906 int AddEntry(int hash);
3908 // Removes the entry, and puts the_hole in entrysize pointers
3909 // (leaving the hash table chain intact).
3910 void RemoveEntry(int entry);
3912 // Returns an index into |this| for the given entry.
3913 int EntryToIndex(int entry) {
3914 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3917 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3920 return !get(kNextTableIndex)->IsSmi();
3923 // The next newer table. This is only valid if the table is obsolete.
3924 Derived* NextTable() {
3925 return Derived::cast(get(kNextTableIndex));
3928 // When the table is obsolete we store the indexes of the removed holes.
3929 int RemovedIndexAt(int index) {
3930 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3933 static const int kNotFound = -1;
3934 static const int kMinCapacity = 4;
3937 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3939 void SetNumberOfBuckets(int num) {
3940 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3943 void SetNumberOfElements(int num) {
3944 set(kNumberOfElementsIndex, Smi::FromInt(num));
3947 void SetNumberOfDeletedElements(int num) {
3948 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3952 return NumberOfBuckets() * kLoadFactor;
3955 // Returns the next entry for the given entry.
3956 int ChainAt(int entry) {
3957 return Smi::cast(get(EntryToIndex(entry) + kChainOffset))->value();
3960 int HashToBucket(int hash) {
3961 return hash & (NumberOfBuckets() - 1);
3964 int HashToEntry(int hash) {
3965 int bucket = HashToBucket(hash);
3966 return Smi::cast(get(kHashTableStartIndex + bucket))->value();
3969 void SetNextTable(Derived* next_table) {
3970 set(kNextTableIndex, next_table);
3973 void SetRemovedIndexAt(int index, int removed_index) {
3974 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3977 static const int kNumberOfBucketsIndex = 0;
3978 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3979 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3980 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3982 static const int kNextTableIndex = kNumberOfElementsIndex;
3983 static const int kRemovedHolesIndex = kHashTableStartIndex;
3985 static const int kEntrySize = entrysize + 1;
3986 static const int kChainOffset = entrysize;
3988 static const int kLoadFactor = 2;
3989 static const int kMaxCapacity =
3990 (FixedArray::kMaxLength - kHashTableStartIndex)
3991 / (1 + (kEntrySize * kLoadFactor));
3995 class JSSetIterator;
3998 class OrderedHashSet: public OrderedHashTable<
3999 OrderedHashSet, JSSetIterator, 1> {
4001 DECLARE_CAST(OrderedHashSet)
4003 bool Contains(Handle<Object> key);
4004 static Handle<OrderedHashSet> Add(
4005 Handle<OrderedHashSet> table, Handle<Object> key);
4009 class JSMapIterator;
4012 class OrderedHashMap:public OrderedHashTable<
4013 OrderedHashMap, JSMapIterator, 2> {
4015 DECLARE_CAST(OrderedHashMap)
4017 Object* Lookup(Handle<Object> key);
4018 static Handle<OrderedHashMap> Put(
4019 Handle<OrderedHashMap> table,
4021 Handle<Object> value);
4023 Object* ValueAt(int entry) {
4024 return get(EntryToIndex(entry) + kValueOffset);
4028 static const int kValueOffset = 1;
4032 template <int entrysize>
4033 class WeakHashTableShape : public BaseShape<Handle<Object> > {
4035 static inline bool IsMatch(Handle<Object> key, Object* other);
4036 static inline uint32_t Hash(Handle<Object> key);
4037 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
4038 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
4039 static const int kPrefixSize = 0;
4040 static const int kEntrySize = entrysize;
4044 // WeakHashTable maps keys that are arbitrary objects to object values.
4045 // It is used for the global weak hash table that maps objects
4046 // embedded in optimized code to dependent code lists.
4047 class WeakHashTable: public HashTable<WeakHashTable,
4048 WeakHashTableShape<2>,
4051 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
4053 DECLARE_CAST(WeakHashTable)
4055 // Looks up the value associated with the given key. The hole value is
4056 // returned in case the key is not present.
4057 Object* Lookup(Handle<Object> key);
4059 // Adds (or overwrites) the value associated with the given key. Mapping a
4060 // key to the hole value causes removal of the whole entry.
4061 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
4063 Handle<Object> value);
4065 // This function is called when heap verification is turned on.
4066 void Zap(Object* value) {
4067 int capacity = Capacity();
4068 for (int i = 0; i < capacity; i++) {
4069 set(EntryToIndex(i), value);
4070 set(EntryToValueIndex(i), value);
4075 friend class MarkCompactCollector;
4077 void AddEntry(int entry, Handle<Object> key, Handle<Object> value);
4079 // Returns the index to the value of an entry.
4080 static inline int EntryToValueIndex(int entry) {
4081 return EntryToIndex(entry) + 1;
4086 // JSFunctionResultCache caches results of some JSFunction invocation.
4087 // It is a fixed array with fixed structure:
4088 // [0]: factory function
4089 // [1]: finger index
4090 // [2]: current cache size
4091 // [3]: dummy field.
4092 // The rest of array are key/value pairs.
4093 class JSFunctionResultCache: public FixedArray {
4095 static const int kFactoryIndex = 0;
4096 static const int kFingerIndex = kFactoryIndex + 1;
4097 static const int kCacheSizeIndex = kFingerIndex + 1;
4098 static const int kDummyIndex = kCacheSizeIndex + 1;
4099 static const int kEntriesIndex = kDummyIndex + 1;
4101 static const int kEntrySize = 2; // key + value
4103 static const int kFactoryOffset = kHeaderSize;
4104 static const int kFingerOffset = kFactoryOffset + kPointerSize;
4105 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4107 inline void MakeZeroSize();
4108 inline void Clear();
4111 inline void set_size(int size);
4112 inline int finger_index();
4113 inline void set_finger_index(int finger_index);
4115 DECLARE_CAST(JSFunctionResultCache)
4117 DECLARE_VERIFIER(JSFunctionResultCache)
4121 // ScopeInfo represents information about different scopes of a source
4122 // program and the allocation of the scope's variables. Scope information
4123 // is stored in a compressed form in ScopeInfo objects and is used
4124 // at runtime (stack dumps, deoptimization, etc.).
4126 // This object provides quick access to scope info details for runtime
4128 class ScopeInfo : public FixedArray {
4130 DECLARE_CAST(ScopeInfo)
4132 // Return the type of this scope.
4133 ScopeType scope_type();
4135 // Does this scope call eval?
4138 // Return the strict mode of this scope.
4139 StrictMode strict_mode();
4141 // Does this scope make a sloppy eval call?
4142 bool CallsSloppyEval() { return CallsEval() && strict_mode() == SLOPPY; }
4144 // Return the total number of locals allocated on the stack and in the
4145 // context. This includes the parameters that are allocated in the context.
4148 // Return the number of stack slots for code. This number consists of two
4150 // 1. One stack slot per stack allocated local.
4151 // 2. One stack slot for the function name if it is stack allocated.
4152 int StackSlotCount();
4154 // Return the number of context slots for code if a context is allocated. This
4155 // number consists of three parts:
4156 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4157 // 2. One context slot per context allocated local.
4158 // 3. One context slot for the function name if it is context allocated.
4159 // Parameters allocated in the context count as context allocated locals. If
4160 // no contexts are allocated for this scope ContextLength returns 0.
4161 int ContextLength();
4163 // Is this scope the scope of a named function expression?
4164 bool HasFunctionName();
4166 // Return if this has context allocated locals.
4167 bool HasHeapAllocatedLocals();
4169 // Return if contexts are allocated for this scope.
4172 // Return if this is a function scope with "use asm".
4173 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
4175 // Return if this is a nested function within an asm module scope.
4176 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
4178 // Return the function_name if present.
4179 String* FunctionName();
4181 // Return the name of the given parameter.
4182 String* ParameterName(int var);
4184 // Return the name of the given local.
4185 String* LocalName(int var);
4187 // Return the name of the given stack local.
4188 String* StackLocalName(int var);
4190 // Return the name of the given context local.
4191 String* ContextLocalName(int var);
4193 // Return the mode of the given context local.
4194 VariableMode ContextLocalMode(int var);
4196 // Return the initialization flag of the given context local.
4197 InitializationFlag ContextLocalInitFlag(int var);
4199 // Return the initialization flag of the given context local.
4200 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
4202 // Return true if this local was introduced by the compiler, and should not be
4203 // exposed to the user in a debugger.
4204 bool LocalIsSynthetic(int var);
4206 // Lookup support for serialized scope info. Returns the
4207 // the stack slot index for a given slot name if the slot is
4208 // present; otherwise returns a value < 0. The name must be an internalized
4210 int StackSlotIndex(String* name);
4212 // Lookup support for serialized scope info. Returns the
4213 // context slot index for a given slot name if the slot is present; otherwise
4214 // returns a value < 0. The name must be an internalized string.
4215 // If the slot is present and mode != NULL, sets *mode to the corresponding
4216 // mode for that variable.
4217 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
4218 VariableMode* mode, InitializationFlag* init_flag,
4219 MaybeAssignedFlag* maybe_assigned_flag);
4221 // Lookup support for serialized scope info. Returns the
4222 // parameter index for a given parameter name if the parameter is present;
4223 // otherwise returns a value < 0. The name must be an internalized string.
4224 int ParameterIndex(String* name);
4226 // Lookup support for serialized scope info. Returns the function context
4227 // slot index if the function name is present and context-allocated (named
4228 // function expressions, only), otherwise returns a value < 0. The name
4229 // must be an internalized string.
4230 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4233 // Copies all the context locals into an object used to materialize a scope.
4234 static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4235 Handle<Context> context,
4236 Handle<JSObject> scope_object);
4239 static Handle<ScopeInfo> Create(Scope* scope, Zone* zone);
4241 // Serializes empty scope info.
4242 static ScopeInfo* Empty(Isolate* isolate);
4248 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4249 // numeric and occupies one array slot.
4250 // 1. A set of properties of the scope
4251 // 2. The number of parameters. This only applies to function scopes. For
4252 // non-function scopes this is 0.
4253 // 3. The number of non-parameter variables allocated on the stack.
4254 // 4. The number of non-parameter and parameter variables allocated in the
4256 #define FOR_EACH_NUMERIC_FIELD(V) \
4259 V(StackLocalCount) \
4260 V(ContextLocalCount)
4262 #define FIELD_ACCESSORS(name) \
4263 void Set##name(int value) { \
4264 set(k##name, Smi::FromInt(value)); \
4267 if (length() > 0) { \
4268 return Smi::cast(get(k##name))->value(); \
4273 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4274 #undef FIELD_ACCESSORS
4278 #define DECL_INDEX(name) k##name,
4279 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4281 #undef FOR_EACH_NUMERIC_FIELD
4285 // The layout of the variable part of a ScopeInfo is as follows:
4286 // 1. ParameterEntries:
4287 // This part stores the names of the parameters for function scopes. One
4288 // slot is used per parameter, so in total this part occupies
4289 // ParameterCount() slots in the array. For other scopes than function
4290 // scopes ParameterCount() is 0.
4291 // 2. StackLocalEntries:
4292 // Contains the names of local variables that are allocated on the stack,
4293 // in increasing order of the stack slot index. One slot is used per stack
4294 // local, so in total this part occupies StackLocalCount() slots in the
4296 // 3. ContextLocalNameEntries:
4297 // Contains the names of local variables and parameters that are allocated
4298 // in the context. They are stored in increasing order of the context slot
4299 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4300 // context local, so in total this part occupies ContextLocalCount() slots
4302 // 4. ContextLocalInfoEntries:
4303 // Contains the variable modes and initialization flags corresponding to
4304 // the context locals in ContextLocalNameEntries. One slot is used per
4305 // context local, so in total this part occupies ContextLocalCount()
4306 // slots in the array.
4307 // 5. FunctionNameEntryIndex:
4308 // If the scope belongs to a named function expression this part contains
4309 // information about the function variable. It always occupies two array
4310 // slots: a. The name of the function variable.
4311 // b. The context or stack slot index for the variable.
4312 int ParameterEntriesIndex();
4313 int StackLocalEntriesIndex();
4314 int ContextLocalNameEntriesIndex();
4315 int ContextLocalInfoEntriesIndex();
4316 int FunctionNameEntryIndex();
4318 // Location of the function variable for named function expressions.
4319 enum FunctionVariableInfo {
4320 NONE, // No function name present.
4326 // Properties of scopes.
4327 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4328 class CallsEvalField : public BitField<bool, 4, 1> {};
4329 class StrictModeField : public BitField<StrictMode, 5, 1> {};
4330 class FunctionVariableField : public BitField<FunctionVariableInfo, 6, 2> {};
4331 class FunctionVariableMode : public BitField<VariableMode, 8, 3> {};
4332 class AsmModuleField : public BitField<bool, 11, 1> {};
4333 class AsmFunctionField : public BitField<bool, 12, 1> {};
4335 // BitFields representing the encoded information for context locals in the
4336 // ContextLocalInfoEntries part.
4337 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4338 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4339 class ContextLocalMaybeAssignedFlag
4340 : public BitField<MaybeAssignedFlag, 4, 1> {};
4344 // The cache for maps used by normalized (dictionary mode) objects.
4345 // Such maps do not have property descriptors, so a typical program
4346 // needs very limited number of distinct normalized maps.
4347 class NormalizedMapCache: public FixedArray {
4349 static Handle<NormalizedMapCache> New(Isolate* isolate);
4351 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4352 PropertyNormalizationMode mode);
4353 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4357 DECLARE_CAST(NormalizedMapCache)
4359 static inline bool IsNormalizedMapCache(const Object* obj);
4361 DECLARE_VERIFIER(NormalizedMapCache)
4363 static const int kEntries = 64;
4365 static inline int GetIndex(Handle<Map> map);
4367 // The following declarations hide base class methods.
4368 Object* get(int index);
4369 void set(int index, Object* value);
4373 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4374 // that is attached to code objects.
4375 class ByteArray: public FixedArrayBase {
4377 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4379 // Setter and getter.
4380 inline byte get(int index);
4381 inline void set(int index, byte value);
4383 // Treat contents as an int array.
4384 inline int get_int(int index);
4386 static int SizeFor(int length) {
4387 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4389 // We use byte arrays for free blocks in the heap. Given a desired size in
4390 // bytes that is a multiple of the word size and big enough to hold a byte
4391 // array, this function returns the number of elements a byte array should
4393 static int LengthFor(int size_in_bytes) {
4394 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4395 DCHECK(size_in_bytes >= kHeaderSize);
4396 return size_in_bytes - kHeaderSize;
4399 // Returns data start address.
4400 inline Address GetDataStartAddress();
4402 // Returns a pointer to the ByteArray object for a given data start address.
4403 static inline ByteArray* FromDataStartAddress(Address address);
4405 DECLARE_CAST(ByteArray)
4407 // Dispatched behavior.
4408 inline int ByteArraySize() {
4409 return SizeFor(this->length());
4411 DECLARE_PRINTER(ByteArray)
4412 DECLARE_VERIFIER(ByteArray)
4414 // Layout description.
4415 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4417 // Maximal memory consumption for a single ByteArray.
4418 static const int kMaxSize = 512 * MB;
4419 // Maximal length of a single ByteArray.
4420 static const int kMaxLength = kMaxSize - kHeaderSize;
4423 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4427 // FreeSpace represents fixed sized areas of the heap that are not currently in
4428 // use. Used by the heap and GC.
4429 class FreeSpace: public HeapObject {
4431 // [size]: size of the free space including the header.
4432 inline int size() const;
4433 inline void set_size(int value);
4435 inline int nobarrier_size() const;
4436 inline void nobarrier_set_size(int value);
4438 inline int Size() { return size(); }
4440 DECLARE_CAST(FreeSpace)
4442 // Dispatched behavior.
4443 DECLARE_PRINTER(FreeSpace)
4444 DECLARE_VERIFIER(FreeSpace)
4446 // Layout description.
4447 // Size is smi tagged when it is stored.
4448 static const int kSizeOffset = HeapObject::kHeaderSize;
4449 static const int kHeaderSize = kSizeOffset + kPointerSize;
4451 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4454 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4458 // V has parameters (Type, type, TYPE, C type, element_size)
4459 #define TYPED_ARRAYS(V) \
4460 V(Uint8, uint8, UINT8, uint8_t, 1) \
4461 V(Int8, int8, INT8, int8_t, 1) \
4462 V(Uint16, uint16, UINT16, uint16_t, 2) \
4463 V(Int16, int16, INT16, int16_t, 2) \
4464 V(Uint32, uint32, UINT32, uint32_t, 4) \
4465 V(Int32, int32, INT32, int32_t, 4) \
4466 V(Float32, float32, FLOAT32, float, 4) \
4467 V(Float64, float64, FLOAT64, double, 8) \
4468 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4472 // An ExternalArray represents a fixed-size array of primitive values
4473 // which live outside the JavaScript heap. Its subclasses are used to
4474 // implement the CanvasArray types being defined in the WebGL
4475 // specification. As of this writing the first public draft is not yet
4476 // available, but Khronos members can access the draft at:
4477 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4479 // The semantics of these arrays differ from CanvasPixelArray.
4480 // Out-of-range values passed to the setter are converted via a C
4481 // cast, not clamping. Out-of-range indices cause exceptions to be
4482 // raised rather than being silently ignored.
4483 class ExternalArray: public FixedArrayBase {
4485 inline bool is_the_hole(int index) { return false; }
4487 // [external_pointer]: The pointer to the external memory area backing this
4489 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4491 DECLARE_CAST(ExternalArray)
4493 // Maximal acceptable length for an external array.
4494 static const int kMaxLength = 0x3fffffff;
4496 // ExternalArray headers are not quadword aligned.
4497 static const int kExternalPointerOffset =
4498 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4499 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4500 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4503 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4507 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4508 // semantics used for implementing the CanvasPixelArray object. Please see the
4509 // specification at:
4511 // http://www.whatwg.org/specs/web-apps/current-work/
4512 // multipage/the-canvas-element.html#canvaspixelarray
4513 // In particular, write access clamps the value written to 0 or 255 if the
4514 // value written is outside this range.
4515 class ExternalUint8ClampedArray: public ExternalArray {
4517 inline uint8_t* external_uint8_clamped_pointer();
4519 // Setter and getter.
4520 inline uint8_t get_scalar(int index);
4521 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4523 inline void set(int index, uint8_t value);
4525 // This accessor applies the correct conversion from Smi, HeapNumber
4526 // and undefined and clamps the converted value between 0 and 255.
4527 static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4529 Handle<Object> value);
4531 DECLARE_CAST(ExternalUint8ClampedArray)
4533 // Dispatched behavior.
4534 DECLARE_PRINTER(ExternalUint8ClampedArray)
4535 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4538 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4542 class ExternalInt8Array: public ExternalArray {
4544 // Setter and getter.
4545 inline int8_t get_scalar(int index);
4546 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4547 inline void set(int index, int8_t value);
4549 // This accessor applies the correct conversion from Smi, HeapNumber
4551 static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4553 Handle<Object> value);
4555 DECLARE_CAST(ExternalInt8Array)
4557 // Dispatched behavior.
4558 DECLARE_PRINTER(ExternalInt8Array)
4559 DECLARE_VERIFIER(ExternalInt8Array)
4562 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4566 class ExternalUint8Array: public ExternalArray {
4568 // Setter and getter.
4569 inline uint8_t get_scalar(int index);
4570 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4571 inline void set(int index, uint8_t value);
4573 // This accessor applies the correct conversion from Smi, HeapNumber
4575 static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
4577 Handle<Object> value);
4579 DECLARE_CAST(ExternalUint8Array)
4581 // Dispatched behavior.
4582 DECLARE_PRINTER(ExternalUint8Array)
4583 DECLARE_VERIFIER(ExternalUint8Array)
4586 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4590 class ExternalInt16Array: public ExternalArray {
4592 // Setter and getter.
4593 inline int16_t get_scalar(int index);
4594 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4595 inline void set(int index, int16_t value);
4597 // This accessor applies the correct conversion from Smi, HeapNumber
4599 static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
4601 Handle<Object> value);
4603 DECLARE_CAST(ExternalInt16Array)
4605 // Dispatched behavior.
4606 DECLARE_PRINTER(ExternalInt16Array)
4607 DECLARE_VERIFIER(ExternalInt16Array)
4610 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4614 class ExternalUint16Array: public ExternalArray {
4616 // Setter and getter.
4617 inline uint16_t get_scalar(int index);
4618 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4620 inline void set(int index, uint16_t value);
4622 // This accessor applies the correct conversion from Smi, HeapNumber
4624 static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
4626 Handle<Object> value);
4628 DECLARE_CAST(ExternalUint16Array)
4630 // Dispatched behavior.
4631 DECLARE_PRINTER(ExternalUint16Array)
4632 DECLARE_VERIFIER(ExternalUint16Array)
4635 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4639 class ExternalInt32Array: public ExternalArray {
4641 // Setter and getter.
4642 inline int32_t get_scalar(int index);
4643 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4644 inline void set(int index, int32_t value);
4646 // This accessor applies the correct conversion from Smi, HeapNumber
4648 static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
4650 Handle<Object> value);
4652 DECLARE_CAST(ExternalInt32Array)
4654 // Dispatched behavior.
4655 DECLARE_PRINTER(ExternalInt32Array)
4656 DECLARE_VERIFIER(ExternalInt32Array)
4659 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4663 class ExternalUint32Array: public ExternalArray {
4665 // Setter and getter.
4666 inline uint32_t get_scalar(int index);
4667 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4669 inline void set(int index, uint32_t value);
4671 // This accessor applies the correct conversion from Smi, HeapNumber
4673 static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
4675 Handle<Object> value);
4677 DECLARE_CAST(ExternalUint32Array)
4679 // Dispatched behavior.
4680 DECLARE_PRINTER(ExternalUint32Array)
4681 DECLARE_VERIFIER(ExternalUint32Array)
4684 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4688 class ExternalFloat32Array: public ExternalArray {
4690 // Setter and getter.
4691 inline float get_scalar(int index);
4692 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4694 inline void set(int index, float value);
4696 // This accessor applies the correct conversion from Smi, HeapNumber
4698 static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
4700 Handle<Object> value);
4702 DECLARE_CAST(ExternalFloat32Array)
4704 // Dispatched behavior.
4705 DECLARE_PRINTER(ExternalFloat32Array)
4706 DECLARE_VERIFIER(ExternalFloat32Array)
4709 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4713 class ExternalFloat64Array: public ExternalArray {
4715 // Setter and getter.
4716 inline double get_scalar(int index);
4717 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4719 inline void set(int index, double value);
4721 // This accessor applies the correct conversion from Smi, HeapNumber
4723 static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
4725 Handle<Object> value);
4727 DECLARE_CAST(ExternalFloat64Array)
4729 // Dispatched behavior.
4730 DECLARE_PRINTER(ExternalFloat64Array)
4731 DECLARE_VERIFIER(ExternalFloat64Array)
4734 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4738 class FixedTypedArrayBase: public FixedArrayBase {
4740 DECLARE_CAST(FixedTypedArrayBase)
4742 static const int kDataOffset = kHeaderSize;
4746 inline int TypedArraySize(InstanceType type);
4748 // Use with care: returns raw pointer into heap.
4749 inline void* DataPtr();
4751 inline int DataSize();
4754 inline int DataSize(InstanceType type);
4756 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4760 template <class Traits>
4761 class FixedTypedArray: public FixedTypedArrayBase {
4763 typedef typename Traits::ElementType ElementType;
4764 static const InstanceType kInstanceType = Traits::kInstanceType;
4766 DECLARE_CAST(FixedTypedArray<Traits>)
4768 static inline int ElementOffset(int index) {
4769 return kDataOffset + index * sizeof(ElementType);
4772 static inline int SizeFor(int length) {
4773 return ElementOffset(length);
4776 inline ElementType get_scalar(int index);
4777 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4778 inline void set(int index, ElementType value);
4780 static inline ElementType from_int(int value);
4781 static inline ElementType from_double(double value);
4783 // This accessor applies the correct conversion from Smi, HeapNumber
4785 static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
4787 Handle<Object> value);
4789 DECLARE_PRINTER(FixedTypedArray)
4790 DECLARE_VERIFIER(FixedTypedArray)
4793 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4796 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4797 class Type##ArrayTraits { \
4798 public: /* NOLINT */ \
4799 typedef elementType ElementType; \
4800 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4801 static const char* Designator() { return #type " array"; } \
4802 static inline Handle<Object> ToHandle(Isolate* isolate, \
4803 elementType scalar); \
4804 static inline elementType defaultValue(); \
4807 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4809 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4811 #undef FIXED_TYPED_ARRAY_TRAITS
4813 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4814 // data for code generated by the Hydrogen/Lithium compiler. It also
4815 // contains information about functions that were inlined. If N different
4816 // functions were inlined then first N elements of the literal array will
4817 // contain these functions.
4820 class DeoptimizationInputData: public FixedArray {
4822 // Layout description. Indices in the array.
4823 static const int kTranslationByteArrayIndex = 0;
4824 static const int kInlinedFunctionCountIndex = 1;
4825 static const int kLiteralArrayIndex = 2;
4826 static const int kOsrAstIdIndex = 3;
4827 static const int kOsrPcOffsetIndex = 4;
4828 static const int kOptimizationIdIndex = 5;
4829 static const int kSharedFunctionInfoIndex = 6;
4830 static const int kFirstDeoptEntryIndex = 7;
4832 // Offsets of deopt entry elements relative to the start of the entry.
4833 static const int kAstIdRawOffset = 0;
4834 static const int kTranslationIndexOffset = 1;
4835 static const int kArgumentsStackHeightOffset = 2;
4836 static const int kPcOffset = 3;
4837 static const int kDeoptEntrySize = 4;
4839 // Simple element accessors.
4840 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4842 return type::cast(get(k##name##Index)); \
4844 void Set##name(type* value) { \
4845 set(k##name##Index, value); \
4848 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4849 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4850 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4851 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4852 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4853 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4854 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4856 #undef DEFINE_ELEMENT_ACCESSORS
4858 // Accessors for elements of the ith deoptimization entry.
4859 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4860 type* name(int i) { \
4861 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4863 void Set##name(int i, type* value) { \
4864 set(IndexForEntry(i) + k##name##Offset, value); \
4867 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4868 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4869 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4870 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4872 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4874 BailoutId AstId(int i) {
4875 return BailoutId(AstIdRaw(i)->value());
4878 void SetAstId(int i, BailoutId value) {
4879 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4883 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4886 // Allocates a DeoptimizationInputData.
4887 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4888 int deopt_entry_count,
4889 PretenureFlag pretenure);
4891 DECLARE_CAST(DeoptimizationInputData)
4893 #ifdef ENABLE_DISASSEMBLER
4894 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4898 static int IndexForEntry(int i) {
4899 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4903 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4907 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4908 // data for code generated by the full compiler.
4909 // The format of the these objects is
4910 // [i * 2]: Ast ID for ith deoptimization.
4911 // [i * 2 + 1]: PC and state of ith deoptimization
4912 class DeoptimizationOutputData: public FixedArray {
4914 int DeoptPoints() { return length() / 2; }
4916 BailoutId AstId(int index) {
4917 return BailoutId(Smi::cast(get(index * 2))->value());
4920 void SetAstId(int index, BailoutId id) {
4921 set(index * 2, Smi::FromInt(id.ToInt()));
4924 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4925 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4927 static int LengthOfFixedArray(int deopt_points) {
4928 return deopt_points * 2;
4931 // Allocates a DeoptimizationOutputData.
4932 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4933 int number_of_deopt_points,
4934 PretenureFlag pretenure);
4936 DECLARE_CAST(DeoptimizationOutputData)
4938 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4939 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4944 // Forward declaration.
4947 class SafepointEntry;
4948 class TypeFeedbackInfo;
4950 // Code describes objects with on-the-fly generated machine code.
4951 class Code: public HeapObject {
4953 // Opaque data type for encapsulating code flags like kind, inline
4954 // cache state, and arguments count.
4955 typedef uint32_t Flags;
4957 #define NON_IC_KIND_LIST(V) \
4959 V(OPTIMIZED_FUNCTION) \
4965 #define IC_KIND_LIST(V) \
4976 #define CODE_KIND_LIST(V) \
4977 NON_IC_KIND_LIST(V) \
4981 #define DEFINE_CODE_KIND_ENUM(name) name,
4982 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4983 #undef DEFINE_CODE_KIND_ENUM
4987 // No more than 16 kinds. The value is currently encoded in four bits in
4989 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4991 static const char* Kind2String(Kind kind);
4999 static const int kPrologueOffsetNotSet = -1;
5001 #ifdef ENABLE_DISASSEMBLER
5003 static const char* ICState2String(InlineCacheState state);
5004 static const char* StubType2String(StubType type);
5005 static void PrintExtraICState(std::ostream& os, // NOLINT
5006 Kind kind, ExtraICState extra);
5007 void Disassemble(const char* name, std::ostream& os); // NOLINT
5008 #endif // ENABLE_DISASSEMBLER
5010 // [instruction_size]: Size of the native instructions
5011 inline int instruction_size() const;
5012 inline void set_instruction_size(int value);
5014 // [relocation_info]: Code relocation information
5015 DECL_ACCESSORS(relocation_info, ByteArray)
5016 void InvalidateRelocation();
5017 void InvalidateEmbeddedObjects();
5019 // [handler_table]: Fixed array containing offsets of exception handlers.
5020 DECL_ACCESSORS(handler_table, FixedArray)
5022 // [deoptimization_data]: Array containing data for deopt.
5023 DECL_ACCESSORS(deoptimization_data, FixedArray)
5025 // [raw_type_feedback_info]: This field stores various things, depending on
5026 // the kind of the code object.
5027 // FUNCTION => type feedback information.
5028 // STUB and ICs => major/minor key as Smi.
5029 DECL_ACCESSORS(raw_type_feedback_info, Object)
5030 inline Object* type_feedback_info();
5031 inline void set_type_feedback_info(
5032 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5033 inline uint32_t stub_key();
5034 inline void set_stub_key(uint32_t key);
5036 // [next_code_link]: Link for lists of optimized or deoptimized code.
5037 // Note that storage for this field is overlapped with typefeedback_info.
5038 DECL_ACCESSORS(next_code_link, Object)
5040 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5041 // field does not have to be traced during garbage collection since
5042 // it is only used by the garbage collector itself.
5043 DECL_ACCESSORS(gc_metadata, Object)
5045 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5046 // at the moment when this object was created.
5047 inline void set_ic_age(int count);
5048 inline int ic_age() const;
5050 // [prologue_offset]: Offset of the function prologue, used for aging
5051 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5052 inline int prologue_offset() const;
5053 inline void set_prologue_offset(int offset);
5055 // Unchecked accessors to be used during GC.
5056 inline ByteArray* unchecked_relocation_info();
5058 inline int relocation_size();
5060 // [flags]: Various code flags.
5061 inline Flags flags();
5062 inline void set_flags(Flags flags);
5064 // [flags]: Access to specific code flags.
5066 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5067 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5069 inline StubType type(); // Only valid for monomorphic IC stubs.
5071 // Testers for IC stub kinds.
5072 inline bool is_inline_cache_stub();
5073 inline bool is_debug_stub();
5074 inline bool is_handler() { return kind() == HANDLER; }
5075 inline bool is_load_stub() { return kind() == LOAD_IC; }
5076 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5077 inline bool is_store_stub() { return kind() == STORE_IC; }
5078 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5079 inline bool is_call_stub() { return kind() == CALL_IC; }
5080 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5081 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5082 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5083 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5084 inline bool is_keyed_stub();
5085 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5086 inline bool is_weak_stub();
5087 inline void mark_as_weak_stub();
5088 inline bool is_invalidated_weak_stub();
5089 inline void mark_as_invalidated_weak_stub();
5091 inline bool CanBeWeakStub() {
5093 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
5094 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
5095 ic_state() == MONOMORPHIC;
5098 inline bool IsCodeStubOrIC();
5100 inline void set_raw_kind_specific_flags1(int value);
5101 inline void set_raw_kind_specific_flags2(int value);
5103 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
5104 // object was generated by either the hydrogen or the TurboFan optimizing
5105 // compiler (but it may not be an optimized function).
5106 inline bool is_crankshafted();
5107 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
5108 inline void set_is_crankshafted(bool value);
5110 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
5111 // code object was generated by the TurboFan optimizing compiler.
5112 inline bool is_turbofanned();
5113 inline void set_is_turbofanned(bool value);
5115 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5116 inline bool optimizable();
5117 inline void set_optimizable(bool value);
5119 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5120 // deoptimization support.
5121 inline bool has_deoptimization_support();
5122 inline void set_has_deoptimization_support(bool value);
5124 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5125 // been compiled with debug break slots.
5126 inline bool has_debug_break_slots();
5127 inline void set_has_debug_break_slots(bool value);
5129 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5130 // been compiled with IsOptimizing set to true.
5131 inline bool is_compiled_optimizable();
5132 inline void set_compiled_optimizable(bool value);
5134 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5135 // how long the function has been marked for OSR and therefore which
5136 // level of loop nesting we are willing to do on-stack replacement
5138 inline void set_allow_osr_at_loop_nesting_level(int level);
5139 inline int allow_osr_at_loop_nesting_level();
5141 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5142 // the code object was seen on the stack with no IC patching going on.
5143 inline int profiler_ticks();
5144 inline void set_profiler_ticks(int ticks);
5146 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5147 // For builtins, tells which builtin index it has.
5148 // Note that builtins can have a code kind other than BUILTIN, which means
5149 // that for arbitrary code objects, this index value may be random garbage.
5150 // To verify in that case, compare the code object to the indexed builtin.
5151 inline int builtin_index();
5152 inline void set_builtin_index(int id);
5154 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5155 // reserved in the code prologue.
5156 inline unsigned stack_slots();
5157 inline void set_stack_slots(unsigned slots);
5159 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5160 // the instruction stream where the safepoint table starts.
5161 inline unsigned safepoint_table_offset();
5162 inline void set_safepoint_table_offset(unsigned offset);
5164 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5165 // instruction stream where the back edge table starts.
5166 inline unsigned back_edge_table_offset();
5167 inline void set_back_edge_table_offset(unsigned offset);
5169 inline bool back_edges_patched_for_osr();
5171 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5172 inline byte to_boolean_state();
5174 // [has_function_cache]: For kind STUB tells whether there is a function
5175 // cache is passed to the stub.
5176 inline bool has_function_cache();
5177 inline void set_has_function_cache(bool flag);
5180 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5181 // the code is going to be deoptimized because of dead embedded maps.
5182 inline bool marked_for_deoptimization();
5183 inline void set_marked_for_deoptimization(bool flag);
5185 // [constant_pool]: The constant pool for this function.
5186 inline ConstantPoolArray* constant_pool();
5187 inline void set_constant_pool(Object* constant_pool);
5189 // Get the safepoint entry for the given pc.
5190 SafepointEntry GetSafepointEntry(Address pc);
5192 // Find an object in a stub with a specified map
5193 Object* FindNthObject(int n, Map* match_map);
5195 // Find the first allocation site in an IC stub.
5196 AllocationSite* FindFirstAllocationSite();
5198 // Find the first map in an IC stub.
5199 Map* FindFirstMap();
5200 void FindAllMaps(MapHandleList* maps);
5202 // Find the first handler in an IC stub.
5203 Code* FindFirstHandler();
5205 // Find |length| handlers and put them into |code_list|. Returns false if not
5206 // enough handlers can be found.
5207 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5209 // Find the handler for |map|.
5210 MaybeHandle<Code> FindHandlerForMap(Map* map);
5212 // Find the first name in an IC stub.
5213 Name* FindFirstName();
5215 class FindAndReplacePattern;
5216 // For each (map-to-find, object-to-replace) pair in the pattern, this
5217 // function replaces the corresponding placeholder in the code with the
5218 // object-to-replace. The function assumes that pairs in the pattern come in
5219 // the same order as the placeholders in the code.
5220 void FindAndReplace(const FindAndReplacePattern& pattern);
5222 // The entire code object including its header is copied verbatim to the
5223 // snapshot so that it can be written in one, fast, memcpy during
5224 // deserialization. The deserializer will overwrite some pointers, rather
5225 // like a runtime linker, but the random allocation addresses used in the
5226 // mksnapshot process would still be present in the unlinked snapshot data,
5227 // which would make snapshot production non-reproducible. This method wipes
5228 // out the to-be-overwritten header data for reproducible snapshots.
5229 inline void WipeOutHeader();
5231 // Flags operations.
5232 static inline Flags ComputeFlags(
5233 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5234 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5235 CacheHolderFlag holder = kCacheOnReceiver);
5237 static inline Flags ComputeMonomorphicFlags(
5238 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5239 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5241 static inline Flags ComputeHandlerFlags(
5242 Kind handler_kind, StubType type = NORMAL,
5243 CacheHolderFlag holder = kCacheOnReceiver);
5245 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5246 static inline StubType ExtractTypeFromFlags(Flags flags);
5247 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5248 static inline Kind ExtractKindFromFlags(Flags flags);
5249 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5251 static inline Flags RemoveTypeFromFlags(Flags flags);
5252 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5254 // Convert a target address into a code object.
5255 static inline Code* GetCodeFromTargetAddress(Address address);
5257 // Convert an entry address into an object.
5258 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5260 // Returns the address of the first instruction.
5261 inline byte* instruction_start();
5263 // Returns the address right after the last instruction.
5264 inline byte* instruction_end();
5266 // Returns the size of the instructions, padding, and relocation information.
5267 inline int body_size();
5269 // Returns the address of the first relocation info (read backwards!).
5270 inline byte* relocation_start();
5272 // Code entry point.
5273 inline byte* entry();
5275 // Returns true if pc is inside this object's instructions.
5276 inline bool contains(byte* pc);
5278 // Relocate the code by delta bytes. Called to signal that this code
5279 // object has been moved by delta bytes.
5280 void Relocate(intptr_t delta);
5282 // Migrate code described by desc.
5283 void CopyFrom(const CodeDesc& desc);
5285 // Returns the object size for a given body (used for allocation).
5286 static int SizeFor(int body_size) {
5287 DCHECK_SIZE_TAG_ALIGNED(body_size);
5288 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5291 // Calculate the size of the code object to report for log events. This takes
5292 // the layout of the code object into account.
5293 int ExecutableSize() {
5294 // Check that the assumptions about the layout of the code object holds.
5295 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5297 return instruction_size() + Code::kHeaderSize;
5300 // Locating source position.
5301 int SourcePosition(Address pc);
5302 int SourceStatementPosition(Address pc);
5306 // Dispatched behavior.
5307 int CodeSize() { return SizeFor(body_size()); }
5308 inline void CodeIterateBody(ObjectVisitor* v);
5310 template<typename StaticVisitor>
5311 inline void CodeIterateBody(Heap* heap);
5313 DECLARE_PRINTER(Code)
5314 DECLARE_VERIFIER(Code)
5316 void ClearInlineCaches();
5317 void ClearInlineCaches(Kind kind);
5319 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5320 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5322 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5324 kNotExecutedCodeAge = -2,
5325 kExecutedOnceCodeAge = -1,
5327 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5329 kFirstCodeAge = kNotExecutedCodeAge,
5330 kLastCodeAge = kAfterLastCodeAge - 1,
5331 kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5332 kIsOldCodeAge = kSexagenarianCodeAge,
5333 kPreAgedCodeAge = kIsOldCodeAge - 1
5335 #undef DECLARE_CODE_AGE_ENUM
5337 // Code aging. Indicates how many full GCs this code has survived without
5338 // being entered through the prologue. Used to determine when it is
5339 // relatively safe to flush this code object and replace it with the lazy
5340 // compilation stub.
5341 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5342 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5344 void MakeOlder(MarkingParity);
5345 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5348 // Gets the raw code age, including psuedo code-age values such as
5349 // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5351 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5352 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5355 void PrintDeoptLocation(FILE* out, int bailout_id);
5356 bool CanDeoptAt(Address pc);
5359 void VerifyEmbeddedObjectsDependency();
5363 void VerifyEmbeddedObjectsInFullCode();
5366 inline bool CanContainWeakObjects() {
5367 return is_optimized_code() || is_weak_stub();
5370 inline bool IsWeakObject(Object* object) {
5371 return (is_optimized_code() && !is_turbofanned() &&
5372 IsWeakObjectInOptimizedCode(object)) ||
5373 (is_weak_stub() && IsWeakObjectInIC(object));
5376 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5377 static inline bool IsWeakObjectInIC(Object* object);
5379 // Max loop nesting marker used to postpose OSR. We don't take loop
5380 // nesting that is deeper than 5 levels into account.
5381 static const int kMaxLoopNestingMarker = 6;
5383 // Layout description.
5384 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5385 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5386 static const int kDeoptimizationDataOffset =
5387 kHandlerTableOffset + kPointerSize;
5388 // For FUNCTION kind, we store the type feedback info here.
5389 static const int kTypeFeedbackInfoOffset =
5390 kDeoptimizationDataOffset + kPointerSize;
5391 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5392 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5393 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5394 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5395 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5396 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5397 static const int kKindSpecificFlags2Offset =
5398 kKindSpecificFlags1Offset + kIntSize;
5399 // Note: We might be able to squeeze this into the flags above.
5400 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5401 static const int kConstantPoolOffset = kPrologueOffset + kPointerSize;
5403 static const int kHeaderPaddingStart = kConstantPoolOffset + kPointerSize;
5405 // Add padding to align the instruction start following right after
5406 // the Code object header.
5407 static const int kHeaderSize =
5408 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5410 // Byte offsets within kKindSpecificFlags1Offset.
5411 static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5413 static const int kFullCodeFlags = kOptimizableOffset + 1;
5414 class FullCodeFlagsHasDeoptimizationSupportField:
5415 public BitField<bool, 0, 1> {}; // NOLINT
5416 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5417 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5419 static const int kProfilerTicksOffset = kFullCodeFlags + 1;
5421 // Flags layout. BitField<type, shift, size>.
5422 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5423 class TypeField : public BitField<StubType, 4, 1> {};
5424 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5425 class KindField : public BitField<Kind, 7, 4> {};
5426 class ExtraICStateField: public BitField<ExtraICState, 11,
5427 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5429 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5430 static const int kStackSlotsFirstBit = 0;
5431 static const int kStackSlotsBitCount = 24;
5432 static const int kHasFunctionCacheBit =
5433 kStackSlotsFirstBit + kStackSlotsBitCount;
5434 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5435 static const int kWeakStubBit = kMarkedForDeoptimizationBit + 1;
5436 static const int kInvalidatedWeakStubBit = kWeakStubBit + 1;
5437 static const int kIsTurbofannedBit = kInvalidatedWeakStubBit + 1;
5439 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5440 STATIC_ASSERT(kIsTurbofannedBit + 1 <= 32);
5442 class StackSlotsField: public BitField<int,
5443 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5444 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5446 class MarkedForDeoptimizationField
5447 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5448 class WeakStubField : public BitField<bool, kWeakStubBit, 1> {}; // NOLINT
5449 class InvalidatedWeakStubField
5450 : public BitField<bool, kInvalidatedWeakStubBit, 1> {}; // NOLINT
5451 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5454 // KindSpecificFlags2 layout (ALL)
5455 static const int kIsCrankshaftedBit = 0;
5456 class IsCrankshaftedField: public BitField<bool,
5457 kIsCrankshaftedBit, 1> {}; // NOLINT
5459 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5460 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5461 static const int kSafepointTableOffsetBitCount = 24;
5463 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5464 kSafepointTableOffsetBitCount <= 32);
5465 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5467 class SafepointTableOffsetField: public BitField<int,
5468 kSafepointTableOffsetFirstBit,
5469 kSafepointTableOffsetBitCount> {}; // NOLINT
5471 // KindSpecificFlags2 layout (FUNCTION)
5472 class BackEdgeTableOffsetField: public BitField<int,
5473 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5474 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5475 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5476 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5478 static const int kArgumentsBits = 16;
5479 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5481 // This constant should be encodable in an ARM instruction.
5482 static const int kFlagsNotUsedInLookup =
5483 TypeField::kMask | CacheHolderField::kMask;
5486 friend class RelocIterator;
5487 friend class Deoptimizer; // For FindCodeAgeSequence.
5489 void ClearInlineCaches(Kind* kind);
5492 byte* FindCodeAgeSequence();
5493 static void GetCodeAgeAndParity(Code* code, Age* age,
5494 MarkingParity* parity);
5495 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5496 MarkingParity* parity);
5497 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5499 // Code aging -- platform-specific
5500 static void PatchPlatformCodeAge(Isolate* isolate,
5501 byte* sequence, Age age,
5502 MarkingParity parity);
5504 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5508 class CompilationInfo;
5510 // This class describes the layout of dependent codes array of a map. The
5511 // array is partitioned into several groups of dependent codes. Each group
5512 // contains codes with the same dependency on the map. The array has the
5513 // following layout for n dependency groups:
5515 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5516 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5517 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5519 // The first n elements are Smis, each of them specifies the number of codes
5520 // in the corresponding group. The subsequent elements contain grouped code
5521 // objects. The suffix of the array can be filled with the undefined value if
5522 // the number of codes is less than the length of the array. The order of the
5523 // code objects within a group is not preserved.
5525 // All code indexes used in the class are counted starting from the first
5526 // code object of the first group. In other words, code index 0 corresponds
5527 // to array index n = kCodesStartIndex.
5529 class DependentCode: public FixedArray {
5531 enum DependencyGroup {
5532 // Group of IC stubs that weakly embed this map and depend on being
5533 // invalidated when the map is garbage collected. Dependent IC stubs form
5534 // a linked list. This group stores only the head of the list. This means
5535 // that the number_of_entries(kWeakICGroup) is 0 or 1.
5537 // Group of code that weakly embed this map and depend on being
5538 // deoptimized when the map is garbage collected.
5540 // Group of code that embed a transition to this map, and depend on being
5541 // deoptimized when the transition is replaced by a new version.
5543 // Group of code that omit run-time prototype checks for prototypes
5544 // described by this map. The group is deoptimized whenever an object
5545 // described by this map changes shape (and transitions to a new map),
5546 // possibly invalidating the assumptions embedded in the code.
5547 kPrototypeCheckGroup,
5548 // Group of code that depends on elements not being added to objects with
5550 kElementsCantBeAddedGroup,
5551 // Group of code that depends on global property values in property cells
5552 // not being changed.
5553 kPropertyCellChangedGroup,
5554 // Group of code that omit run-time type checks for the field(s) introduced
5557 // Group of code that omit run-time type checks for initial maps of
5559 kInitialMapChangedGroup,
5560 // Group of code that depends on tenuring information in AllocationSites
5561 // not being changed.
5562 kAllocationSiteTenuringChangedGroup,
5563 // Group of code that depends on element transition information in
5564 // AllocationSites not being changed.
5565 kAllocationSiteTransitionChangedGroup
5568 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5570 // Array for holding the index of the first code object of each group.
5571 // The last element stores the total number of code objects.
5572 class GroupStartIndexes {
5574 explicit GroupStartIndexes(DependentCode* entries);
5575 void Recompute(DependentCode* entries);
5576 int at(int i) { return start_indexes_[i]; }
5577 int number_of_entries() { return start_indexes_[kGroupCount]; }
5579 int start_indexes_[kGroupCount + 1];
5582 bool Contains(DependencyGroup group, Code* code);
5583 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5584 DependencyGroup group,
5585 Handle<Object> object);
5586 void UpdateToFinishedCode(DependencyGroup group,
5587 CompilationInfo* info,
5589 void RemoveCompilationInfo(DependentCode::DependencyGroup group,
5590 CompilationInfo* info);
5592 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5593 DependentCode::DependencyGroup group);
5595 bool MarkCodeForDeoptimization(Isolate* isolate,
5596 DependentCode::DependencyGroup group);
5597 void AddToDependentICList(Handle<Code> stub);
5599 // The following low-level accessors should only be used by this class
5600 // and the mark compact collector.
5601 inline int number_of_entries(DependencyGroup group);
5602 inline void set_number_of_entries(DependencyGroup group, int value);
5603 inline bool is_code_at(int i);
5604 inline Code* code_at(int i);
5605 inline CompilationInfo* compilation_info_at(int i);
5606 inline void set_object_at(int i, Object* object);
5607 inline Object** slot_at(int i);
5608 inline Object* object_at(int i);
5609 inline void clear_at(int i);
5610 inline void copy(int from, int to);
5611 DECLARE_CAST(DependentCode)
5613 static DependentCode* ForObject(Handle<HeapObject> object,
5614 DependencyGroup group);
5616 static const char* DependencyGroupName(DependencyGroup group);
5617 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5620 // Make a room at the end of the given group by moving out the first
5621 // code objects of the subsequent groups.
5622 inline void ExtendGroup(DependencyGroup group);
5623 static const int kCodesStartIndex = kGroupCount;
5627 // All heap objects have a Map that describes their structure.
5628 // A Map contains information about:
5629 // - Size information about the object
5630 // - How to iterate over an object (for garbage collection)
5631 class Map: public HeapObject {
5634 // Size in bytes or kVariableSizeSentinel if instances do not have
5636 inline int instance_size();
5637 inline void set_instance_size(int value);
5639 // Count of properties allocated in the object.
5640 inline int inobject_properties();
5641 inline void set_inobject_properties(int value);
5643 // Count of property fields pre-allocated in the object when first allocated.
5644 inline int pre_allocated_property_fields();
5645 inline void set_pre_allocated_property_fields(int value);
5648 inline InstanceType instance_type();
5649 inline void set_instance_type(InstanceType value);
5651 // Tells how many unused property fields are available in the
5652 // instance (only used for JSObject in fast mode).
5653 inline int unused_property_fields();
5654 inline void set_unused_property_fields(int value);
5657 inline byte bit_field();
5658 inline void set_bit_field(byte value);
5661 inline byte bit_field2();
5662 inline void set_bit_field2(byte value);
5665 inline uint32_t bit_field3();
5666 inline void set_bit_field3(uint32_t bits);
5668 class EnumLengthBits: public BitField<int,
5669 0, kDescriptorIndexBitCount> {}; // NOLINT
5670 class NumberOfOwnDescriptorsBits: public BitField<int,
5671 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5672 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5673 class DictionaryMap : public BitField<bool, 20, 1> {};
5674 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5675 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5676 class Deprecated : public BitField<bool, 23, 1> {};
5677 class IsFrozen : public BitField<bool, 24, 1> {};
5678 class IsUnstable : public BitField<bool, 25, 1> {};
5679 class IsMigrationTarget : public BitField<bool, 26, 1> {};
5680 class DoneInobjectSlackTracking : public BitField<bool, 27, 1> {};
5683 // Keep this bit field at the very end for better code in
5684 // Builtins::kJSConstructStubGeneric stub.
5685 class ConstructionCount: public BitField<int, 29, 3> {};
5687 // Tells whether the object in the prototype property will be used
5688 // for instances created from this function. If the prototype
5689 // property is set to a value that is not a JSObject, the prototype
5690 // property will not be used to create instances of the function.
5691 // See ECMA-262, 13.2.2.
5692 inline void set_non_instance_prototype(bool value);
5693 inline bool has_non_instance_prototype();
5695 // Tells whether function has special prototype property. If not, prototype
5696 // property will not be created when accessed (will return undefined),
5697 // and construction from this function will not be allowed.
5698 inline void set_function_with_prototype(bool value);
5699 inline bool function_with_prototype();
5701 // Tells whether the instance with this map should be ignored by the
5702 // Object.getPrototypeOf() function and the __proto__ accessor.
5703 inline void set_is_hidden_prototype() {
5704 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5707 inline bool is_hidden_prototype() {
5708 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5711 // Records and queries whether the instance has a named interceptor.
5712 inline void set_has_named_interceptor() {
5713 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5716 inline bool has_named_interceptor() {
5717 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5720 // Records and queries whether the instance has an indexed interceptor.
5721 inline void set_has_indexed_interceptor() {
5722 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5725 inline bool has_indexed_interceptor() {
5726 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5729 // Tells whether the instance is undetectable.
5730 // An undetectable object is a special class of JSObject: 'typeof' operator
5731 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5732 // a normal JS object. It is useful for implementing undetectable
5733 // document.all in Firefox & Safari.
5734 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5735 inline void set_is_undetectable() {
5736 set_bit_field(bit_field() | (1 << kIsUndetectable));
5739 inline bool is_undetectable() {
5740 return ((1 << kIsUndetectable) & bit_field()) != 0;
5743 // Tells whether the instance has a call-as-function handler.
5744 inline void set_is_observed() {
5745 set_bit_field(bit_field() | (1 << kIsObserved));
5748 inline bool is_observed() {
5749 return ((1 << kIsObserved) & bit_field()) != 0;
5752 inline void set_is_extensible(bool value);
5753 inline bool is_extensible();
5754 inline void set_is_prototype_map(bool value);
5755 inline bool is_prototype_map();
5757 inline void set_elements_kind(ElementsKind elements_kind) {
5758 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5759 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5760 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5761 DCHECK(this->elements_kind() == elements_kind);
5764 inline ElementsKind elements_kind() {
5765 return Map::ElementsKindBits::decode(bit_field2());
5768 // Tells whether the instance has fast elements that are only Smis.
5769 inline bool has_fast_smi_elements() {
5770 return IsFastSmiElementsKind(elements_kind());
5773 // Tells whether the instance has fast elements.
5774 inline bool has_fast_object_elements() {
5775 return IsFastObjectElementsKind(elements_kind());
5778 inline bool has_fast_smi_or_object_elements() {
5779 return IsFastSmiOrObjectElementsKind(elements_kind());
5782 inline bool has_fast_double_elements() {
5783 return IsFastDoubleElementsKind(elements_kind());
5786 inline bool has_fast_elements() {
5787 return IsFastElementsKind(elements_kind());
5790 inline bool has_sloppy_arguments_elements() {
5791 return elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5794 inline bool has_external_array_elements() {
5795 return IsExternalArrayElementsKind(elements_kind());
5798 inline bool has_fixed_typed_array_elements() {
5799 return IsFixedTypedArrayElementsKind(elements_kind());
5802 inline bool has_dictionary_elements() {
5803 return IsDictionaryElementsKind(elements_kind());
5806 inline bool has_slow_elements_kind() {
5807 return elements_kind() == DICTIONARY_ELEMENTS
5808 || elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5811 static bool IsValidElementsTransition(ElementsKind from_kind,
5812 ElementsKind to_kind);
5814 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5815 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5816 bool DictionaryElementsInPrototypeChainOnly();
5818 inline bool HasTransitionArray() const;
5819 inline bool HasElementsTransition();
5820 inline Map* elements_transition_map();
5822 inline Map* GetTransition(int transition_index);
5823 inline int SearchTransition(Name* name);
5824 inline FixedArrayBase* GetInitialElements();
5826 DECL_ACCESSORS(transitions, TransitionArray)
5828 static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
5829 static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
5831 // Try to follow an existing transition to a field with attributes NONE. The
5832 // return value indicates whether the transition was successful.
5833 static inline Handle<Map> FindTransitionToField(Handle<Map> map,
5837 Map* FindFieldOwner(int descriptor);
5839 inline int GetInObjectPropertyOffset(int index);
5841 int NumberOfFields();
5843 // TODO(ishell): candidate with JSObject::MigrateToMap().
5844 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5845 int target_inobject, int target_unused,
5846 int* old_number_of_fields);
5847 // TODO(ishell): moveit!
5848 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5849 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5850 Handle<HeapType> type1,
5851 Handle<HeapType> type2,
5853 static void GeneralizeFieldType(Handle<Map> map,
5855 Handle<HeapType> new_field_type);
5856 static Handle<Map> GeneralizeRepresentation(
5859 Representation new_representation,
5860 Handle<HeapType> new_field_type,
5861 StoreMode store_mode);
5862 static Handle<Map> CopyGeneralizeAllRepresentations(
5865 StoreMode store_mode,
5866 PropertyAttributes attributes,
5867 const char* reason);
5868 static Handle<Map> CopyGeneralizeAllRepresentations(
5871 StoreMode store_mode,
5872 const char* reason);
5874 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5875 int descriptor_number,
5876 Handle<Object> value);
5878 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode);
5880 // Returns the constructor name (the name (possibly, inferred name) of the
5881 // function that was used to instantiate the object).
5882 String* constructor_name();
5884 // Tells whether the map is used for JSObjects in dictionary mode (ie
5885 // normalized objects, ie objects for which HasFastProperties returns false).
5886 // A map can never be used for both dictionary mode and fast mode JSObjects.
5887 // False by default and for HeapObjects that are not JSObjects.
5888 inline void set_dictionary_map(bool value);
5889 inline bool is_dictionary_map();
5891 // Tells whether the instance needs security checks when accessing its
5893 inline void set_is_access_check_needed(bool access_check_needed);
5894 inline bool is_access_check_needed();
5896 // Returns true if map has a non-empty stub code cache.
5897 inline bool has_code_cache();
5899 // [prototype]: implicit prototype object.
5900 DECL_ACCESSORS(prototype, Object)
5902 // [constructor]: points back to the function responsible for this map.
5903 DECL_ACCESSORS(constructor, Object)
5905 // [instance descriptors]: describes the object.
5906 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5907 inline void InitializeDescriptors(DescriptorArray* descriptors);
5909 // [stub cache]: contains stubs compiled for this map.
5910 DECL_ACCESSORS(code_cache, Object)
5912 // [dependent code]: list of optimized codes that weakly embed this map.
5913 DECL_ACCESSORS(dependent_code, DependentCode)
5915 // [back pointer]: points back to the parent map from which a transition
5916 // leads to this map. The field overlaps with prototype transitions and the
5917 // back pointer will be moved into the prototype transitions array if
5919 inline Object* GetBackPointer();
5920 inline void SetBackPointer(Object* value,
5921 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5922 inline void init_back_pointer(Object* undefined);
5924 // [prototype transitions]: cache of prototype transitions.
5925 // Prototype transition is a transition that happens
5926 // when we change object's prototype to a new one.
5928 // 0: finger - index of the first free cell in the cache
5929 // 1: back pointer that overlaps with prototype transitions field.
5930 // 2 + 2 * i: prototype
5931 // 3 + 2 * i: target map
5932 inline FixedArray* GetPrototypeTransitions();
5933 inline bool HasPrototypeTransitions();
5935 static const int kProtoTransitionHeaderSize = 1;
5936 static const int kProtoTransitionNumberOfEntriesOffset = 0;
5937 static const int kProtoTransitionElementsPerEntry = 2;
5938 static const int kProtoTransitionPrototypeOffset = 0;
5939 static const int kProtoTransitionMapOffset = 1;
5941 inline int NumberOfProtoTransitions() {
5942 FixedArray* cache = GetPrototypeTransitions();
5943 if (cache->length() == 0) return 0;
5945 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
5948 inline void SetNumberOfProtoTransitions(int value) {
5949 FixedArray* cache = GetPrototypeTransitions();
5950 DCHECK(cache->length() != 0);
5951 cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
5954 // Lookup in the map's instance descriptors and fill out the result
5955 // with the given holder if the name is found. The holder may be
5956 // NULL when this function is used from the compiler.
5957 inline void LookupDescriptor(JSObject* holder,
5959 LookupResult* result);
5961 inline void LookupTransition(JSObject* holder,
5963 LookupResult* result);
5965 inline PropertyDetails GetLastDescriptorDetails();
5967 // The size of transition arrays are limited so they do not end up in large
5968 // object space. Otherwise ClearNonLiveTransitions would leak memory while
5969 // applying in-place right trimming.
5970 inline bool CanHaveMoreTransitions();
5973 int number_of_own_descriptors = NumberOfOwnDescriptors();
5974 DCHECK(number_of_own_descriptors > 0);
5975 return number_of_own_descriptors - 1;
5978 int NumberOfOwnDescriptors() {
5979 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5982 void SetNumberOfOwnDescriptors(int number) {
5983 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5984 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5987 inline Cell* RetrieveDescriptorsPointer();
5990 return EnumLengthBits::decode(bit_field3());
5993 void SetEnumLength(int length) {
5994 if (length != kInvalidEnumCacheSentinel) {
5995 DCHECK(length >= 0);
5996 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5997 DCHECK(length <= NumberOfOwnDescriptors());
5999 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
6002 inline bool owns_descriptors();
6003 inline void set_owns_descriptors(bool owns_descriptors);
6004 inline bool has_instance_call_handler();
6005 inline void set_has_instance_call_handler();
6006 inline void freeze();
6007 inline bool is_frozen();
6008 inline void mark_unstable();
6009 inline bool is_stable();
6010 inline void set_migration_target(bool value);
6011 inline bool is_migration_target();
6012 inline void set_done_inobject_slack_tracking(bool value);
6013 inline bool done_inobject_slack_tracking();
6014 inline void set_construction_count(int value);
6015 inline int construction_count();
6016 inline void deprecate();
6017 inline bool is_deprecated();
6018 inline bool CanBeDeprecated();
6019 // Returns a non-deprecated version of the input. If the input was not
6020 // deprecated, it is directly returned. Otherwise, the non-deprecated version
6021 // is found by re-transitioning from the root of the transition tree using the
6022 // descriptor array of the map. Returns NULL if no updated map is found.
6023 // This method also applies any pending migrations along the prototype chain.
6024 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
6025 // Same as above, but does not touch the prototype chain.
6026 static MaybeHandle<Map> TryUpdateInternal(Handle<Map> map)
6029 // Returns a non-deprecated version of the input. This method may deprecate
6030 // existing maps along the way if encodings conflict. Not for use while
6031 // gathering type feedback. Use TryUpdate in those cases instead.
6032 static Handle<Map> Update(Handle<Map> map);
6034 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6035 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
6036 Descriptor* descriptor,
6037 TransitionFlag flag);
6039 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
6042 Handle<HeapType> type,
6043 PropertyAttributes attributes,
6044 Representation representation,
6045 TransitionFlag flag);
6047 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
6050 Handle<Object> constant,
6051 PropertyAttributes attributes,
6052 TransitionFlag flag);
6054 // Returns a new map with all transitions dropped from the given map and
6055 // the ElementsKind set.
6056 static Handle<Map> TransitionElementsTo(Handle<Map> map,
6057 ElementsKind to_kind);
6059 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
6061 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
6063 TransitionFlag flag);
6065 static Handle<Map> CopyForObserved(Handle<Map> map);
6067 static Handle<Map> CopyForFreeze(Handle<Map> map);
6068 // Maximal number of fast properties. Used to restrict the number of map
6069 // transitions to avoid an explosion in the number of maps for objects used as
6071 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
6072 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
6074 Handle<Object> value,
6075 PropertyAttributes attributes,
6076 StoreFromKeyed store_mode);
6077 static Handle<Map> TransitionToAccessorProperty(
6078 Handle<Map> map, Handle<Name> name, AccessorComponent component,
6079 Handle<Object> accessor, PropertyAttributes attributes);
6080 static Handle<Map> ReconfigureDataProperty(Handle<Map> map, int descriptor,
6081 PropertyAttributes attributes);
6083 inline void AppendDescriptor(Descriptor* desc);
6085 // Returns a copy of the map, with all transitions dropped from the
6086 // instance descriptors.
6087 static Handle<Map> Copy(Handle<Map> map);
6088 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
6090 // Returns the next free property index (only valid for FAST MODE).
6091 int NextFreePropertyIndex();
6093 // Returns the number of properties described in instance_descriptors
6094 // filtering out properties with the specified attributes.
6095 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6096 PropertyAttributes filter = NONE);
6098 // Returns the number of slots allocated for the initial properties
6099 // backing storage for instances of this map.
6100 int InitialPropertiesLength() {
6101 return pre_allocated_property_fields() + unused_property_fields() -
6102 inobject_properties();
6107 // Code cache operations.
6109 // Clears the code cache.
6110 inline void ClearCodeCache(Heap* heap);
6112 // Update code cache.
6113 static void UpdateCodeCache(Handle<Map> map,
6117 // Extend the descriptor array of the map with the list of descriptors.
6118 // In case of duplicates, the latest descriptor is used.
6119 static void AppendCallbackDescriptors(Handle<Map> map,
6120 Handle<Object> descriptors);
6122 static inline int SlackForArraySize(int old_size, int size_limit);
6124 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6126 // Returns the found code or undefined if absent.
6127 Object* FindInCodeCache(Name* name, Code::Flags flags);
6129 // Returns the non-negative index of the code object if it is in the
6130 // cache and -1 otherwise.
6131 int IndexInCodeCache(Object* name, Code* code);
6133 // Removes a code object from the code cache at the given index.
6134 void RemoveFromCodeCache(Name* name, Code* code, int index);
6136 // Set all map transitions from this map to dead maps to null. Also clear
6137 // back pointers in transition targets so that we do not process this map
6138 // again while following back pointers.
6139 void ClearNonLiveTransitions(Heap* heap);
6141 // Computes a hash value for this map, to be used in HashTables and such.
6144 // Returns the map that this map transitions to if its elements_kind
6145 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6146 // |safe_to_add_transitions| is set to false if adding transitions is not
6148 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6150 // Returns the transitioned map for this map with the most generic
6151 // elements_kind that's found in |candidates|, or null handle if no match is
6153 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6155 bool CanTransition() {
6156 // Only JSObject and subtypes have map transitions and back pointers.
6157 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6158 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6161 bool IsJSObjectMap() {
6162 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6164 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6165 bool IsJSProxyMap() {
6166 InstanceType type = instance_type();
6167 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6169 bool IsJSGlobalProxyMap() {
6170 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6172 bool IsJSGlobalObjectMap() {
6173 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6175 bool IsGlobalObjectMap() {
6176 const InstanceType type = instance_type();
6177 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6180 inline bool CanOmitMapChecks();
6182 static void AddDependentCompilationInfo(Handle<Map> map,
6183 DependentCode::DependencyGroup group,
6184 CompilationInfo* info);
6186 static void AddDependentCode(Handle<Map> map,
6187 DependentCode::DependencyGroup group,
6189 static void AddDependentIC(Handle<Map> map,
6192 bool IsMapInArrayPrototypeChain();
6194 // Dispatched behavior.
6195 DECLARE_PRINTER(Map)
6196 DECLARE_VERIFIER(Map)
6199 void DictionaryMapVerify();
6200 void VerifyOmittedMapChecks();
6203 inline int visitor_id();
6204 inline void set_visitor_id(int visitor_id);
6206 typedef void (*TraverseCallback)(Map* map, void* data);
6208 void TraverseTransitionTree(TraverseCallback callback, void* data);
6210 // When you set the prototype of an object using the __proto__ accessor you
6211 // need a new map for the object (the prototype is stored in the map). In
6212 // order not to multiply maps unnecessarily we store these as transitions in
6213 // the original map. That way we can transition to the same map if the same
6214 // prototype is set, rather than creating a new map every time. The
6215 // transitions are in the form of a map where the keys are prototype objects
6216 // and the values are the maps the are transitioned to.
6217 static const int kMaxCachedPrototypeTransitions = 256;
6218 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6219 Handle<Object> prototype);
6221 static const int kMaxPreAllocatedPropertyFields = 255;
6223 // Layout description.
6224 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6225 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6226 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6227 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6228 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6229 // Storage for the transition array is overloaded to directly contain a back
6230 // pointer if unused. When the map has transitions, the back pointer is
6231 // transferred to the transition array and accessed through an extra
6233 static const int kTransitionsOrBackPointerOffset =
6234 kConstructorOffset + kPointerSize;
6235 static const int kDescriptorsOffset =
6236 kTransitionsOrBackPointerOffset + kPointerSize;
6237 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6238 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6239 static const int kSize = kDependentCodeOffset + kPointerSize;
6241 // Layout of pointer fields. Heap iteration code relies on them
6242 // being continuously allocated.
6243 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6244 static const int kPointerFieldsEndOffset = kSize;
6246 // Byte offsets within kInstanceSizesOffset.
6247 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6248 static const int kInObjectPropertiesByte = 1;
6249 static const int kInObjectPropertiesOffset =
6250 kInstanceSizesOffset + kInObjectPropertiesByte;
6251 static const int kPreAllocatedPropertyFieldsByte = 2;
6252 static const int kPreAllocatedPropertyFieldsOffset =
6253 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6254 static const int kVisitorIdByte = 3;
6255 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6257 // Byte offsets within kInstanceAttributesOffset attributes.
6258 #if V8_TARGET_LITTLE_ENDIAN
6259 // Order instance type and bit field together such that they can be loaded
6260 // together as a 16-bit word with instance type in the lower 8 bits regardless
6261 // of endianess. Also provide endian-independent offset to that 16-bit word.
6262 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6263 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6265 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6266 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6268 static const int kInstanceTypeAndBitFieldOffset =
6269 kInstanceAttributesOffset + 0;
6270 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6271 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6273 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6274 Internals::kMapInstanceTypeAndBitFieldOffset);
6276 // Bit positions for bit field.
6277 static const int kHasNonInstancePrototype = 0;
6278 static const int kIsHiddenPrototype = 1;
6279 static const int kHasNamedInterceptor = 2;
6280 static const int kHasIndexedInterceptor = 3;
6281 static const int kIsUndetectable = 4;
6282 static const int kIsObserved = 5;
6283 static const int kIsAccessCheckNeeded = 6;
6284 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6286 // Bit positions for bit field 2
6287 static const int kIsExtensible = 0;
6288 static const int kStringWrapperSafeForDefaultValueOf = 1;
6289 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6290 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6292 // Derived values from bit field 2
6293 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6294 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6295 static const int8_t kMaximumBitField2FastSmiElementValue =
6296 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6297 Map::ElementsKindBits::kShift) - 1;
6298 static const int8_t kMaximumBitField2FastHoleyElementValue =
6299 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6300 Map::ElementsKindBits::kShift) - 1;
6301 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6302 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6303 Map::ElementsKindBits::kShift) - 1;
6305 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6306 kPointerFieldsEndOffset,
6307 kSize> BodyDescriptor;
6309 // Compares this map to another to see if they describe equivalent objects.
6310 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6311 // it had exactly zero inobject properties.
6312 // The "shared" flags of both this map and |other| are ignored.
6313 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6316 static void ConnectElementsTransition(Handle<Map> parent, Handle<Map> child);
6317 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6318 Handle<Name> name, SimpleTransitionFlag flag);
6320 bool EquivalentToForTransition(Map* other);
6321 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6322 static Handle<Map> ShareDescriptor(Handle<Map> map,
6323 Handle<DescriptorArray> descriptors,
6324 Descriptor* descriptor);
6325 static Handle<Map> CopyInstallDescriptors(
6328 Handle<DescriptorArray> descriptors);
6329 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6330 Descriptor* descriptor,
6331 TransitionFlag flag);
6332 static Handle<Map> CopyReplaceDescriptors(
6334 Handle<DescriptorArray> descriptors,
6335 TransitionFlag flag,
6336 MaybeHandle<Name> maybe_name,
6337 SimpleTransitionFlag simple_flag = FULL_TRANSITION);
6338 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6339 Handle<DescriptorArray> descriptors,
6340 Descriptor* descriptor,
6342 TransitionFlag flag);
6344 static Handle<Map> CopyNormalized(Handle<Map> map,
6345 PropertyNormalizationMode mode);
6347 // Fires when the layout of an object with a leaf map changes.
6348 // This includes adding transitions to the leaf map or changing
6349 // the descriptor array.
6350 inline void NotifyLeafMapLayoutChange();
6352 static Handle<Map> TransitionElementsToSlow(Handle<Map> object,
6353 ElementsKind to_kind);
6355 // Zaps the contents of backing data structures. Note that the
6356 // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6357 // holding weak references when incremental marking is used, because it also
6358 // iterates over objects that are otherwise unreachable.
6359 // In general we only want to call these functions in release mode when
6360 // heap verification is turned on.
6361 void ZapPrototypeTransitions();
6362 void ZapTransitions();
6364 void DeprecateTransitionTree();
6365 bool DeprecateTarget(Name* key, DescriptorArray* new_descriptors);
6367 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6369 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6370 Handle<HeapType> new_type);
6372 void PrintGeneralization(FILE* file,
6377 bool constant_to_field,
6378 Representation old_representation,
6379 Representation new_representation,
6380 HeapType* old_field_type,
6381 HeapType* new_field_type);
6383 static inline void SetPrototypeTransitions(
6385 Handle<FixedArray> prototype_transitions);
6387 static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6388 Handle<Object> prototype);
6389 static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6390 Handle<Object> prototype,
6391 Handle<Map> target_map);
6393 static const int kFastPropertiesSoftLimit = 12;
6394 static const int kMaxFastProperties = 128;
6396 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6400 // An abstract superclass, a marker class really, for simple structure classes.
6401 // It doesn't carry much functionality but allows struct classes to be
6402 // identified in the type system.
6403 class Struct: public HeapObject {
6405 inline void InitializeBody(int object_size);
6406 DECLARE_CAST(Struct)
6410 // A simple one-element struct, useful where smis need to be boxed.
6411 class Box : public Struct {
6413 // [value]: the boxed contents.
6414 DECL_ACCESSORS(value, Object)
6418 // Dispatched behavior.
6419 DECLARE_PRINTER(Box)
6420 DECLARE_VERIFIER(Box)
6422 static const int kValueOffset = HeapObject::kHeaderSize;
6423 static const int kSize = kValueOffset + kPointerSize;
6426 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6430 // Script describes a script which has been added to the VM.
6431 class Script: public Struct {
6440 // Script compilation types.
6441 enum CompilationType {
6442 COMPILATION_TYPE_HOST = 0,
6443 COMPILATION_TYPE_EVAL = 1
6446 // Script compilation state.
6447 enum CompilationState {
6448 COMPILATION_STATE_INITIAL = 0,
6449 COMPILATION_STATE_COMPILED = 1
6452 // [source]: the script source.
6453 DECL_ACCESSORS(source, Object)
6455 // [name]: the script name.
6456 DECL_ACCESSORS(name, Object)
6458 // [id]: the script id.
6459 DECL_ACCESSORS(id, Smi)
6461 // [line_offset]: script line offset in resource from where it was extracted.
6462 DECL_ACCESSORS(line_offset, Smi)
6464 // [column_offset]: script column offset in resource from where it was
6466 DECL_ACCESSORS(column_offset, Smi)
6468 // [context_data]: context data for the context this script was compiled in.
6469 DECL_ACCESSORS(context_data, Object)
6471 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6472 DECL_ACCESSORS(wrapper, HeapObject)
6474 // [type]: the script type.
6475 DECL_ACCESSORS(type, Smi)
6477 // [line_ends]: FixedArray of line ends positions.
6478 DECL_ACCESSORS(line_ends, Object)
6480 // [eval_from_shared]: for eval scripts the shared funcion info for the
6481 // function from which eval was called.
6482 DECL_ACCESSORS(eval_from_shared, Object)
6484 // [eval_from_instructions_offset]: the instruction offset in the code for the
6485 // function from which eval was called where eval was called.
6486 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6488 // [flags]: Holds an exciting bitfield.
6489 DECL_ACCESSORS(flags, Smi)
6491 // [source_url]: sourceURL from magic comment
6492 DECL_ACCESSORS(source_url, Object)
6494 // [source_url]: sourceMappingURL magic comment
6495 DECL_ACCESSORS(source_mapping_url, Object)
6497 // [compilation_type]: how the the script was compiled. Encoded in the
6499 inline CompilationType compilation_type();
6500 inline void set_compilation_type(CompilationType type);
6502 // [compilation_state]: determines whether the script has already been
6503 // compiled. Encoded in the 'flags' field.
6504 inline CompilationState compilation_state();
6505 inline void set_compilation_state(CompilationState state);
6507 // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6508 // ScriptOrigin, and used by the embedder to make decisions about the
6509 // script's level of privilege. V8 just passes this through. Encoded in
6510 // the 'flags' field.
6511 DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6513 DECLARE_CAST(Script)
6515 // If script source is an external string, check that the underlying
6516 // resource is accessible. Otherwise, always return true.
6517 inline bool HasValidSource();
6519 // Convert code position into column number.
6520 static int GetColumnNumber(Handle<Script> script, int code_pos);
6522 // Convert code position into (zero-based) line number.
6523 // The non-handlified version does not allocate, but may be much slower.
6524 static int GetLineNumber(Handle<Script> script, int code_pos);
6525 int GetLineNumber(int code_pos);
6527 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6529 // Init line_ends array with code positions of line ends inside script source.
6530 static void InitLineEnds(Handle<Script> script);
6532 // Get the JS object wrapping the given script; create it if none exists.
6533 static Handle<JSObject> GetWrapper(Handle<Script> script);
6535 // Dispatched behavior.
6536 DECLARE_PRINTER(Script)
6537 DECLARE_VERIFIER(Script)
6539 static const int kSourceOffset = HeapObject::kHeaderSize;
6540 static const int kNameOffset = kSourceOffset + kPointerSize;
6541 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6542 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6543 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6544 static const int kWrapperOffset = kContextOffset + kPointerSize;
6545 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6546 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6547 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6548 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6549 static const int kEvalFrominstructionsOffsetOffset =
6550 kEvalFromSharedOffset + kPointerSize;
6551 static const int kFlagsOffset =
6552 kEvalFrominstructionsOffsetOffset + kPointerSize;
6553 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6554 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6555 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6558 int GetLineNumberWithArray(int code_pos);
6560 // Bit positions in the flags field.
6561 static const int kCompilationTypeBit = 0;
6562 static const int kCompilationStateBit = 1;
6563 static const int kIsSharedCrossOriginBit = 2;
6565 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6569 // List of builtin functions we want to identify to improve code
6572 // Each entry has a name of a global object property holding an object
6573 // optionally followed by ".prototype", a name of a builtin function
6574 // on the object (the one the id is set for), and a label.
6576 // Installation of ids for the selected builtin functions is handled
6577 // by the bootstrapper.
6578 #define FUNCTIONS_WITH_ID_LIST(V) \
6579 V(Array.prototype, indexOf, ArrayIndexOf) \
6580 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6581 V(Array.prototype, push, ArrayPush) \
6582 V(Array.prototype, pop, ArrayPop) \
6583 V(Array.prototype, shift, ArrayShift) \
6584 V(Function.prototype, apply, FunctionApply) \
6585 V(Function.prototype, call, FunctionCall) \
6586 V(String.prototype, charCodeAt, StringCharCodeAt) \
6587 V(String.prototype, charAt, StringCharAt) \
6588 V(String, fromCharCode, StringFromCharCode) \
6589 V(Math, random, MathRandom) \
6590 V(Math, floor, MathFloor) \
6591 V(Math, round, MathRound) \
6592 V(Math, ceil, MathCeil) \
6593 V(Math, abs, MathAbs) \
6594 V(Math, log, MathLog) \
6595 V(Math, exp, MathExp) \
6596 V(Math, sqrt, MathSqrt) \
6597 V(Math, pow, MathPow) \
6598 V(Math, max, MathMax) \
6599 V(Math, min, MathMin) \
6600 V(Math, cos, MathCos) \
6601 V(Math, sin, MathSin) \
6602 V(Math, tan, MathTan) \
6603 V(Math, acos, MathAcos) \
6604 V(Math, asin, MathAsin) \
6605 V(Math, atan, MathAtan) \
6606 V(Math, atan2, MathAtan2) \
6607 V(Math, imul, MathImul) \
6608 V(Math, clz32, MathClz32) \
6609 V(Math, fround, MathFround)
6611 enum BuiltinFunctionId {
6613 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6615 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6616 #undef DECLARE_FUNCTION_ID
6617 // Fake id for a special case of Math.pow. Note, it continues the
6618 // list of math functions.
6623 // SharedFunctionInfo describes the JSFunction information that can be
6624 // shared by multiple instances of the function.
6625 class SharedFunctionInfo: public HeapObject {
6627 // [name]: Function name.
6628 DECL_ACCESSORS(name, Object)
6630 // [code]: Function code.
6631 DECL_ACCESSORS(code, Code)
6632 inline void ReplaceCode(Code* code);
6634 // [optimized_code_map]: Map from native context to optimized code
6635 // and a shared literals array or Smi(0) if none.
6636 DECL_ACCESSORS(optimized_code_map, Object)
6638 // Returns index i of the entry with the specified context and OSR entry.
6639 // At position i - 1 is the context, position i the code, and i + 1 the
6640 // literals array. Returns -1 when no matching entry is found.
6641 int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
6643 // Installs optimized code from the code map on the given closure. The
6644 // index has to be consistent with a search result as defined above.
6645 FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
6647 Code* GetCodeFromOptimizedCodeMap(int index);
6649 // Clear optimized code map.
6650 void ClearOptimizedCodeMap();
6652 // Removed a specific optimized code object from the optimized code map.
6653 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6655 void ClearTypeFeedbackInfo();
6657 // Trims the optimized code map after entries have been removed.
6658 void TrimOptimizedCodeMap(int shrink_by);
6660 // Add a new entry to the optimized code map.
6661 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6662 Handle<Context> native_context,
6664 Handle<FixedArray> literals,
6665 BailoutId osr_ast_id);
6667 // Layout description of the optimized code map.
6668 static const int kNextMapIndex = 0;
6669 static const int kEntriesStart = 1;
6670 static const int kContextOffset = 0;
6671 static const int kCachedCodeOffset = 1;
6672 static const int kLiteralsOffset = 2;
6673 static const int kOsrAstIdOffset = 3;
6674 static const int kEntryLength = 4;
6675 static const int kInitialLength = kEntriesStart + kEntryLength;
6677 // [scope_info]: Scope info.
6678 DECL_ACCESSORS(scope_info, ScopeInfo)
6680 // [construct stub]: Code stub for constructing instances of this function.
6681 DECL_ACCESSORS(construct_stub, Code)
6683 // Returns if this function has been compiled to native code yet.
6684 inline bool is_compiled();
6686 // [length]: The function length - usually the number of declared parameters.
6687 // Use up to 2^30 parameters.
6688 inline int length() const;
6689 inline void set_length(int value);
6691 // [formal parameter count]: The declared number of parameters.
6692 inline int formal_parameter_count() const;
6693 inline void set_formal_parameter_count(int value);
6695 // Set the formal parameter count so the function code will be
6696 // called without using argument adaptor frames.
6697 inline void DontAdaptArguments();
6699 // [expected_nof_properties]: Expected number of properties for the function.
6700 inline int expected_nof_properties() const;
6701 inline void set_expected_nof_properties(int value);
6703 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6704 // (increasingly) from crankshafted code where sufficient feedback isn't
6706 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6708 // [instance class name]: class name for instances.
6709 DECL_ACCESSORS(instance_class_name, Object)
6711 // [function data]: This field holds some additional data for function.
6712 // Currently it either has FunctionTemplateInfo to make benefit the API
6713 // or Smi identifying a builtin function.
6714 // In the long run we don't want all functions to have this field but
6715 // we can fix that when we have a better model for storing hidden data
6717 DECL_ACCESSORS(function_data, Object)
6719 inline bool IsApiFunction();
6720 inline FunctionTemplateInfo* get_api_func_data();
6721 inline bool HasBuiltinFunctionId();
6722 inline BuiltinFunctionId builtin_function_id();
6724 // [script info]: Script from which the function originates.
6725 DECL_ACCESSORS(script, Object)
6727 // [num_literals]: Number of literals used by this function.
6728 inline int num_literals() const;
6729 inline void set_num_literals(int value);
6731 // [start_position_and_type]: Field used to store both the source code
6732 // position, whether or not the function is a function expression,
6733 // and whether or not the function is a toplevel function. The two
6734 // least significants bit indicates whether the function is an
6735 // expression and the rest contains the source code position.
6736 inline int start_position_and_type() const;
6737 inline void set_start_position_and_type(int value);
6739 // [debug info]: Debug information.
6740 DECL_ACCESSORS(debug_info, Object)
6742 // [inferred name]: Name inferred from variable or property
6743 // assignment of this function. Used to facilitate debugging and
6744 // profiling of JavaScript code written in OO style, where almost
6745 // all functions are anonymous but are assigned to object
6747 DECL_ACCESSORS(inferred_name, String)
6749 // The function's name if it is non-empty, otherwise the inferred name.
6750 String* DebugName();
6752 // Position of the 'function' token in the script source.
6753 inline int function_token_position() const;
6754 inline void set_function_token_position(int function_token_position);
6756 // Position of this function in the script source.
6757 inline int start_position() const;
6758 inline void set_start_position(int start_position);
6760 // End position of this function in the script source.
6761 inline int end_position() const;
6762 inline void set_end_position(int end_position);
6764 // Is this function a function expression in the source code.
6765 DECL_BOOLEAN_ACCESSORS(is_expression)
6767 // Is this function a top-level function (scripts, evals).
6768 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6770 // Bit field containing various information collected by the compiler to
6771 // drive optimization.
6772 inline int compiler_hints() const;
6773 inline void set_compiler_hints(int value);
6775 inline int ast_node_count() const;
6776 inline void set_ast_node_count(int count);
6778 inline int profiler_ticks() const;
6779 inline void set_profiler_ticks(int ticks);
6781 // Inline cache age is used to infer whether the function survived a context
6782 // disposal or not. In the former case we reset the opt_count.
6783 inline int ic_age();
6784 inline void set_ic_age(int age);
6786 // Indicates if this function can be lazy compiled.
6787 // This is used to determine if we can safely flush code from a function
6788 // when doing GC if we expect that the function will no longer be used.
6789 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6791 // Indicates if this function can be lazy compiled without a context.
6792 // This is used to determine if we can force compilation without reaching
6793 // the function through program execution but through other means (e.g. heap
6794 // iteration by the debugger).
6795 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6797 // Indicates whether optimizations have been disabled for this
6798 // shared function info. If a function is repeatedly optimized or if
6799 // we cannot optimize the function we disable optimization to avoid
6800 // spending time attempting to optimize it again.
6801 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6803 // Indicates the language mode.
6804 inline StrictMode strict_mode();
6805 inline void set_strict_mode(StrictMode strict_mode);
6807 // False if the function definitely does not allocate an arguments object.
6808 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6810 // True if the function has any duplicated parameter names.
6811 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6813 // Indicates whether the function is a native function.
6814 // These needs special treatment in .call and .apply since
6815 // null passed as the receiver should not be translated to the
6817 DECL_BOOLEAN_ACCESSORS(native)
6819 // Indicate that this builtin needs to be inlined in crankshaft.
6820 DECL_BOOLEAN_ACCESSORS(inline_builtin)
6822 // Indicates that the function was created by the Function function.
6823 // Though it's anonymous, toString should treat it as if it had the name
6824 // "anonymous". We don't set the name itself so that the system does not
6825 // see a binding for it.
6826 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6828 // Indicates whether the function is a bound function created using
6829 // the bind function.
6830 DECL_BOOLEAN_ACCESSORS(bound)
6832 // Indicates that the function is anonymous (the name field can be set
6833 // through the API, which does not change this flag).
6834 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6836 // Is this a function or top-level/eval code.
6837 DECL_BOOLEAN_ACCESSORS(is_function)
6839 // Indicates that code for this function cannot be cached.
6840 DECL_BOOLEAN_ACCESSORS(dont_cache)
6842 // Indicates that code for this function cannot be flushed.
6843 DECL_BOOLEAN_ACCESSORS(dont_flush)
6845 // Indicates that this function is a generator.
6846 DECL_BOOLEAN_ACCESSORS(is_generator)
6848 // Indicates that this function is an arrow function.
6849 DECL_BOOLEAN_ACCESSORS(is_arrow)
6851 // Indicates that this function is a concise method.
6852 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6854 // Indicates that this function is an asm function.
6855 DECL_BOOLEAN_ACCESSORS(asm_function)
6857 // Indicates that the the shared function info is deserialized from cache.
6858 DECL_BOOLEAN_ACCESSORS(deserialized)
6860 inline FunctionKind kind();
6861 inline void set_kind(FunctionKind kind);
6863 // Indicates whether or not the code in the shared function support
6865 inline bool has_deoptimization_support();
6867 // Enable deoptimization support through recompiled code.
6868 void EnableDeoptimizationSupport(Code* recompiled);
6870 // Disable (further) attempted optimization of all functions sharing this
6871 // shared function info.
6872 void DisableOptimization(BailoutReason reason);
6874 inline BailoutReason DisableOptimizationReason();
6876 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6877 // code, returns whether it asserted (i.e., always true if assertions are
6879 bool VerifyBailoutId(BailoutId id);
6881 // [source code]: Source code for the function.
6882 bool HasSourceCode() const;
6883 Handle<Object> GetSourceCode();
6885 // Number of times the function was optimized.
6886 inline int opt_count();
6887 inline void set_opt_count(int opt_count);
6889 // Number of times the function was deoptimized.
6890 inline void set_deopt_count(int value);
6891 inline int deopt_count();
6892 inline void increment_deopt_count();
6894 // Number of time we tried to re-enable optimization after it
6895 // was disabled due to high number of deoptimizations.
6896 inline void set_opt_reenable_tries(int value);
6897 inline int opt_reenable_tries();
6899 inline void TryReenableOptimization();
6901 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6902 inline void set_counters(int value);
6903 inline int counters() const;
6905 // Stores opt_count and bailout_reason as bit-fields.
6906 inline void set_opt_count_and_bailout_reason(int value);
6907 inline int opt_count_and_bailout_reason() const;
6909 void set_bailout_reason(BailoutReason reason) {
6910 set_opt_count_and_bailout_reason(
6911 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6915 // Check whether or not this function is inlineable.
6916 bool IsInlineable();
6918 // Source size of this function.
6921 // Calculate the instance size.
6922 int CalculateInstanceSize();
6924 // Calculate the number of in-object properties.
6925 int CalculateInObjectProperties();
6927 // Dispatched behavior.
6928 DECLARE_PRINTER(SharedFunctionInfo)
6929 DECLARE_VERIFIER(SharedFunctionInfo)
6931 void ResetForNewContext(int new_ic_age);
6933 DECLARE_CAST(SharedFunctionInfo)
6936 static const int kDontAdaptArgumentsSentinel = -1;
6938 // Layout description.
6940 static const int kNameOffset = HeapObject::kHeaderSize;
6941 static const int kCodeOffset = kNameOffset + kPointerSize;
6942 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6943 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6944 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6945 static const int kInstanceClassNameOffset =
6946 kConstructStubOffset + kPointerSize;
6947 static const int kFunctionDataOffset =
6948 kInstanceClassNameOffset + kPointerSize;
6949 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6950 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6951 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6952 static const int kFeedbackVectorOffset =
6953 kInferredNameOffset + kPointerSize;
6954 #if V8_HOST_ARCH_32_BIT
6956 static const int kLengthOffset =
6957 kFeedbackVectorOffset + kPointerSize;
6958 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6959 static const int kExpectedNofPropertiesOffset =
6960 kFormalParameterCountOffset + kPointerSize;
6961 static const int kNumLiteralsOffset =
6962 kExpectedNofPropertiesOffset + kPointerSize;
6963 static const int kStartPositionAndTypeOffset =
6964 kNumLiteralsOffset + kPointerSize;
6965 static const int kEndPositionOffset =
6966 kStartPositionAndTypeOffset + kPointerSize;
6967 static const int kFunctionTokenPositionOffset =
6968 kEndPositionOffset + kPointerSize;
6969 static const int kCompilerHintsOffset =
6970 kFunctionTokenPositionOffset + kPointerSize;
6971 static const int kOptCountAndBailoutReasonOffset =
6972 kCompilerHintsOffset + kPointerSize;
6973 static const int kCountersOffset =
6974 kOptCountAndBailoutReasonOffset + kPointerSize;
6975 static const int kAstNodeCountOffset =
6976 kCountersOffset + kPointerSize;
6977 static const int kProfilerTicksOffset =
6978 kAstNodeCountOffset + kPointerSize;
6981 static const int kSize = kProfilerTicksOffset + kPointerSize;
6983 // The only reason to use smi fields instead of int fields
6984 // is to allow iteration without maps decoding during
6985 // garbage collections.
6986 // To avoid wasting space on 64-bit architectures we use
6987 // the following trick: we group integer fields into pairs
6988 // The least significant integer in each pair is shifted left by 1.
6989 // By doing this we guarantee that LSB of each kPointerSize aligned
6990 // word is not set and thus this word cannot be treated as pointer
6991 // to HeapObject during old space traversal.
6992 #if V8_TARGET_LITTLE_ENDIAN
6993 static const int kLengthOffset =
6994 kFeedbackVectorOffset + kPointerSize;
6995 static const int kFormalParameterCountOffset =
6996 kLengthOffset + kIntSize;
6998 static const int kExpectedNofPropertiesOffset =
6999 kFormalParameterCountOffset + kIntSize;
7000 static const int kNumLiteralsOffset =
7001 kExpectedNofPropertiesOffset + kIntSize;
7003 static const int kEndPositionOffset =
7004 kNumLiteralsOffset + kIntSize;
7005 static const int kStartPositionAndTypeOffset =
7006 kEndPositionOffset + kIntSize;
7008 static const int kFunctionTokenPositionOffset =
7009 kStartPositionAndTypeOffset + kIntSize;
7010 static const int kCompilerHintsOffset =
7011 kFunctionTokenPositionOffset + kIntSize;
7013 static const int kOptCountAndBailoutReasonOffset =
7014 kCompilerHintsOffset + kIntSize;
7015 static const int kCountersOffset =
7016 kOptCountAndBailoutReasonOffset + kIntSize;
7018 static const int kAstNodeCountOffset =
7019 kCountersOffset + kIntSize;
7020 static const int kProfilerTicksOffset =
7021 kAstNodeCountOffset + kIntSize;
7024 static const int kSize = kProfilerTicksOffset + kIntSize;
7026 #elif V8_TARGET_BIG_ENDIAN
7027 static const int kFormalParameterCountOffset =
7028 kFeedbackVectorOffset + kPointerSize;
7029 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
7031 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
7032 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
7034 static const int kStartPositionAndTypeOffset =
7035 kExpectedNofPropertiesOffset + kIntSize;
7036 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
7038 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
7039 static const int kFunctionTokenPositionOffset =
7040 kCompilerHintsOffset + kIntSize;
7042 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7043 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7045 static const int kProfilerTicksOffset =
7046 kOptCountAndBailoutReasonOffset + kIntSize;
7047 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7050 static const int kSize = kAstNodeCountOffset + kIntSize;
7053 #error Unknown byte ordering
7054 #endif // Big endian
7058 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7060 typedef FixedBodyDescriptor<kNameOffset,
7061 kFeedbackVectorOffset + kPointerSize,
7062 kSize> BodyDescriptor;
7064 // Bit positions in start_position_and_type.
7065 // The source code start position is in the 30 most significant bits of
7066 // the start_position_and_type field.
7067 static const int kIsExpressionBit = 0;
7068 static const int kIsTopLevelBit = 1;
7069 static const int kStartPositionShift = 2;
7070 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7072 // Bit positions in compiler_hints.
7073 enum CompilerHints {
7074 kAllowLazyCompilation,
7075 kAllowLazyCompilationWithoutContext,
7076 kOptimizationDisabled,
7077 kStrictModeFunction,
7079 kHasDuplicateParameters,
7084 kNameShouldPrintAsAnonymous,
7093 kCompilerHintsCount // Pseudo entry
7096 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 3> {};
7098 class DeoptCountBits : public BitField<int, 0, 4> {};
7099 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7100 class ICAgeBits : public BitField<int, 22, 8> {};
7102 class OptCountBits : public BitField<int, 0, 22> {};
7103 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7106 #if V8_HOST_ARCH_32_BIT
7107 // On 32 bit platforms, compiler hints is a smi.
7108 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7109 static const int kCompilerHintsSize = kPointerSize;
7111 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7112 static const int kCompilerHintsSmiTagSize = 0;
7113 static const int kCompilerHintsSize = kIntSize;
7116 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7117 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7120 // Constants for optimizing codegen for strict mode function and
7122 // Allows to use byte-width instructions.
7123 static const int kStrictModeBitWithinByte =
7124 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7126 static const int kNativeBitWithinByte =
7127 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7129 #if defined(V8_TARGET_LITTLE_ENDIAN)
7130 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7131 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7132 static const int kNativeByteOffset = kCompilerHintsOffset +
7133 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7134 #elif defined(V8_TARGET_BIG_ENDIAN)
7135 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7136 (kCompilerHintsSize - 1) -
7137 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7138 static const int kNativeByteOffset = kCompilerHintsOffset +
7139 (kCompilerHintsSize - 1) -
7140 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7142 #error Unknown byte ordering
7146 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7150 // Printing support.
7151 struct SourceCodeOf {
7152 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7153 : value(v), max_length(max) {}
7154 const SharedFunctionInfo* value;
7159 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7162 class JSGeneratorObject: public JSObject {
7164 // [function]: The function corresponding to this generator object.
7165 DECL_ACCESSORS(function, JSFunction)
7167 // [context]: The context of the suspended computation.
7168 DECL_ACCESSORS(context, Context)
7170 // [receiver]: The receiver of the suspended computation.
7171 DECL_ACCESSORS(receiver, Object)
7173 // [continuation]: Offset into code of continuation.
7175 // A positive offset indicates a suspended generator. The special
7176 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7177 // cannot be resumed.
7178 inline int continuation() const;
7179 inline void set_continuation(int continuation);
7180 inline bool is_closed();
7181 inline bool is_executing();
7182 inline bool is_suspended();
7184 // [operand_stack]: Saved operand stack.
7185 DECL_ACCESSORS(operand_stack, FixedArray)
7187 // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7188 // if the captured activation had no stack handler.
7189 inline int stack_handler_index() const;
7190 inline void set_stack_handler_index(int stack_handler_index);
7192 DECLARE_CAST(JSGeneratorObject)
7194 // Dispatched behavior.
7195 DECLARE_PRINTER(JSGeneratorObject)
7196 DECLARE_VERIFIER(JSGeneratorObject)
7198 // Magic sentinel values for the continuation.
7199 static const int kGeneratorExecuting = -1;
7200 static const int kGeneratorClosed = 0;
7202 // Layout description.
7203 static const int kFunctionOffset = JSObject::kHeaderSize;
7204 static const int kContextOffset = kFunctionOffset + kPointerSize;
7205 static const int kReceiverOffset = kContextOffset + kPointerSize;
7206 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7207 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7208 static const int kStackHandlerIndexOffset =
7209 kOperandStackOffset + kPointerSize;
7210 static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7212 // Resume mode, for use by runtime functions.
7213 enum ResumeMode { NEXT, THROW };
7215 // Yielding from a generator returns an object with the following inobject
7216 // properties. See Context::iterator_result_map() for the map.
7217 static const int kResultValuePropertyIndex = 0;
7218 static const int kResultDonePropertyIndex = 1;
7219 static const int kResultPropertyCount = 2;
7221 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7222 static const int kResultDonePropertyOffset =
7223 kResultValuePropertyOffset + kPointerSize;
7224 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7227 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7231 // Representation for module instance objects.
7232 class JSModule: public JSObject {
7234 // [context]: the context holding the module's locals, or undefined if none.
7235 DECL_ACCESSORS(context, Object)
7237 // [scope_info]: Scope info.
7238 DECL_ACCESSORS(scope_info, ScopeInfo)
7240 DECLARE_CAST(JSModule)
7242 // Dispatched behavior.
7243 DECLARE_PRINTER(JSModule)
7244 DECLARE_VERIFIER(JSModule)
7246 // Layout description.
7247 static const int kContextOffset = JSObject::kHeaderSize;
7248 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7249 static const int kSize = kScopeInfoOffset + kPointerSize;
7252 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7256 // JSFunction describes JavaScript functions.
7257 class JSFunction: public JSObject {
7259 // [prototype_or_initial_map]:
7260 DECL_ACCESSORS(prototype_or_initial_map, Object)
7262 // [shared]: The information about the function that
7263 // can be shared by instances.
7264 DECL_ACCESSORS(shared, SharedFunctionInfo)
7266 // [context]: The context for this function.
7267 inline Context* context();
7268 inline void set_context(Object* context);
7269 inline JSObject* global_proxy();
7271 // [code]: The generated code object for this function. Executed
7272 // when the function is invoked, e.g. foo() or new foo(). See
7273 // [[Call]] and [[Construct]] description in ECMA-262, section
7275 inline Code* code();
7276 inline void set_code(Code* code);
7277 inline void set_code_no_write_barrier(Code* code);
7278 inline void ReplaceCode(Code* code);
7280 // Tells whether this function is builtin.
7281 inline bool IsBuiltin();
7283 // Tells whether this function is defined in a native script.
7284 inline bool IsFromNativeScript();
7286 // Tells whether this function is defined in an extension script.
7287 inline bool IsFromExtensionScript();
7289 // Tells whether or not the function needs arguments adaption.
7290 inline bool NeedsArgumentsAdaption();
7292 // Tells whether or not this function has been optimized.
7293 inline bool IsOptimized();
7295 // Tells whether or not this function can be optimized.
7296 inline bool IsOptimizable();
7298 // Mark this function for lazy recompilation. The function will be
7299 // recompiled the next time it is executed.
7300 void MarkForOptimization();
7301 void MarkForConcurrentOptimization();
7302 void MarkInOptimizationQueue();
7304 // Tells whether or not the function is already marked for lazy
7306 inline bool IsMarkedForOptimization();
7307 inline bool IsMarkedForConcurrentOptimization();
7309 // Tells whether or not the function is on the concurrent recompilation queue.
7310 inline bool IsInOptimizationQueue();
7312 // Inobject slack tracking is the way to reclaim unused inobject space.
7314 // The instance size is initially determined by adding some slack to
7315 // expected_nof_properties (to allow for a few extra properties added
7316 // after the constructor). There is no guarantee that the extra space
7317 // will not be wasted.
7319 // Here is the algorithm to reclaim the unused inobject space:
7320 // - Detect the first constructor call for this JSFunction.
7321 // When it happens enter the "in progress" state: initialize construction
7322 // counter in the initial_map and set the |done_inobject_slack_tracking|
7324 // - While the tracking is in progress create objects filled with
7325 // one_pointer_filler_map instead of undefined_value. This way they can be
7326 // resized quickly and safely.
7327 // - Once enough (kGenerousAllocationCount) objects have been created
7328 // compute the 'slack' (traverse the map transition tree starting from the
7329 // initial_map and find the lowest value of unused_property_fields).
7330 // - Traverse the transition tree again and decrease the instance size
7331 // of every map. Existing objects will resize automatically (they are
7332 // filled with one_pointer_filler_map). All further allocations will
7333 // use the adjusted instance size.
7334 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7335 // allocations made using different closures could actually create different
7336 // kind of objects (see prototype inheritance pattern).
7338 // Important: inobject slack tracking is not attempted during the snapshot
7341 static const int kGenerousAllocationCount = Map::ConstructionCount::kMax;
7342 static const int kFinishSlackTracking = 1;
7343 static const int kNoSlackTracking = 0;
7345 // True if the initial_map is set and the object constructions countdown
7346 // counter is not zero.
7347 inline bool IsInobjectSlackTrackingInProgress();
7349 // Starts the tracking.
7350 // Initializes object constructions countdown counter in the initial map.
7351 // IsInobjectSlackTrackingInProgress is normally true after this call,
7352 // except when tracking have not been started (e.g. the map has no unused
7353 // properties or the snapshot is being built).
7354 void StartInobjectSlackTracking();
7356 // Completes the tracking.
7357 // IsInobjectSlackTrackingInProgress is false after this call.
7358 void CompleteInobjectSlackTracking();
7360 // [literals_or_bindings]: Fixed array holding either
7361 // the materialized literals or the bindings of a bound function.
7363 // If the function contains object, regexp or array literals, the
7364 // literals array prefix contains the object, regexp, and array
7365 // function to be used when creating these literals. This is
7366 // necessary so that we do not dynamically lookup the object, regexp
7367 // or array functions. Performing a dynamic lookup, we might end up
7368 // using the functions from a new context that we should not have
7371 // On bound functions, the array is a (copy-on-write) fixed-array containing
7372 // the function that was bound, bound this-value and any bound
7373 // arguments. Bound functions never contain literals.
7374 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7376 inline FixedArray* literals();
7377 inline void set_literals(FixedArray* literals);
7379 inline FixedArray* function_bindings();
7380 inline void set_function_bindings(FixedArray* bindings);
7382 // The initial map for an object created by this constructor.
7383 inline Map* initial_map();
7384 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7385 Handle<Object> prototype);
7386 inline bool has_initial_map();
7387 static void EnsureHasInitialMap(Handle<JSFunction> function);
7389 // Get and set the prototype property on a JSFunction. If the
7390 // function has an initial map the prototype is set on the initial
7391 // map. Otherwise, the prototype is put in the initial map field
7392 // until an initial map is needed.
7393 inline bool has_prototype();
7394 inline bool has_instance_prototype();
7395 inline Object* prototype();
7396 inline Object* instance_prototype();
7397 static void SetPrototype(Handle<JSFunction> function,
7398 Handle<Object> value);
7399 static void SetInstancePrototype(Handle<JSFunction> function,
7400 Handle<Object> value);
7402 // Creates a new closure for the fucntion with the same bindings,
7403 // bound values, and prototype. An equivalent of spec operations
7404 // ``CloneMethod`` and ``CloneBoundFunction``.
7405 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7407 // After prototype is removed, it will not be created when accessed, and
7408 // [[Construct]] from this function will not be allowed.
7409 bool RemovePrototype();
7410 inline bool should_have_prototype();
7412 // Accessor for this function's initial map's [[class]]
7413 // property. This is primarily used by ECMA native functions. This
7414 // method sets the class_name field of this function's initial map
7415 // to a given value. It creates an initial map if this function does
7416 // not have one. Note that this method does not copy the initial map
7417 // if it has one already, but simply replaces it with the new value.
7418 // Instances created afterwards will have a map whose [[class]] is
7419 // set to 'value', but there is no guarantees on instances created
7421 void SetInstanceClassName(String* name);
7423 // Returns if this function has been compiled to native code yet.
7424 inline bool is_compiled();
7426 // [next_function_link]: Links functions into various lists, e.g. the list
7427 // of optimized functions hanging off the native_context. The CodeFlusher
7428 // uses this link to chain together flushing candidates. Treated weakly
7429 // by the garbage collector.
7430 DECL_ACCESSORS(next_function_link, Object)
7432 // Prints the name of the function using PrintF.
7433 void PrintName(FILE* out = stdout);
7435 DECLARE_CAST(JSFunction)
7437 // Iterates the objects, including code objects indirectly referenced
7438 // through pointers to the first instruction in the code object.
7439 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7441 // Dispatched behavior.
7442 DECLARE_PRINTER(JSFunction)
7443 DECLARE_VERIFIER(JSFunction)
7445 // Returns the number of allocated literals.
7446 inline int NumberOfLiterals();
7448 // Retrieve the native context from a function's literal array.
7449 static Context* NativeContextFromLiterals(FixedArray* literals);
7451 // Used for flags such as --hydrogen-filter.
7452 bool PassesFilter(const char* raw_filter);
7454 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7455 // kSize) is weak and has special handling during garbage collection.
7456 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7457 static const int kPrototypeOrInitialMapOffset =
7458 kCodeEntryOffset + kPointerSize;
7459 static const int kSharedFunctionInfoOffset =
7460 kPrototypeOrInitialMapOffset + kPointerSize;
7461 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7462 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7463 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7464 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7465 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7467 // Layout of the literals array.
7468 static const int kLiteralsPrefixSize = 1;
7469 static const int kLiteralNativeContextIndex = 0;
7471 // Layout of the bound-function binding array.
7472 static const int kBoundFunctionIndex = 0;
7473 static const int kBoundThisIndex = 1;
7474 static const int kBoundArgumentsStartIndex = 2;
7477 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7481 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7482 // and the prototype is hidden. JSGlobalProxy always delegates
7483 // property accesses to its prototype if the prototype is not null.
7485 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7487 // Accessing a JSGlobalProxy requires security check.
7489 class JSGlobalProxy : public JSObject {
7491 // [native_context]: the owner native context of this global proxy object.
7492 // It is null value if this object is not used by any context.
7493 DECL_ACCESSORS(native_context, Object)
7495 // [hash]: The hash code property (undefined if not initialized yet).
7496 DECL_ACCESSORS(hash, Object)
7498 DECLARE_CAST(JSGlobalProxy)
7500 inline bool IsDetachedFrom(GlobalObject* global) const;
7502 // Dispatched behavior.
7503 DECLARE_PRINTER(JSGlobalProxy)
7504 DECLARE_VERIFIER(JSGlobalProxy)
7506 // Layout description.
7507 static const int kNativeContextOffset = JSObject::kHeaderSize;
7508 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7509 static const int kSize = kHashOffset + kPointerSize;
7512 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7516 // Forward declaration.
7517 class JSBuiltinsObject;
7519 // Common super class for JavaScript global objects and the special
7520 // builtins global objects.
7521 class GlobalObject: public JSObject {
7523 // [builtins]: the object holding the runtime routines written in JS.
7524 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7526 // [native context]: the natives corresponding to this global object.
7527 DECL_ACCESSORS(native_context, Context)
7529 // [global context]: the most recent (i.e. innermost) global context.
7530 DECL_ACCESSORS(global_context, Context)
7532 // [global proxy]: the global proxy object of the context
7533 DECL_ACCESSORS(global_proxy, JSObject)
7535 DECLARE_CAST(GlobalObject)
7537 // Layout description.
7538 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7539 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7540 static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7541 static const int kGlobalProxyOffset = kGlobalContextOffset + kPointerSize;
7542 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7545 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7549 // JavaScript global object.
7550 class JSGlobalObject: public GlobalObject {
7552 DECLARE_CAST(JSGlobalObject)
7554 // Ensure that the global object has a cell for the given property name.
7555 static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7558 inline bool IsDetached();
7560 // Dispatched behavior.
7561 DECLARE_PRINTER(JSGlobalObject)
7562 DECLARE_VERIFIER(JSGlobalObject)
7564 // Layout description.
7565 static const int kSize = GlobalObject::kHeaderSize;
7568 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7572 // Builtins global object which holds the runtime routines written in
7574 class JSBuiltinsObject: public GlobalObject {
7576 // Accessors for the runtime routines written in JavaScript.
7577 inline Object* javascript_builtin(Builtins::JavaScript id);
7578 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7580 // Accessors for code of the runtime routines written in JavaScript.
7581 inline Code* javascript_builtin_code(Builtins::JavaScript id);
7582 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7584 DECLARE_CAST(JSBuiltinsObject)
7586 // Dispatched behavior.
7587 DECLARE_PRINTER(JSBuiltinsObject)
7588 DECLARE_VERIFIER(JSBuiltinsObject)
7590 // Layout description. The size of the builtins object includes
7591 // room for two pointers per runtime routine written in javascript
7592 // (function and code object).
7593 static const int kJSBuiltinsCount = Builtins::id_count;
7594 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7595 static const int kJSBuiltinsCodeOffset =
7596 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7597 static const int kSize =
7598 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7600 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7601 return kJSBuiltinsOffset + id * kPointerSize;
7604 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7605 return kJSBuiltinsCodeOffset + id * kPointerSize;
7609 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7613 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7614 class JSValue: public JSObject {
7616 // [value]: the object being wrapped.
7617 DECL_ACCESSORS(value, Object)
7619 DECLARE_CAST(JSValue)
7621 // Dispatched behavior.
7622 DECLARE_PRINTER(JSValue)
7623 DECLARE_VERIFIER(JSValue)
7625 // Layout description.
7626 static const int kValueOffset = JSObject::kHeaderSize;
7627 static const int kSize = kValueOffset + kPointerSize;
7630 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7636 // Representation for JS date objects.
7637 class JSDate: public JSObject {
7639 // If one component is NaN, all of them are, indicating a NaN time value.
7640 // [value]: the time value.
7641 DECL_ACCESSORS(value, Object)
7642 // [year]: caches year. Either undefined, smi, or NaN.
7643 DECL_ACCESSORS(year, Object)
7644 // [month]: caches month. Either undefined, smi, or NaN.
7645 DECL_ACCESSORS(month, Object)
7646 // [day]: caches day. Either undefined, smi, or NaN.
7647 DECL_ACCESSORS(day, Object)
7648 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7649 DECL_ACCESSORS(weekday, Object)
7650 // [hour]: caches hours. Either undefined, smi, or NaN.
7651 DECL_ACCESSORS(hour, Object)
7652 // [min]: caches minutes. Either undefined, smi, or NaN.
7653 DECL_ACCESSORS(min, Object)
7654 // [sec]: caches seconds. Either undefined, smi, or NaN.
7655 DECL_ACCESSORS(sec, Object)
7656 // [cache stamp]: sample of the date cache stamp at the
7657 // moment when chached fields were cached.
7658 DECL_ACCESSORS(cache_stamp, Object)
7660 DECLARE_CAST(JSDate)
7662 // Returns the date field with the specified index.
7663 // See FieldIndex for the list of date fields.
7664 static Object* GetField(Object* date, Smi* index);
7666 void SetValue(Object* value, bool is_value_nan);
7669 // Dispatched behavior.
7670 DECLARE_PRINTER(JSDate)
7671 DECLARE_VERIFIER(JSDate)
7673 // The order is important. It must be kept in sync with date macros
7684 kFirstUncachedField,
7685 kMillisecond = kFirstUncachedField,
7689 kYearUTC = kFirstUTCField,
7702 // Layout description.
7703 static const int kValueOffset = JSObject::kHeaderSize;
7704 static const int kYearOffset = kValueOffset + kPointerSize;
7705 static const int kMonthOffset = kYearOffset + kPointerSize;
7706 static const int kDayOffset = kMonthOffset + kPointerSize;
7707 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7708 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7709 static const int kMinOffset = kHourOffset + kPointerSize;
7710 static const int kSecOffset = kMinOffset + kPointerSize;
7711 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7712 static const int kSize = kCacheStampOffset + kPointerSize;
7715 inline Object* DoGetField(FieldIndex index);
7717 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7719 // Computes and caches the cacheable fields of the date.
7720 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7723 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7727 // Representation of message objects used for error reporting through
7728 // the API. The messages are formatted in JavaScript so this object is
7729 // a real JavaScript object. The information used for formatting the
7730 // error messages are not directly accessible from JavaScript to
7731 // prevent leaking information to user code called during error
7733 class JSMessageObject: public JSObject {
7735 // [type]: the type of error message.
7736 DECL_ACCESSORS(type, String)
7738 // [arguments]: the arguments for formatting the error message.
7739 DECL_ACCESSORS(arguments, JSArray)
7741 // [script]: the script from which the error message originated.
7742 DECL_ACCESSORS(script, Object)
7744 // [stack_frames]: an array of stack frames for this error object.
7745 DECL_ACCESSORS(stack_frames, Object)
7747 // [start_position]: the start position in the script for the error message.
7748 inline int start_position() const;
7749 inline void set_start_position(int value);
7751 // [end_position]: the end position in the script for the error message.
7752 inline int end_position() const;
7753 inline void set_end_position(int value);
7755 DECLARE_CAST(JSMessageObject)
7757 // Dispatched behavior.
7758 DECLARE_PRINTER(JSMessageObject)
7759 DECLARE_VERIFIER(JSMessageObject)
7761 // Layout description.
7762 static const int kTypeOffset = JSObject::kHeaderSize;
7763 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7764 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7765 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7766 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7767 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7768 static const int kSize = kEndPositionOffset + kPointerSize;
7770 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7771 kStackFramesOffset + kPointerSize,
7772 kSize> BodyDescriptor;
7776 // Regular expressions
7777 // The regular expression holds a single reference to a FixedArray in
7778 // the kDataOffset field.
7779 // The FixedArray contains the following data:
7780 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7781 // - reference to the original source string
7782 // - reference to the original flag string
7783 // If it is an atom regexp
7784 // - a reference to a literal string to search for
7785 // If it is an irregexp regexp:
7786 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7787 // used for tracking the last usage (used for code flushing).
7788 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7789 // used for tracking the last usage (used for code flushing)..
7790 // - max number of registers used by irregexp implementations.
7791 // - number of capture registers (output values) of the regexp.
7792 class JSRegExp: public JSObject {
7795 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7796 // ATOM: A simple string to match against using an indexOf operation.
7797 // IRREGEXP: Compiled with Irregexp.
7798 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7799 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7810 explicit Flags(uint32_t value) : value_(value) { }
7811 bool is_global() { return (value_ & GLOBAL) != 0; }
7812 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7813 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7814 bool is_sticky() { return (value_ & STICKY) != 0; }
7815 uint32_t value() { return value_; }
7820 DECL_ACCESSORS(data, Object)
7822 inline Type TypeTag();
7823 inline int CaptureCount();
7824 inline Flags GetFlags();
7825 inline String* Pattern();
7826 inline Object* DataAt(int index);
7827 // Set implementation data after the object has been prepared.
7828 inline void SetDataAt(int index, Object* value);
7830 static int code_index(bool is_latin1) {
7832 return kIrregexpLatin1CodeIndex;
7834 return kIrregexpUC16CodeIndex;
7838 static int saved_code_index(bool is_latin1) {
7840 return kIrregexpLatin1CodeSavedIndex;
7842 return kIrregexpUC16CodeSavedIndex;
7846 DECLARE_CAST(JSRegExp)
7848 // Dispatched behavior.
7849 DECLARE_VERIFIER(JSRegExp)
7851 static const int kDataOffset = JSObject::kHeaderSize;
7852 static const int kSize = kDataOffset + kPointerSize;
7854 // Indices in the data array.
7855 static const int kTagIndex = 0;
7856 static const int kSourceIndex = kTagIndex + 1;
7857 static const int kFlagsIndex = kSourceIndex + 1;
7858 static const int kDataIndex = kFlagsIndex + 1;
7859 // The data fields are used in different ways depending on the
7860 // value of the tag.
7861 // Atom regexps (literal strings).
7862 static const int kAtomPatternIndex = kDataIndex;
7864 static const int kAtomDataSize = kAtomPatternIndex + 1;
7866 // Irregexp compiled code or bytecode for Latin1. If compilation
7867 // fails, this fields hold an exception object that should be
7868 // thrown if the regexp is used again.
7869 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7870 // Irregexp compiled code or bytecode for UC16. If compilation
7871 // fails, this fields hold an exception object that should be
7872 // thrown if the regexp is used again.
7873 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7875 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7876 // is a potential candidate for flushing.
7877 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7878 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7879 // a potential candidate for flushing.
7880 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7882 // Maximal number of registers used by either Latin1 or UC16.
7883 // Only used to check that there is enough stack space
7884 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7885 // Number of captures in the compiled regexp.
7886 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7888 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7890 // Offsets directly into the data fixed array.
7891 static const int kDataTagOffset =
7892 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7893 static const int kDataOneByteCodeOffset =
7894 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7895 static const int kDataUC16CodeOffset =
7896 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7897 static const int kIrregexpCaptureCountOffset =
7898 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7900 // In-object fields.
7901 static const int kSourceFieldIndex = 0;
7902 static const int kGlobalFieldIndex = 1;
7903 static const int kIgnoreCaseFieldIndex = 2;
7904 static const int kMultilineFieldIndex = 3;
7905 static const int kLastIndexFieldIndex = 4;
7906 static const int kInObjectFieldCount = 5;
7908 // The uninitialized value for a regexp code object.
7909 static const int kUninitializedValue = -1;
7911 // The compilation error value for the regexp code object. The real error
7912 // object is in the saved code field.
7913 static const int kCompilationErrorValue = -2;
7915 // When we store the sweep generation at which we moved the code from the
7916 // code index to the saved code index we mask it of to be in the [0:255]
7918 static const int kCodeAgeMask = 0xff;
7922 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7924 static inline bool IsMatch(HashTableKey* key, Object* value) {
7925 return key->IsMatch(value);
7928 static inline uint32_t Hash(HashTableKey* key) {
7932 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7933 return key->HashForObject(object);
7936 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7938 static const int kPrefixSize = 0;
7939 static const int kEntrySize = 2;
7943 // This cache is used in two different variants. For regexp caching, it simply
7944 // maps identifying info of the regexp to the cached regexp object. Scripts and
7945 // eval code only gets cached after a second probe for the code object. To do
7946 // so, on first "put" only a hash identifying the source is entered into the
7947 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7948 // such lifetimes get reduced, and removed once they reach zero. If a second put
7949 // is called while such a hash is live in the cache, the hash gets replaced by
7950 // an actual cache entry. Age also removes stale live entries from the cache.
7951 // Such entries are identified by SharedFunctionInfos pointing to either the
7952 // recompilation stub, or to "old" code. This avoids memory leaks due to
7953 // premature caching of scripts and eval strings that are never needed later.
7954 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7955 CompilationCacheShape,
7958 // Find cached value for a string key, otherwise return null.
7959 Handle<Object> Lookup(Handle<String> src, Handle<Context> context);
7960 Handle<Object> LookupEval(Handle<String> src,
7961 Handle<SharedFunctionInfo> shared,
7962 StrictMode strict_mode, int scope_position);
7963 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7964 static Handle<CompilationCacheTable> Put(
7965 Handle<CompilationCacheTable> cache, Handle<String> src,
7966 Handle<Context> context, Handle<Object> value);
7967 static Handle<CompilationCacheTable> PutEval(
7968 Handle<CompilationCacheTable> cache, Handle<String> src,
7969 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7970 int scope_position);
7971 static Handle<CompilationCacheTable> PutRegExp(
7972 Handle<CompilationCacheTable> cache, Handle<String> src,
7973 JSRegExp::Flags flags, Handle<FixedArray> value);
7974 void Remove(Object* value);
7976 static const int kHashGenerations = 10;
7978 DECLARE_CAST(CompilationCacheTable)
7981 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7985 class CodeCache: public Struct {
7987 DECL_ACCESSORS(default_cache, FixedArray)
7988 DECL_ACCESSORS(normal_type_cache, Object)
7990 // Add the code object to the cache.
7992 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7994 // Lookup code object in the cache. Returns code object if found and undefined
7996 Object* Lookup(Name* name, Code::Flags flags);
7998 // Get the internal index of a code object in the cache. Returns -1 if the
7999 // code object is not in that cache. This index can be used to later call
8000 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8002 int GetIndex(Object* name, Code* code);
8004 // Remove an object from the cache with the provided internal index.
8005 void RemoveByIndex(Object* name, Code* code, int index);
8007 DECLARE_CAST(CodeCache)
8009 // Dispatched behavior.
8010 DECLARE_PRINTER(CodeCache)
8011 DECLARE_VERIFIER(CodeCache)
8013 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8014 static const int kNormalTypeCacheOffset =
8015 kDefaultCacheOffset + kPointerSize;
8016 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8019 static void UpdateDefaultCache(
8020 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8021 static void UpdateNormalTypeCache(
8022 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8023 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8024 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8026 // Code cache layout of the default cache. Elements are alternating name and
8027 // code objects for non normal load/store/call IC's.
8028 static const int kCodeCacheEntrySize = 2;
8029 static const int kCodeCacheEntryNameOffset = 0;
8030 static const int kCodeCacheEntryCodeOffset = 1;
8032 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8036 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8038 static inline bool IsMatch(HashTableKey* key, Object* value) {
8039 return key->IsMatch(value);
8042 static inline uint32_t Hash(HashTableKey* key) {
8046 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8047 return key->HashForObject(object);
8050 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8052 static const int kPrefixSize = 0;
8053 static const int kEntrySize = 2;
8057 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8058 CodeCacheHashTableShape,
8061 Object* Lookup(Name* name, Code::Flags flags);
8062 static Handle<CodeCacheHashTable> Put(
8063 Handle<CodeCacheHashTable> table,
8067 int GetIndex(Name* name, Code::Flags flags);
8068 void RemoveByIndex(int index);
8070 DECLARE_CAST(CodeCacheHashTable)
8072 // Initial size of the fixed array backing the hash table.
8073 static const int kInitialSize = 64;
8076 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8080 class PolymorphicCodeCache: public Struct {
8082 DECL_ACCESSORS(cache, Object)
8084 static void Update(Handle<PolymorphicCodeCache> cache,
8085 MapHandleList* maps,
8090 // Returns an undefined value if the entry is not found.
8091 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8093 DECLARE_CAST(PolymorphicCodeCache)
8095 // Dispatched behavior.
8096 DECLARE_PRINTER(PolymorphicCodeCache)
8097 DECLARE_VERIFIER(PolymorphicCodeCache)
8099 static const int kCacheOffset = HeapObject::kHeaderSize;
8100 static const int kSize = kCacheOffset + kPointerSize;
8103 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8107 class PolymorphicCodeCacheHashTable
8108 : public HashTable<PolymorphicCodeCacheHashTable,
8109 CodeCacheHashTableShape,
8112 Object* Lookup(MapHandleList* maps, int code_kind);
8114 static Handle<PolymorphicCodeCacheHashTable> Put(
8115 Handle<PolymorphicCodeCacheHashTable> hash_table,
8116 MapHandleList* maps,
8120 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8122 static const int kInitialSize = 64;
8124 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8128 class TypeFeedbackInfo: public Struct {
8130 inline int ic_total_count();
8131 inline void set_ic_total_count(int count);
8133 inline int ic_with_type_info_count();
8134 inline void change_ic_with_type_info_count(int delta);
8136 inline int ic_generic_count();
8137 inline void change_ic_generic_count(int delta);
8139 inline void initialize_storage();
8141 inline void change_own_type_change_checksum();
8142 inline int own_type_change_checksum();
8144 inline void set_inlined_type_change_checksum(int checksum);
8145 inline bool matches_inlined_type_change_checksum(int checksum);
8147 DECLARE_CAST(TypeFeedbackInfo)
8149 // Dispatched behavior.
8150 DECLARE_PRINTER(TypeFeedbackInfo)
8151 DECLARE_VERIFIER(TypeFeedbackInfo)
8153 static const int kStorage1Offset = HeapObject::kHeaderSize;
8154 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8155 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8156 static const int kSize = kStorage3Offset + kPointerSize;
8159 static const int kTypeChangeChecksumBits = 7;
8161 class ICTotalCountField: public BitField<int, 0,
8162 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8163 class OwnTypeChangeChecksum: public BitField<int,
8164 kSmiValueSize - kTypeChangeChecksumBits,
8165 kTypeChangeChecksumBits> {}; // NOLINT
8166 class ICsWithTypeInfoCountField: public BitField<int, 0,
8167 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8168 class InlinedTypeChangeChecksum: public BitField<int,
8169 kSmiValueSize - kTypeChangeChecksumBits,
8170 kTypeChangeChecksumBits> {}; // NOLINT
8172 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8176 enum AllocationSiteMode {
8177 DONT_TRACK_ALLOCATION_SITE,
8178 TRACK_ALLOCATION_SITE,
8179 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8183 class AllocationSite: public Struct {
8185 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8186 static const double kPretenureRatio;
8187 static const int kPretenureMinimumCreated = 100;
8189 // Values for pretenure decision field.
8190 enum PretenureDecision {
8196 kLastPretenureDecisionValue = kZombie
8199 const char* PretenureDecisionName(PretenureDecision decision);
8201 DECL_ACCESSORS(transition_info, Object)
8202 // nested_site threads a list of sites that represent nested literals
8203 // walked in a particular order. So [[1, 2], 1, 2] will have one
8204 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8205 DECL_ACCESSORS(nested_site, Object)
8206 DECL_ACCESSORS(pretenure_data, Smi)
8207 DECL_ACCESSORS(pretenure_create_count, Smi)
8208 DECL_ACCESSORS(dependent_code, DependentCode)
8209 DECL_ACCESSORS(weak_next, Object)
8211 inline void Initialize();
8213 // This method is expensive, it should only be called for reporting.
8214 bool IsNestedSite();
8216 // transition_info bitfields, for constructed array transition info.
8217 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8218 class UnusedBits: public BitField<int, 15, 14> {};
8219 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8221 // Bitfields for pretenure_data
8222 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8223 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8224 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8225 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8227 // Increments the mementos found counter and returns true when the first
8228 // memento was found for a given allocation site.
8229 inline bool IncrementMementoFoundCount();
8231 inline void IncrementMementoCreateCount();
8233 PretenureFlag GetPretenureMode();
8235 void ResetPretenureDecision();
8237 PretenureDecision pretenure_decision() {
8238 int value = pretenure_data()->value();
8239 return PretenureDecisionBits::decode(value);
8242 void set_pretenure_decision(PretenureDecision decision) {
8243 int value = pretenure_data()->value();
8245 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8246 SKIP_WRITE_BARRIER);
8249 bool deopt_dependent_code() {
8250 int value = pretenure_data()->value();
8251 return DeoptDependentCodeBit::decode(value);
8254 void set_deopt_dependent_code(bool deopt) {
8255 int value = pretenure_data()->value();
8257 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8258 SKIP_WRITE_BARRIER);
8261 int memento_found_count() {
8262 int value = pretenure_data()->value();
8263 return MementoFoundCountBits::decode(value);
8266 inline void set_memento_found_count(int count);
8268 int memento_create_count() {
8269 return pretenure_create_count()->value();
8272 void set_memento_create_count(int count) {
8273 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8276 // The pretenuring decision is made during gc, and the zombie state allows
8277 // us to recognize when an allocation site is just being kept alive because
8278 // a later traversal of new space may discover AllocationMementos that point
8279 // to this AllocationSite.
8281 return pretenure_decision() == kZombie;
8284 bool IsMaybeTenure() {
8285 return pretenure_decision() == kMaybeTenure;
8288 inline void MarkZombie();
8290 inline bool MakePretenureDecision(PretenureDecision current_decision,
8292 bool maximum_size_scavenge);
8294 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8296 ElementsKind GetElementsKind() {
8297 DCHECK(!SitePointsToLiteral());
8298 int value = Smi::cast(transition_info())->value();
8299 return ElementsKindBits::decode(value);
8302 void SetElementsKind(ElementsKind kind) {
8303 int value = Smi::cast(transition_info())->value();
8304 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8305 SKIP_WRITE_BARRIER);
8308 bool CanInlineCall() {
8309 int value = Smi::cast(transition_info())->value();
8310 return DoNotInlineBit::decode(value) == 0;
8313 void SetDoNotInlineCall() {
8314 int value = Smi::cast(transition_info())->value();
8315 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8316 SKIP_WRITE_BARRIER);
8319 bool SitePointsToLiteral() {
8320 // If transition_info is a smi, then it represents an ElementsKind
8321 // for a constructed array. Otherwise, it must be a boilerplate
8322 // for an object or array literal.
8323 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8326 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8327 ElementsKind to_kind);
8334 static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8336 CompilationInfo* info);
8338 DECLARE_PRINTER(AllocationSite)
8339 DECLARE_VERIFIER(AllocationSite)
8341 DECLARE_CAST(AllocationSite)
8342 static inline AllocationSiteMode GetMode(
8343 ElementsKind boilerplate_elements_kind);
8344 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8345 static inline bool CanTrack(InstanceType type);
8347 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8348 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8349 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8350 static const int kPretenureCreateCountOffset =
8351 kPretenureDataOffset + kPointerSize;
8352 static const int kDependentCodeOffset =
8353 kPretenureCreateCountOffset + kPointerSize;
8354 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8355 static const int kSize = kWeakNextOffset + kPointerSize;
8357 // During mark compact we need to take special care for the dependent code
8359 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8360 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8362 // For other visitors, use the fixed body descriptor below.
8363 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8364 kDependentCodeOffset + kPointerSize,
8365 kSize> BodyDescriptor;
8368 inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8369 bool PretenuringDecisionMade() {
8370 return pretenure_decision() != kUndecided;
8373 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8377 class AllocationMemento: public Struct {
8379 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8380 static const int kSize = kAllocationSiteOffset + kPointerSize;
8382 DECL_ACCESSORS(allocation_site, Object)
8385 return allocation_site()->IsAllocationSite() &&
8386 !AllocationSite::cast(allocation_site())->IsZombie();
8388 AllocationSite* GetAllocationSite() {
8390 return AllocationSite::cast(allocation_site());
8393 DECLARE_PRINTER(AllocationMemento)
8394 DECLARE_VERIFIER(AllocationMemento)
8396 DECLARE_CAST(AllocationMemento)
8399 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8403 // Representation of a slow alias as part of a sloppy arguments objects.
8404 // For fast aliases (if HasSloppyArgumentsElements()):
8405 // - the parameter map contains an index into the context
8406 // - all attributes of the element have default values
8407 // For slow aliases (if HasDictionaryArgumentsElements()):
8408 // - the parameter map contains no fast alias mapping (i.e. the hole)
8409 // - this struct (in the slow backing store) contains an index into the context
8410 // - all attributes are available as part if the property details
8411 class AliasedArgumentsEntry: public Struct {
8413 inline int aliased_context_slot() const;
8414 inline void set_aliased_context_slot(int count);
8416 DECLARE_CAST(AliasedArgumentsEntry)
8418 // Dispatched behavior.
8419 DECLARE_PRINTER(AliasedArgumentsEntry)
8420 DECLARE_VERIFIER(AliasedArgumentsEntry)
8422 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8423 static const int kSize = kAliasedContextSlot + kPointerSize;
8426 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8430 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8431 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8434 class StringHasher {
8436 explicit inline StringHasher(int length, uint32_t seed);
8438 template <typename schar>
8439 static inline uint32_t HashSequentialString(const schar* chars,
8443 // Reads all the data, even for long strings and computes the utf16 length.
8444 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8446 int* utf16_length_out);
8448 // Calculated hash value for a string consisting of 1 to
8449 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8450 // value is represented decimal value.
8451 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8453 // No string is allowed to have a hash of zero. That value is reserved
8454 // for internal properties. If the hash calculation yields zero then we
8456 static const int kZeroHash = 27;
8458 // Reusable parts of the hashing algorithm.
8459 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8460 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8463 // Returns the value to store in the hash field of a string with
8464 // the given length and contents.
8465 uint32_t GetHashField();
8466 // Returns true if the hash of this string can be computed without
8467 // looking at the contents.
8468 inline bool has_trivial_hash();
8469 // Adds a block of characters to the hash.
8470 template<typename Char>
8471 inline void AddCharacters(const Char* chars, int len);
8474 // Add a character to the hash.
8475 inline void AddCharacter(uint16_t c);
8476 // Update index. Returns true if string is still an index.
8477 inline bool UpdateIndex(uint16_t c);
8480 uint32_t raw_running_hash_;
8481 uint32_t array_index_;
8482 bool is_array_index_;
8483 bool is_first_char_;
8484 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8488 class IteratingStringHasher : public StringHasher {
8490 static inline uint32_t Hash(String* string, uint32_t seed);
8491 inline void VisitOneByteString(const uint8_t* chars, int length);
8492 inline void VisitTwoByteString(const uint16_t* chars, int length);
8495 inline IteratingStringHasher(int len, uint32_t seed)
8496 : StringHasher(len, seed) {}
8497 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8501 // The characteristics of a string are stored in its map. Retrieving these
8502 // few bits of information is moderately expensive, involving two memory
8503 // loads where the second is dependent on the first. To improve efficiency
8504 // the shape of the string is given its own class so that it can be retrieved
8505 // once and used for several string operations. A StringShape is small enough
8506 // to be passed by value and is immutable, but be aware that flattening a
8507 // string can potentially alter its shape. Also be aware that a GC caused by
8508 // something else can alter the shape of a string due to ConsString
8509 // shortcutting. Keeping these restrictions in mind has proven to be error-
8510 // prone and so we no longer put StringShapes in variables unless there is a
8511 // concrete performance benefit at that particular point in the code.
8512 class StringShape BASE_EMBEDDED {
8514 inline explicit StringShape(const String* s);
8515 inline explicit StringShape(Map* s);
8516 inline explicit StringShape(InstanceType t);
8517 inline bool IsSequential();
8518 inline bool IsExternal();
8519 inline bool IsCons();
8520 inline bool IsSliced();
8521 inline bool IsIndirect();
8522 inline bool IsExternalOneByte();
8523 inline bool IsExternalTwoByte();
8524 inline bool IsSequentialOneByte();
8525 inline bool IsSequentialTwoByte();
8526 inline bool IsInternalized();
8527 inline StringRepresentationTag representation_tag();
8528 inline uint32_t encoding_tag();
8529 inline uint32_t full_representation_tag();
8530 inline uint32_t size_tag();
8532 inline uint32_t type() { return type_; }
8533 inline void invalidate() { valid_ = false; }
8534 inline bool valid() { return valid_; }
8536 inline void invalidate() { }
8542 inline void set_valid() { valid_ = true; }
8545 inline void set_valid() { }
8550 // The Name abstract class captures anything that can be used as a property
8551 // name, i.e., strings and symbols. All names store a hash value.
8552 class Name: public HeapObject {
8554 // Get and set the hash field of the name.
8555 inline uint32_t hash_field();
8556 inline void set_hash_field(uint32_t value);
8558 // Tells whether the hash code has been computed.
8559 inline bool HasHashCode();
8561 // Returns a hash value used for the property table
8562 inline uint32_t Hash();
8564 // Equality operations.
8565 inline bool Equals(Name* other);
8566 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8569 inline bool AsArrayIndex(uint32_t* index);
8571 // Whether name can only name own properties.
8572 inline bool IsOwn();
8576 DECLARE_PRINTER(Name)
8578 // Layout description.
8579 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8580 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8581 static const int kHashFieldOffset = kHashFieldSlot;
8583 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8585 static const int kSize = kHashFieldSlot + kPointerSize;
8587 // Mask constant for checking if a name has a computed hash code
8588 // and if it is a string that is an array index. The least significant bit
8589 // indicates whether a hash code has been computed. If the hash code has
8590 // been computed the 2nd bit tells whether the string can be used as an
8592 static const int kHashNotComputedMask = 1;
8593 static const int kIsNotArrayIndexMask = 1 << 1;
8594 static const int kNofHashBitFields = 2;
8596 // Shift constant retrieving hash code from hash field.
8597 static const int kHashShift = kNofHashBitFields;
8599 // Only these bits are relevant in the hash, since the top two are shifted
8601 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8603 // Array index strings this short can keep their index in the hash field.
8604 static const int kMaxCachedArrayIndexLength = 7;
8606 // For strings which are array indexes the hash value has the string length
8607 // mixed into the hash, mainly to avoid a hash value of zero which would be
8608 // the case for the string '0'. 24 bits are used for the array index value.
8609 static const int kArrayIndexValueBits = 24;
8610 static const int kArrayIndexLengthBits =
8611 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8613 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8615 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8616 kArrayIndexValueBits> {}; // NOLINT
8617 class ArrayIndexLengthBits : public BitField<unsigned int,
8618 kNofHashBitFields + kArrayIndexValueBits,
8619 kArrayIndexLengthBits> {}; // NOLINT
8621 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8622 // could use a mask to test if the length of string is less than or equal to
8623 // kMaxCachedArrayIndexLength.
8624 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8626 static const unsigned int kContainsCachedArrayIndexMask =
8627 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8628 << ArrayIndexLengthBits::kShift) |
8629 kIsNotArrayIndexMask;
8631 // Value of empty hash field indicating that the hash is not computed.
8632 static const int kEmptyHashField =
8633 kIsNotArrayIndexMask | kHashNotComputedMask;
8636 static inline bool IsHashFieldComputed(uint32_t field);
8639 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8644 class Symbol: public Name {
8646 // [name]: the print name of a symbol, or undefined if none.
8647 DECL_ACCESSORS(name, Object)
8649 DECL_ACCESSORS(flags, Smi)
8651 // [is_private]: whether this is a private symbol.
8652 DECL_BOOLEAN_ACCESSORS(is_private)
8654 // [is_own]: whether this is an own symbol, that is, only used to designate
8655 // own properties of objects.
8656 DECL_BOOLEAN_ACCESSORS(is_own)
8658 DECLARE_CAST(Symbol)
8660 // Dispatched behavior.
8661 DECLARE_PRINTER(Symbol)
8662 DECLARE_VERIFIER(Symbol)
8664 // Layout description.
8665 static const int kNameOffset = Name::kSize;
8666 static const int kFlagsOffset = kNameOffset + kPointerSize;
8667 static const int kSize = kFlagsOffset + kPointerSize;
8669 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8671 void SymbolShortPrint(std::ostream& os);
8674 static const int kPrivateBit = 0;
8675 static const int kOwnBit = 1;
8677 const char* PrivateSymbolToName() const;
8679 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8685 // The String abstract class captures JavaScript string values:
8688 // 4.3.16 String Value
8689 // A string value is a member of the type String and is a finite
8690 // ordered sequence of zero or more 16-bit unsigned integer values.
8692 // All string values have a length field.
8693 class String: public Name {
8695 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8697 // Array index strings this short can keep their index in the hash field.
8698 static const int kMaxCachedArrayIndexLength = 7;
8700 // For strings which are array indexes the hash value has the string length
8701 // mixed into the hash, mainly to avoid a hash value of zero which would be
8702 // the case for the string '0'. 24 bits are used for the array index value.
8703 static const int kArrayIndexValueBits = 24;
8704 static const int kArrayIndexLengthBits =
8705 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8707 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8709 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8710 kArrayIndexValueBits> {}; // NOLINT
8711 class ArrayIndexLengthBits : public BitField<unsigned int,
8712 kNofHashBitFields + kArrayIndexValueBits,
8713 kArrayIndexLengthBits> {}; // NOLINT
8715 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8716 // could use a mask to test if the length of string is less than or equal to
8717 // kMaxCachedArrayIndexLength.
8718 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8720 static const unsigned int kContainsCachedArrayIndexMask =
8721 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8722 << ArrayIndexLengthBits::kShift) |
8723 kIsNotArrayIndexMask;
8725 // Representation of the flat content of a String.
8726 // A non-flat string doesn't have flat content.
8727 // A flat string has content that's encoded as a sequence of either
8728 // one-byte chars or two-byte UC16.
8729 // Returned by String::GetFlatContent().
8732 // Returns true if the string is flat and this structure contains content.
8733 bool IsFlat() { return state_ != NON_FLAT; }
8734 // Returns true if the structure contains one-byte content.
8735 bool IsOneByte() { return state_ == ONE_BYTE; }
8736 // Returns true if the structure contains two-byte content.
8737 bool IsTwoByte() { return state_ == TWO_BYTE; }
8739 // Return the one byte content of the string. Only use if IsOneByte()
8741 Vector<const uint8_t> ToOneByteVector() {
8742 DCHECK_EQ(ONE_BYTE, state_);
8743 return Vector<const uint8_t>(onebyte_start, length_);
8745 // Return the two-byte content of the string. Only use if IsTwoByte()
8747 Vector<const uc16> ToUC16Vector() {
8748 DCHECK_EQ(TWO_BYTE, state_);
8749 return Vector<const uc16>(twobyte_start, length_);
8753 DCHECK(i < length_);
8754 DCHECK(state_ != NON_FLAT);
8755 if (state_ == ONE_BYTE) return onebyte_start[i];
8756 return twobyte_start[i];
8760 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8762 // Constructors only used by String::GetFlatContent().
8763 explicit FlatContent(const uint8_t* start, int length)
8764 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8765 explicit FlatContent(const uc16* start, int length)
8766 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8767 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8770 const uint8_t* onebyte_start;
8771 const uc16* twobyte_start;
8776 friend class String;
8779 // Get and set the length of the string.
8780 inline int length() const;
8781 inline void set_length(int value);
8783 // Get and set the length of the string using acquire loads and release
8785 inline int synchronized_length() const;
8786 inline void synchronized_set_length(int value);
8788 // Returns whether this string has only one-byte chars, i.e. all of them can
8789 // be one-byte encoded. This might be the case even if the string is
8790 // two-byte. Such strings may appear when the embedder prefers
8791 // two-byte external representations even for one-byte data.
8792 inline bool IsOneByteRepresentation() const;
8793 inline bool IsTwoByteRepresentation() const;
8795 // Cons and slices have an encoding flag that may not represent the actual
8796 // encoding of the underlying string. This is taken into account here.
8797 // Requires: this->IsFlat()
8798 inline bool IsOneByteRepresentationUnderneath();
8799 inline bool IsTwoByteRepresentationUnderneath();
8801 // NOTE: this should be considered only a hint. False negatives are
8803 inline bool HasOnlyOneByteChars();
8805 // Get and set individual two byte chars in the string.
8806 inline void Set(int index, uint16_t value);
8807 // Get individual two byte char in the string. Repeated calls
8808 // to this method are not efficient unless the string is flat.
8809 INLINE(uint16_t Get(int index));
8811 // Flattens the string. Checks first inline to see if it is
8812 // necessary. Does nothing if the string is not a cons string.
8813 // Flattening allocates a sequential string with the same data as
8814 // the given string and mutates the cons string to a degenerate
8815 // form, where the first component is the new sequential string and
8816 // the second component is the empty string. If allocation fails,
8817 // this function returns a failure. If flattening succeeds, this
8818 // function returns the sequential string that is now the first
8819 // component of the cons string.
8821 // Degenerate cons strings are handled specially by the garbage
8822 // collector (see IsShortcutCandidate).
8824 static inline Handle<String> Flatten(Handle<String> string,
8825 PretenureFlag pretenure = NOT_TENURED);
8827 // Tries to return the content of a flat string as a structure holding either
8828 // a flat vector of char or of uc16.
8829 // If the string isn't flat, and therefore doesn't have flat content, the
8830 // returned structure will report so, and can't provide a vector of either
8832 FlatContent GetFlatContent();
8834 // Returns the parent of a sliced string or first part of a flat cons string.
8835 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8836 inline String* GetUnderlying();
8838 // Mark the string as an undetectable object. It only applies to
8839 // one-byte and two-byte string types.
8840 bool MarkAsUndetectable();
8842 // String equality operations.
8843 inline bool Equals(String* other);
8844 inline static bool Equals(Handle<String> one, Handle<String> two);
8845 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8846 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8847 bool IsTwoByteEqualTo(Vector<const uc16> str);
8849 // Return a UTF8 representation of the string. The string is null
8850 // terminated but may optionally contain nulls. Length is returned
8851 // in length_output if length_output is not a null pointer The string
8852 // should be nearly flat, otherwise the performance of this method may
8853 // be very slow (quadratic in the length). Setting robustness_flag to
8854 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8855 // handles unexpected data without causing assert failures and it does not
8856 // do any heap allocations. This is useful when printing stack traces.
8857 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8858 RobustnessFlag robustness_flag,
8861 int* length_output = 0);
8862 SmartArrayPointer<char> ToCString(
8863 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8864 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8865 int* length_output = 0);
8867 // Return a 16 bit Unicode representation of the string.
8868 // The string should be nearly flat, otherwise the performance of
8869 // of this method may be very bad. Setting robustness_flag to
8870 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8871 // handles unexpected data without causing assert failures and it does not
8872 // do any heap allocations. This is useful when printing stack traces.
8873 SmartArrayPointer<uc16> ToWideCString(
8874 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8876 bool ComputeArrayIndex(uint32_t* index);
8879 bool MakeExternal(v8::String::ExternalStringResource* resource);
8880 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8883 inline bool AsArrayIndex(uint32_t* index);
8885 DECLARE_CAST(String)
8887 void PrintOn(FILE* out);
8889 // For use during stack traces. Performs rudimentary sanity check.
8892 // Dispatched behavior.
8893 void StringShortPrint(StringStream* accumulator);
8894 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8896 char* ToAsciiArray();
8898 DECLARE_PRINTER(String)
8899 DECLARE_VERIFIER(String)
8901 inline bool IsFlat();
8903 // Layout description.
8904 static const int kLengthOffset = Name::kSize;
8905 static const int kSize = kLengthOffset + kPointerSize;
8907 // Maximum number of characters to consider when trying to convert a string
8908 // value into an array index.
8909 static const int kMaxArrayIndexSize = 10;
8910 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8913 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8914 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8915 static const int kMaxUtf16CodeUnit = 0xffff;
8916 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8918 // Value of hash field containing computed hash equal to zero.
8919 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8921 // Maximal string length.
8922 static const int kMaxLength = (1 << 28) - 16;
8924 // Max length for computing hash. For strings longer than this limit the
8925 // string length is used as the hash value.
8926 static const int kMaxHashCalcLength = 16383;
8928 // Limit for truncation in short printing.
8929 static const int kMaxShortPrintLength = 1024;
8931 // Support for regular expressions.
8932 const uc16* GetTwoByteData(unsigned start);
8934 // Helper function for flattening strings.
8935 template <typename sinkchar>
8936 static void WriteToFlat(String* source,
8941 // The return value may point to the first aligned word containing the first
8942 // non-one-byte character, rather than directly to the non-one-byte character.
8943 // If the return value is >= the passed length, the entire string was
8945 static inline int NonAsciiStart(const char* chars, int length) {
8946 const char* start = chars;
8947 const char* limit = chars + length;
8949 if (length >= kIntptrSize) {
8950 // Check unaligned bytes.
8951 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8952 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8953 return static_cast<int>(chars - start);
8957 // Check aligned words.
8958 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8959 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8960 while (chars + sizeof(uintptr_t) <= limit) {
8961 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8962 return static_cast<int>(chars - start);
8964 chars += sizeof(uintptr_t);
8967 // Check remaining unaligned bytes.
8968 while (chars < limit) {
8969 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8970 return static_cast<int>(chars - start);
8975 return static_cast<int>(chars - start);
8978 static inline bool IsAscii(const char* chars, int length) {
8979 return NonAsciiStart(chars, length) >= length;
8982 static inline bool IsAscii(const uint8_t* chars, int length) {
8984 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8987 static inline int NonOneByteStart(const uc16* chars, int length) {
8988 const uc16* limit = chars + length;
8989 const uc16* start = chars;
8990 while (chars < limit) {
8991 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8994 return static_cast<int>(chars - start);
8997 static inline bool IsOneByte(const uc16* chars, int length) {
8998 return NonOneByteStart(chars, length) >= length;
9001 template<class Visitor>
9002 static inline ConsString* VisitFlat(Visitor* visitor,
9006 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9007 bool include_ending_line);
9009 // Use the hash field to forward to the canonical internalized string
9010 // when deserializing an internalized string.
9011 inline void SetForwardedInternalizedString(String* string);
9012 inline String* GetForwardedInternalizedString();
9016 friend class StringTableInsertionKey;
9018 static Handle<String> SlowFlatten(Handle<ConsString> cons,
9019 PretenureFlag tenure);
9021 // Slow case of String::Equals. This implementation works on any strings
9022 // but it is most efficient on strings that are almost flat.
9023 bool SlowEquals(String* other);
9025 static bool SlowEquals(Handle<String> one, Handle<String> two);
9027 // Slow case of AsArrayIndex.
9028 bool SlowAsArrayIndex(uint32_t* index);
9030 // Compute and set the hash code.
9031 uint32_t ComputeAndSetHash();
9033 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9037 // The SeqString abstract class captures sequential string values.
9038 class SeqString: public String {
9040 DECLARE_CAST(SeqString)
9042 // Layout description.
9043 static const int kHeaderSize = String::kSize;
9045 // Truncate the string in-place if possible and return the result.
9046 // In case of new_length == 0, the empty string is returned without
9047 // truncating the original string.
9048 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9051 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9055 // The OneByteString class captures sequential one-byte string objects.
9056 // Each character in the OneByteString is an one-byte character.
9057 class SeqOneByteString: public SeqString {
9059 static const bool kHasOneByteEncoding = true;
9061 // Dispatched behavior.
9062 inline uint16_t SeqOneByteStringGet(int index);
9063 inline void SeqOneByteStringSet(int index, uint16_t value);
9065 // Get the address of the characters in this string.
9066 inline Address GetCharsAddress();
9068 inline uint8_t* GetChars();
9070 DECLARE_CAST(SeqOneByteString)
9072 // Garbage collection support. This method is called by the
9073 // garbage collector to compute the actual size of an OneByteString
9075 inline int SeqOneByteStringSize(InstanceType instance_type);
9077 // Computes the size for an OneByteString instance of a given length.
9078 static int SizeFor(int length) {
9079 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9082 // Maximal memory usage for a single sequential one-byte string.
9083 static const int kMaxSize = 512 * MB - 1;
9084 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9087 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9091 // The TwoByteString class captures sequential unicode string objects.
9092 // Each character in the TwoByteString is a two-byte uint16_t.
9093 class SeqTwoByteString: public SeqString {
9095 static const bool kHasOneByteEncoding = false;
9097 // Dispatched behavior.
9098 inline uint16_t SeqTwoByteStringGet(int index);
9099 inline void SeqTwoByteStringSet(int index, uint16_t value);
9101 // Get the address of the characters in this string.
9102 inline Address GetCharsAddress();
9104 inline uc16* GetChars();
9107 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9109 DECLARE_CAST(SeqTwoByteString)
9111 // Garbage collection support. This method is called by the
9112 // garbage collector to compute the actual size of a TwoByteString
9114 inline int SeqTwoByteStringSize(InstanceType instance_type);
9116 // Computes the size for a TwoByteString instance of a given length.
9117 static int SizeFor(int length) {
9118 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9121 // Maximal memory usage for a single sequential two-byte string.
9122 static const int kMaxSize = 512 * MB - 1;
9123 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9124 String::kMaxLength);
9127 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9131 // The ConsString class describes string values built by using the
9132 // addition operator on strings. A ConsString is a pair where the
9133 // first and second components are pointers to other string values.
9134 // One or both components of a ConsString can be pointers to other
9135 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9136 // are non-ConsString string values. The string value represented by
9137 // a ConsString can be obtained by concatenating the leaf string
9138 // values in a left-to-right depth-first traversal of the tree.
9139 class ConsString: public String {
9141 // First string of the cons cell.
9142 inline String* first();
9143 // Doesn't check that the result is a string, even in debug mode. This is
9144 // useful during GC where the mark bits confuse the checks.
9145 inline Object* unchecked_first();
9146 inline void set_first(String* first,
9147 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9149 // Second string of the cons cell.
9150 inline String* second();
9151 // Doesn't check that the result is a string, even in debug mode. This is
9152 // useful during GC where the mark bits confuse the checks.
9153 inline Object* unchecked_second();
9154 inline void set_second(String* second,
9155 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9157 // Dispatched behavior.
9158 uint16_t ConsStringGet(int index);
9160 DECLARE_CAST(ConsString)
9162 // Layout description.
9163 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9164 static const int kSecondOffset = kFirstOffset + kPointerSize;
9165 static const int kSize = kSecondOffset + kPointerSize;
9167 // Minimum length for a cons string.
9168 static const int kMinLength = 13;
9170 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9173 DECLARE_VERIFIER(ConsString)
9176 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9180 // The Sliced String class describes strings that are substrings of another
9181 // sequential string. The motivation is to save time and memory when creating
9182 // a substring. A Sliced String is described as a pointer to the parent,
9183 // the offset from the start of the parent string and the length. Using
9184 // a Sliced String therefore requires unpacking of the parent string and
9185 // adding the offset to the start address. A substring of a Sliced String
9186 // are not nested since the double indirection is simplified when creating
9187 // such a substring.
9188 // Currently missing features are:
9189 // - handling externalized parent strings
9190 // - external strings as parent
9191 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9192 class SlicedString: public String {
9194 inline String* parent();
9195 inline void set_parent(String* parent,
9196 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9197 inline int offset() const;
9198 inline void set_offset(int offset);
9200 // Dispatched behavior.
9201 uint16_t SlicedStringGet(int index);
9203 DECLARE_CAST(SlicedString)
9205 // Layout description.
9206 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9207 static const int kOffsetOffset = kParentOffset + kPointerSize;
9208 static const int kSize = kOffsetOffset + kPointerSize;
9210 // Minimum length for a sliced string.
9211 static const int kMinLength = 13;
9213 typedef FixedBodyDescriptor<kParentOffset,
9214 kOffsetOffset + kPointerSize, kSize>
9217 DECLARE_VERIFIER(SlicedString)
9220 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9224 // The ExternalString class describes string values that are backed by
9225 // a string resource that lies outside the V8 heap. ExternalStrings
9226 // consist of the length field common to all strings, a pointer to the
9227 // external resource. It is important to ensure (externally) that the
9228 // resource is not deallocated while the ExternalString is live in the
9231 // The API expects that all ExternalStrings are created through the
9232 // API. Therefore, ExternalStrings should not be used internally.
9233 class ExternalString: public String {
9235 DECLARE_CAST(ExternalString)
9237 // Layout description.
9238 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9239 static const int kShortSize = kResourceOffset + kPointerSize;
9240 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9241 static const int kSize = kResourceDataOffset + kPointerSize;
9243 static const int kMaxShortLength =
9244 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9246 // Return whether external string is short (data pointer is not cached).
9247 inline bool is_short();
9249 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9252 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9256 // The ExternalOneByteString class is an external string backed by an
9258 class ExternalOneByteString : public ExternalString {
9260 static const bool kHasOneByteEncoding = true;
9262 typedef v8::String::ExternalOneByteStringResource Resource;
9264 // The underlying resource.
9265 inline const Resource* resource();
9266 inline void set_resource(const Resource* buffer);
9268 // Update the pointer cache to the external character array.
9269 // The cached pointer is always valid, as the external character array does =
9270 // not move during lifetime. Deserialization is the only exception, after
9271 // which the pointer cache has to be refreshed.
9272 inline void update_data_cache();
9274 inline const uint8_t* GetChars();
9276 // Dispatched behavior.
9277 inline uint16_t ExternalOneByteStringGet(int index);
9279 DECLARE_CAST(ExternalOneByteString)
9281 // Garbage collection support.
9282 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9284 template <typename StaticVisitor>
9285 inline void ExternalOneByteStringIterateBody();
9288 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9292 // The ExternalTwoByteString class is an external string backed by a UTF-16
9294 class ExternalTwoByteString: public ExternalString {
9296 static const bool kHasOneByteEncoding = false;
9298 typedef v8::String::ExternalStringResource Resource;
9300 // The underlying string resource.
9301 inline const Resource* resource();
9302 inline void set_resource(const Resource* buffer);
9304 // Update the pointer cache to the external character array.
9305 // The cached pointer is always valid, as the external character array does =
9306 // not move during lifetime. Deserialization is the only exception, after
9307 // which the pointer cache has to be refreshed.
9308 inline void update_data_cache();
9310 inline const uint16_t* GetChars();
9312 // Dispatched behavior.
9313 inline uint16_t ExternalTwoByteStringGet(int index);
9316 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9318 DECLARE_CAST(ExternalTwoByteString)
9320 // Garbage collection support.
9321 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9323 template<typename StaticVisitor>
9324 inline void ExternalTwoByteStringIterateBody();
9327 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9331 // Utility superclass for stack-allocated objects that must be updated
9332 // on gc. It provides two ways for the gc to update instances, either
9333 // iterating or updating after gc.
9334 class Relocatable BASE_EMBEDDED {
9336 explicit inline Relocatable(Isolate* isolate);
9337 inline virtual ~Relocatable();
9338 virtual void IterateInstance(ObjectVisitor* v) { }
9339 virtual void PostGarbageCollection() { }
9341 static void PostGarbageCollectionProcessing(Isolate* isolate);
9342 static int ArchiveSpacePerThread();
9343 static char* ArchiveState(Isolate* isolate, char* to);
9344 static char* RestoreState(Isolate* isolate, char* from);
9345 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9346 static void Iterate(ObjectVisitor* v, Relocatable* top);
9347 static char* Iterate(ObjectVisitor* v, char* t);
9355 // A flat string reader provides random access to the contents of a
9356 // string independent of the character width of the string. The handle
9357 // must be valid as long as the reader is being used.
9358 class FlatStringReader : public Relocatable {
9360 FlatStringReader(Isolate* isolate, Handle<String> str);
9361 FlatStringReader(Isolate* isolate, Vector<const char> input);
9362 void PostGarbageCollection();
9363 inline uc32 Get(int index);
9364 int length() { return length_; }
9373 // This maintains an off-stack representation of the stack frames required
9374 // to traverse a ConsString, allowing an entirely iterative and restartable
9375 // traversal of the entire string
9376 class ConsStringIterator {
9378 inline ConsStringIterator() {}
9379 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9380 Reset(cons_string, offset);
9382 inline void Reset(ConsString* cons_string, int offset = 0) {
9384 // Next will always return NULL.
9385 if (cons_string == NULL) return;
9386 Initialize(cons_string, offset);
9388 // Returns NULL when complete.
9389 inline String* Next(int* offset_out) {
9391 if (depth_ == 0) return NULL;
9392 return Continue(offset_out);
9396 static const int kStackSize = 32;
9397 // Use a mask instead of doing modulo operations for stack wrapping.
9398 static const int kDepthMask = kStackSize-1;
9399 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9400 static inline int OffsetForDepth(int depth);
9402 inline void PushLeft(ConsString* string);
9403 inline void PushRight(ConsString* string);
9404 inline void AdjustMaximumDepth();
9406 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9407 void Initialize(ConsString* cons_string, int offset);
9408 String* Continue(int* offset_out);
9409 String* NextLeaf(bool* blew_stack);
9410 String* Search(int* offset_out);
9412 // Stack must always contain only frames for which right traversal
9413 // has not yet been performed.
9414 ConsString* frames_[kStackSize];
9419 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9423 class StringCharacterStream {
9425 inline StringCharacterStream(String* string,
9427 inline uint16_t GetNext();
9428 inline bool HasMore();
9429 inline void Reset(String* string, int offset = 0);
9430 inline void VisitOneByteString(const uint8_t* chars, int length);
9431 inline void VisitTwoByteString(const uint16_t* chars, int length);
9434 ConsStringIterator iter_;
9437 const uint8_t* buffer8_;
9438 const uint16_t* buffer16_;
9440 const uint8_t* end_;
9441 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9445 template <typename T>
9446 class VectorIterator {
9448 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9449 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9450 T GetNext() { return data_[index_++]; }
9451 bool has_more() { return index_ < data_.length(); }
9453 Vector<const T> data_;
9458 // The Oddball describes objects null, undefined, true, and false.
9459 class Oddball: public HeapObject {
9461 // [to_string]: Cached to_string computed at startup.
9462 DECL_ACCESSORS(to_string, String)
9464 // [to_number]: Cached to_number computed at startup.
9465 DECL_ACCESSORS(to_number, Object)
9467 inline byte kind() const;
9468 inline void set_kind(byte kind);
9470 DECLARE_CAST(Oddball)
9472 // Dispatched behavior.
9473 DECLARE_VERIFIER(Oddball)
9475 // Initialize the fields.
9476 static void Initialize(Isolate* isolate,
9477 Handle<Oddball> oddball,
9478 const char* to_string,
9479 Handle<Object> to_number,
9482 // Layout description.
9483 static const int kToStringOffset = HeapObject::kHeaderSize;
9484 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9485 static const int kKindOffset = kToNumberOffset + kPointerSize;
9486 static const int kSize = kKindOffset + kPointerSize;
9488 static const byte kFalse = 0;
9489 static const byte kTrue = 1;
9490 static const byte kNotBooleanMask = ~1;
9491 static const byte kTheHole = 2;
9492 static const byte kNull = 3;
9493 static const byte kArgumentMarker = 4;
9494 static const byte kUndefined = 5;
9495 static const byte kUninitialized = 6;
9496 static const byte kOther = 7;
9497 static const byte kException = 8;
9499 typedef FixedBodyDescriptor<kToStringOffset,
9500 kToNumberOffset + kPointerSize,
9501 kSize> BodyDescriptor;
9503 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9504 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9505 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9508 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9512 class Cell: public HeapObject {
9514 // [value]: value of the global property.
9515 DECL_ACCESSORS(value, Object)
9519 static inline Cell* FromValueAddress(Address value) {
9520 Object* result = FromAddress(value - kValueOffset);
9521 DCHECK(result->IsCell() || result->IsPropertyCell());
9522 return static_cast<Cell*>(result);
9525 inline Address ValueAddress() {
9526 return address() + kValueOffset;
9529 // Dispatched behavior.
9530 DECLARE_PRINTER(Cell)
9531 DECLARE_VERIFIER(Cell)
9533 // Layout description.
9534 static const int kValueOffset = HeapObject::kHeaderSize;
9535 static const int kSize = kValueOffset + kPointerSize;
9537 typedef FixedBodyDescriptor<kValueOffset,
9538 kValueOffset + kPointerSize,
9539 kSize> BodyDescriptor;
9542 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9546 class PropertyCell: public Cell {
9548 // [type]: type of the global property.
9550 void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9552 // [dependent_code]: dependent code that depends on the type of the global
9554 DECL_ACCESSORS(dependent_code, DependentCode)
9556 // Sets the value of the cell and updates the type field to be the union
9557 // of the cell's current type and the value's type. If the change causes
9558 // a change of the type of the cell's contents, code dependent on the cell
9559 // will be deoptimized.
9560 static void SetValueInferType(Handle<PropertyCell> cell,
9561 Handle<Object> value);
9563 // Computes the new type of the cell's contents for the given value, but
9564 // without actually modifying the 'type' field.
9565 static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9566 Handle<Object> value);
9568 static void AddDependentCompilationInfo(Handle<PropertyCell> cell,
9569 CompilationInfo* info);
9571 DECLARE_CAST(PropertyCell)
9573 inline Address TypeAddress() {
9574 return address() + kTypeOffset;
9577 // Dispatched behavior.
9578 DECLARE_PRINTER(PropertyCell)
9579 DECLARE_VERIFIER(PropertyCell)
9581 // Layout description.
9582 static const int kTypeOffset = kValueOffset + kPointerSize;
9583 static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9584 static const int kSize = kDependentCodeOffset + kPointerSize;
9586 static const int kPointerFieldsBeginOffset = kValueOffset;
9587 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9589 typedef FixedBodyDescriptor<kValueOffset,
9591 kSize> BodyDescriptor;
9594 DECL_ACCESSORS(type_raw, Object)
9595 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9599 class WeakCell : public HeapObject {
9601 inline Object* value() const;
9603 // This should not be called by anyone except GC.
9604 inline void clear();
9606 // This should not be called by anyone except allocator.
9607 inline void initialize(HeapObject* value);
9609 inline bool cleared() const;
9611 DECL_ACCESSORS(next, Object)
9613 DECLARE_CAST(WeakCell)
9615 DECLARE_PRINTER(WeakCell)
9616 DECLARE_VERIFIER(WeakCell)
9618 // Layout description.
9619 static const int kValueOffset = HeapObject::kHeaderSize;
9620 static const int kNextOffset = kValueOffset + kPointerSize;
9621 static const int kSize = kNextOffset + kPointerSize;
9623 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9626 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9630 // The JSProxy describes EcmaScript Harmony proxies
9631 class JSProxy: public JSReceiver {
9633 // [handler]: The handler property.
9634 DECL_ACCESSORS(handler, Object)
9636 // [hash]: The hash code property (undefined if not initialized yet).
9637 DECL_ACCESSORS(hash, Object)
9639 DECLARE_CAST(JSProxy)
9641 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9642 Handle<JSProxy> proxy,
9643 Handle<Object> receiver,
9645 MUST_USE_RESULT static inline MaybeHandle<Object> GetElementWithHandler(
9646 Handle<JSProxy> proxy,
9647 Handle<Object> receiver,
9650 // If the handler defines an accessor property with a setter, invoke it.
9651 // If it defines an accessor property without a setter, or a data property
9652 // that is read-only, throw. In all these cases set '*done' to true,
9653 // otherwise set it to false.
9655 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9656 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9657 Handle<Object> value, StrictMode strict_mode, bool* done);
9659 MUST_USE_RESULT static Maybe<PropertyAttributes>
9660 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9661 Handle<Object> receiver,
9663 MUST_USE_RESULT static Maybe<PropertyAttributes>
9664 GetElementAttributeWithHandler(Handle<JSProxy> proxy,
9665 Handle<JSReceiver> receiver,
9667 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9668 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9669 Handle<Object> value, StrictMode strict_mode);
9671 // Turn the proxy into an (empty) JSObject.
9672 static void Fix(Handle<JSProxy> proxy);
9674 // Initializes the body after the handler slot.
9675 inline void InitializeBody(int object_size, Object* value);
9677 // Invoke a trap by name. If the trap does not exist on this's handler,
9678 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9679 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9680 Handle<JSProxy> proxy,
9682 Handle<Object> derived_trap,
9684 Handle<Object> args[]);
9686 // Dispatched behavior.
9687 DECLARE_PRINTER(JSProxy)
9688 DECLARE_VERIFIER(JSProxy)
9690 // Layout description. We add padding so that a proxy has the same
9691 // size as a virgin JSObject. This is essential for becoming a JSObject
9693 static const int kHandlerOffset = HeapObject::kHeaderSize;
9694 static const int kHashOffset = kHandlerOffset + kPointerSize;
9695 static const int kPaddingOffset = kHashOffset + kPointerSize;
9696 static const int kSize = JSObject::kHeaderSize;
9697 static const int kHeaderSize = kPaddingOffset;
9698 static const int kPaddingSize = kSize - kPaddingOffset;
9700 STATIC_ASSERT(kPaddingSize >= 0);
9702 typedef FixedBodyDescriptor<kHandlerOffset,
9704 kSize> BodyDescriptor;
9707 friend class JSReceiver;
9709 MUST_USE_RESULT static inline MaybeHandle<Object> SetElementWithHandler(
9710 Handle<JSProxy> proxy,
9711 Handle<JSReceiver> receiver,
9713 Handle<Object> value,
9714 StrictMode strict_mode);
9716 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9717 Handle<JSProxy> proxy, Handle<Name> name);
9718 MUST_USE_RESULT static inline Maybe<bool> HasElementWithHandler(
9719 Handle<JSProxy> proxy, uint32_t index);
9721 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9722 Handle<JSProxy> proxy,
9725 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithHandler(
9726 Handle<JSProxy> proxy,
9730 MUST_USE_RESULT Object* GetIdentityHash();
9732 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9734 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9738 class JSFunctionProxy: public JSProxy {
9740 // [call_trap]: The call trap.
9741 DECL_ACCESSORS(call_trap, Object)
9743 // [construct_trap]: The construct trap.
9744 DECL_ACCESSORS(construct_trap, Object)
9746 DECLARE_CAST(JSFunctionProxy)
9748 // Dispatched behavior.
9749 DECLARE_PRINTER(JSFunctionProxy)
9750 DECLARE_VERIFIER(JSFunctionProxy)
9752 // Layout description.
9753 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9754 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9755 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9756 static const int kSize = JSFunction::kSize;
9757 static const int kPaddingSize = kSize - kPaddingOffset;
9759 STATIC_ASSERT(kPaddingSize >= 0);
9761 typedef FixedBodyDescriptor<kHandlerOffset,
9762 kConstructTrapOffset + kPointerSize,
9763 kSize> BodyDescriptor;
9766 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9770 class JSCollection : public JSObject {
9772 // [table]: the backing hash table
9773 DECL_ACCESSORS(table, Object)
9775 static const int kTableOffset = JSObject::kHeaderSize;
9776 static const int kSize = kTableOffset + kPointerSize;
9779 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9783 // The JSSet describes EcmaScript Harmony sets
9784 class JSSet : public JSCollection {
9788 // Dispatched behavior.
9789 DECLARE_PRINTER(JSSet)
9790 DECLARE_VERIFIER(JSSet)
9793 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9797 // The JSMap describes EcmaScript Harmony maps
9798 class JSMap : public JSCollection {
9802 // Dispatched behavior.
9803 DECLARE_PRINTER(JSMap)
9804 DECLARE_VERIFIER(JSMap)
9807 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9811 // OrderedHashTableIterator is an iterator that iterates over the keys and
9812 // values of an OrderedHashTable.
9814 // The iterator has a reference to the underlying OrderedHashTable data,
9815 // [table], as well as the current [index] the iterator is at.
9817 // When the OrderedHashTable is rehashed it adds a reference from the old table
9818 // to the new table as well as storing enough data about the changes so that the
9819 // iterator [index] can be adjusted accordingly.
9821 // When the [Next] result from the iterator is requested, the iterator checks if
9822 // there is a newer table that it needs to transition to.
9823 template<class Derived, class TableType>
9824 class OrderedHashTableIterator: public JSObject {
9826 // [table]: the backing hash table mapping keys to values.
9827 DECL_ACCESSORS(table, Object)
9829 // [index]: The index into the data table.
9830 DECL_ACCESSORS(index, Object)
9832 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9833 DECL_ACCESSORS(kind, Object)
9836 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9839 static const int kTableOffset = JSObject::kHeaderSize;
9840 static const int kIndexOffset = kTableOffset + kPointerSize;
9841 static const int kKindOffset = kIndexOffset + kPointerSize;
9842 static const int kSize = kKindOffset + kPointerSize;
9850 // Whether the iterator has more elements. This needs to be called before
9851 // calling |CurrentKey| and/or |CurrentValue|.
9854 // Move the index forward one.
9856 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9859 // Populates the array with the next key and value and then moves the iterator
9861 // This returns the |kind| or 0 if the iterator is already at the end.
9862 Smi* Next(JSArray* value_array);
9864 // Returns the current key of the iterator. This should only be called when
9865 // |HasMore| returns true.
9866 inline Object* CurrentKey();
9869 // Transitions the iterator to the non obsolete backing store. This is a NOP
9870 // if the [table] is not obsolete.
9873 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9877 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9880 // Dispatched behavior.
9881 DECLARE_PRINTER(JSSetIterator)
9882 DECLARE_VERIFIER(JSSetIterator)
9884 DECLARE_CAST(JSSetIterator)
9886 // Called by |Next| to populate the array. This allows the subclasses to
9887 // populate the array differently.
9888 inline void PopulateValueArray(FixedArray* array);
9891 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9895 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9898 // Dispatched behavior.
9899 DECLARE_PRINTER(JSMapIterator)
9900 DECLARE_VERIFIER(JSMapIterator)
9902 DECLARE_CAST(JSMapIterator)
9904 // Called by |Next| to populate the array. This allows the subclasses to
9905 // populate the array differently.
9906 inline void PopulateValueArray(FixedArray* array);
9909 // Returns the current value of the iterator. This should only be called when
9910 // |HasMore| returns true.
9911 inline Object* CurrentValue();
9913 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9917 // Base class for both JSWeakMap and JSWeakSet
9918 class JSWeakCollection: public JSObject {
9920 // [table]: the backing hash table mapping keys to values.
9921 DECL_ACCESSORS(table, Object)
9923 // [next]: linked list of encountered weak maps during GC.
9924 DECL_ACCESSORS(next, Object)
9926 static const int kTableOffset = JSObject::kHeaderSize;
9927 static const int kNextOffset = kTableOffset + kPointerSize;
9928 static const int kSize = kNextOffset + kPointerSize;
9931 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9935 // The JSWeakMap describes EcmaScript Harmony weak maps
9936 class JSWeakMap: public JSWeakCollection {
9938 DECLARE_CAST(JSWeakMap)
9940 // Dispatched behavior.
9941 DECLARE_PRINTER(JSWeakMap)
9942 DECLARE_VERIFIER(JSWeakMap)
9945 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9949 // The JSWeakSet describes EcmaScript Harmony weak sets
9950 class JSWeakSet: public JSWeakCollection {
9952 DECLARE_CAST(JSWeakSet)
9954 // Dispatched behavior.
9955 DECLARE_PRINTER(JSWeakSet)
9956 DECLARE_VERIFIER(JSWeakSet)
9959 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9963 class JSArrayBuffer: public JSObject {
9965 // [backing_store]: backing memory for this array
9966 DECL_ACCESSORS(backing_store, void)
9968 // [byte_length]: length in bytes
9969 DECL_ACCESSORS(byte_length, Object)
9972 DECL_ACCESSORS(flag, Smi)
9974 inline bool is_external();
9975 inline void set_is_external(bool value);
9977 inline bool should_be_freed();
9978 inline void set_should_be_freed(bool value);
9980 inline bool is_neuterable();
9981 inline void set_is_neuterable(bool value);
9983 // [weak_next]: linked list of array buffers.
9984 DECL_ACCESSORS(weak_next, Object)
9986 // [weak_first_array]: weak linked list of views.
9987 DECL_ACCESSORS(weak_first_view, Object)
9989 DECLARE_CAST(JSArrayBuffer)
9991 // Neutering. Only neuters the buffer, not associated typed arrays.
9994 // Dispatched behavior.
9995 DECLARE_PRINTER(JSArrayBuffer)
9996 DECLARE_VERIFIER(JSArrayBuffer)
9998 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9999 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10000 static const int kFlagOffset = kByteLengthOffset + kPointerSize;
10001 static const int kWeakNextOffset = kFlagOffset + kPointerSize;
10002 static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
10003 static const int kSize = kWeakFirstViewOffset + kPointerSize;
10005 static const int kSizeWithInternalFields =
10006 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10009 // Bit position in a flag
10010 static const int kIsExternalBit = 0;
10011 static const int kShouldBeFreed = 1;
10012 static const int kIsNeuterableBit = 2;
10014 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10018 class JSArrayBufferView: public JSObject {
10020 // [buffer]: ArrayBuffer that this typed array views.
10021 DECL_ACCESSORS(buffer, Object)
10023 // [byte_length]: offset of typed array in bytes.
10024 DECL_ACCESSORS(byte_offset, Object)
10026 // [byte_length]: length of typed array in bytes.
10027 DECL_ACCESSORS(byte_length, Object)
10029 // [weak_next]: linked list of typed arrays over the same array buffer.
10030 DECL_ACCESSORS(weak_next, Object)
10032 DECLARE_CAST(JSArrayBufferView)
10034 DECLARE_VERIFIER(JSArrayBufferView)
10036 static const int kBufferOffset = JSObject::kHeaderSize;
10037 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10038 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10039 static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
10040 static const int kViewSize = kWeakNextOffset + kPointerSize;
10046 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10050 class JSTypedArray: public JSArrayBufferView {
10052 // [length]: length of typed array in elements.
10053 DECL_ACCESSORS(length, Object)
10055 // Neutering. Only neuters this typed array.
10058 DECLARE_CAST(JSTypedArray)
10060 ExternalArrayType type();
10061 size_t element_size();
10063 Handle<JSArrayBuffer> GetBuffer();
10065 // Dispatched behavior.
10066 DECLARE_PRINTER(JSTypedArray)
10067 DECLARE_VERIFIER(JSTypedArray)
10069 static const int kLengthOffset = kViewSize + kPointerSize;
10070 static const int kSize = kLengthOffset + kPointerSize;
10072 static const int kSizeWithInternalFields =
10073 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10076 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10077 Handle<JSTypedArray> typed_array);
10079 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10083 class JSDataView: public JSArrayBufferView {
10085 // Only neuters this DataView
10088 DECLARE_CAST(JSDataView)
10090 // Dispatched behavior.
10091 DECLARE_PRINTER(JSDataView)
10092 DECLARE_VERIFIER(JSDataView)
10094 static const int kSize = kViewSize;
10096 static const int kSizeWithInternalFields =
10097 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10100 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10104 // Foreign describes objects pointing from JavaScript to C structures.
10105 // Since they cannot contain references to JS HeapObjects they can be
10106 // placed in old_data_space.
10107 class Foreign: public HeapObject {
10109 // [address]: field containing the address.
10110 inline Address foreign_address();
10111 inline void set_foreign_address(Address value);
10113 DECLARE_CAST(Foreign)
10115 // Dispatched behavior.
10116 inline void ForeignIterateBody(ObjectVisitor* v);
10118 template<typename StaticVisitor>
10119 inline void ForeignIterateBody();
10121 // Dispatched behavior.
10122 DECLARE_PRINTER(Foreign)
10123 DECLARE_VERIFIER(Foreign)
10125 // Layout description.
10127 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10128 static const int kSize = kForeignAddressOffset + kPointerSize;
10130 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10133 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10137 // The JSArray describes JavaScript Arrays
10138 // Such an array can be in one of two modes:
10139 // - fast, backing storage is a FixedArray and length <= elements.length();
10140 // Please note: push and pop can be used to grow and shrink the array.
10141 // - slow, backing storage is a HashTable with numbers as keys.
10142 class JSArray: public JSObject {
10144 // [length]: The length property.
10145 DECL_ACCESSORS(length, Object)
10147 // Overload the length setter to skip write barrier when the length
10148 // is set to a smi. This matches the set function on FixedArray.
10149 inline void set_length(Smi* length);
10151 static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10153 Handle<Object> value);
10155 static bool IsReadOnlyLengthDescriptor(Handle<Map> jsarray_map);
10156 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10157 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10159 // Initialize the array with the given capacity. The function may
10160 // fail due to out-of-memory situations, but only if the requested
10161 // capacity is non-zero.
10162 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10164 // Initializes the array to a certain length.
10165 inline bool AllowsSetElementsLength();
10167 MUST_USE_RESULT static MaybeHandle<Object> SetElementsLength(
10168 Handle<JSArray> array,
10169 Handle<Object> length);
10171 // Set the content of the array to the content of storage.
10172 static inline void SetContent(Handle<JSArray> array,
10173 Handle<FixedArrayBase> storage);
10175 DECLARE_CAST(JSArray)
10177 // Ensures that the fixed array backing the JSArray has at
10178 // least the stated size.
10179 static inline void EnsureSize(Handle<JSArray> array,
10180 int minimum_size_of_backing_fixed_array);
10182 // Expand the fixed array backing of a fast-case JSArray to at least
10183 // the requested size.
10184 static void Expand(Handle<JSArray> array,
10185 int minimum_size_of_backing_fixed_array);
10187 // Dispatched behavior.
10188 DECLARE_PRINTER(JSArray)
10189 DECLARE_VERIFIER(JSArray)
10191 // Number of element slots to pre-allocate for an empty array.
10192 static const int kPreallocatedArrayElements = 4;
10194 // Layout description.
10195 static const int kLengthOffset = JSObject::kHeaderSize;
10196 static const int kSize = kLengthOffset + kPointerSize;
10199 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10203 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10204 Handle<Map> initial_map);
10207 // JSRegExpResult is just a JSArray with a specific initial map.
10208 // This initial map adds in-object properties for "index" and "input"
10209 // properties, as assigned by RegExp.prototype.exec, which allows
10210 // faster creation of RegExp exec results.
10211 // This class just holds constants used when creating the result.
10212 // After creation the result must be treated as a JSArray in all regards.
10213 class JSRegExpResult: public JSArray {
10215 // Offsets of object fields.
10216 static const int kIndexOffset = JSArray::kSize;
10217 static const int kInputOffset = kIndexOffset + kPointerSize;
10218 static const int kSize = kInputOffset + kPointerSize;
10219 // Indices of in-object properties.
10220 static const int kIndexIndex = 0;
10221 static const int kInputIndex = 1;
10223 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10227 class AccessorInfo: public Struct {
10229 DECL_ACCESSORS(name, Object)
10230 DECL_ACCESSORS(flag, Smi)
10231 DECL_ACCESSORS(expected_receiver_type, Object)
10233 inline bool all_can_read();
10234 inline void set_all_can_read(bool value);
10236 inline bool all_can_write();
10237 inline void set_all_can_write(bool value);
10239 inline PropertyAttributes property_attributes();
10240 inline void set_property_attributes(PropertyAttributes attributes);
10242 // Checks whether the given receiver is compatible with this accessor.
10243 static bool IsCompatibleReceiverType(Isolate* isolate,
10244 Handle<AccessorInfo> info,
10245 Handle<HeapType> type);
10246 inline bool IsCompatibleReceiver(Object* receiver);
10248 DECLARE_CAST(AccessorInfo)
10250 // Dispatched behavior.
10251 DECLARE_VERIFIER(AccessorInfo)
10253 // Append all descriptors to the array that are not already there.
10254 // Return number added.
10255 static int AppendUnique(Handle<Object> descriptors,
10256 Handle<FixedArray> array,
10257 int valid_descriptors);
10259 static const int kNameOffset = HeapObject::kHeaderSize;
10260 static const int kFlagOffset = kNameOffset + kPointerSize;
10261 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10262 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10265 inline bool HasExpectedReceiverType() {
10266 return expected_receiver_type()->IsFunctionTemplateInfo();
10268 // Bit positions in flag.
10269 static const int kAllCanReadBit = 0;
10270 static const int kAllCanWriteBit = 1;
10271 class AttributesField: public BitField<PropertyAttributes, 2, 3> {};
10273 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10277 enum AccessorDescriptorType {
10278 kDescriptorBitmaskCompare,
10279 kDescriptorPointerCompare,
10280 kDescriptorPrimitiveValue,
10281 kDescriptorObjectDereference,
10282 kDescriptorPointerDereference,
10283 kDescriptorPointerShift,
10284 kDescriptorReturnObject
10288 struct BitmaskCompareDescriptor {
10290 uint32_t compare_value;
10291 uint8_t size; // Must be in {1,2,4}.
10295 struct PointerCompareDescriptor {
10296 void* compare_value;
10300 struct PrimitiveValueDescriptor {
10301 v8::DeclaredAccessorDescriptorDataType data_type;
10302 uint8_t bool_offset; // Must be in [0,7], used for kDescriptorBoolType.
10306 struct ObjectDerefenceDescriptor {
10307 uint8_t internal_field;
10311 struct PointerShiftDescriptor {
10312 int16_t byte_offset;
10316 struct DeclaredAccessorDescriptorData {
10317 AccessorDescriptorType type;
10319 struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10320 struct PointerCompareDescriptor pointer_compare_descriptor;
10321 struct PrimitiveValueDescriptor primitive_value_descriptor;
10322 struct ObjectDerefenceDescriptor object_dereference_descriptor;
10323 struct PointerShiftDescriptor pointer_shift_descriptor;
10328 class DeclaredAccessorDescriptor;
10331 class DeclaredAccessorDescriptorIterator {
10333 explicit DeclaredAccessorDescriptorIterator(
10334 DeclaredAccessorDescriptor* descriptor);
10335 const DeclaredAccessorDescriptorData* Next();
10336 bool Complete() const { return length_ == offset_; }
10341 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10345 class DeclaredAccessorDescriptor: public Struct {
10347 DECL_ACCESSORS(serialized_data, ByteArray)
10349 DECLARE_CAST(DeclaredAccessorDescriptor)
10351 static Handle<DeclaredAccessorDescriptor> Create(
10353 const DeclaredAccessorDescriptorData& data,
10354 Handle<DeclaredAccessorDescriptor> previous);
10356 // Dispatched behavior.
10357 DECLARE_PRINTER(DeclaredAccessorDescriptor)
10358 DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10360 static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10361 static const int kSize = kSerializedDataOffset + kPointerSize;
10364 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10368 class DeclaredAccessorInfo: public AccessorInfo {
10370 DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10372 DECLARE_CAST(DeclaredAccessorInfo)
10374 // Dispatched behavior.
10375 DECLARE_PRINTER(DeclaredAccessorInfo)
10376 DECLARE_VERIFIER(DeclaredAccessorInfo)
10378 static const int kDescriptorOffset = AccessorInfo::kSize;
10379 static const int kSize = kDescriptorOffset + kPointerSize;
10382 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10386 // An accessor must have a getter, but can have no setter.
10388 // When setting a property, V8 searches accessors in prototypes.
10389 // If an accessor was found and it does not have a setter,
10390 // the request is ignored.
10392 // If the accessor in the prototype has the READ_ONLY property attribute, then
10393 // a new value is added to the derived object when the property is set.
10394 // This shadows the accessor in the prototype.
10395 class ExecutableAccessorInfo: public AccessorInfo {
10397 DECL_ACCESSORS(getter, Object)
10398 DECL_ACCESSORS(setter, Object)
10399 DECL_ACCESSORS(data, Object)
10401 DECLARE_CAST(ExecutableAccessorInfo)
10403 // Dispatched behavior.
10404 DECLARE_PRINTER(ExecutableAccessorInfo)
10405 DECLARE_VERIFIER(ExecutableAccessorInfo)
10407 static const int kGetterOffset = AccessorInfo::kSize;
10408 static const int kSetterOffset = kGetterOffset + kPointerSize;
10409 static const int kDataOffset = kSetterOffset + kPointerSize;
10410 static const int kSize = kDataOffset + kPointerSize;
10412 inline void clear_setter();
10415 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10419 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10420 // accessor can either be
10421 // * a pointer to a JavaScript function or proxy: a real accessor
10422 // * undefined: considered an accessor by the spec, too, strangely enough
10423 // * the hole: an accessor which has not been set
10424 // * a pointer to a map: a transition used to ensure map sharing
10425 class AccessorPair: public Struct {
10427 DECL_ACCESSORS(getter, Object)
10428 DECL_ACCESSORS(setter, Object)
10430 DECLARE_CAST(AccessorPair)
10432 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10434 Object* get(AccessorComponent component) {
10435 return component == ACCESSOR_GETTER ? getter() : setter();
10438 void set(AccessorComponent component, Object* value) {
10439 if (component == ACCESSOR_GETTER) {
10446 // Note: Returns undefined instead in case of a hole.
10447 Object* GetComponent(AccessorComponent component);
10449 // Set both components, skipping arguments which are a JavaScript null.
10450 void SetComponents(Object* getter, Object* setter) {
10451 if (!getter->IsNull()) set_getter(getter);
10452 if (!setter->IsNull()) set_setter(setter);
10455 bool ContainsAccessor() {
10456 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10459 // Dispatched behavior.
10460 DECLARE_PRINTER(AccessorPair)
10461 DECLARE_VERIFIER(AccessorPair)
10463 static const int kGetterOffset = HeapObject::kHeaderSize;
10464 static const int kSetterOffset = kGetterOffset + kPointerSize;
10465 static const int kSize = kSetterOffset + kPointerSize;
10468 // Strangely enough, in addition to functions and harmony proxies, the spec
10469 // requires us to consider undefined as a kind of accessor, too:
10471 // Object.defineProperty(obj, "foo", {get: undefined});
10472 // assertTrue("foo" in obj);
10473 bool IsJSAccessor(Object* obj) {
10474 return obj->IsSpecFunction() || obj->IsUndefined();
10477 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10481 class AccessCheckInfo: public Struct {
10483 DECL_ACCESSORS(named_callback, Object)
10484 DECL_ACCESSORS(indexed_callback, Object)
10485 DECL_ACCESSORS(data, Object)
10487 DECLARE_CAST(AccessCheckInfo)
10489 // Dispatched behavior.
10490 DECLARE_PRINTER(AccessCheckInfo)
10491 DECLARE_VERIFIER(AccessCheckInfo)
10493 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10494 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10495 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10496 static const int kSize = kDataOffset + kPointerSize;
10499 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10503 class InterceptorInfo: public Struct {
10505 DECL_ACCESSORS(getter, Object)
10506 DECL_ACCESSORS(setter, Object)
10507 DECL_ACCESSORS(query, Object)
10508 DECL_ACCESSORS(deleter, Object)
10509 DECL_ACCESSORS(enumerator, Object)
10510 DECL_ACCESSORS(data, Object)
10512 DECLARE_CAST(InterceptorInfo)
10514 // Dispatched behavior.
10515 DECLARE_PRINTER(InterceptorInfo)
10516 DECLARE_VERIFIER(InterceptorInfo)
10518 static const int kGetterOffset = HeapObject::kHeaderSize;
10519 static const int kSetterOffset = kGetterOffset + kPointerSize;
10520 static const int kQueryOffset = kSetterOffset + kPointerSize;
10521 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10522 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10523 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10524 static const int kSize = kDataOffset + kPointerSize;
10527 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10531 class CallHandlerInfo: public Struct {
10533 DECL_ACCESSORS(callback, Object)
10534 DECL_ACCESSORS(data, Object)
10536 DECLARE_CAST(CallHandlerInfo)
10538 // Dispatched behavior.
10539 DECLARE_PRINTER(CallHandlerInfo)
10540 DECLARE_VERIFIER(CallHandlerInfo)
10542 static const int kCallbackOffset = HeapObject::kHeaderSize;
10543 static const int kDataOffset = kCallbackOffset + kPointerSize;
10544 static const int kSize = kDataOffset + kPointerSize;
10547 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10551 class TemplateInfo: public Struct {
10553 DECL_ACCESSORS(tag, Object)
10554 DECL_ACCESSORS(property_list, Object)
10555 DECL_ACCESSORS(property_accessors, Object)
10557 DECLARE_VERIFIER(TemplateInfo)
10559 static const int kTagOffset = HeapObject::kHeaderSize;
10560 static const int kPropertyListOffset = kTagOffset + kPointerSize;
10561 static const int kPropertyAccessorsOffset =
10562 kPropertyListOffset + kPointerSize;
10563 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10566 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10570 class FunctionTemplateInfo: public TemplateInfo {
10572 DECL_ACCESSORS(serial_number, Object)
10573 DECL_ACCESSORS(call_code, Object)
10574 DECL_ACCESSORS(prototype_template, Object)
10575 DECL_ACCESSORS(parent_template, Object)
10576 DECL_ACCESSORS(named_property_handler, Object)
10577 DECL_ACCESSORS(indexed_property_handler, Object)
10578 DECL_ACCESSORS(instance_template, Object)
10579 DECL_ACCESSORS(class_name, Object)
10580 DECL_ACCESSORS(signature, Object)
10581 DECL_ACCESSORS(instance_call_handler, Object)
10582 DECL_ACCESSORS(access_check_info, Object)
10583 DECL_ACCESSORS(flag, Smi)
10585 inline int length() const;
10586 inline void set_length(int value);
10588 // Following properties use flag bits.
10589 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10590 DECL_BOOLEAN_ACCESSORS(undetectable)
10591 // If the bit is set, object instances created by this function
10592 // requires access check.
10593 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10594 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10595 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10596 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10598 DECLARE_CAST(FunctionTemplateInfo)
10600 // Dispatched behavior.
10601 DECLARE_PRINTER(FunctionTemplateInfo)
10602 DECLARE_VERIFIER(FunctionTemplateInfo)
10604 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10605 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10606 static const int kPrototypeTemplateOffset =
10607 kCallCodeOffset + kPointerSize;
10608 static const int kParentTemplateOffset =
10609 kPrototypeTemplateOffset + kPointerSize;
10610 static const int kNamedPropertyHandlerOffset =
10611 kParentTemplateOffset + kPointerSize;
10612 static const int kIndexedPropertyHandlerOffset =
10613 kNamedPropertyHandlerOffset + kPointerSize;
10614 static const int kInstanceTemplateOffset =
10615 kIndexedPropertyHandlerOffset + kPointerSize;
10616 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10617 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10618 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10619 static const int kAccessCheckInfoOffset =
10620 kInstanceCallHandlerOffset + kPointerSize;
10621 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10622 static const int kLengthOffset = kFlagOffset + kPointerSize;
10623 static const int kSize = kLengthOffset + kPointerSize;
10625 // Returns true if |object| is an instance of this function template.
10626 bool IsTemplateFor(Object* object);
10627 bool IsTemplateFor(Map* map);
10630 // Bit position in the flag, from least significant bit position.
10631 static const int kHiddenPrototypeBit = 0;
10632 static const int kUndetectableBit = 1;
10633 static const int kNeedsAccessCheckBit = 2;
10634 static const int kReadOnlyPrototypeBit = 3;
10635 static const int kRemovePrototypeBit = 4;
10636 static const int kDoNotCacheBit = 5;
10638 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10642 class ObjectTemplateInfo: public TemplateInfo {
10644 DECL_ACCESSORS(constructor, Object)
10645 DECL_ACCESSORS(internal_field_count, Object)
10647 DECLARE_CAST(ObjectTemplateInfo)
10649 // Dispatched behavior.
10650 DECLARE_PRINTER(ObjectTemplateInfo)
10651 DECLARE_VERIFIER(ObjectTemplateInfo)
10653 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10654 static const int kInternalFieldCountOffset =
10655 kConstructorOffset + kPointerSize;
10656 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10660 class SignatureInfo: public Struct {
10662 DECL_ACCESSORS(receiver, Object)
10663 DECL_ACCESSORS(args, Object)
10665 DECLARE_CAST(SignatureInfo)
10667 // Dispatched behavior.
10668 DECLARE_PRINTER(SignatureInfo)
10669 DECLARE_VERIFIER(SignatureInfo)
10671 static const int kReceiverOffset = Struct::kHeaderSize;
10672 static const int kArgsOffset = kReceiverOffset + kPointerSize;
10673 static const int kSize = kArgsOffset + kPointerSize;
10676 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
10680 class TypeSwitchInfo: public Struct {
10682 DECL_ACCESSORS(types, Object)
10684 DECLARE_CAST(TypeSwitchInfo)
10686 // Dispatched behavior.
10687 DECLARE_PRINTER(TypeSwitchInfo)
10688 DECLARE_VERIFIER(TypeSwitchInfo)
10690 static const int kTypesOffset = Struct::kHeaderSize;
10691 static const int kSize = kTypesOffset + kPointerSize;
10695 // The DebugInfo class holds additional information for a function being
10697 class DebugInfo: public Struct {
10699 // The shared function info for the source being debugged.
10700 DECL_ACCESSORS(shared, SharedFunctionInfo)
10701 // Code object for the original code.
10702 DECL_ACCESSORS(original_code, Code)
10703 // Code object for the patched code. This code object is the code object
10704 // currently active for the function.
10705 DECL_ACCESSORS(code, Code)
10706 // Fixed array holding status information for each active break point.
10707 DECL_ACCESSORS(break_points, FixedArray)
10709 // Check if there is a break point at a code position.
10710 bool HasBreakPoint(int code_position);
10711 // Get the break point info object for a code position.
10712 Object* GetBreakPointInfo(int code_position);
10713 // Clear a break point.
10714 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10716 Handle<Object> break_point_object);
10717 // Set a break point.
10718 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10719 int source_position, int statement_position,
10720 Handle<Object> break_point_object);
10721 // Get the break point objects for a code position.
10722 Object* GetBreakPointObjects(int code_position);
10723 // Find the break point info holding this break point object.
10724 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
10725 Handle<Object> break_point_object);
10726 // Get the number of break points for this function.
10727 int GetBreakPointCount();
10729 DECLARE_CAST(DebugInfo)
10731 // Dispatched behavior.
10732 DECLARE_PRINTER(DebugInfo)
10733 DECLARE_VERIFIER(DebugInfo)
10735 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10736 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10737 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
10738 static const int kActiveBreakPointsCountIndex =
10739 kPatchedCodeIndex + kPointerSize;
10740 static const int kBreakPointsStateIndex =
10741 kActiveBreakPointsCountIndex + kPointerSize;
10742 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10744 static const int kEstimatedNofBreakPointsInFunction = 16;
10747 static const int kNoBreakPointInfo = -1;
10749 // Lookup the index in the break_points array for a code position.
10750 int GetBreakPointInfoIndex(int code_position);
10752 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10756 // The BreakPointInfo class holds information for break points set in a
10757 // function. The DebugInfo object holds a BreakPointInfo object for each code
10758 // position with one or more break points.
10759 class BreakPointInfo: public Struct {
10761 // The position in the code for the break point.
10762 DECL_ACCESSORS(code_position, Smi)
10763 // The position in the source for the break position.
10764 DECL_ACCESSORS(source_position, Smi)
10765 // The position in the source for the last statement before this break
10767 DECL_ACCESSORS(statement_position, Smi)
10768 // List of related JavaScript break points.
10769 DECL_ACCESSORS(break_point_objects, Object)
10771 // Removes a break point.
10772 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10773 Handle<Object> break_point_object);
10774 // Set a break point.
10775 static void SetBreakPoint(Handle<BreakPointInfo> info,
10776 Handle<Object> break_point_object);
10777 // Check if break point info has this break point object.
10778 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10779 Handle<Object> break_point_object);
10780 // Get the number of break points for this code position.
10781 int GetBreakPointCount();
10783 DECLARE_CAST(BreakPointInfo)
10785 // Dispatched behavior.
10786 DECLARE_PRINTER(BreakPointInfo)
10787 DECLARE_VERIFIER(BreakPointInfo)
10789 static const int kCodePositionIndex = Struct::kHeaderSize;
10790 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10791 static const int kStatementPositionIndex =
10792 kSourcePositionIndex + kPointerSize;
10793 static const int kBreakPointObjectsIndex =
10794 kStatementPositionIndex + kPointerSize;
10795 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10798 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10802 #undef DECL_BOOLEAN_ACCESSORS
10803 #undef DECL_ACCESSORS
10804 #undef DECLARE_CAST
10805 #undef DECLARE_VERIFIER
10807 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10808 V(kStringTable, "string_table", "(Internalized strings)") \
10809 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10810 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10811 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10812 V(kInternalizedString, "internalized_string", "(Internal string)") \
10813 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10814 V(kTop, "top", "(Isolate)") \
10815 V(kRelocatable, "relocatable", "(Relocatable)") \
10816 V(kDebug, "debug", "(Debugger)") \
10817 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10818 V(kHandleScope, "handlescope", "(Handle scope)") \
10819 V(kBuiltins, "builtins", "(Builtins)") \
10820 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10821 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10822 V(kThreadManager, "threadmanager", "(Thread manager)") \
10823 V(kExtensions, "Extensions", "(Extensions)")
10825 class VisitorSynchronization : public AllStatic {
10827 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10829 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10832 #undef DECLARE_ENUM
10834 static const char* const kTags[kNumberOfSyncTags];
10835 static const char* const kTagNames[kNumberOfSyncTags];
10838 // Abstract base class for visiting, and optionally modifying, the
10839 // pointers contained in Objects. Used in GC and serialization/deserialization.
10840 class ObjectVisitor BASE_EMBEDDED {
10842 virtual ~ObjectVisitor() {}
10844 // Visits a contiguous arrays of pointers in the half-open range
10845 // [start, end). Any or all of the values may be modified on return.
10846 virtual void VisitPointers(Object** start, Object** end) = 0;
10848 // Handy shorthand for visiting a single pointer.
10849 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10851 // Visit weak next_code_link in Code object.
10852 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10854 // To allow lazy clearing of inline caches the visitor has
10855 // a rich interface for iterating over Code objects..
10857 // Visits a code target in the instruction stream.
10858 virtual void VisitCodeTarget(RelocInfo* rinfo);
10860 // Visits a code entry in a JS function.
10861 virtual void VisitCodeEntry(Address entry_address);
10863 // Visits a global property cell reference in the instruction stream.
10864 virtual void VisitCell(RelocInfo* rinfo);
10866 // Visits a runtime entry in the instruction stream.
10867 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10869 // Visits the resource of an one-byte or two-byte string.
10870 virtual void VisitExternalOneByteString(
10871 v8::String::ExternalOneByteStringResource** resource) {}
10872 virtual void VisitExternalTwoByteString(
10873 v8::String::ExternalStringResource** resource) {}
10875 // Visits a debug call target in the instruction stream.
10876 virtual void VisitDebugTarget(RelocInfo* rinfo);
10878 // Visits the byte sequence in a function's prologue that contains information
10879 // about the code's age.
10880 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10882 // Visit pointer embedded into a code object.
10883 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10885 // Visits an external reference embedded into a code object.
10886 virtual void VisitExternalReference(RelocInfo* rinfo);
10888 // Visits an external reference. The value may be modified on return.
10889 virtual void VisitExternalReference(Address* p) {}
10891 // Visits a handle that has an embedder-assigned class ID.
10892 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10894 // Intended for serialization/deserialization checking: insert, or
10895 // check for the presence of, a tag at this position in the stream.
10896 // Also used for marking up GC roots in heap snapshots.
10897 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10901 class StructBodyDescriptor : public
10902 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10904 static inline int SizeOf(Map* map, HeapObject* object) {
10905 return map->instance_size();
10910 // BooleanBit is a helper class for setting and getting a bit in an
10912 class BooleanBit : public AllStatic {
10914 static inline bool get(Smi* smi, int bit_position) {
10915 return get(smi->value(), bit_position);
10918 static inline bool get(int value, int bit_position) {
10919 return (value & (1 << bit_position)) != 0;
10922 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10923 return Smi::FromInt(set(smi->value(), bit_position, v));
10926 static inline int set(int value, int bit_position, bool v) {
10928 value |= (1 << bit_position);
10930 value &= ~(1 << bit_position);
10936 } } // namespace v8::internal
10938 #endif // V8_OBJECTS_H_