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"
25 #if V8_TARGET_ARCH_ARM
26 #include "src/arm/constants-arm.h" // NOLINT
27 #elif V8_TARGET_ARCH_ARM64
28 #include "src/arm64/constants-arm64.h" // NOLINT
29 #elif V8_TARGET_ARCH_MIPS
30 #include "src/mips/constants-mips.h" // NOLINT
31 #elif V8_TARGET_ARCH_MIPS64
32 #include "src/mips64/constants-mips64.h" // NOLINT
37 // Most object types in the V8 JavaScript are described in this file.
39 // Inheritance hierarchy:
41 // - Smi (immediate small integer)
42 // - HeapObject (superclass for everything allocated in the heap)
43 // - JSReceiver (suitable for property access)
47 // - JSArrayBufferView
60 // - JSGeneratorObject
78 // - CompilationCacheTable
79 // - CodeCacheHashTable
85 // - TypeFeedbackVector
86 // - JSFunctionResultCache
91 // - ExternalUint8ClampedArray
92 // - ExternalInt8Array
93 // - ExternalUint8Array
94 // - ExternalInt16Array
95 // - ExternalUint16Array
96 // - ExternalInt32Array
97 // - ExternalUint32Array
98 // - ExternalFloat32Array
102 // - SeqOneByteString
103 // - SeqTwoByteString
107 // - ExternalOneByteString
108 // - ExternalTwoByteString
109 // - InternalizedString
110 // - SeqInternalizedString
111 // - SeqOneByteInternalizedString
112 // - SeqTwoByteInternalizedString
113 // - ConsInternalizedString
114 // - ExternalInternalizedString
115 // - ExternalOneByteInternalizedString
116 // - ExternalTwoByteInternalizedString
125 // - SharedFunctionInfo
128 // - DeclaredAccessorDescriptor
130 // - DeclaredAccessorInfo
131 // - ExecutableAccessorInfo
137 // - FunctionTemplateInfo
138 // - ObjectTemplateInfo
146 // Formats of Object*:
147 // Smi: [31 bit signed int] 0
148 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
153 enum KeyedAccessStoreMode {
155 STORE_TRANSITION_SMI_TO_OBJECT,
156 STORE_TRANSITION_SMI_TO_DOUBLE,
157 STORE_TRANSITION_DOUBLE_TO_OBJECT,
158 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
159 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
160 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
161 STORE_AND_GROW_NO_TRANSITION,
162 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
163 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
164 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
165 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
166 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
167 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
168 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
169 STORE_NO_TRANSITION_HANDLE_COW
173 enum ContextualMode {
185 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
187 STATIC_ASSERT(STANDARD_STORE == 0);
188 STATIC_ASSERT(kGrowICDelta ==
189 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
190 STORE_TRANSITION_SMI_TO_OBJECT);
191 STATIC_ASSERT(kGrowICDelta ==
192 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
193 STORE_TRANSITION_SMI_TO_DOUBLE);
194 STATIC_ASSERT(kGrowICDelta ==
195 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
196 STORE_TRANSITION_DOUBLE_TO_OBJECT);
199 static inline KeyedAccessStoreMode GetGrowStoreMode(
200 KeyedAccessStoreMode store_mode) {
201 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
202 store_mode = static_cast<KeyedAccessStoreMode>(
203 static_cast<int>(store_mode) + kGrowICDelta);
209 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
210 return store_mode > STANDARD_STORE &&
211 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
212 store_mode != STORE_AND_GROW_NO_TRANSITION;
216 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
217 KeyedAccessStoreMode store_mode) {
218 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
221 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
222 return STORE_AND_GROW_NO_TRANSITION;
224 return STANDARD_STORE;
228 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
229 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
230 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
234 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
235 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
238 // Indicates whether a value can be loaded as a constant.
245 // PropertyNormalizationMode is used to specify whether to keep
246 // inobject properties when normalizing properties of a JSObject.
247 enum PropertyNormalizationMode {
248 CLEAR_INOBJECT_PROPERTIES,
249 KEEP_INOBJECT_PROPERTIES
253 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
254 // will give the fastest result by tailoring the map to the prototype, but that
255 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
256 // (at least for now) when dynamically modifying the prototype chain of an
257 // object using __proto__ or Object.setPrototypeOf.
258 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
261 // Indicates whether transitions can be added to a source map or not.
262 enum TransitionFlag {
268 enum DebugExtraICState {
270 DEBUG_PREPARE_STEP_IN
274 // Indicates whether the transition is simple: the target map of the transition
275 // either extends the current map with a new property, or it modifies the
276 // property that was added last to the current map.
277 enum SimpleTransitionFlag {
283 // Indicates whether we are only interested in the descriptors of a particular
284 // map, or in all descriptors in the descriptor array.
285 enum DescriptorFlag {
290 // The GC maintains a bit of information, the MarkingParity, which toggles
291 // from odd to even and back every time marking is completed. Incremental
292 // marking can visit an object twice during a marking phase, so algorithms that
293 // that piggy-back on marking can use the parity to ensure that they only
294 // perform an operation on an object once per marking phase: they record the
295 // MarkingParity when they visit an object, and only re-visit the object when it
296 // is marked again and the MarkingParity changes.
303 // ICs store extra state in a Code object. The default extra state is
305 typedef int ExtraICState;
306 static const ExtraICState kNoExtraICState = 0;
308 // Instance size sentinel for objects of variable size.
309 const int kVariableSizeSentinel = 0;
311 // We may store the unsigned bit field as signed Smi value and do not
313 const int kStubMajorKeyBits = 7;
314 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
316 // All Maps have a field instance_type containing a InstanceType.
317 // It describes the type of the instances.
319 // As an example, a JavaScript object is a heap object and its map
320 // instance_type is JS_OBJECT_TYPE.
322 // The names of the string instance types are intended to systematically
323 // mirror their encoding in the instance_type field of the map. The default
324 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
325 // encoding is mentioned explicitly in the name. Likewise, the default
326 // representation is considered sequential. It is not mentioned in the
327 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
328 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
329 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
331 // NOTE: The following things are some that depend on the string types having
332 // instance_types that are less than those of all other types:
333 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
336 // NOTE: Everything following JS_VALUE_TYPE is considered a
337 // JSObject for GC purposes. The first four entries here have typeof
338 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
339 #define INSTANCE_TYPE_LIST(V) \
341 V(ONE_BYTE_STRING_TYPE) \
342 V(CONS_STRING_TYPE) \
343 V(CONS_ONE_BYTE_STRING_TYPE) \
344 V(SLICED_STRING_TYPE) \
345 V(SLICED_ONE_BYTE_STRING_TYPE) \
346 V(EXTERNAL_STRING_TYPE) \
347 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
348 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
349 V(SHORT_EXTERNAL_STRING_TYPE) \
350 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
351 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
353 V(INTERNALIZED_STRING_TYPE) \
354 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
355 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
356 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
357 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
358 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
359 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
360 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
368 V(PROPERTY_CELL_TYPE) \
370 V(HEAP_NUMBER_TYPE) \
371 V(MUTABLE_HEAP_NUMBER_TYPE) \
375 /* Note: the order of these external array */ \
376 /* types is relied upon in */ \
377 /* Object::IsExternalArray(). */ \
378 V(EXTERNAL_INT8_ARRAY_TYPE) \
379 V(EXTERNAL_UINT8_ARRAY_TYPE) \
380 V(EXTERNAL_INT16_ARRAY_TYPE) \
381 V(EXTERNAL_UINT16_ARRAY_TYPE) \
382 V(EXTERNAL_INT32_ARRAY_TYPE) \
383 V(EXTERNAL_UINT32_ARRAY_TYPE) \
384 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
385 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
386 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
388 V(FIXED_INT8_ARRAY_TYPE) \
389 V(FIXED_UINT8_ARRAY_TYPE) \
390 V(FIXED_INT16_ARRAY_TYPE) \
391 V(FIXED_UINT16_ARRAY_TYPE) \
392 V(FIXED_INT32_ARRAY_TYPE) \
393 V(FIXED_UINT32_ARRAY_TYPE) \
394 V(FIXED_FLOAT32_ARRAY_TYPE) \
395 V(FIXED_FLOAT64_ARRAY_TYPE) \
396 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
400 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
401 V(DECLARED_ACCESSOR_INFO_TYPE) \
402 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
403 V(ACCESSOR_PAIR_TYPE) \
404 V(ACCESS_CHECK_INFO_TYPE) \
405 V(INTERCEPTOR_INFO_TYPE) \
406 V(CALL_HANDLER_INFO_TYPE) \
407 V(FUNCTION_TEMPLATE_INFO_TYPE) \
408 V(OBJECT_TEMPLATE_INFO_TYPE) \
409 V(SIGNATURE_INFO_TYPE) \
410 V(TYPE_SWITCH_INFO_TYPE) \
411 V(ALLOCATION_MEMENTO_TYPE) \
412 V(ALLOCATION_SITE_TYPE) \
415 V(POLYMORPHIC_CODE_CACHE_TYPE) \
416 V(TYPE_FEEDBACK_INFO_TYPE) \
417 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
420 V(FIXED_ARRAY_TYPE) \
421 V(FIXED_DOUBLE_ARRAY_TYPE) \
422 V(CONSTANT_POOL_ARRAY_TYPE) \
423 V(SHARED_FUNCTION_INFO_TYPE) \
425 V(JS_MESSAGE_OBJECT_TYPE) \
430 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
431 V(JS_GENERATOR_OBJECT_TYPE) \
433 V(JS_GLOBAL_OBJECT_TYPE) \
434 V(JS_BUILTINS_OBJECT_TYPE) \
435 V(JS_GLOBAL_PROXY_TYPE) \
437 V(JS_ARRAY_BUFFER_TYPE) \
438 V(JS_TYPED_ARRAY_TYPE) \
439 V(JS_DATA_VIEW_TYPE) \
443 V(JS_SET_ITERATOR_TYPE) \
444 V(JS_MAP_ITERATOR_TYPE) \
445 V(JS_WEAK_MAP_TYPE) \
446 V(JS_WEAK_SET_TYPE) \
449 V(JS_FUNCTION_TYPE) \
450 V(JS_FUNCTION_PROXY_TYPE) \
452 V(BREAK_POINT_INFO_TYPE)
455 // Since string types are not consecutive, this macro is used to
456 // iterate over them.
457 #define STRING_TYPE_LIST(V) \
458 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
459 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
461 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
462 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
464 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
465 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
466 SlicedOneByteString) \
467 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
469 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
470 external_one_byte_string, ExternalOneByteString) \
471 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
472 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
473 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
474 short_external_string, ShortExternalString) \
475 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
476 short_external_one_byte_string, ShortExternalOneByteString) \
477 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
478 ExternalTwoByteString::kShortSize, \
479 short_external_string_with_one_byte_data, \
480 ShortExternalStringWithOneByteData) \
482 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
483 InternalizedString) \
484 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
485 one_byte_internalized_string, OneByteInternalizedString) \
486 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
487 external_internalized_string, ExternalInternalizedString) \
488 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
489 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
490 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
491 ExternalTwoByteString::kSize, \
492 external_internalized_string_with_one_byte_data, \
493 ExternalInternalizedStringWithOneByteData) \
494 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
495 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
496 ShortExternalInternalizedString) \
497 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
498 ExternalOneByteString::kShortSize, \
499 short_external_one_byte_internalized_string, \
500 ShortExternalOneByteInternalizedString) \
501 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
502 ExternalTwoByteString::kShortSize, \
503 short_external_internalized_string_with_one_byte_data, \
504 ShortExternalInternalizedStringWithOneByteData)
506 // A struct is a simple object a set of object-valued fields. Including an
507 // object type in this causes the compiler to generate most of the boilerplate
508 // code for the class including allocation and garbage collection routines,
509 // casts and predicates. All you need to define is the class, methods and
510 // object verification routines. Easy, no?
512 // Note that for subtle reasons related to the ordering or numerical values of
513 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
515 #define STRUCT_LIST(V) \
517 V(DECLARED_ACCESSOR_DESCRIPTOR, \
518 DeclaredAccessorDescriptor, \
519 declared_accessor_descriptor) \
520 V(DECLARED_ACCESSOR_INFO, DeclaredAccessorInfo, declared_accessor_info) \
521 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, executable_accessor_info)\
522 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
523 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
524 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
525 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
526 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
527 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
528 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
529 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
530 V(SCRIPT, Script, script) \
531 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
532 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
533 V(CODE_CACHE, CodeCache, code_cache) \
534 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
535 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
536 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
537 V(DEBUG_INFO, DebugInfo, debug_info) \
538 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
540 // We use the full 8 bits of the instance_type field to encode heap object
541 // instance types. The high-order bit (bit 7) is set if the object is not a
542 // string, and cleared if it is a string.
543 const uint32_t kIsNotStringMask = 0x80;
544 const uint32_t kStringTag = 0x0;
545 const uint32_t kNotStringTag = 0x80;
547 // Bit 6 indicates that the object is an internalized string (if set) or not.
548 // Bit 7 has to be clear as well.
549 const uint32_t kIsNotInternalizedMask = 0x40;
550 const uint32_t kNotInternalizedTag = 0x40;
551 const uint32_t kInternalizedTag = 0x0;
553 // If bit 7 is clear then bit 2 indicates whether the string consists of
554 // two-byte characters or one-byte characters.
555 const uint32_t kStringEncodingMask = 0x4;
556 const uint32_t kTwoByteStringTag = 0x0;
557 const uint32_t kOneByteStringTag = 0x4;
559 // If bit 7 is clear, the low-order 2 bits indicate the representation
561 const uint32_t kStringRepresentationMask = 0x03;
562 enum StringRepresentationTag {
564 kConsStringTag = 0x1,
565 kExternalStringTag = 0x2,
566 kSlicedStringTag = 0x3
568 const uint32_t kIsIndirectStringMask = 0x1;
569 const uint32_t kIsIndirectStringTag = 0x1;
570 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
571 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
572 STATIC_ASSERT((kConsStringTag &
573 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
574 STATIC_ASSERT((kSlicedStringTag &
575 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
577 // Use this mask to distinguish between cons and slice only after making
578 // sure that the string is one of the two (an indirect string).
579 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
580 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
582 // If bit 7 is clear, then bit 3 indicates whether this two-byte
583 // string actually contains one byte data.
584 const uint32_t kOneByteDataHintMask = 0x08;
585 const uint32_t kOneByteDataHintTag = 0x08;
587 // If bit 7 is clear and string representation indicates an external string,
588 // then bit 4 indicates whether the data pointer is cached.
589 const uint32_t kShortExternalStringMask = 0x10;
590 const uint32_t kShortExternalStringTag = 0x10;
593 // A ConsString with an empty string as the right side is a candidate
594 // for being shortcut by the garbage collector. We don't allocate any
595 // non-flat internalized strings, so we do not shortcut them thereby
596 // avoiding turning internalized strings into strings. The bit-masks
597 // below contain the internalized bit as additional safety.
598 // See heap.cc, mark-compact.cc and objects-visiting.cc.
599 const uint32_t kShortcutTypeMask =
601 kIsNotInternalizedMask |
602 kStringRepresentationMask;
603 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
605 static inline bool IsShortcutCandidate(int type) {
606 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
612 INTERNALIZED_STRING_TYPE =
613 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
614 ONE_BYTE_INTERNALIZED_STRING_TYPE =
615 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
616 EXTERNAL_INTERNALIZED_STRING_TYPE =
617 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
618 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
619 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
620 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
621 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
623 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
624 kShortExternalStringTag |
626 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
627 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
629 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
630 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
631 kShortExternalStringTag | kInternalizedTag,
632 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
633 ONE_BYTE_STRING_TYPE =
634 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
635 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
636 CONS_ONE_BYTE_STRING_TYPE =
637 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
639 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
640 SLICED_ONE_BYTE_STRING_TYPE =
641 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
642 EXTERNAL_STRING_TYPE =
643 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
644 EXTERNAL_ONE_BYTE_STRING_TYPE =
645 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
646 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
647 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
649 SHORT_EXTERNAL_STRING_TYPE =
650 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
651 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
652 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
653 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
654 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
658 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
660 // Objects allocated in their own spaces (never in new space).
667 // "Data", objects that cannot contain non-map-word pointers to heap
670 MUTABLE_HEAP_NUMBER_TYPE,
674 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
675 EXTERNAL_UINT8_ARRAY_TYPE,
676 EXTERNAL_INT16_ARRAY_TYPE,
677 EXTERNAL_UINT16_ARRAY_TYPE,
678 EXTERNAL_INT32_ARRAY_TYPE,
679 EXTERNAL_UINT32_ARRAY_TYPE,
680 EXTERNAL_FLOAT32_ARRAY_TYPE,
681 EXTERNAL_FLOAT64_ARRAY_TYPE,
682 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
683 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
684 FIXED_UINT8_ARRAY_TYPE,
685 FIXED_INT16_ARRAY_TYPE,
686 FIXED_UINT16_ARRAY_TYPE,
687 FIXED_INT32_ARRAY_TYPE,
688 FIXED_UINT32_ARRAY_TYPE,
689 FIXED_FLOAT32_ARRAY_TYPE,
690 FIXED_FLOAT64_ARRAY_TYPE,
691 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
692 FIXED_DOUBLE_ARRAY_TYPE,
693 FILLER_TYPE, // LAST_DATA_TYPE
696 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
697 DECLARED_ACCESSOR_INFO_TYPE,
698 EXECUTABLE_ACCESSOR_INFO_TYPE,
700 ACCESS_CHECK_INFO_TYPE,
701 INTERCEPTOR_INFO_TYPE,
702 CALL_HANDLER_INFO_TYPE,
703 FUNCTION_TEMPLATE_INFO_TYPE,
704 OBJECT_TEMPLATE_INFO_TYPE,
706 TYPE_SWITCH_INFO_TYPE,
707 ALLOCATION_SITE_TYPE,
708 ALLOCATION_MEMENTO_TYPE,
711 POLYMORPHIC_CODE_CACHE_TYPE,
712 TYPE_FEEDBACK_INFO_TYPE,
713 ALIASED_ARGUMENTS_ENTRY_TYPE,
716 BREAK_POINT_INFO_TYPE,
718 CONSTANT_POOL_ARRAY_TYPE,
719 SHARED_FUNCTION_INFO_TYPE,
721 // All the following types are subtypes of JSReceiver, which corresponds to
722 // objects in the JS sense. The first and the last type in this range are
723 // the two forms of function. This organization enables using the same
724 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
725 // NONCALLABLE_JS_OBJECT range.
726 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
727 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
728 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
729 JS_MESSAGE_OBJECT_TYPE,
732 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
733 JS_GENERATOR_OBJECT_TYPE,
735 JS_GLOBAL_OBJECT_TYPE,
736 JS_BUILTINS_OBJECT_TYPE,
737 JS_GLOBAL_PROXY_TYPE,
739 JS_ARRAY_BUFFER_TYPE,
744 JS_SET_ITERATOR_TYPE,
745 JS_MAP_ITERATOR_TYPE,
749 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
753 LAST_TYPE = JS_FUNCTION_TYPE,
754 FIRST_NAME_TYPE = FIRST_TYPE,
755 LAST_NAME_TYPE = SYMBOL_TYPE,
756 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
757 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
758 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
759 // Boundaries for testing for an external array.
760 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
761 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
762 // Boundaries for testing for a fixed typed array.
763 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
764 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
765 // Boundary for promotion to old data space/old pointer space.
766 LAST_DATA_TYPE = FILLER_TYPE,
767 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
768 // Note that there is no range for JSObject or JSProxy, since their subtypes
769 // are not continuous in this enum! The enum ranges instead reflect the
770 // external class names, where proxies are treated as either ordinary objects,
772 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
773 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
774 // Boundaries for testing the types represented as JSObject
775 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
776 LAST_JS_OBJECT_TYPE = LAST_TYPE,
777 // Boundaries for testing the types represented as JSProxy
778 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
779 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
780 // Boundaries for testing whether the type is a JavaScript object.
781 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
782 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
783 // Boundaries for testing the types for which typeof is "object".
784 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
785 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
786 // Note that the types for which typeof is "function" are not continuous.
787 // Define this so that we can put assertions on discrete checks.
788 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
791 const int kExternalArrayTypeCount =
792 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
794 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
795 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
796 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
797 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
800 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
801 V(FAST_ELEMENTS_SUB_TYPE) \
802 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
803 V(FAST_PROPERTIES_SUB_TYPE) \
804 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
805 V(MAP_CODE_CACHE_SUB_TYPE) \
806 V(SCOPE_INFO_SUB_TYPE) \
807 V(STRING_TABLE_SUB_TYPE) \
808 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
809 V(TRANSITION_ARRAY_SUB_TYPE)
811 enum FixedArraySubInstanceType {
812 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
813 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
814 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
815 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
828 #define DECL_BOOLEAN_ACCESSORS(name) \
829 inline bool name() const; \
830 inline void set_##name(bool value); \
833 #define DECL_ACCESSORS(name, type) \
834 inline type* name() const; \
835 inline void set_##name(type* value, \
836 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
839 #define DECLARE_CAST(type) \
840 INLINE(static type* cast(Object* object)); \
841 INLINE(static const type* cast(const Object* object));
845 class AllocationSite;
846 class AllocationSiteCreationContext;
847 class AllocationSiteUsageContext;
848 class DictionaryElementsAccessor;
849 class ElementsAccessor;
850 class FixedArrayBase;
853 class LookupIterator;
855 class TypeFeedbackVector;
856 // We cannot just say "class HeapType;" if it is created from a template... =8-?
857 template<class> class TypeImpl;
858 struct HeapTypeConfig;
859 typedef TypeImpl<HeapTypeConfig> HeapType;
862 // A template-ized version of the IsXXX functions.
863 template <class C> inline bool Is(Object* obj);
866 #define DECLARE_VERIFIER(Name) void Name##Verify();
868 #define DECLARE_VERIFIER(Name)
872 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
874 #define DECLARE_PRINTER(Name)
878 #define OBJECT_TYPE_LIST(V) \
883 #define HEAP_OBJECT_TYPE_LIST(V) \
885 V(MutableHeapNumber) \
893 V(ExternalTwoByteString) \
894 V(ExternalOneByteString) \
895 V(SeqTwoByteString) \
896 V(SeqOneByteString) \
897 V(InternalizedString) \
901 V(ExternalInt8Array) \
902 V(ExternalUint8Array) \
903 V(ExternalInt16Array) \
904 V(ExternalUint16Array) \
905 V(ExternalInt32Array) \
906 V(ExternalUint32Array) \
907 V(ExternalFloat32Array) \
908 V(ExternalFloat64Array) \
909 V(ExternalUint8ClampedArray) \
910 V(FixedTypedArrayBase) \
913 V(FixedUint16Array) \
915 V(FixedUint32Array) \
917 V(FixedFloat32Array) \
918 V(FixedFloat64Array) \
919 V(FixedUint8ClampedArray) \
924 V(JSContextExtensionObject) \
925 V(JSGeneratorObject) \
930 V(TypeFeedbackVector) \
931 V(DeoptimizationInputData) \
932 V(DeoptimizationOutputData) \
935 V(FixedDoubleArray) \
936 V(ConstantPoolArray) \
943 V(SharedFunctionInfo) \
952 V(JSArrayBufferView) \
961 V(JSWeakCollection) \
968 V(JSFunctionResultCache) \
969 V(NormalizedMapCache) \
970 V(CompilationCacheTable) \
971 V(CodeCacheHashTable) \
972 V(PolymorphicCodeCacheHashTable) \
977 V(JSBuiltinsObject) \
979 V(UndetectableObject) \
980 V(AccessCheckNeeded) \
987 // Object is the abstract superclass for all classes in the
989 // Object does not use any virtual functions to avoid the
990 // allocation of the C++ vtable.
991 // Since both Smi and HeapObject are subclasses of Object no
992 // data members can be present in Object.
996 bool IsObject() const { return true; }
998 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
999 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1000 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1001 #undef IS_TYPE_FUNCTION_DECL
1003 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1004 // a keyed store is of the form a[expression] = foo.
1005 enum StoreFromKeyed {
1006 MAY_BE_STORE_FROM_KEYED,
1007 CERTAINLY_NOT_STORE_FROM_KEYED
1010 enum StorePropertyMode { NORMAL_PROPERTY, SUPER_PROPERTY };
1012 INLINE(bool IsFixedArrayBase() const);
1013 INLINE(bool IsExternal() const);
1014 INLINE(bool IsAccessorInfo() const);
1016 INLINE(bool IsStruct() const);
1017 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1018 INLINE(bool Is##Name() const);
1019 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1020 #undef DECLARE_STRUCT_PREDICATE
1022 INLINE(bool IsSpecObject()) const;
1023 INLINE(bool IsSpecFunction()) const;
1024 INLINE(bool IsTemplateInfo()) const;
1025 INLINE(bool IsNameDictionary() const);
1026 INLINE(bool IsSeededNumberDictionary() const);
1027 INLINE(bool IsUnseededNumberDictionary() const);
1028 INLINE(bool IsOrderedHashSet() const);
1029 INLINE(bool IsOrderedHashMap() const);
1030 bool IsCallable() const;
1033 INLINE(bool IsUndefined() const);
1034 INLINE(bool IsNull() const);
1035 INLINE(bool IsTheHole() const);
1036 INLINE(bool IsException() const);
1037 INLINE(bool IsUninitialized() const);
1038 INLINE(bool IsTrue() const);
1039 INLINE(bool IsFalse() const);
1040 INLINE(bool IsArgumentsMarker() const);
1042 // Filler objects (fillers and free space objects).
1043 INLINE(bool IsFiller() const);
1045 // Extract the number.
1046 inline double Number();
1047 INLINE(bool IsNaN() const);
1048 INLINE(bool IsMinusZero() const);
1049 bool ToInt32(int32_t* value);
1050 bool ToUint32(uint32_t* value);
1052 inline Representation OptimalRepresentation() {
1053 if (!FLAG_track_fields) return Representation::Tagged();
1055 return Representation::Smi();
1056 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1057 return Representation::Double();
1058 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1059 return Representation::None();
1060 } else if (FLAG_track_heap_object_fields) {
1061 DCHECK(IsHeapObject());
1062 return Representation::HeapObject();
1064 return Representation::Tagged();
1068 inline bool FitsRepresentation(Representation representation) {
1069 if (FLAG_track_fields && representation.IsNone()) {
1071 } else if (FLAG_track_fields && representation.IsSmi()) {
1073 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1074 return IsMutableHeapNumber() || IsNumber();
1075 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1076 return IsHeapObject();
1081 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1083 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1084 Handle<Object> object,
1085 Representation representation);
1087 inline static Handle<Object> WrapForRead(Isolate* isolate,
1088 Handle<Object> object,
1089 Representation representation);
1091 // Returns true if the object is of the correct type to be used as a
1092 // implementation of a JSObject's elements.
1093 inline bool HasValidElements();
1095 inline bool HasSpecificClassOf(String* name);
1097 bool BooleanValue(); // ECMA-262 9.2.
1099 // Convert to a JSObject if needed.
1100 // native_context is used when creating wrapper object.
1101 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1102 Handle<Object> object);
1103 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1104 Handle<Object> object,
1105 Handle<Context> context);
1107 // Converts this to a Smi if possible.
1108 static MUST_USE_RESULT inline MaybeHandle<Smi> ToSmi(Isolate* isolate,
1109 Handle<Object> object);
1111 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(LookupIterator* it);
1113 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1114 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1115 Handle<Object> object, Handle<Name> key, Handle<Object> value,
1116 StrictMode strict_mode,
1117 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1119 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1120 LookupIterator* it, Handle<Object> value, StrictMode strict_mode,
1121 StoreFromKeyed store_mode,
1122 StorePropertyMode data_store_mode = NORMAL_PROPERTY);
1123 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1124 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
1125 static Handle<Object> SetDataProperty(LookupIterator* it,
1126 Handle<Object> value);
1127 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1128 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1129 StrictMode strict_mode, StoreFromKeyed store_mode);
1130 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1131 Handle<Object> object,
1133 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1135 Handle<Object> object,
1137 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1138 Handle<Object> object,
1141 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1142 Handle<Object> receiver,
1144 Handle<JSObject> holder,
1145 Handle<Object> structure);
1146 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1147 Handle<Object> receiver, Handle<Name> name, Handle<Object> value,
1148 Handle<JSObject> holder, Handle<Object> structure,
1149 StrictMode strict_mode);
1151 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1152 Handle<Object> receiver,
1153 Handle<JSReceiver> getter);
1154 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1155 Handle<Object> receiver,
1156 Handle<JSReceiver> setter,
1157 Handle<Object> value);
1159 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1161 Handle<Object> object,
1164 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithReceiver(
1166 Handle<Object> object,
1167 Handle<Object> receiver,
1170 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1171 Isolate* isolate, Handle<Object> receiver);
1173 // Returns the permanent hash code associated with this object. May return
1174 // undefined if not yet created.
1177 // Returns the permanent hash code associated with this object depending on
1178 // the actual object type. May create and store a hash code if needed and none
1180 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1182 // Checks whether this object has the same value as the given one. This
1183 // function is implemented according to ES5, section 9.12 and can be used
1184 // to implement the Harmony "egal" function.
1185 bool SameValue(Object* other);
1187 // Checks whether this object has the same value as the given one.
1188 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1189 // This function is implemented according to ES6, section 7.2.4 and is used
1190 // by ES6 Map and Set.
1191 bool SameValueZero(Object* other);
1193 // Tries to convert an object to an array index. Returns true and sets
1194 // the output parameter if it succeeds.
1195 inline bool ToArrayIndex(uint32_t* index);
1197 // Returns true if this is a JSValue containing a string and the index is
1198 // < the length of the string. Used to implement [] on strings.
1199 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1201 DECLARE_VERIFIER(Object)
1203 // Verify a pointer is a valid object pointer.
1204 static void VerifyPointer(Object* p);
1207 inline void VerifyApiCallResultType();
1209 // Prints this object without details.
1210 void ShortPrint(FILE* out = stdout);
1212 // Prints this object without details to a message accumulator.
1213 void ShortPrint(StringStream* accumulator);
1215 DECLARE_CAST(Object)
1217 // Layout description.
1218 static const int kHeaderSize = 0; // Object does not take up any space.
1221 // For our gdb macros, we should perhaps change these in the future.
1224 // Prints this object with details.
1225 void Print(std::ostream& os); // NOLINT
1229 friend class LookupIterator;
1230 friend class PrototypeIterator;
1232 // Return the map of the root of object's prototype chain.
1233 Map* GetRootMap(Isolate* isolate);
1235 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1240 explicit Brief(const Object* const v) : value(v) {}
1241 const Object* value;
1245 std::ostream& operator<<(std::ostream& os, const Brief& v);
1248 // Smi represents integer Numbers that can be stored in 31 bits.
1249 // Smis are immediate which means they are NOT allocated in the heap.
1250 // The this pointer has the following format: [31 bit signed int] 0
1251 // For long smis it has the following format:
1252 // [32 bit signed int] [31 bits zero padding] 0
1253 // Smi stands for small integer.
1254 class Smi: public Object {
1256 // Returns the integer value.
1257 inline int value() const;
1259 // Convert a value to a Smi object.
1260 static inline Smi* FromInt(int value);
1262 static inline Smi* FromIntptr(intptr_t value);
1264 // Returns whether value can be represented in a Smi.
1265 static inline bool IsValid(intptr_t value);
1269 // Dispatched behavior.
1270 void SmiPrint(std::ostream& os) const; // NOLINT
1271 DECLARE_VERIFIER(Smi)
1273 static const int kMinValue =
1274 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1275 static const int kMaxValue = -(kMinValue + 1);
1278 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1282 // Heap objects typically have a map pointer in their first word. However,
1283 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1284 // encoded in the first word. The class MapWord is an abstraction of the
1285 // value in a heap object's first word.
1286 class MapWord BASE_EMBEDDED {
1288 // Normal state: the map word contains a map pointer.
1290 // Create a map word from a map pointer.
1291 static inline MapWord FromMap(const Map* map);
1293 // View this map word as a map pointer.
1294 inline Map* ToMap();
1297 // Scavenge collection: the map word of live objects in the from space
1298 // contains a forwarding address (a heap object pointer in the to space).
1300 // True if this map word is a forwarding address for a scavenge
1301 // collection. Only valid during a scavenge collection (specifically,
1302 // when all map words are heap object pointers, i.e. not during a full GC).
1303 inline bool IsForwardingAddress();
1305 // Create a map word from a forwarding address.
1306 static inline MapWord FromForwardingAddress(HeapObject* object);
1308 // View this map word as a forwarding address.
1309 inline HeapObject* ToForwardingAddress();
1311 static inline MapWord FromRawValue(uintptr_t value) {
1312 return MapWord(value);
1315 inline uintptr_t ToRawValue() {
1320 // HeapObject calls the private constructor and directly reads the value.
1321 friend class HeapObject;
1323 explicit MapWord(uintptr_t value) : value_(value) {}
1329 // HeapObject is the superclass for all classes describing heap allocated
1331 class HeapObject: public Object {
1333 // [map]: Contains a map which contains the object's reflective
1335 inline Map* map() const;
1336 inline void set_map(Map* value);
1337 // The no-write-barrier version. This is OK if the object is white and in
1338 // new space, or if the value is an immortal immutable object, like the maps
1339 // of primitive (non-JS) objects like strings, heap numbers etc.
1340 inline void set_map_no_write_barrier(Map* value);
1342 // Get the map using acquire load.
1343 inline Map* synchronized_map();
1344 inline MapWord synchronized_map_word() const;
1346 // Set the map using release store
1347 inline void synchronized_set_map(Map* value);
1348 inline void synchronized_set_map_no_write_barrier(Map* value);
1349 inline void synchronized_set_map_word(MapWord map_word);
1351 // During garbage collection, the map word of a heap object does not
1352 // necessarily contain a map pointer.
1353 inline MapWord map_word() const;
1354 inline void set_map_word(MapWord map_word);
1356 // The Heap the object was allocated in. Used also to access Isolate.
1357 inline Heap* GetHeap() const;
1359 // Convenience method to get current isolate.
1360 inline Isolate* GetIsolate() const;
1362 // Converts an address to a HeapObject pointer.
1363 static inline HeapObject* FromAddress(Address address);
1365 // Returns the address of this HeapObject.
1366 inline Address address();
1368 // Iterates over pointers contained in the object (including the Map)
1369 void Iterate(ObjectVisitor* v);
1371 // Iterates over all pointers contained in the object except the
1372 // first map pointer. The object type is given in the first
1373 // parameter. This function does not access the map pointer in the
1374 // object, and so is safe to call while the map pointer is modified.
1375 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1377 // Returns the heap object's size in bytes
1380 // Returns true if this heap object may contain raw values, i.e., values that
1381 // look like pointers to heap objects.
1382 inline bool MayContainRawValues();
1384 // Given a heap object's map pointer, returns the heap size in bytes
1385 // Useful when the map pointer field is used for other purposes.
1387 inline int SizeFromMap(Map* map);
1389 // Returns the field at offset in obj, as a read/write Object* reference.
1390 // Does no checking, and is safe to use during GC, while maps are invalid.
1391 // Does not invoke write barrier, so should only be assigned to
1392 // during marking GC.
1393 static inline Object** RawField(HeapObject* obj, int offset);
1395 // Adds the |code| object related to |name| to the code cache of this map. If
1396 // this map is a dictionary map that is shared, the map copied and installed
1398 static void UpdateMapCodeCache(Handle<HeapObject> object,
1402 DECLARE_CAST(HeapObject)
1404 // Return the write barrier mode for this. Callers of this function
1405 // must be able to present a reference to an DisallowHeapAllocation
1406 // object as a sign that they are not going to use this function
1407 // from code that allocates and thus invalidates the returned write
1409 inline WriteBarrierMode GetWriteBarrierMode(
1410 const DisallowHeapAllocation& promise);
1412 // Dispatched behavior.
1413 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1415 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1417 DECLARE_PRINTER(HeapObject)
1418 DECLARE_VERIFIER(HeapObject)
1420 inline void VerifyObjectField(int offset);
1421 inline void VerifySmiField(int offset);
1423 // Verify a pointer is a valid HeapObject pointer that points to object
1424 // areas in the heap.
1425 static void VerifyHeapPointer(Object* p);
1428 // Layout description.
1429 // First field in a heap object is map.
1430 static const int kMapOffset = Object::kHeaderSize;
1431 static const int kHeaderSize = kMapOffset + kPointerSize;
1433 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1436 // helpers for calling an ObjectVisitor to iterate over pointers in the
1437 // half-open range [start, end) specified as integer offsets
1438 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1439 // as above, for the single element at "offset"
1440 inline void IteratePointer(ObjectVisitor* v, int offset);
1441 // as above, for the next code link of a code object.
1442 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1445 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1449 // This class describes a body of an object of a fixed size
1450 // in which all pointer fields are located in the [start_offset, end_offset)
1452 template<int start_offset, int end_offset, int size>
1453 class FixedBodyDescriptor {
1455 static const int kStartOffset = start_offset;
1456 static const int kEndOffset = end_offset;
1457 static const int kSize = size;
1459 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1461 template<typename StaticVisitor>
1462 static inline void IterateBody(HeapObject* obj) {
1463 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1464 HeapObject::RawField(obj, end_offset));
1469 // This class describes a body of an object of a variable size
1470 // in which all pointer fields are located in the [start_offset, object_size)
1472 template<int start_offset>
1473 class FlexibleBodyDescriptor {
1475 static const int kStartOffset = start_offset;
1477 static inline void IterateBody(HeapObject* obj,
1481 template<typename StaticVisitor>
1482 static inline void IterateBody(HeapObject* obj, int object_size) {
1483 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1484 HeapObject::RawField(obj, object_size));
1489 // The HeapNumber class describes heap allocated numbers that cannot be
1490 // represented in a Smi (small integer)
1491 class HeapNumber: public HeapObject {
1493 // [value]: number value.
1494 inline double value() const;
1495 inline void set_value(double value);
1497 DECLARE_CAST(HeapNumber)
1499 // Dispatched behavior.
1500 bool HeapNumberBooleanValue();
1502 void HeapNumberPrint(std::ostream& os); // NOLINT
1503 DECLARE_VERIFIER(HeapNumber)
1505 inline int get_exponent();
1506 inline int get_sign();
1508 // Layout description.
1509 static const int kValueOffset = HeapObject::kHeaderSize;
1510 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1511 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1512 // words within double numbers are endian dependent and they are set
1514 #if defined(V8_TARGET_LITTLE_ENDIAN)
1515 static const int kMantissaOffset = kValueOffset;
1516 static const int kExponentOffset = kValueOffset + 4;
1517 #elif defined(V8_TARGET_BIG_ENDIAN)
1518 static const int kMantissaOffset = kValueOffset + 4;
1519 static const int kExponentOffset = kValueOffset;
1521 #error Unknown byte ordering
1524 static const int kSize = kValueOffset + kDoubleSize;
1525 static const uint32_t kSignMask = 0x80000000u;
1526 static const uint32_t kExponentMask = 0x7ff00000u;
1527 static const uint32_t kMantissaMask = 0xfffffu;
1528 static const int kMantissaBits = 52;
1529 static const int kExponentBits = 11;
1530 static const int kExponentBias = 1023;
1531 static const int kExponentShift = 20;
1532 static const int kInfinityOrNanExponent =
1533 (kExponentMask >> kExponentShift) - kExponentBias;
1534 static const int kMantissaBitsInTopWord = 20;
1535 static const int kNonMantissaBitsInTopWord = 12;
1538 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1542 enum EnsureElementsMode {
1543 DONT_ALLOW_DOUBLE_ELEMENTS,
1544 ALLOW_COPIED_DOUBLE_ELEMENTS,
1545 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1549 // Indicates whether a property should be set or (re)defined. Setting of a
1550 // property causes attributes to remain unchanged, writability to be checked
1551 // and callbacks to be called. Defining of a property causes attributes to
1552 // be updated and callbacks to be overridden.
1553 enum SetPropertyMode {
1559 // Indicator for one component of an AccessorPair.
1560 enum AccessorComponent {
1566 // JSReceiver includes types on which properties can be defined, i.e.,
1567 // JSObject and JSProxy.
1568 class JSReceiver: public HeapObject {
1576 DECLARE_CAST(JSReceiver)
1578 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1579 Handle<JSReceiver> object,
1581 Handle<Object> value,
1582 PropertyAttributes attributes,
1583 StrictMode strict_mode);
1585 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1586 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1587 Handle<JSReceiver> object, Handle<Name> name);
1588 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1590 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1591 Handle<JSReceiver> object, uint32_t index);
1592 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1593 Handle<JSReceiver> object, uint32_t index);
1595 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1596 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1597 Handle<JSReceiver> object,
1599 DeleteMode mode = NORMAL_DELETION);
1600 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1601 Handle<JSReceiver> object,
1603 DeleteMode mode = NORMAL_DELETION);
1605 // Tests for the fast common case for property enumeration.
1606 bool IsSimpleEnum();
1608 // Returns the class name ([[Class]] property in the specification).
1609 String* class_name();
1611 // Returns the constructor name (the name (possibly, inferred name) of the
1612 // function that was used to instantiate the object).
1613 String* constructor_name();
1615 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1616 Handle<JSReceiver> object, Handle<Name> name);
1617 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1618 LookupIterator* it);
1619 MUST_USE_RESULT static Maybe<PropertyAttributes> GetOwnPropertyAttributes(
1620 Handle<JSReceiver> object, Handle<Name> name);
1622 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttribute(
1623 Handle<JSReceiver> object, uint32_t index);
1624 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1625 GetOwnElementAttribute(Handle<JSReceiver> object, uint32_t index);
1627 // Return the constructor function (may be Heap::null_value()).
1628 inline Object* GetConstructor();
1630 // Retrieves a permanent object identity hash code. The undefined value might
1631 // be returned in case no hash was created yet.
1632 inline Object* GetIdentityHash();
1634 // Retrieves a permanent object identity hash code. May create and store a
1635 // hash code if needed and none exists.
1636 inline static Handle<Smi> GetOrCreateIdentityHash(
1637 Handle<JSReceiver> object);
1639 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1641 // Computes the enumerable keys for a JSObject. Used for implementing
1642 // "for (n in object) { }".
1643 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1644 Handle<JSReceiver> object,
1645 KeyCollectionType type);
1648 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1651 // Forward declaration for JSObject::GetOrCreateHiddenPropertiesHashTable.
1652 class ObjectHashTable;
1654 // Forward declaration for JSObject::Copy.
1655 class AllocationSite;
1658 // The JSObject describes real heap allocated JavaScript objects with
1660 // Note that the map of JSObject changes during execution to enable inline
1662 class JSObject: public JSReceiver {
1664 // [properties]: Backing storage for properties.
1665 // properties is a FixedArray in the fast case and a Dictionary in the
1667 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1668 inline void initialize_properties();
1669 inline bool HasFastProperties();
1670 inline NameDictionary* property_dictionary(); // Gets slow properties.
1672 // [elements]: The elements (properties with names that are integers).
1674 // Elements can be in two general modes: fast and slow. Each mode
1675 // corrensponds to a set of object representations of elements that
1676 // have something in common.
1678 // In the fast mode elements is a FixedArray and so each element can
1679 // be quickly accessed. This fact is used in the generated code. The
1680 // elements array can have one of three maps in this mode:
1681 // fixed_array_map, sloppy_arguments_elements_map or
1682 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1683 // the elements array may be shared by a few objects and so before
1684 // writing to any element the array must be copied. Use
1685 // EnsureWritableFastElements in this case.
1687 // In the slow mode the elements is either a NumberDictionary, an
1688 // ExternalArray, or a FixedArray parameter map for a (sloppy)
1689 // arguments object.
1690 DECL_ACCESSORS(elements, FixedArrayBase)
1691 inline void initialize_elements();
1692 static void ResetElements(Handle<JSObject> object);
1693 static inline void SetMapAndElements(Handle<JSObject> object,
1695 Handle<FixedArrayBase> elements);
1696 inline ElementsKind GetElementsKind();
1697 inline ElementsAccessor* GetElementsAccessor();
1698 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1699 inline bool HasFastSmiElements();
1700 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1701 inline bool HasFastObjectElements();
1702 // Returns true if an object has elements of FAST_ELEMENTS or
1703 // FAST_SMI_ONLY_ELEMENTS.
1704 inline bool HasFastSmiOrObjectElements();
1705 // Returns true if an object has any of the fast elements kinds.
1706 inline bool HasFastElements();
1707 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1709 inline bool HasFastDoubleElements();
1710 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1712 inline bool HasFastHoleyElements();
1713 inline bool HasSloppyArgumentsElements();
1714 inline bool HasDictionaryElements();
1716 inline bool HasExternalUint8ClampedElements();
1717 inline bool HasExternalArrayElements();
1718 inline bool HasExternalInt8Elements();
1719 inline bool HasExternalUint8Elements();
1720 inline bool HasExternalInt16Elements();
1721 inline bool HasExternalUint16Elements();
1722 inline bool HasExternalInt32Elements();
1723 inline bool HasExternalUint32Elements();
1724 inline bool HasExternalFloat32Elements();
1725 inline bool HasExternalFloat64Elements();
1727 inline bool HasFixedTypedArrayElements();
1729 inline bool HasFixedUint8ClampedElements();
1730 inline bool HasFixedArrayElements();
1731 inline bool HasFixedInt8Elements();
1732 inline bool HasFixedUint8Elements();
1733 inline bool HasFixedInt16Elements();
1734 inline bool HasFixedUint16Elements();
1735 inline bool HasFixedInt32Elements();
1736 inline bool HasFixedUint32Elements();
1737 inline bool HasFixedFloat32Elements();
1738 inline bool HasFixedFloat64Elements();
1740 bool HasFastArgumentsElements();
1741 bool HasDictionaryArgumentsElements();
1742 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1744 // Requires: HasFastElements().
1745 static Handle<FixedArray> EnsureWritableFastElements(
1746 Handle<JSObject> object);
1748 // Collects elements starting at index 0.
1749 // Undefined values are placed after non-undefined values.
1750 // Returns the number of non-undefined values.
1751 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1753 // As PrepareElementsForSort, but only on objects where elements is
1754 // a dictionary, and it will stay a dictionary. Collates undefined and
1755 // unexisting elements below limit from position zero of the elements.
1756 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1759 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1760 LookupIterator* it, Handle<Object> value);
1762 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1763 // grant an exemption to ExecutableAccessor callbacks in some cases.
1764 enum ExecutableAccessorInfoHandling {
1769 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1770 Handle<JSObject> object,
1772 Handle<Object> value,
1773 PropertyAttributes attributes,
1774 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1776 static void AddProperty(Handle<JSObject> object, Handle<Name> key,
1777 Handle<Object> value, PropertyAttributes attributes);
1779 // Extend the receiver with a single fast property appeared first in the
1780 // passed map. This also extends the property backing store if necessary.
1781 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1783 // Migrates the given object to a map whose field representations are the
1784 // lowest upper bound of all known representations for that field.
1785 static void MigrateInstance(Handle<JSObject> instance);
1787 // Migrates the given object only if the target map is already available,
1788 // or returns false if such a map is not yet available.
1789 static bool TryMigrateInstance(Handle<JSObject> instance);
1791 // Sets the property value in a normalized object given (key, value, details).
1792 // Handles the special representation of JS global objects.
1793 static void SetNormalizedProperty(Handle<JSObject> object,
1795 Handle<Object> value,
1796 PropertyDetails details);
1798 static void OptimizeAsPrototype(Handle<JSObject> object,
1799 PrototypeOptimizationMode mode);
1800 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1802 // Retrieve interceptors.
1803 InterceptorInfo* GetNamedInterceptor();
1804 InterceptorInfo* GetIndexedInterceptor();
1806 // Used from JSReceiver.
1807 MUST_USE_RESULT static Maybe<PropertyAttributes>
1808 GetPropertyAttributesWithInterceptor(Handle<JSObject> holder,
1809 Handle<Object> receiver,
1811 MUST_USE_RESULT static Maybe<PropertyAttributes>
1812 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1813 MUST_USE_RESULT static Maybe<PropertyAttributes>
1814 GetElementAttributeWithReceiver(Handle<JSObject> object,
1815 Handle<JSReceiver> receiver,
1816 uint32_t index, bool check_prototype);
1818 // Retrieves an AccessorPair property from the given object. Might return
1819 // undefined if the property doesn't exist or is of a different kind.
1820 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1821 Handle<JSObject> object,
1823 AccessorComponent component);
1825 // Defines an AccessorPair property on the given object.
1826 // TODO(mstarzinger): Rename to SetAccessor().
1827 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1829 Handle<Object> getter,
1830 Handle<Object> setter,
1831 PropertyAttributes attributes);
1833 // Defines an AccessorInfo property on the given object.
1834 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1835 Handle<JSObject> object,
1836 Handle<AccessorInfo> info);
1838 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1839 Handle<JSObject> object,
1840 Handle<Object> receiver,
1843 // Returns true if this is an instance of an api function and has
1844 // been modified since it was created. May give false positives.
1847 // Accessors for hidden properties object.
1849 // Hidden properties are not own properties of the object itself.
1850 // Instead they are stored in an auxiliary structure kept as an own
1851 // property with a special name Heap::hidden_string(). But if the
1852 // receiver is a JSGlobalProxy then the auxiliary object is a property
1853 // of its prototype, and if it's a detached proxy, then you can't have
1854 // hidden properties.
1856 // Sets a hidden property on this object. Returns this object if successful,
1857 // undefined if called on a detached proxy.
1858 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1860 Handle<Object> value);
1861 // Gets the value of a hidden property with the given key. Returns the hole
1862 // if the property doesn't exist (or if called on a detached proxy),
1863 // otherwise returns the value set for the key.
1864 Object* GetHiddenProperty(Handle<Name> key);
1865 // Deletes a hidden property. Deleting a non-existing property is
1866 // considered successful.
1867 static void DeleteHiddenProperty(Handle<JSObject> object,
1869 // Returns true if the object has a property with the hidden string as name.
1870 static bool HasHiddenProperties(Handle<JSObject> object);
1872 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1874 static inline void ValidateElements(Handle<JSObject> object);
1876 // Makes sure that this object can contain HeapObject as elements.
1877 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1879 // Makes sure that this object can contain the specified elements.
1880 static inline void EnsureCanContainElements(
1881 Handle<JSObject> object,
1884 EnsureElementsMode mode);
1885 static inline void EnsureCanContainElements(
1886 Handle<JSObject> object,
1887 Handle<FixedArrayBase> elements,
1889 EnsureElementsMode mode);
1890 static void EnsureCanContainElements(
1891 Handle<JSObject> object,
1892 Arguments* arguments,
1895 EnsureElementsMode mode);
1897 // Would we convert a fast elements array to dictionary mode given
1898 // an access at key?
1899 bool WouldConvertToSlowElements(Handle<Object> key);
1900 // Do we want to keep the elements in fast case when increasing the
1902 bool ShouldConvertToSlowElements(int new_capacity);
1903 // Returns true if the backing storage for the slow-case elements of
1904 // this object takes up nearly as much space as a fast-case backing
1905 // storage would. In that case the JSObject should have fast
1907 bool ShouldConvertToFastElements();
1908 // Returns true if the elements of JSObject contains only values that can be
1909 // represented in a FixedDoubleArray and has at least one value that can only
1910 // be represented as a double and not a Smi.
1911 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
1913 // Computes the new capacity when expanding the elements of a JSObject.
1914 static int NewElementsCapacity(int old_capacity) {
1915 // (old_capacity + 50%) + 16
1916 return old_capacity + (old_capacity >> 1) + 16;
1919 // These methods do not perform access checks!
1920 MUST_USE_RESULT static MaybeHandle<AccessorPair> GetOwnElementAccessorPair(
1921 Handle<JSObject> object,
1924 MUST_USE_RESULT static MaybeHandle<Object> SetFastElement(
1925 Handle<JSObject> object,
1927 Handle<Object> value,
1928 StrictMode strict_mode,
1929 bool check_prototype);
1931 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElement(
1932 Handle<JSObject> object,
1934 Handle<Object> value,
1935 StrictMode strict_mode);
1937 // Empty handle is returned if the element cannot be set to the given value.
1938 MUST_USE_RESULT static MaybeHandle<Object> SetElement(
1939 Handle<JSObject> object,
1941 Handle<Object> value,
1942 PropertyAttributes attributes,
1943 StrictMode strict_mode,
1944 bool check_prototype = true,
1945 SetPropertyMode set_mode = SET_PROPERTY);
1947 // Returns the index'th element.
1948 // The undefined object if index is out of bounds.
1949 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithInterceptor(
1950 Handle<JSObject> object,
1951 Handle<Object> receiver,
1954 enum SetFastElementsCapacitySmiMode {
1957 kDontAllowSmiElements
1960 // Replace the elements' backing store with fast elements of the given
1961 // capacity. Update the length for JSArrays. Returns the new backing
1963 static Handle<FixedArray> SetFastElementsCapacityAndLength(
1964 Handle<JSObject> object,
1967 SetFastElementsCapacitySmiMode smi_mode);
1968 static void SetFastDoubleElementsCapacityAndLength(
1969 Handle<JSObject> object,
1973 // Lookup interceptors are used for handling properties controlled by host
1975 inline bool HasNamedInterceptor();
1976 inline bool HasIndexedInterceptor();
1978 // Computes the enumerable keys from interceptors. Used for debug mirrors and
1979 // by JSReceiver::GetKeys.
1980 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
1981 Handle<JSObject> object,
1982 Handle<JSReceiver> receiver);
1983 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
1984 Handle<JSObject> object,
1985 Handle<JSReceiver> receiver);
1987 // Support functions for v8 api (needed for correct interceptor behavior).
1988 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
1989 Handle<JSObject> object, Handle<Name> key);
1990 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
1991 Handle<JSObject> object, uint32_t index);
1992 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
1993 Handle<JSObject> object, Handle<Name> key);
1995 // Get the header size for a JSObject. Used to compute the index of
1996 // internal fields as well as the number of internal fields.
1997 inline int GetHeaderSize();
1999 inline int GetInternalFieldCount();
2000 inline int GetInternalFieldOffset(int index);
2001 inline Object* GetInternalField(int index);
2002 inline void SetInternalField(int index, Object* value);
2003 inline void SetInternalField(int index, Smi* value);
2005 // Returns the number of properties on this object filtering out properties
2006 // with the specified attributes (ignoring interceptors).
2007 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2008 // Fill in details for properties into storage starting at the specified
2010 void GetOwnPropertyNames(
2011 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2013 // Returns the number of properties on this object filtering out properties
2014 // with the specified attributes (ignoring interceptors).
2015 int NumberOfOwnElements(PropertyAttributes filter);
2016 // Returns the number of enumerable elements (ignoring interceptors).
2017 int NumberOfEnumElements();
2018 // Returns the number of elements on this object filtering out elements
2019 // with the specified attributes (ignoring interceptors).
2020 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2021 // Count and fill in the enumerable elements into storage.
2022 // (storage->length() == NumberOfEnumElements()).
2023 // If storage is NULL, will count the elements without adding
2024 // them to any storage.
2025 // Returns the number of enumerable elements.
2026 int GetEnumElementKeys(FixedArray* storage);
2028 // Returns a new map with all transitions dropped from the object's current
2029 // map and the ElementsKind set.
2030 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2031 ElementsKind to_kind);
2032 static void TransitionElementsKind(Handle<JSObject> object,
2033 ElementsKind to_kind);
2035 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map);
2037 // Convert the object to use the canonical dictionary
2038 // representation. If the object is expected to have additional properties
2039 // added this number can be indicated to have the backing store allocated to
2040 // an initial capacity for holding these properties.
2041 static void NormalizeProperties(Handle<JSObject> object,
2042 PropertyNormalizationMode mode,
2043 int expected_additional_properties);
2045 // Convert and update the elements backing store to be a
2046 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2047 static Handle<SeededNumberDictionary> NormalizeElements(
2048 Handle<JSObject> object);
2050 // Transform slow named properties to fast variants.
2051 static void MigrateSlowToFast(Handle<JSObject> object,
2052 int unused_property_fields);
2054 // Access fast-case object properties at index.
2055 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2056 Representation representation,
2058 inline Object* RawFastPropertyAt(FieldIndex index);
2059 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2060 void WriteToField(int descriptor, Object* value);
2062 // Access to in object properties.
2063 inline int GetInObjectPropertyOffset(int index);
2064 inline Object* InObjectPropertyAt(int index);
2065 inline Object* InObjectPropertyAtPut(int index,
2067 WriteBarrierMode mode
2068 = UPDATE_WRITE_BARRIER);
2070 // Set the object's prototype (only JSReceiver and null are allowed values).
2071 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2072 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2074 // Initializes the body after properties slot, properties slot is
2075 // initialized by set_properties. Fill the pre-allocated fields with
2076 // pre_allocated_value and the rest with filler_value.
2077 // Note: this call does not update write barrier, the caller is responsible
2078 // to ensure that |filler_value| can be collected without WB here.
2079 inline void InitializeBody(Map* map,
2080 Object* pre_allocated_value,
2081 Object* filler_value);
2083 // Check whether this object references another object
2084 bool ReferencesObject(Object* obj);
2086 // Disalow further properties to be added to the object.
2087 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2088 Handle<JSObject> object);
2090 // ES5 Object.freeze
2091 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2093 // Called the first time an object is observed with ES7 Object.observe.
2094 static void SetObserved(Handle<JSObject> object);
2097 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2099 static Handle<JSObject> Copy(Handle<JSObject> object);
2100 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2101 Handle<JSObject> object,
2102 AllocationSiteUsageContext* site_context,
2103 DeepCopyHints hints = kNoHints);
2104 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2105 Handle<JSObject> object,
2106 AllocationSiteCreationContext* site_context);
2108 static Handle<Object> GetDataProperty(Handle<JSObject> object,
2110 static Handle<Object> GetDataProperty(LookupIterator* it);
2112 DECLARE_CAST(JSObject)
2114 // Dispatched behavior.
2115 void JSObjectShortPrint(StringStream* accumulator);
2116 DECLARE_PRINTER(JSObject)
2117 DECLARE_VERIFIER(JSObject)
2119 void PrintProperties(std::ostream& os); // NOLINT
2120 void PrintElements(std::ostream& os); // NOLINT
2121 void PrintTransitions(std::ostream& os); // NOLINT
2124 static void PrintElementsTransition(
2125 FILE* file, Handle<JSObject> object,
2126 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2127 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2129 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2132 // Structure for collecting spill information about JSObjects.
2133 class SpillInformation {
2137 int number_of_objects_;
2138 int number_of_objects_with_fast_properties_;
2139 int number_of_objects_with_fast_elements_;
2140 int number_of_fast_used_fields_;
2141 int number_of_fast_unused_fields_;
2142 int number_of_slow_used_properties_;
2143 int number_of_slow_unused_properties_;
2144 int number_of_fast_used_elements_;
2145 int number_of_fast_unused_elements_;
2146 int number_of_slow_used_elements_;
2147 int number_of_slow_unused_elements_;
2150 void IncrementSpillStatistics(SpillInformation* info);
2154 // If a GC was caused while constructing this object, the elements pointer
2155 // may point to a one pointer filler map. The object won't be rooted, but
2156 // our heap verification code could stumble across it.
2157 bool ElementsAreSafeToExamine();
2160 Object* SlowReverseLookup(Object* value);
2162 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2163 // Also maximal value of JSArray's length property.
2164 static const uint32_t kMaxElementCount = 0xffffffffu;
2166 // Constants for heuristics controlling conversion of fast elements
2167 // to slow elements.
2169 // Maximal gap that can be introduced by adding an element beyond
2170 // the current elements length.
2171 static const uint32_t kMaxGap = 1024;
2173 // Maximal length of fast elements array that won't be checked for
2174 // being dense enough on expansion.
2175 static const int kMaxUncheckedFastElementsLength = 5000;
2177 // Same as above but for old arrays. This limit is more strict. We
2178 // don't want to be wasteful with long lived objects.
2179 static const int kMaxUncheckedOldFastElementsLength = 500;
2181 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2182 // permissible values (see the DCHECK in heap.cc).
2183 static const int kInitialMaxFastElementArray = 100000;
2185 // This constant applies only to the initial map of "$Object" aka
2186 // "global.Object" and not to arbitrary other JSObject maps.
2187 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2189 static const int kMaxInstanceSize = 255 * kPointerSize;
2190 // When extending the backing storage for property values, we increase
2191 // its size by more than the 1 entry necessary, so sequentially adding fields
2192 // to the same object requires fewer allocations and copies.
2193 static const int kFieldsAdded = 3;
2195 // Layout description.
2196 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2197 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2198 static const int kHeaderSize = kElementsOffset + kPointerSize;
2200 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2202 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2204 static inline int SizeOf(Map* map, HeapObject* object);
2207 Context* GetCreationContext();
2209 // Enqueue change record for Object.observe. May cause GC.
2210 static void EnqueueChangeRecord(Handle<JSObject> object,
2213 Handle<Object> old_value);
2216 friend class DictionaryElementsAccessor;
2217 friend class JSReceiver;
2218 friend class Object;
2220 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2221 static void MigrateFastToSlow(Handle<JSObject> object,
2222 Handle<Map> new_map,
2223 int expected_additional_properties);
2225 static void GeneralizeFieldRepresentation(Handle<JSObject> object,
2227 Representation new_representation,
2228 Handle<HeapType> new_field_type);
2230 static void UpdateAllocationSite(Handle<JSObject> object,
2231 ElementsKind to_kind);
2233 // Used from Object::GetProperty().
2234 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2235 LookupIterator* it);
2237 MUST_USE_RESULT static MaybeHandle<Object> GetElementWithCallback(
2238 Handle<JSObject> object,
2239 Handle<Object> receiver,
2240 Handle<Object> structure,
2242 Handle<Object> holder);
2244 MUST_USE_RESULT static Maybe<PropertyAttributes>
2245 GetElementAttributeWithInterceptor(Handle<JSObject> object,
2246 Handle<JSReceiver> receiver,
2247 uint32_t index, bool continue_search);
2248 MUST_USE_RESULT static Maybe<PropertyAttributes>
2249 GetElementAttributeWithoutInterceptor(Handle<JSObject> object,
2250 Handle<JSReceiver> receiver,
2252 bool continue_search);
2253 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithCallback(
2254 Handle<JSObject> object,
2255 Handle<Object> structure,
2257 Handle<Object> value,
2258 Handle<JSObject> holder,
2259 StrictMode strict_mode);
2260 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithInterceptor(
2261 Handle<JSObject> object,
2263 Handle<Object> value,
2264 PropertyAttributes attributes,
2265 StrictMode strict_mode,
2266 bool check_prototype,
2267 SetPropertyMode set_mode);
2268 MUST_USE_RESULT static MaybeHandle<Object> SetElementWithoutInterceptor(
2269 Handle<JSObject> object,
2271 Handle<Object> value,
2272 PropertyAttributes attributes,
2273 StrictMode strict_mode,
2274 bool check_prototype,
2275 SetPropertyMode set_mode);
2277 static MaybeHandle<Object> SetElementWithCallbackSetterInPrototypes(
2278 Handle<JSObject> object,
2280 Handle<Object> value,
2282 StrictMode strict_mode);
2283 MUST_USE_RESULT static MaybeHandle<Object> SetDictionaryElement(
2284 Handle<JSObject> object,
2286 Handle<Object> value,
2287 PropertyAttributes attributes,
2288 StrictMode strict_mode,
2289 bool check_prototype,
2290 SetPropertyMode set_mode = SET_PROPERTY);
2291 MUST_USE_RESULT static MaybeHandle<Object> SetFastDoubleElement(
2292 Handle<JSObject> object,
2294 Handle<Object> value,
2295 StrictMode strict_mode,
2296 bool check_prototype = true);
2298 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2299 LookupIterator* it, Handle<Object> value, StrictMode strict_mode);
2301 // Add a property to a slow-case object.
2302 static void AddSlowProperty(Handle<JSObject> object,
2304 Handle<Object> value,
2305 PropertyAttributes attributes);
2307 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
2308 Handle<JSObject> object,
2311 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2312 Handle<JSObject> holder, Handle<JSObject> receiver, Handle<Name> name);
2314 // Deletes the named property in a normalized object.
2315 static Handle<Object> DeleteNormalizedProperty(Handle<JSObject> object,
2319 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
2320 Handle<JSObject> object,
2323 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithInterceptor(
2324 Handle<JSObject> object,
2327 bool ReferencesObjectFromElements(FixedArray* elements,
2331 // Returns true if most of the elements backing storage is used.
2332 bool HasDenseElements();
2334 // Gets the current elements capacity and the number of used elements.
2335 void GetElementsCapacityAndUsage(int* capacity, int* used);
2337 static bool CanSetCallback(Handle<JSObject> object, Handle<Name> name);
2338 static void SetElementCallback(Handle<JSObject> object,
2340 Handle<Object> structure,
2341 PropertyAttributes attributes);
2342 static void SetPropertyCallback(Handle<JSObject> object,
2344 Handle<Object> structure,
2345 PropertyAttributes attributes);
2346 static void DefineElementAccessor(Handle<JSObject> object,
2348 Handle<Object> getter,
2349 Handle<Object> setter,
2350 PropertyAttributes attributes);
2352 // Return the hash table backing store or the inline stored identity hash,
2353 // whatever is found.
2354 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2356 // Return the hash table backing store for hidden properties. If there is no
2357 // backing store, allocate one.
2358 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2359 Handle<JSObject> object);
2361 // Set the hidden property backing store to either a hash table or
2362 // the inline-stored identity hash.
2363 static Handle<Object> SetHiddenPropertiesHashTable(
2364 Handle<JSObject> object,
2365 Handle<Object> value);
2367 MUST_USE_RESULT Object* GetIdentityHash();
2369 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2371 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2375 // Common superclass for FixedArrays that allow implementations to share
2376 // common accessors and some code paths.
2377 class FixedArrayBase: public HeapObject {
2379 // [length]: length of the array.
2380 inline int length() const;
2381 inline void set_length(int value);
2383 // Get and set the length using acquire loads and release stores.
2384 inline int synchronized_length() const;
2385 inline void synchronized_set_length(int value);
2387 DECLARE_CAST(FixedArrayBase)
2389 // Layout description.
2390 // Length is smi tagged when it is stored.
2391 static const int kLengthOffset = HeapObject::kHeaderSize;
2392 static const int kHeaderSize = kLengthOffset + kPointerSize;
2396 class FixedDoubleArray;
2397 class IncrementalMarking;
2400 // FixedArray describes fixed-sized arrays with element type Object*.
2401 class FixedArray: public FixedArrayBase {
2403 // Setter and getter for elements.
2404 inline Object* get(int index);
2405 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2406 // Setter that uses write barrier.
2407 inline void set(int index, Object* value);
2408 inline bool is_the_hole(int index);
2410 // Setter that doesn't need write barrier.
2411 inline void set(int index, Smi* value);
2412 // Setter with explicit barrier mode.
2413 inline void set(int index, Object* value, WriteBarrierMode mode);
2415 // Setters for frequently used oddballs located in old space.
2416 inline void set_undefined(int index);
2417 inline void set_null(int index);
2418 inline void set_the_hole(int index);
2420 inline Object** GetFirstElementAddress();
2421 inline bool ContainsOnlySmisOrHoles();
2423 // Gives access to raw memory which stores the array's data.
2424 inline Object** data_start();
2426 inline void FillWithHoles(int from, int to);
2428 // Shrink length and insert filler objects.
2429 void Shrink(int length);
2432 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2434 PretenureFlag pretenure = NOT_TENURED);
2436 // Add the elements of a JSArray to this FixedArray.
2437 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2438 Handle<FixedArray> content,
2439 Handle<JSObject> array);
2441 // Computes the union of keys and return the result.
2442 // Used for implementing "for (n in object) { }"
2443 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2444 Handle<FixedArray> first,
2445 Handle<FixedArray> second);
2447 // Copy a sub array from the receiver to dest.
2448 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2450 // Garbage collection support.
2451 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2453 // Code Generation support.
2454 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2456 // Garbage collection support.
2457 Object** RawFieldOfElementAt(int index) {
2458 return HeapObject::RawField(this, OffsetOfElementAt(index));
2461 DECLARE_CAST(FixedArray)
2463 // Maximal allowed size, in bytes, of a single FixedArray.
2464 // Prevents overflowing size computations, as well as extreme memory
2466 static const int kMaxSize = 128 * MB * kPointerSize;
2467 // Maximally allowed length of a FixedArray.
2468 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2470 // Dispatched behavior.
2471 DECLARE_PRINTER(FixedArray)
2472 DECLARE_VERIFIER(FixedArray)
2474 // Checks if two FixedArrays have identical contents.
2475 bool IsEqualTo(FixedArray* other);
2478 // Swap two elements in a pair of arrays. If this array and the
2479 // numbers array are the same object, the elements are only swapped
2481 void SwapPairs(FixedArray* numbers, int i, int j);
2483 // Sort prefix of this array and the numbers array as pairs wrt. the
2484 // numbers. If the numbers array and the this array are the same
2485 // object, the prefix of this array is sorted.
2486 void SortPairs(FixedArray* numbers, uint32_t len);
2488 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2490 static inline int SizeOf(Map* map, HeapObject* object) {
2491 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2496 // Set operation on FixedArray without using write barriers. Can
2497 // only be used for storing old space objects or smis.
2498 static inline void NoWriteBarrierSet(FixedArray* array,
2502 // Set operation on FixedArray without incremental write barrier. Can
2503 // only be used if the object is guaranteed to be white (whiteness witness
2505 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2510 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2512 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2516 // FixedDoubleArray describes fixed-sized arrays with element type double.
2517 class FixedDoubleArray: public FixedArrayBase {
2519 // Setter and getter for elements.
2520 inline double get_scalar(int index);
2521 inline int64_t get_representation(int index);
2522 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2523 inline void set(int index, double value);
2524 inline void set_the_hole(int index);
2526 // Checking for the hole.
2527 inline bool is_the_hole(int index);
2529 // Garbage collection support.
2530 inline static int SizeFor(int length) {
2531 return kHeaderSize + length * kDoubleSize;
2534 // Gives access to raw memory which stores the array's data.
2535 inline double* data_start();
2537 inline void FillWithHoles(int from, int to);
2539 // Code Generation support.
2540 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2542 inline static bool is_the_hole_nan(double value);
2543 inline static double hole_nan_as_double();
2544 inline static double canonical_not_the_hole_nan_as_double();
2546 DECLARE_CAST(FixedDoubleArray)
2548 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2549 // Prevents overflowing size computations, as well as extreme memory
2551 static const int kMaxSize = 512 * MB;
2552 // Maximally allowed length of a FixedArray.
2553 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2555 // Dispatched behavior.
2556 DECLARE_PRINTER(FixedDoubleArray)
2557 DECLARE_VERIFIER(FixedDoubleArray)
2560 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2564 // ConstantPoolArray describes a fixed-sized array containing constant pool
2567 // A ConstantPoolArray can be structured in two different ways depending upon
2568 // whether it is extended or small. The is_extended_layout() method can be used
2569 // to discover which layout the constant pool has.
2571 // The format of a small constant pool is:
2572 // [kSmallLayout1Offset] : Small section layout bitmap 1
2573 // [kSmallLayout2Offset] : Small section layout bitmap 2
2574 // [first_index(INT64, SMALL_SECTION)] : 64 bit entries
2576 // [first_index(CODE_PTR, SMALL_SECTION)] : code pointer entries
2578 // [first_index(HEAP_PTR, SMALL_SECTION)] : heap pointer entries
2580 // [first_index(INT32, SMALL_SECTION)] : 32 bit entries
2583 // If the constant pool has an extended layout, the extended section constant
2584 // pool also contains an extended section, which has the following format at
2585 // location get_extended_section_header_offset():
2586 // [kExtendedInt64CountOffset] : count of extended 64 bit entries
2587 // [kExtendedCodePtrCountOffset] : count of extended code pointers
2588 // [kExtendedHeapPtrCountOffset] : count of extended heap pointers
2589 // [kExtendedInt32CountOffset] : count of extended 32 bit entries
2590 // [first_index(INT64, EXTENDED_SECTION)] : 64 bit entries
2592 // [first_index(CODE_PTR, EXTENDED_SECTION)]: code pointer entries
2594 // [first_index(HEAP_PTR, EXTENDED_SECTION)]: heap pointer entries
2596 // [first_index(INT32, EXTENDED_SECTION)] : 32 bit entries
2599 class ConstantPoolArray: public HeapObject {
2601 enum WeakObjectState {
2603 WEAK_OBJECTS_IN_OPTIMIZED_CODE,
2612 // Number of types stored by the ConstantPoolArrays.
2618 enum LayoutSection {
2621 NUMBER_OF_LAYOUT_SECTIONS
2624 class NumberOfEntries BASE_EMBEDDED {
2626 inline NumberOfEntries() {
2627 for (int i = 0; i < NUMBER_OF_TYPES; i++) {
2628 element_counts_[i] = 0;
2632 inline NumberOfEntries(int int64_count, int code_ptr_count,
2633 int heap_ptr_count, int int32_count) {
2634 element_counts_[INT64] = int64_count;
2635 element_counts_[CODE_PTR] = code_ptr_count;
2636 element_counts_[HEAP_PTR] = heap_ptr_count;
2637 element_counts_[INT32] = int32_count;
2640 inline NumberOfEntries(ConstantPoolArray* array, LayoutSection section) {
2641 element_counts_[INT64] = array->number_of_entries(INT64, section);
2642 element_counts_[CODE_PTR] = array->number_of_entries(CODE_PTR, section);
2643 element_counts_[HEAP_PTR] = array->number_of_entries(HEAP_PTR, section);
2644 element_counts_[INT32] = array->number_of_entries(INT32, section);
2647 inline void increment(Type type);
2648 inline int equals(const NumberOfEntries& other) const;
2649 inline bool is_empty() const;
2650 inline int count_of(Type type) const;
2651 inline int base_of(Type type) const;
2652 inline int total_count() const;
2653 inline int are_in_range(int min, int max) const;
2656 int element_counts_[NUMBER_OF_TYPES];
2659 class Iterator BASE_EMBEDDED {
2661 inline Iterator(ConstantPoolArray* array, Type type)
2664 final_section_(array->final_section()),
2665 current_section_(SMALL_SECTION),
2666 next_index_(array->first_index(type, SMALL_SECTION)) {
2670 inline Iterator(ConstantPoolArray* array, Type type, LayoutSection section)
2673 final_section_(section),
2674 current_section_(section),
2675 next_index_(array->first_index(type, section)) {
2679 inline int next_index();
2680 inline bool is_finished();
2683 inline void update_section();
2684 ConstantPoolArray* array_;
2686 const LayoutSection final_section_;
2688 LayoutSection current_section_;
2692 // Getters for the first index, the last index and the count of entries of
2693 // a given type for a given layout section.
2694 inline int first_index(Type type, LayoutSection layout_section);
2695 inline int last_index(Type type, LayoutSection layout_section);
2696 inline int number_of_entries(Type type, LayoutSection layout_section);
2698 // Returns the type of the entry at the given index.
2699 inline Type get_type(int index);
2700 inline bool offset_is_type(int offset, Type type);
2702 // Setter and getter for pool elements.
2703 inline Address get_code_ptr_entry(int index);
2704 inline Object* get_heap_ptr_entry(int index);
2705 inline int64_t get_int64_entry(int index);
2706 inline int32_t get_int32_entry(int index);
2707 inline double get_int64_entry_as_double(int index);
2709 inline void set(int index, Address value);
2710 inline void set(int index, Object* value);
2711 inline void set(int index, int64_t value);
2712 inline void set(int index, double value);
2713 inline void set(int index, int32_t value);
2715 // Setters which take a raw offset rather than an index (for code generation).
2716 inline void set_at_offset(int offset, int32_t value);
2717 inline void set_at_offset(int offset, int64_t value);
2718 inline void set_at_offset(int offset, double value);
2719 inline void set_at_offset(int offset, Address value);
2720 inline void set_at_offset(int offset, Object* value);
2722 // Setter and getter for weak objects state
2723 inline void set_weak_object_state(WeakObjectState state);
2724 inline WeakObjectState get_weak_object_state();
2726 // Returns true if the constant pool has an extended layout, false if it has
2727 // only the small layout.
2728 inline bool is_extended_layout();
2730 // Returns the last LayoutSection in this constant pool array.
2731 inline LayoutSection final_section();
2733 // Set up initial state for a small layout constant pool array.
2734 inline void Init(const NumberOfEntries& small);
2736 // Set up initial state for an extended layout constant pool array.
2737 inline void InitExtended(const NumberOfEntries& small,
2738 const NumberOfEntries& extended);
2740 // Clears the pointer entries with GC safe values.
2741 void ClearPtrEntries(Isolate* isolate);
2743 // returns the total number of entries in the constant pool array.
2744 inline int length();
2746 // Garbage collection support.
2750 inline static int MaxInt64Offset(int number_of_int64) {
2751 return kFirstEntryOffset + (number_of_int64 * kInt64Size);
2754 inline static int SizeFor(const NumberOfEntries& small) {
2755 int size = kFirstEntryOffset +
2756 (small.count_of(INT64) * kInt64Size) +
2757 (small.count_of(CODE_PTR) * kPointerSize) +
2758 (small.count_of(HEAP_PTR) * kPointerSize) +
2759 (small.count_of(INT32) * kInt32Size);
2760 return RoundUp(size, kPointerSize);
2763 inline static int SizeForExtended(const NumberOfEntries& small,
2764 const NumberOfEntries& extended) {
2765 int size = SizeFor(small);
2766 size = RoundUp(size, kInt64Size); // Align extended header to 64 bits.
2767 size += kExtendedFirstOffset +
2768 (extended.count_of(INT64) * kInt64Size) +
2769 (extended.count_of(CODE_PTR) * kPointerSize) +
2770 (extended.count_of(HEAP_PTR) * kPointerSize) +
2771 (extended.count_of(INT32) * kInt32Size);
2772 return RoundUp(size, kPointerSize);
2775 inline static int entry_size(Type type) {
2783 return kPointerSize;
2790 // Code Generation support.
2791 inline int OffsetOfElementAt(int index) {
2793 LayoutSection section;
2794 if (is_extended_layout() && index >= first_extended_section_index()) {
2795 section = EXTENDED_SECTION;
2796 offset = get_extended_section_header_offset() + kExtendedFirstOffset;
2798 section = SMALL_SECTION;
2799 offset = kFirstEntryOffset;
2802 // Add offsets for the preceding type sections.
2803 DCHECK(index <= last_index(LAST_TYPE, section));
2804 for (Type type = FIRST_TYPE; index > last_index(type, section);
2805 type = next_type(type)) {
2806 offset += entry_size(type) * number_of_entries(type, section);
2809 // Add offset for the index in it's type.
2810 Type type = get_type(index);
2811 offset += entry_size(type) * (index - first_index(type, section));
2815 DECLARE_CAST(ConstantPoolArray)
2817 // Garbage collection support.
2818 Object** RawFieldOfElementAt(int index) {
2819 return HeapObject::RawField(this, OffsetOfElementAt(index));
2822 // Small Layout description.
2823 static const int kSmallLayout1Offset = HeapObject::kHeaderSize;
2824 static const int kSmallLayout2Offset = kSmallLayout1Offset + kInt32Size;
2825 static const int kHeaderSize = kSmallLayout2Offset + kInt32Size;
2826 static const int kFirstEntryOffset = ROUND_UP(kHeaderSize, kInt64Size);
2828 static const int kSmallLayoutCountBits = 10;
2829 static const int kMaxSmallEntriesPerType = (1 << kSmallLayoutCountBits) - 1;
2831 // Fields in kSmallLayout1Offset.
2832 class Int64CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2833 class CodePtrCountField: public BitField<int, 11, kSmallLayoutCountBits> {};
2834 class HeapPtrCountField: public BitField<int, 21, kSmallLayoutCountBits> {};
2835 class IsExtendedField: public BitField<bool, 31, 1> {};
2837 // Fields in kSmallLayout2Offset.
2838 class Int32CountField: public BitField<int, 1, kSmallLayoutCountBits> {};
2839 class TotalCountField: public BitField<int, 11, 12> {};
2840 class WeakObjectStateField: public BitField<WeakObjectState, 23, 2> {};
2842 // Extended layout description, which starts at
2843 // get_extended_section_header_offset().
2844 static const int kExtendedInt64CountOffset = 0;
2845 static const int kExtendedCodePtrCountOffset =
2846 kExtendedInt64CountOffset + kInt32Size;
2847 static const int kExtendedHeapPtrCountOffset =
2848 kExtendedCodePtrCountOffset + kInt32Size;
2849 static const int kExtendedInt32CountOffset =
2850 kExtendedHeapPtrCountOffset + kInt32Size;
2851 static const int kExtendedFirstOffset =
2852 kExtendedInt32CountOffset + kInt32Size;
2854 // Dispatched behavior.
2855 void ConstantPoolIterateBody(ObjectVisitor* v);
2857 DECLARE_PRINTER(ConstantPoolArray)
2858 DECLARE_VERIFIER(ConstantPoolArray)
2861 inline int first_extended_section_index();
2862 inline int get_extended_section_header_offset();
2864 inline static Type next_type(Type type) {
2865 DCHECK(type >= FIRST_TYPE && type < NUMBER_OF_TYPES);
2866 int type_int = static_cast<int>(type);
2867 return static_cast<Type>(++type_int);
2870 DISALLOW_IMPLICIT_CONSTRUCTORS(ConstantPoolArray);
2874 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2875 // The format of the these objects is:
2876 // [0]: Number of descriptors
2877 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2878 // [0]: pointer to fixed array with enum cache
2879 // [1]: either Smi(0) or pointer to fixed array with indices
2881 // [2 + number of descriptors * kDescriptorSize]: start of slack
2882 class DescriptorArray: public FixedArray {
2884 // Returns true for both shared empty_descriptor_array and for smis, which the
2885 // map uses to encode additional bit fields when the descriptor array is not
2887 inline bool IsEmpty();
2889 // Returns the number of descriptors in the array.
2890 int number_of_descriptors() {
2891 DCHECK(length() >= kFirstIndex || IsEmpty());
2893 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2896 int number_of_descriptors_storage() {
2898 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2901 int NumberOfSlackDescriptors() {
2902 return number_of_descriptors_storage() - number_of_descriptors();
2905 inline void SetNumberOfDescriptors(int number_of_descriptors);
2906 inline int number_of_entries() { return number_of_descriptors(); }
2908 bool HasEnumCache() {
2909 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2912 void CopyEnumCacheFrom(DescriptorArray* array) {
2913 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2916 FixedArray* GetEnumCache() {
2917 DCHECK(HasEnumCache());
2918 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2919 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2922 bool HasEnumIndicesCache() {
2923 if (IsEmpty()) return false;
2924 Object* object = get(kEnumCacheIndex);
2925 if (object->IsSmi()) return false;
2926 FixedArray* bridge = FixedArray::cast(object);
2927 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2930 FixedArray* GetEnumIndicesCache() {
2931 DCHECK(HasEnumIndicesCache());
2932 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2933 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2936 Object** GetEnumCacheSlot() {
2937 DCHECK(HasEnumCache());
2938 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2942 void ClearEnumCache();
2944 // Initialize or change the enum cache,
2945 // using the supplied storage for the small "bridge".
2946 void SetEnumCache(FixedArray* bridge_storage,
2947 FixedArray* new_cache,
2948 Object* new_index_cache);
2950 bool CanHoldValue(int descriptor, Object* value);
2952 // Accessors for fetching instance descriptor at descriptor number.
2953 inline Name* GetKey(int descriptor_number);
2954 inline Object** GetKeySlot(int descriptor_number);
2955 inline Object* GetValue(int descriptor_number);
2956 inline void SetValue(int descriptor_number, Object* value);
2957 inline Object** GetValueSlot(int descriptor_number);
2958 static inline int GetValueOffset(int descriptor_number);
2959 inline Object** GetDescriptorStartSlot(int descriptor_number);
2960 inline Object** GetDescriptorEndSlot(int descriptor_number);
2961 inline PropertyDetails GetDetails(int descriptor_number);
2962 inline PropertyType GetType(int descriptor_number);
2963 inline int GetFieldIndex(int descriptor_number);
2964 inline HeapType* GetFieldType(int descriptor_number);
2965 inline Object* GetConstant(int descriptor_number);
2966 inline Object* GetCallbacksObject(int descriptor_number);
2967 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2969 inline Name* GetSortedKey(int descriptor_number);
2970 inline int GetSortedKeyIndex(int descriptor_number);
2971 inline void SetSortedKey(int pointer, int descriptor_number);
2972 inline void SetRepresentation(int descriptor_number,
2973 Representation representation);
2975 // Accessor for complete descriptor.
2976 inline void Get(int descriptor_number, Descriptor* desc);
2977 inline void Set(int descriptor_number, Descriptor* desc);
2978 void Replace(int descriptor_number, Descriptor* descriptor);
2980 // Append automatically sets the enumeration index. This should only be used
2981 // to add descriptors in bulk at the end, followed by sorting the descriptor
2983 inline void Append(Descriptor* desc);
2985 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2986 int enumeration_index,
2989 static Handle<DescriptorArray> CopyUpToAddAttributes(
2990 Handle<DescriptorArray> desc,
2991 int enumeration_index,
2992 PropertyAttributes attributes,
2995 // Sort the instance descriptors by the hash codes of their keys.
2998 // Search the instance descriptors for given name.
2999 INLINE(int Search(Name* name, int number_of_own_descriptors));
3001 // As the above, but uses DescriptorLookupCache and updates it when
3003 INLINE(int SearchWithCache(Name* name, Map* map));
3005 // Allocates a DescriptorArray, but returns the singleton
3006 // empty descriptor array object if number_of_descriptors is 0.
3007 static Handle<DescriptorArray> Allocate(Isolate* isolate,
3008 int number_of_descriptors,
3011 DECLARE_CAST(DescriptorArray)
3013 // Constant for denoting key was not found.
3014 static const int kNotFound = -1;
3016 static const int kDescriptorLengthIndex = 0;
3017 static const int kEnumCacheIndex = 1;
3018 static const int kFirstIndex = 2;
3020 // The length of the "bridge" to the enum cache.
3021 static const int kEnumCacheBridgeLength = 2;
3022 static const int kEnumCacheBridgeCacheIndex = 0;
3023 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
3025 // Layout description.
3026 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
3027 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
3028 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
3030 // Layout description for the bridge array.
3031 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
3033 // Layout of descriptor.
3034 static const int kDescriptorKey = 0;
3035 static const int kDescriptorDetails = 1;
3036 static const int kDescriptorValue = 2;
3037 static const int kDescriptorSize = 3;
3040 // Print all the descriptors.
3041 void PrintDescriptors(std::ostream& os); // NOLINT
3045 // Is the descriptor array sorted and without duplicates?
3046 bool IsSortedNoDuplicates(int valid_descriptors = -1);
3048 // Is the descriptor array consistent with the back pointers in targets?
3049 bool IsConsistentWithBackPointers(Map* current_map);
3051 // Are two DescriptorArrays equal?
3052 bool IsEqualTo(DescriptorArray* other);
3055 // Returns the fixed array length required to hold number_of_descriptors
3057 static int LengthFor(int number_of_descriptors) {
3058 return ToKeyIndex(number_of_descriptors);
3062 // WhitenessWitness is used to prove that a descriptor array is white
3063 // (unmarked), so incremental write barriers can be skipped because the
3064 // marking invariant cannot be broken and slots pointing into evacuation
3065 // candidates will be discovered when the object is scanned. A witness is
3066 // always stack-allocated right after creating an array. By allocating a
3067 // witness, incremental marking is globally disabled. The witness is then
3068 // passed along wherever needed to statically prove that the array is known to
3070 class WhitenessWitness {
3072 inline explicit WhitenessWitness(DescriptorArray* array);
3073 inline ~WhitenessWitness();
3076 IncrementalMarking* marking_;
3079 // An entry in a DescriptorArray, represented as an (array, index) pair.
3082 inline explicit Entry(DescriptorArray* descs, int index) :
3083 descs_(descs), index_(index) { }
3085 inline PropertyType type() { return descs_->GetType(index_); }
3086 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
3089 DescriptorArray* descs_;
3093 // Conversion from descriptor number to array indices.
3094 static int ToKeyIndex(int descriptor_number) {
3095 return kFirstIndex +
3096 (descriptor_number * kDescriptorSize) +
3100 static int ToDetailsIndex(int descriptor_number) {
3101 return kFirstIndex +
3102 (descriptor_number * kDescriptorSize) +
3106 static int ToValueIndex(int descriptor_number) {
3107 return kFirstIndex +
3108 (descriptor_number * kDescriptorSize) +
3112 // Transfer a complete descriptor from the src descriptor array to this
3113 // descriptor array.
3114 void CopyFrom(int index,
3115 DescriptorArray* src,
3116 const WhitenessWitness&);
3118 inline void Set(int descriptor_number,
3120 const WhitenessWitness&);
3122 // Swap first and second descriptor.
3123 inline void SwapSortedKeys(int first, int second);
3125 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
3129 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
3131 template<SearchMode search_mode, typename T>
3132 inline int LinearSearch(T* array, Name* name, int len, int valid_entries);
3135 template<SearchMode search_mode, typename T>
3136 inline int Search(T* array, Name* name, int valid_entries = 0);
3139 // HashTable is a subclass of FixedArray that implements a hash table
3140 // that uses open addressing and quadratic probing.
3142 // In order for the quadratic probing to work, elements that have not
3143 // yet been used and elements that have been deleted are
3144 // distinguished. Probing continues when deleted elements are
3145 // encountered and stops when unused elements are encountered.
3147 // - Elements with key == undefined have not been used yet.
3148 // - Elements with key == the_hole have been deleted.
3150 // The hash table class is parameterized with a Shape and a Key.
3151 // Shape must be a class with the following interface:
3152 // class ExampleShape {
3154 // // Tells whether key matches other.
3155 // static bool IsMatch(Key key, Object* other);
3156 // // Returns the hash value for key.
3157 // static uint32_t Hash(Key key);
3158 // // Returns the hash value for object.
3159 // static uint32_t HashForObject(Key key, Object* object);
3160 // // Convert key to an object.
3161 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
3162 // // The prefix size indicates number of elements in the beginning
3163 // // of the backing storage.
3164 // static const int kPrefixSize = ..;
3165 // // The Element size indicates number of elements per entry.
3166 // static const int kEntrySize = ..;
3168 // The prefix size indicates an amount of memory in the
3169 // beginning of the backing storage that can be used for non-element
3170 // information by subclasses.
3172 template<typename Key>
3175 static const bool UsesSeed = false;
3176 static uint32_t Hash(Key key) { return 0; }
3177 static uint32_t SeededHash(Key key, uint32_t seed) {
3181 static uint32_t HashForObject(Key key, Object* object) { return 0; }
3182 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
3184 return HashForObject(key, object);
3188 template<typename Derived, typename Shape, typename Key>
3189 class HashTable: public FixedArray {
3192 inline uint32_t Hash(Key key) {
3193 if (Shape::UsesSeed) {
3194 return Shape::SeededHash(key, GetHeap()->HashSeed());
3196 return Shape::Hash(key);
3200 inline uint32_t HashForObject(Key key, Object* object) {
3201 if (Shape::UsesSeed) {
3202 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3204 return Shape::HashForObject(key, object);
3208 // Returns the number of elements in the hash table.
3209 int NumberOfElements() {
3210 return Smi::cast(get(kNumberOfElementsIndex))->value();
3213 // Returns the number of deleted elements in the hash table.
3214 int NumberOfDeletedElements() {
3215 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3218 // Returns the capacity of the hash table.
3220 return Smi::cast(get(kCapacityIndex))->value();
3223 // ElementAdded should be called whenever an element is added to a
3225 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
3227 // ElementRemoved should be called whenever an element is removed from
3229 void ElementRemoved() {
3230 SetNumberOfElements(NumberOfElements() - 1);
3231 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
3233 void ElementsRemoved(int n) {
3234 SetNumberOfElements(NumberOfElements() - n);
3235 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
3238 // Returns a new HashTable object.
3239 MUST_USE_RESULT static Handle<Derived> New(
3241 int at_least_space_for,
3242 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3243 PretenureFlag pretenure = NOT_TENURED);
3245 // Computes the required capacity for a table holding the given
3246 // number of elements. May be more than HashTable::kMaxCapacity.
3247 static int ComputeCapacity(int at_least_space_for);
3249 // Returns the key at entry.
3250 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3252 // Tells whether k is a real key. The hole and undefined are not allowed
3253 // as keys and can be used to indicate missing or deleted elements.
3254 bool IsKey(Object* k) {
3255 return !k->IsTheHole() && !k->IsUndefined();
3258 // Garbage collection support.
3259 void IteratePrefix(ObjectVisitor* visitor);
3260 void IterateElements(ObjectVisitor* visitor);
3262 DECLARE_CAST(HashTable)
3264 // Compute the probe offset (quadratic probing).
3265 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
3266 return (n + n * n) >> 1;
3269 static const int kNumberOfElementsIndex = 0;
3270 static const int kNumberOfDeletedElementsIndex = 1;
3271 static const int kCapacityIndex = 2;
3272 static const int kPrefixStartIndex = 3;
3273 static const int kElementsStartIndex =
3274 kPrefixStartIndex + Shape::kPrefixSize;
3275 static const int kEntrySize = Shape::kEntrySize;
3276 static const int kElementsStartOffset =
3277 kHeaderSize + kElementsStartIndex * kPointerSize;
3278 static const int kCapacityOffset =
3279 kHeaderSize + kCapacityIndex * kPointerSize;
3281 // Constant used for denoting a absent entry.
3282 static const int kNotFound = -1;
3284 // Maximal capacity of HashTable. Based on maximal length of underlying
3285 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3287 static const int kMaxCapacity =
3288 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3290 // Find entry for key otherwise return kNotFound.
3291 inline int FindEntry(Key key);
3292 int FindEntry(Isolate* isolate, Key key);
3294 // Rehashes the table in-place.
3295 void Rehash(Key key);
3298 friend class ObjectHashTable;
3300 // Find the entry at which to insert element with the given key that
3301 // has the given hash value.
3302 uint32_t FindInsertionEntry(uint32_t hash);
3304 // Returns the index for an entry (of the key)
3305 static inline int EntryToIndex(int entry) {
3306 return (entry * kEntrySize) + kElementsStartIndex;
3309 // Update the number of elements in the hash table.
3310 void SetNumberOfElements(int nof) {
3311 set(kNumberOfElementsIndex, Smi::FromInt(nof));
3314 // Update the number of deleted elements in the hash table.
3315 void SetNumberOfDeletedElements(int nod) {
3316 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3319 // Sets the capacity of the hash table.
3320 void SetCapacity(int capacity) {
3321 // To scale a computed hash code to fit within the hash table, we
3322 // use bit-wise AND with a mask, so the capacity must be positive
3324 DCHECK(capacity > 0);
3325 DCHECK(capacity <= kMaxCapacity);
3326 set(kCapacityIndex, Smi::FromInt(capacity));
3330 // Returns probe entry.
3331 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3332 DCHECK(base::bits::IsPowerOfTwo32(size));
3333 return (hash + GetProbeOffset(number)) & (size - 1);
3336 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3337 return hash & (size - 1);
3340 inline static uint32_t NextProbe(
3341 uint32_t last, uint32_t number, uint32_t size) {
3342 return (last + number) & (size - 1);
3345 // Attempt to shrink hash table after removal of key.
3346 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3348 // Ensure enough space for n additional elements.
3349 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3350 Handle<Derived> table,
3353 PretenureFlag pretenure = NOT_TENURED);
3356 // Returns _expected_ if one of entries given by the first _probe_ probes is
3357 // equal to _expected_. Otherwise, returns the entry given by the probe
3359 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3361 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3363 // Rehashes this hash-table into the new table.
3364 void Rehash(Handle<Derived> new_table, Key key);
3368 // HashTableKey is an abstract superclass for virtual key behavior.
3369 class HashTableKey {
3371 // Returns whether the other object matches this key.
3372 virtual bool IsMatch(Object* other) = 0;
3373 // Returns the hash value for this key.
3374 virtual uint32_t Hash() = 0;
3375 // Returns the hash value for object.
3376 virtual uint32_t HashForObject(Object* key) = 0;
3377 // Returns the key object for storing into the hash table.
3378 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3380 virtual ~HashTableKey() {}
3384 class StringTableShape : public BaseShape<HashTableKey*> {
3386 static inline bool IsMatch(HashTableKey* key, Object* value) {
3387 return key->IsMatch(value);
3390 static inline uint32_t Hash(HashTableKey* key) {
3394 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3395 return key->HashForObject(object);
3398 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3400 static const int kPrefixSize = 0;
3401 static const int kEntrySize = 1;
3404 class SeqOneByteString;
3408 // No special elements in the prefix and the element size is 1
3409 // because only the string itself (the key) needs to be stored.
3410 class StringTable: public HashTable<StringTable,
3414 // Find string in the string table. If it is not there yet, it is
3415 // added. The return value is the string found.
3416 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3417 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3419 // Tries to internalize given string and returns string handle on success
3420 // or an empty handle otherwise.
3421 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3423 Handle<String> string);
3425 // Looks up a string that is equal to the given string and returns
3426 // string handle if it is found, or an empty handle otherwise.
3427 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3429 Handle<String> str);
3430 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3435 DECLARE_CAST(StringTable)
3438 template <bool seq_one_byte>
3439 friend class JsonParser;
3441 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3445 class MapCacheShape : public BaseShape<HashTableKey*> {
3447 static inline bool IsMatch(HashTableKey* key, Object* value) {
3448 return key->IsMatch(value);
3451 static inline uint32_t Hash(HashTableKey* key) {
3455 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3456 return key->HashForObject(object);
3459 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3461 static const int kPrefixSize = 0;
3462 static const int kEntrySize = 2;
3468 // Maps keys that are a fixed array of unique names to a map.
3469 // Used for canonicalize maps for object literals.
3470 class MapCache: public HashTable<MapCache, MapCacheShape, HashTableKey*> {
3472 // Find cached value for a name key, otherwise return null.
3473 Object* Lookup(FixedArray* key);
3474 static Handle<MapCache> Put(
3475 Handle<MapCache> map_cache, Handle<FixedArray> key, Handle<Map> value);
3476 DECLARE_CAST(MapCache)
3479 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
3483 template <typename Derived, typename Shape, typename Key>
3484 class Dictionary: public HashTable<Derived, Shape, Key> {
3486 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3489 // Returns the value at entry.
3490 Object* ValueAt(int entry) {
3491 return this->get(DerivedHashTable::EntryToIndex(entry) + 1);
3494 // Set the value for entry.
3495 void ValueAtPut(int entry, Object* value) {
3496 this->set(DerivedHashTable::EntryToIndex(entry) + 1, value);
3499 // Returns the property details for the property at entry.
3500 PropertyDetails DetailsAt(int entry) {
3501 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3502 return PropertyDetails(
3503 Smi::cast(this->get(DerivedHashTable::EntryToIndex(entry) + 2)));
3506 // Set the details for entry.
3507 void DetailsAtPut(int entry, PropertyDetails value) {
3508 this->set(DerivedHashTable::EntryToIndex(entry) + 2, value.AsSmi());
3512 void CopyValuesTo(FixedArray* elements);
3514 // Delete a property from the dictionary.
3515 static Handle<Object> DeleteProperty(
3516 Handle<Derived> dictionary,
3518 JSObject::DeleteMode mode);
3520 // Attempt to shrink the dictionary after deletion of key.
3521 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3522 Handle<Derived> dictionary,
3524 return DerivedHashTable::Shrink(dictionary, key);
3527 // Returns the number of elements in the dictionary filtering out properties
3528 // with the specified attributes.
3529 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3531 // Returns the number of enumerable elements in the dictionary.
3532 int NumberOfEnumElements();
3534 enum SortMode { UNSORTED, SORTED };
3535 // Copies keys to preallocated fixed array.
3536 void CopyKeysTo(FixedArray* storage,
3537 PropertyAttributes filter,
3538 SortMode sort_mode);
3539 // Fill in details for properties into storage.
3540 void CopyKeysTo(FixedArray* storage,
3542 PropertyAttributes filter,
3543 SortMode sort_mode);
3545 // Accessors for next enumeration index.
3546 void SetNextEnumerationIndex(int index) {
3548 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3551 int NextEnumerationIndex() {
3552 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3555 // Creates a new dictionary.
3556 MUST_USE_RESULT static Handle<Derived> New(
3558 int at_least_space_for,
3559 PretenureFlag pretenure = NOT_TENURED);
3561 // Ensure enough space for n additional elements.
3562 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3565 void Print(std::ostream& os); // NOLINT
3567 // Returns the key (slow).
3568 Object* SlowReverseLookup(Object* value);
3570 // Sets the entry to (key, value) pair.
3571 inline void SetEntry(int entry,
3573 Handle<Object> value);
3574 inline void SetEntry(int entry,
3576 Handle<Object> value,
3577 PropertyDetails details);
3579 MUST_USE_RESULT static Handle<Derived> Add(
3580 Handle<Derived> dictionary,
3582 Handle<Object> value,
3583 PropertyDetails details);
3586 // Generic at put operation.
3587 MUST_USE_RESULT static Handle<Derived> AtPut(
3588 Handle<Derived> dictionary,
3590 Handle<Object> value);
3592 // Add entry to dictionary.
3593 static void AddEntry(
3594 Handle<Derived> dictionary,
3596 Handle<Object> value,
3597 PropertyDetails details,
3600 // Generate new enumeration indices to avoid enumeration index overflow.
3601 static void GenerateNewEnumerationIndices(Handle<Derived> dictionary);
3602 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3603 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3607 class NameDictionaryShape : public BaseShape<Handle<Name> > {
3609 static inline bool IsMatch(Handle<Name> key, Object* other);
3610 static inline uint32_t Hash(Handle<Name> key);
3611 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3612 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3613 static const int kPrefixSize = 2;
3614 static const int kEntrySize = 3;
3615 static const bool kIsEnumerable = true;
3619 class NameDictionary: public Dictionary<NameDictionary,
3620 NameDictionaryShape,
3623 NameDictionary, NameDictionaryShape, Handle<Name> > DerivedDictionary;
3626 DECLARE_CAST(NameDictionary)
3628 // Copies enumerable keys to preallocated fixed array.
3629 void CopyEnumKeysTo(FixedArray* storage);
3630 inline static void DoGenerateNewEnumerationIndices(
3631 Handle<NameDictionary> dictionary);
3633 // Find entry for key, otherwise return kNotFound. Optimized version of
3634 // HashTable::FindEntry.
3635 int FindEntry(Handle<Name> key);
3639 class NumberDictionaryShape : public BaseShape<uint32_t> {
3641 static inline bool IsMatch(uint32_t key, Object* other);
3642 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3643 static const int kEntrySize = 3;
3644 static const bool kIsEnumerable = false;
3648 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3650 static const bool UsesSeed = true;
3651 static const int kPrefixSize = 2;
3653 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3654 static inline uint32_t SeededHashForObject(uint32_t key,
3660 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3662 static const int kPrefixSize = 0;
3664 static inline uint32_t Hash(uint32_t key);
3665 static inline uint32_t HashForObject(uint32_t key, Object* object);
3669 class SeededNumberDictionary
3670 : public Dictionary<SeededNumberDictionary,
3671 SeededNumberDictionaryShape,
3674 DECLARE_CAST(SeededNumberDictionary)
3676 // Type specific at put (default NONE attributes is used when adding).
3677 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3678 Handle<SeededNumberDictionary> dictionary,
3680 Handle<Object> value);
3681 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3682 Handle<SeededNumberDictionary> dictionary,
3684 Handle<Object> value,
3685 PropertyDetails details);
3687 // Set an existing entry or add a new one if needed.
3688 // Return the updated dictionary.
3689 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3690 Handle<SeededNumberDictionary> dictionary,
3692 Handle<Object> value,
3693 PropertyDetails details);
3695 void UpdateMaxNumberKey(uint32_t key);
3697 // If slow elements are required we will never go back to fast-case
3698 // for the elements kept in this dictionary. We require slow
3699 // elements if an element has been added at an index larger than
3700 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3701 // when defining a getter or setter with a number key.
3702 inline bool requires_slow_elements();
3703 inline void set_requires_slow_elements();
3705 // Get the value of the max number key that has been added to this
3706 // dictionary. max_number_key can only be called if
3707 // requires_slow_elements returns false.
3708 inline uint32_t max_number_key();
3711 static const int kRequiresSlowElementsMask = 1;
3712 static const int kRequiresSlowElementsTagSize = 1;
3713 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3717 class UnseededNumberDictionary
3718 : public Dictionary<UnseededNumberDictionary,
3719 UnseededNumberDictionaryShape,
3722 DECLARE_CAST(UnseededNumberDictionary)
3724 // Type specific at put (default NONE attributes is used when adding).
3725 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3726 Handle<UnseededNumberDictionary> dictionary,
3728 Handle<Object> value);
3729 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3730 Handle<UnseededNumberDictionary> dictionary,
3732 Handle<Object> value);
3734 // Set an existing entry or add a new one if needed.
3735 // Return the updated dictionary.
3736 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3737 Handle<UnseededNumberDictionary> dictionary,
3739 Handle<Object> value);
3743 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3745 static inline bool IsMatch(Handle<Object> key, Object* other);
3746 static inline uint32_t Hash(Handle<Object> key);
3747 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3748 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3749 static const int kPrefixSize = 0;
3750 static const int kEntrySize = 2;
3754 // ObjectHashTable maps keys that are arbitrary objects to object values by
3755 // using the identity hash of the key for hashing purposes.
3756 class ObjectHashTable: public HashTable<ObjectHashTable,
3757 ObjectHashTableShape,
3760 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3762 DECLARE_CAST(ObjectHashTable)
3764 // Attempt to shrink hash table after removal of key.
3765 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3766 Handle<ObjectHashTable> table,
3767 Handle<Object> key);
3769 // Looks up the value associated with the given key. The hole value is
3770 // returned in case the key is not present.
3771 Object* Lookup(Handle<Object> key);
3773 // Adds (or overwrites) the value associated with the given key.
3774 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3776 Handle<Object> value);
3778 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3779 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3784 friend class MarkCompactCollector;
3786 void AddEntry(int entry, Object* key, Object* value);
3787 void RemoveEntry(int entry);
3789 // Returns the index to the value of an entry.
3790 static inline int EntryToValueIndex(int entry) {
3791 return EntryToIndex(entry) + 1;
3796 // OrderedHashTable is a HashTable with Object keys that preserves
3797 // insertion order. There are Map and Set interfaces (OrderedHashMap
3798 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3800 // Only Object* keys are supported, with Object::SameValueZero() used as the
3801 // equality operator and Object::GetHash() for the hash function.
3803 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3804 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3805 // Originally attributed to Tyler Close.
3808 // [0]: bucket count
3809 // [1]: element count
3810 // [2]: deleted element count
3811 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3812 // offset into the data table (see below) where the
3813 // first item in this bucket is stored.
3814 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3815 // Capacity() * kEntrySize, where the first entrysize
3816 // items are handled by the derived class and the
3817 // item at kChainOffset is another entry into the
3818 // data table indicating the next entry in this hash
3821 // When we transition the table to a new version we obsolete it and reuse parts
3822 // of the memory to store information how to transition an iterator to the new
3825 // Memory layout for obsolete table:
3826 // [0]: bucket count
3827 // [1]: Next newer table
3828 // [2]: Number of removed holes or -1 when the table was cleared.
3829 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3830 // [3 + NumberOfRemovedHoles()..length]: Not used
3832 template<class Derived, class Iterator, int entrysize>
3833 class OrderedHashTable: public FixedArray {
3835 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3836 static Handle<Derived> Allocate(
3837 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3839 // Returns an OrderedHashTable (possibly |table|) with enough space
3840 // to add at least one new element.
3841 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3843 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3845 static Handle<Derived> Shrink(Handle<Derived> table);
3847 // Returns a new empty OrderedHashTable and records the clearing so that
3848 // exisiting iterators can be updated.
3849 static Handle<Derived> Clear(Handle<Derived> table);
3851 // Returns an OrderedHashTable (possibly |table|) where |key| has been
3853 static Handle<Derived> Remove(Handle<Derived> table, Handle<Object> key,
3856 // Returns kNotFound if the key isn't present.
3857 int FindEntry(Handle<Object> key, int hash);
3859 // Like the above, but doesn't require the caller to provide a hash.
3860 int FindEntry(Handle<Object> key);
3862 int NumberOfElements() {
3863 return Smi::cast(get(kNumberOfElementsIndex))->value();
3866 int NumberOfDeletedElements() {
3867 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3870 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3872 int NumberOfBuckets() {
3873 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3876 // Returns the index into the data table where the new entry
3877 // should be placed. The table is assumed to have enough space
3879 int AddEntry(int hash);
3881 // Removes the entry, and puts the_hole in entrysize pointers
3882 // (leaving the hash table chain intact).
3883 void RemoveEntry(int entry);
3885 // Returns an index into |this| for the given entry.
3886 int EntryToIndex(int entry) {
3887 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3890 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3893 return !get(kNextTableIndex)->IsSmi();
3896 // The next newer table. This is only valid if the table is obsolete.
3897 Derived* NextTable() {
3898 return Derived::cast(get(kNextTableIndex));
3901 // When the table is obsolete we store the indexes of the removed holes.
3902 int RemovedIndexAt(int index) {
3903 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3906 static const int kNotFound = -1;
3907 static const int kMinCapacity = 4;
3910 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3912 void SetNumberOfBuckets(int num) {
3913 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3916 void SetNumberOfElements(int num) {
3917 set(kNumberOfElementsIndex, Smi::FromInt(num));
3920 void SetNumberOfDeletedElements(int num) {
3921 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3925 return NumberOfBuckets() * kLoadFactor;
3928 // Returns the next entry for the given entry.
3929 int ChainAt(int entry) {
3930 return Smi::cast(get(EntryToIndex(entry) + kChainOffset))->value();
3933 int HashToBucket(int hash) {
3934 return hash & (NumberOfBuckets() - 1);
3937 int HashToEntry(int hash) {
3938 int bucket = HashToBucket(hash);
3939 return Smi::cast(get(kHashTableStartIndex + bucket))->value();
3942 void SetNextTable(Derived* next_table) {
3943 set(kNextTableIndex, next_table);
3946 void SetRemovedIndexAt(int index, int removed_index) {
3947 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3950 static const int kNumberOfBucketsIndex = 0;
3951 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3952 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3953 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3955 static const int kNextTableIndex = kNumberOfElementsIndex;
3956 static const int kRemovedHolesIndex = kHashTableStartIndex;
3958 static const int kEntrySize = entrysize + 1;
3959 static const int kChainOffset = entrysize;
3961 static const int kLoadFactor = 2;
3962 static const int kMaxCapacity =
3963 (FixedArray::kMaxLength - kHashTableStartIndex)
3964 / (1 + (kEntrySize * kLoadFactor));
3968 class JSSetIterator;
3971 class OrderedHashSet: public OrderedHashTable<
3972 OrderedHashSet, JSSetIterator, 1> {
3974 DECLARE_CAST(OrderedHashSet)
3976 bool Contains(Handle<Object> key);
3977 static Handle<OrderedHashSet> Add(
3978 Handle<OrderedHashSet> table, Handle<Object> key);
3982 class JSMapIterator;
3985 class OrderedHashMap:public OrderedHashTable<
3986 OrderedHashMap, JSMapIterator, 2> {
3988 DECLARE_CAST(OrderedHashMap)
3990 Object* Lookup(Handle<Object> key);
3991 static Handle<OrderedHashMap> Put(
3992 Handle<OrderedHashMap> table,
3994 Handle<Object> value);
3996 Object* ValueAt(int entry) {
3997 return get(EntryToIndex(entry) + kValueOffset);
4001 static const int kValueOffset = 1;
4005 template <int entrysize>
4006 class WeakHashTableShape : public BaseShape<Handle<Object> > {
4008 static inline bool IsMatch(Handle<Object> key, Object* other);
4009 static inline uint32_t Hash(Handle<Object> key);
4010 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
4011 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
4012 static const int kPrefixSize = 0;
4013 static const int kEntrySize = entrysize;
4017 // WeakHashTable maps keys that are arbitrary objects to object values.
4018 // It is used for the global weak hash table that maps objects
4019 // embedded in optimized code to dependent code lists.
4020 class WeakHashTable: public HashTable<WeakHashTable,
4021 WeakHashTableShape<2>,
4024 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
4026 DECLARE_CAST(WeakHashTable)
4028 // Looks up the value associated with the given key. The hole value is
4029 // returned in case the key is not present.
4030 Object* Lookup(Handle<Object> key);
4032 // Adds (or overwrites) the value associated with the given key. Mapping a
4033 // key to the hole value causes removal of the whole entry.
4034 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
4036 Handle<Object> value);
4038 // This function is called when heap verification is turned on.
4039 void Zap(Object* value) {
4040 int capacity = Capacity();
4041 for (int i = 0; i < capacity; i++) {
4042 set(EntryToIndex(i), value);
4043 set(EntryToValueIndex(i), value);
4048 friend class MarkCompactCollector;
4050 void AddEntry(int entry, Handle<Object> key, Handle<Object> value);
4052 // Returns the index to the value of an entry.
4053 static inline int EntryToValueIndex(int entry) {
4054 return EntryToIndex(entry) + 1;
4059 // JSFunctionResultCache caches results of some JSFunction invocation.
4060 // It is a fixed array with fixed structure:
4061 // [0]: factory function
4062 // [1]: finger index
4063 // [2]: current cache size
4064 // [3]: dummy field.
4065 // The rest of array are key/value pairs.
4066 class JSFunctionResultCache: public FixedArray {
4068 static const int kFactoryIndex = 0;
4069 static const int kFingerIndex = kFactoryIndex + 1;
4070 static const int kCacheSizeIndex = kFingerIndex + 1;
4071 static const int kDummyIndex = kCacheSizeIndex + 1;
4072 static const int kEntriesIndex = kDummyIndex + 1;
4074 static const int kEntrySize = 2; // key + value
4076 static const int kFactoryOffset = kHeaderSize;
4077 static const int kFingerOffset = kFactoryOffset + kPointerSize;
4078 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
4080 inline void MakeZeroSize();
4081 inline void Clear();
4084 inline void set_size(int size);
4085 inline int finger_index();
4086 inline void set_finger_index(int finger_index);
4088 DECLARE_CAST(JSFunctionResultCache)
4090 DECLARE_VERIFIER(JSFunctionResultCache)
4094 // ScopeInfo represents information about different scopes of a source
4095 // program and the allocation of the scope's variables. Scope information
4096 // is stored in a compressed form in ScopeInfo objects and is used
4097 // at runtime (stack dumps, deoptimization, etc.).
4099 // This object provides quick access to scope info details for runtime
4101 class ScopeInfo : public FixedArray {
4103 DECLARE_CAST(ScopeInfo)
4105 // Return the type of this scope.
4106 ScopeType scope_type();
4108 // Does this scope call eval?
4111 // Return the strict mode of this scope.
4112 StrictMode strict_mode();
4114 // Does this scope make a sloppy eval call?
4115 bool CallsSloppyEval() { return CallsEval() && strict_mode() == SLOPPY; }
4117 // Return the total number of locals allocated on the stack and in the
4118 // context. This includes the parameters that are allocated in the context.
4121 // Return the number of stack slots for code. This number consists of two
4123 // 1. One stack slot per stack allocated local.
4124 // 2. One stack slot for the function name if it is stack allocated.
4125 int StackSlotCount();
4127 // Return the number of context slots for code if a context is allocated. This
4128 // number consists of three parts:
4129 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
4130 // 2. One context slot per context allocated local.
4131 // 3. One context slot for the function name if it is context allocated.
4132 // Parameters allocated in the context count as context allocated locals. If
4133 // no contexts are allocated for this scope ContextLength returns 0.
4134 int ContextLength();
4136 // Is this scope the scope of a named function expression?
4137 bool HasFunctionName();
4139 // Return if this has context allocated locals.
4140 bool HasHeapAllocatedLocals();
4142 // Return if contexts are allocated for this scope.
4145 // Return if this is a function scope with "use asm".
4146 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
4148 // Return if this is a nested function within an asm module scope.
4149 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
4151 // Return the function_name if present.
4152 String* FunctionName();
4154 // Return the name of the given parameter.
4155 String* ParameterName(int var);
4157 // Return the name of the given local.
4158 String* LocalName(int var);
4160 // Return the name of the given stack local.
4161 String* StackLocalName(int var);
4163 // Return the name of the given context local.
4164 String* ContextLocalName(int var);
4166 // Return the mode of the given context local.
4167 VariableMode ContextLocalMode(int var);
4169 // Return the initialization flag of the given context local.
4170 InitializationFlag ContextLocalInitFlag(int var);
4172 // Return the initialization flag of the given context local.
4173 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
4175 // Return true if this local was introduced by the compiler, and should not be
4176 // exposed to the user in a debugger.
4177 bool LocalIsSynthetic(int var);
4179 // Lookup support for serialized scope info. Returns the
4180 // the stack slot index for a given slot name if the slot is
4181 // present; otherwise returns a value < 0. The name must be an internalized
4183 int StackSlotIndex(String* name);
4185 // Lookup support for serialized scope info. Returns the
4186 // context slot index for a given slot name if the slot is present; otherwise
4187 // returns a value < 0. The name must be an internalized string.
4188 // If the slot is present and mode != NULL, sets *mode to the corresponding
4189 // mode for that variable.
4190 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
4191 VariableMode* mode, InitializationFlag* init_flag,
4192 MaybeAssignedFlag* maybe_assigned_flag);
4194 // Lookup support for serialized scope info. Returns the
4195 // parameter index for a given parameter name if the parameter is present;
4196 // otherwise returns a value < 0. The name must be an internalized string.
4197 int ParameterIndex(String* name);
4199 // Lookup support for serialized scope info. Returns the function context
4200 // slot index if the function name is present and context-allocated (named
4201 // function expressions, only), otherwise returns a value < 0. The name
4202 // must be an internalized string.
4203 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4206 // Copies all the context locals into an object used to materialize a scope.
4207 static bool CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4208 Handle<Context> context,
4209 Handle<JSObject> scope_object);
4212 static Handle<ScopeInfo> Create(Scope* scope, Zone* zone);
4214 // Serializes empty scope info.
4215 static ScopeInfo* Empty(Isolate* isolate);
4221 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4222 // numeric and occupies one array slot.
4223 // 1. A set of properties of the scope
4224 // 2. The number of parameters. This only applies to function scopes. For
4225 // non-function scopes this is 0.
4226 // 3. The number of non-parameter variables allocated on the stack.
4227 // 4. The number of non-parameter and parameter variables allocated in the
4229 #define FOR_EACH_NUMERIC_FIELD(V) \
4232 V(StackLocalCount) \
4233 V(ContextLocalCount)
4235 #define FIELD_ACCESSORS(name) \
4236 void Set##name(int value) { \
4237 set(k##name, Smi::FromInt(value)); \
4240 if (length() > 0) { \
4241 return Smi::cast(get(k##name))->value(); \
4246 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4247 #undef FIELD_ACCESSORS
4251 #define DECL_INDEX(name) k##name,
4252 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4254 #undef FOR_EACH_NUMERIC_FIELD
4258 // The layout of the variable part of a ScopeInfo is as follows:
4259 // 1. ParameterEntries:
4260 // This part stores the names of the parameters for function scopes. One
4261 // slot is used per parameter, so in total this part occupies
4262 // ParameterCount() slots in the array. For other scopes than function
4263 // scopes ParameterCount() is 0.
4264 // 2. StackLocalEntries:
4265 // Contains the names of local variables that are allocated on the stack,
4266 // in increasing order of the stack slot index. One slot is used per stack
4267 // local, so in total this part occupies StackLocalCount() slots in the
4269 // 3. ContextLocalNameEntries:
4270 // Contains the names of local variables and parameters that are allocated
4271 // in the context. They are stored in increasing order of the context slot
4272 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4273 // context local, so in total this part occupies ContextLocalCount() slots
4275 // 4. ContextLocalInfoEntries:
4276 // Contains the variable modes and initialization flags corresponding to
4277 // the context locals in ContextLocalNameEntries. One slot is used per
4278 // context local, so in total this part occupies ContextLocalCount()
4279 // slots in the array.
4280 // 5. FunctionNameEntryIndex:
4281 // If the scope belongs to a named function expression this part contains
4282 // information about the function variable. It always occupies two array
4283 // slots: a. The name of the function variable.
4284 // b. The context or stack slot index for the variable.
4285 int ParameterEntriesIndex();
4286 int StackLocalEntriesIndex();
4287 int ContextLocalNameEntriesIndex();
4288 int ContextLocalInfoEntriesIndex();
4289 int FunctionNameEntryIndex();
4291 // Location of the function variable for named function expressions.
4292 enum FunctionVariableInfo {
4293 NONE, // No function name present.
4299 // Properties of scopes.
4300 class ScopeTypeField: public BitField<ScopeType, 0, 3> {};
4301 class CallsEvalField: public BitField<bool, 3, 1> {};
4302 class StrictModeField: public BitField<StrictMode, 4, 1> {};
4303 class FunctionVariableField: public BitField<FunctionVariableInfo, 5, 2> {};
4304 class FunctionVariableMode: public BitField<VariableMode, 7, 3> {};
4305 class AsmModuleField : public BitField<bool, 10, 1> {};
4306 class AsmFunctionField : public BitField<bool, 11, 1> {};
4308 // BitFields representing the encoded information for context locals in the
4309 // ContextLocalInfoEntries part.
4310 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4311 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4312 class ContextLocalMaybeAssignedFlag
4313 : public BitField<MaybeAssignedFlag, 4, 1> {};
4317 // The cache for maps used by normalized (dictionary mode) objects.
4318 // Such maps do not have property descriptors, so a typical program
4319 // needs very limited number of distinct normalized maps.
4320 class NormalizedMapCache: public FixedArray {
4322 static Handle<NormalizedMapCache> New(Isolate* isolate);
4324 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4325 PropertyNormalizationMode mode);
4326 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4330 DECLARE_CAST(NormalizedMapCache)
4332 static inline bool IsNormalizedMapCache(const Object* obj);
4334 DECLARE_VERIFIER(NormalizedMapCache)
4336 static const int kEntries = 64;
4338 static inline int GetIndex(Handle<Map> map);
4340 // The following declarations hide base class methods.
4341 Object* get(int index);
4342 void set(int index, Object* value);
4346 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4347 // that is attached to code objects.
4348 class ByteArray: public FixedArrayBase {
4350 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4352 // Setter and getter.
4353 inline byte get(int index);
4354 inline void set(int index, byte value);
4356 // Treat contents as an int array.
4357 inline int get_int(int index);
4359 static int SizeFor(int length) {
4360 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4362 // We use byte arrays for free blocks in the heap. Given a desired size in
4363 // bytes that is a multiple of the word size and big enough to hold a byte
4364 // array, this function returns the number of elements a byte array should
4366 static int LengthFor(int size_in_bytes) {
4367 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4368 DCHECK(size_in_bytes >= kHeaderSize);
4369 return size_in_bytes - kHeaderSize;
4372 // Returns data start address.
4373 inline Address GetDataStartAddress();
4375 // Returns a pointer to the ByteArray object for a given data start address.
4376 static inline ByteArray* FromDataStartAddress(Address address);
4378 DECLARE_CAST(ByteArray)
4380 // Dispatched behavior.
4381 inline int ByteArraySize() {
4382 return SizeFor(this->length());
4384 DECLARE_PRINTER(ByteArray)
4385 DECLARE_VERIFIER(ByteArray)
4387 // Layout description.
4388 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4390 // Maximal memory consumption for a single ByteArray.
4391 static const int kMaxSize = 512 * MB;
4392 // Maximal length of a single ByteArray.
4393 static const int kMaxLength = kMaxSize - kHeaderSize;
4396 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4400 // FreeSpace represents fixed sized areas of the heap that are not currently in
4401 // use. Used by the heap and GC.
4402 class FreeSpace: public HeapObject {
4404 // [size]: size of the free space including the header.
4405 inline int size() const;
4406 inline void set_size(int value);
4408 inline int nobarrier_size() const;
4409 inline void nobarrier_set_size(int value);
4411 inline int Size() { return size(); }
4413 DECLARE_CAST(FreeSpace)
4415 // Dispatched behavior.
4416 DECLARE_PRINTER(FreeSpace)
4417 DECLARE_VERIFIER(FreeSpace)
4419 // Layout description.
4420 // Size is smi tagged when it is stored.
4421 static const int kSizeOffset = HeapObject::kHeaderSize;
4422 static const int kHeaderSize = kSizeOffset + kPointerSize;
4424 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4427 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4431 // V has parameters (Type, type, TYPE, C type, element_size)
4432 #define TYPED_ARRAYS(V) \
4433 V(Uint8, uint8, UINT8, uint8_t, 1) \
4434 V(Int8, int8, INT8, int8_t, 1) \
4435 V(Uint16, uint16, UINT16, uint16_t, 2) \
4436 V(Int16, int16, INT16, int16_t, 2) \
4437 V(Uint32, uint32, UINT32, uint32_t, 4) \
4438 V(Int32, int32, INT32, int32_t, 4) \
4439 V(Float32, float32, FLOAT32, float, 4) \
4440 V(Float64, float64, FLOAT64, double, 8) \
4441 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4445 // An ExternalArray represents a fixed-size array of primitive values
4446 // which live outside the JavaScript heap. Its subclasses are used to
4447 // implement the CanvasArray types being defined in the WebGL
4448 // specification. As of this writing the first public draft is not yet
4449 // available, but Khronos members can access the draft at:
4450 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4452 // The semantics of these arrays differ from CanvasPixelArray.
4453 // Out-of-range values passed to the setter are converted via a C
4454 // cast, not clamping. Out-of-range indices cause exceptions to be
4455 // raised rather than being silently ignored.
4456 class ExternalArray: public FixedArrayBase {
4458 inline bool is_the_hole(int index) { return false; }
4460 // [external_pointer]: The pointer to the external memory area backing this
4462 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4464 DECLARE_CAST(ExternalArray)
4466 // Maximal acceptable length for an external array.
4467 static const int kMaxLength = 0x3fffffff;
4469 // ExternalArray headers are not quadword aligned.
4470 static const int kExternalPointerOffset =
4471 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4472 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
4473 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4476 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4480 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4481 // semantics used for implementing the CanvasPixelArray object. Please see the
4482 // specification at:
4484 // http://www.whatwg.org/specs/web-apps/current-work/
4485 // multipage/the-canvas-element.html#canvaspixelarray
4486 // In particular, write access clamps the value written to 0 or 255 if the
4487 // value written is outside this range.
4488 class ExternalUint8ClampedArray: public ExternalArray {
4490 inline uint8_t* external_uint8_clamped_pointer();
4492 // Setter and getter.
4493 inline uint8_t get_scalar(int index);
4494 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4496 inline void set(int index, uint8_t value);
4498 // This accessor applies the correct conversion from Smi, HeapNumber
4499 // and undefined and clamps the converted value between 0 and 255.
4500 static Handle<Object> SetValue(Handle<ExternalUint8ClampedArray> array,
4502 Handle<Object> value);
4504 DECLARE_CAST(ExternalUint8ClampedArray)
4506 // Dispatched behavior.
4507 DECLARE_PRINTER(ExternalUint8ClampedArray)
4508 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4511 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4515 class ExternalInt8Array: public ExternalArray {
4517 // Setter and getter.
4518 inline int8_t get_scalar(int index);
4519 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4520 inline void set(int index, int8_t value);
4522 // This accessor applies the correct conversion from Smi, HeapNumber
4524 static Handle<Object> SetValue(Handle<ExternalInt8Array> array,
4526 Handle<Object> value);
4528 DECLARE_CAST(ExternalInt8Array)
4530 // Dispatched behavior.
4531 DECLARE_PRINTER(ExternalInt8Array)
4532 DECLARE_VERIFIER(ExternalInt8Array)
4535 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4539 class ExternalUint8Array: public ExternalArray {
4541 // Setter and getter.
4542 inline uint8_t get_scalar(int index);
4543 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4544 inline void set(int index, uint8_t value);
4546 // This accessor applies the correct conversion from Smi, HeapNumber
4548 static Handle<Object> SetValue(Handle<ExternalUint8Array> array,
4550 Handle<Object> value);
4552 DECLARE_CAST(ExternalUint8Array)
4554 // Dispatched behavior.
4555 DECLARE_PRINTER(ExternalUint8Array)
4556 DECLARE_VERIFIER(ExternalUint8Array)
4559 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4563 class ExternalInt16Array: public ExternalArray {
4565 // Setter and getter.
4566 inline int16_t get_scalar(int index);
4567 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4568 inline void set(int index, int16_t value);
4570 // This accessor applies the correct conversion from Smi, HeapNumber
4572 static Handle<Object> SetValue(Handle<ExternalInt16Array> array,
4574 Handle<Object> value);
4576 DECLARE_CAST(ExternalInt16Array)
4578 // Dispatched behavior.
4579 DECLARE_PRINTER(ExternalInt16Array)
4580 DECLARE_VERIFIER(ExternalInt16Array)
4583 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4587 class ExternalUint16Array: public ExternalArray {
4589 // Setter and getter.
4590 inline uint16_t get_scalar(int index);
4591 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4593 inline void set(int index, uint16_t value);
4595 // This accessor applies the correct conversion from Smi, HeapNumber
4597 static Handle<Object> SetValue(Handle<ExternalUint16Array> array,
4599 Handle<Object> value);
4601 DECLARE_CAST(ExternalUint16Array)
4603 // Dispatched behavior.
4604 DECLARE_PRINTER(ExternalUint16Array)
4605 DECLARE_VERIFIER(ExternalUint16Array)
4608 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4612 class ExternalInt32Array: public ExternalArray {
4614 // Setter and getter.
4615 inline int32_t get_scalar(int index);
4616 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4617 inline void set(int index, int32_t value);
4619 // This accessor applies the correct conversion from Smi, HeapNumber
4621 static Handle<Object> SetValue(Handle<ExternalInt32Array> array,
4623 Handle<Object> value);
4625 DECLARE_CAST(ExternalInt32Array)
4627 // Dispatched behavior.
4628 DECLARE_PRINTER(ExternalInt32Array)
4629 DECLARE_VERIFIER(ExternalInt32Array)
4632 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4636 class ExternalUint32Array: public ExternalArray {
4638 // Setter and getter.
4639 inline uint32_t get_scalar(int index);
4640 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4642 inline void set(int index, uint32_t value);
4644 // This accessor applies the correct conversion from Smi, HeapNumber
4646 static Handle<Object> SetValue(Handle<ExternalUint32Array> array,
4648 Handle<Object> value);
4650 DECLARE_CAST(ExternalUint32Array)
4652 // Dispatched behavior.
4653 DECLARE_PRINTER(ExternalUint32Array)
4654 DECLARE_VERIFIER(ExternalUint32Array)
4657 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4661 class ExternalFloat32Array: public ExternalArray {
4663 // Setter and getter.
4664 inline float get_scalar(int index);
4665 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4667 inline void set(int index, float value);
4669 // This accessor applies the correct conversion from Smi, HeapNumber
4671 static Handle<Object> SetValue(Handle<ExternalFloat32Array> array,
4673 Handle<Object> value);
4675 DECLARE_CAST(ExternalFloat32Array)
4677 // Dispatched behavior.
4678 DECLARE_PRINTER(ExternalFloat32Array)
4679 DECLARE_VERIFIER(ExternalFloat32Array)
4682 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4686 class ExternalFloat64Array: public ExternalArray {
4688 // Setter and getter.
4689 inline double get_scalar(int index);
4690 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4692 inline void set(int index, double value);
4694 // This accessor applies the correct conversion from Smi, HeapNumber
4696 static Handle<Object> SetValue(Handle<ExternalFloat64Array> array,
4698 Handle<Object> value);
4700 DECLARE_CAST(ExternalFloat64Array)
4702 // Dispatched behavior.
4703 DECLARE_PRINTER(ExternalFloat64Array)
4704 DECLARE_VERIFIER(ExternalFloat64Array)
4707 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4711 class FixedTypedArrayBase: public FixedArrayBase {
4713 DECLARE_CAST(FixedTypedArrayBase)
4715 static const int kDataOffset = kHeaderSize;
4719 inline int TypedArraySize(InstanceType type);
4721 // Use with care: returns raw pointer into heap.
4722 inline void* DataPtr();
4724 inline int DataSize();
4727 inline int DataSize(InstanceType type);
4729 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4733 template <class Traits>
4734 class FixedTypedArray: public FixedTypedArrayBase {
4736 typedef typename Traits::ElementType ElementType;
4737 static const InstanceType kInstanceType = Traits::kInstanceType;
4739 DECLARE_CAST(FixedTypedArray<Traits>)
4741 static inline int ElementOffset(int index) {
4742 return kDataOffset + index * sizeof(ElementType);
4745 static inline int SizeFor(int length) {
4746 return ElementOffset(length);
4749 inline ElementType get_scalar(int index);
4750 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4751 inline void set(int index, ElementType value);
4753 static inline ElementType from_int(int value);
4754 static inline ElementType from_double(double value);
4756 // This accessor applies the correct conversion from Smi, HeapNumber
4758 static Handle<Object> SetValue(Handle<FixedTypedArray<Traits> > array,
4760 Handle<Object> value);
4762 DECLARE_PRINTER(FixedTypedArray)
4763 DECLARE_VERIFIER(FixedTypedArray)
4766 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4769 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4770 class Type##ArrayTraits { \
4771 public: /* NOLINT */ \
4772 typedef elementType ElementType; \
4773 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4774 static const char* Designator() { return #type " array"; } \
4775 static inline Handle<Object> ToHandle(Isolate* isolate, \
4776 elementType scalar); \
4777 static inline elementType defaultValue(); \
4780 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4782 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4784 #undef FIXED_TYPED_ARRAY_TRAITS
4786 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4787 // data for code generated by the Hydrogen/Lithium compiler. It also
4788 // contains information about functions that were inlined. If N different
4789 // functions were inlined then first N elements of the literal array will
4790 // contain these functions.
4793 class DeoptimizationInputData: public FixedArray {
4795 // Layout description. Indices in the array.
4796 static const int kTranslationByteArrayIndex = 0;
4797 static const int kInlinedFunctionCountIndex = 1;
4798 static const int kLiteralArrayIndex = 2;
4799 static const int kOsrAstIdIndex = 3;
4800 static const int kOsrPcOffsetIndex = 4;
4801 static const int kOptimizationIdIndex = 5;
4802 static const int kSharedFunctionInfoIndex = 6;
4803 static const int kFirstDeoptEntryIndex = 7;
4805 // Offsets of deopt entry elements relative to the start of the entry.
4806 static const int kAstIdRawOffset = 0;
4807 static const int kTranslationIndexOffset = 1;
4808 static const int kArgumentsStackHeightOffset = 2;
4809 static const int kPcOffset = 3;
4810 static const int kDeoptEntrySize = 4;
4812 // Simple element accessors.
4813 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4815 return type::cast(get(k##name##Index)); \
4817 void Set##name(type* value) { \
4818 set(k##name##Index, value); \
4821 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4822 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4823 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4824 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4825 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4826 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4827 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4829 #undef DEFINE_ELEMENT_ACCESSORS
4831 // Accessors for elements of the ith deoptimization entry.
4832 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4833 type* name(int i) { \
4834 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4836 void Set##name(int i, type* value) { \
4837 set(IndexForEntry(i) + k##name##Offset, value); \
4840 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4841 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4842 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4843 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4845 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4847 BailoutId AstId(int i) {
4848 return BailoutId(AstIdRaw(i)->value());
4851 void SetAstId(int i, BailoutId value) {
4852 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4856 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4859 // Allocates a DeoptimizationInputData.
4860 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4861 int deopt_entry_count,
4862 PretenureFlag pretenure);
4864 DECLARE_CAST(DeoptimizationInputData)
4866 #ifdef ENABLE_DISASSEMBLER
4867 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4871 static int IndexForEntry(int i) {
4872 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4876 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4880 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4881 // data for code generated by the full compiler.
4882 // The format of the these objects is
4883 // [i * 2]: Ast ID for ith deoptimization.
4884 // [i * 2 + 1]: PC and state of ith deoptimization
4885 class DeoptimizationOutputData: public FixedArray {
4887 int DeoptPoints() { return length() / 2; }
4889 BailoutId AstId(int index) {
4890 return BailoutId(Smi::cast(get(index * 2))->value());
4893 void SetAstId(int index, BailoutId id) {
4894 set(index * 2, Smi::FromInt(id.ToInt()));
4897 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4898 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4900 static int LengthOfFixedArray(int deopt_points) {
4901 return deopt_points * 2;
4904 // Allocates a DeoptimizationOutputData.
4905 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4906 int number_of_deopt_points,
4907 PretenureFlag pretenure);
4909 DECLARE_CAST(DeoptimizationOutputData)
4911 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4912 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4917 // Forward declaration.
4920 class SafepointEntry;
4921 class TypeFeedbackInfo;
4923 // Code describes objects with on-the-fly generated machine code.
4924 class Code: public HeapObject {
4926 // Opaque data type for encapsulating code flags like kind, inline
4927 // cache state, and arguments count.
4928 typedef uint32_t Flags;
4930 #define NON_IC_KIND_LIST(V) \
4932 V(OPTIMIZED_FUNCTION) \
4938 #define IC_KIND_LIST(V) \
4949 #define CODE_KIND_LIST(V) \
4950 NON_IC_KIND_LIST(V) \
4954 #define DEFINE_CODE_KIND_ENUM(name) name,
4955 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4956 #undef DEFINE_CODE_KIND_ENUM
4960 // No more than 16 kinds. The value is currently encoded in four bits in
4962 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4964 static const char* Kind2String(Kind kind);
4972 static const int kPrologueOffsetNotSet = -1;
4974 #ifdef ENABLE_DISASSEMBLER
4976 static const char* ICState2String(InlineCacheState state);
4977 static const char* StubType2String(StubType type);
4978 static void PrintExtraICState(std::ostream& os, // NOLINT
4979 Kind kind, ExtraICState extra);
4980 void Disassemble(const char* name, std::ostream& os); // NOLINT
4981 #endif // ENABLE_DISASSEMBLER
4983 // [instruction_size]: Size of the native instructions
4984 inline int instruction_size() const;
4985 inline void set_instruction_size(int value);
4987 // [relocation_info]: Code relocation information
4988 DECL_ACCESSORS(relocation_info, ByteArray)
4989 void InvalidateRelocation();
4990 void InvalidateEmbeddedObjects();
4992 // [handler_table]: Fixed array containing offsets of exception handlers.
4993 DECL_ACCESSORS(handler_table, FixedArray)
4995 // [deoptimization_data]: Array containing data for deopt.
4996 DECL_ACCESSORS(deoptimization_data, FixedArray)
4998 // [raw_type_feedback_info]: This field stores various things, depending on
4999 // the kind of the code object.
5000 // FUNCTION => type feedback information.
5001 // STUB and ICs => major/minor key as Smi.
5002 DECL_ACCESSORS(raw_type_feedback_info, Object)
5003 inline Object* type_feedback_info();
5004 inline void set_type_feedback_info(
5005 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5006 inline uint32_t stub_key();
5007 inline void set_stub_key(uint32_t key);
5009 // [next_code_link]: Link for lists of optimized or deoptimized code.
5010 // Note that storage for this field is overlapped with typefeedback_info.
5011 DECL_ACCESSORS(next_code_link, Object)
5013 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
5014 // field does not have to be traced during garbage collection since
5015 // it is only used by the garbage collector itself.
5016 DECL_ACCESSORS(gc_metadata, Object)
5018 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
5019 // at the moment when this object was created.
5020 inline void set_ic_age(int count);
5021 inline int ic_age() const;
5023 // [prologue_offset]: Offset of the function prologue, used for aging
5024 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
5025 inline int prologue_offset() const;
5026 inline void set_prologue_offset(int offset);
5028 // Unchecked accessors to be used during GC.
5029 inline ByteArray* unchecked_relocation_info();
5031 inline int relocation_size();
5033 // [flags]: Various code flags.
5034 inline Flags flags();
5035 inline void set_flags(Flags flags);
5037 // [flags]: Access to specific code flags.
5039 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5040 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5042 inline StubType type(); // Only valid for monomorphic IC stubs.
5044 // Testers for IC stub kinds.
5045 inline bool is_inline_cache_stub();
5046 inline bool is_debug_stub();
5047 inline bool is_handler() { return kind() == HANDLER; }
5048 inline bool is_load_stub() { return kind() == LOAD_IC; }
5049 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5050 inline bool is_store_stub() { return kind() == STORE_IC; }
5051 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5052 inline bool is_call_stub() { return kind() == CALL_IC; }
5053 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5054 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5055 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5056 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5057 inline bool is_keyed_stub();
5058 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5059 inline bool is_weak_stub();
5060 inline void mark_as_weak_stub();
5061 inline bool is_invalidated_weak_stub();
5062 inline void mark_as_invalidated_weak_stub();
5064 inline bool CanBeWeakStub() {
5066 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
5067 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
5068 ic_state() == MONOMORPHIC;
5071 inline bool IsCodeStubOrIC();
5073 inline void set_raw_kind_specific_flags1(int value);
5074 inline void set_raw_kind_specific_flags2(int value);
5076 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
5077 // object was generated by either the hydrogen or the TurboFan optimizing
5078 // compiler (but it may not be an optimized function).
5079 inline bool is_crankshafted();
5080 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
5081 inline void set_is_crankshafted(bool value);
5083 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
5084 // code object was generated by the TurboFan optimizing compiler.
5085 inline bool is_turbofanned();
5086 inline void set_is_turbofanned(bool value);
5088 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
5089 inline bool optimizable();
5090 inline void set_optimizable(bool value);
5092 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5093 // deoptimization support.
5094 inline bool has_deoptimization_support();
5095 inline void set_has_deoptimization_support(bool value);
5097 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5098 // been compiled with debug break slots.
5099 inline bool has_debug_break_slots();
5100 inline void set_has_debug_break_slots(bool value);
5102 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5103 // been compiled with IsOptimizing set to true.
5104 inline bool is_compiled_optimizable();
5105 inline void set_compiled_optimizable(bool value);
5107 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5108 // how long the function has been marked for OSR and therefore which
5109 // level of loop nesting we are willing to do on-stack replacement
5111 inline void set_allow_osr_at_loop_nesting_level(int level);
5112 inline int allow_osr_at_loop_nesting_level();
5114 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5115 // the code object was seen on the stack with no IC patching going on.
5116 inline int profiler_ticks();
5117 inline void set_profiler_ticks(int ticks);
5119 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5120 inline int builtin_index();
5121 inline void set_builtin_index(int id);
5123 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5124 // reserved in the code prologue.
5125 inline unsigned stack_slots();
5126 inline void set_stack_slots(unsigned slots);
5128 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5129 // the instruction stream where the safepoint table starts.
5130 inline unsigned safepoint_table_offset();
5131 inline void set_safepoint_table_offset(unsigned offset);
5133 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5134 // instruction stream where the back edge table starts.
5135 inline unsigned back_edge_table_offset();
5136 inline void set_back_edge_table_offset(unsigned offset);
5138 inline bool back_edges_patched_for_osr();
5140 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5141 inline byte to_boolean_state();
5143 // [has_function_cache]: For kind STUB tells whether there is a function
5144 // cache is passed to the stub.
5145 inline bool has_function_cache();
5146 inline void set_has_function_cache(bool flag);
5149 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5150 // the code is going to be deoptimized because of dead embedded maps.
5151 inline bool marked_for_deoptimization();
5152 inline void set_marked_for_deoptimization(bool flag);
5154 // [constant_pool]: The constant pool for this function.
5155 inline ConstantPoolArray* constant_pool();
5156 inline void set_constant_pool(Object* constant_pool);
5158 // Get the safepoint entry for the given pc.
5159 SafepointEntry GetSafepointEntry(Address pc);
5161 // Find an object in a stub with a specified map
5162 Object* FindNthObject(int n, Map* match_map);
5164 // Find the first allocation site in an IC stub.
5165 AllocationSite* FindFirstAllocationSite();
5167 // Find the first map in an IC stub.
5168 Map* FindFirstMap();
5169 void FindAllMaps(MapHandleList* maps);
5171 // Find the first handler in an IC stub.
5172 Code* FindFirstHandler();
5174 // Find |length| handlers and put them into |code_list|. Returns false if not
5175 // enough handlers can be found.
5176 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5178 // Find the handler for |map|.
5179 MaybeHandle<Code> FindHandlerForMap(Map* map);
5181 // Find the first name in an IC stub.
5182 Name* FindFirstName();
5184 class FindAndReplacePattern;
5185 // For each (map-to-find, object-to-replace) pair in the pattern, this
5186 // function replaces the corresponding placeholder in the code with the
5187 // object-to-replace. The function assumes that pairs in the pattern come in
5188 // the same order as the placeholders in the code.
5189 void FindAndReplace(const FindAndReplacePattern& pattern);
5191 // The entire code object including its header is copied verbatim to the
5192 // snapshot so that it can be written in one, fast, memcpy during
5193 // deserialization. The deserializer will overwrite some pointers, rather
5194 // like a runtime linker, but the random allocation addresses used in the
5195 // mksnapshot process would still be present in the unlinked snapshot data,
5196 // which would make snapshot production non-reproducible. This method wipes
5197 // out the to-be-overwritten header data for reproducible snapshots.
5198 inline void WipeOutHeader();
5200 // Flags operations.
5201 static inline Flags ComputeFlags(
5202 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5203 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5204 CacheHolderFlag holder = kCacheOnReceiver);
5206 static inline Flags ComputeMonomorphicFlags(
5207 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5208 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5210 static inline Flags ComputeHandlerFlags(
5211 Kind handler_kind, StubType type = NORMAL,
5212 CacheHolderFlag holder = kCacheOnReceiver);
5214 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5215 static inline StubType ExtractTypeFromFlags(Flags flags);
5216 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5217 static inline Kind ExtractKindFromFlags(Flags flags);
5218 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5220 static inline Flags RemoveTypeFromFlags(Flags flags);
5221 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5223 // Convert a target address into a code object.
5224 static inline Code* GetCodeFromTargetAddress(Address address);
5226 // Convert an entry address into an object.
5227 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5229 // Returns the address of the first instruction.
5230 inline byte* instruction_start();
5232 // Returns the address right after the last instruction.
5233 inline byte* instruction_end();
5235 // Returns the size of the instructions, padding, and relocation information.
5236 inline int body_size();
5238 // Returns the address of the first relocation info (read backwards!).
5239 inline byte* relocation_start();
5241 // Code entry point.
5242 inline byte* entry();
5244 // Returns true if pc is inside this object's instructions.
5245 inline bool contains(byte* pc);
5247 // Relocate the code by delta bytes. Called to signal that this code
5248 // object has been moved by delta bytes.
5249 void Relocate(intptr_t delta);
5251 // Migrate code described by desc.
5252 void CopyFrom(const CodeDesc& desc);
5254 // Returns the object size for a given body (used for allocation).
5255 static int SizeFor(int body_size) {
5256 DCHECK_SIZE_TAG_ALIGNED(body_size);
5257 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5260 // Calculate the size of the code object to report for log events. This takes
5261 // the layout of the code object into account.
5262 int ExecutableSize() {
5263 // Check that the assumptions about the layout of the code object holds.
5264 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5266 return instruction_size() + Code::kHeaderSize;
5269 // Locating source position.
5270 int SourcePosition(Address pc);
5271 int SourceStatementPosition(Address pc);
5275 // Dispatched behavior.
5276 int CodeSize() { return SizeFor(body_size()); }
5277 inline void CodeIterateBody(ObjectVisitor* v);
5279 template<typename StaticVisitor>
5280 inline void CodeIterateBody(Heap* heap);
5282 DECLARE_PRINTER(Code)
5283 DECLARE_VERIFIER(Code)
5285 void ClearInlineCaches();
5286 void ClearInlineCaches(Kind kind);
5288 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5289 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5291 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5293 kNotExecutedCodeAge = -2,
5294 kExecutedOnceCodeAge = -1,
5296 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5298 kFirstCodeAge = kNotExecutedCodeAge,
5299 kLastCodeAge = kAfterLastCodeAge - 1,
5300 kCodeAgeCount = kAfterLastCodeAge - kNotExecutedCodeAge - 1,
5301 kIsOldCodeAge = kSexagenarianCodeAge,
5302 kPreAgedCodeAge = kIsOldCodeAge - 1
5304 #undef DECLARE_CODE_AGE_ENUM
5306 // Code aging. Indicates how many full GCs this code has survived without
5307 // being entered through the prologue. Used to determine when it is
5308 // relatively safe to flush this code object and replace it with the lazy
5309 // compilation stub.
5310 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5311 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5312 void MakeOlder(MarkingParity);
5313 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5316 // Gets the raw code age, including psuedo code-age values such as
5317 // kNotExecutedCodeAge and kExecutedOnceCodeAge.
5319 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5320 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5323 void PrintDeoptLocation(FILE* out, int bailout_id);
5324 bool CanDeoptAt(Address pc);
5327 void VerifyEmbeddedObjectsDependency();
5330 inline bool CanContainWeakObjects() {
5331 return is_optimized_code() || is_weak_stub();
5334 inline bool IsWeakObject(Object* object) {
5335 return (is_optimized_code() && !is_turbofanned() &&
5336 IsWeakObjectInOptimizedCode(object)) ||
5337 (is_weak_stub() && IsWeakObjectInIC(object));
5340 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5341 static inline bool IsWeakObjectInIC(Object* object);
5343 // Max loop nesting marker used to postpose OSR. We don't take loop
5344 // nesting that is deeper than 5 levels into account.
5345 static const int kMaxLoopNestingMarker = 6;
5347 // Layout description.
5348 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
5349 static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
5350 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5351 static const int kDeoptimizationDataOffset =
5352 kHandlerTableOffset + kPointerSize;
5353 // For FUNCTION kind, we store the type feedback info here.
5354 static const int kTypeFeedbackInfoOffset =
5355 kDeoptimizationDataOffset + kPointerSize;
5356 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5357 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5358 static const int kICAgeOffset =
5359 kGCMetadataOffset + kPointerSize;
5360 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5361 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5362 static const int kKindSpecificFlags2Offset =
5363 kKindSpecificFlags1Offset + kIntSize;
5364 // Note: We might be able to squeeze this into the flags above.
5365 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5366 static const int kConstantPoolOffset = kPrologueOffset + kPointerSize;
5368 static const int kHeaderPaddingStart = kConstantPoolOffset + kPointerSize;
5370 // Add padding to align the instruction start following right after
5371 // the Code object header.
5372 static const int kHeaderSize =
5373 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5375 // Byte offsets within kKindSpecificFlags1Offset.
5376 static const int kOptimizableOffset = kKindSpecificFlags1Offset;
5378 static const int kFullCodeFlags = kOptimizableOffset + 1;
5379 class FullCodeFlagsHasDeoptimizationSupportField:
5380 public BitField<bool, 0, 1> {}; // NOLINT
5381 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5382 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5384 static const int kProfilerTicksOffset = kFullCodeFlags + 1;
5386 // Flags layout. BitField<type, shift, size>.
5387 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5388 class TypeField : public BitField<StubType, 4, 1> {};
5389 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5390 class KindField : public BitField<Kind, 7, 4> {};
5391 class ExtraICStateField: public BitField<ExtraICState, 11,
5392 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5394 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5395 static const int kStackSlotsFirstBit = 0;
5396 static const int kStackSlotsBitCount = 24;
5397 static const int kHasFunctionCacheBit =
5398 kStackSlotsFirstBit + kStackSlotsBitCount;
5399 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5400 static const int kWeakStubBit = kMarkedForDeoptimizationBit + 1;
5401 static const int kInvalidatedWeakStubBit = kWeakStubBit + 1;
5402 static const int kIsTurbofannedBit = kInvalidatedWeakStubBit + 1;
5404 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5405 STATIC_ASSERT(kIsTurbofannedBit + 1 <= 32);
5407 class StackSlotsField: public BitField<int,
5408 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5409 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5411 class MarkedForDeoptimizationField
5412 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5413 class WeakStubField : public BitField<bool, kWeakStubBit, 1> {}; // NOLINT
5414 class InvalidatedWeakStubField
5415 : public BitField<bool, kInvalidatedWeakStubBit, 1> {}; // NOLINT
5416 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5419 // KindSpecificFlags2 layout (ALL)
5420 static const int kIsCrankshaftedBit = 0;
5421 class IsCrankshaftedField: public BitField<bool,
5422 kIsCrankshaftedBit, 1> {}; // NOLINT
5424 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5425 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5426 static const int kSafepointTableOffsetBitCount = 24;
5428 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5429 kSafepointTableOffsetBitCount <= 32);
5430 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5432 class SafepointTableOffsetField: public BitField<int,
5433 kSafepointTableOffsetFirstBit,
5434 kSafepointTableOffsetBitCount> {}; // NOLINT
5436 // KindSpecificFlags2 layout (FUNCTION)
5437 class BackEdgeTableOffsetField: public BitField<int,
5438 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5439 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5440 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5441 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5443 static const int kArgumentsBits = 16;
5444 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5446 // This constant should be encodable in an ARM instruction.
5447 static const int kFlagsNotUsedInLookup =
5448 TypeField::kMask | CacheHolderField::kMask;
5451 friend class RelocIterator;
5452 friend class Deoptimizer; // For FindCodeAgeSequence.
5454 void ClearInlineCaches(Kind* kind);
5457 byte* FindCodeAgeSequence();
5458 static void GetCodeAgeAndParity(Code* code, Age* age,
5459 MarkingParity* parity);
5460 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5461 MarkingParity* parity);
5462 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5464 // Code aging -- platform-specific
5465 static void PatchPlatformCodeAge(Isolate* isolate,
5466 byte* sequence, Age age,
5467 MarkingParity parity);
5469 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5473 class CompilationInfo;
5475 // This class describes the layout of dependent codes array of a map. The
5476 // array is partitioned into several groups of dependent codes. Each group
5477 // contains codes with the same dependency on the map. The array has the
5478 // following layout for n dependency groups:
5480 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5481 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5482 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5484 // The first n elements are Smis, each of them specifies the number of codes
5485 // in the corresponding group. The subsequent elements contain grouped code
5486 // objects. The suffix of the array can be filled with the undefined value if
5487 // the number of codes is less than the length of the array. The order of the
5488 // code objects within a group is not preserved.
5490 // All code indexes used in the class are counted starting from the first
5491 // code object of the first group. In other words, code index 0 corresponds
5492 // to array index n = kCodesStartIndex.
5494 class DependentCode: public FixedArray {
5496 enum DependencyGroup {
5497 // Group of IC stubs that weakly embed this map and depend on being
5498 // invalidated when the map is garbage collected. Dependent IC stubs form
5499 // a linked list. This group stores only the head of the list. This means
5500 // that the number_of_entries(kWeakICGroup) is 0 or 1.
5502 // Group of code that weakly embed this map and depend on being
5503 // deoptimized when the map is garbage collected.
5505 // Group of code that embed a transition to this map, and depend on being
5506 // deoptimized when the transition is replaced by a new version.
5508 // Group of code that omit run-time prototype checks for prototypes
5509 // described by this map. The group is deoptimized whenever an object
5510 // described by this map changes shape (and transitions to a new map),
5511 // possibly invalidating the assumptions embedded in the code.
5512 kPrototypeCheckGroup,
5513 // Group of code that depends on elements not being added to objects with
5515 kElementsCantBeAddedGroup,
5516 // Group of code that depends on global property values in property cells
5517 // not being changed.
5518 kPropertyCellChangedGroup,
5519 // Group of code that omit run-time type checks for the field(s) introduced
5522 // Group of code that omit run-time type checks for initial maps of
5524 kInitialMapChangedGroup,
5525 // Group of code that depends on tenuring information in AllocationSites
5526 // not being changed.
5527 kAllocationSiteTenuringChangedGroup,
5528 // Group of code that depends on element transition information in
5529 // AllocationSites not being changed.
5530 kAllocationSiteTransitionChangedGroup
5533 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5535 // Array for holding the index of the first code object of each group.
5536 // The last element stores the total number of code objects.
5537 class GroupStartIndexes {
5539 explicit GroupStartIndexes(DependentCode* entries);
5540 void Recompute(DependentCode* entries);
5541 int at(int i) { return start_indexes_[i]; }
5542 int number_of_entries() { return start_indexes_[kGroupCount]; }
5544 int start_indexes_[kGroupCount + 1];
5547 bool Contains(DependencyGroup group, Code* code);
5548 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5549 DependencyGroup group,
5550 Handle<Object> object);
5551 void UpdateToFinishedCode(DependencyGroup group,
5552 CompilationInfo* info,
5554 void RemoveCompilationInfo(DependentCode::DependencyGroup group,
5555 CompilationInfo* info);
5557 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5558 DependentCode::DependencyGroup group);
5560 bool MarkCodeForDeoptimization(Isolate* isolate,
5561 DependentCode::DependencyGroup group);
5562 void AddToDependentICList(Handle<Code> stub);
5564 // The following low-level accessors should only be used by this class
5565 // and the mark compact collector.
5566 inline int number_of_entries(DependencyGroup group);
5567 inline void set_number_of_entries(DependencyGroup group, int value);
5568 inline bool is_code_at(int i);
5569 inline Code* code_at(int i);
5570 inline CompilationInfo* compilation_info_at(int i);
5571 inline void set_object_at(int i, Object* object);
5572 inline Object** slot_at(int i);
5573 inline Object* object_at(int i);
5574 inline void clear_at(int i);
5575 inline void copy(int from, int to);
5576 DECLARE_CAST(DependentCode)
5578 static DependentCode* ForObject(Handle<HeapObject> object,
5579 DependencyGroup group);
5581 static const char* DependencyGroupName(DependencyGroup group);
5582 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5585 // Make a room at the end of the given group by moving out the first
5586 // code objects of the subsequent groups.
5587 inline void ExtendGroup(DependencyGroup group);
5588 static const int kCodesStartIndex = kGroupCount;
5592 // All heap objects have a Map that describes their structure.
5593 // A Map contains information about:
5594 // - Size information about the object
5595 // - How to iterate over an object (for garbage collection)
5596 class Map: public HeapObject {
5599 // Size in bytes or kVariableSizeSentinel if instances do not have
5601 inline int instance_size();
5602 inline void set_instance_size(int value);
5604 // Count of properties allocated in the object.
5605 inline int inobject_properties();
5606 inline void set_inobject_properties(int value);
5608 // Count of property fields pre-allocated in the object when first allocated.
5609 inline int pre_allocated_property_fields();
5610 inline void set_pre_allocated_property_fields(int value);
5613 inline InstanceType instance_type();
5614 inline void set_instance_type(InstanceType value);
5616 // Tells how many unused property fields are available in the
5617 // instance (only used for JSObject in fast mode).
5618 inline int unused_property_fields();
5619 inline void set_unused_property_fields(int value);
5622 inline byte bit_field();
5623 inline void set_bit_field(byte value);
5626 inline byte bit_field2();
5627 inline void set_bit_field2(byte value);
5630 inline uint32_t bit_field3();
5631 inline void set_bit_field3(uint32_t bits);
5633 class EnumLengthBits: public BitField<int,
5634 0, kDescriptorIndexBitCount> {}; // NOLINT
5635 class NumberOfOwnDescriptorsBits: public BitField<int,
5636 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5637 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5638 class DictionaryMap : public BitField<bool, 20, 1> {};
5639 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5640 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5641 class Deprecated : public BitField<bool, 23, 1> {};
5642 class IsFrozen : public BitField<bool, 24, 1> {};
5643 class IsUnstable : public BitField<bool, 25, 1> {};
5644 class IsMigrationTarget : public BitField<bool, 26, 1> {};
5645 class DoneInobjectSlackTracking : public BitField<bool, 27, 1> {};
5648 // Keep this bit field at the very end for better code in
5649 // Builtins::kJSConstructStubGeneric stub.
5650 class ConstructionCount: public BitField<int, 29, 3> {};
5652 // Tells whether the object in the prototype property will be used
5653 // for instances created from this function. If the prototype
5654 // property is set to a value that is not a JSObject, the prototype
5655 // property will not be used to create instances of the function.
5656 // See ECMA-262, 13.2.2.
5657 inline void set_non_instance_prototype(bool value);
5658 inline bool has_non_instance_prototype();
5660 // Tells whether function has special prototype property. If not, prototype
5661 // property will not be created when accessed (will return undefined),
5662 // and construction from this function will not be allowed.
5663 inline void set_function_with_prototype(bool value);
5664 inline bool function_with_prototype();
5666 // Tells whether the instance with this map should be ignored by the
5667 // Object.getPrototypeOf() function and the __proto__ accessor.
5668 inline void set_is_hidden_prototype() {
5669 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5672 inline bool is_hidden_prototype() {
5673 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5676 // Records and queries whether the instance has a named interceptor.
5677 inline void set_has_named_interceptor() {
5678 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5681 inline bool has_named_interceptor() {
5682 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5685 // Records and queries whether the instance has an indexed interceptor.
5686 inline void set_has_indexed_interceptor() {
5687 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5690 inline bool has_indexed_interceptor() {
5691 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5694 // Tells whether the instance is undetectable.
5695 // An undetectable object is a special class of JSObject: 'typeof' operator
5696 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5697 // a normal JS object. It is useful for implementing undetectable
5698 // document.all in Firefox & Safari.
5699 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5700 inline void set_is_undetectable() {
5701 set_bit_field(bit_field() | (1 << kIsUndetectable));
5704 inline bool is_undetectable() {
5705 return ((1 << kIsUndetectable) & bit_field()) != 0;
5708 // Tells whether the instance has a call-as-function handler.
5709 inline void set_is_observed() {
5710 set_bit_field(bit_field() | (1 << kIsObserved));
5713 inline bool is_observed() {
5714 return ((1 << kIsObserved) & bit_field()) != 0;
5717 inline void set_is_extensible(bool value);
5718 inline bool is_extensible();
5719 inline void set_is_prototype_map(bool value);
5720 inline bool is_prototype_map();
5722 inline void set_elements_kind(ElementsKind elements_kind) {
5723 DCHECK(elements_kind < kElementsKindCount);
5724 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5725 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5726 DCHECK(this->elements_kind() == elements_kind);
5729 inline ElementsKind elements_kind() {
5730 return Map::ElementsKindBits::decode(bit_field2());
5733 // Tells whether the instance has fast elements that are only Smis.
5734 inline bool has_fast_smi_elements() {
5735 return IsFastSmiElementsKind(elements_kind());
5738 // Tells whether the instance has fast elements.
5739 inline bool has_fast_object_elements() {
5740 return IsFastObjectElementsKind(elements_kind());
5743 inline bool has_fast_smi_or_object_elements() {
5744 return IsFastSmiOrObjectElementsKind(elements_kind());
5747 inline bool has_fast_double_elements() {
5748 return IsFastDoubleElementsKind(elements_kind());
5751 inline bool has_fast_elements() {
5752 return IsFastElementsKind(elements_kind());
5755 inline bool has_sloppy_arguments_elements() {
5756 return elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5759 inline bool has_external_array_elements() {
5760 return IsExternalArrayElementsKind(elements_kind());
5763 inline bool has_fixed_typed_array_elements() {
5764 return IsFixedTypedArrayElementsKind(elements_kind());
5767 inline bool has_dictionary_elements() {
5768 return IsDictionaryElementsKind(elements_kind());
5771 inline bool has_slow_elements_kind() {
5772 return elements_kind() == DICTIONARY_ELEMENTS
5773 || elements_kind() == SLOPPY_ARGUMENTS_ELEMENTS;
5776 static bool IsValidElementsTransition(ElementsKind from_kind,
5777 ElementsKind to_kind);
5779 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5780 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5781 bool DictionaryElementsInPrototypeChainOnly();
5783 inline bool HasTransitionArray() const;
5784 inline bool HasElementsTransition();
5785 inline Map* elements_transition_map();
5787 inline Map* GetTransition(int transition_index);
5788 inline int SearchTransition(Name* name);
5789 inline FixedArrayBase* GetInitialElements();
5791 DECL_ACCESSORS(transitions, TransitionArray)
5793 static inline Handle<String> ExpectedTransitionKey(Handle<Map> map);
5794 static inline Handle<Map> ExpectedTransitionTarget(Handle<Map> map);
5796 // Try to follow an existing transition to a field with attributes NONE. The
5797 // return value indicates whether the transition was successful.
5798 static inline Handle<Map> FindTransitionToField(Handle<Map> map,
5802 Map* FindFieldOwner(int descriptor);
5804 inline int GetInObjectPropertyOffset(int index);
5806 int NumberOfFields();
5808 // TODO(ishell): candidate with JSObject::MigrateToMap().
5809 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5810 int target_inobject, int target_unused,
5811 int* old_number_of_fields);
5812 // TODO(ishell): moveit!
5813 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5814 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5815 Handle<HeapType> type1,
5816 Handle<HeapType> type2,
5818 static void GeneralizeFieldType(Handle<Map> map,
5820 Handle<HeapType> new_field_type);
5821 static Handle<Map> GeneralizeRepresentation(
5824 Representation new_representation,
5825 Handle<HeapType> new_field_type,
5826 StoreMode store_mode);
5827 static Handle<Map> CopyGeneralizeAllRepresentations(
5830 StoreMode store_mode,
5831 PropertyAttributes attributes,
5832 const char* reason);
5833 static Handle<Map> CopyGeneralizeAllRepresentations(
5836 StoreMode store_mode,
5837 const char* reason);
5839 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5840 int descriptor_number,
5841 Handle<Object> value);
5843 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode);
5845 // Returns the constructor name (the name (possibly, inferred name) of the
5846 // function that was used to instantiate the object).
5847 String* constructor_name();
5849 // Tells whether the map is used for JSObjects in dictionary mode (ie
5850 // normalized objects, ie objects for which HasFastProperties returns false).
5851 // A map can never be used for both dictionary mode and fast mode JSObjects.
5852 // False by default and for HeapObjects that are not JSObjects.
5853 inline void set_dictionary_map(bool value);
5854 inline bool is_dictionary_map();
5856 // Tells whether the instance needs security checks when accessing its
5858 inline void set_is_access_check_needed(bool access_check_needed);
5859 inline bool is_access_check_needed();
5861 // Returns true if map has a non-empty stub code cache.
5862 inline bool has_code_cache();
5864 // [prototype]: implicit prototype object.
5865 DECL_ACCESSORS(prototype, Object)
5867 // [constructor]: points back to the function responsible for this map.
5868 DECL_ACCESSORS(constructor, Object)
5870 // [instance descriptors]: describes the object.
5871 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5872 inline void InitializeDescriptors(DescriptorArray* descriptors);
5874 // [stub cache]: contains stubs compiled for this map.
5875 DECL_ACCESSORS(code_cache, Object)
5877 // [dependent code]: list of optimized codes that weakly embed this map.
5878 DECL_ACCESSORS(dependent_code, DependentCode)
5880 // [back pointer]: points back to the parent map from which a transition
5881 // leads to this map. The field overlaps with prototype transitions and the
5882 // back pointer will be moved into the prototype transitions array if
5884 inline Object* GetBackPointer();
5885 inline void SetBackPointer(Object* value,
5886 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5887 inline void init_back_pointer(Object* undefined);
5889 // [prototype transitions]: cache of prototype transitions.
5890 // Prototype transition is a transition that happens
5891 // when we change object's prototype to a new one.
5893 // 0: finger - index of the first free cell in the cache
5894 // 1: back pointer that overlaps with prototype transitions field.
5895 // 2 + 2 * i: prototype
5896 // 3 + 2 * i: target map
5897 inline FixedArray* GetPrototypeTransitions();
5898 inline bool HasPrototypeTransitions();
5900 static const int kProtoTransitionHeaderSize = 1;
5901 static const int kProtoTransitionNumberOfEntriesOffset = 0;
5902 static const int kProtoTransitionElementsPerEntry = 2;
5903 static const int kProtoTransitionPrototypeOffset = 0;
5904 static const int kProtoTransitionMapOffset = 1;
5906 inline int NumberOfProtoTransitions() {
5907 FixedArray* cache = GetPrototypeTransitions();
5908 if (cache->length() == 0) return 0;
5910 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
5913 inline void SetNumberOfProtoTransitions(int value) {
5914 FixedArray* cache = GetPrototypeTransitions();
5915 DCHECK(cache->length() != 0);
5916 cache->set(kProtoTransitionNumberOfEntriesOffset, Smi::FromInt(value));
5919 // Lookup in the map's instance descriptors and fill out the result
5920 // with the given holder if the name is found. The holder may be
5921 // NULL when this function is used from the compiler.
5922 inline void LookupDescriptor(JSObject* holder,
5924 LookupResult* result);
5926 inline void LookupTransition(JSObject* holder,
5928 LookupResult* result);
5930 inline PropertyDetails GetLastDescriptorDetails();
5932 // The size of transition arrays are limited so they do not end up in large
5933 // object space. Otherwise ClearNonLiveTransitions would leak memory while
5934 // applying in-place right trimming.
5935 inline bool CanHaveMoreTransitions();
5938 int number_of_own_descriptors = NumberOfOwnDescriptors();
5939 DCHECK(number_of_own_descriptors > 0);
5940 return number_of_own_descriptors - 1;
5943 int NumberOfOwnDescriptors() {
5944 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5947 void SetNumberOfOwnDescriptors(int number) {
5948 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5949 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5952 inline Cell* RetrieveDescriptorsPointer();
5955 return EnumLengthBits::decode(bit_field3());
5958 void SetEnumLength(int length) {
5959 if (length != kInvalidEnumCacheSentinel) {
5960 DCHECK(length >= 0);
5961 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5962 DCHECK(length <= NumberOfOwnDescriptors());
5964 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5967 inline bool owns_descriptors();
5968 inline void set_owns_descriptors(bool owns_descriptors);
5969 inline bool has_instance_call_handler();
5970 inline void set_has_instance_call_handler();
5971 inline void freeze();
5972 inline bool is_frozen();
5973 inline void mark_unstable();
5974 inline bool is_stable();
5975 inline void set_migration_target(bool value);
5976 inline bool is_migration_target();
5977 inline void set_done_inobject_slack_tracking(bool value);
5978 inline bool done_inobject_slack_tracking();
5979 inline void set_construction_count(int value);
5980 inline int construction_count();
5981 inline void deprecate();
5982 inline bool is_deprecated();
5983 inline bool CanBeDeprecated();
5984 // Returns a non-deprecated version of the input. If the input was not
5985 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5986 // is found by re-transitioning from the root of the transition tree using the
5987 // descriptor array of the map. Returns NULL if no updated map is found.
5988 // This method also applies any pending migrations along the prototype chain.
5989 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5990 // Same as above, but does not touch the prototype chain.
5991 static MaybeHandle<Map> TryUpdateInternal(Handle<Map> map)
5994 // Returns a non-deprecated version of the input. This method may deprecate
5995 // existing maps along the way if encodings conflict. Not for use while
5996 // gathering type feedback. Use TryUpdate in those cases instead.
5997 static Handle<Map> Update(Handle<Map> map);
5999 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
6000 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
6001 Descriptor* descriptor,
6002 TransitionFlag flag);
6004 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
6007 Handle<HeapType> type,
6008 PropertyAttributes attributes,
6009 Representation representation,
6010 TransitionFlag flag);
6012 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
6015 Handle<Object> constant,
6016 PropertyAttributes attributes,
6017 TransitionFlag flag);
6019 // Returns a new map with all transitions dropped from the given map and
6020 // the ElementsKind set.
6021 static Handle<Map> TransitionElementsTo(Handle<Map> map,
6022 ElementsKind to_kind);
6024 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
6026 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
6028 TransitionFlag flag);
6030 static Handle<Map> CopyForObserved(Handle<Map> map);
6032 static Handle<Map> CopyForFreeze(Handle<Map> map);
6033 // Maximal number of fast properties. Used to restrict the number of map
6034 // transitions to avoid an explosion in the number of maps for objects used as
6036 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
6037 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
6039 Handle<Object> value,
6040 PropertyAttributes attributes,
6041 StoreFromKeyed store_mode);
6042 static Handle<Map> TransitionToAccessorProperty(
6043 Handle<Map> map, Handle<Name> name, AccessorComponent component,
6044 Handle<Object> accessor, PropertyAttributes attributes);
6045 static Handle<Map> ReconfigureDataProperty(Handle<Map> map, int descriptor,
6046 PropertyAttributes attributes);
6048 inline void AppendDescriptor(Descriptor* desc);
6050 // Returns a copy of the map, with all transitions dropped from the
6051 // instance descriptors.
6052 static Handle<Map> Copy(Handle<Map> map);
6053 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
6055 // Returns the next free property index (only valid for FAST MODE).
6056 int NextFreePropertyIndex();
6058 // Returns the number of properties described in instance_descriptors
6059 // filtering out properties with the specified attributes.
6060 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6061 PropertyAttributes filter = NONE);
6063 // Returns the number of slots allocated for the initial properties
6064 // backing storage for instances of this map.
6065 int InitialPropertiesLength() {
6066 return pre_allocated_property_fields() + unused_property_fields() -
6067 inobject_properties();
6072 // Code cache operations.
6074 // Clears the code cache.
6075 inline void ClearCodeCache(Heap* heap);
6077 // Update code cache.
6078 static void UpdateCodeCache(Handle<Map> map,
6082 // Extend the descriptor array of the map with the list of descriptors.
6083 // In case of duplicates, the latest descriptor is used.
6084 static void AppendCallbackDescriptors(Handle<Map> map,
6085 Handle<Object> descriptors);
6087 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6089 // Returns the found code or undefined if absent.
6090 Object* FindInCodeCache(Name* name, Code::Flags flags);
6092 // Returns the non-negative index of the code object if it is in the
6093 // cache and -1 otherwise.
6094 int IndexInCodeCache(Object* name, Code* code);
6096 // Removes a code object from the code cache at the given index.
6097 void RemoveFromCodeCache(Name* name, Code* code, int index);
6099 // Set all map transitions from this map to dead maps to null. Also clear
6100 // back pointers in transition targets so that we do not process this map
6101 // again while following back pointers.
6102 void ClearNonLiveTransitions(Heap* heap);
6104 // Computes a hash value for this map, to be used in HashTables and such.
6107 // Returns the map that this map transitions to if its elements_kind
6108 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6109 // |safe_to_add_transitions| is set to false if adding transitions is not
6111 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6113 // Returns the transitioned map for this map with the most generic
6114 // elements_kind that's found in |candidates|, or null handle if no match is
6116 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
6118 bool CanTransition() {
6119 // Only JSObject and subtypes have map transitions and back pointers.
6120 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6121 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6124 bool IsJSObjectMap() {
6125 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6127 bool IsJSProxyMap() {
6128 InstanceType type = instance_type();
6129 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6131 bool IsJSGlobalProxyMap() {
6132 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6134 bool IsJSGlobalObjectMap() {
6135 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6137 bool IsGlobalObjectMap() {
6138 const InstanceType type = instance_type();
6139 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6142 inline bool CanOmitMapChecks();
6144 static void AddDependentCompilationInfo(Handle<Map> map,
6145 DependentCode::DependencyGroup group,
6146 CompilationInfo* info);
6148 static void AddDependentCode(Handle<Map> map,
6149 DependentCode::DependencyGroup group,
6151 static void AddDependentIC(Handle<Map> map,
6154 bool IsMapInArrayPrototypeChain();
6156 // Dispatched behavior.
6157 DECLARE_PRINTER(Map)
6158 DECLARE_VERIFIER(Map)
6161 void DictionaryMapVerify();
6162 void VerifyOmittedMapChecks();
6165 inline int visitor_id();
6166 inline void set_visitor_id(int visitor_id);
6168 typedef void (*TraverseCallback)(Map* map, void* data);
6170 void TraverseTransitionTree(TraverseCallback callback, void* data);
6172 // When you set the prototype of an object using the __proto__ accessor you
6173 // need a new map for the object (the prototype is stored in the map). In
6174 // order not to multiply maps unnecessarily we store these as transitions in
6175 // the original map. That way we can transition to the same map if the same
6176 // prototype is set, rather than creating a new map every time. The
6177 // transitions are in the form of a map where the keys are prototype objects
6178 // and the values are the maps the are transitioned to.
6179 static const int kMaxCachedPrototypeTransitions = 256;
6180 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6181 Handle<Object> prototype);
6183 static const int kMaxPreAllocatedPropertyFields = 255;
6185 // Layout description.
6186 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6187 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6188 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6189 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6190 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
6191 // Storage for the transition array is overloaded to directly contain a back
6192 // pointer if unused. When the map has transitions, the back pointer is
6193 // transferred to the transition array and accessed through an extra
6195 static const int kTransitionsOrBackPointerOffset =
6196 kConstructorOffset + kPointerSize;
6197 static const int kDescriptorsOffset =
6198 kTransitionsOrBackPointerOffset + kPointerSize;
6199 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6200 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6201 static const int kSize = kDependentCodeOffset + kPointerSize;
6203 // Layout of pointer fields. Heap iteration code relies on them
6204 // being continuously allocated.
6205 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6206 static const int kPointerFieldsEndOffset = kSize;
6208 // Byte offsets within kInstanceSizesOffset.
6209 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6210 static const int kInObjectPropertiesByte = 1;
6211 static const int kInObjectPropertiesOffset =
6212 kInstanceSizesOffset + kInObjectPropertiesByte;
6213 static const int kPreAllocatedPropertyFieldsByte = 2;
6214 static const int kPreAllocatedPropertyFieldsOffset =
6215 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
6216 static const int kVisitorIdByte = 3;
6217 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6219 // Byte offsets within kInstanceAttributesOffset attributes.
6220 #if V8_TARGET_LITTLE_ENDIAN
6221 // Order instance type and bit field together such that they can be loaded
6222 // together as a 16-bit word with instance type in the lower 8 bits regardless
6223 // of endianess. Also provide endian-independent offset to that 16-bit word.
6224 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6225 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6227 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6228 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6230 static const int kInstanceTypeAndBitFieldOffset =
6231 kInstanceAttributesOffset + 0;
6232 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6233 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6235 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6236 Internals::kMapInstanceTypeAndBitFieldOffset);
6238 // Bit positions for bit field.
6239 static const int kHasNonInstancePrototype = 0;
6240 static const int kIsHiddenPrototype = 1;
6241 static const int kHasNamedInterceptor = 2;
6242 static const int kHasIndexedInterceptor = 3;
6243 static const int kIsUndetectable = 4;
6244 static const int kIsObserved = 5;
6245 static const int kIsAccessCheckNeeded = 6;
6246 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6248 // Bit positions for bit field 2
6249 static const int kIsExtensible = 0;
6250 static const int kStringWrapperSafeForDefaultValueOf = 1;
6251 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6252 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6254 // Derived values from bit field 2
6255 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6256 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6257 static const int8_t kMaximumBitField2FastSmiElementValue =
6258 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6259 Map::ElementsKindBits::kShift) - 1;
6260 static const int8_t kMaximumBitField2FastHoleyElementValue =
6261 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6262 Map::ElementsKindBits::kShift) - 1;
6263 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6264 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6265 Map::ElementsKindBits::kShift) - 1;
6267 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6268 kPointerFieldsEndOffset,
6269 kSize> BodyDescriptor;
6271 // Compares this map to another to see if they describe equivalent objects.
6272 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6273 // it had exactly zero inobject properties.
6274 // The "shared" flags of both this map and |other| are ignored.
6275 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6278 static void ConnectElementsTransition(Handle<Map> parent, Handle<Map> child);
6279 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6280 Handle<Name> name, SimpleTransitionFlag flag);
6282 bool EquivalentToForTransition(Map* other);
6283 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6284 static Handle<Map> ShareDescriptor(Handle<Map> map,
6285 Handle<DescriptorArray> descriptors,
6286 Descriptor* descriptor);
6287 static Handle<Map> CopyInstallDescriptors(
6290 Handle<DescriptorArray> descriptors);
6291 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6292 Descriptor* descriptor,
6293 TransitionFlag flag);
6294 static Handle<Map> CopyReplaceDescriptors(
6296 Handle<DescriptorArray> descriptors,
6297 TransitionFlag flag,
6298 MaybeHandle<Name> maybe_name,
6299 SimpleTransitionFlag simple_flag = FULL_TRANSITION);
6300 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6301 Handle<DescriptorArray> descriptors,
6302 Descriptor* descriptor,
6304 TransitionFlag flag);
6306 static Handle<Map> CopyNormalized(Handle<Map> map,
6307 PropertyNormalizationMode mode);
6309 // Fires when the layout of an object with a leaf map changes.
6310 // This includes adding transitions to the leaf map or changing
6311 // the descriptor array.
6312 inline void NotifyLeafMapLayoutChange();
6314 static Handle<Map> TransitionElementsToSlow(Handle<Map> object,
6315 ElementsKind to_kind);
6317 // Zaps the contents of backing data structures. Note that the
6318 // heap verifier (i.e. VerifyMarkingVisitor) relies on zapping of objects
6319 // holding weak references when incremental marking is used, because it also
6320 // iterates over objects that are otherwise unreachable.
6321 // In general we only want to call these functions in release mode when
6322 // heap verification is turned on.
6323 void ZapPrototypeTransitions();
6324 void ZapTransitions();
6326 void DeprecateTransitionTree();
6327 void DeprecateTarget(Name* key, DescriptorArray* new_descriptors);
6329 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6331 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6332 Handle<HeapType> new_type);
6334 void PrintGeneralization(FILE* file,
6339 bool constant_to_field,
6340 Representation old_representation,
6341 Representation new_representation,
6342 HeapType* old_field_type,
6343 HeapType* new_field_type);
6345 static inline void SetPrototypeTransitions(
6347 Handle<FixedArray> prototype_transitions);
6349 static Handle<Map> GetPrototypeTransition(Handle<Map> map,
6350 Handle<Object> prototype);
6351 static Handle<Map> PutPrototypeTransition(Handle<Map> map,
6352 Handle<Object> prototype,
6353 Handle<Map> target_map);
6355 static const int kFastPropertiesSoftLimit = 12;
6356 static const int kMaxFastProperties = 128;
6358 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6362 // An abstract superclass, a marker class really, for simple structure classes.
6363 // It doesn't carry much functionality but allows struct classes to be
6364 // identified in the type system.
6365 class Struct: public HeapObject {
6367 inline void InitializeBody(int object_size);
6368 DECLARE_CAST(Struct)
6372 // A simple one-element struct, useful where smis need to be boxed.
6373 class Box : public Struct {
6375 // [value]: the boxed contents.
6376 DECL_ACCESSORS(value, Object)
6380 // Dispatched behavior.
6381 DECLARE_PRINTER(Box)
6382 DECLARE_VERIFIER(Box)
6384 static const int kValueOffset = HeapObject::kHeaderSize;
6385 static const int kSize = kValueOffset + kPointerSize;
6388 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6392 // Script describes a script which has been added to the VM.
6393 class Script: public Struct {
6402 // Script compilation types.
6403 enum CompilationType {
6404 COMPILATION_TYPE_HOST = 0,
6405 COMPILATION_TYPE_EVAL = 1
6408 // Script compilation state.
6409 enum CompilationState {
6410 COMPILATION_STATE_INITIAL = 0,
6411 COMPILATION_STATE_COMPILED = 1
6414 // [source]: the script source.
6415 DECL_ACCESSORS(source, Object)
6417 // [name]: the script name.
6418 DECL_ACCESSORS(name, Object)
6420 // [id]: the script id.
6421 DECL_ACCESSORS(id, Smi)
6423 // [line_offset]: script line offset in resource from where it was extracted.
6424 DECL_ACCESSORS(line_offset, Smi)
6426 // [column_offset]: script column offset in resource from where it was
6428 DECL_ACCESSORS(column_offset, Smi)
6430 // [context_data]: context data for the context this script was compiled in.
6431 DECL_ACCESSORS(context_data, Object)
6433 // [wrapper]: the wrapper cache.
6434 DECL_ACCESSORS(wrapper, Foreign)
6436 // [type]: the script type.
6437 DECL_ACCESSORS(type, Smi)
6439 // [line_ends]: FixedArray of line ends positions.
6440 DECL_ACCESSORS(line_ends, Object)
6442 // [eval_from_shared]: for eval scripts the shared funcion info for the
6443 // function from which eval was called.
6444 DECL_ACCESSORS(eval_from_shared, Object)
6446 // [eval_from_instructions_offset]: the instruction offset in the code for the
6447 // function from which eval was called where eval was called.
6448 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6450 // [flags]: Holds an exciting bitfield.
6451 DECL_ACCESSORS(flags, Smi)
6453 // [source_url]: sourceURL from magic comment
6454 DECL_ACCESSORS(source_url, Object)
6456 // [source_url]: sourceMappingURL magic comment
6457 DECL_ACCESSORS(source_mapping_url, Object)
6459 // [compilation_type]: how the the script was compiled. Encoded in the
6461 inline CompilationType compilation_type();
6462 inline void set_compilation_type(CompilationType type);
6464 // [compilation_state]: determines whether the script has already been
6465 // compiled. Encoded in the 'flags' field.
6466 inline CompilationState compilation_state();
6467 inline void set_compilation_state(CompilationState state);
6469 // [is_shared_cross_origin]: An opaque boolean set by the embedder via
6470 // ScriptOrigin, and used by the embedder to make decisions about the
6471 // script's level of privilege. V8 just passes this through. Encoded in
6472 // the 'flags' field.
6473 DECL_BOOLEAN_ACCESSORS(is_shared_cross_origin)
6475 DECLARE_CAST(Script)
6477 // If script source is an external string, check that the underlying
6478 // resource is accessible. Otherwise, always return true.
6479 inline bool HasValidSource();
6481 // Convert code position into column number.
6482 static int GetColumnNumber(Handle<Script> script, int code_pos);
6484 // Convert code position into (zero-based) line number.
6485 // The non-handlified version does not allocate, but may be much slower.
6486 static int GetLineNumber(Handle<Script> script, int code_pos);
6487 int GetLineNumber(int code_pos);
6489 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6491 // Init line_ends array with code positions of line ends inside script source.
6492 static void InitLineEnds(Handle<Script> script);
6494 // Get the JS object wrapping the given script; create it if none exists.
6495 static Handle<JSObject> GetWrapper(Handle<Script> script);
6496 void ClearWrapperCache();
6498 // Dispatched behavior.
6499 DECLARE_PRINTER(Script)
6500 DECLARE_VERIFIER(Script)
6502 static const int kSourceOffset = HeapObject::kHeaderSize;
6503 static const int kNameOffset = kSourceOffset + kPointerSize;
6504 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6505 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6506 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6507 static const int kWrapperOffset = kContextOffset + kPointerSize;
6508 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6509 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6510 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6511 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6512 static const int kEvalFrominstructionsOffsetOffset =
6513 kEvalFromSharedOffset + kPointerSize;
6514 static const int kFlagsOffset =
6515 kEvalFrominstructionsOffsetOffset + kPointerSize;
6516 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6517 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6518 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6521 int GetLineNumberWithArray(int code_pos);
6523 // Bit positions in the flags field.
6524 static const int kCompilationTypeBit = 0;
6525 static const int kCompilationStateBit = 1;
6526 static const int kIsSharedCrossOriginBit = 2;
6528 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6532 // List of builtin functions we want to identify to improve code
6535 // Each entry has a name of a global object property holding an object
6536 // optionally followed by ".prototype", a name of a builtin function
6537 // on the object (the one the id is set for), and a label.
6539 // Installation of ids for the selected builtin functions is handled
6540 // by the bootstrapper.
6541 #define FUNCTIONS_WITH_ID_LIST(V) \
6542 V(Array.prototype, indexOf, ArrayIndexOf) \
6543 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6544 V(Array.prototype, push, ArrayPush) \
6545 V(Array.prototype, pop, ArrayPop) \
6546 V(Array.prototype, shift, ArrayShift) \
6547 V(Function.prototype, apply, FunctionApply) \
6548 V(String.prototype, charCodeAt, StringCharCodeAt) \
6549 V(String.prototype, charAt, StringCharAt) \
6550 V(String, fromCharCode, StringFromCharCode) \
6551 V(Math, random, MathRandom) \
6552 V(Math, floor, MathFloor) \
6553 V(Math, round, MathRound) \
6554 V(Math, ceil, MathCeil) \
6555 V(Math, abs, MathAbs) \
6556 V(Math, log, MathLog) \
6557 V(Math, exp, MathExp) \
6558 V(Math, sqrt, MathSqrt) \
6559 V(Math, pow, MathPow) \
6560 V(Math, max, MathMax) \
6561 V(Math, min, MathMin) \
6562 V(Math, cos, MathCos) \
6563 V(Math, sin, MathSin) \
6564 V(Math, tan, MathTan) \
6565 V(Math, acos, MathAcos) \
6566 V(Math, asin, MathAsin) \
6567 V(Math, atan, MathAtan) \
6568 V(Math, atan2, MathAtan2) \
6569 V(Math, imul, MathImul) \
6570 V(Math, clz32, MathClz32) \
6571 V(Math, fround, MathFround)
6573 enum BuiltinFunctionId {
6575 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6577 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6578 #undef DECLARE_FUNCTION_ID
6579 // Fake id for a special case of Math.pow. Note, it continues the
6580 // list of math functions.
6585 // SharedFunctionInfo describes the JSFunction information that can be
6586 // shared by multiple instances of the function.
6587 class SharedFunctionInfo: public HeapObject {
6589 // [name]: Function name.
6590 DECL_ACCESSORS(name, Object)
6592 // [code]: Function code.
6593 DECL_ACCESSORS(code, Code)
6594 inline void ReplaceCode(Code* code);
6596 // [optimized_code_map]: Map from native context to optimized code
6597 // and a shared literals array or Smi(0) if none.
6598 DECL_ACCESSORS(optimized_code_map, Object)
6600 // Returns index i of the entry with the specified context and OSR entry.
6601 // At position i - 1 is the context, position i the code, and i + 1 the
6602 // literals array. Returns -1 when no matching entry is found.
6603 int SearchOptimizedCodeMap(Context* native_context, BailoutId osr_ast_id);
6605 // Installs optimized code from the code map on the given closure. The
6606 // index has to be consistent with a search result as defined above.
6607 FixedArray* GetLiteralsFromOptimizedCodeMap(int index);
6609 Code* GetCodeFromOptimizedCodeMap(int index);
6611 // Clear optimized code map.
6612 void ClearOptimizedCodeMap();
6614 // Removed a specific optimized code object from the optimized code map.
6615 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6617 void ClearTypeFeedbackInfo();
6619 // Trims the optimized code map after entries have been removed.
6620 void TrimOptimizedCodeMap(int shrink_by);
6622 // Add a new entry to the optimized code map.
6623 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6624 Handle<Context> native_context,
6626 Handle<FixedArray> literals,
6627 BailoutId osr_ast_id);
6629 // Layout description of the optimized code map.
6630 static const int kNextMapIndex = 0;
6631 static const int kEntriesStart = 1;
6632 static const int kContextOffset = 0;
6633 static const int kCachedCodeOffset = 1;
6634 static const int kLiteralsOffset = 2;
6635 static const int kOsrAstIdOffset = 3;
6636 static const int kEntryLength = 4;
6637 static const int kInitialLength = kEntriesStart + kEntryLength;
6639 // [scope_info]: Scope info.
6640 DECL_ACCESSORS(scope_info, ScopeInfo)
6642 // [construct stub]: Code stub for constructing instances of this function.
6643 DECL_ACCESSORS(construct_stub, Code)
6645 // Returns if this function has been compiled to native code yet.
6646 inline bool is_compiled();
6648 // [length]: The function length - usually the number of declared parameters.
6649 // Use up to 2^30 parameters.
6650 inline int length() const;
6651 inline void set_length(int value);
6653 // [formal parameter count]: The declared number of parameters.
6654 inline int formal_parameter_count() const;
6655 inline void set_formal_parameter_count(int value);
6657 // Set the formal parameter count so the function code will be
6658 // called without using argument adaptor frames.
6659 inline void DontAdaptArguments();
6661 // [expected_nof_properties]: Expected number of properties for the function.
6662 inline int expected_nof_properties() const;
6663 inline void set_expected_nof_properties(int value);
6665 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6666 // (increasingly) from crankshafted code where sufficient feedback isn't
6668 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6670 // [instance class name]: class name for instances.
6671 DECL_ACCESSORS(instance_class_name, Object)
6673 // [function data]: This field holds some additional data for function.
6674 // Currently it either has FunctionTemplateInfo to make benefit the API
6675 // or Smi identifying a builtin function.
6676 // In the long run we don't want all functions to have this field but
6677 // we can fix that when we have a better model for storing hidden data
6679 DECL_ACCESSORS(function_data, Object)
6681 inline bool IsApiFunction();
6682 inline FunctionTemplateInfo* get_api_func_data();
6683 inline bool HasBuiltinFunctionId();
6684 inline BuiltinFunctionId builtin_function_id();
6686 // [script info]: Script from which the function originates.
6687 DECL_ACCESSORS(script, Object)
6689 // [num_literals]: Number of literals used by this function.
6690 inline int num_literals() const;
6691 inline void set_num_literals(int value);
6693 // [start_position_and_type]: Field used to store both the source code
6694 // position, whether or not the function is a function expression,
6695 // and whether or not the function is a toplevel function. The two
6696 // least significants bit indicates whether the function is an
6697 // expression and the rest contains the source code position.
6698 inline int start_position_and_type() const;
6699 inline void set_start_position_and_type(int value);
6701 // [debug info]: Debug information.
6702 DECL_ACCESSORS(debug_info, Object)
6704 // [inferred name]: Name inferred from variable or property
6705 // assignment of this function. Used to facilitate debugging and
6706 // profiling of JavaScript code written in OO style, where almost
6707 // all functions are anonymous but are assigned to object
6709 DECL_ACCESSORS(inferred_name, String)
6711 // The function's name if it is non-empty, otherwise the inferred name.
6712 String* DebugName();
6714 // Position of the 'function' token in the script source.
6715 inline int function_token_position() const;
6716 inline void set_function_token_position(int function_token_position);
6718 // Position of this function in the script source.
6719 inline int start_position() const;
6720 inline void set_start_position(int start_position);
6722 // End position of this function in the script source.
6723 inline int end_position() const;
6724 inline void set_end_position(int end_position);
6726 // Is this function a function expression in the source code.
6727 DECL_BOOLEAN_ACCESSORS(is_expression)
6729 // Is this function a top-level function (scripts, evals).
6730 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6732 // Bit field containing various information collected by the compiler to
6733 // drive optimization.
6734 inline int compiler_hints() const;
6735 inline void set_compiler_hints(int value);
6737 inline int ast_node_count() const;
6738 inline void set_ast_node_count(int count);
6740 inline int profiler_ticks() const;
6741 inline void set_profiler_ticks(int ticks);
6743 // Inline cache age is used to infer whether the function survived a context
6744 // disposal or not. In the former case we reset the opt_count.
6745 inline int ic_age();
6746 inline void set_ic_age(int age);
6748 // Indicates if this function can be lazy compiled.
6749 // This is used to determine if we can safely flush code from a function
6750 // when doing GC if we expect that the function will no longer be used.
6751 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6753 // Indicates if this function can be lazy compiled without a context.
6754 // This is used to determine if we can force compilation without reaching
6755 // the function through program execution but through other means (e.g. heap
6756 // iteration by the debugger).
6757 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6759 // Indicates whether optimizations have been disabled for this
6760 // shared function info. If a function is repeatedly optimized or if
6761 // we cannot optimize the function we disable optimization to avoid
6762 // spending time attempting to optimize it again.
6763 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6765 // Indicates the language mode.
6766 inline StrictMode strict_mode();
6767 inline void set_strict_mode(StrictMode strict_mode);
6769 // False if the function definitely does not allocate an arguments object.
6770 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6772 // True if the function has any duplicated parameter names.
6773 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6775 // Indicates whether the function is a native function.
6776 // These needs special treatment in .call and .apply since
6777 // null passed as the receiver should not be translated to the
6779 DECL_BOOLEAN_ACCESSORS(native)
6781 // Indicate that this builtin needs to be inlined in crankshaft.
6782 DECL_BOOLEAN_ACCESSORS(inline_builtin)
6784 // Indicates that the function was created by the Function function.
6785 // Though it's anonymous, toString should treat it as if it had the name
6786 // "anonymous". We don't set the name itself so that the system does not
6787 // see a binding for it.
6788 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6790 // Indicates whether the function is a bound function created using
6791 // the bind function.
6792 DECL_BOOLEAN_ACCESSORS(bound)
6794 // Indicates that the function is anonymous (the name field can be set
6795 // through the API, which does not change this flag).
6796 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6798 // Is this a function or top-level/eval code.
6799 DECL_BOOLEAN_ACCESSORS(is_function)
6801 // Indicates that code for this function cannot be cached.
6802 DECL_BOOLEAN_ACCESSORS(dont_cache)
6804 // Indicates that code for this function cannot be flushed.
6805 DECL_BOOLEAN_ACCESSORS(dont_flush)
6807 // Indicates that this function is a generator.
6808 DECL_BOOLEAN_ACCESSORS(is_generator)
6810 // Indicates that this function is an arrow function.
6811 DECL_BOOLEAN_ACCESSORS(is_arrow)
6813 // Indicates that this function is a concise method.
6814 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6816 // Indicates that this function is an asm function.
6817 DECL_BOOLEAN_ACCESSORS(asm_function)
6819 inline FunctionKind kind();
6820 inline void set_kind(FunctionKind kind);
6822 // Indicates whether or not the code in the shared function support
6824 inline bool has_deoptimization_support();
6826 // Enable deoptimization support through recompiled code.
6827 void EnableDeoptimizationSupport(Code* recompiled);
6829 // Disable (further) attempted optimization of all functions sharing this
6830 // shared function info.
6831 void DisableOptimization(BailoutReason reason);
6833 inline BailoutReason DisableOptimizationReason();
6835 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6836 // code, returns whether it asserted (i.e., always true if assertions are
6838 bool VerifyBailoutId(BailoutId id);
6840 // [source code]: Source code for the function.
6841 bool HasSourceCode() const;
6842 Handle<Object> GetSourceCode();
6844 // Number of times the function was optimized.
6845 inline int opt_count();
6846 inline void set_opt_count(int opt_count);
6848 // Number of times the function was deoptimized.
6849 inline void set_deopt_count(int value);
6850 inline int deopt_count();
6851 inline void increment_deopt_count();
6853 // Number of time we tried to re-enable optimization after it
6854 // was disabled due to high number of deoptimizations.
6855 inline void set_opt_reenable_tries(int value);
6856 inline int opt_reenable_tries();
6858 inline void TryReenableOptimization();
6860 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6861 inline void set_counters(int value);
6862 inline int counters() const;
6864 // Stores opt_count and bailout_reason as bit-fields.
6865 inline void set_opt_count_and_bailout_reason(int value);
6866 inline int opt_count_and_bailout_reason() const;
6868 void set_bailout_reason(BailoutReason reason) {
6869 set_opt_count_and_bailout_reason(
6870 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6874 // Check whether or not this function is inlineable.
6875 bool IsInlineable();
6877 // Source size of this function.
6880 // Calculate the instance size.
6881 int CalculateInstanceSize();
6883 // Calculate the number of in-object properties.
6884 int CalculateInObjectProperties();
6886 // Dispatched behavior.
6887 DECLARE_PRINTER(SharedFunctionInfo)
6888 DECLARE_VERIFIER(SharedFunctionInfo)
6890 void ResetForNewContext(int new_ic_age);
6892 DECLARE_CAST(SharedFunctionInfo)
6895 static const int kDontAdaptArgumentsSentinel = -1;
6897 // Layout description.
6899 static const int kNameOffset = HeapObject::kHeaderSize;
6900 static const int kCodeOffset = kNameOffset + kPointerSize;
6901 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6902 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6903 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6904 static const int kInstanceClassNameOffset =
6905 kConstructStubOffset + kPointerSize;
6906 static const int kFunctionDataOffset =
6907 kInstanceClassNameOffset + kPointerSize;
6908 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6909 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6910 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6911 static const int kFeedbackVectorOffset =
6912 kInferredNameOffset + kPointerSize;
6913 #if V8_HOST_ARCH_32_BIT
6915 static const int kLengthOffset =
6916 kFeedbackVectorOffset + kPointerSize;
6917 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6918 static const int kExpectedNofPropertiesOffset =
6919 kFormalParameterCountOffset + kPointerSize;
6920 static const int kNumLiteralsOffset =
6921 kExpectedNofPropertiesOffset + kPointerSize;
6922 static const int kStartPositionAndTypeOffset =
6923 kNumLiteralsOffset + kPointerSize;
6924 static const int kEndPositionOffset =
6925 kStartPositionAndTypeOffset + kPointerSize;
6926 static const int kFunctionTokenPositionOffset =
6927 kEndPositionOffset + kPointerSize;
6928 static const int kCompilerHintsOffset =
6929 kFunctionTokenPositionOffset + kPointerSize;
6930 static const int kOptCountAndBailoutReasonOffset =
6931 kCompilerHintsOffset + kPointerSize;
6932 static const int kCountersOffset =
6933 kOptCountAndBailoutReasonOffset + kPointerSize;
6934 static const int kAstNodeCountOffset =
6935 kCountersOffset + kPointerSize;
6936 static const int kProfilerTicksOffset =
6937 kAstNodeCountOffset + kPointerSize;
6940 static const int kSize = kProfilerTicksOffset + kPointerSize;
6942 // The only reason to use smi fields instead of int fields
6943 // is to allow iteration without maps decoding during
6944 // garbage collections.
6945 // To avoid wasting space on 64-bit architectures we use
6946 // the following trick: we group integer fields into pairs
6947 // The least significant integer in each pair is shifted left by 1.
6948 // By doing this we guarantee that LSB of each kPointerSize aligned
6949 // word is not set and thus this word cannot be treated as pointer
6950 // to HeapObject during old space traversal.
6951 #if V8_TARGET_LITTLE_ENDIAN
6952 static const int kLengthOffset =
6953 kFeedbackVectorOffset + kPointerSize;
6954 static const int kFormalParameterCountOffset =
6955 kLengthOffset + kIntSize;
6957 static const int kExpectedNofPropertiesOffset =
6958 kFormalParameterCountOffset + kIntSize;
6959 static const int kNumLiteralsOffset =
6960 kExpectedNofPropertiesOffset + kIntSize;
6962 static const int kEndPositionOffset =
6963 kNumLiteralsOffset + kIntSize;
6964 static const int kStartPositionAndTypeOffset =
6965 kEndPositionOffset + kIntSize;
6967 static const int kFunctionTokenPositionOffset =
6968 kStartPositionAndTypeOffset + kIntSize;
6969 static const int kCompilerHintsOffset =
6970 kFunctionTokenPositionOffset + kIntSize;
6972 static const int kOptCountAndBailoutReasonOffset =
6973 kCompilerHintsOffset + kIntSize;
6974 static const int kCountersOffset =
6975 kOptCountAndBailoutReasonOffset + kIntSize;
6977 static const int kAstNodeCountOffset =
6978 kCountersOffset + kIntSize;
6979 static const int kProfilerTicksOffset =
6980 kAstNodeCountOffset + kIntSize;
6983 static const int kSize = kProfilerTicksOffset + kIntSize;
6985 #elif V8_TARGET_BIG_ENDIAN
6986 static const int kFormalParameterCountOffset =
6987 kFeedbackVectorOffset + kPointerSize;
6988 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6990 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6991 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6993 static const int kStartPositionAndTypeOffset =
6994 kExpectedNofPropertiesOffset + kIntSize;
6995 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6997 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6998 static const int kFunctionTokenPositionOffset =
6999 kCompilerHintsOffset + kIntSize;
7001 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7002 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7004 static const int kProfilerTicksOffset =
7005 kOptCountAndBailoutReasonOffset + kIntSize;
7006 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7009 static const int kSize = kAstNodeCountOffset + kIntSize;
7012 #error Unknown byte ordering
7013 #endif // Big endian
7017 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7019 typedef FixedBodyDescriptor<kNameOffset,
7020 kFeedbackVectorOffset + kPointerSize,
7021 kSize> BodyDescriptor;
7023 // Bit positions in start_position_and_type.
7024 // The source code start position is in the 30 most significant bits of
7025 // the start_position_and_type field.
7026 static const int kIsExpressionBit = 0;
7027 static const int kIsTopLevelBit = 1;
7028 static const int kStartPositionShift = 2;
7029 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7031 // Bit positions in compiler_hints.
7032 enum CompilerHints {
7033 kAllowLazyCompilation,
7034 kAllowLazyCompilationWithoutContext,
7035 kOptimizationDisabled,
7036 kStrictModeFunction,
7038 kHasDuplicateParameters,
7043 kNameShouldPrintAsAnonymous,
7051 kCompilerHintsCount // Pseudo entry
7054 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 3> {};
7056 class DeoptCountBits : public BitField<int, 0, 4> {};
7057 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7058 class ICAgeBits : public BitField<int, 22, 8> {};
7060 class OptCountBits : public BitField<int, 0, 22> {};
7061 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7064 #if V8_HOST_ARCH_32_BIT
7065 // On 32 bit platforms, compiler hints is a smi.
7066 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7067 static const int kCompilerHintsSize = kPointerSize;
7069 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7070 static const int kCompilerHintsSmiTagSize = 0;
7071 static const int kCompilerHintsSize = kIntSize;
7074 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7075 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7078 // Constants for optimizing codegen for strict mode function and
7080 // Allows to use byte-width instructions.
7081 static const int kStrictModeBitWithinByte =
7082 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7084 static const int kNativeBitWithinByte =
7085 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7087 #if defined(V8_TARGET_LITTLE_ENDIAN)
7088 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7089 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7090 static const int kNativeByteOffset = kCompilerHintsOffset +
7091 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7092 #elif defined(V8_TARGET_BIG_ENDIAN)
7093 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7094 (kCompilerHintsSize - 1) -
7095 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7096 static const int kNativeByteOffset = kCompilerHintsOffset +
7097 (kCompilerHintsSize - 1) -
7098 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7100 #error Unknown byte ordering
7104 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7108 // Printing support.
7109 struct SourceCodeOf {
7110 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7111 : value(v), max_length(max) {}
7112 const SharedFunctionInfo* value;
7117 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7120 class JSGeneratorObject: public JSObject {
7122 // [function]: The function corresponding to this generator object.
7123 DECL_ACCESSORS(function, JSFunction)
7125 // [context]: The context of the suspended computation.
7126 DECL_ACCESSORS(context, Context)
7128 // [receiver]: The receiver of the suspended computation.
7129 DECL_ACCESSORS(receiver, Object)
7131 // [continuation]: Offset into code of continuation.
7133 // A positive offset indicates a suspended generator. The special
7134 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7135 // cannot be resumed.
7136 inline int continuation() const;
7137 inline void set_continuation(int continuation);
7138 inline bool is_closed();
7139 inline bool is_executing();
7140 inline bool is_suspended();
7142 // [operand_stack]: Saved operand stack.
7143 DECL_ACCESSORS(operand_stack, FixedArray)
7145 // [stack_handler_index]: Index of first stack handler in operand_stack, or -1
7146 // if the captured activation had no stack handler.
7147 inline int stack_handler_index() const;
7148 inline void set_stack_handler_index(int stack_handler_index);
7150 DECLARE_CAST(JSGeneratorObject)
7152 // Dispatched behavior.
7153 DECLARE_PRINTER(JSGeneratorObject)
7154 DECLARE_VERIFIER(JSGeneratorObject)
7156 // Magic sentinel values for the continuation.
7157 static const int kGeneratorExecuting = -1;
7158 static const int kGeneratorClosed = 0;
7160 // Layout description.
7161 static const int kFunctionOffset = JSObject::kHeaderSize;
7162 static const int kContextOffset = kFunctionOffset + kPointerSize;
7163 static const int kReceiverOffset = kContextOffset + kPointerSize;
7164 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7165 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7166 static const int kStackHandlerIndexOffset =
7167 kOperandStackOffset + kPointerSize;
7168 static const int kSize = kStackHandlerIndexOffset + kPointerSize;
7170 // Resume mode, for use by runtime functions.
7171 enum ResumeMode { NEXT, THROW };
7173 // Yielding from a generator returns an object with the following inobject
7174 // properties. See Context::iterator_result_map() for the map.
7175 static const int kResultValuePropertyIndex = 0;
7176 static const int kResultDonePropertyIndex = 1;
7177 static const int kResultPropertyCount = 2;
7179 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7180 static const int kResultDonePropertyOffset =
7181 kResultValuePropertyOffset + kPointerSize;
7182 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7185 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7189 // Representation for module instance objects.
7190 class JSModule: public JSObject {
7192 // [context]: the context holding the module's locals, or undefined if none.
7193 DECL_ACCESSORS(context, Object)
7195 // [scope_info]: Scope info.
7196 DECL_ACCESSORS(scope_info, ScopeInfo)
7198 DECLARE_CAST(JSModule)
7200 // Dispatched behavior.
7201 DECLARE_PRINTER(JSModule)
7202 DECLARE_VERIFIER(JSModule)
7204 // Layout description.
7205 static const int kContextOffset = JSObject::kHeaderSize;
7206 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7207 static const int kSize = kScopeInfoOffset + kPointerSize;
7210 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7214 // JSFunction describes JavaScript functions.
7215 class JSFunction: public JSObject {
7217 // [prototype_or_initial_map]:
7218 DECL_ACCESSORS(prototype_or_initial_map, Object)
7220 // [shared]: The information about the function that
7221 // can be shared by instances.
7222 DECL_ACCESSORS(shared, SharedFunctionInfo)
7224 // [context]: The context for this function.
7225 inline Context* context();
7226 inline void set_context(Object* context);
7227 inline JSObject* global_proxy();
7229 // [code]: The generated code object for this function. Executed
7230 // when the function is invoked, e.g. foo() or new foo(). See
7231 // [[Call]] and [[Construct]] description in ECMA-262, section
7233 inline Code* code();
7234 inline void set_code(Code* code);
7235 inline void set_code_no_write_barrier(Code* code);
7236 inline void ReplaceCode(Code* code);
7238 // Tells whether this function is builtin.
7239 inline bool IsBuiltin();
7241 // Tells whether this function is defined in a native script.
7242 inline bool IsFromNativeScript();
7244 // Tells whether this function is defined in an extension script.
7245 inline bool IsFromExtensionScript();
7247 // Tells whether or not the function needs arguments adaption.
7248 inline bool NeedsArgumentsAdaption();
7250 // Tells whether or not this function has been optimized.
7251 inline bool IsOptimized();
7253 // Tells whether or not this function can be optimized.
7254 inline bool IsOptimizable();
7256 // Mark this function for lazy recompilation. The function will be
7257 // recompiled the next time it is executed.
7258 void MarkForOptimization();
7259 void MarkForConcurrentOptimization();
7260 void MarkInOptimizationQueue();
7262 // Tells whether or not the function is already marked for lazy
7264 inline bool IsMarkedForOptimization();
7265 inline bool IsMarkedForConcurrentOptimization();
7267 // Tells whether or not the function is on the concurrent recompilation queue.
7268 inline bool IsInOptimizationQueue();
7270 // Inobject slack tracking is the way to reclaim unused inobject space.
7272 // The instance size is initially determined by adding some slack to
7273 // expected_nof_properties (to allow for a few extra properties added
7274 // after the constructor). There is no guarantee that the extra space
7275 // will not be wasted.
7277 // Here is the algorithm to reclaim the unused inobject space:
7278 // - Detect the first constructor call for this JSFunction.
7279 // When it happens enter the "in progress" state: initialize construction
7280 // counter in the initial_map and set the |done_inobject_slack_tracking|
7282 // - While the tracking is in progress create objects filled with
7283 // one_pointer_filler_map instead of undefined_value. This way they can be
7284 // resized quickly and safely.
7285 // - Once enough (kGenerousAllocationCount) objects have been created
7286 // compute the 'slack' (traverse the map transition tree starting from the
7287 // initial_map and find the lowest value of unused_property_fields).
7288 // - Traverse the transition tree again and decrease the instance size
7289 // of every map. Existing objects will resize automatically (they are
7290 // filled with one_pointer_filler_map). All further allocations will
7291 // use the adjusted instance size.
7292 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7293 // allocations made using different closures could actually create different
7294 // kind of objects (see prototype inheritance pattern).
7296 // Important: inobject slack tracking is not attempted during the snapshot
7299 static const int kGenerousAllocationCount = Map::ConstructionCount::kMax;
7300 static const int kFinishSlackTracking = 1;
7301 static const int kNoSlackTracking = 0;
7303 // True if the initial_map is set and the object constructions countdown
7304 // counter is not zero.
7305 inline bool IsInobjectSlackTrackingInProgress();
7307 // Starts the tracking.
7308 // Initializes object constructions countdown counter in the initial map.
7309 // IsInobjectSlackTrackingInProgress is normally true after this call,
7310 // except when tracking have not been started (e.g. the map has no unused
7311 // properties or the snapshot is being built).
7312 void StartInobjectSlackTracking();
7314 // Completes the tracking.
7315 // IsInobjectSlackTrackingInProgress is false after this call.
7316 void CompleteInobjectSlackTracking();
7318 // [literals_or_bindings]: Fixed array holding either
7319 // the materialized literals or the bindings of a bound function.
7321 // If the function contains object, regexp or array literals, the
7322 // literals array prefix contains the object, regexp, and array
7323 // function to be used when creating these literals. This is
7324 // necessary so that we do not dynamically lookup the object, regexp
7325 // or array functions. Performing a dynamic lookup, we might end up
7326 // using the functions from a new context that we should not have
7329 // On bound functions, the array is a (copy-on-write) fixed-array containing
7330 // the function that was bound, bound this-value and any bound
7331 // arguments. Bound functions never contain literals.
7332 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7334 inline FixedArray* literals();
7335 inline void set_literals(FixedArray* literals);
7337 inline FixedArray* function_bindings();
7338 inline void set_function_bindings(FixedArray* bindings);
7340 // The initial map for an object created by this constructor.
7341 inline Map* initial_map();
7342 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7343 Handle<Object> prototype);
7344 inline bool has_initial_map();
7345 static void EnsureHasInitialMap(Handle<JSFunction> function);
7347 // Get and set the prototype property on a JSFunction. If the
7348 // function has an initial map the prototype is set on the initial
7349 // map. Otherwise, the prototype is put in the initial map field
7350 // until an initial map is needed.
7351 inline bool has_prototype();
7352 inline bool has_instance_prototype();
7353 inline Object* prototype();
7354 inline Object* instance_prototype();
7355 static void SetPrototype(Handle<JSFunction> function,
7356 Handle<Object> value);
7357 static void SetInstancePrototype(Handle<JSFunction> function,
7358 Handle<Object> value);
7360 // Creates a new closure for the fucntion with the same bindings,
7361 // bound values, and prototype. An equivalent of spec operations
7362 // ``CloneMethod`` and ``CloneBoundFunction``.
7363 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7365 // After prototype is removed, it will not be created when accessed, and
7366 // [[Construct]] from this function will not be allowed.
7367 bool RemovePrototype();
7368 inline bool should_have_prototype();
7370 // Accessor for this function's initial map's [[class]]
7371 // property. This is primarily used by ECMA native functions. This
7372 // method sets the class_name field of this function's initial map
7373 // to a given value. It creates an initial map if this function does
7374 // not have one. Note that this method does not copy the initial map
7375 // if it has one already, but simply replaces it with the new value.
7376 // Instances created afterwards will have a map whose [[class]] is
7377 // set to 'value', but there is no guarantees on instances created
7379 void SetInstanceClassName(String* name);
7381 // Returns if this function has been compiled to native code yet.
7382 inline bool is_compiled();
7384 // [next_function_link]: Links functions into various lists, e.g. the list
7385 // of optimized functions hanging off the native_context. The CodeFlusher
7386 // uses this link to chain together flushing candidates. Treated weakly
7387 // by the garbage collector.
7388 DECL_ACCESSORS(next_function_link, Object)
7390 // Prints the name of the function using PrintF.
7391 void PrintName(FILE* out = stdout);
7393 DECLARE_CAST(JSFunction)
7395 // Iterates the objects, including code objects indirectly referenced
7396 // through pointers to the first instruction in the code object.
7397 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7399 // Dispatched behavior.
7400 DECLARE_PRINTER(JSFunction)
7401 DECLARE_VERIFIER(JSFunction)
7403 // Returns the number of allocated literals.
7404 inline int NumberOfLiterals();
7406 // Retrieve the native context from a function's literal array.
7407 static Context* NativeContextFromLiterals(FixedArray* literals);
7409 // Used for flags such as --hydrogen-filter.
7410 bool PassesFilter(const char* raw_filter);
7412 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7413 // kSize) is weak and has special handling during garbage collection.
7414 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7415 static const int kPrototypeOrInitialMapOffset =
7416 kCodeEntryOffset + kPointerSize;
7417 static const int kSharedFunctionInfoOffset =
7418 kPrototypeOrInitialMapOffset + kPointerSize;
7419 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7420 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7421 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7422 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7423 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7425 // Layout of the literals array.
7426 static const int kLiteralsPrefixSize = 1;
7427 static const int kLiteralNativeContextIndex = 0;
7429 // Layout of the bound-function binding array.
7430 static const int kBoundFunctionIndex = 0;
7431 static const int kBoundThisIndex = 1;
7432 static const int kBoundArgumentsStartIndex = 2;
7435 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7439 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7440 // and the prototype is hidden. JSGlobalProxy always delegates
7441 // property accesses to its prototype if the prototype is not null.
7443 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7445 // Accessing a JSGlobalProxy requires security check.
7447 class JSGlobalProxy : public JSObject {
7449 // [native_context]: the owner native context of this global proxy object.
7450 // It is null value if this object is not used by any context.
7451 DECL_ACCESSORS(native_context, Object)
7453 // [hash]: The hash code property (undefined if not initialized yet).
7454 DECL_ACCESSORS(hash, Object)
7456 DECLARE_CAST(JSGlobalProxy)
7458 inline bool IsDetachedFrom(GlobalObject* global) const;
7460 // Dispatched behavior.
7461 DECLARE_PRINTER(JSGlobalProxy)
7462 DECLARE_VERIFIER(JSGlobalProxy)
7464 // Layout description.
7465 static const int kNativeContextOffset = JSObject::kHeaderSize;
7466 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7467 static const int kSize = kHashOffset + kPointerSize;
7470 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7474 // Forward declaration.
7475 class JSBuiltinsObject;
7477 // Common super class for JavaScript global objects and the special
7478 // builtins global objects.
7479 class GlobalObject: public JSObject {
7481 // [builtins]: the object holding the runtime routines written in JS.
7482 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7484 // [native context]: the natives corresponding to this global object.
7485 DECL_ACCESSORS(native_context, Context)
7487 // [global context]: the most recent (i.e. innermost) global context.
7488 DECL_ACCESSORS(global_context, Context)
7490 // [global proxy]: the global proxy object of the context
7491 DECL_ACCESSORS(global_proxy, JSObject)
7493 DECLARE_CAST(GlobalObject)
7495 // Layout description.
7496 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7497 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7498 static const int kGlobalContextOffset = kNativeContextOffset + kPointerSize;
7499 static const int kGlobalProxyOffset = kGlobalContextOffset + kPointerSize;
7500 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7503 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7507 // JavaScript global object.
7508 class JSGlobalObject: public GlobalObject {
7510 DECLARE_CAST(JSGlobalObject)
7512 // Ensure that the global object has a cell for the given property name.
7513 static Handle<PropertyCell> EnsurePropertyCell(Handle<JSGlobalObject> global,
7516 inline bool IsDetached();
7518 // Dispatched behavior.
7519 DECLARE_PRINTER(JSGlobalObject)
7520 DECLARE_VERIFIER(JSGlobalObject)
7522 // Layout description.
7523 static const int kSize = GlobalObject::kHeaderSize;
7526 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7530 // Builtins global object which holds the runtime routines written in
7532 class JSBuiltinsObject: public GlobalObject {
7534 // Accessors for the runtime routines written in JavaScript.
7535 inline Object* javascript_builtin(Builtins::JavaScript id);
7536 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7538 // Accessors for code of the runtime routines written in JavaScript.
7539 inline Code* javascript_builtin_code(Builtins::JavaScript id);
7540 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
7542 DECLARE_CAST(JSBuiltinsObject)
7544 // Dispatched behavior.
7545 DECLARE_PRINTER(JSBuiltinsObject)
7546 DECLARE_VERIFIER(JSBuiltinsObject)
7548 // Layout description. The size of the builtins object includes
7549 // room for two pointers per runtime routine written in javascript
7550 // (function and code object).
7551 static const int kJSBuiltinsCount = Builtins::id_count;
7552 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7553 static const int kJSBuiltinsCodeOffset =
7554 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7555 static const int kSize =
7556 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
7558 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7559 return kJSBuiltinsOffset + id * kPointerSize;
7562 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
7563 return kJSBuiltinsCodeOffset + id * kPointerSize;
7567 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7571 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7572 class JSValue: public JSObject {
7574 // [value]: the object being wrapped.
7575 DECL_ACCESSORS(value, Object)
7577 DECLARE_CAST(JSValue)
7579 // Dispatched behavior.
7580 DECLARE_PRINTER(JSValue)
7581 DECLARE_VERIFIER(JSValue)
7583 // Layout description.
7584 static const int kValueOffset = JSObject::kHeaderSize;
7585 static const int kSize = kValueOffset + kPointerSize;
7588 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7594 // Representation for JS date objects.
7595 class JSDate: public JSObject {
7597 // If one component is NaN, all of them are, indicating a NaN time value.
7598 // [value]: the time value.
7599 DECL_ACCESSORS(value, Object)
7600 // [year]: caches year. Either undefined, smi, or NaN.
7601 DECL_ACCESSORS(year, Object)
7602 // [month]: caches month. Either undefined, smi, or NaN.
7603 DECL_ACCESSORS(month, Object)
7604 // [day]: caches day. Either undefined, smi, or NaN.
7605 DECL_ACCESSORS(day, Object)
7606 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7607 DECL_ACCESSORS(weekday, Object)
7608 // [hour]: caches hours. Either undefined, smi, or NaN.
7609 DECL_ACCESSORS(hour, Object)
7610 // [min]: caches minutes. Either undefined, smi, or NaN.
7611 DECL_ACCESSORS(min, Object)
7612 // [sec]: caches seconds. Either undefined, smi, or NaN.
7613 DECL_ACCESSORS(sec, Object)
7614 // [cache stamp]: sample of the date cache stamp at the
7615 // moment when chached fields were cached.
7616 DECL_ACCESSORS(cache_stamp, Object)
7618 DECLARE_CAST(JSDate)
7620 // Returns the date field with the specified index.
7621 // See FieldIndex for the list of date fields.
7622 static Object* GetField(Object* date, Smi* index);
7624 void SetValue(Object* value, bool is_value_nan);
7627 // Dispatched behavior.
7628 DECLARE_PRINTER(JSDate)
7629 DECLARE_VERIFIER(JSDate)
7631 // The order is important. It must be kept in sync with date macros
7642 kFirstUncachedField,
7643 kMillisecond = kFirstUncachedField,
7647 kYearUTC = kFirstUTCField,
7660 // Layout description.
7661 static const int kValueOffset = JSObject::kHeaderSize;
7662 static const int kYearOffset = kValueOffset + kPointerSize;
7663 static const int kMonthOffset = kYearOffset + kPointerSize;
7664 static const int kDayOffset = kMonthOffset + kPointerSize;
7665 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7666 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7667 static const int kMinOffset = kHourOffset + kPointerSize;
7668 static const int kSecOffset = kMinOffset + kPointerSize;
7669 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7670 static const int kSize = kCacheStampOffset + kPointerSize;
7673 inline Object* DoGetField(FieldIndex index);
7675 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7677 // Computes and caches the cacheable fields of the date.
7678 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7681 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7685 // Representation of message objects used for error reporting through
7686 // the API. The messages are formatted in JavaScript so this object is
7687 // a real JavaScript object. The information used for formatting the
7688 // error messages are not directly accessible from JavaScript to
7689 // prevent leaking information to user code called during error
7691 class JSMessageObject: public JSObject {
7693 // [type]: the type of error message.
7694 DECL_ACCESSORS(type, String)
7696 // [arguments]: the arguments for formatting the error message.
7697 DECL_ACCESSORS(arguments, JSArray)
7699 // [script]: the script from which the error message originated.
7700 DECL_ACCESSORS(script, Object)
7702 // [stack_frames]: an array of stack frames for this error object.
7703 DECL_ACCESSORS(stack_frames, Object)
7705 // [start_position]: the start position in the script for the error message.
7706 inline int start_position() const;
7707 inline void set_start_position(int value);
7709 // [end_position]: the end position in the script for the error message.
7710 inline int end_position() const;
7711 inline void set_end_position(int value);
7713 DECLARE_CAST(JSMessageObject)
7715 // Dispatched behavior.
7716 DECLARE_PRINTER(JSMessageObject)
7717 DECLARE_VERIFIER(JSMessageObject)
7719 // Layout description.
7720 static const int kTypeOffset = JSObject::kHeaderSize;
7721 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7722 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7723 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7724 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7725 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7726 static const int kSize = kEndPositionOffset + kPointerSize;
7728 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7729 kStackFramesOffset + kPointerSize,
7730 kSize> BodyDescriptor;
7734 // Regular expressions
7735 // The regular expression holds a single reference to a FixedArray in
7736 // the kDataOffset field.
7737 // The FixedArray contains the following data:
7738 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7739 // - reference to the original source string
7740 // - reference to the original flag string
7741 // If it is an atom regexp
7742 // - a reference to a literal string to search for
7743 // If it is an irregexp regexp:
7744 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7745 // used for tracking the last usage (used for code flushing).
7746 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7747 // used for tracking the last usage (used for code flushing)..
7748 // - max number of registers used by irregexp implementations.
7749 // - number of capture registers (output values) of the regexp.
7750 class JSRegExp: public JSObject {
7753 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7754 // ATOM: A simple string to match against using an indexOf operation.
7755 // IRREGEXP: Compiled with Irregexp.
7756 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7757 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7768 explicit Flags(uint32_t value) : value_(value) { }
7769 bool is_global() { return (value_ & GLOBAL) != 0; }
7770 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7771 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7772 bool is_sticky() { return (value_ & STICKY) != 0; }
7773 uint32_t value() { return value_; }
7778 DECL_ACCESSORS(data, Object)
7780 inline Type TypeTag();
7781 inline int CaptureCount();
7782 inline Flags GetFlags();
7783 inline String* Pattern();
7784 inline Object* DataAt(int index);
7785 // Set implementation data after the object has been prepared.
7786 inline void SetDataAt(int index, Object* value);
7788 static int code_index(bool is_latin1) {
7790 return kIrregexpLatin1CodeIndex;
7792 return kIrregexpUC16CodeIndex;
7796 static int saved_code_index(bool is_latin1) {
7798 return kIrregexpLatin1CodeSavedIndex;
7800 return kIrregexpUC16CodeSavedIndex;
7804 DECLARE_CAST(JSRegExp)
7806 // Dispatched behavior.
7807 DECLARE_VERIFIER(JSRegExp)
7809 static const int kDataOffset = JSObject::kHeaderSize;
7810 static const int kSize = kDataOffset + kPointerSize;
7812 // Indices in the data array.
7813 static const int kTagIndex = 0;
7814 static const int kSourceIndex = kTagIndex + 1;
7815 static const int kFlagsIndex = kSourceIndex + 1;
7816 static const int kDataIndex = kFlagsIndex + 1;
7817 // The data fields are used in different ways depending on the
7818 // value of the tag.
7819 // Atom regexps (literal strings).
7820 static const int kAtomPatternIndex = kDataIndex;
7822 static const int kAtomDataSize = kAtomPatternIndex + 1;
7824 // Irregexp compiled code or bytecode for Latin1. If compilation
7825 // fails, this fields hold an exception object that should be
7826 // thrown if the regexp is used again.
7827 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7828 // Irregexp compiled code or bytecode for UC16. If compilation
7829 // fails, this fields hold an exception object that should be
7830 // thrown if the regexp is used again.
7831 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7833 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7834 // is a potential candidate for flushing.
7835 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7836 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7837 // a potential candidate for flushing.
7838 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7840 // Maximal number of registers used by either Latin1 or UC16.
7841 // Only used to check that there is enough stack space
7842 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7843 // Number of captures in the compiled regexp.
7844 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7846 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7848 // Offsets directly into the data fixed array.
7849 static const int kDataTagOffset =
7850 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7851 static const int kDataOneByteCodeOffset =
7852 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7853 static const int kDataUC16CodeOffset =
7854 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7855 static const int kIrregexpCaptureCountOffset =
7856 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7858 // In-object fields.
7859 static const int kSourceFieldIndex = 0;
7860 static const int kGlobalFieldIndex = 1;
7861 static const int kIgnoreCaseFieldIndex = 2;
7862 static const int kMultilineFieldIndex = 3;
7863 static const int kLastIndexFieldIndex = 4;
7864 static const int kInObjectFieldCount = 5;
7866 // The uninitialized value for a regexp code object.
7867 static const int kUninitializedValue = -1;
7869 // The compilation error value for the regexp code object. The real error
7870 // object is in the saved code field.
7871 static const int kCompilationErrorValue = -2;
7873 // When we store the sweep generation at which we moved the code from the
7874 // code index to the saved code index we mask it of to be in the [0:255]
7876 static const int kCodeAgeMask = 0xff;
7880 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7882 static inline bool IsMatch(HashTableKey* key, Object* value) {
7883 return key->IsMatch(value);
7886 static inline uint32_t Hash(HashTableKey* key) {
7890 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7891 return key->HashForObject(object);
7894 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7896 static const int kPrefixSize = 0;
7897 static const int kEntrySize = 2;
7901 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7902 CompilationCacheShape,
7905 // Find cached value for a string key, otherwise return null.
7906 Handle<Object> Lookup(Handle<String> src, Handle<Context> context);
7907 Handle<Object> LookupEval(Handle<String> src, Handle<Context> context,
7908 StrictMode strict_mode, int scope_position);
7909 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7910 static Handle<CompilationCacheTable> Put(
7911 Handle<CompilationCacheTable> cache, Handle<String> src,
7912 Handle<Context> context, Handle<Object> value);
7913 static Handle<CompilationCacheTable> PutEval(
7914 Handle<CompilationCacheTable> cache, Handle<String> src,
7915 Handle<Context> context, Handle<SharedFunctionInfo> value,
7916 int scope_position);
7917 static Handle<CompilationCacheTable> PutRegExp(
7918 Handle<CompilationCacheTable> cache, Handle<String> src,
7919 JSRegExp::Flags flags, Handle<FixedArray> value);
7920 void Remove(Object* value);
7922 DECLARE_CAST(CompilationCacheTable)
7925 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7929 class CodeCache: public Struct {
7931 DECL_ACCESSORS(default_cache, FixedArray)
7932 DECL_ACCESSORS(normal_type_cache, Object)
7934 // Add the code object to the cache.
7936 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7938 // Lookup code object in the cache. Returns code object if found and undefined
7940 Object* Lookup(Name* name, Code::Flags flags);
7942 // Get the internal index of a code object in the cache. Returns -1 if the
7943 // code object is not in that cache. This index can be used to later call
7944 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7946 int GetIndex(Object* name, Code* code);
7948 // Remove an object from the cache with the provided internal index.
7949 void RemoveByIndex(Object* name, Code* code, int index);
7951 DECLARE_CAST(CodeCache)
7953 // Dispatched behavior.
7954 DECLARE_PRINTER(CodeCache)
7955 DECLARE_VERIFIER(CodeCache)
7957 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7958 static const int kNormalTypeCacheOffset =
7959 kDefaultCacheOffset + kPointerSize;
7960 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7963 static void UpdateDefaultCache(
7964 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7965 static void UpdateNormalTypeCache(
7966 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7967 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7968 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7970 // Code cache layout of the default cache. Elements are alternating name and
7971 // code objects for non normal load/store/call IC's.
7972 static const int kCodeCacheEntrySize = 2;
7973 static const int kCodeCacheEntryNameOffset = 0;
7974 static const int kCodeCacheEntryCodeOffset = 1;
7976 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7980 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7982 static inline bool IsMatch(HashTableKey* key, Object* value) {
7983 return key->IsMatch(value);
7986 static inline uint32_t Hash(HashTableKey* key) {
7990 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7991 return key->HashForObject(object);
7994 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7996 static const int kPrefixSize = 0;
7997 static const int kEntrySize = 2;
8001 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8002 CodeCacheHashTableShape,
8005 Object* Lookup(Name* name, Code::Flags flags);
8006 static Handle<CodeCacheHashTable> Put(
8007 Handle<CodeCacheHashTable> table,
8011 int GetIndex(Name* name, Code::Flags flags);
8012 void RemoveByIndex(int index);
8014 DECLARE_CAST(CodeCacheHashTable)
8016 // Initial size of the fixed array backing the hash table.
8017 static const int kInitialSize = 64;
8020 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8024 class PolymorphicCodeCache: public Struct {
8026 DECL_ACCESSORS(cache, Object)
8028 static void Update(Handle<PolymorphicCodeCache> cache,
8029 MapHandleList* maps,
8034 // Returns an undefined value if the entry is not found.
8035 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8037 DECLARE_CAST(PolymorphicCodeCache)
8039 // Dispatched behavior.
8040 DECLARE_PRINTER(PolymorphicCodeCache)
8041 DECLARE_VERIFIER(PolymorphicCodeCache)
8043 static const int kCacheOffset = HeapObject::kHeaderSize;
8044 static const int kSize = kCacheOffset + kPointerSize;
8047 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8051 class PolymorphicCodeCacheHashTable
8052 : public HashTable<PolymorphicCodeCacheHashTable,
8053 CodeCacheHashTableShape,
8056 Object* Lookup(MapHandleList* maps, int code_kind);
8058 static Handle<PolymorphicCodeCacheHashTable> Put(
8059 Handle<PolymorphicCodeCacheHashTable> hash_table,
8060 MapHandleList* maps,
8064 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8066 static const int kInitialSize = 64;
8068 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8072 class TypeFeedbackInfo: public Struct {
8074 inline int ic_total_count();
8075 inline void set_ic_total_count(int count);
8077 inline int ic_with_type_info_count();
8078 inline void change_ic_with_type_info_count(int delta);
8080 inline int ic_generic_count();
8081 inline void change_ic_generic_count(int delta);
8083 inline void initialize_storage();
8085 inline void change_own_type_change_checksum();
8086 inline int own_type_change_checksum();
8088 inline void set_inlined_type_change_checksum(int checksum);
8089 inline bool matches_inlined_type_change_checksum(int checksum);
8092 DECLARE_CAST(TypeFeedbackInfo)
8094 // Dispatched behavior.
8095 DECLARE_PRINTER(TypeFeedbackInfo)
8096 DECLARE_VERIFIER(TypeFeedbackInfo)
8098 static const int kStorage1Offset = HeapObject::kHeaderSize;
8099 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8100 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8101 static const int kSize = kStorage3Offset + kPointerSize;
8104 static const int kTypeChangeChecksumBits = 7;
8106 class ICTotalCountField: public BitField<int, 0,
8107 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8108 class OwnTypeChangeChecksum: public BitField<int,
8109 kSmiValueSize - kTypeChangeChecksumBits,
8110 kTypeChangeChecksumBits> {}; // NOLINT
8111 class ICsWithTypeInfoCountField: public BitField<int, 0,
8112 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8113 class InlinedTypeChangeChecksum: public BitField<int,
8114 kSmiValueSize - kTypeChangeChecksumBits,
8115 kTypeChangeChecksumBits> {}; // NOLINT
8117 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8121 enum AllocationSiteMode {
8122 DONT_TRACK_ALLOCATION_SITE,
8123 TRACK_ALLOCATION_SITE,
8124 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8128 class AllocationSite: public Struct {
8130 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8131 static const double kPretenureRatio;
8132 static const int kPretenureMinimumCreated = 100;
8134 // Values for pretenure decision field.
8135 enum PretenureDecision {
8141 kLastPretenureDecisionValue = kZombie
8144 const char* PretenureDecisionName(PretenureDecision decision);
8146 DECL_ACCESSORS(transition_info, Object)
8147 // nested_site threads a list of sites that represent nested literals
8148 // walked in a particular order. So [[1, 2], 1, 2] will have one
8149 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8150 DECL_ACCESSORS(nested_site, Object)
8151 DECL_ACCESSORS(pretenure_data, Smi)
8152 DECL_ACCESSORS(pretenure_create_count, Smi)
8153 DECL_ACCESSORS(dependent_code, DependentCode)
8154 DECL_ACCESSORS(weak_next, Object)
8156 inline void Initialize();
8158 // This method is expensive, it should only be called for reporting.
8159 bool IsNestedSite();
8161 // transition_info bitfields, for constructed array transition info.
8162 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8163 class UnusedBits: public BitField<int, 15, 14> {};
8164 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8166 // Bitfields for pretenure_data
8167 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8168 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8169 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8170 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8172 // Increments the mementos found counter and returns true when the first
8173 // memento was found for a given allocation site.
8174 inline bool IncrementMementoFoundCount();
8176 inline void IncrementMementoCreateCount();
8178 PretenureFlag GetPretenureMode();
8180 void ResetPretenureDecision();
8182 PretenureDecision pretenure_decision() {
8183 int value = pretenure_data()->value();
8184 return PretenureDecisionBits::decode(value);
8187 void set_pretenure_decision(PretenureDecision decision) {
8188 int value = pretenure_data()->value();
8190 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8191 SKIP_WRITE_BARRIER);
8194 bool deopt_dependent_code() {
8195 int value = pretenure_data()->value();
8196 return DeoptDependentCodeBit::decode(value);
8199 void set_deopt_dependent_code(bool deopt) {
8200 int value = pretenure_data()->value();
8202 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8203 SKIP_WRITE_BARRIER);
8206 int memento_found_count() {
8207 int value = pretenure_data()->value();
8208 return MementoFoundCountBits::decode(value);
8211 inline void set_memento_found_count(int count);
8213 int memento_create_count() {
8214 return pretenure_create_count()->value();
8217 void set_memento_create_count(int count) {
8218 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8221 // The pretenuring decision is made during gc, and the zombie state allows
8222 // us to recognize when an allocation site is just being kept alive because
8223 // a later traversal of new space may discover AllocationMementos that point
8224 // to this AllocationSite.
8226 return pretenure_decision() == kZombie;
8229 bool IsMaybeTenure() {
8230 return pretenure_decision() == kMaybeTenure;
8233 inline void MarkZombie();
8235 inline bool MakePretenureDecision(PretenureDecision current_decision,
8237 bool maximum_size_scavenge);
8239 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8241 ElementsKind GetElementsKind() {
8242 DCHECK(!SitePointsToLiteral());
8243 int value = Smi::cast(transition_info())->value();
8244 return ElementsKindBits::decode(value);
8247 void SetElementsKind(ElementsKind kind) {
8248 int value = Smi::cast(transition_info())->value();
8249 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8250 SKIP_WRITE_BARRIER);
8253 bool CanInlineCall() {
8254 int value = Smi::cast(transition_info())->value();
8255 return DoNotInlineBit::decode(value) == 0;
8258 void SetDoNotInlineCall() {
8259 int value = Smi::cast(transition_info())->value();
8260 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8261 SKIP_WRITE_BARRIER);
8264 bool SitePointsToLiteral() {
8265 // If transition_info is a smi, then it represents an ElementsKind
8266 // for a constructed array. Otherwise, it must be a boilerplate
8267 // for an object or array literal.
8268 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8271 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8272 ElementsKind to_kind);
8279 static void AddDependentCompilationInfo(Handle<AllocationSite> site,
8281 CompilationInfo* info);
8283 DECLARE_PRINTER(AllocationSite)
8284 DECLARE_VERIFIER(AllocationSite)
8286 DECLARE_CAST(AllocationSite)
8287 static inline AllocationSiteMode GetMode(
8288 ElementsKind boilerplate_elements_kind);
8289 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8290 static inline bool CanTrack(InstanceType type);
8292 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8293 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8294 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8295 static const int kPretenureCreateCountOffset =
8296 kPretenureDataOffset + kPointerSize;
8297 static const int kDependentCodeOffset =
8298 kPretenureCreateCountOffset + kPointerSize;
8299 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8300 static const int kSize = kWeakNextOffset + kPointerSize;
8302 // During mark compact we need to take special care for the dependent code
8304 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8305 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
8307 // For other visitors, use the fixed body descriptor below.
8308 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8309 kDependentCodeOffset + kPointerSize,
8310 kSize> BodyDescriptor;
8313 inline DependentCode::DependencyGroup ToDependencyGroup(Reason reason);
8314 bool PretenuringDecisionMade() {
8315 return pretenure_decision() != kUndecided;
8318 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8322 class AllocationMemento: public Struct {
8324 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8325 static const int kSize = kAllocationSiteOffset + kPointerSize;
8327 DECL_ACCESSORS(allocation_site, Object)
8330 return allocation_site()->IsAllocationSite() &&
8331 !AllocationSite::cast(allocation_site())->IsZombie();
8333 AllocationSite* GetAllocationSite() {
8335 return AllocationSite::cast(allocation_site());
8338 DECLARE_PRINTER(AllocationMemento)
8339 DECLARE_VERIFIER(AllocationMemento)
8341 DECLARE_CAST(AllocationMemento)
8344 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8348 // Representation of a slow alias as part of a sloppy arguments objects.
8349 // For fast aliases (if HasSloppyArgumentsElements()):
8350 // - the parameter map contains an index into the context
8351 // - all attributes of the element have default values
8352 // For slow aliases (if HasDictionaryArgumentsElements()):
8353 // - the parameter map contains no fast alias mapping (i.e. the hole)
8354 // - this struct (in the slow backing store) contains an index into the context
8355 // - all attributes are available as part if the property details
8356 class AliasedArgumentsEntry: public Struct {
8358 inline int aliased_context_slot() const;
8359 inline void set_aliased_context_slot(int count);
8361 DECLARE_CAST(AliasedArgumentsEntry)
8363 // Dispatched behavior.
8364 DECLARE_PRINTER(AliasedArgumentsEntry)
8365 DECLARE_VERIFIER(AliasedArgumentsEntry)
8367 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8368 static const int kSize = kAliasedContextSlot + kPointerSize;
8371 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8375 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8376 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8379 class StringHasher {
8381 explicit inline StringHasher(int length, uint32_t seed);
8383 template <typename schar>
8384 static inline uint32_t HashSequentialString(const schar* chars,
8388 // Reads all the data, even for long strings and computes the utf16 length.
8389 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8391 int* utf16_length_out);
8393 // Calculated hash value for a string consisting of 1 to
8394 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8395 // value is represented decimal value.
8396 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8398 // No string is allowed to have a hash of zero. That value is reserved
8399 // for internal properties. If the hash calculation yields zero then we
8401 static const int kZeroHash = 27;
8403 // Reusable parts of the hashing algorithm.
8404 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8405 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8408 // Returns the value to store in the hash field of a string with
8409 // the given length and contents.
8410 uint32_t GetHashField();
8411 // Returns true if the hash of this string can be computed without
8412 // looking at the contents.
8413 inline bool has_trivial_hash();
8414 // Adds a block of characters to the hash.
8415 template<typename Char>
8416 inline void AddCharacters(const Char* chars, int len);
8419 // Add a character to the hash.
8420 inline void AddCharacter(uint16_t c);
8421 // Update index. Returns true if string is still an index.
8422 inline bool UpdateIndex(uint16_t c);
8425 uint32_t raw_running_hash_;
8426 uint32_t array_index_;
8427 bool is_array_index_;
8428 bool is_first_char_;
8429 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8433 class IteratingStringHasher : public StringHasher {
8435 static inline uint32_t Hash(String* string, uint32_t seed);
8436 inline void VisitOneByteString(const uint8_t* chars, int length);
8437 inline void VisitTwoByteString(const uint16_t* chars, int length);
8440 inline IteratingStringHasher(int len, uint32_t seed)
8441 : StringHasher(len, seed) {}
8442 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8446 // The characteristics of a string are stored in its map. Retrieving these
8447 // few bits of information is moderately expensive, involving two memory
8448 // loads where the second is dependent on the first. To improve efficiency
8449 // the shape of the string is given its own class so that it can be retrieved
8450 // once and used for several string operations. A StringShape is small enough
8451 // to be passed by value and is immutable, but be aware that flattening a
8452 // string can potentially alter its shape. Also be aware that a GC caused by
8453 // something else can alter the shape of a string due to ConsString
8454 // shortcutting. Keeping these restrictions in mind has proven to be error-
8455 // prone and so we no longer put StringShapes in variables unless there is a
8456 // concrete performance benefit at that particular point in the code.
8457 class StringShape BASE_EMBEDDED {
8459 inline explicit StringShape(const String* s);
8460 inline explicit StringShape(Map* s);
8461 inline explicit StringShape(InstanceType t);
8462 inline bool IsSequential();
8463 inline bool IsExternal();
8464 inline bool IsCons();
8465 inline bool IsSliced();
8466 inline bool IsIndirect();
8467 inline bool IsExternalOneByte();
8468 inline bool IsExternalTwoByte();
8469 inline bool IsSequentialOneByte();
8470 inline bool IsSequentialTwoByte();
8471 inline bool IsInternalized();
8472 inline StringRepresentationTag representation_tag();
8473 inline uint32_t encoding_tag();
8474 inline uint32_t full_representation_tag();
8475 inline uint32_t size_tag();
8477 inline uint32_t type() { return type_; }
8478 inline void invalidate() { valid_ = false; }
8479 inline bool valid() { return valid_; }
8481 inline void invalidate() { }
8487 inline void set_valid() { valid_ = true; }
8490 inline void set_valid() { }
8495 // The Name abstract class captures anything that can be used as a property
8496 // name, i.e., strings and symbols. All names store a hash value.
8497 class Name: public HeapObject {
8499 // Get and set the hash field of the name.
8500 inline uint32_t hash_field();
8501 inline void set_hash_field(uint32_t value);
8503 // Tells whether the hash code has been computed.
8504 inline bool HasHashCode();
8506 // Returns a hash value used for the property table
8507 inline uint32_t Hash();
8509 // Equality operations.
8510 inline bool Equals(Name* other);
8511 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8514 inline bool AsArrayIndex(uint32_t* index);
8516 // Whether name can only name own properties.
8517 inline bool IsOwn();
8521 DECLARE_PRINTER(Name)
8523 // Layout description.
8524 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8525 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8526 static const int kHashFieldOffset = kHashFieldSlot;
8528 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8530 static const int kSize = kHashFieldSlot + kPointerSize;
8532 // Mask constant for checking if a name has a computed hash code
8533 // and if it is a string that is an array index. The least significant bit
8534 // indicates whether a hash code has been computed. If the hash code has
8535 // been computed the 2nd bit tells whether the string can be used as an
8537 static const int kHashNotComputedMask = 1;
8538 static const int kIsNotArrayIndexMask = 1 << 1;
8539 static const int kNofHashBitFields = 2;
8541 // Shift constant retrieving hash code from hash field.
8542 static const int kHashShift = kNofHashBitFields;
8544 // Only these bits are relevant in the hash, since the top two are shifted
8546 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8548 // Array index strings this short can keep their index in the hash field.
8549 static const int kMaxCachedArrayIndexLength = 7;
8551 // For strings which are array indexes the hash value has the string length
8552 // mixed into the hash, mainly to avoid a hash value of zero which would be
8553 // the case for the string '0'. 24 bits are used for the array index value.
8554 static const int kArrayIndexValueBits = 24;
8555 static const int kArrayIndexLengthBits =
8556 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8558 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8560 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8561 kArrayIndexValueBits> {}; // NOLINT
8562 class ArrayIndexLengthBits : public BitField<unsigned int,
8563 kNofHashBitFields + kArrayIndexValueBits,
8564 kArrayIndexLengthBits> {}; // NOLINT
8566 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8567 // could use a mask to test if the length of string is less than or equal to
8568 // kMaxCachedArrayIndexLength.
8569 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8571 static const unsigned int kContainsCachedArrayIndexMask =
8572 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8573 << ArrayIndexLengthBits::kShift) |
8574 kIsNotArrayIndexMask;
8576 // Value of empty hash field indicating that the hash is not computed.
8577 static const int kEmptyHashField =
8578 kIsNotArrayIndexMask | kHashNotComputedMask;
8581 static inline bool IsHashFieldComputed(uint32_t field);
8584 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8589 class Symbol: public Name {
8591 // [name]: the print name of a symbol, or undefined if none.
8592 DECL_ACCESSORS(name, Object)
8594 DECL_ACCESSORS(flags, Smi)
8596 // [is_private]: whether this is a private symbol.
8597 DECL_BOOLEAN_ACCESSORS(is_private)
8599 // [is_own]: whether this is an own symbol, that is, only used to designate
8600 // own properties of objects.
8601 DECL_BOOLEAN_ACCESSORS(is_own)
8603 DECLARE_CAST(Symbol)
8605 // Dispatched behavior.
8606 DECLARE_PRINTER(Symbol)
8607 DECLARE_VERIFIER(Symbol)
8609 // Layout description.
8610 static const int kNameOffset = Name::kSize;
8611 static const int kFlagsOffset = kNameOffset + kPointerSize;
8612 static const int kSize = kFlagsOffset + kPointerSize;
8614 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8617 static const int kPrivateBit = 0;
8618 static const int kOwnBit = 1;
8620 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8626 // The String abstract class captures JavaScript string values:
8629 // 4.3.16 String Value
8630 // A string value is a member of the type String and is a finite
8631 // ordered sequence of zero or more 16-bit unsigned integer values.
8633 // All string values have a length field.
8634 class String: public Name {
8636 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8638 // Array index strings this short can keep their index in the hash field.
8639 static const int kMaxCachedArrayIndexLength = 7;
8641 // For strings which are array indexes the hash value has the string length
8642 // mixed into the hash, mainly to avoid a hash value of zero which would be
8643 // the case for the string '0'. 24 bits are used for the array index value.
8644 static const int kArrayIndexValueBits = 24;
8645 static const int kArrayIndexLengthBits =
8646 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8648 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8650 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8651 kArrayIndexValueBits> {}; // NOLINT
8652 class ArrayIndexLengthBits : public BitField<unsigned int,
8653 kNofHashBitFields + kArrayIndexValueBits,
8654 kArrayIndexLengthBits> {}; // NOLINT
8656 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8657 // could use a mask to test if the length of string is less than or equal to
8658 // kMaxCachedArrayIndexLength.
8659 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8661 static const unsigned int kContainsCachedArrayIndexMask =
8662 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8663 << ArrayIndexLengthBits::kShift) |
8664 kIsNotArrayIndexMask;
8666 // Representation of the flat content of a String.
8667 // A non-flat string doesn't have flat content.
8668 // A flat string has content that's encoded as a sequence of either
8669 // one-byte chars or two-byte UC16.
8670 // Returned by String::GetFlatContent().
8673 // Returns true if the string is flat and this structure contains content.
8674 bool IsFlat() { return state_ != NON_FLAT; }
8675 // Returns true if the structure contains one-byte content.
8676 bool IsOneByte() { return state_ == ONE_BYTE; }
8677 // Returns true if the structure contains two-byte content.
8678 bool IsTwoByte() { return state_ == TWO_BYTE; }
8680 // Return the one byte content of the string. Only use if IsOneByte()
8682 Vector<const uint8_t> ToOneByteVector() {
8683 DCHECK_EQ(ONE_BYTE, state_);
8684 return Vector<const uint8_t>(onebyte_start, length_);
8686 // Return the two-byte content of the string. Only use if IsTwoByte()
8688 Vector<const uc16> ToUC16Vector() {
8689 DCHECK_EQ(TWO_BYTE, state_);
8690 return Vector<const uc16>(twobyte_start, length_);
8694 DCHECK(i < length_);
8695 DCHECK(state_ != NON_FLAT);
8696 if (state_ == ONE_BYTE) return onebyte_start[i];
8697 return twobyte_start[i];
8701 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8703 // Constructors only used by String::GetFlatContent().
8704 explicit FlatContent(const uint8_t* start, int length)
8705 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8706 explicit FlatContent(const uc16* start, int length)
8707 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8708 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8711 const uint8_t* onebyte_start;
8712 const uc16* twobyte_start;
8717 friend class String;
8720 // Get and set the length of the string.
8721 inline int length() const;
8722 inline void set_length(int value);
8724 // Get and set the length of the string using acquire loads and release
8726 inline int synchronized_length() const;
8727 inline void synchronized_set_length(int value);
8729 // Returns whether this string has only one-byte chars, i.e. all of them can
8730 // be one-byte encoded. This might be the case even if the string is
8731 // two-byte. Such strings may appear when the embedder prefers
8732 // two-byte external representations even for one-byte data.
8733 inline bool IsOneByteRepresentation() const;
8734 inline bool IsTwoByteRepresentation() const;
8736 // Cons and slices have an encoding flag that may not represent the actual
8737 // encoding of the underlying string. This is taken into account here.
8738 // Requires: this->IsFlat()
8739 inline bool IsOneByteRepresentationUnderneath();
8740 inline bool IsTwoByteRepresentationUnderneath();
8742 // NOTE: this should be considered only a hint. False negatives are
8744 inline bool HasOnlyOneByteChars();
8746 // Get and set individual two byte chars in the string.
8747 inline void Set(int index, uint16_t value);
8748 // Get individual two byte char in the string. Repeated calls
8749 // to this method are not efficient unless the string is flat.
8750 INLINE(uint16_t Get(int index));
8752 // Flattens the string. Checks first inline to see if it is
8753 // necessary. Does nothing if the string is not a cons string.
8754 // Flattening allocates a sequential string with the same data as
8755 // the given string and mutates the cons string to a degenerate
8756 // form, where the first component is the new sequential string and
8757 // the second component is the empty string. If allocation fails,
8758 // this function returns a failure. If flattening succeeds, this
8759 // function returns the sequential string that is now the first
8760 // component of the cons string.
8762 // Degenerate cons strings are handled specially by the garbage
8763 // collector (see IsShortcutCandidate).
8765 static inline Handle<String> Flatten(Handle<String> string,
8766 PretenureFlag pretenure = NOT_TENURED);
8768 // Tries to return the content of a flat string as a structure holding either
8769 // a flat vector of char or of uc16.
8770 // If the string isn't flat, and therefore doesn't have flat content, the
8771 // returned structure will report so, and can't provide a vector of either
8773 FlatContent GetFlatContent();
8775 // Returns the parent of a sliced string or first part of a flat cons string.
8776 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8777 inline String* GetUnderlying();
8779 // Mark the string as an undetectable object. It only applies to
8780 // one-byte and two-byte string types.
8781 bool MarkAsUndetectable();
8783 // String equality operations.
8784 inline bool Equals(String* other);
8785 inline static bool Equals(Handle<String> one, Handle<String> two);
8786 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8787 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8788 bool IsTwoByteEqualTo(Vector<const uc16> str);
8790 // Return a UTF8 representation of the string. The string is null
8791 // terminated but may optionally contain nulls. Length is returned
8792 // in length_output if length_output is not a null pointer The string
8793 // should be nearly flat, otherwise the performance of this method may
8794 // be very slow (quadratic in the length). Setting robustness_flag to
8795 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8796 // handles unexpected data without causing assert failures and it does not
8797 // do any heap allocations. This is useful when printing stack traces.
8798 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8799 RobustnessFlag robustness_flag,
8802 int* length_output = 0);
8803 SmartArrayPointer<char> ToCString(
8804 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8805 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8806 int* length_output = 0);
8808 // Return a 16 bit Unicode representation of the string.
8809 // The string should be nearly flat, otherwise the performance of
8810 // of this method may be very bad. Setting robustness_flag to
8811 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8812 // handles unexpected data without causing assert failures and it does not
8813 // do any heap allocations. This is useful when printing stack traces.
8814 SmartArrayPointer<uc16> ToWideCString(
8815 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8817 bool ComputeArrayIndex(uint32_t* index);
8820 bool MakeExternal(v8::String::ExternalStringResource* resource);
8821 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8824 inline bool AsArrayIndex(uint32_t* index);
8826 DECLARE_CAST(String)
8828 void PrintOn(FILE* out);
8830 // For use during stack traces. Performs rudimentary sanity check.
8833 // Dispatched behavior.
8834 void StringShortPrint(StringStream* accumulator);
8835 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8837 char* ToAsciiArray();
8839 DECLARE_PRINTER(String)
8840 DECLARE_VERIFIER(String)
8842 inline bool IsFlat();
8844 // Layout description.
8845 static const int kLengthOffset = Name::kSize;
8846 static const int kSize = kLengthOffset + kPointerSize;
8848 // Maximum number of characters to consider when trying to convert a string
8849 // value into an array index.
8850 static const int kMaxArrayIndexSize = 10;
8851 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8854 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8855 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8856 static const int kMaxUtf16CodeUnit = 0xffff;
8857 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8859 // Value of hash field containing computed hash equal to zero.
8860 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8862 // Maximal string length.
8863 static const int kMaxLength = (1 << 28) - 16;
8865 // Max length for computing hash. For strings longer than this limit the
8866 // string length is used as the hash value.
8867 static const int kMaxHashCalcLength = 16383;
8869 // Limit for truncation in short printing.
8870 static const int kMaxShortPrintLength = 1024;
8872 // Support for regular expressions.
8873 const uc16* GetTwoByteData(unsigned start);
8875 // Helper function for flattening strings.
8876 template <typename sinkchar>
8877 static void WriteToFlat(String* source,
8882 // The return value may point to the first aligned word containing the first
8883 // non-one-byte character, rather than directly to the non-one-byte character.
8884 // If the return value is >= the passed length, the entire string was
8886 static inline int NonAsciiStart(const char* chars, int length) {
8887 const char* start = chars;
8888 const char* limit = chars + length;
8890 if (length >= kIntptrSize) {
8891 // Check unaligned bytes.
8892 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8893 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8894 return static_cast<int>(chars - start);
8898 // Check aligned words.
8899 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8900 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8901 while (chars + sizeof(uintptr_t) <= limit) {
8902 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8903 return static_cast<int>(chars - start);
8905 chars += sizeof(uintptr_t);
8908 // Check remaining unaligned bytes.
8909 while (chars < limit) {
8910 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8911 return static_cast<int>(chars - start);
8916 return static_cast<int>(chars - start);
8919 static inline bool IsAscii(const char* chars, int length) {
8920 return NonAsciiStart(chars, length) >= length;
8923 static inline bool IsAscii(const uint8_t* chars, int length) {
8925 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8928 static inline int NonOneByteStart(const uc16* chars, int length) {
8929 const uc16* limit = chars + length;
8930 const uc16* start = chars;
8931 while (chars < limit) {
8932 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8935 return static_cast<int>(chars - start);
8938 static inline bool IsOneByte(const uc16* chars, int length) {
8939 return NonOneByteStart(chars, length) >= length;
8942 template<class Visitor>
8943 static inline ConsString* VisitFlat(Visitor* visitor,
8947 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8948 bool include_ending_line);
8950 // Use the hash field to forward to the canonical internalized string
8951 // when deserializing an internalized string.
8952 inline void SetForwardedInternalizedString(String* string);
8953 inline String* GetForwardedInternalizedString();
8957 friend class StringTableInsertionKey;
8959 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8960 PretenureFlag tenure);
8962 // Slow case of String::Equals. This implementation works on any strings
8963 // but it is most efficient on strings that are almost flat.
8964 bool SlowEquals(String* other);
8966 static bool SlowEquals(Handle<String> one, Handle<String> two);
8968 // Slow case of AsArrayIndex.
8969 bool SlowAsArrayIndex(uint32_t* index);
8971 // Compute and set the hash code.
8972 uint32_t ComputeAndSetHash();
8974 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
8978 // The SeqString abstract class captures sequential string values.
8979 class SeqString: public String {
8981 DECLARE_CAST(SeqString)
8983 // Layout description.
8984 static const int kHeaderSize = String::kSize;
8986 // Truncate the string in-place if possible and return the result.
8987 // In case of new_length == 0, the empty string is returned without
8988 // truncating the original string.
8989 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
8992 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
8996 // The OneByteString class captures sequential one-byte string objects.
8997 // Each character in the OneByteString is an one-byte character.
8998 class SeqOneByteString: public SeqString {
9000 static const bool kHasOneByteEncoding = true;
9002 // Dispatched behavior.
9003 inline uint16_t SeqOneByteStringGet(int index);
9004 inline void SeqOneByteStringSet(int index, uint16_t value);
9006 // Get the address of the characters in this string.
9007 inline Address GetCharsAddress();
9009 inline uint8_t* GetChars();
9011 DECLARE_CAST(SeqOneByteString)
9013 // Garbage collection support. This method is called by the
9014 // garbage collector to compute the actual size of an OneByteString
9016 inline int SeqOneByteStringSize(InstanceType instance_type);
9018 // Computes the size for an OneByteString instance of a given length.
9019 static int SizeFor(int length) {
9020 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9023 // Maximal memory usage for a single sequential one-byte string.
9024 static const int kMaxSize = 512 * MB - 1;
9025 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9028 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9032 // The TwoByteString class captures sequential unicode string objects.
9033 // Each character in the TwoByteString is a two-byte uint16_t.
9034 class SeqTwoByteString: public SeqString {
9036 static const bool kHasOneByteEncoding = false;
9038 // Dispatched behavior.
9039 inline uint16_t SeqTwoByteStringGet(int index);
9040 inline void SeqTwoByteStringSet(int index, uint16_t value);
9042 // Get the address of the characters in this string.
9043 inline Address GetCharsAddress();
9045 inline uc16* GetChars();
9048 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9050 DECLARE_CAST(SeqTwoByteString)
9052 // Garbage collection support. This method is called by the
9053 // garbage collector to compute the actual size of a TwoByteString
9055 inline int SeqTwoByteStringSize(InstanceType instance_type);
9057 // Computes the size for a TwoByteString instance of a given length.
9058 static int SizeFor(int length) {
9059 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9062 // Maximal memory usage for a single sequential two-byte string.
9063 static const int kMaxSize = 512 * MB - 1;
9064 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9065 String::kMaxLength);
9068 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9072 // The ConsString class describes string values built by using the
9073 // addition operator on strings. A ConsString is a pair where the
9074 // first and second components are pointers to other string values.
9075 // One or both components of a ConsString can be pointers to other
9076 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9077 // are non-ConsString string values. The string value represented by
9078 // a ConsString can be obtained by concatenating the leaf string
9079 // values in a left-to-right depth-first traversal of the tree.
9080 class ConsString: public String {
9082 // First string of the cons cell.
9083 inline String* first();
9084 // Doesn't check that the result is a string, even in debug mode. This is
9085 // useful during GC where the mark bits confuse the checks.
9086 inline Object* unchecked_first();
9087 inline void set_first(String* first,
9088 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9090 // Second string of the cons cell.
9091 inline String* second();
9092 // Doesn't check that the result is a string, even in debug mode. This is
9093 // useful during GC where the mark bits confuse the checks.
9094 inline Object* unchecked_second();
9095 inline void set_second(String* second,
9096 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9098 // Dispatched behavior.
9099 uint16_t ConsStringGet(int index);
9101 DECLARE_CAST(ConsString)
9103 // Layout description.
9104 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9105 static const int kSecondOffset = kFirstOffset + kPointerSize;
9106 static const int kSize = kSecondOffset + kPointerSize;
9108 // Minimum length for a cons string.
9109 static const int kMinLength = 13;
9111 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9114 DECLARE_VERIFIER(ConsString)
9117 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9121 // The Sliced String class describes strings that are substrings of another
9122 // sequential string. The motivation is to save time and memory when creating
9123 // a substring. A Sliced String is described as a pointer to the parent,
9124 // the offset from the start of the parent string and the length. Using
9125 // a Sliced String therefore requires unpacking of the parent string and
9126 // adding the offset to the start address. A substring of a Sliced String
9127 // are not nested since the double indirection is simplified when creating
9128 // such a substring.
9129 // Currently missing features are:
9130 // - handling externalized parent strings
9131 // - external strings as parent
9132 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9133 class SlicedString: public String {
9135 inline String* parent();
9136 inline void set_parent(String* parent,
9137 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9138 inline int offset() const;
9139 inline void set_offset(int offset);
9141 // Dispatched behavior.
9142 uint16_t SlicedStringGet(int index);
9144 DECLARE_CAST(SlicedString)
9146 // Layout description.
9147 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9148 static const int kOffsetOffset = kParentOffset + kPointerSize;
9149 static const int kSize = kOffsetOffset + kPointerSize;
9151 // Minimum length for a sliced string.
9152 static const int kMinLength = 13;
9154 typedef FixedBodyDescriptor<kParentOffset,
9155 kOffsetOffset + kPointerSize, kSize>
9158 DECLARE_VERIFIER(SlicedString)
9161 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9165 // The ExternalString class describes string values that are backed by
9166 // a string resource that lies outside the V8 heap. ExternalStrings
9167 // consist of the length field common to all strings, a pointer to the
9168 // external resource. It is important to ensure (externally) that the
9169 // resource is not deallocated while the ExternalString is live in the
9172 // The API expects that all ExternalStrings are created through the
9173 // API. Therefore, ExternalStrings should not be used internally.
9174 class ExternalString: public String {
9176 DECLARE_CAST(ExternalString)
9178 // Layout description.
9179 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9180 static const int kShortSize = kResourceOffset + kPointerSize;
9181 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9182 static const int kSize = kResourceDataOffset + kPointerSize;
9184 static const int kMaxShortLength =
9185 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9187 // Return whether external string is short (data pointer is not cached).
9188 inline bool is_short();
9190 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9193 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9197 // The ExternalOneByteString class is an external string backed by an
9199 class ExternalOneByteString : public ExternalString {
9201 static const bool kHasOneByteEncoding = true;
9203 typedef v8::String::ExternalOneByteStringResource Resource;
9205 // The underlying resource.
9206 inline const Resource* resource();
9207 inline void set_resource(const Resource* buffer);
9209 // Update the pointer cache to the external character array.
9210 // The cached pointer is always valid, as the external character array does =
9211 // not move during lifetime. Deserialization is the only exception, after
9212 // which the pointer cache has to be refreshed.
9213 inline void update_data_cache();
9215 inline const uint8_t* GetChars();
9217 // Dispatched behavior.
9218 inline uint16_t ExternalOneByteStringGet(int index);
9220 DECLARE_CAST(ExternalOneByteString)
9222 // Garbage collection support.
9223 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9225 template <typename StaticVisitor>
9226 inline void ExternalOneByteStringIterateBody();
9229 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9233 // The ExternalTwoByteString class is an external string backed by a UTF-16
9235 class ExternalTwoByteString: public ExternalString {
9237 static const bool kHasOneByteEncoding = false;
9239 typedef v8::String::ExternalStringResource Resource;
9241 // The underlying string resource.
9242 inline const Resource* resource();
9243 inline void set_resource(const Resource* buffer);
9245 // Update the pointer cache to the external character array.
9246 // The cached pointer is always valid, as the external character array does =
9247 // not move during lifetime. Deserialization is the only exception, after
9248 // which the pointer cache has to be refreshed.
9249 inline void update_data_cache();
9251 inline const uint16_t* GetChars();
9253 // Dispatched behavior.
9254 inline uint16_t ExternalTwoByteStringGet(int index);
9257 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9259 DECLARE_CAST(ExternalTwoByteString)
9261 // Garbage collection support.
9262 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9264 template<typename StaticVisitor>
9265 inline void ExternalTwoByteStringIterateBody();
9268 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9272 // Utility superclass for stack-allocated objects that must be updated
9273 // on gc. It provides two ways for the gc to update instances, either
9274 // iterating or updating after gc.
9275 class Relocatable BASE_EMBEDDED {
9277 explicit inline Relocatable(Isolate* isolate);
9278 inline virtual ~Relocatable();
9279 virtual void IterateInstance(ObjectVisitor* v) { }
9280 virtual void PostGarbageCollection() { }
9282 static void PostGarbageCollectionProcessing(Isolate* isolate);
9283 static int ArchiveSpacePerThread();
9284 static char* ArchiveState(Isolate* isolate, char* to);
9285 static char* RestoreState(Isolate* isolate, char* from);
9286 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9287 static void Iterate(ObjectVisitor* v, Relocatable* top);
9288 static char* Iterate(ObjectVisitor* v, char* t);
9296 // A flat string reader provides random access to the contents of a
9297 // string independent of the character width of the string. The handle
9298 // must be valid as long as the reader is being used.
9299 class FlatStringReader : public Relocatable {
9301 FlatStringReader(Isolate* isolate, Handle<String> str);
9302 FlatStringReader(Isolate* isolate, Vector<const char> input);
9303 void PostGarbageCollection();
9304 inline uc32 Get(int index);
9305 int length() { return length_; }
9314 // A ConsStringOp that returns null.
9315 // Useful when the operation to apply on a ConsString
9316 // requires an expensive data structure.
9317 class ConsStringNullOp {
9319 inline ConsStringNullOp() {}
9320 static inline String* Operate(String*, unsigned*, int32_t*, unsigned*);
9322 DISALLOW_COPY_AND_ASSIGN(ConsStringNullOp);
9326 // This maintains an off-stack representation of the stack frames required
9327 // to traverse a ConsString, allowing an entirely iterative and restartable
9328 // traversal of the entire string
9329 class ConsStringIteratorOp {
9331 inline ConsStringIteratorOp() {}
9332 inline explicit ConsStringIteratorOp(ConsString* cons_string,
9334 Reset(cons_string, offset);
9336 inline void Reset(ConsString* cons_string, int offset = 0) {
9338 // Next will always return NULL.
9339 if (cons_string == NULL) return;
9340 Initialize(cons_string, offset);
9342 // Returns NULL when complete.
9343 inline String* Next(int* offset_out) {
9345 if (depth_ == 0) return NULL;
9346 return Continue(offset_out);
9350 static const int kStackSize = 32;
9351 // Use a mask instead of doing modulo operations for stack wrapping.
9352 static const int kDepthMask = kStackSize-1;
9353 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9354 static inline int OffsetForDepth(int depth);
9356 inline void PushLeft(ConsString* string);
9357 inline void PushRight(ConsString* string);
9358 inline void AdjustMaximumDepth();
9360 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9361 void Initialize(ConsString* cons_string, int offset);
9362 String* Continue(int* offset_out);
9363 String* NextLeaf(bool* blew_stack);
9364 String* Search(int* offset_out);
9366 // Stack must always contain only frames for which right traversal
9367 // has not yet been performed.
9368 ConsString* frames_[kStackSize];
9373 DISALLOW_COPY_AND_ASSIGN(ConsStringIteratorOp);
9377 class StringCharacterStream {
9379 inline StringCharacterStream(String* string,
9380 ConsStringIteratorOp* op,
9382 inline uint16_t GetNext();
9383 inline bool HasMore();
9384 inline void Reset(String* string, int offset = 0);
9385 inline void VisitOneByteString(const uint8_t* chars, int length);
9386 inline void VisitTwoByteString(const uint16_t* chars, int length);
9391 const uint8_t* buffer8_;
9392 const uint16_t* buffer16_;
9394 const uint8_t* end_;
9395 ConsStringIteratorOp* op_;
9396 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9400 template <typename T>
9401 class VectorIterator {
9403 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9404 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9405 T GetNext() { return data_[index_++]; }
9406 bool has_more() { return index_ < data_.length(); }
9408 Vector<const T> data_;
9413 // The Oddball describes objects null, undefined, true, and false.
9414 class Oddball: public HeapObject {
9416 // [to_string]: Cached to_string computed at startup.
9417 DECL_ACCESSORS(to_string, String)
9419 // [to_number]: Cached to_number computed at startup.
9420 DECL_ACCESSORS(to_number, Object)
9422 inline byte kind() const;
9423 inline void set_kind(byte kind);
9425 DECLARE_CAST(Oddball)
9427 // Dispatched behavior.
9428 DECLARE_VERIFIER(Oddball)
9430 // Initialize the fields.
9431 static void Initialize(Isolate* isolate,
9432 Handle<Oddball> oddball,
9433 const char* to_string,
9434 Handle<Object> to_number,
9437 // Layout description.
9438 static const int kToStringOffset = HeapObject::kHeaderSize;
9439 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9440 static const int kKindOffset = kToNumberOffset + kPointerSize;
9441 static const int kSize = kKindOffset + kPointerSize;
9443 static const byte kFalse = 0;
9444 static const byte kTrue = 1;
9445 static const byte kNotBooleanMask = ~1;
9446 static const byte kTheHole = 2;
9447 static const byte kNull = 3;
9448 static const byte kArgumentMarker = 4;
9449 static const byte kUndefined = 5;
9450 static const byte kUninitialized = 6;
9451 static const byte kOther = 7;
9452 static const byte kException = 8;
9454 typedef FixedBodyDescriptor<kToStringOffset,
9455 kToNumberOffset + kPointerSize,
9456 kSize> BodyDescriptor;
9458 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9459 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9460 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9463 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9467 class Cell: public HeapObject {
9469 // [value]: value of the global property.
9470 DECL_ACCESSORS(value, Object)
9474 static inline Cell* FromValueAddress(Address value) {
9475 Object* result = FromAddress(value - kValueOffset);
9476 DCHECK(result->IsCell() || result->IsPropertyCell());
9477 return static_cast<Cell*>(result);
9480 inline Address ValueAddress() {
9481 return address() + kValueOffset;
9484 // Dispatched behavior.
9485 DECLARE_PRINTER(Cell)
9486 DECLARE_VERIFIER(Cell)
9488 // Layout description.
9489 static const int kValueOffset = HeapObject::kHeaderSize;
9490 static const int kSize = kValueOffset + kPointerSize;
9492 typedef FixedBodyDescriptor<kValueOffset,
9493 kValueOffset + kPointerSize,
9494 kSize> BodyDescriptor;
9497 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9501 class PropertyCell: public Cell {
9503 // [type]: type of the global property.
9505 void set_type(HeapType* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9507 // [dependent_code]: dependent code that depends on the type of the global
9509 DECL_ACCESSORS(dependent_code, DependentCode)
9511 // Sets the value of the cell and updates the type field to be the union
9512 // of the cell's current type and the value's type. If the change causes
9513 // a change of the type of the cell's contents, code dependent on the cell
9514 // will be deoptimized.
9515 static void SetValueInferType(Handle<PropertyCell> cell,
9516 Handle<Object> value);
9518 // Computes the new type of the cell's contents for the given value, but
9519 // without actually modifying the 'type' field.
9520 static Handle<HeapType> UpdatedType(Handle<PropertyCell> cell,
9521 Handle<Object> value);
9523 static void AddDependentCompilationInfo(Handle<PropertyCell> cell,
9524 CompilationInfo* info);
9526 DECLARE_CAST(PropertyCell)
9528 inline Address TypeAddress() {
9529 return address() + kTypeOffset;
9532 // Dispatched behavior.
9533 DECLARE_PRINTER(PropertyCell)
9534 DECLARE_VERIFIER(PropertyCell)
9536 // Layout description.
9537 static const int kTypeOffset = kValueOffset + kPointerSize;
9538 static const int kDependentCodeOffset = kTypeOffset + kPointerSize;
9539 static const int kSize = kDependentCodeOffset + kPointerSize;
9541 static const int kPointerFieldsBeginOffset = kValueOffset;
9542 static const int kPointerFieldsEndOffset = kDependentCodeOffset;
9544 typedef FixedBodyDescriptor<kValueOffset,
9546 kSize> BodyDescriptor;
9549 DECL_ACCESSORS(type_raw, Object)
9550 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9554 // The JSProxy describes EcmaScript Harmony proxies
9555 class JSProxy: public JSReceiver {
9557 // [handler]: The handler property.
9558 DECL_ACCESSORS(handler, Object)
9560 // [hash]: The hash code property (undefined if not initialized yet).
9561 DECL_ACCESSORS(hash, Object)
9563 DECLARE_CAST(JSProxy)
9565 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9566 Handle<JSProxy> proxy,
9567 Handle<Object> receiver,
9569 MUST_USE_RESULT static inline MaybeHandle<Object> GetElementWithHandler(
9570 Handle<JSProxy> proxy,
9571 Handle<Object> receiver,
9574 // If the handler defines an accessor property with a setter, invoke it.
9575 // If it defines an accessor property without a setter, or a data property
9576 // that is read-only, throw. In all these cases set '*done' to true,
9577 // otherwise set it to false.
9579 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9580 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9581 Handle<Object> value, StrictMode strict_mode, bool* done);
9583 MUST_USE_RESULT static Maybe<PropertyAttributes>
9584 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9585 Handle<Object> receiver,
9587 MUST_USE_RESULT static Maybe<PropertyAttributes>
9588 GetElementAttributeWithHandler(Handle<JSProxy> proxy,
9589 Handle<JSReceiver> receiver,
9591 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9592 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9593 Handle<Object> value, StrictMode strict_mode);
9595 // Turn the proxy into an (empty) JSObject.
9596 static void Fix(Handle<JSProxy> proxy);
9598 // Initializes the body after the handler slot.
9599 inline void InitializeBody(int object_size, Object* value);
9601 // Invoke a trap by name. If the trap does not exist on this's handler,
9602 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9603 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9604 Handle<JSProxy> proxy,
9606 Handle<Object> derived_trap,
9608 Handle<Object> args[]);
9610 // Dispatched behavior.
9611 DECLARE_PRINTER(JSProxy)
9612 DECLARE_VERIFIER(JSProxy)
9614 // Layout description. We add padding so that a proxy has the same
9615 // size as a virgin JSObject. This is essential for becoming a JSObject
9617 static const int kHandlerOffset = HeapObject::kHeaderSize;
9618 static const int kHashOffset = kHandlerOffset + kPointerSize;
9619 static const int kPaddingOffset = kHashOffset + kPointerSize;
9620 static const int kSize = JSObject::kHeaderSize;
9621 static const int kHeaderSize = kPaddingOffset;
9622 static const int kPaddingSize = kSize - kPaddingOffset;
9624 STATIC_ASSERT(kPaddingSize >= 0);
9626 typedef FixedBodyDescriptor<kHandlerOffset,
9628 kSize> BodyDescriptor;
9631 friend class JSReceiver;
9633 MUST_USE_RESULT static inline MaybeHandle<Object> SetElementWithHandler(
9634 Handle<JSProxy> proxy,
9635 Handle<JSReceiver> receiver,
9637 Handle<Object> value,
9638 StrictMode strict_mode);
9640 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9641 Handle<JSProxy> proxy, Handle<Name> name);
9642 MUST_USE_RESULT static inline Maybe<bool> HasElementWithHandler(
9643 Handle<JSProxy> proxy, uint32_t index);
9645 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9646 Handle<JSProxy> proxy,
9649 MUST_USE_RESULT static MaybeHandle<Object> DeleteElementWithHandler(
9650 Handle<JSProxy> proxy,
9654 MUST_USE_RESULT Object* GetIdentityHash();
9656 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9658 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9662 class JSFunctionProxy: public JSProxy {
9664 // [call_trap]: The call trap.
9665 DECL_ACCESSORS(call_trap, Object)
9667 // [construct_trap]: The construct trap.
9668 DECL_ACCESSORS(construct_trap, Object)
9670 DECLARE_CAST(JSFunctionProxy)
9672 // Dispatched behavior.
9673 DECLARE_PRINTER(JSFunctionProxy)
9674 DECLARE_VERIFIER(JSFunctionProxy)
9676 // Layout description.
9677 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9678 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9679 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9680 static const int kSize = JSFunction::kSize;
9681 static const int kPaddingSize = kSize - kPaddingOffset;
9683 STATIC_ASSERT(kPaddingSize >= 0);
9685 typedef FixedBodyDescriptor<kHandlerOffset,
9686 kConstructTrapOffset + kPointerSize,
9687 kSize> BodyDescriptor;
9690 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9694 class JSCollection : public JSObject {
9696 // [table]: the backing hash table
9697 DECL_ACCESSORS(table, Object)
9699 static const int kTableOffset = JSObject::kHeaderSize;
9700 static const int kSize = kTableOffset + kPointerSize;
9703 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9707 // The JSSet describes EcmaScript Harmony sets
9708 class JSSet : public JSCollection {
9712 // Dispatched behavior.
9713 DECLARE_PRINTER(JSSet)
9714 DECLARE_VERIFIER(JSSet)
9717 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9721 // The JSMap describes EcmaScript Harmony maps
9722 class JSMap : public JSCollection {
9726 // Dispatched behavior.
9727 DECLARE_PRINTER(JSMap)
9728 DECLARE_VERIFIER(JSMap)
9731 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9735 // OrderedHashTableIterator is an iterator that iterates over the keys and
9736 // values of an OrderedHashTable.
9738 // The iterator has a reference to the underlying OrderedHashTable data,
9739 // [table], as well as the current [index] the iterator is at.
9741 // When the OrderedHashTable is rehashed it adds a reference from the old table
9742 // to the new table as well as storing enough data about the changes so that the
9743 // iterator [index] can be adjusted accordingly.
9745 // When the [Next] result from the iterator is requested, the iterator checks if
9746 // there is a newer table that it needs to transition to.
9747 template<class Derived, class TableType>
9748 class OrderedHashTableIterator: public JSObject {
9750 // [table]: the backing hash table mapping keys to values.
9751 DECL_ACCESSORS(table, Object)
9753 // [index]: The index into the data table.
9754 DECL_ACCESSORS(index, Object)
9756 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9757 DECL_ACCESSORS(kind, Object)
9760 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9763 static const int kTableOffset = JSObject::kHeaderSize;
9764 static const int kIndexOffset = kTableOffset + kPointerSize;
9765 static const int kKindOffset = kIndexOffset + kPointerSize;
9766 static const int kSize = kKindOffset + kPointerSize;
9774 // Whether the iterator has more elements. This needs to be called before
9775 // calling |CurrentKey| and/or |CurrentValue|.
9778 // Move the index forward one.
9780 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9783 // Populates the array with the next key and value and then moves the iterator
9785 // This returns the |kind| or 0 if the iterator is already at the end.
9786 Smi* Next(JSArray* value_array);
9788 // Returns the current key of the iterator. This should only be called when
9789 // |HasMore| returns true.
9790 inline Object* CurrentKey();
9793 // Transitions the iterator to the non obsolete backing store. This is a NOP
9794 // if the [table] is not obsolete.
9797 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9801 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9804 // Dispatched behavior.
9805 DECLARE_PRINTER(JSSetIterator)
9806 DECLARE_VERIFIER(JSSetIterator)
9808 DECLARE_CAST(JSSetIterator)
9810 // Called by |Next| to populate the array. This allows the subclasses to
9811 // populate the array differently.
9812 inline void PopulateValueArray(FixedArray* array);
9815 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9819 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9822 // Dispatched behavior.
9823 DECLARE_PRINTER(JSMapIterator)
9824 DECLARE_VERIFIER(JSMapIterator)
9826 DECLARE_CAST(JSMapIterator)
9828 // Called by |Next| to populate the array. This allows the subclasses to
9829 // populate the array differently.
9830 inline void PopulateValueArray(FixedArray* array);
9833 // Returns the current value of the iterator. This should only be called when
9834 // |HasMore| returns true.
9835 inline Object* CurrentValue();
9837 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9841 // Base class for both JSWeakMap and JSWeakSet
9842 class JSWeakCollection: public JSObject {
9844 // [table]: the backing hash table mapping keys to values.
9845 DECL_ACCESSORS(table, Object)
9847 // [next]: linked list of encountered weak maps during GC.
9848 DECL_ACCESSORS(next, Object)
9850 static const int kTableOffset = JSObject::kHeaderSize;
9851 static const int kNextOffset = kTableOffset + kPointerSize;
9852 static const int kSize = kNextOffset + kPointerSize;
9855 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9859 // The JSWeakMap describes EcmaScript Harmony weak maps
9860 class JSWeakMap: public JSWeakCollection {
9862 DECLARE_CAST(JSWeakMap)
9864 // Dispatched behavior.
9865 DECLARE_PRINTER(JSWeakMap)
9866 DECLARE_VERIFIER(JSWeakMap)
9869 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9873 // The JSWeakSet describes EcmaScript Harmony weak sets
9874 class JSWeakSet: public JSWeakCollection {
9876 DECLARE_CAST(JSWeakSet)
9878 // Dispatched behavior.
9879 DECLARE_PRINTER(JSWeakSet)
9880 DECLARE_VERIFIER(JSWeakSet)
9883 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9887 class JSArrayBuffer: public JSObject {
9889 // [backing_store]: backing memory for this array
9890 DECL_ACCESSORS(backing_store, void)
9892 // [byte_length]: length in bytes
9893 DECL_ACCESSORS(byte_length, Object)
9896 DECL_ACCESSORS(flag, Smi)
9898 inline bool is_external();
9899 inline void set_is_external(bool value);
9901 inline bool should_be_freed();
9902 inline void set_should_be_freed(bool value);
9904 // [weak_next]: linked list of array buffers.
9905 DECL_ACCESSORS(weak_next, Object)
9907 // [weak_first_array]: weak linked list of views.
9908 DECL_ACCESSORS(weak_first_view, Object)
9910 DECLARE_CAST(JSArrayBuffer)
9912 // Neutering. Only neuters the buffer, not associated typed arrays.
9915 // Dispatched behavior.
9916 DECLARE_PRINTER(JSArrayBuffer)
9917 DECLARE_VERIFIER(JSArrayBuffer)
9919 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9920 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9921 static const int kFlagOffset = kByteLengthOffset + kPointerSize;
9922 static const int kWeakNextOffset = kFlagOffset + kPointerSize;
9923 static const int kWeakFirstViewOffset = kWeakNextOffset + kPointerSize;
9924 static const int kSize = kWeakFirstViewOffset + kPointerSize;
9926 static const int kSizeWithInternalFields =
9927 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9930 // Bit position in a flag
9931 static const int kIsExternalBit = 0;
9932 static const int kShouldBeFreed = 1;
9934 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9938 class JSArrayBufferView: public JSObject {
9940 // [buffer]: ArrayBuffer that this typed array views.
9941 DECL_ACCESSORS(buffer, Object)
9943 // [byte_length]: offset of typed array in bytes.
9944 DECL_ACCESSORS(byte_offset, Object)
9946 // [byte_length]: length of typed array in bytes.
9947 DECL_ACCESSORS(byte_length, Object)
9949 // [weak_next]: linked list of typed arrays over the same array buffer.
9950 DECL_ACCESSORS(weak_next, Object)
9952 DECLARE_CAST(JSArrayBufferView)
9954 DECLARE_VERIFIER(JSArrayBufferView)
9956 static const int kBufferOffset = JSObject::kHeaderSize;
9957 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
9958 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
9959 static const int kWeakNextOffset = kByteLengthOffset + kPointerSize;
9960 static const int kViewSize = kWeakNextOffset + kPointerSize;
9966 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
9970 class JSTypedArray: public JSArrayBufferView {
9972 // [length]: length of typed array in elements.
9973 DECL_ACCESSORS(length, Object)
9975 // Neutering. Only neuters this typed array.
9978 DECLARE_CAST(JSTypedArray)
9980 ExternalArrayType type();
9981 size_t element_size();
9983 Handle<JSArrayBuffer> GetBuffer();
9985 // Dispatched behavior.
9986 DECLARE_PRINTER(JSTypedArray)
9987 DECLARE_VERIFIER(JSTypedArray)
9989 static const int kLengthOffset = kViewSize + kPointerSize;
9990 static const int kSize = kLengthOffset + kPointerSize;
9992 static const int kSizeWithInternalFields =
9993 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
9996 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
9997 Handle<JSTypedArray> typed_array);
9999 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10003 class JSDataView: public JSArrayBufferView {
10005 // Only neuters this DataView
10008 DECLARE_CAST(JSDataView)
10010 // Dispatched behavior.
10011 DECLARE_PRINTER(JSDataView)
10012 DECLARE_VERIFIER(JSDataView)
10014 static const int kSize = kViewSize;
10016 static const int kSizeWithInternalFields =
10017 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10020 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10024 // Foreign describes objects pointing from JavaScript to C structures.
10025 // Since they cannot contain references to JS HeapObjects they can be
10026 // placed in old_data_space.
10027 class Foreign: public HeapObject {
10029 // [address]: field containing the address.
10030 inline Address foreign_address();
10031 inline void set_foreign_address(Address value);
10033 DECLARE_CAST(Foreign)
10035 // Dispatched behavior.
10036 inline void ForeignIterateBody(ObjectVisitor* v);
10038 template<typename StaticVisitor>
10039 inline void ForeignIterateBody();
10041 // Dispatched behavior.
10042 DECLARE_PRINTER(Foreign)
10043 DECLARE_VERIFIER(Foreign)
10045 // Layout description.
10047 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10048 static const int kSize = kForeignAddressOffset + kPointerSize;
10050 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10053 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10057 // The JSArray describes JavaScript Arrays
10058 // Such an array can be in one of two modes:
10059 // - fast, backing storage is a FixedArray and length <= elements.length();
10060 // Please note: push and pop can be used to grow and shrink the array.
10061 // - slow, backing storage is a HashTable with numbers as keys.
10062 class JSArray: public JSObject {
10064 // [length]: The length property.
10065 DECL_ACCESSORS(length, Object)
10067 // Overload the length setter to skip write barrier when the length
10068 // is set to a smi. This matches the set function on FixedArray.
10069 inline void set_length(Smi* length);
10071 static void JSArrayUpdateLengthFromIndex(Handle<JSArray> array,
10073 Handle<Object> value);
10075 static bool IsReadOnlyLengthDescriptor(Handle<Map> jsarray_map);
10076 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10077 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10079 // Initialize the array with the given capacity. The function may
10080 // fail due to out-of-memory situations, but only if the requested
10081 // capacity is non-zero.
10082 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10084 // Initializes the array to a certain length.
10085 inline bool AllowsSetElementsLength();
10087 MUST_USE_RESULT static MaybeHandle<Object> SetElementsLength(
10088 Handle<JSArray> array,
10089 Handle<Object> length);
10091 // Set the content of the array to the content of storage.
10092 static inline void SetContent(Handle<JSArray> array,
10093 Handle<FixedArrayBase> storage);
10095 DECLARE_CAST(JSArray)
10097 // Ensures that the fixed array backing the JSArray has at
10098 // least the stated size.
10099 static inline void EnsureSize(Handle<JSArray> array,
10100 int minimum_size_of_backing_fixed_array);
10102 // Expand the fixed array backing of a fast-case JSArray to at least
10103 // the requested size.
10104 static void Expand(Handle<JSArray> array,
10105 int minimum_size_of_backing_fixed_array);
10107 // Dispatched behavior.
10108 DECLARE_PRINTER(JSArray)
10109 DECLARE_VERIFIER(JSArray)
10111 // Number of element slots to pre-allocate for an empty array.
10112 static const int kPreallocatedArrayElements = 4;
10114 // Layout description.
10115 static const int kLengthOffset = JSObject::kHeaderSize;
10116 static const int kSize = kLengthOffset + kPointerSize;
10119 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10123 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10124 Handle<Map> initial_map);
10127 // JSRegExpResult is just a JSArray with a specific initial map.
10128 // This initial map adds in-object properties for "index" and "input"
10129 // properties, as assigned by RegExp.prototype.exec, which allows
10130 // faster creation of RegExp exec results.
10131 // This class just holds constants used when creating the result.
10132 // After creation the result must be treated as a JSArray in all regards.
10133 class JSRegExpResult: public JSArray {
10135 // Offsets of object fields.
10136 static const int kIndexOffset = JSArray::kSize;
10137 static const int kInputOffset = kIndexOffset + kPointerSize;
10138 static const int kSize = kInputOffset + kPointerSize;
10139 // Indices of in-object properties.
10140 static const int kIndexIndex = 0;
10141 static const int kInputIndex = 1;
10143 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10147 class AccessorInfo: public Struct {
10149 DECL_ACCESSORS(name, Object)
10150 DECL_ACCESSORS(flag, Smi)
10151 DECL_ACCESSORS(expected_receiver_type, Object)
10153 inline bool all_can_read();
10154 inline void set_all_can_read(bool value);
10156 inline bool all_can_write();
10157 inline void set_all_can_write(bool value);
10159 inline PropertyAttributes property_attributes();
10160 inline void set_property_attributes(PropertyAttributes attributes);
10162 // Checks whether the given receiver is compatible with this accessor.
10163 static bool IsCompatibleReceiverType(Isolate* isolate,
10164 Handle<AccessorInfo> info,
10165 Handle<HeapType> type);
10166 inline bool IsCompatibleReceiver(Object* receiver);
10168 DECLARE_CAST(AccessorInfo)
10170 // Dispatched behavior.
10171 DECLARE_VERIFIER(AccessorInfo)
10173 // Append all descriptors to the array that are not already there.
10174 // Return number added.
10175 static int AppendUnique(Handle<Object> descriptors,
10176 Handle<FixedArray> array,
10177 int valid_descriptors);
10179 static const int kNameOffset = HeapObject::kHeaderSize;
10180 static const int kFlagOffset = kNameOffset + kPointerSize;
10181 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10182 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10185 inline bool HasExpectedReceiverType() {
10186 return expected_receiver_type()->IsFunctionTemplateInfo();
10188 // Bit positions in flag.
10189 static const int kAllCanReadBit = 0;
10190 static const int kAllCanWriteBit = 1;
10191 class AttributesField: public BitField<PropertyAttributes, 2, 3> {};
10193 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10197 enum AccessorDescriptorType {
10198 kDescriptorBitmaskCompare,
10199 kDescriptorPointerCompare,
10200 kDescriptorPrimitiveValue,
10201 kDescriptorObjectDereference,
10202 kDescriptorPointerDereference,
10203 kDescriptorPointerShift,
10204 kDescriptorReturnObject
10208 struct BitmaskCompareDescriptor {
10210 uint32_t compare_value;
10211 uint8_t size; // Must be in {1,2,4}.
10215 struct PointerCompareDescriptor {
10216 void* compare_value;
10220 struct PrimitiveValueDescriptor {
10221 v8::DeclaredAccessorDescriptorDataType data_type;
10222 uint8_t bool_offset; // Must be in [0,7], used for kDescriptorBoolType.
10226 struct ObjectDerefenceDescriptor {
10227 uint8_t internal_field;
10231 struct PointerShiftDescriptor {
10232 int16_t byte_offset;
10236 struct DeclaredAccessorDescriptorData {
10237 AccessorDescriptorType type;
10239 struct BitmaskCompareDescriptor bitmask_compare_descriptor;
10240 struct PointerCompareDescriptor pointer_compare_descriptor;
10241 struct PrimitiveValueDescriptor primitive_value_descriptor;
10242 struct ObjectDerefenceDescriptor object_dereference_descriptor;
10243 struct PointerShiftDescriptor pointer_shift_descriptor;
10248 class DeclaredAccessorDescriptor;
10251 class DeclaredAccessorDescriptorIterator {
10253 explicit DeclaredAccessorDescriptorIterator(
10254 DeclaredAccessorDescriptor* descriptor);
10255 const DeclaredAccessorDescriptorData* Next();
10256 bool Complete() const { return length_ == offset_; }
10261 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptorIterator);
10265 class DeclaredAccessorDescriptor: public Struct {
10267 DECL_ACCESSORS(serialized_data, ByteArray)
10269 DECLARE_CAST(DeclaredAccessorDescriptor)
10271 static Handle<DeclaredAccessorDescriptor> Create(
10273 const DeclaredAccessorDescriptorData& data,
10274 Handle<DeclaredAccessorDescriptor> previous);
10276 // Dispatched behavior.
10277 DECLARE_PRINTER(DeclaredAccessorDescriptor)
10278 DECLARE_VERIFIER(DeclaredAccessorDescriptor)
10280 static const int kSerializedDataOffset = HeapObject::kHeaderSize;
10281 static const int kSize = kSerializedDataOffset + kPointerSize;
10284 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorDescriptor);
10288 class DeclaredAccessorInfo: public AccessorInfo {
10290 DECL_ACCESSORS(descriptor, DeclaredAccessorDescriptor)
10292 DECLARE_CAST(DeclaredAccessorInfo)
10294 // Dispatched behavior.
10295 DECLARE_PRINTER(DeclaredAccessorInfo)
10296 DECLARE_VERIFIER(DeclaredAccessorInfo)
10298 static const int kDescriptorOffset = AccessorInfo::kSize;
10299 static const int kSize = kDescriptorOffset + kPointerSize;
10302 DISALLOW_IMPLICIT_CONSTRUCTORS(DeclaredAccessorInfo);
10306 // An accessor must have a getter, but can have no setter.
10308 // When setting a property, V8 searches accessors in prototypes.
10309 // If an accessor was found and it does not have a setter,
10310 // the request is ignored.
10312 // If the accessor in the prototype has the READ_ONLY property attribute, then
10313 // a new value is added to the derived object when the property is set.
10314 // This shadows the accessor in the prototype.
10315 class ExecutableAccessorInfo: public AccessorInfo {
10317 DECL_ACCESSORS(getter, Object)
10318 DECL_ACCESSORS(setter, Object)
10319 DECL_ACCESSORS(data, Object)
10321 DECLARE_CAST(ExecutableAccessorInfo)
10323 // Dispatched behavior.
10324 DECLARE_PRINTER(ExecutableAccessorInfo)
10325 DECLARE_VERIFIER(ExecutableAccessorInfo)
10327 static const int kGetterOffset = AccessorInfo::kSize;
10328 static const int kSetterOffset = kGetterOffset + kPointerSize;
10329 static const int kDataOffset = kSetterOffset + kPointerSize;
10330 static const int kSize = kDataOffset + kPointerSize;
10332 inline void clear_setter();
10335 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10339 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10340 // accessor can either be
10341 // * a pointer to a JavaScript function or proxy: a real accessor
10342 // * undefined: considered an accessor by the spec, too, strangely enough
10343 // * the hole: an accessor which has not been set
10344 // * a pointer to a map: a transition used to ensure map sharing
10345 class AccessorPair: public Struct {
10347 DECL_ACCESSORS(getter, Object)
10348 DECL_ACCESSORS(setter, Object)
10350 DECLARE_CAST(AccessorPair)
10352 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10354 Object* get(AccessorComponent component) {
10355 return component == ACCESSOR_GETTER ? getter() : setter();
10358 void set(AccessorComponent component, Object* value) {
10359 if (component == ACCESSOR_GETTER) {
10366 // Note: Returns undefined instead in case of a hole.
10367 Object* GetComponent(AccessorComponent component);
10369 // Set both components, skipping arguments which are a JavaScript null.
10370 void SetComponents(Object* getter, Object* setter) {
10371 if (!getter->IsNull()) set_getter(getter);
10372 if (!setter->IsNull()) set_setter(setter);
10375 bool ContainsAccessor() {
10376 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10379 // Dispatched behavior.
10380 DECLARE_PRINTER(AccessorPair)
10381 DECLARE_VERIFIER(AccessorPair)
10383 static const int kGetterOffset = HeapObject::kHeaderSize;
10384 static const int kSetterOffset = kGetterOffset + kPointerSize;
10385 static const int kSize = kSetterOffset + kPointerSize;
10388 // Strangely enough, in addition to functions and harmony proxies, the spec
10389 // requires us to consider undefined as a kind of accessor, too:
10391 // Object.defineProperty(obj, "foo", {get: undefined});
10392 // assertTrue("foo" in obj);
10393 bool IsJSAccessor(Object* obj) {
10394 return obj->IsSpecFunction() || obj->IsUndefined();
10397 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10401 class AccessCheckInfo: public Struct {
10403 DECL_ACCESSORS(named_callback, Object)
10404 DECL_ACCESSORS(indexed_callback, Object)
10405 DECL_ACCESSORS(data, Object)
10407 DECLARE_CAST(AccessCheckInfo)
10409 // Dispatched behavior.
10410 DECLARE_PRINTER(AccessCheckInfo)
10411 DECLARE_VERIFIER(AccessCheckInfo)
10413 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10414 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10415 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10416 static const int kSize = kDataOffset + kPointerSize;
10419 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10423 class InterceptorInfo: public Struct {
10425 DECL_ACCESSORS(getter, Object)
10426 DECL_ACCESSORS(setter, Object)
10427 DECL_ACCESSORS(query, Object)
10428 DECL_ACCESSORS(deleter, Object)
10429 DECL_ACCESSORS(enumerator, Object)
10430 DECL_ACCESSORS(data, Object)
10432 DECLARE_CAST(InterceptorInfo)
10434 // Dispatched behavior.
10435 DECLARE_PRINTER(InterceptorInfo)
10436 DECLARE_VERIFIER(InterceptorInfo)
10438 static const int kGetterOffset = HeapObject::kHeaderSize;
10439 static const int kSetterOffset = kGetterOffset + kPointerSize;
10440 static const int kQueryOffset = kSetterOffset + kPointerSize;
10441 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10442 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10443 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10444 static const int kSize = kDataOffset + kPointerSize;
10447 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10451 class CallHandlerInfo: public Struct {
10453 DECL_ACCESSORS(callback, Object)
10454 DECL_ACCESSORS(data, Object)
10456 DECLARE_CAST(CallHandlerInfo)
10458 // Dispatched behavior.
10459 DECLARE_PRINTER(CallHandlerInfo)
10460 DECLARE_VERIFIER(CallHandlerInfo)
10462 static const int kCallbackOffset = HeapObject::kHeaderSize;
10463 static const int kDataOffset = kCallbackOffset + kPointerSize;
10464 static const int kSize = kDataOffset + kPointerSize;
10467 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10471 class TemplateInfo: public Struct {
10473 DECL_ACCESSORS(tag, Object)
10474 DECL_ACCESSORS(property_list, Object)
10475 DECL_ACCESSORS(property_accessors, Object)
10477 DECLARE_VERIFIER(TemplateInfo)
10479 static const int kTagOffset = HeapObject::kHeaderSize;
10480 static const int kPropertyListOffset = kTagOffset + kPointerSize;
10481 static const int kPropertyAccessorsOffset =
10482 kPropertyListOffset + kPointerSize;
10483 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10486 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10490 class FunctionTemplateInfo: public TemplateInfo {
10492 DECL_ACCESSORS(serial_number, Object)
10493 DECL_ACCESSORS(call_code, Object)
10494 DECL_ACCESSORS(prototype_template, Object)
10495 DECL_ACCESSORS(parent_template, Object)
10496 DECL_ACCESSORS(named_property_handler, Object)
10497 DECL_ACCESSORS(indexed_property_handler, Object)
10498 DECL_ACCESSORS(instance_template, Object)
10499 DECL_ACCESSORS(class_name, Object)
10500 DECL_ACCESSORS(signature, Object)
10501 DECL_ACCESSORS(instance_call_handler, Object)
10502 DECL_ACCESSORS(access_check_info, Object)
10503 DECL_ACCESSORS(flag, Smi)
10505 inline int length() const;
10506 inline void set_length(int value);
10508 // Following properties use flag bits.
10509 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10510 DECL_BOOLEAN_ACCESSORS(undetectable)
10511 // If the bit is set, object instances created by this function
10512 // requires access check.
10513 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10514 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10515 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10516 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10518 DECLARE_CAST(FunctionTemplateInfo)
10520 // Dispatched behavior.
10521 DECLARE_PRINTER(FunctionTemplateInfo)
10522 DECLARE_VERIFIER(FunctionTemplateInfo)
10524 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10525 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10526 static const int kPrototypeTemplateOffset =
10527 kCallCodeOffset + kPointerSize;
10528 static const int kParentTemplateOffset =
10529 kPrototypeTemplateOffset + kPointerSize;
10530 static const int kNamedPropertyHandlerOffset =
10531 kParentTemplateOffset + kPointerSize;
10532 static const int kIndexedPropertyHandlerOffset =
10533 kNamedPropertyHandlerOffset + kPointerSize;
10534 static const int kInstanceTemplateOffset =
10535 kIndexedPropertyHandlerOffset + kPointerSize;
10536 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10537 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10538 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10539 static const int kAccessCheckInfoOffset =
10540 kInstanceCallHandlerOffset + kPointerSize;
10541 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10542 static const int kLengthOffset = kFlagOffset + kPointerSize;
10543 static const int kSize = kLengthOffset + kPointerSize;
10545 // Returns true if |object| is an instance of this function template.
10546 bool IsTemplateFor(Object* object);
10547 bool IsTemplateFor(Map* map);
10550 // Bit position in the flag, from least significant bit position.
10551 static const int kHiddenPrototypeBit = 0;
10552 static const int kUndetectableBit = 1;
10553 static const int kNeedsAccessCheckBit = 2;
10554 static const int kReadOnlyPrototypeBit = 3;
10555 static const int kRemovePrototypeBit = 4;
10556 static const int kDoNotCacheBit = 5;
10558 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10562 class ObjectTemplateInfo: public TemplateInfo {
10564 DECL_ACCESSORS(constructor, Object)
10565 DECL_ACCESSORS(internal_field_count, Object)
10567 DECLARE_CAST(ObjectTemplateInfo)
10569 // Dispatched behavior.
10570 DECLARE_PRINTER(ObjectTemplateInfo)
10571 DECLARE_VERIFIER(ObjectTemplateInfo)
10573 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10574 static const int kInternalFieldCountOffset =
10575 kConstructorOffset + kPointerSize;
10576 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10580 class SignatureInfo: public Struct {
10582 DECL_ACCESSORS(receiver, Object)
10583 DECL_ACCESSORS(args, Object)
10585 DECLARE_CAST(SignatureInfo)
10587 // Dispatched behavior.
10588 DECLARE_PRINTER(SignatureInfo)
10589 DECLARE_VERIFIER(SignatureInfo)
10591 static const int kReceiverOffset = Struct::kHeaderSize;
10592 static const int kArgsOffset = kReceiverOffset + kPointerSize;
10593 static const int kSize = kArgsOffset + kPointerSize;
10596 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
10600 class TypeSwitchInfo: public Struct {
10602 DECL_ACCESSORS(types, Object)
10604 DECLARE_CAST(TypeSwitchInfo)
10606 // Dispatched behavior.
10607 DECLARE_PRINTER(TypeSwitchInfo)
10608 DECLARE_VERIFIER(TypeSwitchInfo)
10610 static const int kTypesOffset = Struct::kHeaderSize;
10611 static const int kSize = kTypesOffset + kPointerSize;
10615 // The DebugInfo class holds additional information for a function being
10617 class DebugInfo: public Struct {
10619 // The shared function info for the source being debugged.
10620 DECL_ACCESSORS(shared, SharedFunctionInfo)
10621 // Code object for the original code.
10622 DECL_ACCESSORS(original_code, Code)
10623 // Code object for the patched code. This code object is the code object
10624 // currently active for the function.
10625 DECL_ACCESSORS(code, Code)
10626 // Fixed array holding status information for each active break point.
10627 DECL_ACCESSORS(break_points, FixedArray)
10629 // Check if there is a break point at a code position.
10630 bool HasBreakPoint(int code_position);
10631 // Get the break point info object for a code position.
10632 Object* GetBreakPointInfo(int code_position);
10633 // Clear a break point.
10634 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10636 Handle<Object> break_point_object);
10637 // Set a break point.
10638 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10639 int source_position, int statement_position,
10640 Handle<Object> break_point_object);
10641 // Get the break point objects for a code position.
10642 Object* GetBreakPointObjects(int code_position);
10643 // Find the break point info holding this break point object.
10644 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
10645 Handle<Object> break_point_object);
10646 // Get the number of break points for this function.
10647 int GetBreakPointCount();
10649 DECLARE_CAST(DebugInfo)
10651 // Dispatched behavior.
10652 DECLARE_PRINTER(DebugInfo)
10653 DECLARE_VERIFIER(DebugInfo)
10655 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10656 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10657 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
10658 static const int kActiveBreakPointsCountIndex =
10659 kPatchedCodeIndex + kPointerSize;
10660 static const int kBreakPointsStateIndex =
10661 kActiveBreakPointsCountIndex + kPointerSize;
10662 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10664 static const int kEstimatedNofBreakPointsInFunction = 16;
10667 static const int kNoBreakPointInfo = -1;
10669 // Lookup the index in the break_points array for a code position.
10670 int GetBreakPointInfoIndex(int code_position);
10672 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10676 // The BreakPointInfo class holds information for break points set in a
10677 // function. The DebugInfo object holds a BreakPointInfo object for each code
10678 // position with one or more break points.
10679 class BreakPointInfo: public Struct {
10681 // The position in the code for the break point.
10682 DECL_ACCESSORS(code_position, Smi)
10683 // The position in the source for the break position.
10684 DECL_ACCESSORS(source_position, Smi)
10685 // The position in the source for the last statement before this break
10687 DECL_ACCESSORS(statement_position, Smi)
10688 // List of related JavaScript break points.
10689 DECL_ACCESSORS(break_point_objects, Object)
10691 // Removes a break point.
10692 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10693 Handle<Object> break_point_object);
10694 // Set a break point.
10695 static void SetBreakPoint(Handle<BreakPointInfo> info,
10696 Handle<Object> break_point_object);
10697 // Check if break point info has this break point object.
10698 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10699 Handle<Object> break_point_object);
10700 // Get the number of break points for this code position.
10701 int GetBreakPointCount();
10703 DECLARE_CAST(BreakPointInfo)
10705 // Dispatched behavior.
10706 DECLARE_PRINTER(BreakPointInfo)
10707 DECLARE_VERIFIER(BreakPointInfo)
10709 static const int kCodePositionIndex = Struct::kHeaderSize;
10710 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10711 static const int kStatementPositionIndex =
10712 kSourcePositionIndex + kPointerSize;
10713 static const int kBreakPointObjectsIndex =
10714 kStatementPositionIndex + kPointerSize;
10715 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10718 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10722 #undef DECL_BOOLEAN_ACCESSORS
10723 #undef DECL_ACCESSORS
10724 #undef DECLARE_CAST
10725 #undef DECLARE_VERIFIER
10727 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10728 V(kStringTable, "string_table", "(Internalized strings)") \
10729 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10730 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10731 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10732 V(kInternalizedString, "internalized_string", "(Internal string)") \
10733 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10734 V(kTop, "top", "(Isolate)") \
10735 V(kRelocatable, "relocatable", "(Relocatable)") \
10736 V(kDebug, "debug", "(Debugger)") \
10737 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10738 V(kHandleScope, "handlescope", "(Handle scope)") \
10739 V(kBuiltins, "builtins", "(Builtins)") \
10740 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10741 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10742 V(kThreadManager, "threadmanager", "(Thread manager)") \
10743 V(kExtensions, "Extensions", "(Extensions)")
10745 class VisitorSynchronization : public AllStatic {
10747 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10749 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10752 #undef DECLARE_ENUM
10754 static const char* const kTags[kNumberOfSyncTags];
10755 static const char* const kTagNames[kNumberOfSyncTags];
10758 // Abstract base class for visiting, and optionally modifying, the
10759 // pointers contained in Objects. Used in GC and serialization/deserialization.
10760 class ObjectVisitor BASE_EMBEDDED {
10762 virtual ~ObjectVisitor() {}
10764 // Visits a contiguous arrays of pointers in the half-open range
10765 // [start, end). Any or all of the values may be modified on return.
10766 virtual void VisitPointers(Object** start, Object** end) = 0;
10768 // Handy shorthand for visiting a single pointer.
10769 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10771 // Visit weak next_code_link in Code object.
10772 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10774 // To allow lazy clearing of inline caches the visitor has
10775 // a rich interface for iterating over Code objects..
10777 // Visits a code target in the instruction stream.
10778 virtual void VisitCodeTarget(RelocInfo* rinfo);
10780 // Visits a code entry in a JS function.
10781 virtual void VisitCodeEntry(Address entry_address);
10783 // Visits a global property cell reference in the instruction stream.
10784 virtual void VisitCell(RelocInfo* rinfo);
10786 // Visits a runtime entry in the instruction stream.
10787 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10789 // Visits the resource of an one-byte or two-byte string.
10790 virtual void VisitExternalOneByteString(
10791 v8::String::ExternalOneByteStringResource** resource) {}
10792 virtual void VisitExternalTwoByteString(
10793 v8::String::ExternalStringResource** resource) {}
10795 // Visits a debug call target in the instruction stream.
10796 virtual void VisitDebugTarget(RelocInfo* rinfo);
10798 // Visits the byte sequence in a function's prologue that contains information
10799 // about the code's age.
10800 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10802 // Visit pointer embedded into a code object.
10803 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10805 // Visits an external reference embedded into a code object.
10806 virtual void VisitExternalReference(RelocInfo* rinfo);
10808 // Visits an external reference. The value may be modified on return.
10809 virtual void VisitExternalReference(Address* p) {}
10811 // Visits a handle that has an embedder-assigned class ID.
10812 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10814 // Intended for serialization/deserialization checking: insert, or
10815 // check for the presence of, a tag at this position in the stream.
10816 // Also used for marking up GC roots in heap snapshots.
10817 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10821 class StructBodyDescriptor : public
10822 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10824 static inline int SizeOf(Map* map, HeapObject* object) {
10825 return map->instance_size();
10830 // BooleanBit is a helper class for setting and getting a bit in an
10832 class BooleanBit : public AllStatic {
10834 static inline bool get(Smi* smi, int bit_position) {
10835 return get(smi->value(), bit_position);
10838 static inline bool get(int value, int bit_position) {
10839 return (value & (1 << bit_position)) != 0;
10842 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10843 return Smi::FromInt(set(smi->value(), bit_position, v));
10846 static inline int set(int value, int bit_position, bool v) {
10848 value |= (1 << bit_position);
10850 value &= ~(1 << bit_position);
10856 } } // namespace v8::internal
10858 #endif // V8_OBJECTS_H_