1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/bailout-reason.h"
13 #include "src/base/bits.h"
14 #include "src/base/smart-pointers.h"
15 #include "src/builtins.h"
16 #include "src/checks.h"
17 #include "src/elements-kind.h"
18 #include "src/field-index.h"
19 #include "src/flags.h"
21 #include "src/property-details.h"
22 #include "src/unicode-inl.h"
23 #include "src/unicode-decoder.h"
26 #if V8_TARGET_ARCH_ARM
27 #include "src/arm/constants-arm.h" // NOLINT
28 #elif V8_TARGET_ARCH_ARM64
29 #include "src/arm64/constants-arm64.h" // NOLINT
30 #elif V8_TARGET_ARCH_MIPS
31 #include "src/mips/constants-mips.h" // NOLINT
32 #elif V8_TARGET_ARCH_MIPS64
33 #include "src/mips64/constants-mips64.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/constants-ppc.h" // NOLINT
40 // Most object types in the V8 JavaScript are described in this file.
42 // Inheritance hierarchy:
44 // - Smi (immediate small integer)
45 // - HeapObject (superclass for everything allocated in the heap)
46 // - JSReceiver (suitable for property access)
50 // - JSArrayBufferView
63 // - JSGeneratorObject
81 // - CompilationCacheTable
82 // - CodeCacheHashTable
88 // - TypeFeedbackVector
89 // - JSFunctionResultCache
92 // - ScriptContextTable
96 // - ExternalUint8ClampedArray
97 // - ExternalInt8Array
98 // - ExternalUint8Array
99 // - ExternalInt16Array
100 // - ExternalUint16Array
101 // - ExternalInt32Array
102 // - ExternalUint32Array
103 // - ExternalFloat32Array
107 // - SeqOneByteString
108 // - SeqTwoByteString
112 // - ExternalOneByteString
113 // - ExternalTwoByteString
114 // - InternalizedString
115 // - SeqInternalizedString
116 // - SeqOneByteInternalizedString
117 // - SeqTwoByteInternalizedString
118 // - ConsInternalizedString
119 // - ExternalInternalizedString
120 // - ExternalOneByteInternalizedString
121 // - ExternalTwoByteInternalizedString
131 // - SharedFunctionInfo
135 // - ExecutableAccessorInfo
141 // - FunctionTemplateInfo
142 // - ObjectTemplateInfo
151 // Formats of Object*:
152 // Smi: [31 bit signed int] 0
153 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
158 enum KeyedAccessStoreMode {
160 STORE_TRANSITION_SMI_TO_OBJECT,
161 STORE_TRANSITION_SMI_TO_DOUBLE,
162 STORE_TRANSITION_DOUBLE_TO_OBJECT,
163 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
164 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
165 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
166 STORE_AND_GROW_NO_TRANSITION,
167 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
168 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
169 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
170 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
171 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
172 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
173 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
174 STORE_NO_TRANSITION_HANDLE_COW
178 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
187 enum ExternalArrayType {
188 kExternalInt8Array = 1,
191 kExternalUint16Array,
193 kExternalUint32Array,
194 kExternalFloat32Array,
195 kExternalFloat64Array,
196 kExternalUint8ClampedArray,
200 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
202 STATIC_ASSERT(STANDARD_STORE == 0);
203 STATIC_ASSERT(kGrowICDelta ==
204 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
205 STORE_TRANSITION_SMI_TO_OBJECT);
206 STATIC_ASSERT(kGrowICDelta ==
207 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
208 STORE_TRANSITION_SMI_TO_DOUBLE);
209 STATIC_ASSERT(kGrowICDelta ==
210 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
211 STORE_TRANSITION_DOUBLE_TO_OBJECT);
214 static inline KeyedAccessStoreMode GetGrowStoreMode(
215 KeyedAccessStoreMode store_mode) {
216 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
217 store_mode = static_cast<KeyedAccessStoreMode>(
218 static_cast<int>(store_mode) + kGrowICDelta);
224 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
225 return store_mode > STANDARD_STORE &&
226 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
227 store_mode != STORE_AND_GROW_NO_TRANSITION;
231 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
232 KeyedAccessStoreMode store_mode) {
233 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
236 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
237 return STORE_AND_GROW_NO_TRANSITION;
239 return STANDARD_STORE;
243 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
244 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
245 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
249 enum IcCheckType { ELEMENT, PROPERTY };
252 // SKIP_WRITE_BARRIER skips the write barrier.
253 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
254 // only performs the generational part.
255 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
256 enum WriteBarrierMode {
258 UPDATE_WEAK_WRITE_BARRIER,
263 // Indicates whether a value can be loaded as a constant.
264 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
267 // PropertyNormalizationMode is used to specify whether to keep
268 // inobject properties when normalizing properties of a JSObject.
269 enum PropertyNormalizationMode {
270 CLEAR_INOBJECT_PROPERTIES,
271 KEEP_INOBJECT_PROPERTIES
275 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
276 // will give the fastest result by tailoring the map to the prototype, but that
277 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
278 // (at least for now) when dynamically modifying the prototype chain of an
279 // object using __proto__ or Object.setPrototypeOf.
280 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
283 // Indicates whether transitions can be added to a source map or not.
284 enum TransitionFlag {
290 // Indicates whether the transition is simple: the target map of the transition
291 // either extends the current map with a new property, or it modifies the
292 // property that was added last to the current map.
293 enum SimpleTransitionFlag {
294 SIMPLE_PROPERTY_TRANSITION,
300 // Indicates whether we are only interested in the descriptors of a particular
301 // map, or in all descriptors in the descriptor array.
302 enum DescriptorFlag {
307 // The GC maintains a bit of information, the MarkingParity, which toggles
308 // from odd to even and back every time marking is completed. Incremental
309 // marking can visit an object twice during a marking phase, so algorithms that
310 // that piggy-back on marking can use the parity to ensure that they only
311 // perform an operation on an object once per marking phase: they record the
312 // MarkingParity when they visit an object, and only re-visit the object when it
313 // is marked again and the MarkingParity changes.
320 // ICs store extra state in a Code object. The default extra state is
322 typedef int ExtraICState;
323 static const ExtraICState kNoExtraICState = 0;
325 // Instance size sentinel for objects of variable size.
326 const int kVariableSizeSentinel = 0;
328 // We may store the unsigned bit field as signed Smi value and do not
330 const int kStubMajorKeyBits = 7;
331 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
333 // All Maps have a field instance_type containing a InstanceType.
334 // It describes the type of the instances.
336 // As an example, a JavaScript object is a heap object and its map
337 // instance_type is JS_OBJECT_TYPE.
339 // The names of the string instance types are intended to systematically
340 // mirror their encoding in the instance_type field of the map. The default
341 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
342 // encoding is mentioned explicitly in the name. Likewise, the default
343 // representation is considered sequential. It is not mentioned in the
344 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
345 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
346 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
348 // NOTE: The following things are some that depend on the string types having
349 // instance_types that are less than those of all other types:
350 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
353 // NOTE: Everything following JS_VALUE_TYPE is considered a
354 // JSObject for GC purposes. The first four entries here have typeof
355 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
356 #define INSTANCE_TYPE_LIST(V) \
358 V(ONE_BYTE_STRING_TYPE) \
359 V(CONS_STRING_TYPE) \
360 V(CONS_ONE_BYTE_STRING_TYPE) \
361 V(SLICED_STRING_TYPE) \
362 V(SLICED_ONE_BYTE_STRING_TYPE) \
363 V(EXTERNAL_STRING_TYPE) \
364 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
365 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
366 V(SHORT_EXTERNAL_STRING_TYPE) \
367 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
368 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
370 V(INTERNALIZED_STRING_TYPE) \
371 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
372 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
373 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
374 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
375 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
376 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
377 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
385 V(PROPERTY_CELL_TYPE) \
387 V(HEAP_NUMBER_TYPE) \
388 V(MUTABLE_HEAP_NUMBER_TYPE) \
393 /* Note: the order of these external array */ \
394 /* types is relied upon in */ \
395 /* Object::IsExternalArray(). */ \
396 V(EXTERNAL_INT8_ARRAY_TYPE) \
397 V(EXTERNAL_UINT8_ARRAY_TYPE) \
398 V(EXTERNAL_INT16_ARRAY_TYPE) \
399 V(EXTERNAL_UINT16_ARRAY_TYPE) \
400 V(EXTERNAL_INT32_ARRAY_TYPE) \
401 V(EXTERNAL_UINT32_ARRAY_TYPE) \
402 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
403 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
404 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
406 V(FIXED_INT8_ARRAY_TYPE) \
407 V(FIXED_UINT8_ARRAY_TYPE) \
408 V(FIXED_INT16_ARRAY_TYPE) \
409 V(FIXED_UINT16_ARRAY_TYPE) \
410 V(FIXED_INT32_ARRAY_TYPE) \
411 V(FIXED_UINT32_ARRAY_TYPE) \
412 V(FIXED_FLOAT32_ARRAY_TYPE) \
413 V(FIXED_FLOAT64_ARRAY_TYPE) \
414 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
418 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
419 V(DECLARED_ACCESSOR_INFO_TYPE) \
420 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
421 V(ACCESSOR_PAIR_TYPE) \
422 V(ACCESS_CHECK_INFO_TYPE) \
423 V(INTERCEPTOR_INFO_TYPE) \
424 V(CALL_HANDLER_INFO_TYPE) \
425 V(FUNCTION_TEMPLATE_INFO_TYPE) \
426 V(OBJECT_TEMPLATE_INFO_TYPE) \
427 V(SIGNATURE_INFO_TYPE) \
428 V(TYPE_SWITCH_INFO_TYPE) \
429 V(ALLOCATION_MEMENTO_TYPE) \
430 V(ALLOCATION_SITE_TYPE) \
433 V(POLYMORPHIC_CODE_CACHE_TYPE) \
434 V(TYPE_FEEDBACK_INFO_TYPE) \
435 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
437 V(PROTOTYPE_INFO_TYPE) \
439 V(FIXED_ARRAY_TYPE) \
440 V(FIXED_DOUBLE_ARRAY_TYPE) \
441 V(SHARED_FUNCTION_INFO_TYPE) \
444 V(JS_MESSAGE_OBJECT_TYPE) \
449 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
450 V(JS_GENERATOR_OBJECT_TYPE) \
452 V(JS_GLOBAL_OBJECT_TYPE) \
453 V(JS_BUILTINS_OBJECT_TYPE) \
454 V(JS_GLOBAL_PROXY_TYPE) \
456 V(JS_ARRAY_BUFFER_TYPE) \
457 V(JS_TYPED_ARRAY_TYPE) \
458 V(JS_DATA_VIEW_TYPE) \
462 V(JS_SET_ITERATOR_TYPE) \
463 V(JS_MAP_ITERATOR_TYPE) \
464 V(JS_WEAK_MAP_TYPE) \
465 V(JS_WEAK_SET_TYPE) \
468 V(JS_FUNCTION_TYPE) \
469 V(JS_FUNCTION_PROXY_TYPE) \
471 V(BREAK_POINT_INFO_TYPE)
474 // Since string types are not consecutive, this macro is used to
475 // iterate over them.
476 #define STRING_TYPE_LIST(V) \
477 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
478 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
480 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
481 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
483 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
484 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
485 SlicedOneByteString) \
486 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
488 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
489 external_one_byte_string, ExternalOneByteString) \
490 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
491 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
492 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
493 short_external_string, ShortExternalString) \
494 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
495 short_external_one_byte_string, ShortExternalOneByteString) \
496 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
497 ExternalTwoByteString::kShortSize, \
498 short_external_string_with_one_byte_data, \
499 ShortExternalStringWithOneByteData) \
501 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
502 InternalizedString) \
503 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
504 one_byte_internalized_string, OneByteInternalizedString) \
505 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
506 external_internalized_string, ExternalInternalizedString) \
507 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
508 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
509 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
510 ExternalTwoByteString::kSize, \
511 external_internalized_string_with_one_byte_data, \
512 ExternalInternalizedStringWithOneByteData) \
513 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
514 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
515 ShortExternalInternalizedString) \
516 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
517 ExternalOneByteString::kShortSize, \
518 short_external_one_byte_internalized_string, \
519 ShortExternalOneByteInternalizedString) \
520 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
521 ExternalTwoByteString::kShortSize, \
522 short_external_internalized_string_with_one_byte_data, \
523 ShortExternalInternalizedStringWithOneByteData)
525 // A struct is a simple object a set of object-valued fields. Including an
526 // object type in this causes the compiler to generate most of the boilerplate
527 // code for the class including allocation and garbage collection routines,
528 // casts and predicates. All you need to define is the class, methods and
529 // object verification routines. Easy, no?
531 // Note that for subtle reasons related to the ordering or numerical values of
532 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
534 #define STRUCT_LIST(V) \
536 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
537 executable_accessor_info) \
538 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
539 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
540 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
541 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
542 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
543 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
544 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
545 V(SCRIPT, Script, script) \
546 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
547 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
548 V(CODE_CACHE, CodeCache, code_cache) \
549 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
550 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
551 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
552 V(DEBUG_INFO, DebugInfo, debug_info) \
553 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
554 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
556 // We use the full 8 bits of the instance_type field to encode heap object
557 // instance types. The high-order bit (bit 7) is set if the object is not a
558 // string, and cleared if it is a string.
559 const uint32_t kIsNotStringMask = 0x80;
560 const uint32_t kStringTag = 0x0;
561 const uint32_t kNotStringTag = 0x80;
563 // Bit 6 indicates that the object is an internalized string (if set) or not.
564 // Bit 7 has to be clear as well.
565 const uint32_t kIsNotInternalizedMask = 0x40;
566 const uint32_t kNotInternalizedTag = 0x40;
567 const uint32_t kInternalizedTag = 0x0;
569 // If bit 7 is clear then bit 2 indicates whether the string consists of
570 // two-byte characters or one-byte characters.
571 const uint32_t kStringEncodingMask = 0x4;
572 const uint32_t kTwoByteStringTag = 0x0;
573 const uint32_t kOneByteStringTag = 0x4;
575 // If bit 7 is clear, the low-order 2 bits indicate the representation
577 const uint32_t kStringRepresentationMask = 0x03;
578 enum StringRepresentationTag {
580 kConsStringTag = 0x1,
581 kExternalStringTag = 0x2,
582 kSlicedStringTag = 0x3
584 const uint32_t kIsIndirectStringMask = 0x1;
585 const uint32_t kIsIndirectStringTag = 0x1;
586 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
587 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
588 STATIC_ASSERT((kConsStringTag &
589 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
590 STATIC_ASSERT((kSlicedStringTag &
591 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
593 // Use this mask to distinguish between cons and slice only after making
594 // sure that the string is one of the two (an indirect string).
595 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
596 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
598 // If bit 7 is clear, then bit 3 indicates whether this two-byte
599 // string actually contains one byte data.
600 const uint32_t kOneByteDataHintMask = 0x08;
601 const uint32_t kOneByteDataHintTag = 0x08;
603 // If bit 7 is clear and string representation indicates an external string,
604 // then bit 4 indicates whether the data pointer is cached.
605 const uint32_t kShortExternalStringMask = 0x10;
606 const uint32_t kShortExternalStringTag = 0x10;
609 // A ConsString with an empty string as the right side is a candidate
610 // for being shortcut by the garbage collector. We don't allocate any
611 // non-flat internalized strings, so we do not shortcut them thereby
612 // avoiding turning internalized strings into strings. The bit-masks
613 // below contain the internalized bit as additional safety.
614 // See heap.cc, mark-compact.cc and objects-visiting.cc.
615 const uint32_t kShortcutTypeMask =
617 kIsNotInternalizedMask |
618 kStringRepresentationMask;
619 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
621 static inline bool IsShortcutCandidate(int type) {
622 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
628 INTERNALIZED_STRING_TYPE =
629 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
630 ONE_BYTE_INTERNALIZED_STRING_TYPE =
631 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
632 EXTERNAL_INTERNALIZED_STRING_TYPE =
633 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
634 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
635 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
636 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
637 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
639 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
640 kShortExternalStringTag |
642 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
643 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
645 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
646 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
647 kShortExternalStringTag | kInternalizedTag,
648 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
649 ONE_BYTE_STRING_TYPE =
650 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
651 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
652 CONS_ONE_BYTE_STRING_TYPE =
653 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
655 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
656 SLICED_ONE_BYTE_STRING_TYPE =
657 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
658 EXTERNAL_STRING_TYPE =
659 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
660 EXTERNAL_ONE_BYTE_STRING_TYPE =
661 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
662 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
663 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
665 SHORT_EXTERNAL_STRING_TYPE =
666 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
667 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
668 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
669 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
670 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
674 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
676 // Objects allocated in their own spaces (never in new space).
681 // "Data", objects that cannot contain non-map-word pointers to heap
684 MUTABLE_HEAP_NUMBER_TYPE,
685 FLOAT32X4_TYPE, // FIRST_SIMD_TYPE, LAST_SIMD_TYPE
689 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
690 EXTERNAL_UINT8_ARRAY_TYPE,
691 EXTERNAL_INT16_ARRAY_TYPE,
692 EXTERNAL_UINT16_ARRAY_TYPE,
693 EXTERNAL_INT32_ARRAY_TYPE,
694 EXTERNAL_UINT32_ARRAY_TYPE,
695 EXTERNAL_FLOAT32_ARRAY_TYPE,
696 EXTERNAL_FLOAT64_ARRAY_TYPE,
697 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
698 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
699 FIXED_UINT8_ARRAY_TYPE,
700 FIXED_INT16_ARRAY_TYPE,
701 FIXED_UINT16_ARRAY_TYPE,
702 FIXED_INT32_ARRAY_TYPE,
703 FIXED_UINT32_ARRAY_TYPE,
704 FIXED_FLOAT32_ARRAY_TYPE,
705 FIXED_FLOAT64_ARRAY_TYPE,
706 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
707 FIXED_DOUBLE_ARRAY_TYPE,
708 FILLER_TYPE, // LAST_DATA_TYPE
711 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
712 DECLARED_ACCESSOR_INFO_TYPE,
713 EXECUTABLE_ACCESSOR_INFO_TYPE,
715 ACCESS_CHECK_INFO_TYPE,
716 INTERCEPTOR_INFO_TYPE,
717 CALL_HANDLER_INFO_TYPE,
718 FUNCTION_TEMPLATE_INFO_TYPE,
719 OBJECT_TEMPLATE_INFO_TYPE,
721 TYPE_SWITCH_INFO_TYPE,
722 ALLOCATION_SITE_TYPE,
723 ALLOCATION_MEMENTO_TYPE,
726 POLYMORPHIC_CODE_CACHE_TYPE,
727 TYPE_FEEDBACK_INFO_TYPE,
728 ALIASED_ARGUMENTS_ENTRY_TYPE,
731 BREAK_POINT_INFO_TYPE,
733 SHARED_FUNCTION_INFO_TYPE,
739 // All the following types are subtypes of JSReceiver, which corresponds to
740 // objects in the JS sense. The first and the last type in this range are
741 // the two forms of function. This organization enables using the same
742 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
743 // NONCALLABLE_JS_OBJECT range.
744 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
745 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
746 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
747 JS_MESSAGE_OBJECT_TYPE,
750 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
751 JS_GENERATOR_OBJECT_TYPE,
753 JS_GLOBAL_OBJECT_TYPE,
754 JS_BUILTINS_OBJECT_TYPE,
755 JS_GLOBAL_PROXY_TYPE,
757 JS_ARRAY_BUFFER_TYPE,
762 JS_SET_ITERATOR_TYPE,
763 JS_MAP_ITERATOR_TYPE,
767 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
771 LAST_TYPE = JS_FUNCTION_TYPE,
772 FIRST_NAME_TYPE = FIRST_TYPE,
773 LAST_NAME_TYPE = SYMBOL_TYPE,
774 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
775 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
776 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
777 // Boundaries for testing for a SIMD type.
778 FIRST_SIMD_TYPE = FLOAT32X4_TYPE,
779 LAST_SIMD_TYPE = FLOAT32X4_TYPE,
780 // Boundaries for testing for an external array.
781 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
782 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
783 // Boundaries for testing for a fixed typed array.
784 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
785 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
786 // Boundary for promotion to old space.
787 LAST_DATA_TYPE = FILLER_TYPE,
788 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
789 // Note that there is no range for JSObject or JSProxy, since their subtypes
790 // are not continuous in this enum! The enum ranges instead reflect the
791 // external class names, where proxies are treated as either ordinary objects,
793 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
794 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
795 // Boundaries for testing the types represented as JSObject
796 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
797 LAST_JS_OBJECT_TYPE = LAST_TYPE,
798 // Boundaries for testing the types represented as JSProxy
799 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
800 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
801 // Boundaries for testing whether the type is a JavaScript object.
802 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
803 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
804 // Boundaries for testing the types for which typeof is "object".
805 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
806 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
807 // Note that the types for which typeof is "function" are not continuous.
808 // Define this so that we can put assertions on discrete checks.
809 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
812 const int kExternalArrayTypeCount =
813 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
815 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
816 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
817 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
818 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
821 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
822 V(FAST_ELEMENTS_SUB_TYPE) \
823 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
824 V(FAST_PROPERTIES_SUB_TYPE) \
825 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
826 V(MAP_CODE_CACHE_SUB_TYPE) \
827 V(SCOPE_INFO_SUB_TYPE) \
828 V(STRING_TABLE_SUB_TYPE) \
829 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
830 V(TRANSITION_ARRAY_SUB_TYPE)
832 enum FixedArraySubInstanceType {
833 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
834 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
835 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
836 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
849 #define DECL_BOOLEAN_ACCESSORS(name) \
850 inline bool name() const; \
851 inline void set_##name(bool value); \
854 #define DECL_ACCESSORS(name, type) \
855 inline type* name() const; \
856 inline void set_##name(type* value, \
857 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
860 #define DECLARE_CAST(type) \
861 INLINE(static type* cast(Object* object)); \
862 INLINE(static const type* cast(const Object* object));
866 class AllocationSite;
867 class AllocationSiteCreationContext;
868 class AllocationSiteUsageContext;
871 class ElementsAccessor;
872 class FixedArrayBase;
873 class FunctionLiteral;
875 class JSBuiltinsObject;
876 class LayoutDescriptor;
877 class LookupIterator;
878 class ObjectHashTable;
881 class SafepointEntry;
882 class SharedFunctionInfo;
884 class TypeFeedbackInfo;
885 class TypeFeedbackVector;
888 // We cannot just say "class HeapType;" if it is created from a template... =8-?
889 template<class> class TypeImpl;
890 struct HeapTypeConfig;
891 typedef TypeImpl<HeapTypeConfig> HeapType;
894 // A template-ized version of the IsXXX functions.
895 template <class C> inline bool Is(Object* obj);
898 #define DECLARE_VERIFIER(Name) void Name##Verify();
900 #define DECLARE_VERIFIER(Name)
904 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
906 #define DECLARE_PRINTER(Name)
910 #define OBJECT_TYPE_LIST(V) \
915 #define HEAP_OBJECT_TYPE_LIST(V) \
917 V(MutableHeapNumber) \
925 V(ExternalTwoByteString) \
926 V(ExternalOneByteString) \
927 V(SeqTwoByteString) \
928 V(SeqOneByteString) \
929 V(InternalizedString) \
933 V(ExternalInt8Array) \
934 V(ExternalUint8Array) \
935 V(ExternalInt16Array) \
936 V(ExternalUint16Array) \
937 V(ExternalInt32Array) \
938 V(ExternalUint32Array) \
939 V(ExternalFloat32Array) \
940 V(ExternalFloat64Array) \
941 V(ExternalUint8ClampedArray) \
942 V(FixedTypedArrayBase) \
945 V(FixedUint16Array) \
947 V(FixedUint32Array) \
949 V(FixedFloat32Array) \
950 V(FixedFloat64Array) \
951 V(FixedUint8ClampedArray) \
957 V(JSContextExtensionObject) \
958 V(JSGeneratorObject) \
960 V(LayoutDescriptor) \
964 V(TypeFeedbackVector) \
965 V(DeoptimizationInputData) \
966 V(DeoptimizationOutputData) \
970 V(FixedDoubleArray) \
974 V(ScriptContextTable) \
980 V(SharedFunctionInfo) \
989 V(JSArrayBufferView) \
998 V(JSWeakCollection) \
1005 V(JSFunctionResultCache) \
1006 V(NormalizedMapCache) \
1007 V(CompilationCacheTable) \
1008 V(CodeCacheHashTable) \
1009 V(PolymorphicCodeCacheHashTable) \
1014 V(JSBuiltinsObject) \
1016 V(UndetectableObject) \
1017 V(AccessCheckNeeded) \
1021 V(ObjectHashTable) \
1023 V(WeakValueHashTable) \
1026 // Object is the abstract superclass for all classes in the
1027 // object hierarchy.
1028 // Object does not use any virtual functions to avoid the
1029 // allocation of the C++ vtable.
1030 // Since both Smi and HeapObject are subclasses of Object no
1031 // data members can be present in Object.
1035 bool IsObject() const { return true; }
1037 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1038 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1039 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1040 #undef IS_TYPE_FUNCTION_DECL
1042 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1043 // a keyed store is of the form a[expression] = foo.
1044 enum StoreFromKeyed {
1045 MAY_BE_STORE_FROM_KEYED,
1046 CERTAINLY_NOT_STORE_FROM_KEYED
1049 INLINE(bool IsFixedArrayBase() const);
1050 INLINE(bool IsExternal() const);
1051 INLINE(bool IsAccessorInfo() const);
1053 INLINE(bool IsStruct() const);
1054 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1055 INLINE(bool Is##Name() const);
1056 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1057 #undef DECLARE_STRUCT_PREDICATE
1059 INLINE(bool IsSpecObject()) const;
1060 INLINE(bool IsSpecFunction()) const;
1061 INLINE(bool IsTemplateInfo()) const;
1062 INLINE(bool IsNameDictionary() const);
1063 INLINE(bool IsGlobalDictionary() const);
1064 INLINE(bool IsSeededNumberDictionary() const);
1065 INLINE(bool IsUnseededNumberDictionary() const);
1066 INLINE(bool IsOrderedHashSet() const);
1067 INLINE(bool IsOrderedHashMap() const);
1068 bool IsCallable() const;
1069 static bool IsPromise(Handle<Object> object);
1072 INLINE(bool IsUndefined() const);
1073 INLINE(bool IsNull() const);
1074 INLINE(bool IsTheHole() const);
1075 INLINE(bool IsException() const);
1076 INLINE(bool IsUninitialized() const);
1077 INLINE(bool IsTrue() const);
1078 INLINE(bool IsFalse() const);
1079 INLINE(bool IsArgumentsMarker() const);
1081 // Filler objects (fillers and free space objects).
1082 INLINE(bool IsFiller() const);
1084 // Extract the number.
1085 inline double Number();
1086 INLINE(bool IsNaN() const);
1087 INLINE(bool IsMinusZero() const);
1088 bool ToInt32(int32_t* value);
1089 bool ToUint32(uint32_t* value);
1091 inline Representation OptimalRepresentation() {
1092 if (!FLAG_track_fields) return Representation::Tagged();
1094 return Representation::Smi();
1095 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1096 return Representation::Double();
1097 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1098 return Representation::None();
1099 } else if (FLAG_track_heap_object_fields) {
1100 DCHECK(IsHeapObject());
1101 return Representation::HeapObject();
1103 return Representation::Tagged();
1107 inline ElementsKind OptimalElementsKind() {
1108 if (IsSmi()) return FAST_SMI_ELEMENTS;
1109 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1110 return FAST_ELEMENTS;
1113 inline bool FitsRepresentation(Representation representation) {
1114 if (FLAG_track_fields && representation.IsNone()) {
1116 } else if (FLAG_track_fields && representation.IsSmi()) {
1118 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1119 return IsMutableHeapNumber() || IsNumber();
1120 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1121 return IsHeapObject();
1126 // Checks whether two valid primitive encodings of a property name resolve to
1127 // the same logical property. E.g., the smi 1, the string "1" and the double
1128 // 1 all refer to the same property, so this helper will return true.
1129 inline bool KeyEquals(Object* other);
1131 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1133 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1134 Handle<Object> object,
1135 Representation representation);
1137 inline static Handle<Object> WrapForRead(Isolate* isolate,
1138 Handle<Object> object,
1139 Representation representation);
1141 // Returns true if the object is of the correct type to be used as a
1142 // implementation of a JSObject's elements.
1143 inline bool HasValidElements();
1145 inline bool HasSpecificClassOf(String* name);
1147 bool BooleanValue(); // ECMA-262 9.2.
1149 // Convert to a JSObject if needed.
1150 // native_context is used when creating wrapper object.
1151 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1152 Handle<Object> object);
1153 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1154 Handle<Object> object,
1155 Handle<Context> context);
1157 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1158 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1160 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1161 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1162 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1163 LanguageMode language_mode,
1164 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1166 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1167 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1168 StoreFromKeyed store_mode);
1170 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1171 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1172 StoreFromKeyed store_mode);
1174 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1175 LookupIterator* it, LanguageMode language_mode);
1176 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1177 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1178 LanguageMode language_mode);
1179 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1180 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1181 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1182 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1183 Handle<Object> value, LanguageMode language_mode);
1184 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1185 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1186 LanguageMode language_mode);
1187 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1188 LookupIterator* it, Handle<Object> value);
1189 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1190 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1191 LanguageMode language_mode, StoreFromKeyed store_mode);
1192 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1193 Handle<Object> object, Handle<Name> name,
1194 LanguageMode language_mode = SLOPPY);
1195 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1196 Isolate* isolate, Handle<Object> object, const char* key,
1197 LanguageMode language_mode = SLOPPY);
1198 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1199 Handle<Object> object, Handle<Name> name,
1200 LanguageMode language_mode = SLOPPY);
1202 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1203 LookupIterator* it, LanguageMode language_mode);
1204 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1205 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1207 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1208 Handle<Object> receiver,
1209 Handle<JSReceiver> getter);
1210 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1211 Handle<Object> receiver,
1212 Handle<JSReceiver> setter,
1213 Handle<Object> value);
1215 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1216 Isolate* isolate, Handle<Object> object, uint32_t index,
1217 LanguageMode language_mode = SLOPPY);
1219 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1220 Isolate* isolate, Handle<Object> object, uint32_t index,
1221 Handle<Object> value, LanguageMode language_mode);
1223 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1224 Isolate* isolate, Handle<Object> receiver);
1226 // Returns the permanent hash code associated with this object. May return
1227 // undefined if not yet created.
1230 // Returns undefined for JSObjects, but returns the hash code for simple
1231 // objects. This avoids a double lookup in the cases where we know we will
1232 // add the hash to the JSObject if it does not already exist.
1233 Object* GetSimpleHash();
1235 // Returns the permanent hash code associated with this object depending on
1236 // the actual object type. May create and store a hash code if needed and none
1238 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1240 // Checks whether this object has the same value as the given one. This
1241 // function is implemented according to ES5, section 9.12 and can be used
1242 // to implement the Harmony "egal" function.
1243 bool SameValue(Object* other);
1245 // Checks whether this object has the same value as the given one.
1246 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1247 // This function is implemented according to ES6, section 7.2.4 and is used
1248 // by ES6 Map and Set.
1249 bool SameValueZero(Object* other);
1251 // Tries to convert an object to an array length. Returns true and sets the
1252 // output parameter if it succeeds.
1253 inline bool ToArrayLength(uint32_t* index);
1255 // Tries to convert an object to an array index. Returns true and sets the
1256 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1257 // allow kMaxUInt32.
1258 inline bool ToArrayIndex(uint32_t* index);
1260 // Returns true if this is a JSValue containing a string and the index is
1261 // < the length of the string. Used to implement [] on strings.
1262 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1264 DECLARE_VERIFIER(Object)
1266 // Verify a pointer is a valid object pointer.
1267 static void VerifyPointer(Object* p);
1270 inline void VerifyApiCallResultType();
1272 // Prints this object without details.
1273 void ShortPrint(FILE* out = stdout);
1275 // Prints this object without details to a message accumulator.
1276 void ShortPrint(StringStream* accumulator);
1278 void ShortPrint(std::ostream& os); // NOLINT
1280 DECLARE_CAST(Object)
1282 // Layout description.
1283 static const int kHeaderSize = 0; // Object does not take up any space.
1286 // For our gdb macros, we should perhaps change these in the future.
1289 // Prints this object with details.
1290 void Print(std::ostream& os); // NOLINT
1292 void Print() { ShortPrint(); }
1293 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1297 friend class LookupIterator;
1298 friend class PrototypeIterator;
1300 // Return the map of the root of object's prototype chain.
1301 Map* GetRootMap(Isolate* isolate);
1303 // Helper for SetProperty and SetSuperProperty.
1304 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1305 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1306 StoreFromKeyed store_mode, bool* found);
1308 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1313 explicit Brief(const Object* const v) : value(v) {}
1314 const Object* value;
1318 std::ostream& operator<<(std::ostream& os, const Brief& v);
1321 // Smi represents integer Numbers that can be stored in 31 bits.
1322 // Smis are immediate which means they are NOT allocated in the heap.
1323 // The this pointer has the following format: [31 bit signed int] 0
1324 // For long smis it has the following format:
1325 // [32 bit signed int] [31 bits zero padding] 0
1326 // Smi stands for small integer.
1327 class Smi: public Object {
1329 // Returns the integer value.
1330 inline int value() const;
1332 // Convert a value to a Smi object.
1333 static inline Smi* FromInt(int value);
1335 static inline Smi* FromIntptr(intptr_t value);
1337 // Returns whether value can be represented in a Smi.
1338 static inline bool IsValid(intptr_t value);
1342 // Dispatched behavior.
1343 void SmiPrint(std::ostream& os) const; // NOLINT
1344 DECLARE_VERIFIER(Smi)
1346 static const int kMinValue =
1347 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1348 static const int kMaxValue = -(kMinValue + 1);
1351 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1355 // Heap objects typically have a map pointer in their first word. However,
1356 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1357 // encoded in the first word. The class MapWord is an abstraction of the
1358 // value in a heap object's first word.
1359 class MapWord BASE_EMBEDDED {
1361 // Normal state: the map word contains a map pointer.
1363 // Create a map word from a map pointer.
1364 static inline MapWord FromMap(const Map* map);
1366 // View this map word as a map pointer.
1367 inline Map* ToMap();
1370 // Scavenge collection: the map word of live objects in the from space
1371 // contains a forwarding address (a heap object pointer in the to space).
1373 // True if this map word is a forwarding address for a scavenge
1374 // collection. Only valid during a scavenge collection (specifically,
1375 // when all map words are heap object pointers, i.e. not during a full GC).
1376 inline bool IsForwardingAddress();
1378 // Create a map word from a forwarding address.
1379 static inline MapWord FromForwardingAddress(HeapObject* object);
1381 // View this map word as a forwarding address.
1382 inline HeapObject* ToForwardingAddress();
1384 static inline MapWord FromRawValue(uintptr_t value) {
1385 return MapWord(value);
1388 inline uintptr_t ToRawValue() {
1393 // HeapObject calls the private constructor and directly reads the value.
1394 friend class HeapObject;
1396 explicit MapWord(uintptr_t value) : value_(value) {}
1402 // The content of an heap object (except for the map pointer). kTaggedValues
1403 // objects can contain both heap pointers and Smis, kMixedValues can contain
1404 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1405 // objects can contain raw values and Smis.
1406 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1409 // HeapObject is the superclass for all classes describing heap allocated
1411 class HeapObject: public Object {
1413 // [map]: Contains a map which contains the object's reflective
1415 inline Map* map() const;
1416 inline void set_map(Map* value);
1417 // The no-write-barrier version. This is OK if the object is white and in
1418 // new space, or if the value is an immortal immutable object, like the maps
1419 // of primitive (non-JS) objects like strings, heap numbers etc.
1420 inline void set_map_no_write_barrier(Map* value);
1422 // Get the map using acquire load.
1423 inline Map* synchronized_map();
1424 inline MapWord synchronized_map_word() const;
1426 // Set the map using release store
1427 inline void synchronized_set_map(Map* value);
1428 inline void synchronized_set_map_no_write_barrier(Map* value);
1429 inline void synchronized_set_map_word(MapWord map_word);
1431 // During garbage collection, the map word of a heap object does not
1432 // necessarily contain a map pointer.
1433 inline MapWord map_word() const;
1434 inline void set_map_word(MapWord map_word);
1436 // The Heap the object was allocated in. Used also to access Isolate.
1437 inline Heap* GetHeap() const;
1439 // Convenience method to get current isolate.
1440 inline Isolate* GetIsolate() const;
1442 // Converts an address to a HeapObject pointer.
1443 static inline HeapObject* FromAddress(Address address);
1445 // Returns the address of this HeapObject.
1446 inline Address address();
1448 // Iterates over pointers contained in the object (including the Map)
1449 void Iterate(ObjectVisitor* v);
1451 // Iterates over all pointers contained in the object except the
1452 // first map pointer. The object type is given in the first
1453 // parameter. This function does not access the map pointer in the
1454 // object, and so is safe to call while the map pointer is modified.
1455 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1457 // Returns the heap object's size in bytes
1460 // Indicates what type of values this heap object may contain.
1461 inline HeapObjectContents ContentType();
1463 // Given a heap object's map pointer, returns the heap size in bytes
1464 // Useful when the map pointer field is used for other purposes.
1466 inline int SizeFromMap(Map* map);
1468 // Returns the field at offset in obj, as a read/write Object* reference.
1469 // Does no checking, and is safe to use during GC, while maps are invalid.
1470 // Does not invoke write barrier, so should only be assigned to
1471 // during marking GC.
1472 static inline Object** RawField(HeapObject* obj, int offset);
1474 // Adds the |code| object related to |name| to the code cache of this map. If
1475 // this map is a dictionary map that is shared, the map copied and installed
1477 static void UpdateMapCodeCache(Handle<HeapObject> object,
1481 DECLARE_CAST(HeapObject)
1483 // Return the write barrier mode for this. Callers of this function
1484 // must be able to present a reference to an DisallowHeapAllocation
1485 // object as a sign that they are not going to use this function
1486 // from code that allocates and thus invalidates the returned write
1488 inline WriteBarrierMode GetWriteBarrierMode(
1489 const DisallowHeapAllocation& promise);
1491 // Dispatched behavior.
1492 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1494 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1496 DECLARE_PRINTER(HeapObject)
1497 DECLARE_VERIFIER(HeapObject)
1499 inline void VerifyObjectField(int offset);
1500 inline void VerifySmiField(int offset);
1502 // Verify a pointer is a valid HeapObject pointer that points to object
1503 // areas in the heap.
1504 static void VerifyHeapPointer(Object* p);
1507 inline AllocationAlignment RequiredAlignment();
1509 // Layout description.
1510 // First field in a heap object is map.
1511 static const int kMapOffset = Object::kHeaderSize;
1512 static const int kHeaderSize = kMapOffset + kPointerSize;
1514 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1517 // helpers for calling an ObjectVisitor to iterate over pointers in the
1518 // half-open range [start, end) specified as integer offsets
1519 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1520 // as above, for the single element at "offset"
1521 inline void IteratePointer(ObjectVisitor* v, int offset);
1522 // as above, for the next code link of a code object.
1523 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1526 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1530 // This class describes a body of an object of a fixed size
1531 // in which all pointer fields are located in the [start_offset, end_offset)
1533 template<int start_offset, int end_offset, int size>
1534 class FixedBodyDescriptor {
1536 static const int kStartOffset = start_offset;
1537 static const int kEndOffset = end_offset;
1538 static const int kSize = size;
1540 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1542 template<typename StaticVisitor>
1543 static inline void IterateBody(HeapObject* obj) {
1544 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1545 HeapObject::RawField(obj, end_offset));
1550 // This class describes a body of an object of a variable size
1551 // in which all pointer fields are located in the [start_offset, object_size)
1553 template<int start_offset>
1554 class FlexibleBodyDescriptor {
1556 static const int kStartOffset = start_offset;
1558 static inline void IterateBody(HeapObject* obj,
1562 template<typename StaticVisitor>
1563 static inline void IterateBody(HeapObject* obj, int object_size) {
1564 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1565 HeapObject::RawField(obj, object_size));
1570 // The HeapNumber class describes heap allocated numbers that cannot be
1571 // represented in a Smi (small integer)
1572 class HeapNumber: public HeapObject {
1574 // [value]: number value.
1575 inline double value() const;
1576 inline void set_value(double value);
1578 DECLARE_CAST(HeapNumber)
1580 // Dispatched behavior.
1581 bool HeapNumberBooleanValue();
1583 void HeapNumberPrint(std::ostream& os); // NOLINT
1584 DECLARE_VERIFIER(HeapNumber)
1586 inline int get_exponent();
1587 inline int get_sign();
1589 // Layout description.
1590 static const int kValueOffset = HeapObject::kHeaderSize;
1591 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1592 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1593 // words within double numbers are endian dependent and they are set
1595 #if defined(V8_TARGET_LITTLE_ENDIAN)
1596 static const int kMantissaOffset = kValueOffset;
1597 static const int kExponentOffset = kValueOffset + 4;
1598 #elif defined(V8_TARGET_BIG_ENDIAN)
1599 static const int kMantissaOffset = kValueOffset + 4;
1600 static const int kExponentOffset = kValueOffset;
1602 #error Unknown byte ordering
1605 static const int kSize = kValueOffset + kDoubleSize;
1606 static const uint32_t kSignMask = 0x80000000u;
1607 static const uint32_t kExponentMask = 0x7ff00000u;
1608 static const uint32_t kMantissaMask = 0xfffffu;
1609 static const int kMantissaBits = 52;
1610 static const int kExponentBits = 11;
1611 static const int kExponentBias = 1023;
1612 static const int kExponentShift = 20;
1613 static const int kInfinityOrNanExponent =
1614 (kExponentMask >> kExponentShift) - kExponentBias;
1615 static const int kMantissaBitsInTopWord = 20;
1616 static const int kNonMantissaBitsInTopWord = 12;
1619 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1623 // The Float32x4 class describes heap allocated SIMD values holding 4 32-bit
1625 class Float32x4 : public HeapObject {
1627 inline float get_lane(int lane) const;
1628 inline void set_lane(int lane, float value);
1630 DECLARE_CAST(Float32x4)
1632 // Dispatched behavior.
1633 void Float32x4Print(std::ostream& os); // NOLINT
1634 DECLARE_VERIFIER(Float32x4)
1636 // Layout description.
1637 static const int kValueOffset = HeapObject::kHeaderSize;
1638 static const int kSize = kValueOffset + kSimd128Size;
1641 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
1645 enum EnsureElementsMode {
1646 DONT_ALLOW_DOUBLE_ELEMENTS,
1647 ALLOW_COPIED_DOUBLE_ELEMENTS,
1648 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1652 // Indicator for one component of an AccessorPair.
1653 enum AccessorComponent {
1659 // JSReceiver includes types on which properties can be defined, i.e.,
1660 // JSObject and JSProxy.
1661 class JSReceiver: public HeapObject {
1663 DECLARE_CAST(JSReceiver)
1665 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1666 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1667 Handle<JSReceiver> object, Handle<Name> name);
1668 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1670 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1671 Handle<JSReceiver> object, uint32_t index);
1672 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1673 Handle<JSReceiver> object, uint32_t index);
1675 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1676 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1677 Handle<JSReceiver> object, Handle<Name> name,
1678 LanguageMode language_mode = SLOPPY);
1679 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1680 Handle<JSReceiver> object, Handle<Name> name,
1681 LanguageMode language_mode = SLOPPY);
1682 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1683 LookupIterator* it, LanguageMode language_mode);
1684 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1685 Handle<JSReceiver> object, uint32_t index,
1686 LanguageMode language_mode = SLOPPY);
1688 // Tests for the fast common case for property enumeration.
1689 bool IsSimpleEnum();
1691 // Returns the class name ([[Class]] property in the specification).
1692 String* class_name();
1694 // Returns the constructor name (the name (possibly, inferred name) of the
1695 // function that was used to instantiate the object).
1696 String* constructor_name();
1698 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1699 Handle<JSReceiver> object, Handle<Name> name);
1700 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1701 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1703 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1704 Handle<JSReceiver> object, uint32_t index);
1705 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1706 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1708 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1709 LookupIterator* it);
1712 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1714 static Handle<Object> GetDataProperty(LookupIterator* it);
1717 // Retrieves a permanent object identity hash code. The undefined value might
1718 // be returned in case no hash was created yet.
1719 inline Object* GetIdentityHash();
1721 // Retrieves a permanent object identity hash code. May create and store a
1722 // hash code if needed and none exists.
1723 inline static Handle<Smi> GetOrCreateIdentityHash(
1724 Handle<JSReceiver> object);
1726 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1728 // Computes the enumerable keys for a JSObject. Used for implementing
1729 // "for (n in object) { }".
1730 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1731 Handle<JSReceiver> object,
1732 KeyCollectionType type);
1735 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1739 // The JSObject describes real heap allocated JavaScript objects with
1741 // Note that the map of JSObject changes during execution to enable inline
1743 class JSObject: public JSReceiver {
1745 // [properties]: Backing storage for properties.
1746 // properties is a FixedArray in the fast case and a Dictionary in the
1748 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1749 inline void initialize_properties();
1750 inline bool HasFastProperties();
1751 // Gets slow properties for non-global objects.
1752 inline NameDictionary* property_dictionary();
1753 // Gets global object properties.
1754 inline GlobalDictionary* global_dictionary();
1756 // [elements]: The elements (properties with names that are integers).
1758 // Elements can be in two general modes: fast and slow. Each mode
1759 // corrensponds to a set of object representations of elements that
1760 // have something in common.
1762 // In the fast mode elements is a FixedArray and so each element can
1763 // be quickly accessed. This fact is used in the generated code. The
1764 // elements array can have one of three maps in this mode:
1765 // fixed_array_map, sloppy_arguments_elements_map or
1766 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1767 // the elements array may be shared by a few objects and so before
1768 // writing to any element the array must be copied. Use
1769 // EnsureWritableFastElements in this case.
1771 // In the slow mode the elements is either a NumberDictionary, an
1772 // ExternalArray, or a FixedArray parameter map for a (sloppy)
1773 // arguments object.
1774 DECL_ACCESSORS(elements, FixedArrayBase)
1775 inline void initialize_elements();
1776 static void ResetElements(Handle<JSObject> object);
1777 static inline void SetMapAndElements(Handle<JSObject> object,
1779 Handle<FixedArrayBase> elements);
1780 inline ElementsKind GetElementsKind();
1781 ElementsAccessor* GetElementsAccessor();
1782 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1783 inline bool HasFastSmiElements();
1784 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1785 inline bool HasFastObjectElements();
1786 // Returns true if an object has elements of FAST_ELEMENTS or
1787 // FAST_SMI_ONLY_ELEMENTS.
1788 inline bool HasFastSmiOrObjectElements();
1789 // Returns true if an object has any of the fast elements kinds.
1790 inline bool HasFastElements();
1791 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1793 inline bool HasFastDoubleElements();
1794 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1796 inline bool HasFastHoleyElements();
1797 inline bool HasSloppyArgumentsElements();
1798 inline bool HasDictionaryElements();
1800 inline bool HasExternalUint8ClampedElements();
1801 inline bool HasExternalArrayElements();
1802 inline bool HasExternalInt8Elements();
1803 inline bool HasExternalUint8Elements();
1804 inline bool HasExternalInt16Elements();
1805 inline bool HasExternalUint16Elements();
1806 inline bool HasExternalInt32Elements();
1807 inline bool HasExternalUint32Elements();
1808 inline bool HasExternalFloat32Elements();
1809 inline bool HasExternalFloat64Elements();
1811 inline bool HasFixedTypedArrayElements();
1813 inline bool HasFixedUint8ClampedElements();
1814 inline bool HasFixedArrayElements();
1815 inline bool HasFixedInt8Elements();
1816 inline bool HasFixedUint8Elements();
1817 inline bool HasFixedInt16Elements();
1818 inline bool HasFixedUint16Elements();
1819 inline bool HasFixedInt32Elements();
1820 inline bool HasFixedUint32Elements();
1821 inline bool HasFixedFloat32Elements();
1822 inline bool HasFixedFloat64Elements();
1824 inline bool HasFastArgumentsElements();
1825 inline bool HasSlowArgumentsElements();
1826 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1828 // Requires: HasFastElements().
1829 static Handle<FixedArray> EnsureWritableFastElements(
1830 Handle<JSObject> object);
1832 // Collects elements starting at index 0.
1833 // Undefined values are placed after non-undefined values.
1834 // Returns the number of non-undefined values.
1835 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1837 // As PrepareElementsForSort, but only on objects where elements is
1838 // a dictionary, and it will stay a dictionary. Collates undefined and
1839 // unexisting elements below limit from position zero of the elements.
1840 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1843 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1844 LookupIterator* it, Handle<Object> value);
1846 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1847 // grant an exemption to ExecutableAccessor callbacks in some cases.
1848 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1850 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1851 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1852 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1854 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1855 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1856 PropertyAttributes attributes,
1857 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1859 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1860 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1861 PropertyAttributes attributes,
1862 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1864 // Equivalent to one of the above depending on whether |name| can be converted
1865 // to an array index.
1866 MUST_USE_RESULT static MaybeHandle<Object>
1867 DefinePropertyOrElementIgnoreAttributes(
1868 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1869 PropertyAttributes attributes = NONE,
1870 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1872 // Adds or reconfigures a property to attributes NONE. It will fail when it
1874 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1875 Handle<Object> value);
1877 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1878 Handle<Object> value, PropertyAttributes attributes);
1880 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1881 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1882 PropertyAttributes attributes);
1884 // Extend the receiver with a single fast property appeared first in the
1885 // passed map. This also extends the property backing store if necessary.
1886 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1888 // Migrates the given object to a map whose field representations are the
1889 // lowest upper bound of all known representations for that field.
1890 static void MigrateInstance(Handle<JSObject> instance);
1892 // Migrates the given object only if the target map is already available,
1893 // or returns false if such a map is not yet available.
1894 static bool TryMigrateInstance(Handle<JSObject> instance);
1896 // Sets the property value in a normalized object given (key, value, details).
1897 // Handles the special representation of JS global objects.
1898 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1899 Handle<Object> value,
1900 PropertyDetails details);
1901 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1902 Handle<Object> value,
1903 PropertyAttributes attributes);
1904 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1906 Handle<Object> value,
1907 PropertyAttributes attributes);
1909 static void OptimizeAsPrototype(Handle<JSObject> object,
1910 PrototypeOptimizationMode mode);
1911 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1912 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1913 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1914 Handle<HeapObject> user,
1916 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1917 Handle<HeapObject> user);
1918 static void InvalidatePrototypeChains(Map* map);
1920 // Retrieve interceptors.
1921 InterceptorInfo* GetNamedInterceptor();
1922 InterceptorInfo* GetIndexedInterceptor();
1924 // Used from JSReceiver.
1925 MUST_USE_RESULT static Maybe<PropertyAttributes>
1926 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1927 MUST_USE_RESULT static Maybe<PropertyAttributes>
1928 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1930 // Retrieves an AccessorPair property from the given object. Might return
1931 // undefined if the property doesn't exist or is of a different kind.
1932 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1933 Handle<JSObject> object,
1935 AccessorComponent component);
1937 // Defines an AccessorPair property on the given object.
1938 // TODO(mstarzinger): Rename to SetAccessor().
1939 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1941 Handle<Object> getter,
1942 Handle<Object> setter,
1943 PropertyAttributes attributes);
1945 // Defines an AccessorInfo property on the given object.
1946 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1947 Handle<JSObject> object,
1948 Handle<AccessorInfo> info);
1950 // The result must be checked first for exceptions. If there's no exception,
1951 // the output parameter |done| indicates whether the interceptor has a result
1953 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1954 LookupIterator* it, bool* done);
1956 // Accessors for hidden properties object.
1958 // Hidden properties are not own properties of the object itself.
1959 // Instead they are stored in an auxiliary structure kept as an own
1960 // property with a special name Heap::hidden_string(). But if the
1961 // receiver is a JSGlobalProxy then the auxiliary object is a property
1962 // of its prototype, and if it's a detached proxy, then you can't have
1963 // hidden properties.
1965 // Sets a hidden property on this object. Returns this object if successful,
1966 // undefined if called on a detached proxy.
1967 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1969 Handle<Object> value);
1970 // Gets the value of a hidden property with the given key. Returns the hole
1971 // if the property doesn't exist (or if called on a detached proxy),
1972 // otherwise returns the value set for the key.
1973 Object* GetHiddenProperty(Handle<Name> key);
1974 // Deletes a hidden property. Deleting a non-existing property is
1975 // considered successful.
1976 static void DeleteHiddenProperty(Handle<JSObject> object,
1978 // Returns true if the object has a property with the hidden string as name.
1979 static bool HasHiddenProperties(Handle<JSObject> object);
1981 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1983 static void ValidateElements(Handle<JSObject> object);
1985 // Makes sure that this object can contain HeapObject as elements.
1986 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1988 // Makes sure that this object can contain the specified elements.
1989 static inline void EnsureCanContainElements(
1990 Handle<JSObject> object,
1993 EnsureElementsMode mode);
1994 static inline void EnsureCanContainElements(
1995 Handle<JSObject> object,
1996 Handle<FixedArrayBase> elements,
1998 EnsureElementsMode mode);
1999 static void EnsureCanContainElements(
2000 Handle<JSObject> object,
2001 Arguments* arguments,
2004 EnsureElementsMode mode);
2006 // Would we convert a fast elements array to dictionary mode given
2007 // an access at key?
2008 bool WouldConvertToSlowElements(uint32_t index);
2010 // Computes the new capacity when expanding the elements of a JSObject.
2011 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2012 // (old_capacity + 50%) + 16
2013 return old_capacity + (old_capacity >> 1) + 16;
2016 // These methods do not perform access checks!
2017 static void UpdateAllocationSite(Handle<JSObject> object,
2018 ElementsKind to_kind);
2020 // Lookup interceptors are used for handling properties controlled by host
2022 inline bool HasNamedInterceptor();
2023 inline bool HasIndexedInterceptor();
2025 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2026 // by JSReceiver::GetKeys.
2027 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2028 Handle<JSObject> object,
2029 Handle<JSReceiver> receiver);
2030 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2031 Handle<JSObject> object,
2032 Handle<JSReceiver> receiver);
2034 // Support functions for v8 api (needed for correct interceptor behavior).
2035 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2036 Handle<JSObject> object, Handle<Name> name);
2037 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2038 Handle<JSObject> object, uint32_t index);
2039 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2040 Handle<JSObject> object, Handle<Name> name);
2042 // Get the header size for a JSObject. Used to compute the index of
2043 // internal fields as well as the number of internal fields.
2044 inline int GetHeaderSize();
2046 inline int GetInternalFieldCount();
2047 inline int GetInternalFieldOffset(int index);
2048 inline Object* GetInternalField(int index);
2049 inline void SetInternalField(int index, Object* value);
2050 inline void SetInternalField(int index, Smi* value);
2052 // Returns the number of properties on this object filtering out properties
2053 // with the specified attributes (ignoring interceptors).
2054 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2055 // Fill in details for properties into storage starting at the specified
2057 void GetOwnPropertyNames(
2058 FixedArray* storage, int index, PropertyAttributes filter = NONE);
2060 // Returns the number of properties on this object filtering out properties
2061 // with the specified attributes (ignoring interceptors).
2062 int NumberOfOwnElements(PropertyAttributes filter);
2063 // Returns the number of enumerable elements (ignoring interceptors).
2064 int NumberOfEnumElements();
2065 // Returns the number of elements on this object filtering out elements
2066 // with the specified attributes (ignoring interceptors).
2067 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2068 // Count and fill in the enumerable elements into storage.
2069 // (storage->length() == NumberOfEnumElements()).
2070 // If storage is NULL, will count the elements without adding
2071 // them to any storage.
2072 // Returns the number of enumerable elements.
2073 int GetEnumElementKeys(FixedArray* storage);
2075 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2078 // Returns a new map with all transitions dropped from the object's current
2079 // map and the ElementsKind set.
2080 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2081 ElementsKind to_kind);
2082 static void TransitionElementsKind(Handle<JSObject> object,
2083 ElementsKind to_kind);
2085 // Always use this to migrate an object to a new map.
2086 // |expected_additional_properties| is only used for fast-to-slow transitions
2087 // and ignored otherwise.
2088 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2089 int expected_additional_properties = 0);
2091 // Convert the object to use the canonical dictionary
2092 // representation. If the object is expected to have additional properties
2093 // added this number can be indicated to have the backing store allocated to
2094 // an initial capacity for holding these properties.
2095 static void NormalizeProperties(Handle<JSObject> object,
2096 PropertyNormalizationMode mode,
2097 int expected_additional_properties,
2098 const char* reason);
2100 // Convert and update the elements backing store to be a
2101 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2102 static Handle<SeededNumberDictionary> NormalizeElements(
2103 Handle<JSObject> object);
2105 // Transform slow named properties to fast variants.
2106 static void MigrateSlowToFast(Handle<JSObject> object,
2107 int unused_property_fields, const char* reason);
2109 inline bool IsUnboxedDoubleField(FieldIndex index);
2111 // Access fast-case object properties at index.
2112 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2113 Representation representation,
2115 inline Object* RawFastPropertyAt(FieldIndex index);
2116 inline double RawFastDoublePropertyAt(FieldIndex index);
2118 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2119 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2120 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2121 inline void WriteToField(int descriptor, Object* value);
2123 // Access to in object properties.
2124 inline int GetInObjectPropertyOffset(int index);
2125 inline Object* InObjectPropertyAt(int index);
2126 inline Object* InObjectPropertyAtPut(int index,
2128 WriteBarrierMode mode
2129 = UPDATE_WRITE_BARRIER);
2131 // Set the object's prototype (only JSReceiver and null are allowed values).
2132 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2133 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2135 // Initializes the body after properties slot, properties slot is
2136 // initialized by set_properties. Fill the pre-allocated fields with
2137 // pre_allocated_value and the rest with filler_value.
2138 // Note: this call does not update write barrier, the caller is responsible
2139 // to ensure that |filler_value| can be collected without WB here.
2140 inline void InitializeBody(Map* map,
2141 Object* pre_allocated_value,
2142 Object* filler_value);
2144 // Check whether this object references another object
2145 bool ReferencesObject(Object* obj);
2147 // Disalow further properties to be added to the oject.
2148 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2149 Handle<JSObject> object);
2151 bool IsExtensible();
2154 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2156 // ES5 Object.freeze
2157 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2159 // Called the first time an object is observed with ES7 Object.observe.
2160 static void SetObserved(Handle<JSObject> object);
2163 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2165 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2166 Handle<JSObject> object,
2167 AllocationSiteUsageContext* site_context,
2168 DeepCopyHints hints = kNoHints);
2169 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2170 Handle<JSObject> object,
2171 AllocationSiteCreationContext* site_context);
2173 DECLARE_CAST(JSObject)
2175 // Dispatched behavior.
2176 void JSObjectShortPrint(StringStream* accumulator);
2177 DECLARE_PRINTER(JSObject)
2178 DECLARE_VERIFIER(JSObject)
2180 void PrintProperties(std::ostream& os); // NOLINT
2181 void PrintElements(std::ostream& os); // NOLINT
2183 #if defined(DEBUG) || defined(OBJECT_PRINT)
2184 void PrintTransitions(std::ostream& os); // NOLINT
2187 static void PrintElementsTransition(
2188 FILE* file, Handle<JSObject> object,
2189 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2190 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2192 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2195 // Structure for collecting spill information about JSObjects.
2196 class SpillInformation {
2200 int number_of_objects_;
2201 int number_of_objects_with_fast_properties_;
2202 int number_of_objects_with_fast_elements_;
2203 int number_of_fast_used_fields_;
2204 int number_of_fast_unused_fields_;
2205 int number_of_slow_used_properties_;
2206 int number_of_slow_unused_properties_;
2207 int number_of_fast_used_elements_;
2208 int number_of_fast_unused_elements_;
2209 int number_of_slow_used_elements_;
2210 int number_of_slow_unused_elements_;
2213 void IncrementSpillStatistics(SpillInformation* info);
2217 // If a GC was caused while constructing this object, the elements pointer
2218 // may point to a one pointer filler map. The object won't be rooted, but
2219 // our heap verification code could stumble across it.
2220 bool ElementsAreSafeToExamine();
2223 Object* SlowReverseLookup(Object* value);
2225 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2226 // Also maximal value of JSArray's length property.
2227 static const uint32_t kMaxElementCount = 0xffffffffu;
2229 // Constants for heuristics controlling conversion of fast elements
2230 // to slow elements.
2232 // Maximal gap that can be introduced by adding an element beyond
2233 // the current elements length.
2234 static const uint32_t kMaxGap = 1024;
2236 // Maximal length of fast elements array that won't be checked for
2237 // being dense enough on expansion.
2238 static const int kMaxUncheckedFastElementsLength = 5000;
2240 // Same as above but for old arrays. This limit is more strict. We
2241 // don't want to be wasteful with long lived objects.
2242 static const int kMaxUncheckedOldFastElementsLength = 500;
2244 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2245 // permissible values (see the DCHECK in heap.cc).
2246 static const int kInitialMaxFastElementArray = 100000;
2248 // This constant applies only to the initial map of "global.Object" and
2249 // not to arbitrary other JSObject maps.
2250 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2252 static const int kMaxInstanceSize = 255 * kPointerSize;
2253 // When extending the backing storage for property values, we increase
2254 // its size by more than the 1 entry necessary, so sequentially adding fields
2255 // to the same object requires fewer allocations and copies.
2256 static const int kFieldsAdded = 3;
2258 // Layout description.
2259 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2260 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2261 static const int kHeaderSize = kElementsOffset + kPointerSize;
2263 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2265 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2267 static inline int SizeOf(Map* map, HeapObject* object);
2270 Context* GetCreationContext();
2272 // Enqueue change record for Object.observe. May cause GC.
2273 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2274 Handle<JSObject> object, const char* type, Handle<Name> name,
2275 Handle<Object> old_value);
2277 // Gets the current elements capacity and the number of used elements.
2278 void GetElementsCapacityAndUsage(int* capacity, int* used);
2280 // Deletes an existing named property in a normalized object.
2281 static void DeleteNormalizedProperty(Handle<JSObject> object,
2282 Handle<Name> name, int entry);
2285 friend class JSReceiver;
2286 friend class Object;
2288 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2289 static void MigrateFastToSlow(Handle<JSObject> object,
2290 Handle<Map> new_map,
2291 int expected_additional_properties);
2293 // Used from Object::GetProperty().
2294 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2295 LookupIterator* it);
2297 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2298 LookupIterator* it, Handle<Object> value);
2300 // Add a property to a slow-case object.
2301 static void AddSlowProperty(Handle<JSObject> object,
2303 Handle<Object> value,
2304 PropertyAttributes attributes);
2306 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2307 LookupIterator* it);
2309 bool ReferencesObjectFromElements(FixedArray* elements,
2313 // Return the hash table backing store or the inline stored identity hash,
2314 // whatever is found.
2315 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2317 // Return the hash table backing store for hidden properties. If there is no
2318 // backing store, allocate one.
2319 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2320 Handle<JSObject> object);
2322 // Set the hidden property backing store to either a hash table or
2323 // the inline-stored identity hash.
2324 static Handle<Object> SetHiddenPropertiesHashTable(
2325 Handle<JSObject> object,
2326 Handle<Object> value);
2328 MUST_USE_RESULT Object* GetIdentityHash();
2330 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2332 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2333 Handle<JSObject> object);
2335 // Helper for fast versions of preventExtensions, seal, and freeze.
2336 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2337 template <PropertyAttributes attrs>
2338 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2339 Handle<JSObject> object);
2341 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2345 // Common superclass for FixedArrays that allow implementations to share
2346 // common accessors and some code paths.
2347 class FixedArrayBase: public HeapObject {
2349 // [length]: length of the array.
2350 inline int length() const;
2351 inline void set_length(int value);
2353 // Get and set the length using acquire loads and release stores.
2354 inline int synchronized_length() const;
2355 inline void synchronized_set_length(int value);
2357 DECLARE_CAST(FixedArrayBase)
2359 // Layout description.
2360 // Length is smi tagged when it is stored.
2361 static const int kLengthOffset = HeapObject::kHeaderSize;
2362 static const int kHeaderSize = kLengthOffset + kPointerSize;
2366 class FixedDoubleArray;
2367 class IncrementalMarking;
2370 // FixedArray describes fixed-sized arrays with element type Object*.
2371 class FixedArray: public FixedArrayBase {
2373 // Setter and getter for elements.
2374 inline Object* get(int index) const;
2375 void SetValue(uint32_t index, Object* value);
2376 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2377 // Setter that uses write barrier.
2378 inline void set(int index, Object* value);
2379 inline bool is_the_hole(int index);
2381 // Setter that doesn't need write barrier.
2382 inline void set(int index, Smi* value);
2383 // Setter with explicit barrier mode.
2384 inline void set(int index, Object* value, WriteBarrierMode mode);
2386 // Setters for frequently used oddballs located in old space.
2387 inline void set_undefined(int index);
2388 inline void set_null(int index);
2389 inline void set_the_hole(int index);
2391 inline Object** GetFirstElementAddress();
2392 inline bool ContainsOnlySmisOrHoles();
2394 // Gives access to raw memory which stores the array's data.
2395 inline Object** data_start();
2397 inline void FillWithHoles(int from, int to);
2399 // Shrink length and insert filler objects.
2400 void Shrink(int length);
2403 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2405 PretenureFlag pretenure = NOT_TENURED);
2407 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2409 // Add the elements of a JSArray to this FixedArray.
2410 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2411 Handle<FixedArray> content, Handle<JSObject> array,
2412 KeyFilter filter = ALL_KEYS);
2414 // Computes the union of keys and return the result.
2415 // Used for implementing "for (n in object) { }"
2416 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2417 Handle<FixedArray> first,
2418 Handle<FixedArray> second);
2420 // Copy a sub array from the receiver to dest.
2421 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2423 // Garbage collection support.
2424 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2426 // Code Generation support.
2427 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2429 // Garbage collection support.
2430 Object** RawFieldOfElementAt(int index) {
2431 return HeapObject::RawField(this, OffsetOfElementAt(index));
2434 DECLARE_CAST(FixedArray)
2436 // Maximal allowed size, in bytes, of a single FixedArray.
2437 // Prevents overflowing size computations, as well as extreme memory
2439 static const int kMaxSize = 128 * MB * kPointerSize;
2440 // Maximally allowed length of a FixedArray.
2441 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2443 // Dispatched behavior.
2444 DECLARE_PRINTER(FixedArray)
2445 DECLARE_VERIFIER(FixedArray)
2447 // Checks if two FixedArrays have identical contents.
2448 bool IsEqualTo(FixedArray* other);
2451 // Swap two elements in a pair of arrays. If this array and the
2452 // numbers array are the same object, the elements are only swapped
2454 void SwapPairs(FixedArray* numbers, int i, int j);
2456 // Sort prefix of this array and the numbers array as pairs wrt. the
2457 // numbers. If the numbers array and the this array are the same
2458 // object, the prefix of this array is sorted.
2459 void SortPairs(FixedArray* numbers, uint32_t len);
2461 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2463 static inline int SizeOf(Map* map, HeapObject* object) {
2465 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2470 // Set operation on FixedArray without using write barriers. Can
2471 // only be used for storing old space objects or smis.
2472 static inline void NoWriteBarrierSet(FixedArray* array,
2476 // Set operation on FixedArray without incremental write barrier. Can
2477 // only be used if the object is guaranteed to be white (whiteness witness
2479 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2484 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2486 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2490 // FixedDoubleArray describes fixed-sized arrays with element type double.
2491 class FixedDoubleArray: public FixedArrayBase {
2493 // Setter and getter for elements.
2494 inline double get_scalar(int index);
2495 inline uint64_t get_representation(int index);
2496 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2497 // This accessor has to get a Number as |value|.
2498 void SetValue(uint32_t index, Object* value);
2499 inline void set(int index, double value);
2500 inline void set_the_hole(int index);
2502 // Checking for the hole.
2503 inline bool is_the_hole(int index);
2505 // Garbage collection support.
2506 inline static int SizeFor(int length) {
2507 return kHeaderSize + length * kDoubleSize;
2510 // Gives access to raw memory which stores the array's data.
2511 inline double* data_start();
2513 inline void FillWithHoles(int from, int to);
2515 // Code Generation support.
2516 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2518 DECLARE_CAST(FixedDoubleArray)
2520 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2521 // Prevents overflowing size computations, as well as extreme memory
2523 static const int kMaxSize = 512 * MB;
2524 // Maximally allowed length of a FixedArray.
2525 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2527 // Dispatched behavior.
2528 DECLARE_PRINTER(FixedDoubleArray)
2529 DECLARE_VERIFIER(FixedDoubleArray)
2532 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2536 class WeakFixedArray : public FixedArray {
2538 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2540 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2541 static Handle<WeakFixedArray> Add(
2542 Handle<Object> maybe_array, Handle<HeapObject> value,
2543 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2544 bool* was_present = NULL);
2546 // Returns true if an entry was found and removed.
2547 bool Remove(Handle<HeapObject> value);
2551 inline Object* Get(int index) const;
2552 inline void Clear(int index);
2553 inline int Length() const;
2555 inline bool IsEmptySlot(int index) const;
2556 static Object* Empty() { return Smi::FromInt(0); }
2558 DECLARE_CAST(WeakFixedArray)
2561 static const int kLastUsedIndexIndex = 0;
2562 static const int kFirstIndex = 1;
2564 static Handle<WeakFixedArray> Allocate(
2565 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2567 static void Set(Handle<WeakFixedArray> array, int index,
2568 Handle<HeapObject> value);
2569 inline void clear(int index);
2571 inline int last_used_index() const;
2572 inline void set_last_used_index(int index);
2574 // Disallow inherited setters.
2575 void set(int index, Smi* value);
2576 void set(int index, Object* value);
2577 void set(int index, Object* value, WriteBarrierMode mode);
2578 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2582 // Generic array grows dynamically with O(1) amortized insertion.
2583 class ArrayList : public FixedArray {
2587 // Use this if GC can delete elements from the array.
2588 kReloadLengthAfterAllocation,
2590 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2591 AddMode mode = kNone);
2592 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2593 Handle<Object> obj2, AddMode = kNone);
2594 inline int Length();
2595 inline void SetLength(int length);
2596 inline Object* Get(int index);
2597 inline Object** Slot(int index);
2598 inline void Set(int index, Object* obj);
2599 inline void Clear(int index, Object* undefined);
2600 DECLARE_CAST(ArrayList)
2603 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2604 static const int kLengthIndex = 0;
2605 static const int kFirstIndex = 1;
2606 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2610 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2611 // The format of the these objects is:
2612 // [0]: Number of descriptors
2613 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2614 // [0]: pointer to fixed array with enum cache
2615 // [1]: either Smi(0) or pointer to fixed array with indices
2617 // [2 + number of descriptors * kDescriptorSize]: start of slack
2618 class DescriptorArray: public FixedArray {
2620 // Returns true for both shared empty_descriptor_array and for smis, which the
2621 // map uses to encode additional bit fields when the descriptor array is not
2623 inline bool IsEmpty();
2625 // Returns the number of descriptors in the array.
2626 int number_of_descriptors() {
2627 DCHECK(length() >= kFirstIndex || IsEmpty());
2629 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2632 int number_of_descriptors_storage() {
2634 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2637 int NumberOfSlackDescriptors() {
2638 return number_of_descriptors_storage() - number_of_descriptors();
2641 inline void SetNumberOfDescriptors(int number_of_descriptors);
2642 inline int number_of_entries() { return number_of_descriptors(); }
2644 bool HasEnumCache() {
2645 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2648 void CopyEnumCacheFrom(DescriptorArray* array) {
2649 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2652 FixedArray* GetEnumCache() {
2653 DCHECK(HasEnumCache());
2654 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2655 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2658 bool HasEnumIndicesCache() {
2659 if (IsEmpty()) return false;
2660 Object* object = get(kEnumCacheIndex);
2661 if (object->IsSmi()) return false;
2662 FixedArray* bridge = FixedArray::cast(object);
2663 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2666 FixedArray* GetEnumIndicesCache() {
2667 DCHECK(HasEnumIndicesCache());
2668 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2669 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2672 Object** GetEnumCacheSlot() {
2673 DCHECK(HasEnumCache());
2674 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2678 void ClearEnumCache();
2680 // Initialize or change the enum cache,
2681 // using the supplied storage for the small "bridge".
2682 void SetEnumCache(FixedArray* bridge_storage,
2683 FixedArray* new_cache,
2684 Object* new_index_cache);
2686 bool CanHoldValue(int descriptor, Object* value);
2688 // Accessors for fetching instance descriptor at descriptor number.
2689 inline Name* GetKey(int descriptor_number);
2690 inline Object** GetKeySlot(int descriptor_number);
2691 inline Object* GetValue(int descriptor_number);
2692 inline void SetValue(int descriptor_number, Object* value);
2693 inline Object** GetValueSlot(int descriptor_number);
2694 static inline int GetValueOffset(int descriptor_number);
2695 inline Object** GetDescriptorStartSlot(int descriptor_number);
2696 inline Object** GetDescriptorEndSlot(int descriptor_number);
2697 inline PropertyDetails GetDetails(int descriptor_number);
2698 inline PropertyType GetType(int descriptor_number);
2699 inline int GetFieldIndex(int descriptor_number);
2700 inline HeapType* GetFieldType(int descriptor_number);
2701 inline Object* GetConstant(int descriptor_number);
2702 inline Object* GetCallbacksObject(int descriptor_number);
2703 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2705 inline Name* GetSortedKey(int descriptor_number);
2706 inline int GetSortedKeyIndex(int descriptor_number);
2707 inline void SetSortedKey(int pointer, int descriptor_number);
2708 inline void SetRepresentation(int descriptor_number,
2709 Representation representation);
2711 // Accessor for complete descriptor.
2712 inline void Get(int descriptor_number, Descriptor* desc);
2713 inline void Set(int descriptor_number, Descriptor* desc);
2714 void Replace(int descriptor_number, Descriptor* descriptor);
2716 // Append automatically sets the enumeration index. This should only be used
2717 // to add descriptors in bulk at the end, followed by sorting the descriptor
2719 inline void Append(Descriptor* desc);
2721 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2722 int enumeration_index,
2725 static Handle<DescriptorArray> CopyUpToAddAttributes(
2726 Handle<DescriptorArray> desc,
2727 int enumeration_index,
2728 PropertyAttributes attributes,
2731 // Sort the instance descriptors by the hash codes of their keys.
2734 // Search the instance descriptors for given name.
2735 INLINE(int Search(Name* name, int number_of_own_descriptors));
2737 // As the above, but uses DescriptorLookupCache and updates it when
2739 INLINE(int SearchWithCache(Name* name, Map* map));
2741 // Allocates a DescriptorArray, but returns the singleton
2742 // empty descriptor array object if number_of_descriptors is 0.
2743 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2744 int number_of_descriptors,
2747 DECLARE_CAST(DescriptorArray)
2749 // Constant for denoting key was not found.
2750 static const int kNotFound = -1;
2752 static const int kDescriptorLengthIndex = 0;
2753 static const int kEnumCacheIndex = 1;
2754 static const int kFirstIndex = 2;
2756 // The length of the "bridge" to the enum cache.
2757 static const int kEnumCacheBridgeLength = 2;
2758 static const int kEnumCacheBridgeCacheIndex = 0;
2759 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2761 // Layout description.
2762 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2763 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2764 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2766 // Layout description for the bridge array.
2767 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2769 // Layout of descriptor.
2770 static const int kDescriptorKey = 0;
2771 static const int kDescriptorDetails = 1;
2772 static const int kDescriptorValue = 2;
2773 static const int kDescriptorSize = 3;
2775 #if defined(DEBUG) || defined(OBJECT_PRINT)
2776 // For our gdb macros, we should perhaps change these in the future.
2779 // Print all the descriptors.
2780 void PrintDescriptors(std::ostream& os); // NOLINT
2784 // Is the descriptor array sorted and without duplicates?
2785 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2787 // Is the descriptor array consistent with the back pointers in targets?
2788 bool IsConsistentWithBackPointers(Map* current_map);
2790 // Are two DescriptorArrays equal?
2791 bool IsEqualTo(DescriptorArray* other);
2794 // Returns the fixed array length required to hold number_of_descriptors
2796 static int LengthFor(int number_of_descriptors) {
2797 return ToKeyIndex(number_of_descriptors);
2801 // WhitenessWitness is used to prove that a descriptor array is white
2802 // (unmarked), so incremental write barriers can be skipped because the
2803 // marking invariant cannot be broken and slots pointing into evacuation
2804 // candidates will be discovered when the object is scanned. A witness is
2805 // always stack-allocated right after creating an array. By allocating a
2806 // witness, incremental marking is globally disabled. The witness is then
2807 // passed along wherever needed to statically prove that the array is known to
2809 class WhitenessWitness {
2811 inline explicit WhitenessWitness(DescriptorArray* array);
2812 inline ~WhitenessWitness();
2815 IncrementalMarking* marking_;
2818 // An entry in a DescriptorArray, represented as an (array, index) pair.
2821 inline explicit Entry(DescriptorArray* descs, int index) :
2822 descs_(descs), index_(index) { }
2824 inline PropertyType type() { return descs_->GetType(index_); }
2825 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2828 DescriptorArray* descs_;
2832 // Conversion from descriptor number to array indices.
2833 static int ToKeyIndex(int descriptor_number) {
2834 return kFirstIndex +
2835 (descriptor_number * kDescriptorSize) +
2839 static int ToDetailsIndex(int descriptor_number) {
2840 return kFirstIndex +
2841 (descriptor_number * kDescriptorSize) +
2845 static int ToValueIndex(int descriptor_number) {
2846 return kFirstIndex +
2847 (descriptor_number * kDescriptorSize) +
2851 // Transfer a complete descriptor from the src descriptor array to this
2852 // descriptor array.
2853 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2855 inline void Set(int descriptor_number,
2857 const WhitenessWitness&);
2859 // Swap first and second descriptor.
2860 inline void SwapSortedKeys(int first, int second);
2862 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2866 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2868 template <SearchMode search_mode, typename T>
2869 inline int Search(T* array, Name* name, int valid_entries = 0,
2870 int* out_insertion_index = NULL);
2873 // HashTable is a subclass of FixedArray that implements a hash table
2874 // that uses open addressing and quadratic probing.
2876 // In order for the quadratic probing to work, elements that have not
2877 // yet been used and elements that have been deleted are
2878 // distinguished. Probing continues when deleted elements are
2879 // encountered and stops when unused elements are encountered.
2881 // - Elements with key == undefined have not been used yet.
2882 // - Elements with key == the_hole have been deleted.
2884 // The hash table class is parameterized with a Shape and a Key.
2885 // Shape must be a class with the following interface:
2886 // class ExampleShape {
2888 // // Tells whether key matches other.
2889 // static bool IsMatch(Key key, Object* other);
2890 // // Returns the hash value for key.
2891 // static uint32_t Hash(Key key);
2892 // // Returns the hash value for object.
2893 // static uint32_t HashForObject(Key key, Object* object);
2894 // // Convert key to an object.
2895 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2896 // // The prefix size indicates number of elements in the beginning
2897 // // of the backing storage.
2898 // static const int kPrefixSize = ..;
2899 // // The Element size indicates number of elements per entry.
2900 // static const int kEntrySize = ..;
2902 // The prefix size indicates an amount of memory in the
2903 // beginning of the backing storage that can be used for non-element
2904 // information by subclasses.
2906 template<typename Key>
2909 static const bool UsesSeed = false;
2910 static uint32_t Hash(Key key) { return 0; }
2911 static uint32_t SeededHash(Key key, uint32_t seed) {
2915 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2916 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2918 return HashForObject(key, object);
2923 class HashTableBase : public FixedArray {
2925 // Returns the number of elements in the hash table.
2926 int NumberOfElements() {
2927 return Smi::cast(get(kNumberOfElementsIndex))->value();
2930 // Returns the number of deleted elements in the hash table.
2931 int NumberOfDeletedElements() {
2932 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2935 // Returns the capacity of the hash table.
2937 return Smi::cast(get(kCapacityIndex))->value();
2940 // ElementAdded should be called whenever an element is added to a
2942 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2944 // ElementRemoved should be called whenever an element is removed from
2946 void ElementRemoved() {
2947 SetNumberOfElements(NumberOfElements() - 1);
2948 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2950 void ElementsRemoved(int n) {
2951 SetNumberOfElements(NumberOfElements() - n);
2952 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2955 // Computes the required capacity for a table holding the given
2956 // number of elements. May be more than HashTable::kMaxCapacity.
2957 static inline int ComputeCapacity(int at_least_space_for);
2959 // Use a different heuristic to compute capacity when serializing.
2960 static inline int ComputeCapacityForSerialization(int at_least_space_for);
2962 // Tells whether k is a real key. The hole and undefined are not allowed
2963 // as keys and can be used to indicate missing or deleted elements.
2964 bool IsKey(Object* k) {
2965 return !k->IsTheHole() && !k->IsUndefined();
2968 // Compute the probe offset (quadratic probing).
2969 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2970 return (n + n * n) >> 1;
2973 static const int kNumberOfElementsIndex = 0;
2974 static const int kNumberOfDeletedElementsIndex = 1;
2975 static const int kCapacityIndex = 2;
2976 static const int kPrefixStartIndex = 3;
2978 // Constant used for denoting a absent entry.
2979 static const int kNotFound = -1;
2982 // Update the number of elements in the hash table.
2983 void SetNumberOfElements(int nof) {
2984 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2987 // Update the number of deleted elements in the hash table.
2988 void SetNumberOfDeletedElements(int nod) {
2989 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2992 // Returns probe entry.
2993 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2994 DCHECK(base::bits::IsPowerOfTwo32(size));
2995 return (hash + GetProbeOffset(number)) & (size - 1);
2998 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2999 return hash & (size - 1);
3002 inline static uint32_t NextProbe(
3003 uint32_t last, uint32_t number, uint32_t size) {
3004 return (last + number) & (size - 1);
3009 template <typename Derived, typename Shape, typename Key>
3010 class HashTable : public HashTableBase {
3013 inline uint32_t Hash(Key key) {
3014 if (Shape::UsesSeed) {
3015 return Shape::SeededHash(key, GetHeap()->HashSeed());
3017 return Shape::Hash(key);
3021 inline uint32_t HashForObject(Key key, Object* object) {
3022 if (Shape::UsesSeed) {
3023 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3025 return Shape::HashForObject(key, object);
3029 // Returns a new HashTable object.
3030 MUST_USE_RESULT static Handle<Derived> New(
3031 Isolate* isolate, int at_least_space_for,
3032 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3033 PretenureFlag pretenure = NOT_TENURED);
3035 DECLARE_CAST(HashTable)
3037 // Garbage collection support.
3038 void IteratePrefix(ObjectVisitor* visitor);
3039 void IterateElements(ObjectVisitor* visitor);
3041 // Find entry for key otherwise return kNotFound.
3042 inline int FindEntry(Key key);
3043 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3044 int FindEntry(Isolate* isolate, Key key);
3046 // Rehashes the table in-place.
3047 void Rehash(Key key);
3049 // Returns the key at entry.
3050 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3052 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3053 static const int kEntrySize = Shape::kEntrySize;
3054 static const int kElementsStartOffset =
3055 kHeaderSize + kElementsStartIndex * kPointerSize;
3056 static const int kCapacityOffset =
3057 kHeaderSize + kCapacityIndex * kPointerSize;
3059 // Returns the index for an entry (of the key)
3060 static inline int EntryToIndex(int entry) {
3061 return (entry * kEntrySize) + kElementsStartIndex;
3065 friend class ObjectHashTable;
3067 // Find the entry at which to insert element with the given key that
3068 // has the given hash value.
3069 uint32_t FindInsertionEntry(uint32_t hash);
3071 // Attempt to shrink hash table after removal of key.
3072 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3074 // Ensure enough space for n additional elements.
3075 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3076 Handle<Derived> table,
3079 PretenureFlag pretenure = NOT_TENURED);
3081 // Sets the capacity of the hash table.
3082 void SetCapacity(int capacity) {
3083 // To scale a computed hash code to fit within the hash table, we
3084 // use bit-wise AND with a mask, so the capacity must be positive
3086 DCHECK(capacity > 0);
3087 DCHECK(capacity <= kMaxCapacity);
3088 set(kCapacityIndex, Smi::FromInt(capacity));
3091 // Maximal capacity of HashTable. Based on maximal length of underlying
3092 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3094 static const int kMaxCapacity =
3095 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3098 // Returns _expected_ if one of entries given by the first _probe_ probes is
3099 // equal to _expected_. Otherwise, returns the entry given by the probe
3101 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3103 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3105 // Rehashes this hash-table into the new table.
3106 void Rehash(Handle<Derived> new_table, Key key);
3110 // HashTableKey is an abstract superclass for virtual key behavior.
3111 class HashTableKey {
3113 // Returns whether the other object matches this key.
3114 virtual bool IsMatch(Object* other) = 0;
3115 // Returns the hash value for this key.
3116 virtual uint32_t Hash() = 0;
3117 // Returns the hash value for object.
3118 virtual uint32_t HashForObject(Object* key) = 0;
3119 // Returns the key object for storing into the hash table.
3120 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3122 virtual ~HashTableKey() {}
3126 class StringTableShape : public BaseShape<HashTableKey*> {
3128 static inline bool IsMatch(HashTableKey* key, Object* value) {
3129 return key->IsMatch(value);
3132 static inline uint32_t Hash(HashTableKey* key) {
3136 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3137 return key->HashForObject(object);
3140 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3142 static const int kPrefixSize = 0;
3143 static const int kEntrySize = 1;
3146 class SeqOneByteString;
3150 // No special elements in the prefix and the element size is 1
3151 // because only the string itself (the key) needs to be stored.
3152 class StringTable: public HashTable<StringTable,
3156 // Find string in the string table. If it is not there yet, it is
3157 // added. The return value is the string found.
3158 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3159 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3160 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3162 // Tries to internalize given string and returns string handle on success
3163 // or an empty handle otherwise.
3164 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3166 Handle<String> string);
3168 // Looks up a string that is equal to the given string and returns
3169 // string handle if it is found, or an empty handle otherwise.
3170 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3172 Handle<String> str);
3173 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3178 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3180 DECLARE_CAST(StringTable)
3183 template <bool seq_one_byte>
3184 friend class JsonParser;
3186 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3190 template <typename Derived, typename Shape, typename Key>
3191 class Dictionary: public HashTable<Derived, Shape, Key> {
3192 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3195 // Returns the value at entry.
3196 Object* ValueAt(int entry) {
3197 return this->get(Derived::EntryToIndex(entry) + 1);
3200 // Set the value for entry.
3201 void ValueAtPut(int entry, Object* value) {
3202 this->set(Derived::EntryToIndex(entry) + 1, value);
3205 // Returns the property details for the property at entry.
3206 PropertyDetails DetailsAt(int entry) {
3207 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3210 // Set the details for entry.
3211 void DetailsAtPut(int entry, PropertyDetails value) {
3212 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3215 // Returns true if property at given entry is deleted.
3216 bool IsDeleted(int entry) {
3217 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3220 // Delete a property from the dictionary.
3221 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3223 // Attempt to shrink the dictionary after deletion of key.
3224 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3225 Handle<Derived> dictionary,
3227 return DerivedHashTable::Shrink(dictionary, key);
3231 // TODO(dcarney): templatize or move to SeededNumberDictionary
3232 void CopyValuesTo(FixedArray* elements);
3234 // Returns the number of elements in the dictionary filtering out properties
3235 // with the specified attributes.
3236 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3238 // Returns the number of enumerable elements in the dictionary.
3239 int NumberOfEnumElements() {
3240 return NumberOfElementsFilterAttributes(
3241 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3244 // Returns true if the dictionary contains any elements that are non-writable,
3245 // non-configurable, non-enumerable, or have getters/setters.
3246 bool HasComplexElements();
3248 enum SortMode { UNSORTED, SORTED };
3250 // Copies keys to preallocated fixed array.
3251 void CopyKeysTo(FixedArray* storage, PropertyAttributes filter,
3252 SortMode sort_mode);
3254 // Fill in details for properties into storage.
3255 void CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3256 SortMode sort_mode);
3258 // Copies enumerable keys to preallocated fixed array.
3259 void CopyEnumKeysTo(FixedArray* storage);
3261 // Accessors for next enumeration index.
3262 void SetNextEnumerationIndex(int index) {
3264 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3267 int NextEnumerationIndex() {
3268 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3271 // Creates a new dictionary.
3272 MUST_USE_RESULT static Handle<Derived> New(
3274 int at_least_space_for,
3275 PretenureFlag pretenure = NOT_TENURED);
3277 // Ensure enough space for n additional elements.
3278 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3281 void Print(std::ostream& os); // NOLINT
3283 // Returns the key (slow).
3284 Object* SlowReverseLookup(Object* value);
3286 // Sets the entry to (key, value) pair.
3287 inline void SetEntry(int entry,
3289 Handle<Object> value);
3290 inline void SetEntry(int entry,
3292 Handle<Object> value,
3293 PropertyDetails details);
3295 MUST_USE_RESULT static Handle<Derived> Add(
3296 Handle<Derived> dictionary,
3298 Handle<Object> value,
3299 PropertyDetails details);
3301 // Returns iteration indices array for the |dictionary|.
3302 // Values are direct indices in the |HashTable| array.
3303 static Handle<FixedArray> BuildIterationIndicesArray(
3304 Handle<Derived> dictionary);
3307 // Generic at put operation.
3308 MUST_USE_RESULT static Handle<Derived> AtPut(
3309 Handle<Derived> dictionary,
3311 Handle<Object> value);
3313 // Add entry to dictionary.
3314 static void AddEntry(
3315 Handle<Derived> dictionary,
3317 Handle<Object> value,
3318 PropertyDetails details,
3321 // Generate new enumeration indices to avoid enumeration index overflow.
3322 // Returns iteration indices array for the |dictionary|.
3323 static Handle<FixedArray> GenerateNewEnumerationIndices(
3324 Handle<Derived> dictionary);
3325 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3326 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3330 template <typename Derived, typename Shape>
3331 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3332 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3335 // Find entry for key, otherwise return kNotFound. Optimized version of
3336 // HashTable::FindEntry.
3337 int FindEntry(Handle<Name> key);
3341 template <typename Key>
3342 class BaseDictionaryShape : public BaseShape<Key> {
3344 template <typename Dictionary>
3345 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3346 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3347 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3348 return PropertyDetails(
3349 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3352 template <typename Dictionary>
3353 static inline void DetailsAtPut(Dictionary* dict, int entry,
3354 PropertyDetails value) {
3355 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3356 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3359 template <typename Dictionary>
3360 static bool IsDeleted(Dictionary* dict, int entry) {
3364 template <typename Dictionary>
3365 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3366 Handle<Object> value, PropertyDetails details);
3370 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3372 static inline bool IsMatch(Handle<Name> key, Object* other);
3373 static inline uint32_t Hash(Handle<Name> key);
3374 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3375 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3376 static const int kPrefixSize = 2;
3377 static const int kEntrySize = 3;
3378 static const bool kIsEnumerable = true;
3382 class NameDictionary
3383 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3384 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3388 DECLARE_CAST(NameDictionary)
3390 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3391 Handle<NameDictionary> dictionary);
3395 class GlobalDictionaryShape : public NameDictionaryShape {
3397 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3399 template <typename Dictionary>
3400 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3402 template <typename Dictionary>
3403 static inline void DetailsAtPut(Dictionary* dict, int entry,
3404 PropertyDetails value);
3406 template <typename Dictionary>
3407 static bool IsDeleted(Dictionary* dict, int entry);
3409 template <typename Dictionary>
3410 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3411 Handle<Object> value, PropertyDetails details);
3415 class GlobalDictionary
3416 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3418 DECLARE_CAST(GlobalDictionary)
3422 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3424 static inline bool IsMatch(uint32_t key, Object* other);
3425 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3426 static const int kEntrySize = 3;
3427 static const bool kIsEnumerable = false;
3431 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3433 static const bool UsesSeed = true;
3434 static const int kPrefixSize = 2;
3436 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3437 static inline uint32_t SeededHashForObject(uint32_t key,
3443 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3445 static const int kPrefixSize = 0;
3447 static inline uint32_t Hash(uint32_t key);
3448 static inline uint32_t HashForObject(uint32_t key, Object* object);
3452 class SeededNumberDictionary
3453 : public Dictionary<SeededNumberDictionary,
3454 SeededNumberDictionaryShape,
3457 DECLARE_CAST(SeededNumberDictionary)
3459 // Type specific at put (default NONE attributes is used when adding).
3460 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3461 Handle<SeededNumberDictionary> dictionary,
3463 Handle<Object> value);
3464 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3465 Handle<SeededNumberDictionary> dictionary,
3467 Handle<Object> value,
3468 PropertyDetails details);
3470 // Set an existing entry or add a new one if needed.
3471 // Return the updated dictionary.
3472 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3473 Handle<SeededNumberDictionary> dictionary,
3475 Handle<Object> value,
3476 PropertyDetails details);
3478 void UpdateMaxNumberKey(uint32_t key);
3480 // If slow elements are required we will never go back to fast-case
3481 // for the elements kept in this dictionary. We require slow
3482 // elements if an element has been added at an index larger than
3483 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3484 // when defining a getter or setter with a number key.
3485 inline bool requires_slow_elements();
3486 inline void set_requires_slow_elements();
3488 // Get the value of the max number key that has been added to this
3489 // dictionary. max_number_key can only be called if
3490 // requires_slow_elements returns false.
3491 inline uint32_t max_number_key();
3494 static const int kRequiresSlowElementsMask = 1;
3495 static const int kRequiresSlowElementsTagSize = 1;
3496 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3500 class UnseededNumberDictionary
3501 : public Dictionary<UnseededNumberDictionary,
3502 UnseededNumberDictionaryShape,
3505 DECLARE_CAST(UnseededNumberDictionary)
3507 // Type specific at put (default NONE attributes is used when adding).
3508 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3509 Handle<UnseededNumberDictionary> dictionary,
3511 Handle<Object> value);
3512 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3513 Handle<UnseededNumberDictionary> dictionary,
3515 Handle<Object> value);
3517 // Set an existing entry or add a new one if needed.
3518 // Return the updated dictionary.
3519 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3520 Handle<UnseededNumberDictionary> dictionary,
3522 Handle<Object> value);
3526 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3528 static inline bool IsMatch(Handle<Object> key, Object* other);
3529 static inline uint32_t Hash(Handle<Object> key);
3530 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3531 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3532 static const int kPrefixSize = 0;
3533 static const int kEntrySize = 2;
3537 // ObjectHashTable maps keys that are arbitrary objects to object values by
3538 // using the identity hash of the key for hashing purposes.
3539 class ObjectHashTable: public HashTable<ObjectHashTable,
3540 ObjectHashTableShape,
3543 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3545 DECLARE_CAST(ObjectHashTable)
3547 // Attempt to shrink hash table after removal of key.
3548 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3549 Handle<ObjectHashTable> table,
3550 Handle<Object> key);
3552 // Looks up the value associated with the given key. The hole value is
3553 // returned in case the key is not present.
3554 Object* Lookup(Handle<Object> key);
3555 Object* Lookup(Handle<Object> key, int32_t hash);
3556 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3558 // Adds (or overwrites) the value associated with the given key.
3559 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3561 Handle<Object> value);
3562 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3563 Handle<Object> key, Handle<Object> value,
3566 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3567 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3570 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3571 Handle<Object> key, bool* was_present,
3575 friend class MarkCompactCollector;
3577 void AddEntry(int entry, Object* key, Object* value);
3578 void RemoveEntry(int entry);
3580 // Returns the index to the value of an entry.
3581 static inline int EntryToValueIndex(int entry) {
3582 return EntryToIndex(entry) + 1;
3587 // OrderedHashTable is a HashTable with Object keys that preserves
3588 // insertion order. There are Map and Set interfaces (OrderedHashMap
3589 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3591 // Only Object* keys are supported, with Object::SameValueZero() used as the
3592 // equality operator and Object::GetHash() for the hash function.
3594 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3595 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3596 // Originally attributed to Tyler Close.
3599 // [0]: bucket count
3600 // [1]: element count
3601 // [2]: deleted element count
3602 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3603 // offset into the data table (see below) where the
3604 // first item in this bucket is stored.
3605 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3606 // Capacity() * kEntrySize, where the first entrysize
3607 // items are handled by the derived class and the
3608 // item at kChainOffset is another entry into the
3609 // data table indicating the next entry in this hash
3612 // When we transition the table to a new version we obsolete it and reuse parts
3613 // of the memory to store information how to transition an iterator to the new
3616 // Memory layout for obsolete table:
3617 // [0]: bucket count
3618 // [1]: Next newer table
3619 // [2]: Number of removed holes or -1 when the table was cleared.
3620 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3621 // [3 + NumberOfRemovedHoles()..length]: Not used
3623 template<class Derived, class Iterator, int entrysize>
3624 class OrderedHashTable: public FixedArray {
3626 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3627 static Handle<Derived> Allocate(
3628 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3630 // Returns an OrderedHashTable (possibly |table|) with enough space
3631 // to add at least one new element.
3632 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3634 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3636 static Handle<Derived> Shrink(Handle<Derived> table);
3638 // Returns a new empty OrderedHashTable and records the clearing so that
3639 // exisiting iterators can be updated.
3640 static Handle<Derived> Clear(Handle<Derived> table);
3642 int NumberOfElements() {
3643 return Smi::cast(get(kNumberOfElementsIndex))->value();
3646 int NumberOfDeletedElements() {
3647 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3650 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3652 int NumberOfBuckets() {
3653 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3656 // Returns an index into |this| for the given entry.
3657 int EntryToIndex(int entry) {
3658 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3661 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3664 return !get(kNextTableIndex)->IsSmi();
3667 // The next newer table. This is only valid if the table is obsolete.
3668 Derived* NextTable() {
3669 return Derived::cast(get(kNextTableIndex));
3672 // When the table is obsolete we store the indexes of the removed holes.
3673 int RemovedIndexAt(int index) {
3674 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3677 static const int kNotFound = -1;
3678 static const int kMinCapacity = 4;
3680 static const int kNumberOfBucketsIndex = 0;
3681 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3682 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3683 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3684 static const int kNextTableIndex = kNumberOfElementsIndex;
3686 static const int kNumberOfBucketsOffset =
3687 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3688 static const int kNumberOfElementsOffset =
3689 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3690 static const int kNumberOfDeletedElementsOffset =
3691 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3692 static const int kHashTableStartOffset =
3693 kHeaderSize + kHashTableStartIndex * kPointerSize;
3694 static const int kNextTableOffset =
3695 kHeaderSize + kNextTableIndex * kPointerSize;
3697 static const int kEntrySize = entrysize + 1;
3698 static const int kChainOffset = entrysize;
3700 static const int kLoadFactor = 2;
3702 // NumberOfDeletedElements is set to kClearedTableSentinel when
3703 // the table is cleared, which allows iterator transitions to
3704 // optimize that case.
3705 static const int kClearedTableSentinel = -1;
3708 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3710 void SetNumberOfBuckets(int num) {
3711 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3714 void SetNumberOfElements(int num) {
3715 set(kNumberOfElementsIndex, Smi::FromInt(num));
3718 void SetNumberOfDeletedElements(int num) {
3719 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3723 return NumberOfBuckets() * kLoadFactor;
3726 void SetNextTable(Derived* next_table) {
3727 set(kNextTableIndex, next_table);
3730 void SetRemovedIndexAt(int index, int removed_index) {
3731 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3734 static const int kRemovedHolesIndex = kHashTableStartIndex;
3736 static const int kMaxCapacity =
3737 (FixedArray::kMaxLength - kHashTableStartIndex)
3738 / (1 + (kEntrySize * kLoadFactor));
3742 class JSSetIterator;
3745 class OrderedHashSet: public OrderedHashTable<
3746 OrderedHashSet, JSSetIterator, 1> {
3748 DECLARE_CAST(OrderedHashSet)
3752 class JSMapIterator;
3755 class OrderedHashMap
3756 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3758 DECLARE_CAST(OrderedHashMap)
3760 Object* ValueAt(int entry) {
3761 return get(EntryToIndex(entry) + kValueOffset);
3764 static const int kValueOffset = 1;
3768 template <int entrysize>
3769 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3771 static inline bool IsMatch(Handle<Object> key, Object* other);
3772 static inline uint32_t Hash(Handle<Object> key);
3773 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3774 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3775 static const int kPrefixSize = 0;
3776 static const int kEntrySize = entrysize;
3780 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3781 // values. The table wraps the keys in weak cells and store values directly.
3782 // Thus it references keys weakly and values strongly.
3783 class WeakHashTable: public HashTable<WeakHashTable,
3784 WeakHashTableShape<2>,
3787 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3789 DECLARE_CAST(WeakHashTable)
3791 // Looks up the value associated with the given key. The hole value is
3792 // returned in case the key is not present.
3793 Object* Lookup(Handle<HeapObject> key);
3795 // Adds (or overwrites) the value associated with the given key. Mapping a
3796 // key to the hole value causes removal of the whole entry.
3797 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3798 Handle<HeapObject> key,
3799 Handle<HeapObject> value);
3801 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3804 friend class MarkCompactCollector;
3806 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3808 // Returns the index to the value of an entry.
3809 static inline int EntryToValueIndex(int entry) {
3810 return EntryToIndex(entry) + 1;
3815 class WeakValueHashTable : public ObjectHashTable {
3817 DECLARE_CAST(WeakValueHashTable)
3820 // Looks up the value associated with the given key. The hole value is
3821 // returned in case the key is not present.
3822 Object* LookupWeak(Handle<Object> key);
3825 // Adds (or overwrites) the value associated with the given key. Mapping a
3826 // key to the hole value causes removal of the whole entry.
3827 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3828 Handle<WeakValueHashTable> table, Handle<Object> key,
3829 Handle<HeapObject> value);
3831 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3835 // JSFunctionResultCache caches results of some JSFunction invocation.
3836 // It is a fixed array with fixed structure:
3837 // [0]: factory function
3838 // [1]: finger index
3839 // [2]: current cache size
3840 // [3]: dummy field.
3841 // The rest of array are key/value pairs.
3842 class JSFunctionResultCache : public FixedArray {
3844 static const int kFactoryIndex = 0;
3845 static const int kFingerIndex = kFactoryIndex + 1;
3846 static const int kCacheSizeIndex = kFingerIndex + 1;
3847 static const int kDummyIndex = kCacheSizeIndex + 1;
3848 static const int kEntriesIndex = kDummyIndex + 1;
3850 static const int kEntrySize = 2; // key + value
3852 static const int kFactoryOffset = kHeaderSize;
3853 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3854 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3856 inline void MakeZeroSize();
3857 inline void Clear();
3860 inline void set_size(int size);
3861 inline int finger_index();
3862 inline void set_finger_index(int finger_index);
3864 DECLARE_CAST(JSFunctionResultCache)
3866 DECLARE_VERIFIER(JSFunctionResultCache)
3870 // ScopeInfo represents information about different scopes of a source
3871 // program and the allocation of the scope's variables. Scope information
3872 // is stored in a compressed form in ScopeInfo objects and is used
3873 // at runtime (stack dumps, deoptimization, etc.).
3875 // This object provides quick access to scope info details for runtime
3877 class ScopeInfo : public FixedArray {
3879 DECLARE_CAST(ScopeInfo)
3881 // Return the type of this scope.
3882 ScopeType scope_type();
3884 // Does this scope call eval?
3887 // Return the language mode of this scope.
3888 LanguageMode language_mode();
3890 // Does this scope make a sloppy eval call?
3891 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3893 // Return the total number of locals allocated on the stack and in the
3894 // context. This includes the parameters that are allocated in the context.
3897 // Return the number of stack slots for code. This number consists of two
3899 // 1. One stack slot per stack allocated local.
3900 // 2. One stack slot for the function name if it is stack allocated.
3901 int StackSlotCount();
3903 // Return the number of context slots for code if a context is allocated. This
3904 // number consists of three parts:
3905 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3906 // 2. One context slot per context allocated local.
3907 // 3. One context slot for the function name if it is context allocated.
3908 // Parameters allocated in the context count as context allocated locals. If
3909 // no contexts are allocated for this scope ContextLength returns 0.
3910 int ContextLength();
3912 // Does this scope declare a "this" binding?
3915 // Does this scope declare a "this" binding, and the "this" binding is stack-
3916 // or context-allocated?
3917 bool HasAllocatedReceiver();
3919 // Is this scope the scope of a named function expression?
3920 bool HasFunctionName();
3922 // Return if this has context allocated locals.
3923 bool HasHeapAllocatedLocals();
3925 // Return if contexts are allocated for this scope.
3928 // Return if this is a function scope with "use asm".
3929 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3931 // Return if this is a nested function within an asm module scope.
3932 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3934 bool IsSimpleParameterList() {
3935 return IsSimpleParameterListField::decode(Flags());
3938 // Return the function_name if present.
3939 String* FunctionName();
3941 // Return the name of the given parameter.
3942 String* ParameterName(int var);
3944 // Return the name of the given local.
3945 String* LocalName(int var);
3947 // Return the name of the given stack local.
3948 String* StackLocalName(int var);
3950 // Return the name of the given stack local.
3951 int StackLocalIndex(int var);
3953 // Return the name of the given context local.
3954 String* ContextLocalName(int var);
3956 // Return the mode of the given context local.
3957 VariableMode ContextLocalMode(int var);
3959 // Return the initialization flag of the given context local.
3960 InitializationFlag ContextLocalInitFlag(int var);
3962 // Return the initialization flag of the given context local.
3963 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3965 // Return true if this local was introduced by the compiler, and should not be
3966 // exposed to the user in a debugger.
3967 bool LocalIsSynthetic(int var);
3969 String* StrongModeFreeVariableName(int var);
3970 int StrongModeFreeVariableStartPosition(int var);
3971 int StrongModeFreeVariableEndPosition(int var);
3973 // Lookup support for serialized scope info. Returns the
3974 // the stack slot index for a given slot name if the slot is
3975 // present; otherwise returns a value < 0. The name must be an internalized
3977 int StackSlotIndex(String* name);
3979 // Lookup support for serialized scope info. Returns the
3980 // context slot index for a given slot name if the slot is present; otherwise
3981 // returns a value < 0. The name must be an internalized string.
3982 // If the slot is present and mode != NULL, sets *mode to the corresponding
3983 // mode for that variable.
3984 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3985 VariableMode* mode, VariableLocation* location,
3986 InitializationFlag* init_flag,
3987 MaybeAssignedFlag* maybe_assigned_flag);
3989 // Lookup support for serialized scope info. Returns the
3990 // parameter index for a given parameter name if the parameter is present;
3991 // otherwise returns a value < 0. The name must be an internalized string.
3992 int ParameterIndex(String* name);
3994 // Lookup support for serialized scope info. Returns the function context
3995 // slot index if the function name is present and context-allocated (named
3996 // function expressions, only), otherwise returns a value < 0. The name
3997 // must be an internalized string.
3998 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4000 // Lookup support for serialized scope info. Returns the receiver context
4001 // slot index if scope has a "this" binding, and the binding is
4002 // context-allocated. Otherwise returns a value < 0.
4003 int ReceiverContextSlotIndex();
4005 FunctionKind function_kind();
4007 // Copies all the context locals into an object used to materialize a scope.
4008 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4009 Handle<Context> context,
4010 Handle<JSObject> scope_object);
4013 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4014 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4016 // Serializes empty scope info.
4017 static ScopeInfo* Empty(Isolate* isolate);
4023 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4024 // numeric and occupies one array slot.
4025 // 1. A set of properties of the scope
4026 // 2. The number of parameters. This only applies to function scopes. For
4027 // non-function scopes this is 0.
4028 // 3. The number of non-parameter variables allocated on the stack.
4029 // 4. The number of non-parameter and parameter variables allocated in the
4031 #define FOR_EACH_NUMERIC_FIELD(V) \
4034 V(StackLocalCount) \
4035 V(ContextLocalCount) \
4036 V(ContextGlobalCount) \
4037 V(StrongModeFreeVariableCount)
4039 #define FIELD_ACCESSORS(name) \
4040 void Set##name(int value) { \
4041 set(k##name, Smi::FromInt(value)); \
4044 if (length() > 0) { \
4045 return Smi::cast(get(k##name))->value(); \
4050 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4051 #undef FIELD_ACCESSORS
4055 #define DECL_INDEX(name) k##name,
4056 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4058 #undef FOR_EACH_NUMERIC_FIELD
4062 // The layout of the variable part of a ScopeInfo is as follows:
4063 // 1. ParameterEntries:
4064 // This part stores the names of the parameters for function scopes. One
4065 // slot is used per parameter, so in total this part occupies
4066 // ParameterCount() slots in the array. For other scopes than function
4067 // scopes ParameterCount() is 0.
4068 // 2. StackLocalFirstSlot:
4069 // Index of a first stack slot for stack local. Stack locals belonging to
4070 // this scope are located on a stack at slots starting from this index.
4071 // 3. StackLocalEntries:
4072 // Contains the names of local variables that are allocated on the stack,
4073 // in increasing order of the stack slot index. First local variable has
4074 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4075 // One slot is used per stack local, so in total this part occupies
4076 // StackLocalCount() slots in the array.
4077 // 4. ContextLocalNameEntries:
4078 // Contains the names of local variables and parameters that are allocated
4079 // in the context. They are stored in increasing order of the context slot
4080 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4081 // context local, so in total this part occupies ContextLocalCount() slots
4083 // 5. ContextLocalInfoEntries:
4084 // Contains the variable modes and initialization flags corresponding to
4085 // the context locals in ContextLocalNameEntries. One slot is used per
4086 // context local, so in total this part occupies ContextLocalCount()
4087 // slots in the array.
4088 // 6. StrongModeFreeVariableNameEntries:
4089 // Stores the names of strong mode free variables.
4090 // 7. StrongModeFreeVariablePositionEntries:
4091 // Stores the locations (start and end position) of strong mode free
4093 // 8. RecieverEntryIndex:
4094 // If the scope binds a "this" value, one slot is reserved to hold the
4095 // context or stack slot index for the variable.
4096 // 9. FunctionNameEntryIndex:
4097 // If the scope belongs to a named function expression this part contains
4098 // information about the function variable. It always occupies two array
4099 // slots: a. The name of the function variable.
4100 // b. The context or stack slot index for the variable.
4101 int ParameterEntriesIndex();
4102 int StackLocalFirstSlotIndex();
4103 int StackLocalEntriesIndex();
4104 int ContextLocalNameEntriesIndex();
4105 int ContextGlobalNameEntriesIndex();
4106 int ContextLocalInfoEntriesIndex();
4107 int ContextGlobalInfoEntriesIndex();
4108 int StrongModeFreeVariableNameEntriesIndex();
4109 int StrongModeFreeVariablePositionEntriesIndex();
4110 int ReceiverEntryIndex();
4111 int FunctionNameEntryIndex();
4113 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4114 VariableLocation* location, InitializationFlag* init_flag,
4115 MaybeAssignedFlag* maybe_assigned_flag);
4117 // Used for the function name variable for named function expressions, and for
4119 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4121 // Properties of scopes.
4122 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4123 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4124 STATIC_ASSERT(LANGUAGE_END == 3);
4125 class LanguageModeField
4126 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4127 class ReceiverVariableField
4128 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4129 class FunctionVariableField
4130 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4132 class FunctionVariableMode
4133 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4134 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4136 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4137 class IsSimpleParameterListField
4138 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4139 class FunctionKindField
4140 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4142 // BitFields representing the encoded information for context locals in the
4143 // ContextLocalInfoEntries part.
4144 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4145 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4146 class ContextLocalMaybeAssignedFlag
4147 : public BitField<MaybeAssignedFlag, 4, 1> {};
4151 // The cache for maps used by normalized (dictionary mode) objects.
4152 // Such maps do not have property descriptors, so a typical program
4153 // needs very limited number of distinct normalized maps.
4154 class NormalizedMapCache: public FixedArray {
4156 static Handle<NormalizedMapCache> New(Isolate* isolate);
4158 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4159 PropertyNormalizationMode mode);
4160 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4164 DECLARE_CAST(NormalizedMapCache)
4166 static inline bool IsNormalizedMapCache(const Object* obj);
4168 DECLARE_VERIFIER(NormalizedMapCache)
4170 static const int kEntries = 64;
4172 static inline int GetIndex(Handle<Map> map);
4174 // The following declarations hide base class methods.
4175 Object* get(int index);
4176 void set(int index, Object* value);
4180 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4181 // that is attached to code objects.
4182 class ByteArray: public FixedArrayBase {
4184 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4186 // Setter and getter.
4187 inline byte get(int index);
4188 inline void set(int index, byte value);
4190 // Treat contents as an int array.
4191 inline int get_int(int index);
4193 static int SizeFor(int length) {
4194 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4196 // We use byte arrays for free blocks in the heap. Given a desired size in
4197 // bytes that is a multiple of the word size and big enough to hold a byte
4198 // array, this function returns the number of elements a byte array should
4200 static int LengthFor(int size_in_bytes) {
4201 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4202 DCHECK(size_in_bytes >= kHeaderSize);
4203 return size_in_bytes - kHeaderSize;
4206 // Returns data start address.
4207 inline Address GetDataStartAddress();
4209 // Returns a pointer to the ByteArray object for a given data start address.
4210 static inline ByteArray* FromDataStartAddress(Address address);
4212 DECLARE_CAST(ByteArray)
4214 // Dispatched behavior.
4215 inline int ByteArraySize() {
4216 return SizeFor(this->length());
4218 DECLARE_PRINTER(ByteArray)
4219 DECLARE_VERIFIER(ByteArray)
4221 // Layout description.
4222 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4224 // Maximal memory consumption for a single ByteArray.
4225 static const int kMaxSize = 512 * MB;
4226 // Maximal length of a single ByteArray.
4227 static const int kMaxLength = kMaxSize - kHeaderSize;
4230 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4234 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4235 // They look like heap objects (are heap object tagged and have a map) so that
4236 // the heap remains iterable. They have a size and a next pointer.
4237 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4238 // in the free list.
4239 class FreeSpace: public HeapObject {
4241 // [size]: size of the free space including the header.
4242 inline int size() const;
4243 inline void set_size(int value);
4245 inline int nobarrier_size() const;
4246 inline void nobarrier_set_size(int value);
4248 inline int Size() { return size(); }
4250 // Accessors for the next field.
4251 inline FreeSpace* next();
4252 inline FreeSpace** next_address();
4253 inline void set_next(FreeSpace* next);
4255 inline static FreeSpace* cast(HeapObject* obj);
4257 // Dispatched behavior.
4258 DECLARE_PRINTER(FreeSpace)
4259 DECLARE_VERIFIER(FreeSpace)
4261 // Layout description.
4262 // Size is smi tagged when it is stored.
4263 static const int kSizeOffset = HeapObject::kHeaderSize;
4264 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4267 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4271 // V has parameters (Type, type, TYPE, C type, element_size)
4272 #define TYPED_ARRAYS(V) \
4273 V(Uint8, uint8, UINT8, uint8_t, 1) \
4274 V(Int8, int8, INT8, int8_t, 1) \
4275 V(Uint16, uint16, UINT16, uint16_t, 2) \
4276 V(Int16, int16, INT16, int16_t, 2) \
4277 V(Uint32, uint32, UINT32, uint32_t, 4) \
4278 V(Int32, int32, INT32, int32_t, 4) \
4279 V(Float32, float32, FLOAT32, float, 4) \
4280 V(Float64, float64, FLOAT64, double, 8) \
4281 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4285 // An ExternalArray represents a fixed-size array of primitive values
4286 // which live outside the JavaScript heap. Its subclasses are used to
4287 // implement the CanvasArray types being defined in the WebGL
4288 // specification. As of this writing the first public draft is not yet
4289 // available, but Khronos members can access the draft at:
4290 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4292 // The semantics of these arrays differ from CanvasPixelArray.
4293 // Out-of-range values passed to the setter are converted via a C
4294 // cast, not clamping. Out-of-range indices cause exceptions to be
4295 // raised rather than being silently ignored.
4296 class ExternalArray: public FixedArrayBase {
4298 inline bool is_the_hole(int index) { return false; }
4300 // [external_pointer]: The pointer to the external memory area backing this
4302 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4304 DECLARE_CAST(ExternalArray)
4306 // Maximal acceptable length for an external array.
4307 static const int kMaxLength = 0x3fffffff;
4309 // ExternalArray headers are not quadword aligned.
4310 static const int kExternalPointerOffset =
4311 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4312 static const int kSize = kExternalPointerOffset + kPointerSize;
4315 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4319 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4320 // semantics used for implementing the CanvasPixelArray object. Please see the
4321 // specification at:
4323 // http://www.whatwg.org/specs/web-apps/current-work/
4324 // multipage/the-canvas-element.html#canvaspixelarray
4325 // In particular, write access clamps the value written to 0 or 255 if the
4326 // value written is outside this range.
4327 class ExternalUint8ClampedArray: public ExternalArray {
4329 inline uint8_t* external_uint8_clamped_pointer();
4331 // Setter and getter.
4332 inline uint8_t get_scalar(int index);
4333 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4335 inline void set(int index, uint8_t value);
4337 // This accessor applies the correct conversion from Smi, HeapNumber
4338 // and undefined and clamps the converted value between 0 and 255.
4339 void SetValue(uint32_t index, Object* value);
4341 DECLARE_CAST(ExternalUint8ClampedArray)
4343 // Dispatched behavior.
4344 DECLARE_PRINTER(ExternalUint8ClampedArray)
4345 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4348 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4352 class ExternalInt8Array: public ExternalArray {
4354 // Setter and getter.
4355 inline int8_t get_scalar(int index);
4356 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4357 inline void set(int index, int8_t value);
4359 // This accessor applies the correct conversion from Smi, HeapNumber
4361 void SetValue(uint32_t index, Object* value);
4363 DECLARE_CAST(ExternalInt8Array)
4365 // Dispatched behavior.
4366 DECLARE_PRINTER(ExternalInt8Array)
4367 DECLARE_VERIFIER(ExternalInt8Array)
4370 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4374 class ExternalUint8Array: public ExternalArray {
4376 // Setter and getter.
4377 inline uint8_t get_scalar(int index);
4378 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4379 inline void set(int index, uint8_t value);
4381 // This accessor applies the correct conversion from Smi, HeapNumber
4383 void SetValue(uint32_t index, Object* value);
4385 DECLARE_CAST(ExternalUint8Array)
4387 // Dispatched behavior.
4388 DECLARE_PRINTER(ExternalUint8Array)
4389 DECLARE_VERIFIER(ExternalUint8Array)
4392 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4396 class ExternalInt16Array: public ExternalArray {
4398 // Setter and getter.
4399 inline int16_t get_scalar(int index);
4400 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4401 inline void set(int index, int16_t value);
4403 // This accessor applies the correct conversion from Smi, HeapNumber
4405 void SetValue(uint32_t index, Object* value);
4407 DECLARE_CAST(ExternalInt16Array)
4409 // Dispatched behavior.
4410 DECLARE_PRINTER(ExternalInt16Array)
4411 DECLARE_VERIFIER(ExternalInt16Array)
4414 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4418 class ExternalUint16Array: public ExternalArray {
4420 // Setter and getter.
4421 inline uint16_t get_scalar(int index);
4422 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4424 inline void set(int index, uint16_t value);
4426 // This accessor applies the correct conversion from Smi, HeapNumber
4428 void SetValue(uint32_t index, Object* value);
4430 DECLARE_CAST(ExternalUint16Array)
4432 // Dispatched behavior.
4433 DECLARE_PRINTER(ExternalUint16Array)
4434 DECLARE_VERIFIER(ExternalUint16Array)
4437 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4441 class ExternalInt32Array: public ExternalArray {
4443 // Setter and getter.
4444 inline int32_t get_scalar(int index);
4445 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4446 inline void set(int index, int32_t value);
4448 // This accessor applies the correct conversion from Smi, HeapNumber
4450 void SetValue(uint32_t index, Object* value);
4452 DECLARE_CAST(ExternalInt32Array)
4454 // Dispatched behavior.
4455 DECLARE_PRINTER(ExternalInt32Array)
4456 DECLARE_VERIFIER(ExternalInt32Array)
4459 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4463 class ExternalUint32Array: public ExternalArray {
4465 // Setter and getter.
4466 inline uint32_t get_scalar(int index);
4467 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4469 inline void set(int index, uint32_t value);
4471 // This accessor applies the correct conversion from Smi, HeapNumber
4473 void SetValue(uint32_t index, Object* value);
4475 DECLARE_CAST(ExternalUint32Array)
4477 // Dispatched behavior.
4478 DECLARE_PRINTER(ExternalUint32Array)
4479 DECLARE_VERIFIER(ExternalUint32Array)
4482 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4486 class ExternalFloat32Array: public ExternalArray {
4488 // Setter and getter.
4489 inline float get_scalar(int index);
4490 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4492 inline void set(int index, float value);
4494 // This accessor applies the correct conversion from Smi, HeapNumber
4496 void SetValue(uint32_t index, Object* value);
4498 DECLARE_CAST(ExternalFloat32Array)
4500 // Dispatched behavior.
4501 DECLARE_PRINTER(ExternalFloat32Array)
4502 DECLARE_VERIFIER(ExternalFloat32Array)
4505 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4509 class ExternalFloat64Array: public ExternalArray {
4511 // Setter and getter.
4512 inline double get_scalar(int index);
4513 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4515 inline void set(int index, double value);
4517 // This accessor applies the correct conversion from Smi, HeapNumber
4519 void SetValue(uint32_t index, Object* value);
4521 DECLARE_CAST(ExternalFloat64Array)
4523 // Dispatched behavior.
4524 DECLARE_PRINTER(ExternalFloat64Array)
4525 DECLARE_VERIFIER(ExternalFloat64Array)
4528 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4532 class FixedTypedArrayBase: public FixedArrayBase {
4534 // [base_pointer]: For now, points to the FixedTypedArrayBase itself.
4535 DECL_ACCESSORS(base_pointer, Object)
4537 // Dispatched behavior.
4538 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4540 template <typename StaticVisitor>
4541 inline void FixedTypedArrayBaseIterateBody();
4543 DECLARE_CAST(FixedTypedArrayBase)
4545 static const int kBasePointerOffset =
4546 FixedArrayBase::kHeaderSize + kPointerSize;
4547 static const int kHeaderSize = kBasePointerOffset + kPointerSize;
4549 static const int kDataOffset = DOUBLE_POINTER_ALIGN(kHeaderSize);
4553 static inline int TypedArraySize(InstanceType type, int length);
4554 inline int TypedArraySize(InstanceType type);
4556 // Use with care: returns raw pointer into heap.
4557 inline void* DataPtr();
4559 inline int DataSize();
4562 static inline int ElementSize(InstanceType type);
4564 inline int DataSize(InstanceType type);
4566 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4570 template <class Traits>
4571 class FixedTypedArray: public FixedTypedArrayBase {
4573 typedef typename Traits::ElementType ElementType;
4574 static const InstanceType kInstanceType = Traits::kInstanceType;
4576 DECLARE_CAST(FixedTypedArray<Traits>)
4578 inline ElementType get_scalar(int index);
4579 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4580 inline void set(int index, ElementType value);
4582 static inline ElementType from_int(int value);
4583 static inline ElementType from_double(double value);
4585 // This accessor applies the correct conversion from Smi, HeapNumber
4587 void SetValue(uint32_t index, Object* value);
4589 DECLARE_PRINTER(FixedTypedArray)
4590 DECLARE_VERIFIER(FixedTypedArray)
4593 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4596 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4597 class Type##ArrayTraits { \
4598 public: /* NOLINT */ \
4599 typedef elementType ElementType; \
4600 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4601 static const char* Designator() { return #type " array"; } \
4602 static inline Handle<Object> ToHandle(Isolate* isolate, \
4603 elementType scalar); \
4604 static inline elementType defaultValue(); \
4607 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4609 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4611 #undef FIXED_TYPED_ARRAY_TRAITS
4614 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4615 // data for code generated by the Hydrogen/Lithium compiler. It also
4616 // contains information about functions that were inlined. If N different
4617 // functions were inlined then first N elements of the literal array will
4618 // contain these functions.
4621 class DeoptimizationInputData: public FixedArray {
4623 // Layout description. Indices in the array.
4624 static const int kTranslationByteArrayIndex = 0;
4625 static const int kInlinedFunctionCountIndex = 1;
4626 static const int kLiteralArrayIndex = 2;
4627 static const int kOsrAstIdIndex = 3;
4628 static const int kOsrPcOffsetIndex = 4;
4629 static const int kOptimizationIdIndex = 5;
4630 static const int kSharedFunctionInfoIndex = 6;
4631 static const int kWeakCellCacheIndex = 7;
4632 static const int kFirstDeoptEntryIndex = 8;
4634 // Offsets of deopt entry elements relative to the start of the entry.
4635 static const int kAstIdRawOffset = 0;
4636 static const int kTranslationIndexOffset = 1;
4637 static const int kArgumentsStackHeightOffset = 2;
4638 static const int kPcOffset = 3;
4639 static const int kDeoptEntrySize = 4;
4641 // Simple element accessors.
4642 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4644 return type::cast(get(k##name##Index)); \
4646 void Set##name(type* value) { \
4647 set(k##name##Index, value); \
4650 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4651 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4652 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4653 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4654 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4655 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4656 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4657 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4659 #undef DEFINE_ELEMENT_ACCESSORS
4661 // Accessors for elements of the ith deoptimization entry.
4662 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4663 type* name(int i) { \
4664 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4666 void Set##name(int i, type* value) { \
4667 set(IndexForEntry(i) + k##name##Offset, value); \
4670 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4671 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4672 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4673 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4675 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4677 BailoutId AstId(int i) {
4678 return BailoutId(AstIdRaw(i)->value());
4681 void SetAstId(int i, BailoutId value) {
4682 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4686 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4689 // Allocates a DeoptimizationInputData.
4690 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4691 int deopt_entry_count,
4692 PretenureFlag pretenure);
4694 DECLARE_CAST(DeoptimizationInputData)
4696 #ifdef ENABLE_DISASSEMBLER
4697 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4701 static int IndexForEntry(int i) {
4702 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4706 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4710 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4711 // data for code generated by the full compiler.
4712 // The format of the these objects is
4713 // [i * 2]: Ast ID for ith deoptimization.
4714 // [i * 2 + 1]: PC and state of ith deoptimization
4715 class DeoptimizationOutputData: public FixedArray {
4717 int DeoptPoints() { return length() / 2; }
4719 BailoutId AstId(int index) {
4720 return BailoutId(Smi::cast(get(index * 2))->value());
4723 void SetAstId(int index, BailoutId id) {
4724 set(index * 2, Smi::FromInt(id.ToInt()));
4727 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4728 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4730 static int LengthOfFixedArray(int deopt_points) {
4731 return deopt_points * 2;
4734 // Allocates a DeoptimizationOutputData.
4735 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4736 int number_of_deopt_points,
4737 PretenureFlag pretenure);
4739 DECLARE_CAST(DeoptimizationOutputData)
4741 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4742 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4747 // HandlerTable is a fixed array containing entries for exception handlers in
4748 // the code object it is associated with. The tables comes in two flavors:
4749 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4750 // exception handler and a range representing the try-block covered by that
4751 // handler. Layout looks as follows:
4752 // [ range-start , range-end , handler-offset , stack-depth ]
4753 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4754 // per call-site that could throw an exception. Layout looks as follows:
4755 // [ return-address-offset , handler-offset ]
4756 class HandlerTable : public FixedArray {
4758 // Conservative prediction whether a given handler will locally catch an
4759 // exception or cause a re-throw to outside the code boundary. Since this is
4760 // undecidable it is merely an approximation (e.g. useful for debugger).
4761 enum CatchPrediction { UNCAUGHT, CAUGHT };
4763 // Accessors for handler table based on ranges.
4764 void SetRangeStart(int index, int value) {
4765 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4767 void SetRangeEnd(int index, int value) {
4768 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4770 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4771 int value = HandlerOffsetField::encode(offset) |
4772 HandlerPredictionField::encode(prediction);
4773 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4775 void SetRangeDepth(int index, int value) {
4776 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4779 // Accessors for handler table based on return addresses.
4780 void SetReturnOffset(int index, int value) {
4781 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4783 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4784 int value = HandlerOffsetField::encode(offset) |
4785 HandlerPredictionField::encode(prediction);
4786 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4789 // Lookup handler in a table based on ranges.
4790 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4792 // Lookup handler in a table based on return addresses.
4793 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4795 // Returns the required length of the underlying fixed array.
4796 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4797 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4799 DECLARE_CAST(HandlerTable)
4801 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4802 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4803 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4807 // Layout description for handler table based on ranges.
4808 static const int kRangeStartIndex = 0;
4809 static const int kRangeEndIndex = 1;
4810 static const int kRangeHandlerIndex = 2;
4811 static const int kRangeDepthIndex = 3;
4812 static const int kRangeEntrySize = 4;
4814 // Layout description for handler table based on return addresses.
4815 static const int kReturnOffsetIndex = 0;
4816 static const int kReturnHandlerIndex = 1;
4817 static const int kReturnEntrySize = 2;
4819 // Encoding of the {handler} field.
4820 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4821 class HandlerOffsetField : public BitField<int, 1, 30> {};
4825 // Code describes objects with on-the-fly generated machine code.
4826 class Code: public HeapObject {
4828 // Opaque data type for encapsulating code flags like kind, inline
4829 // cache state, and arguments count.
4830 typedef uint32_t Flags;
4832 #define NON_IC_KIND_LIST(V) \
4834 V(OPTIMIZED_FUNCTION) \
4840 #define IC_KIND_LIST(V) \
4851 #define CODE_KIND_LIST(V) \
4852 NON_IC_KIND_LIST(V) \
4856 #define DEFINE_CODE_KIND_ENUM(name) name,
4857 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4858 #undef DEFINE_CODE_KIND_ENUM
4862 // No more than 16 kinds. The value is currently encoded in four bits in
4864 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4866 static const char* Kind2String(Kind kind);
4874 static const int kPrologueOffsetNotSet = -1;
4876 #ifdef ENABLE_DISASSEMBLER
4878 static const char* ICState2String(InlineCacheState state);
4879 static const char* StubType2String(StubType type);
4880 static void PrintExtraICState(std::ostream& os, // NOLINT
4881 Kind kind, ExtraICState extra);
4882 void Disassemble(const char* name, std::ostream& os); // NOLINT
4883 #endif // ENABLE_DISASSEMBLER
4885 // [instruction_size]: Size of the native instructions
4886 inline int instruction_size() const;
4887 inline void set_instruction_size(int value);
4889 // [relocation_info]: Code relocation information
4890 DECL_ACCESSORS(relocation_info, ByteArray)
4891 void InvalidateRelocation();
4892 void InvalidateEmbeddedObjects();
4894 // [handler_table]: Fixed array containing offsets of exception handlers.
4895 DECL_ACCESSORS(handler_table, FixedArray)
4897 // [deoptimization_data]: Array containing data for deopt.
4898 DECL_ACCESSORS(deoptimization_data, FixedArray)
4900 // [raw_type_feedback_info]: This field stores various things, depending on
4901 // the kind of the code object.
4902 // FUNCTION => type feedback information.
4903 // STUB and ICs => major/minor key as Smi.
4904 DECL_ACCESSORS(raw_type_feedback_info, Object)
4905 inline Object* type_feedback_info();
4906 inline void set_type_feedback_info(
4907 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4908 inline uint32_t stub_key();
4909 inline void set_stub_key(uint32_t key);
4911 // [next_code_link]: Link for lists of optimized or deoptimized code.
4912 // Note that storage for this field is overlapped with typefeedback_info.
4913 DECL_ACCESSORS(next_code_link, Object)
4915 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4916 // field does not have to be traced during garbage collection since
4917 // it is only used by the garbage collector itself.
4918 DECL_ACCESSORS(gc_metadata, Object)
4920 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4921 // at the moment when this object was created.
4922 inline void set_ic_age(int count);
4923 inline int ic_age() const;
4925 // [prologue_offset]: Offset of the function prologue, used for aging
4926 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4927 inline int prologue_offset() const;
4928 inline void set_prologue_offset(int offset);
4930 // [constant_pool offset]: Offset of the constant pool.
4931 // Valid for FLAG_enable_embedded_constant_pool only
4932 inline int constant_pool_offset() const;
4933 inline void set_constant_pool_offset(int offset);
4935 // Unchecked accessors to be used during GC.
4936 inline ByteArray* unchecked_relocation_info();
4938 inline int relocation_size();
4940 // [flags]: Various code flags.
4941 inline Flags flags();
4942 inline void set_flags(Flags flags);
4944 // [flags]: Access to specific code flags.
4946 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4947 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4949 inline StubType type(); // Only valid for monomorphic IC stubs.
4951 // Testers for IC stub kinds.
4952 inline bool is_inline_cache_stub();
4953 inline bool is_debug_stub();
4954 inline bool is_handler() { return kind() == HANDLER; }
4955 inline bool is_load_stub() { return kind() == LOAD_IC; }
4956 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4957 inline bool is_store_stub() { return kind() == STORE_IC; }
4958 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4959 inline bool is_call_stub() { return kind() == CALL_IC; }
4960 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4961 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4962 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
4963 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4964 inline bool is_keyed_stub();
4965 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
4966 inline bool embeds_maps_weakly() {
4968 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
4969 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
4970 ic_state() == MONOMORPHIC;
4973 inline bool IsCodeStubOrIC();
4975 inline void set_raw_kind_specific_flags1(int value);
4976 inline void set_raw_kind_specific_flags2(int value);
4978 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
4979 // object was generated by either the hydrogen or the TurboFan optimizing
4980 // compiler (but it may not be an optimized function).
4981 inline bool is_crankshafted();
4982 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
4983 inline void set_is_crankshafted(bool value);
4985 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
4986 // code object was generated by the TurboFan optimizing compiler.
4987 inline bool is_turbofanned();
4988 inline void set_is_turbofanned(bool value);
4990 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
4991 // embedded objects in code should be treated weakly.
4992 inline bool can_have_weak_objects();
4993 inline void set_can_have_weak_objects(bool value);
4995 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4996 // deoptimization support.
4997 inline bool has_deoptimization_support();
4998 inline void set_has_deoptimization_support(bool value);
5000 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5001 // been compiled with debug break slots.
5002 inline bool has_debug_break_slots();
5003 inline void set_has_debug_break_slots(bool value);
5005 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5006 // been compiled with IsOptimizing set to true.
5007 inline bool is_compiled_optimizable();
5008 inline void set_compiled_optimizable(bool value);
5010 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
5011 // reloc info includes runtime and external references to support
5012 // serialization/deserialization.
5013 inline bool has_reloc_info_for_serialization();
5014 inline void set_has_reloc_info_for_serialization(bool value);
5016 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5017 // how long the function has been marked for OSR and therefore which
5018 // level of loop nesting we are willing to do on-stack replacement
5020 inline void set_allow_osr_at_loop_nesting_level(int level);
5021 inline int allow_osr_at_loop_nesting_level();
5023 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5024 // the code object was seen on the stack with no IC patching going on.
5025 inline int profiler_ticks();
5026 inline void set_profiler_ticks(int ticks);
5028 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5029 // For builtins, tells which builtin index it has.
5030 // Note that builtins can have a code kind other than BUILTIN, which means
5031 // that for arbitrary code objects, this index value may be random garbage.
5032 // To verify in that case, compare the code object to the indexed builtin.
5033 inline int builtin_index();
5034 inline void set_builtin_index(int id);
5036 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5037 // reserved in the code prologue.
5038 inline unsigned stack_slots();
5039 inline void set_stack_slots(unsigned slots);
5041 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5042 // the instruction stream where the safepoint table starts.
5043 inline unsigned safepoint_table_offset();
5044 inline void set_safepoint_table_offset(unsigned offset);
5046 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5047 // instruction stream where the back edge table starts.
5048 inline unsigned back_edge_table_offset();
5049 inline void set_back_edge_table_offset(unsigned offset);
5051 inline bool back_edges_patched_for_osr();
5053 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5054 inline uint16_t to_boolean_state();
5056 // [has_function_cache]: For kind STUB tells whether there is a function
5057 // cache is passed to the stub.
5058 inline bool has_function_cache();
5059 inline void set_has_function_cache(bool flag);
5062 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5063 // the code is going to be deoptimized because of dead embedded maps.
5064 inline bool marked_for_deoptimization();
5065 inline void set_marked_for_deoptimization(bool flag);
5067 // [constant_pool]: The constant pool for this function.
5068 inline Address constant_pool();
5070 // Get the safepoint entry for the given pc.
5071 SafepointEntry GetSafepointEntry(Address pc);
5073 // Find an object in a stub with a specified map
5074 Object* FindNthObject(int n, Map* match_map);
5076 // Find the first allocation site in an IC stub.
5077 AllocationSite* FindFirstAllocationSite();
5079 // Find the first map in an IC stub.
5080 Map* FindFirstMap();
5081 void FindAllMaps(MapHandleList* maps);
5083 // Find the first handler in an IC stub.
5084 Code* FindFirstHandler();
5086 // Find |length| handlers and put them into |code_list|. Returns false if not
5087 // enough handlers can be found.
5088 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5090 // Find the handler for |map|.
5091 MaybeHandle<Code> FindHandlerForMap(Map* map);
5093 // Find the first name in an IC stub.
5094 Name* FindFirstName();
5096 class FindAndReplacePattern;
5097 // For each (map-to-find, object-to-replace) pair in the pattern, this
5098 // function replaces the corresponding placeholder in the code with the
5099 // object-to-replace. The function assumes that pairs in the pattern come in
5100 // the same order as the placeholders in the code.
5101 // If the placeholder is a weak cell, then the value of weak cell is matched
5102 // against the map-to-find.
5103 void FindAndReplace(const FindAndReplacePattern& pattern);
5105 // The entire code object including its header is copied verbatim to the
5106 // snapshot so that it can be written in one, fast, memcpy during
5107 // deserialization. The deserializer will overwrite some pointers, rather
5108 // like a runtime linker, but the random allocation addresses used in the
5109 // mksnapshot process would still be present in the unlinked snapshot data,
5110 // which would make snapshot production non-reproducible. This method wipes
5111 // out the to-be-overwritten header data for reproducible snapshots.
5112 inline void WipeOutHeader();
5114 // Flags operations.
5115 static inline Flags ComputeFlags(
5116 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5117 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5118 CacheHolderFlag holder = kCacheOnReceiver);
5120 static inline Flags ComputeMonomorphicFlags(
5121 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5122 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5124 static inline Flags ComputeHandlerFlags(
5125 Kind handler_kind, StubType type = NORMAL,
5126 CacheHolderFlag holder = kCacheOnReceiver);
5128 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5129 static inline StubType ExtractTypeFromFlags(Flags flags);
5130 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5131 static inline Kind ExtractKindFromFlags(Flags flags);
5132 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5134 static inline Flags RemoveTypeFromFlags(Flags flags);
5135 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5137 // Convert a target address into a code object.
5138 static inline Code* GetCodeFromTargetAddress(Address address);
5140 // Convert an entry address into an object.
5141 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5143 // Returns the address of the first instruction.
5144 inline byte* instruction_start();
5146 // Returns the address right after the last instruction.
5147 inline byte* instruction_end();
5149 // Returns the size of the instructions, padding, and relocation information.
5150 inline int body_size();
5152 // Returns the address of the first relocation info (read backwards!).
5153 inline byte* relocation_start();
5155 // Code entry point.
5156 inline byte* entry();
5158 // Returns true if pc is inside this object's instructions.
5159 inline bool contains(byte* pc);
5161 // Relocate the code by delta bytes. Called to signal that this code
5162 // object has been moved by delta bytes.
5163 void Relocate(intptr_t delta);
5165 // Migrate code described by desc.
5166 void CopyFrom(const CodeDesc& desc);
5168 // Returns the object size for a given body (used for allocation).
5169 static int SizeFor(int body_size) {
5170 DCHECK_SIZE_TAG_ALIGNED(body_size);
5171 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5174 // Calculate the size of the code object to report for log events. This takes
5175 // the layout of the code object into account.
5176 int ExecutableSize() {
5177 // Check that the assumptions about the layout of the code object holds.
5178 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5180 return instruction_size() + Code::kHeaderSize;
5183 // Locating source position.
5184 int SourcePosition(Address pc);
5185 int SourceStatementPosition(Address pc);
5189 // Dispatched behavior.
5190 int CodeSize() { return SizeFor(body_size()); }
5191 inline void CodeIterateBody(ObjectVisitor* v);
5193 template<typename StaticVisitor>
5194 inline void CodeIterateBody(Heap* heap);
5196 DECLARE_PRINTER(Code)
5197 DECLARE_VERIFIER(Code)
5199 void ClearInlineCaches();
5200 void ClearInlineCaches(Kind kind);
5202 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5203 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5205 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5207 kToBeExecutedOnceCodeAge = -3,
5208 kNotExecutedCodeAge = -2,
5209 kExecutedOnceCodeAge = -1,
5211 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5213 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5214 kLastCodeAge = kAfterLastCodeAge - 1,
5215 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5216 kIsOldCodeAge = kSexagenarianCodeAge,
5217 kPreAgedCodeAge = kIsOldCodeAge - 1
5219 #undef DECLARE_CODE_AGE_ENUM
5221 // Code aging. Indicates how many full GCs this code has survived without
5222 // being entered through the prologue. Used to determine when it is
5223 // relatively safe to flush this code object and replace it with the lazy
5224 // compilation stub.
5225 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5226 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5227 void MakeYoung(Isolate* isolate);
5228 void MarkToBeExecutedOnce(Isolate* isolate);
5229 void MakeOlder(MarkingParity);
5230 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5233 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5234 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5237 void PrintDeoptLocation(FILE* out, Address pc);
5238 bool CanDeoptAt(Address pc);
5241 void VerifyEmbeddedObjectsDependency();
5245 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5246 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5249 inline bool CanContainWeakObjects() {
5250 // is_turbofanned() implies !can_have_weak_objects().
5251 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5252 !can_have_weak_objects());
5253 return is_optimized_code() && can_have_weak_objects();
5256 inline bool IsWeakObject(Object* object) {
5257 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5260 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5262 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5263 WeakCell* CachedWeakCell();
5265 // Max loop nesting marker used to postpose OSR. We don't take loop
5266 // nesting that is deeper than 5 levels into account.
5267 static const int kMaxLoopNestingMarker = 6;
5269 static const int kConstantPoolSize =
5270 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5272 // Layout description.
5273 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5274 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5275 static const int kDeoptimizationDataOffset =
5276 kHandlerTableOffset + kPointerSize;
5277 // For FUNCTION kind, we store the type feedback info here.
5278 static const int kTypeFeedbackInfoOffset =
5279 kDeoptimizationDataOffset + kPointerSize;
5280 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5281 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5282 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5283 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5284 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5285 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5286 static const int kKindSpecificFlags2Offset =
5287 kKindSpecificFlags1Offset + kIntSize;
5288 // Note: We might be able to squeeze this into the flags above.
5289 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5290 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5291 static const int kHeaderPaddingStart =
5292 kConstantPoolOffset + kConstantPoolSize;
5294 // Add padding to align the instruction start following right after
5295 // the Code object header.
5296 static const int kHeaderSize =
5297 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5299 // Byte offsets within kKindSpecificFlags1Offset.
5300 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5301 class FullCodeFlagsHasDeoptimizationSupportField:
5302 public BitField<bool, 0, 1> {}; // NOLINT
5303 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5304 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5305 class FullCodeFlagsHasRelocInfoForSerialization
5306 : public BitField<bool, 3, 1> {};
5307 class ProfilerTicksField : public BitField<int, 4, 28> {};
5309 // Flags layout. BitField<type, shift, size>.
5310 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5311 class TypeField : public BitField<StubType, 4, 1> {};
5312 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5313 class KindField : public BitField<Kind, 7, 4> {};
5314 class ExtraICStateField: public BitField<ExtraICState, 11,
5315 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5317 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5318 static const int kStackSlotsFirstBit = 0;
5319 static const int kStackSlotsBitCount = 24;
5320 static const int kHasFunctionCacheBit =
5321 kStackSlotsFirstBit + kStackSlotsBitCount;
5322 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5323 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5324 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5326 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5327 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5329 class StackSlotsField: public BitField<int,
5330 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5331 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5333 class MarkedForDeoptimizationField
5334 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5335 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5337 class CanHaveWeakObjectsField
5338 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5340 // KindSpecificFlags2 layout (ALL)
5341 static const int kIsCrankshaftedBit = 0;
5342 class IsCrankshaftedField: public BitField<bool,
5343 kIsCrankshaftedBit, 1> {}; // NOLINT
5345 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5346 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5347 static const int kSafepointTableOffsetBitCount = 24;
5349 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5350 kSafepointTableOffsetBitCount <= 32);
5351 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5353 class SafepointTableOffsetField: public BitField<int,
5354 kSafepointTableOffsetFirstBit,
5355 kSafepointTableOffsetBitCount> {}; // NOLINT
5357 // KindSpecificFlags2 layout (FUNCTION)
5358 class BackEdgeTableOffsetField: public BitField<int,
5359 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5360 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5361 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5362 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5364 static const int kArgumentsBits = 16;
5365 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5367 // This constant should be encodable in an ARM instruction.
5368 static const int kFlagsNotUsedInLookup =
5369 TypeField::kMask | CacheHolderField::kMask;
5372 friend class RelocIterator;
5373 friend class Deoptimizer; // For FindCodeAgeSequence.
5375 void ClearInlineCaches(Kind* kind);
5378 byte* FindCodeAgeSequence();
5379 static void GetCodeAgeAndParity(Code* code, Age* age,
5380 MarkingParity* parity);
5381 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5382 MarkingParity* parity);
5383 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5385 // Code aging -- platform-specific
5386 static void PatchPlatformCodeAge(Isolate* isolate,
5387 byte* sequence, Age age,
5388 MarkingParity parity);
5390 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5394 // This class describes the layout of dependent codes array of a map. The
5395 // array is partitioned into several groups of dependent codes. Each group
5396 // contains codes with the same dependency on the map. The array has the
5397 // following layout for n dependency groups:
5399 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5400 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5401 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5403 // The first n elements are Smis, each of them specifies the number of codes
5404 // in the corresponding group. The subsequent elements contain grouped code
5405 // objects in weak cells. The suffix of the array can be filled with the
5406 // undefined value if the number of codes is less than the length of the
5407 // array. The order of the code objects within a group is not preserved.
5409 // All code indexes used in the class are counted starting from the first
5410 // code object of the first group. In other words, code index 0 corresponds
5411 // to array index n = kCodesStartIndex.
5413 class DependentCode: public FixedArray {
5415 enum DependencyGroup {
5416 // Group of code that weakly embed this map and depend on being
5417 // deoptimized when the map is garbage collected.
5419 // Group of code that embed a transition to this map, and depend on being
5420 // deoptimized when the transition is replaced by a new version.
5422 // Group of code that omit run-time prototype checks for prototypes
5423 // described by this map. The group is deoptimized whenever an object
5424 // described by this map changes shape (and transitions to a new map),
5425 // possibly invalidating the assumptions embedded in the code.
5426 kPrototypeCheckGroup,
5427 // Group of code that depends on global property values in property cells
5428 // not being changed.
5429 kPropertyCellChangedGroup,
5430 // Group of code that omit run-time type checks for the field(s) introduced
5433 // Group of code that omit run-time type checks for initial maps of
5435 kInitialMapChangedGroup,
5436 // Group of code that depends on tenuring information in AllocationSites
5437 // not being changed.
5438 kAllocationSiteTenuringChangedGroup,
5439 // Group of code that depends on element transition information in
5440 // AllocationSites not being changed.
5441 kAllocationSiteTransitionChangedGroup
5444 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5446 // Array for holding the index of the first code object of each group.
5447 // The last element stores the total number of code objects.
5448 class GroupStartIndexes {
5450 explicit GroupStartIndexes(DependentCode* entries);
5451 void Recompute(DependentCode* entries);
5452 int at(int i) { return start_indexes_[i]; }
5453 int number_of_entries() { return start_indexes_[kGroupCount]; }
5455 int start_indexes_[kGroupCount + 1];
5458 bool Contains(DependencyGroup group, WeakCell* code_cell);
5460 static Handle<DependentCode> InsertCompilationDependencies(
5461 Handle<DependentCode> entries, DependencyGroup group,
5462 Handle<Foreign> info);
5464 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5465 DependencyGroup group,
5466 Handle<WeakCell> code_cell);
5468 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5469 WeakCell* code_cell);
5471 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5474 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5475 DependentCode::DependencyGroup group);
5477 bool MarkCodeForDeoptimization(Isolate* isolate,
5478 DependentCode::DependencyGroup group);
5480 // The following low-level accessors should only be used by this class
5481 // and the mark compact collector.
5482 inline int number_of_entries(DependencyGroup group);
5483 inline void set_number_of_entries(DependencyGroup group, int value);
5484 inline Object* object_at(int i);
5485 inline void set_object_at(int i, Object* object);
5486 inline void clear_at(int i);
5487 inline void copy(int from, int to);
5488 DECLARE_CAST(DependentCode)
5490 static const char* DependencyGroupName(DependencyGroup group);
5491 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5494 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5495 DependencyGroup group,
5496 Handle<Object> object);
5497 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5498 // Make a room at the end of the given group by moving out the first
5499 // code objects of the subsequent groups.
5500 inline void ExtendGroup(DependencyGroup group);
5501 // Compact by removing cleared weak cells and return true if there was
5502 // any cleared weak cell.
5504 static int Grow(int number_of_entries) {
5505 if (number_of_entries < 5) return number_of_entries + 1;
5506 return number_of_entries * 5 / 4;
5508 static const int kCodesStartIndex = kGroupCount;
5512 class PrototypeInfo;
5515 // All heap objects have a Map that describes their structure.
5516 // A Map contains information about:
5517 // - Size information about the object
5518 // - How to iterate over an object (for garbage collection)
5519 class Map: public HeapObject {
5522 // Size in bytes or kVariableSizeSentinel if instances do not have
5524 inline int instance_size();
5525 inline void set_instance_size(int value);
5527 // Only to clear an unused byte, remove once byte is used.
5528 inline void clear_unused();
5530 // Count of properties allocated in the object.
5531 inline int inobject_properties();
5532 inline void set_inobject_properties(int value);
5535 inline InstanceType instance_type();
5536 inline void set_instance_type(InstanceType value);
5538 // Tells how many unused property fields are available in the
5539 // instance (only used for JSObject in fast mode).
5540 inline int unused_property_fields();
5541 inline void set_unused_property_fields(int value);
5544 inline byte bit_field() const;
5545 inline void set_bit_field(byte value);
5548 inline byte bit_field2() const;
5549 inline void set_bit_field2(byte value);
5552 inline uint32_t bit_field3() const;
5553 inline void set_bit_field3(uint32_t bits);
5555 class EnumLengthBits: public BitField<int,
5556 0, kDescriptorIndexBitCount> {}; // NOLINT
5557 class NumberOfOwnDescriptorsBits: public BitField<int,
5558 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5559 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5560 class DictionaryMap : public BitField<bool, 20, 1> {};
5561 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5562 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5563 class Deprecated : public BitField<bool, 23, 1> {};
5564 class IsUnstable : public BitField<bool, 24, 1> {};
5565 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5566 class IsStrong : public BitField<bool, 26, 1> {};
5569 // Keep this bit field at the very end for better code in
5570 // Builtins::kJSConstructStubGeneric stub.
5571 // This counter is used for in-object slack tracking and for map aging.
5572 // The in-object slack tracking is considered enabled when the counter is
5573 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5574 class Counter : public BitField<int, 28, 4> {};
5575 static const int kSlackTrackingCounterStart = 14;
5576 static const int kSlackTrackingCounterEnd = 8;
5577 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5578 static const int kRetainingCounterEnd = 0;
5580 // Tells whether the object in the prototype property will be used
5581 // for instances created from this function. If the prototype
5582 // property is set to a value that is not a JSObject, the prototype
5583 // property will not be used to create instances of the function.
5584 // See ECMA-262, 13.2.2.
5585 inline void set_non_instance_prototype(bool value);
5586 inline bool has_non_instance_prototype();
5588 // Tells whether function has special prototype property. If not, prototype
5589 // property will not be created when accessed (will return undefined),
5590 // and construction from this function will not be allowed.
5591 inline void set_function_with_prototype(bool value);
5592 inline bool function_with_prototype();
5594 // Tells whether the instance with this map should be ignored by the
5595 // Object.getPrototypeOf() function and the __proto__ accessor.
5596 inline void set_is_hidden_prototype() {
5597 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5600 inline bool is_hidden_prototype() {
5601 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5604 // Records and queries whether the instance has a named interceptor.
5605 inline void set_has_named_interceptor() {
5606 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5609 inline bool has_named_interceptor() {
5610 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5613 // Records and queries whether the instance has an indexed interceptor.
5614 inline void set_has_indexed_interceptor() {
5615 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5618 inline bool has_indexed_interceptor() {
5619 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5622 // Tells whether the instance is undetectable.
5623 // An undetectable object is a special class of JSObject: 'typeof' operator
5624 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5625 // a normal JS object. It is useful for implementing undetectable
5626 // document.all in Firefox & Safari.
5627 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5628 inline void set_is_undetectable() {
5629 set_bit_field(bit_field() | (1 << kIsUndetectable));
5632 inline bool is_undetectable() {
5633 return ((1 << kIsUndetectable) & bit_field()) != 0;
5636 // Tells whether the instance has a call-as-function handler.
5637 inline void set_is_observed() {
5638 set_bit_field(bit_field() | (1 << kIsObserved));
5641 inline bool is_observed() {
5642 return ((1 << kIsObserved) & bit_field()) != 0;
5645 inline void set_is_strong();
5646 inline bool is_strong();
5647 inline void set_is_extensible(bool value);
5648 inline bool is_extensible();
5649 inline void set_is_prototype_map(bool value);
5650 inline bool is_prototype_map() const;
5652 inline void set_elements_kind(ElementsKind elements_kind) {
5653 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5654 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5655 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5656 DCHECK(this->elements_kind() == elements_kind);
5659 inline ElementsKind elements_kind() {
5660 return Map::ElementsKindBits::decode(bit_field2());
5663 // Tells whether the instance has fast elements that are only Smis.
5664 inline bool has_fast_smi_elements() {
5665 return IsFastSmiElementsKind(elements_kind());
5668 // Tells whether the instance has fast elements.
5669 inline bool has_fast_object_elements() {
5670 return IsFastObjectElementsKind(elements_kind());
5673 inline bool has_fast_smi_or_object_elements() {
5674 return IsFastSmiOrObjectElementsKind(elements_kind());
5677 inline bool has_fast_double_elements() {
5678 return IsFastDoubleElementsKind(elements_kind());
5681 inline bool has_fast_elements() {
5682 return IsFastElementsKind(elements_kind());
5685 inline bool has_sloppy_arguments_elements() {
5686 return IsSloppyArgumentsElements(elements_kind());
5689 inline bool has_external_array_elements() {
5690 return IsExternalArrayElementsKind(elements_kind());
5693 inline bool has_fixed_typed_array_elements() {
5694 return IsFixedTypedArrayElementsKind(elements_kind());
5697 inline bool has_dictionary_elements() {
5698 return IsDictionaryElementsKind(elements_kind());
5701 static bool IsValidElementsTransition(ElementsKind from_kind,
5702 ElementsKind to_kind);
5704 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5705 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5706 bool DictionaryElementsInPrototypeChainOnly();
5708 inline Map* ElementsTransitionMap();
5710 inline FixedArrayBase* GetInitialElements();
5712 // [raw_transitions]: Provides access to the transitions storage field.
5713 // Don't call set_raw_transitions() directly to overwrite transitions, use
5714 // the TransitionArray::ReplaceTransitions() wrapper instead!
5715 DECL_ACCESSORS(raw_transitions, Object)
5716 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5717 // (which prototype maps don't have).
5718 DECL_ACCESSORS(prototype_info, Object)
5719 // PrototypeInfo is created lazily using this helper (which installs it on
5720 // the given prototype's map).
5721 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5722 Handle<JSObject> prototype, Isolate* isolate);
5724 // [prototype chain validity cell]: Associated with a prototype object,
5725 // stored in that object's map's PrototypeInfo, indicates that prototype
5726 // chains through this object are currently valid. The cell will be
5727 // invalidated and replaced when the prototype chain changes.
5728 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5730 static const int kPrototypeChainValid = 0;
5731 static const int kPrototypeChainInvalid = 1;
5734 Map* FindFieldOwner(int descriptor);
5736 inline int GetInObjectPropertyOffset(int index);
5738 int NumberOfFields();
5740 // TODO(ishell): candidate with JSObject::MigrateToMap().
5741 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5742 int target_inobject, int target_unused,
5743 int* old_number_of_fields);
5744 // TODO(ishell): moveit!
5745 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5746 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5747 Handle<HeapType> type1,
5748 Handle<HeapType> type2,
5750 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5751 Representation new_representation,
5752 Handle<HeapType> new_field_type);
5753 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5754 PropertyKind new_kind,
5755 PropertyAttributes new_attributes,
5756 Representation new_representation,
5757 Handle<HeapType> new_field_type,
5758 StoreMode store_mode);
5759 static Handle<Map> CopyGeneralizeAllRepresentations(
5760 Handle<Map> map, int modify_index, StoreMode store_mode,
5761 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5763 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5764 int descriptor_number,
5765 Handle<Object> value);
5766 static Handle<Map> PrepareForDataElement(Handle<Map> old_map,
5767 Handle<Object> value);
5769 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5770 const char* reason);
5772 // Returns the constructor name (the name (possibly, inferred name) of the
5773 // function that was used to instantiate the object).
5774 String* constructor_name();
5776 // Tells whether the map is used for JSObjects in dictionary mode (ie
5777 // normalized objects, ie objects for which HasFastProperties returns false).
5778 // A map can never be used for both dictionary mode and fast mode JSObjects.
5779 // False by default and for HeapObjects that are not JSObjects.
5780 inline void set_dictionary_map(bool value);
5781 inline bool is_dictionary_map();
5783 // Tells whether the instance needs security checks when accessing its
5785 inline void set_is_access_check_needed(bool access_check_needed);
5786 inline bool is_access_check_needed();
5788 // Returns true if map has a non-empty stub code cache.
5789 inline bool has_code_cache();
5791 // [prototype]: implicit prototype object.
5792 DECL_ACCESSORS(prototype, Object)
5793 // TODO(jkummerow): make set_prototype private.
5794 static void SetPrototype(
5795 Handle<Map> map, Handle<Object> prototype,
5796 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5798 // [constructor]: points back to the function responsible for this map.
5799 // The field overlaps with the back pointer. All maps in a transition tree
5800 // have the same constructor, so maps with back pointers can walk the
5801 // back pointer chain until they find the map holding their constructor.
5802 DECL_ACCESSORS(constructor_or_backpointer, Object)
5803 inline Object* GetConstructor() const;
5804 inline void SetConstructor(Object* constructor,
5805 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5806 // [back pointer]: points back to the parent map from which a transition
5807 // leads to this map. The field overlaps with the constructor (see above).
5808 inline Object* GetBackPointer();
5809 inline void SetBackPointer(Object* value,
5810 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5812 // [instance descriptors]: describes the object.
5813 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5815 // [layout descriptor]: describes the object layout.
5816 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5817 // |layout descriptor| accessor which can be used from GC.
5818 inline LayoutDescriptor* layout_descriptor_gc_safe();
5819 inline bool HasFastPointerLayout() const;
5821 // |layout descriptor| accessor that is safe to call even when
5822 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5823 // |layout_descriptor| field at all).
5824 inline LayoutDescriptor* GetLayoutDescriptor();
5826 inline void UpdateDescriptors(DescriptorArray* descriptors,
5827 LayoutDescriptor* layout_descriptor);
5828 inline void InitializeDescriptors(DescriptorArray* descriptors,
5829 LayoutDescriptor* layout_descriptor);
5831 // [stub cache]: contains stubs compiled for this map.
5832 DECL_ACCESSORS(code_cache, Object)
5834 // [dependent code]: list of optimized codes that weakly embed this map.
5835 DECL_ACCESSORS(dependent_code, DependentCode)
5837 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5838 DECL_ACCESSORS(weak_cell_cache, Object)
5840 inline PropertyDetails GetLastDescriptorDetails();
5843 int number_of_own_descriptors = NumberOfOwnDescriptors();
5844 DCHECK(number_of_own_descriptors > 0);
5845 return number_of_own_descriptors - 1;
5848 int NumberOfOwnDescriptors() {
5849 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5852 void SetNumberOfOwnDescriptors(int number) {
5853 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5854 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5857 inline Cell* RetrieveDescriptorsPointer();
5860 return EnumLengthBits::decode(bit_field3());
5863 void SetEnumLength(int length) {
5864 if (length != kInvalidEnumCacheSentinel) {
5865 DCHECK(length >= 0);
5866 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5867 DCHECK(length <= NumberOfOwnDescriptors());
5869 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5872 inline bool owns_descriptors();
5873 inline void set_owns_descriptors(bool owns_descriptors);
5874 inline bool has_instance_call_handler();
5875 inline void set_has_instance_call_handler();
5876 inline void mark_unstable();
5877 inline bool is_stable();
5878 inline void set_migration_target(bool value);
5879 inline bool is_migration_target();
5880 inline void set_counter(int value);
5881 inline int counter();
5882 inline void deprecate();
5883 inline bool is_deprecated();
5884 inline bool CanBeDeprecated();
5885 // Returns a non-deprecated version of the input. If the input was not
5886 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5887 // is found by re-transitioning from the root of the transition tree using the
5888 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5890 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5892 // Returns a non-deprecated version of the input. This method may deprecate
5893 // existing maps along the way if encodings conflict. Not for use while
5894 // gathering type feedback. Use TryUpdate in those cases instead.
5895 static Handle<Map> Update(Handle<Map> map);
5897 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5898 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5899 Descriptor* descriptor,
5900 TransitionFlag flag);
5902 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5905 Handle<HeapType> type,
5906 PropertyAttributes attributes,
5907 Representation representation,
5908 TransitionFlag flag);
5910 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5913 Handle<Object> constant,
5914 PropertyAttributes attributes,
5915 TransitionFlag flag);
5917 // Returns a new map with all transitions dropped from the given map and
5918 // the ElementsKind set.
5919 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5920 ElementsKind to_kind);
5922 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5924 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5926 TransitionFlag flag);
5928 static Handle<Map> CopyForObserved(Handle<Map> map);
5930 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5931 PropertyAttributes attrs_to_add,
5932 Handle<Symbol> transition_marker,
5933 const char* reason);
5935 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5938 // Maximal number of fast properties. Used to restrict the number of map
5939 // transitions to avoid an explosion in the number of maps for objects used as
5941 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5942 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5944 Handle<Object> value,
5945 PropertyAttributes attributes,
5946 StoreFromKeyed store_mode);
5947 static Handle<Map> TransitionToAccessorProperty(
5948 Handle<Map> map, Handle<Name> name, AccessorComponent component,
5949 Handle<Object> accessor, PropertyAttributes attributes);
5950 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
5953 PropertyAttributes attributes);
5955 inline void AppendDescriptor(Descriptor* desc);
5957 // Returns a copy of the map, prepared for inserting into the transition
5958 // tree (if the |map| owns descriptors then the new one will share
5959 // descriptors with |map|).
5960 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
5962 // Returns a copy of the map, with all transitions dropped from the
5963 // instance descriptors.
5964 static Handle<Map> Copy(Handle<Map> map, const char* reason);
5965 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
5967 // Returns the next free property index (only valid for FAST MODE).
5968 int NextFreePropertyIndex();
5970 // Returns the number of properties described in instance_descriptors
5971 // filtering out properties with the specified attributes.
5972 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
5973 PropertyAttributes filter = NONE);
5977 // Code cache operations.
5979 // Clears the code cache.
5980 inline void ClearCodeCache(Heap* heap);
5982 // Update code cache.
5983 static void UpdateCodeCache(Handle<Map> map,
5987 // Extend the descriptor array of the map with the list of descriptors.
5988 // In case of duplicates, the latest descriptor is used.
5989 static void AppendCallbackDescriptors(Handle<Map> map,
5990 Handle<Object> descriptors);
5992 static inline int SlackForArraySize(int old_size, int size_limit);
5994 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
5996 // Returns the found code or undefined if absent.
5997 Object* FindInCodeCache(Name* name, Code::Flags flags);
5999 // Returns the non-negative index of the code object if it is in the
6000 // cache and -1 otherwise.
6001 int IndexInCodeCache(Object* name, Code* code);
6003 // Removes a code object from the code cache at the given index.
6004 void RemoveFromCodeCache(Name* name, Code* code, int index);
6006 // Computes a hash value for this map, to be used in HashTables and such.
6009 // Returns the map that this map transitions to if its elements_kind
6010 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6011 // |safe_to_add_transitions| is set to false if adding transitions is not
6013 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6015 // Returns the transitioned map for this map with the most generic
6016 // elements_kind that's found in |candidates|, or null handle if no match is
6018 static Handle<Map> FindTransitionedMap(Handle<Map> map,
6019 MapHandleList* candidates);
6021 bool CanTransition() {
6022 // Only JSObject and subtypes have map transitions and back pointers.
6023 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6024 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6027 bool IsJSObjectMap() {
6028 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6030 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6031 bool IsJSProxyMap() {
6032 InstanceType type = instance_type();
6033 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6035 bool IsJSGlobalProxyMap() {
6036 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6038 bool IsJSGlobalObjectMap() {
6039 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6041 bool IsGlobalObjectMap() {
6042 const InstanceType type = instance_type();
6043 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6046 inline bool CanOmitMapChecks();
6048 static void AddDependentCode(Handle<Map> map,
6049 DependentCode::DependencyGroup group,
6052 bool IsMapInArrayPrototypeChain();
6054 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
6056 // Dispatched behavior.
6057 DECLARE_PRINTER(Map)
6058 DECLARE_VERIFIER(Map)
6061 void DictionaryMapVerify();
6062 void VerifyOmittedMapChecks();
6065 inline int visitor_id();
6066 inline void set_visitor_id(int visitor_id);
6068 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6069 Handle<Object> prototype,
6070 PrototypeOptimizationMode mode);
6072 static const int kMaxPreAllocatedPropertyFields = 255;
6074 // Layout description.
6075 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6076 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6077 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6078 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6079 static const int kConstructorOrBackPointerOffset =
6080 kPrototypeOffset + kPointerSize;
6081 // When there is only one transition, it is stored directly in this field;
6082 // otherwise a transition array is used.
6083 // For prototype maps, this slot is used to store this map's PrototypeInfo
6085 static const int kTransitionsOrPrototypeInfoOffset =
6086 kConstructorOrBackPointerOffset + kPointerSize;
6087 static const int kDescriptorsOffset =
6088 kTransitionsOrPrototypeInfoOffset + kPointerSize;
6089 #if V8_DOUBLE_FIELDS_UNBOXING
6090 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
6091 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
6093 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
6094 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6096 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6097 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
6098 static const int kSize = kWeakCellCacheOffset + kPointerSize;
6100 // Layout of pointer fields. Heap iteration code relies on them
6101 // being continuously allocated.
6102 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6103 static const int kPointerFieldsEndOffset = kSize;
6105 // Byte offsets within kInstanceSizesOffset.
6106 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6107 static const int kInObjectPropertiesByte = 1;
6108 static const int kInObjectPropertiesOffset =
6109 kInstanceSizesOffset + kInObjectPropertiesByte;
6110 // Note there is one byte available for use here.
6111 static const int kUnusedByte = 2;
6112 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
6113 static const int kVisitorIdByte = 3;
6114 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6116 // Byte offsets within kInstanceAttributesOffset attributes.
6117 #if V8_TARGET_LITTLE_ENDIAN
6118 // Order instance type and bit field together such that they can be loaded
6119 // together as a 16-bit word with instance type in the lower 8 bits regardless
6120 // of endianess. Also provide endian-independent offset to that 16-bit word.
6121 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6122 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6124 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6125 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6127 static const int kInstanceTypeAndBitFieldOffset =
6128 kInstanceAttributesOffset + 0;
6129 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6130 static const int kUnusedPropertyFieldsByte = 3;
6131 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6133 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6134 Internals::kMapInstanceTypeAndBitFieldOffset);
6136 // Bit positions for bit field.
6137 static const int kHasNonInstancePrototype = 0;
6138 static const int kIsHiddenPrototype = 1;
6139 static const int kHasNamedInterceptor = 2;
6140 static const int kHasIndexedInterceptor = 3;
6141 static const int kIsUndetectable = 4;
6142 static const int kIsObserved = 5;
6143 static const int kIsAccessCheckNeeded = 6;
6144 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6146 // Bit positions for bit field 2
6147 static const int kIsExtensible = 0;
6148 static const int kStringWrapperSafeForDefaultValueOf = 1;
6149 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6150 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6152 // Derived values from bit field 2
6153 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6154 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6155 static const int8_t kMaximumBitField2FastSmiElementValue =
6156 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6157 Map::ElementsKindBits::kShift) - 1;
6158 static const int8_t kMaximumBitField2FastHoleyElementValue =
6159 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6160 Map::ElementsKindBits::kShift) - 1;
6161 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6162 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6163 Map::ElementsKindBits::kShift) - 1;
6165 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6166 kPointerFieldsEndOffset,
6167 kSize> BodyDescriptor;
6169 // Compares this map to another to see if they describe equivalent objects.
6170 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6171 // it had exactly zero inobject properties.
6172 // The "shared" flags of both this map and |other| are ignored.
6173 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6175 // Returns true if given field is unboxed double.
6176 inline bool IsUnboxedDoubleField(FieldIndex index);
6179 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
6180 static void TraceAllTransitions(Map* map);
6183 static inline Handle<Map> CopyInstallDescriptorsForTesting(
6184 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6185 Handle<LayoutDescriptor> layout_descriptor);
6188 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6189 Handle<Name> name, SimpleTransitionFlag flag);
6191 bool EquivalentToForTransition(Map* other);
6192 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6193 static Handle<Map> ShareDescriptor(Handle<Map> map,
6194 Handle<DescriptorArray> descriptors,
6195 Descriptor* descriptor);
6196 static Handle<Map> CopyInstallDescriptors(
6197 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6198 Handle<LayoutDescriptor> layout_descriptor);
6199 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6200 Descriptor* descriptor,
6201 TransitionFlag flag);
6202 static Handle<Map> CopyReplaceDescriptors(
6203 Handle<Map> map, Handle<DescriptorArray> descriptors,
6204 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
6205 MaybeHandle<Name> maybe_name, const char* reason,
6206 SimpleTransitionFlag simple_flag);
6208 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6209 Handle<DescriptorArray> descriptors,
6210 Descriptor* descriptor,
6212 TransitionFlag flag);
6213 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
6214 Handle<Map> map, int descriptor, PropertyKind kind,
6215 PropertyAttributes attributes, const char** reason);
6217 static Handle<Map> CopyNormalized(Handle<Map> map,
6218 PropertyNormalizationMode mode);
6220 // Fires when the layout of an object with a leaf map changes.
6221 // This includes adding transitions to the leaf map or changing
6222 // the descriptor array.
6223 inline void NotifyLeafMapLayoutChange();
6225 void DeprecateTransitionTree();
6226 bool DeprecateTarget(PropertyKind kind, Name* key,
6227 PropertyAttributes attributes,
6228 DescriptorArray* new_descriptors,
6229 LayoutDescriptor* new_layout_descriptor);
6231 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6233 // Update field type of the given descriptor to new representation and new
6234 // type. The type must be prepared for storing in descriptor array:
6235 // it must be either a simple type or a map wrapped in a weak cell.
6236 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6237 Representation new_representation,
6238 Handle<Object> new_wrapped_type);
6240 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6241 PropertyAttributes attributes);
6242 void PrintGeneralization(FILE* file,
6247 bool constant_to_field,
6248 Representation old_representation,
6249 Representation new_representation,
6250 HeapType* old_field_type,
6251 HeapType* new_field_type);
6253 static const int kFastPropertiesSoftLimit = 12;
6254 static const int kMaxFastProperties = 128;
6256 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6260 // An abstract superclass, a marker class really, for simple structure classes.
6261 // It doesn't carry much functionality but allows struct classes to be
6262 // identified in the type system.
6263 class Struct: public HeapObject {
6265 inline void InitializeBody(int object_size);
6266 DECLARE_CAST(Struct)
6270 // A simple one-element struct, useful where smis need to be boxed.
6271 class Box : public Struct {
6273 // [value]: the boxed contents.
6274 DECL_ACCESSORS(value, Object)
6278 // Dispatched behavior.
6279 DECLARE_PRINTER(Box)
6280 DECLARE_VERIFIER(Box)
6282 static const int kValueOffset = HeapObject::kHeaderSize;
6283 static const int kSize = kValueOffset + kPointerSize;
6286 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6290 // Container for metadata stored on each prototype map.
6291 class PrototypeInfo : public Struct {
6293 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6294 // or Smi(0) if uninitialized.
6295 DECL_ACCESSORS(prototype_users, Object)
6296 // [validity_cell]: Cell containing the validity bit for prototype chains
6297 // going through this object, or Smi(0) if uninitialized.
6298 DECL_ACCESSORS(validity_cell, Object)
6299 // [constructor_name]: User-friendly name of the original constructor.
6300 DECL_ACCESSORS(constructor_name, Object)
6302 DECLARE_CAST(PrototypeInfo)
6304 // Dispatched behavior.
6305 DECLARE_PRINTER(PrototypeInfo)
6306 DECLARE_VERIFIER(PrototypeInfo)
6308 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6309 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6310 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6311 static const int kSize = kConstructorNameOffset + kPointerSize;
6314 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6318 // Script describes a script which has been added to the VM.
6319 class Script: public Struct {
6328 // Script compilation types.
6329 enum CompilationType {
6330 COMPILATION_TYPE_HOST = 0,
6331 COMPILATION_TYPE_EVAL = 1
6334 // Script compilation state.
6335 enum CompilationState {
6336 COMPILATION_STATE_INITIAL = 0,
6337 COMPILATION_STATE_COMPILED = 1
6340 // [source]: the script source.
6341 DECL_ACCESSORS(source, Object)
6343 // [name]: the script name.
6344 DECL_ACCESSORS(name, Object)
6346 // [id]: the script id.
6347 DECL_ACCESSORS(id, Smi)
6349 // [line_offset]: script line offset in resource from where it was extracted.
6350 DECL_ACCESSORS(line_offset, Smi)
6352 // [column_offset]: script column offset in resource from where it was
6354 DECL_ACCESSORS(column_offset, Smi)
6356 // [context_data]: context data for the context this script was compiled in.
6357 DECL_ACCESSORS(context_data, Object)
6359 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6360 DECL_ACCESSORS(wrapper, HeapObject)
6362 // [type]: the script type.
6363 DECL_ACCESSORS(type, Smi)
6365 // [line_ends]: FixedArray of line ends positions.
6366 DECL_ACCESSORS(line_ends, Object)
6368 // [eval_from_shared]: for eval scripts the shared funcion info for the
6369 // function from which eval was called.
6370 DECL_ACCESSORS(eval_from_shared, Object)
6372 // [eval_from_instructions_offset]: the instruction offset in the code for the
6373 // function from which eval was called where eval was called.
6374 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6376 // [shared_function_infos]: weak fixed array containing all shared
6377 // function infos created from this script.
6378 DECL_ACCESSORS(shared_function_infos, Object)
6380 // [flags]: Holds an exciting bitfield.
6381 DECL_ACCESSORS(flags, Smi)
6383 // [source_url]: sourceURL from magic comment
6384 DECL_ACCESSORS(source_url, Object)
6386 // [source_url]: sourceMappingURL magic comment
6387 DECL_ACCESSORS(source_mapping_url, Object)
6389 // [compilation_type]: how the the script was compiled. Encoded in the
6391 inline CompilationType compilation_type();
6392 inline void set_compilation_type(CompilationType type);
6394 // [compilation_state]: determines whether the script has already been
6395 // compiled. Encoded in the 'flags' field.
6396 inline CompilationState compilation_state();
6397 inline void set_compilation_state(CompilationState state);
6399 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6400 // and used by the embedder to make decisions about the script. V8 just passes
6401 // this through. Encoded in the 'flags' field.
6402 inline v8::ScriptOriginOptions origin_options();
6403 inline void set_origin_options(ScriptOriginOptions origin_options);
6405 DECLARE_CAST(Script)
6407 // If script source is an external string, check that the underlying
6408 // resource is accessible. Otherwise, always return true.
6409 inline bool HasValidSource();
6411 // Convert code position into column number.
6412 static int GetColumnNumber(Handle<Script> script, int code_pos);
6414 // Convert code position into (zero-based) line number.
6415 // The non-handlified version does not allocate, but may be much slower.
6416 static int GetLineNumber(Handle<Script> script, int code_pos);
6417 int GetLineNumber(int code_pos);
6419 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6421 // Init line_ends array with code positions of line ends inside script source.
6422 static void InitLineEnds(Handle<Script> script);
6424 // Get the JS object wrapping the given script; create it if none exists.
6425 static Handle<JSObject> GetWrapper(Handle<Script> script);
6427 // Look through the list of existing shared function infos to find one
6428 // that matches the function literal. Return empty handle if not found.
6429 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6431 // Dispatched behavior.
6432 DECLARE_PRINTER(Script)
6433 DECLARE_VERIFIER(Script)
6435 static const int kSourceOffset = HeapObject::kHeaderSize;
6436 static const int kNameOffset = kSourceOffset + kPointerSize;
6437 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6438 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6439 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6440 static const int kWrapperOffset = kContextOffset + kPointerSize;
6441 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6442 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6443 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6444 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6445 static const int kEvalFrominstructionsOffsetOffset =
6446 kEvalFromSharedOffset + kPointerSize;
6447 static const int kSharedFunctionInfosOffset =
6448 kEvalFrominstructionsOffsetOffset + kPointerSize;
6449 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6450 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6451 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6452 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6455 int GetLineNumberWithArray(int code_pos);
6457 // Bit positions in the flags field.
6458 static const int kCompilationTypeBit = 0;
6459 static const int kCompilationStateBit = 1;
6460 static const int kOriginOptionsShift = 2;
6461 static const int kOriginOptionsSize = 3;
6462 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6463 << kOriginOptionsShift;
6465 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6469 // List of builtin functions we want to identify to improve code
6472 // Each entry has a name of a global object property holding an object
6473 // optionally followed by ".prototype", a name of a builtin function
6474 // on the object (the one the id is set for), and a label.
6476 // Installation of ids for the selected builtin functions is handled
6477 // by the bootstrapper.
6478 #define FUNCTIONS_WITH_ID_LIST(V) \
6479 V(Array.prototype, indexOf, ArrayIndexOf) \
6480 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6481 V(Array.prototype, push, ArrayPush) \
6482 V(Array.prototype, pop, ArrayPop) \
6483 V(Array.prototype, shift, ArrayShift) \
6484 V(Function.prototype, apply, FunctionApply) \
6485 V(Function.prototype, call, FunctionCall) \
6486 V(String.prototype, charCodeAt, StringCharCodeAt) \
6487 V(String.prototype, charAt, StringCharAt) \
6488 V(String, fromCharCode, StringFromCharCode) \
6489 V(Math, random, MathRandom) \
6490 V(Math, floor, MathFloor) \
6491 V(Math, round, MathRound) \
6492 V(Math, ceil, MathCeil) \
6493 V(Math, abs, MathAbs) \
6494 V(Math, log, MathLog) \
6495 V(Math, exp, MathExp) \
6496 V(Math, sqrt, MathSqrt) \
6497 V(Math, pow, MathPow) \
6498 V(Math, max, MathMax) \
6499 V(Math, min, MathMin) \
6500 V(Math, cos, MathCos) \
6501 V(Math, sin, MathSin) \
6502 V(Math, tan, MathTan) \
6503 V(Math, acos, MathAcos) \
6504 V(Math, asin, MathAsin) \
6505 V(Math, atan, MathAtan) \
6506 V(Math, atan2, MathAtan2) \
6507 V(Math, imul, MathImul) \
6508 V(Math, clz32, MathClz32) \
6509 V(Math, fround, MathFround)
6511 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6512 V(Atomics, load, AtomicsLoad) \
6513 V(Atomics, store, AtomicsStore)
6515 enum BuiltinFunctionId {
6517 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6519 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6520 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6521 #undef DECLARE_FUNCTION_ID
6522 // Fake id for a special case of Math.pow. Note, it continues the
6523 // list of math functions.
6528 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6529 // that both {code} and {literals} can be NULL to pass search result status.
6530 struct CodeAndLiterals {
6531 Code* code; // Cached optimized code.
6532 FixedArray* literals; // Cached literals array.
6536 // SharedFunctionInfo describes the JSFunction information that can be
6537 // shared by multiple instances of the function.
6538 class SharedFunctionInfo: public HeapObject {
6540 // [name]: Function name.
6541 DECL_ACCESSORS(name, Object)
6543 // [code]: Function code.
6544 DECL_ACCESSORS(code, Code)
6545 inline void ReplaceCode(Code* code);
6547 // [optimized_code_map]: Map from native context to optimized code
6548 // and a shared literals array or Smi(0) if none.
6549 DECL_ACCESSORS(optimized_code_map, Object)
6551 // Returns entry from optimized code map for specified context and OSR entry.
6552 // Note that {code == nullptr} indicates no matching entry has been found,
6553 // whereas {literals == nullptr} indicates the code is context-independent.
6554 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6555 BailoutId osr_ast_id);
6557 // Clear optimized code map.
6558 void ClearOptimizedCodeMap();
6560 // Removed a specific optimized code object from the optimized code map.
6561 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6563 // Trims the optimized code map after entries have been removed.
6564 void TrimOptimizedCodeMap(int shrink_by);
6566 // Add a new entry to the optimized code map for context-independent code.
6567 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6570 // Add a new entry to the optimized code map for context-dependent code.
6571 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6572 Handle<Context> native_context,
6574 Handle<FixedArray> literals,
6575 BailoutId osr_ast_id);
6577 // Set up the link between shared function info and the script. The shared
6578 // function info is added to the list on the script.
6579 static void SetScript(Handle<SharedFunctionInfo> shared,
6580 Handle<Object> script_object);
6582 // Layout description of the optimized code map.
6583 static const int kNextMapIndex = 0;
6584 static const int kSharedCodeIndex = 1;
6585 static const int kEntriesStart = 2;
6586 static const int kContextOffset = 0;
6587 static const int kCachedCodeOffset = 1;
6588 static const int kLiteralsOffset = 2;
6589 static const int kOsrAstIdOffset = 3;
6590 static const int kEntryLength = 4;
6591 static const int kInitialLength = kEntriesStart + kEntryLength;
6593 // [scope_info]: Scope info.
6594 DECL_ACCESSORS(scope_info, ScopeInfo)
6596 // [construct stub]: Code stub for constructing instances of this function.
6597 DECL_ACCESSORS(construct_stub, Code)
6599 // Returns if this function has been compiled to native code yet.
6600 inline bool is_compiled();
6602 // [length]: The function length - usually the number of declared parameters.
6603 // Use up to 2^30 parameters.
6604 inline int length() const;
6605 inline void set_length(int value);
6607 // [internal formal parameter count]: The declared number of parameters.
6608 // For subclass constructors, also includes new.target.
6609 // The size of function's frame is internal_formal_parameter_count + 1.
6610 inline int internal_formal_parameter_count() const;
6611 inline void set_internal_formal_parameter_count(int value);
6613 // Set the formal parameter count so the function code will be
6614 // called without using argument adaptor frames.
6615 inline void DontAdaptArguments();
6617 // [expected_nof_properties]: Expected number of properties for the function.
6618 inline int expected_nof_properties() const;
6619 inline void set_expected_nof_properties(int value);
6621 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6622 // (increasingly) from crankshafted code where sufficient feedback isn't
6624 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6626 // Unconditionally clear the type feedback vector (including vector ICs).
6627 void ClearTypeFeedbackInfo();
6629 // Clear the type feedback vector with a more subtle policy at GC time.
6630 void ClearTypeFeedbackInfoAtGCTime();
6633 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6634 // even if the GC moves this SharedFunctionInfo.
6635 inline int unique_id() const;
6636 inline void set_unique_id(int value);
6639 // [instance class name]: class name for instances.
6640 DECL_ACCESSORS(instance_class_name, Object)
6642 // [function data]: This field holds some additional data for function.
6643 // Currently it either has FunctionTemplateInfo to make benefit the API
6644 // or Smi identifying a builtin function.
6645 // In the long run we don't want all functions to have this field but
6646 // we can fix that when we have a better model for storing hidden data
6648 DECL_ACCESSORS(function_data, Object)
6650 inline bool IsApiFunction();
6651 inline FunctionTemplateInfo* get_api_func_data();
6652 inline bool HasBuiltinFunctionId();
6653 inline BuiltinFunctionId builtin_function_id();
6655 // [script info]: Script from which the function originates.
6656 DECL_ACCESSORS(script, Object)
6658 // [num_literals]: Number of literals used by this function.
6659 inline int num_literals() const;
6660 inline void set_num_literals(int value);
6662 // [start_position_and_type]: Field used to store both the source code
6663 // position, whether or not the function is a function expression,
6664 // and whether or not the function is a toplevel function. The two
6665 // least significants bit indicates whether the function is an
6666 // expression and the rest contains the source code position.
6667 inline int start_position_and_type() const;
6668 inline void set_start_position_and_type(int value);
6670 // [debug info]: Debug information.
6671 DECL_ACCESSORS(debug_info, Object)
6673 // [inferred name]: Name inferred from variable or property
6674 // assignment of this function. Used to facilitate debugging and
6675 // profiling of JavaScript code written in OO style, where almost
6676 // all functions are anonymous but are assigned to object
6678 DECL_ACCESSORS(inferred_name, String)
6680 // The function's name if it is non-empty, otherwise the inferred name.
6681 String* DebugName();
6683 // Position of the 'function' token in the script source.
6684 inline int function_token_position() const;
6685 inline void set_function_token_position(int function_token_position);
6687 // Position of this function in the script source.
6688 inline int start_position() const;
6689 inline void set_start_position(int start_position);
6691 // End position of this function in the script source.
6692 inline int end_position() const;
6693 inline void set_end_position(int end_position);
6695 // Is this function a function expression in the source code.
6696 DECL_BOOLEAN_ACCESSORS(is_expression)
6698 // Is this function a top-level function (scripts, evals).
6699 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6701 // Bit field containing various information collected by the compiler to
6702 // drive optimization.
6703 inline int compiler_hints() const;
6704 inline void set_compiler_hints(int value);
6706 inline int ast_node_count() const;
6707 inline void set_ast_node_count(int count);
6709 inline int profiler_ticks() const;
6710 inline void set_profiler_ticks(int ticks);
6712 // Inline cache age is used to infer whether the function survived a context
6713 // disposal or not. In the former case we reset the opt_count.
6714 inline int ic_age();
6715 inline void set_ic_age(int age);
6717 // Indicates if this function can be lazy compiled.
6718 // This is used to determine if we can safely flush code from a function
6719 // when doing GC if we expect that the function will no longer be used.
6720 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6722 // Indicates if this function can be lazy compiled without a context.
6723 // This is used to determine if we can force compilation without reaching
6724 // the function through program execution but through other means (e.g. heap
6725 // iteration by the debugger).
6726 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6728 // Indicates whether optimizations have been disabled for this
6729 // shared function info. If a function is repeatedly optimized or if
6730 // we cannot optimize the function we disable optimization to avoid
6731 // spending time attempting to optimize it again.
6732 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6734 // Indicates the language mode.
6735 inline LanguageMode language_mode();
6736 inline void set_language_mode(LanguageMode language_mode);
6738 // False if the function definitely does not allocate an arguments object.
6739 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6741 // Indicates that this function uses a super property (or an eval that may
6742 // use a super property).
6743 // This is needed to set up the [[HomeObject]] on the function instance.
6744 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6746 // True if the function has any duplicated parameter names.
6747 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6749 // Indicates whether the function is a native function.
6750 // These needs special treatment in .call and .apply since
6751 // null passed as the receiver should not be translated to the
6753 DECL_BOOLEAN_ACCESSORS(native)
6755 // Indicate that this function should always be inlined in optimized code.
6756 DECL_BOOLEAN_ACCESSORS(force_inline)
6758 // Indicates that the function was created by the Function function.
6759 // Though it's anonymous, toString should treat it as if it had the name
6760 // "anonymous". We don't set the name itself so that the system does not
6761 // see a binding for it.
6762 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6764 // Indicates whether the function is a bound function created using
6765 // the bind function.
6766 DECL_BOOLEAN_ACCESSORS(bound)
6768 // Indicates that the function is anonymous (the name field can be set
6769 // through the API, which does not change this flag).
6770 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6772 // Is this a function or top-level/eval code.
6773 DECL_BOOLEAN_ACCESSORS(is_function)
6775 // Indicates that code for this function cannot be compiled with Crankshaft.
6776 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6778 // Indicates that code for this function cannot be flushed.
6779 DECL_BOOLEAN_ACCESSORS(dont_flush)
6781 // Indicates that this function is a generator.
6782 DECL_BOOLEAN_ACCESSORS(is_generator)
6784 // Indicates that this function is an arrow function.
6785 DECL_BOOLEAN_ACCESSORS(is_arrow)
6787 // Indicates that this function is a concise method.
6788 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6790 // Indicates that this function is an accessor (getter or setter).
6791 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6793 // Indicates that this function is a default constructor.
6794 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6796 // Indicates that this function is an asm function.
6797 DECL_BOOLEAN_ACCESSORS(asm_function)
6799 // Indicates that the the shared function info is deserialized from cache.
6800 DECL_BOOLEAN_ACCESSORS(deserialized)
6802 // Indicates that the the shared function info has never been compiled before.
6803 DECL_BOOLEAN_ACCESSORS(never_compiled)
6805 inline FunctionKind kind();
6806 inline void set_kind(FunctionKind kind);
6808 // Indicates whether or not the code in the shared function support
6810 inline bool has_deoptimization_support();
6812 // Enable deoptimization support through recompiled code.
6813 void EnableDeoptimizationSupport(Code* recompiled);
6815 // Disable (further) attempted optimization of all functions sharing this
6816 // shared function info.
6817 void DisableOptimization(BailoutReason reason);
6819 inline BailoutReason disable_optimization_reason();
6821 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6822 // code, returns whether it asserted (i.e., always true if assertions are
6824 bool VerifyBailoutId(BailoutId id);
6826 // [source code]: Source code for the function.
6827 bool HasSourceCode() const;
6828 Handle<Object> GetSourceCode();
6830 // Number of times the function was optimized.
6831 inline int opt_count();
6832 inline void set_opt_count(int opt_count);
6834 // Number of times the function was deoptimized.
6835 inline void set_deopt_count(int value);
6836 inline int deopt_count();
6837 inline void increment_deopt_count();
6839 // Number of time we tried to re-enable optimization after it
6840 // was disabled due to high number of deoptimizations.
6841 inline void set_opt_reenable_tries(int value);
6842 inline int opt_reenable_tries();
6844 inline void TryReenableOptimization();
6846 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6847 inline void set_counters(int value);
6848 inline int counters() const;
6850 // Stores opt_count and bailout_reason as bit-fields.
6851 inline void set_opt_count_and_bailout_reason(int value);
6852 inline int opt_count_and_bailout_reason() const;
6854 void set_disable_optimization_reason(BailoutReason reason) {
6855 set_opt_count_and_bailout_reason(
6856 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6860 // Check whether or not this function is inlineable.
6861 bool IsInlineable();
6863 // Source size of this function.
6866 // Calculate the instance size.
6867 int CalculateInstanceSize();
6869 // Calculate the number of in-object properties.
6870 int CalculateInObjectProperties();
6872 inline bool is_simple_parameter_list();
6874 // Initialize a SharedFunctionInfo from a parsed function literal.
6875 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6876 FunctionLiteral* lit);
6878 // Dispatched behavior.
6879 DECLARE_PRINTER(SharedFunctionInfo)
6880 DECLARE_VERIFIER(SharedFunctionInfo)
6882 void ResetForNewContext(int new_ic_age);
6884 DECLARE_CAST(SharedFunctionInfo)
6887 static const int kDontAdaptArgumentsSentinel = -1;
6889 // Layout description.
6891 static const int kNameOffset = HeapObject::kHeaderSize;
6892 static const int kCodeOffset = kNameOffset + kPointerSize;
6893 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6894 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6895 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6896 static const int kInstanceClassNameOffset =
6897 kConstructStubOffset + kPointerSize;
6898 static const int kFunctionDataOffset =
6899 kInstanceClassNameOffset + kPointerSize;
6900 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6901 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6902 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6903 static const int kFeedbackVectorOffset =
6904 kInferredNameOffset + kPointerSize;
6906 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6907 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6909 // Just to not break the postmortrem support with conditional offsets
6910 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6911 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6914 #if V8_HOST_ARCH_32_BIT
6916 static const int kLengthOffset = kLastPointerFieldOffset + 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 = kLastPointerFieldOffset + kPointerSize;
6953 static const int kFormalParameterCountOffset =
6954 kLengthOffset + kIntSize;
6956 static const int kExpectedNofPropertiesOffset =
6957 kFormalParameterCountOffset + kIntSize;
6958 static const int kNumLiteralsOffset =
6959 kExpectedNofPropertiesOffset + kIntSize;
6961 static const int kEndPositionOffset =
6962 kNumLiteralsOffset + kIntSize;
6963 static const int kStartPositionAndTypeOffset =
6964 kEndPositionOffset + kIntSize;
6966 static const int kFunctionTokenPositionOffset =
6967 kStartPositionAndTypeOffset + kIntSize;
6968 static const int kCompilerHintsOffset =
6969 kFunctionTokenPositionOffset + kIntSize;
6971 static const int kOptCountAndBailoutReasonOffset =
6972 kCompilerHintsOffset + kIntSize;
6973 static const int kCountersOffset =
6974 kOptCountAndBailoutReasonOffset + kIntSize;
6976 static const int kAstNodeCountOffset =
6977 kCountersOffset + kIntSize;
6978 static const int kProfilerTicksOffset =
6979 kAstNodeCountOffset + kIntSize;
6982 static const int kSize = kProfilerTicksOffset + kIntSize;
6984 #elif V8_TARGET_BIG_ENDIAN
6985 static const int kFormalParameterCountOffset =
6986 kLastPointerFieldOffset + kPointerSize;
6987 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
6989 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
6990 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
6992 static const int kStartPositionAndTypeOffset =
6993 kExpectedNofPropertiesOffset + kIntSize;
6994 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
6996 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
6997 static const int kFunctionTokenPositionOffset =
6998 kCompilerHintsOffset + kIntSize;
7000 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7001 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7003 static const int kProfilerTicksOffset =
7004 kOptCountAndBailoutReasonOffset + kIntSize;
7005 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7008 static const int kSize = kAstNodeCountOffset + kIntSize;
7011 #error Unknown byte ordering
7012 #endif // Big endian
7016 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7018 typedef FixedBodyDescriptor<kNameOffset,
7019 kLastPointerFieldOffset + kPointerSize,
7020 kSize> BodyDescriptor;
7022 // Bit positions in start_position_and_type.
7023 // The source code start position is in the 30 most significant bits of
7024 // the start_position_and_type field.
7025 static const int kIsExpressionBit = 0;
7026 static const int kIsTopLevelBit = 1;
7027 static const int kStartPositionShift = 2;
7028 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7030 // Bit positions in compiler_hints.
7031 enum CompilerHints {
7032 kAllowLazyCompilation,
7033 kAllowLazyCompilationWithoutContext,
7034 kOptimizationDisabled,
7035 kStrictModeFunction,
7036 kStrongModeFunction,
7039 kHasDuplicateParameters,
7044 kNameShouldPrintAsAnonymous,
7051 kIsAccessorFunction,
7052 kIsDefaultConstructor,
7053 kIsSubclassConstructor,
7059 kCompilerHintsCount // Pseudo entry
7061 // Add hints for other modes when they're added.
7062 STATIC_ASSERT(LANGUAGE_END == 3);
7064 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
7066 class DeoptCountBits : public BitField<int, 0, 4> {};
7067 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7068 class ICAgeBits : public BitField<int, 22, 8> {};
7070 class OptCountBits : public BitField<int, 0, 22> {};
7071 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7074 #if V8_HOST_ARCH_32_BIT
7075 // On 32 bit platforms, compiler hints is a smi.
7076 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7077 static const int kCompilerHintsSize = kPointerSize;
7079 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7080 static const int kCompilerHintsSmiTagSize = 0;
7081 static const int kCompilerHintsSize = kIntSize;
7084 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7085 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7088 // Constants for optimizing codegen for strict mode function and
7090 // Allows to use byte-width instructions.
7091 static const int kStrictModeBitWithinByte =
7092 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7093 static const int kStrongModeBitWithinByte =
7094 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7096 static const int kNativeBitWithinByte =
7097 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7099 #if defined(V8_TARGET_LITTLE_ENDIAN)
7100 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7101 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7102 static const int kStrongModeByteOffset =
7103 kCompilerHintsOffset +
7104 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7105 static const int kNativeByteOffset = kCompilerHintsOffset +
7106 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7107 #elif defined(V8_TARGET_BIG_ENDIAN)
7108 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7109 (kCompilerHintsSize - 1) -
7110 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7111 static const int kStrongModeByteOffset =
7112 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
7113 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7114 static const int kNativeByteOffset = kCompilerHintsOffset +
7115 (kCompilerHintsSize - 1) -
7116 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7118 #error Unknown byte ordering
7122 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7126 // Printing support.
7127 struct SourceCodeOf {
7128 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7129 : value(v), max_length(max) {}
7130 const SharedFunctionInfo* value;
7135 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7138 class JSGeneratorObject: public JSObject {
7140 // [function]: The function corresponding to this generator object.
7141 DECL_ACCESSORS(function, JSFunction)
7143 // [context]: The context of the suspended computation.
7144 DECL_ACCESSORS(context, Context)
7146 // [receiver]: The receiver of the suspended computation.
7147 DECL_ACCESSORS(receiver, Object)
7149 // [continuation]: Offset into code of continuation.
7151 // A positive offset indicates a suspended generator. The special
7152 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7153 // cannot be resumed.
7154 inline int continuation() const;
7155 inline void set_continuation(int continuation);
7156 inline bool is_closed();
7157 inline bool is_executing();
7158 inline bool is_suspended();
7160 // [operand_stack]: Saved operand stack.
7161 DECL_ACCESSORS(operand_stack, FixedArray)
7163 DECLARE_CAST(JSGeneratorObject)
7165 // Dispatched behavior.
7166 DECLARE_PRINTER(JSGeneratorObject)
7167 DECLARE_VERIFIER(JSGeneratorObject)
7169 // Magic sentinel values for the continuation.
7170 static const int kGeneratorExecuting = -1;
7171 static const int kGeneratorClosed = 0;
7173 // Layout description.
7174 static const int kFunctionOffset = JSObject::kHeaderSize;
7175 static const int kContextOffset = kFunctionOffset + kPointerSize;
7176 static const int kReceiverOffset = kContextOffset + kPointerSize;
7177 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7178 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7179 static const int kSize = kOperandStackOffset + kPointerSize;
7181 // Resume mode, for use by runtime functions.
7182 enum ResumeMode { NEXT, THROW };
7184 // Yielding from a generator returns an object with the following inobject
7185 // properties. See Context::iterator_result_map() for the map.
7186 static const int kResultValuePropertyIndex = 0;
7187 static const int kResultDonePropertyIndex = 1;
7188 static const int kResultPropertyCount = 2;
7190 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7191 static const int kResultDonePropertyOffset =
7192 kResultValuePropertyOffset + kPointerSize;
7193 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7196 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7200 // Representation for module instance objects.
7201 class JSModule: public JSObject {
7203 // [context]: the context holding the module's locals, or undefined if none.
7204 DECL_ACCESSORS(context, Object)
7206 // [scope_info]: Scope info.
7207 DECL_ACCESSORS(scope_info, ScopeInfo)
7209 DECLARE_CAST(JSModule)
7211 // Dispatched behavior.
7212 DECLARE_PRINTER(JSModule)
7213 DECLARE_VERIFIER(JSModule)
7215 // Layout description.
7216 static const int kContextOffset = JSObject::kHeaderSize;
7217 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7218 static const int kSize = kScopeInfoOffset + kPointerSize;
7221 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7225 // JSFunction describes JavaScript functions.
7226 class JSFunction: public JSObject {
7228 // [prototype_or_initial_map]:
7229 DECL_ACCESSORS(prototype_or_initial_map, Object)
7231 // [shared]: The information about the function that
7232 // can be shared by instances.
7233 DECL_ACCESSORS(shared, SharedFunctionInfo)
7235 // [context]: The context for this function.
7236 inline Context* context();
7237 inline void set_context(Object* context);
7238 inline JSObject* global_proxy();
7240 // [code]: The generated code object for this function. Executed
7241 // when the function is invoked, e.g. foo() or new foo(). See
7242 // [[Call]] and [[Construct]] description in ECMA-262, section
7244 inline Code* code();
7245 inline void set_code(Code* code);
7246 inline void set_code_no_write_barrier(Code* code);
7247 inline void ReplaceCode(Code* code);
7249 // Tells whether this function is builtin.
7250 inline bool IsBuiltin();
7252 // Tells whether this function is defined in a native script.
7253 inline bool IsFromNativeScript();
7255 // Tells whether this function is defined in an extension script.
7256 inline bool IsFromExtensionScript();
7258 // Tells whether this function should be subject to debugging.
7259 inline bool IsSubjectToDebugging();
7261 // Tells whether or not the function needs arguments adaption.
7262 inline bool NeedsArgumentsAdaption();
7264 // Tells whether or not this function has been optimized.
7265 inline bool IsOptimized();
7267 // Mark this function for lazy recompilation. The function will be
7268 // recompiled the next time it is executed.
7269 void MarkForOptimization();
7270 void AttemptConcurrentOptimization();
7272 // Tells whether or not the function is already marked for lazy
7274 inline bool IsMarkedForOptimization();
7275 inline bool IsMarkedForConcurrentOptimization();
7277 // Tells whether or not the function is on the concurrent recompilation queue.
7278 inline bool IsInOptimizationQueue();
7280 // Inobject slack tracking is the way to reclaim unused inobject space.
7282 // The instance size is initially determined by adding some slack to
7283 // expected_nof_properties (to allow for a few extra properties added
7284 // after the constructor). There is no guarantee that the extra space
7285 // will not be wasted.
7287 // Here is the algorithm to reclaim the unused inobject space:
7288 // - Detect the first constructor call for this JSFunction.
7289 // When it happens enter the "in progress" state: initialize construction
7290 // counter in the initial_map.
7291 // - While the tracking is in progress create objects filled with
7292 // one_pointer_filler_map instead of undefined_value. This way they can be
7293 // resized quickly and safely.
7294 // - Once enough objects have been created compute the 'slack'
7295 // (traverse the map transition tree starting from the
7296 // initial_map and find the lowest value of unused_property_fields).
7297 // - Traverse the transition tree again and decrease the instance size
7298 // of every map. Existing objects will resize automatically (they are
7299 // filled with one_pointer_filler_map). All further allocations will
7300 // use the adjusted instance size.
7301 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7302 // allocations made using different closures could actually create different
7303 // kind of objects (see prototype inheritance pattern).
7305 // Important: inobject slack tracking is not attempted during the snapshot
7308 // True if the initial_map is set and the object constructions countdown
7309 // counter is not zero.
7310 static const int kGenerousAllocationCount =
7311 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7312 inline bool IsInobjectSlackTrackingInProgress();
7314 // Starts the tracking.
7315 // Initializes object constructions countdown counter in the initial map.
7316 void StartInobjectSlackTracking();
7318 // Completes the tracking.
7319 void CompleteInobjectSlackTracking();
7321 // [literals_or_bindings]: Fixed array holding either
7322 // the materialized literals or the bindings of a bound function.
7324 // If the function contains object, regexp or array literals, the
7325 // literals array prefix contains the object, regexp, and array
7326 // function to be used when creating these literals. This is
7327 // necessary so that we do not dynamically lookup the object, regexp
7328 // or array functions. Performing a dynamic lookup, we might end up
7329 // using the functions from a new context that we should not have
7332 // On bound functions, the array is a (copy-on-write) fixed-array containing
7333 // the function that was bound, bound this-value and any bound
7334 // arguments. Bound functions never contain literals.
7335 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7337 inline FixedArray* literals();
7338 inline void set_literals(FixedArray* literals);
7340 inline FixedArray* function_bindings();
7341 inline void set_function_bindings(FixedArray* bindings);
7343 // The initial map for an object created by this constructor.
7344 inline Map* initial_map();
7345 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7346 Handle<Object> prototype);
7347 inline bool has_initial_map();
7348 static void EnsureHasInitialMap(Handle<JSFunction> function);
7350 // Get and set the prototype property on a JSFunction. If the
7351 // function has an initial map the prototype is set on the initial
7352 // map. Otherwise, the prototype is put in the initial map field
7353 // until an initial map is needed.
7354 inline bool has_prototype();
7355 inline bool has_instance_prototype();
7356 inline Object* prototype();
7357 inline Object* instance_prototype();
7358 static void SetPrototype(Handle<JSFunction> function,
7359 Handle<Object> value);
7360 static void SetInstancePrototype(Handle<JSFunction> function,
7361 Handle<Object> value);
7363 // Creates a new closure for the fucntion with the same bindings,
7364 // bound values, and prototype. An equivalent of spec operations
7365 // ``CloneMethod`` and ``CloneBoundFunction``.
7366 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7368 // After prototype is removed, it will not be created when accessed, and
7369 // [[Construct]] from this function will not be allowed.
7370 bool RemovePrototype();
7371 inline bool should_have_prototype();
7373 // Accessor for this function's initial map's [[class]]
7374 // property. This is primarily used by ECMA native functions. This
7375 // method sets the class_name field of this function's initial map
7376 // to a given value. It creates an initial map if this function does
7377 // not have one. Note that this method does not copy the initial map
7378 // if it has one already, but simply replaces it with the new value.
7379 // Instances created afterwards will have a map whose [[class]] is
7380 // set to 'value', but there is no guarantees on instances created
7382 void SetInstanceClassName(String* name);
7384 // Returns if this function has been compiled to native code yet.
7385 inline bool is_compiled();
7387 // Returns `false` if formal parameters include rest parameters, optional
7388 // parameters, or destructuring parameters.
7389 // TODO(caitp): make this a flag set during parsing
7390 inline bool is_simple_parameter_list();
7392 // [next_function_link]: Links functions into various lists, e.g. the list
7393 // of optimized functions hanging off the native_context. The CodeFlusher
7394 // uses this link to chain together flushing candidates. Treated weakly
7395 // by the garbage collector.
7396 DECL_ACCESSORS(next_function_link, Object)
7398 // Prints the name of the function using PrintF.
7399 void PrintName(FILE* out = stdout);
7401 DECLARE_CAST(JSFunction)
7403 // Iterates the objects, including code objects indirectly referenced
7404 // through pointers to the first instruction in the code object.
7405 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7407 // Dispatched behavior.
7408 DECLARE_PRINTER(JSFunction)
7409 DECLARE_VERIFIER(JSFunction)
7411 // Returns the number of allocated literals.
7412 inline int NumberOfLiterals();
7414 // Used for flags such as --hydrogen-filter.
7415 bool PassesFilter(const char* raw_filter);
7417 // The function's name if it is configured, otherwise shared function info
7419 static Handle<String> GetDebugName(Handle<JSFunction> function);
7421 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7422 // kSize) is weak and has special handling during garbage collection.
7423 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7424 static const int kPrototypeOrInitialMapOffset =
7425 kCodeEntryOffset + kPointerSize;
7426 static const int kSharedFunctionInfoOffset =
7427 kPrototypeOrInitialMapOffset + kPointerSize;
7428 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7429 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7430 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7431 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7432 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7434 // Layout of the bound-function binding array.
7435 static const int kBoundFunctionIndex = 0;
7436 static const int kBoundThisIndex = 1;
7437 static const int kBoundArgumentsStartIndex = 2;
7440 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7444 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7445 // and the prototype is hidden. JSGlobalProxy always delegates
7446 // property accesses to its prototype if the prototype is not null.
7448 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7450 // Accessing a JSGlobalProxy requires security check.
7452 class JSGlobalProxy : public JSObject {
7454 // [native_context]: the owner native context of this global proxy object.
7455 // It is null value if this object is not used by any context.
7456 DECL_ACCESSORS(native_context, Object)
7458 // [hash]: The hash code property (undefined if not initialized yet).
7459 DECL_ACCESSORS(hash, Object)
7461 DECLARE_CAST(JSGlobalProxy)
7463 inline bool IsDetachedFrom(GlobalObject* global) const;
7465 // Dispatched behavior.
7466 DECLARE_PRINTER(JSGlobalProxy)
7467 DECLARE_VERIFIER(JSGlobalProxy)
7469 // Layout description.
7470 static const int kNativeContextOffset = JSObject::kHeaderSize;
7471 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7472 static const int kSize = kHashOffset + kPointerSize;
7475 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7479 // Common super class for JavaScript global objects and the special
7480 // builtins global objects.
7481 class GlobalObject: public JSObject {
7483 // [builtins]: the object holding the runtime routines written in JS.
7484 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7486 // [native context]: the natives corresponding to this global object.
7487 DECL_ACCESSORS(native_context, Context)
7489 // [global proxy]: the global proxy object of the context
7490 DECL_ACCESSORS(global_proxy, JSObject)
7492 DECLARE_CAST(GlobalObject)
7494 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7496 // Ensure that the global object has a cell for the given property name.
7497 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7500 // Layout description.
7501 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7502 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7503 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7504 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7507 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7511 // JavaScript global object.
7512 class JSGlobalObject: public GlobalObject {
7514 DECLARE_CAST(JSGlobalObject)
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 DECLARE_CAST(JSBuiltinsObject)
7540 // Dispatched behavior.
7541 DECLARE_PRINTER(JSBuiltinsObject)
7542 DECLARE_VERIFIER(JSBuiltinsObject)
7544 // Layout description. The size of the builtins object includes
7545 // room for two pointers per runtime routine written in javascript
7546 // (function and code object).
7547 static const int kJSBuiltinsCount = Builtins::id_count;
7548 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7549 static const int kSize =
7550 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7552 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7553 return kJSBuiltinsOffset + id * kPointerSize;
7557 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7561 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7562 class JSValue: public JSObject {
7564 // [value]: the object being wrapped.
7565 DECL_ACCESSORS(value, Object)
7567 DECLARE_CAST(JSValue)
7569 // Dispatched behavior.
7570 DECLARE_PRINTER(JSValue)
7571 DECLARE_VERIFIER(JSValue)
7573 // Layout description.
7574 static const int kValueOffset = JSObject::kHeaderSize;
7575 static const int kSize = kValueOffset + kPointerSize;
7578 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7584 // Representation for JS date objects.
7585 class JSDate: public JSObject {
7587 // If one component is NaN, all of them are, indicating a NaN time value.
7588 // [value]: the time value.
7589 DECL_ACCESSORS(value, Object)
7590 // [year]: caches year. Either undefined, smi, or NaN.
7591 DECL_ACCESSORS(year, Object)
7592 // [month]: caches month. Either undefined, smi, or NaN.
7593 DECL_ACCESSORS(month, Object)
7594 // [day]: caches day. Either undefined, smi, or NaN.
7595 DECL_ACCESSORS(day, Object)
7596 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7597 DECL_ACCESSORS(weekday, Object)
7598 // [hour]: caches hours. Either undefined, smi, or NaN.
7599 DECL_ACCESSORS(hour, Object)
7600 // [min]: caches minutes. Either undefined, smi, or NaN.
7601 DECL_ACCESSORS(min, Object)
7602 // [sec]: caches seconds. Either undefined, smi, or NaN.
7603 DECL_ACCESSORS(sec, Object)
7604 // [cache stamp]: sample of the date cache stamp at the
7605 // moment when chached fields were cached.
7606 DECL_ACCESSORS(cache_stamp, Object)
7608 DECLARE_CAST(JSDate)
7610 // Returns the date field with the specified index.
7611 // See FieldIndex for the list of date fields.
7612 static Object* GetField(Object* date, Smi* index);
7614 void SetValue(Object* value, bool is_value_nan);
7617 // Dispatched behavior.
7618 DECLARE_PRINTER(JSDate)
7619 DECLARE_VERIFIER(JSDate)
7621 // The order is important. It must be kept in sync with date macros
7632 kFirstUncachedField,
7633 kMillisecond = kFirstUncachedField,
7637 kYearUTC = kFirstUTCField,
7650 // Layout description.
7651 static const int kValueOffset = JSObject::kHeaderSize;
7652 static const int kYearOffset = kValueOffset + kPointerSize;
7653 static const int kMonthOffset = kYearOffset + kPointerSize;
7654 static const int kDayOffset = kMonthOffset + kPointerSize;
7655 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7656 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7657 static const int kMinOffset = kHourOffset + kPointerSize;
7658 static const int kSecOffset = kMinOffset + kPointerSize;
7659 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7660 static const int kSize = kCacheStampOffset + kPointerSize;
7663 inline Object* DoGetField(FieldIndex index);
7665 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7667 // Computes and caches the cacheable fields of the date.
7668 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7671 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7675 // Representation of message objects used for error reporting through
7676 // the API. The messages are formatted in JavaScript so this object is
7677 // a real JavaScript object. The information used for formatting the
7678 // error messages are not directly accessible from JavaScript to
7679 // prevent leaking information to user code called during error
7681 class JSMessageObject: public JSObject {
7683 // [type]: the type of error message.
7684 inline int type() const;
7685 inline void set_type(int value);
7687 // [arguments]: the arguments for formatting the error message.
7688 DECL_ACCESSORS(argument, Object)
7690 // [script]: the script from which the error message originated.
7691 DECL_ACCESSORS(script, Object)
7693 // [stack_frames]: an array of stack frames for this error object.
7694 DECL_ACCESSORS(stack_frames, Object)
7696 // [start_position]: the start position in the script for the error message.
7697 inline int start_position() const;
7698 inline void set_start_position(int value);
7700 // [end_position]: the end position in the script for the error message.
7701 inline int end_position() const;
7702 inline void set_end_position(int value);
7704 DECLARE_CAST(JSMessageObject)
7706 // Dispatched behavior.
7707 DECLARE_PRINTER(JSMessageObject)
7708 DECLARE_VERIFIER(JSMessageObject)
7710 // Layout description.
7711 static const int kTypeOffset = JSObject::kHeaderSize;
7712 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7713 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7714 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7715 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7716 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7717 static const int kSize = kEndPositionOffset + kPointerSize;
7719 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7720 kStackFramesOffset + kPointerSize,
7721 kSize> BodyDescriptor;
7725 // Regular expressions
7726 // The regular expression holds a single reference to a FixedArray in
7727 // the kDataOffset field.
7728 // The FixedArray contains the following data:
7729 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7730 // - reference to the original source string
7731 // - reference to the original flag string
7732 // If it is an atom regexp
7733 // - a reference to a literal string to search for
7734 // If it is an irregexp regexp:
7735 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7736 // used for tracking the last usage (used for code flushing).
7737 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7738 // used for tracking the last usage (used for code flushing)..
7739 // - max number of registers used by irregexp implementations.
7740 // - number of capture registers (output values) of the regexp.
7741 class JSRegExp: public JSObject {
7744 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7745 // ATOM: A simple string to match against using an indexOf operation.
7746 // IRREGEXP: Compiled with Irregexp.
7747 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7748 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7755 UNICODE_ESCAPES = 16
7760 explicit Flags(uint32_t value) : value_(value) { }
7761 bool is_global() { return (value_ & GLOBAL) != 0; }
7762 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7763 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7764 bool is_sticky() { return (value_ & STICKY) != 0; }
7765 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7766 uint32_t value() { return value_; }
7771 DECL_ACCESSORS(data, Object)
7773 inline Type TypeTag();
7774 inline int CaptureCount();
7775 inline Flags GetFlags();
7776 inline String* Pattern();
7777 inline Object* DataAt(int index);
7778 // Set implementation data after the object has been prepared.
7779 inline void SetDataAt(int index, Object* value);
7781 static int code_index(bool is_latin1) {
7783 return kIrregexpLatin1CodeIndex;
7785 return kIrregexpUC16CodeIndex;
7789 static int saved_code_index(bool is_latin1) {
7791 return kIrregexpLatin1CodeSavedIndex;
7793 return kIrregexpUC16CodeSavedIndex;
7797 DECLARE_CAST(JSRegExp)
7799 // Dispatched behavior.
7800 DECLARE_VERIFIER(JSRegExp)
7802 static const int kDataOffset = JSObject::kHeaderSize;
7803 static const int kSize = kDataOffset + kPointerSize;
7805 // Indices in the data array.
7806 static const int kTagIndex = 0;
7807 static const int kSourceIndex = kTagIndex + 1;
7808 static const int kFlagsIndex = kSourceIndex + 1;
7809 static const int kDataIndex = kFlagsIndex + 1;
7810 // The data fields are used in different ways depending on the
7811 // value of the tag.
7812 // Atom regexps (literal strings).
7813 static const int kAtomPatternIndex = kDataIndex;
7815 static const int kAtomDataSize = kAtomPatternIndex + 1;
7817 // Irregexp compiled code or bytecode for Latin1. If compilation
7818 // fails, this fields hold an exception object that should be
7819 // thrown if the regexp is used again.
7820 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7821 // Irregexp compiled code or bytecode for UC16. If compilation
7822 // fails, this fields hold an exception object that should be
7823 // thrown if the regexp is used again.
7824 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7826 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7827 // is a potential candidate for flushing.
7828 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7829 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7830 // a potential candidate for flushing.
7831 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7833 // Maximal number of registers used by either Latin1 or UC16.
7834 // Only used to check that there is enough stack space
7835 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7836 // Number of captures in the compiled regexp.
7837 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7839 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7841 // Offsets directly into the data fixed array.
7842 static const int kDataTagOffset =
7843 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7844 static const int kDataOneByteCodeOffset =
7845 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7846 static const int kDataUC16CodeOffset =
7847 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7848 static const int kIrregexpCaptureCountOffset =
7849 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7851 // In-object fields.
7852 static const int kSourceFieldIndex = 0;
7853 static const int kGlobalFieldIndex = 1;
7854 static const int kIgnoreCaseFieldIndex = 2;
7855 static const int kMultilineFieldIndex = 3;
7856 static const int kLastIndexFieldIndex = 4;
7857 static const int kInObjectFieldCount = 5;
7859 // The uninitialized value for a regexp code object.
7860 static const int kUninitializedValue = -1;
7862 // The compilation error value for the regexp code object. The real error
7863 // object is in the saved code field.
7864 static const int kCompilationErrorValue = -2;
7866 // When we store the sweep generation at which we moved the code from the
7867 // code index to the saved code index we mask it of to be in the [0:255]
7869 static const int kCodeAgeMask = 0xff;
7873 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7875 static inline bool IsMatch(HashTableKey* key, Object* value) {
7876 return key->IsMatch(value);
7879 static inline uint32_t Hash(HashTableKey* key) {
7883 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7884 return key->HashForObject(object);
7887 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7889 static const int kPrefixSize = 0;
7890 static const int kEntrySize = 2;
7894 // This cache is used in two different variants. For regexp caching, it simply
7895 // maps identifying info of the regexp to the cached regexp object. Scripts and
7896 // eval code only gets cached after a second probe for the code object. To do
7897 // so, on first "put" only a hash identifying the source is entered into the
7898 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7899 // such lifetimes get reduced, and removed once they reach zero. If a second put
7900 // is called while such a hash is live in the cache, the hash gets replaced by
7901 // an actual cache entry. Age also removes stale live entries from the cache.
7902 // Such entries are identified by SharedFunctionInfos pointing to either the
7903 // recompilation stub, or to "old" code. This avoids memory leaks due to
7904 // premature caching of scripts and eval strings that are never needed later.
7905 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7906 CompilationCacheShape,
7909 // Find cached value for a string key, otherwise return null.
7910 Handle<Object> Lookup(
7911 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7912 Handle<Object> LookupEval(
7913 Handle<String> src, Handle<SharedFunctionInfo> shared,
7914 LanguageMode language_mode, int scope_position);
7915 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7916 static Handle<CompilationCacheTable> Put(
7917 Handle<CompilationCacheTable> cache, Handle<String> src,
7918 Handle<Context> context, LanguageMode language_mode,
7919 Handle<Object> value);
7920 static Handle<CompilationCacheTable> PutEval(
7921 Handle<CompilationCacheTable> cache, Handle<String> src,
7922 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7923 int scope_position);
7924 static Handle<CompilationCacheTable> PutRegExp(
7925 Handle<CompilationCacheTable> cache, Handle<String> src,
7926 JSRegExp::Flags flags, Handle<FixedArray> value);
7927 void Remove(Object* value);
7929 static const int kHashGenerations = 10;
7931 DECLARE_CAST(CompilationCacheTable)
7934 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
7938 class CodeCache: public Struct {
7940 DECL_ACCESSORS(default_cache, FixedArray)
7941 DECL_ACCESSORS(normal_type_cache, Object)
7943 // Add the code object to the cache.
7945 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
7947 // Lookup code object in the cache. Returns code object if found and undefined
7949 Object* Lookup(Name* name, Code::Flags flags);
7951 // Get the internal index of a code object in the cache. Returns -1 if the
7952 // code object is not in that cache. This index can be used to later call
7953 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
7955 int GetIndex(Object* name, Code* code);
7957 // Remove an object from the cache with the provided internal index.
7958 void RemoveByIndex(Object* name, Code* code, int index);
7960 DECLARE_CAST(CodeCache)
7962 // Dispatched behavior.
7963 DECLARE_PRINTER(CodeCache)
7964 DECLARE_VERIFIER(CodeCache)
7966 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
7967 static const int kNormalTypeCacheOffset =
7968 kDefaultCacheOffset + kPointerSize;
7969 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
7972 static void UpdateDefaultCache(
7973 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7974 static void UpdateNormalTypeCache(
7975 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
7976 Object* LookupDefaultCache(Name* name, Code::Flags flags);
7977 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
7979 // Code cache layout of the default cache. Elements are alternating name and
7980 // code objects for non normal load/store/call IC's.
7981 static const int kCodeCacheEntrySize = 2;
7982 static const int kCodeCacheEntryNameOffset = 0;
7983 static const int kCodeCacheEntryCodeOffset = 1;
7985 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
7989 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
7991 static inline bool IsMatch(HashTableKey* key, Object* value) {
7992 return key->IsMatch(value);
7995 static inline uint32_t Hash(HashTableKey* key) {
7999 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8000 return key->HashForObject(object);
8003 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8005 static const int kPrefixSize = 0;
8006 static const int kEntrySize = 2;
8010 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8011 CodeCacheHashTableShape,
8014 Object* Lookup(Name* name, Code::Flags flags);
8015 static Handle<CodeCacheHashTable> Put(
8016 Handle<CodeCacheHashTable> table,
8020 int GetIndex(Name* name, Code::Flags flags);
8021 void RemoveByIndex(int index);
8023 DECLARE_CAST(CodeCacheHashTable)
8025 // Initial size of the fixed array backing the hash table.
8026 static const int kInitialSize = 64;
8029 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8033 class PolymorphicCodeCache: public Struct {
8035 DECL_ACCESSORS(cache, Object)
8037 static void Update(Handle<PolymorphicCodeCache> cache,
8038 MapHandleList* maps,
8043 // Returns an undefined value if the entry is not found.
8044 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8046 DECLARE_CAST(PolymorphicCodeCache)
8048 // Dispatched behavior.
8049 DECLARE_PRINTER(PolymorphicCodeCache)
8050 DECLARE_VERIFIER(PolymorphicCodeCache)
8052 static const int kCacheOffset = HeapObject::kHeaderSize;
8053 static const int kSize = kCacheOffset + kPointerSize;
8056 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8060 class PolymorphicCodeCacheHashTable
8061 : public HashTable<PolymorphicCodeCacheHashTable,
8062 CodeCacheHashTableShape,
8065 Object* Lookup(MapHandleList* maps, int code_kind);
8067 static Handle<PolymorphicCodeCacheHashTable> Put(
8068 Handle<PolymorphicCodeCacheHashTable> hash_table,
8069 MapHandleList* maps,
8073 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8075 static const int kInitialSize = 64;
8077 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8081 class TypeFeedbackInfo: public Struct {
8083 inline int ic_total_count();
8084 inline void set_ic_total_count(int count);
8086 inline int ic_with_type_info_count();
8087 inline void change_ic_with_type_info_count(int delta);
8089 inline int ic_generic_count();
8090 inline void change_ic_generic_count(int delta);
8092 inline void initialize_storage();
8094 inline void change_own_type_change_checksum();
8095 inline int own_type_change_checksum();
8097 inline void set_inlined_type_change_checksum(int checksum);
8098 inline bool matches_inlined_type_change_checksum(int checksum);
8100 DECLARE_CAST(TypeFeedbackInfo)
8102 // Dispatched behavior.
8103 DECLARE_PRINTER(TypeFeedbackInfo)
8104 DECLARE_VERIFIER(TypeFeedbackInfo)
8106 static const int kStorage1Offset = HeapObject::kHeaderSize;
8107 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8108 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8109 static const int kSize = kStorage3Offset + kPointerSize;
8112 static const int kTypeChangeChecksumBits = 7;
8114 class ICTotalCountField: public BitField<int, 0,
8115 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8116 class OwnTypeChangeChecksum: public BitField<int,
8117 kSmiValueSize - kTypeChangeChecksumBits,
8118 kTypeChangeChecksumBits> {}; // NOLINT
8119 class ICsWithTypeInfoCountField: public BitField<int, 0,
8120 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8121 class InlinedTypeChangeChecksum: public BitField<int,
8122 kSmiValueSize - kTypeChangeChecksumBits,
8123 kTypeChangeChecksumBits> {}; // NOLINT
8125 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8129 enum AllocationSiteMode {
8130 DONT_TRACK_ALLOCATION_SITE,
8131 TRACK_ALLOCATION_SITE,
8132 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8136 class AllocationSite: public Struct {
8138 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8139 static const double kPretenureRatio;
8140 static const int kPretenureMinimumCreated = 100;
8142 // Values for pretenure decision field.
8143 enum PretenureDecision {
8149 kLastPretenureDecisionValue = kZombie
8152 const char* PretenureDecisionName(PretenureDecision decision);
8154 DECL_ACCESSORS(transition_info, Object)
8155 // nested_site threads a list of sites that represent nested literals
8156 // walked in a particular order. So [[1, 2], 1, 2] will have one
8157 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8158 DECL_ACCESSORS(nested_site, Object)
8159 DECL_ACCESSORS(pretenure_data, Smi)
8160 DECL_ACCESSORS(pretenure_create_count, Smi)
8161 DECL_ACCESSORS(dependent_code, DependentCode)
8162 DECL_ACCESSORS(weak_next, Object)
8164 inline void Initialize();
8166 // This method is expensive, it should only be called for reporting.
8167 bool IsNestedSite();
8169 // transition_info bitfields, for constructed array transition info.
8170 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8171 class UnusedBits: public BitField<int, 15, 14> {};
8172 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8174 // Bitfields for pretenure_data
8175 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8176 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8177 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8178 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8180 // Increments the mementos found counter and returns true when the first
8181 // memento was found for a given allocation site.
8182 inline bool IncrementMementoFoundCount();
8184 inline void IncrementMementoCreateCount();
8186 PretenureFlag GetPretenureMode();
8188 void ResetPretenureDecision();
8190 PretenureDecision pretenure_decision() {
8191 int value = pretenure_data()->value();
8192 return PretenureDecisionBits::decode(value);
8195 void set_pretenure_decision(PretenureDecision decision) {
8196 int value = pretenure_data()->value();
8198 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8199 SKIP_WRITE_BARRIER);
8202 bool deopt_dependent_code() {
8203 int value = pretenure_data()->value();
8204 return DeoptDependentCodeBit::decode(value);
8207 void set_deopt_dependent_code(bool deopt) {
8208 int value = pretenure_data()->value();
8210 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8211 SKIP_WRITE_BARRIER);
8214 int memento_found_count() {
8215 int value = pretenure_data()->value();
8216 return MementoFoundCountBits::decode(value);
8219 inline void set_memento_found_count(int count);
8221 int memento_create_count() {
8222 return pretenure_create_count()->value();
8225 void set_memento_create_count(int count) {
8226 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8229 // The pretenuring decision is made during gc, and the zombie state allows
8230 // us to recognize when an allocation site is just being kept alive because
8231 // a later traversal of new space may discover AllocationMementos that point
8232 // to this AllocationSite.
8234 return pretenure_decision() == kZombie;
8237 bool IsMaybeTenure() {
8238 return pretenure_decision() == kMaybeTenure;
8241 inline void MarkZombie();
8243 inline bool MakePretenureDecision(PretenureDecision current_decision,
8245 bool maximum_size_scavenge);
8247 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8249 ElementsKind GetElementsKind() {
8250 DCHECK(!SitePointsToLiteral());
8251 int value = Smi::cast(transition_info())->value();
8252 return ElementsKindBits::decode(value);
8255 void SetElementsKind(ElementsKind kind) {
8256 int value = Smi::cast(transition_info())->value();
8257 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8258 SKIP_WRITE_BARRIER);
8261 bool CanInlineCall() {
8262 int value = Smi::cast(transition_info())->value();
8263 return DoNotInlineBit::decode(value) == 0;
8266 void SetDoNotInlineCall() {
8267 int value = Smi::cast(transition_info())->value();
8268 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8269 SKIP_WRITE_BARRIER);
8272 bool SitePointsToLiteral() {
8273 // If transition_info is a smi, then it represents an ElementsKind
8274 // for a constructed array. Otherwise, it must be a boilerplate
8275 // for an object or array literal.
8276 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8279 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8280 ElementsKind to_kind);
8282 DECLARE_PRINTER(AllocationSite)
8283 DECLARE_VERIFIER(AllocationSite)
8285 DECLARE_CAST(AllocationSite)
8286 static inline AllocationSiteMode GetMode(
8287 ElementsKind boilerplate_elements_kind);
8288 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8289 static inline bool CanTrack(InstanceType type);
8291 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8292 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8293 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8294 static const int kPretenureCreateCountOffset =
8295 kPretenureDataOffset + kPointerSize;
8296 static const int kDependentCodeOffset =
8297 kPretenureCreateCountOffset + kPointerSize;
8298 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8299 static const int kSize = kWeakNextOffset + kPointerSize;
8301 // During mark compact we need to take special care for the dependent code
8303 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8304 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8306 // For other visitors, use the fixed body descriptor below.
8307 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8308 kDependentCodeOffset + kPointerSize,
8309 kSize> BodyDescriptor;
8312 bool PretenuringDecisionMade() {
8313 return pretenure_decision() != kUndecided;
8316 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8320 class AllocationMemento: public Struct {
8322 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8323 static const int kSize = kAllocationSiteOffset + kPointerSize;
8325 DECL_ACCESSORS(allocation_site, Object)
8328 return allocation_site()->IsAllocationSite() &&
8329 !AllocationSite::cast(allocation_site())->IsZombie();
8331 AllocationSite* GetAllocationSite() {
8333 return AllocationSite::cast(allocation_site());
8336 DECLARE_PRINTER(AllocationMemento)
8337 DECLARE_VERIFIER(AllocationMemento)
8339 DECLARE_CAST(AllocationMemento)
8342 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8346 // Representation of a slow alias as part of a sloppy arguments objects.
8347 // For fast aliases (if HasSloppyArgumentsElements()):
8348 // - the parameter map contains an index into the context
8349 // - all attributes of the element have default values
8350 // For slow aliases (if HasDictionaryArgumentsElements()):
8351 // - the parameter map contains no fast alias mapping (i.e. the hole)
8352 // - this struct (in the slow backing store) contains an index into the context
8353 // - all attributes are available as part if the property details
8354 class AliasedArgumentsEntry: public Struct {
8356 inline int aliased_context_slot() const;
8357 inline void set_aliased_context_slot(int count);
8359 DECLARE_CAST(AliasedArgumentsEntry)
8361 // Dispatched behavior.
8362 DECLARE_PRINTER(AliasedArgumentsEntry)
8363 DECLARE_VERIFIER(AliasedArgumentsEntry)
8365 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8366 static const int kSize = kAliasedContextSlot + kPointerSize;
8369 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8373 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8374 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8377 class StringHasher {
8379 explicit inline StringHasher(int length, uint32_t seed);
8381 template <typename schar>
8382 static inline uint32_t HashSequentialString(const schar* chars,
8386 // Reads all the data, even for long strings and computes the utf16 length.
8387 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8389 int* utf16_length_out);
8391 // Calculated hash value for a string consisting of 1 to
8392 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8393 // value is represented decimal value.
8394 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8396 // No string is allowed to have a hash of zero. That value is reserved
8397 // for internal properties. If the hash calculation yields zero then we
8399 static const int kZeroHash = 27;
8401 // Reusable parts of the hashing algorithm.
8402 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8403 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8404 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8405 const uc16* chars, int length));
8406 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8411 // Returns the value to store in the hash field of a string with
8412 // the given length and contents.
8413 uint32_t GetHashField();
8414 // Returns true if the hash of this string can be computed without
8415 // looking at the contents.
8416 inline bool has_trivial_hash();
8417 // Adds a block of characters to the hash.
8418 template<typename Char>
8419 inline void AddCharacters(const Char* chars, int len);
8422 // Add a character to the hash.
8423 inline void AddCharacter(uint16_t c);
8424 // Update index. Returns true if string is still an index.
8425 inline bool UpdateIndex(uint16_t c);
8428 uint32_t raw_running_hash_;
8429 uint32_t array_index_;
8430 bool is_array_index_;
8431 bool is_first_char_;
8432 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8436 class IteratingStringHasher : public StringHasher {
8438 static inline uint32_t Hash(String* string, uint32_t seed);
8439 inline void VisitOneByteString(const uint8_t* chars, int length);
8440 inline void VisitTwoByteString(const uint16_t* chars, int length);
8443 inline IteratingStringHasher(int len, uint32_t seed)
8444 : StringHasher(len, seed) {}
8445 void VisitConsString(ConsString* cons_string);
8446 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8450 // The characteristics of a string are stored in its map. Retrieving these
8451 // few bits of information is moderately expensive, involving two memory
8452 // loads where the second is dependent on the first. To improve efficiency
8453 // the shape of the string is given its own class so that it can be retrieved
8454 // once and used for several string operations. A StringShape is small enough
8455 // to be passed by value and is immutable, but be aware that flattening a
8456 // string can potentially alter its shape. Also be aware that a GC caused by
8457 // something else can alter the shape of a string due to ConsString
8458 // shortcutting. Keeping these restrictions in mind has proven to be error-
8459 // prone and so we no longer put StringShapes in variables unless there is a
8460 // concrete performance benefit at that particular point in the code.
8461 class StringShape BASE_EMBEDDED {
8463 inline explicit StringShape(const String* s);
8464 inline explicit StringShape(Map* s);
8465 inline explicit StringShape(InstanceType t);
8466 inline bool IsSequential();
8467 inline bool IsExternal();
8468 inline bool IsCons();
8469 inline bool IsSliced();
8470 inline bool IsIndirect();
8471 inline bool IsExternalOneByte();
8472 inline bool IsExternalTwoByte();
8473 inline bool IsSequentialOneByte();
8474 inline bool IsSequentialTwoByte();
8475 inline bool IsInternalized();
8476 inline StringRepresentationTag representation_tag();
8477 inline uint32_t encoding_tag();
8478 inline uint32_t full_representation_tag();
8479 inline uint32_t size_tag();
8481 inline uint32_t type() { return type_; }
8482 inline void invalidate() { valid_ = false; }
8483 inline bool valid() { return valid_; }
8485 inline void invalidate() { }
8491 inline void set_valid() { valid_ = true; }
8494 inline void set_valid() { }
8499 // The Name abstract class captures anything that can be used as a property
8500 // name, i.e., strings and symbols. All names store a hash value.
8501 class Name: public HeapObject {
8503 // Get and set the hash field of the name.
8504 inline uint32_t hash_field();
8505 inline void set_hash_field(uint32_t value);
8507 // Tells whether the hash code has been computed.
8508 inline bool HasHashCode();
8510 // Returns a hash value used for the property table
8511 inline uint32_t Hash();
8513 // Equality operations.
8514 inline bool Equals(Name* other);
8515 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8518 inline bool AsArrayIndex(uint32_t* index);
8520 // If the name is private, it can only name own properties.
8521 inline bool IsPrivate();
8523 // If the name is a non-flat string, this method returns a flat version of the
8524 // string. Otherwise it'll just return the input.
8525 static inline Handle<Name> Flatten(Handle<Name> name,
8526 PretenureFlag pretenure = NOT_TENURED);
8530 DECLARE_PRINTER(Name)
8532 void NameShortPrint();
8533 int NameShortPrint(Vector<char> str);
8536 // Layout description.
8537 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8538 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8539 static const int kHashFieldOffset = kHashFieldSlot;
8541 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8543 static const int kSize = kHashFieldSlot + kPointerSize;
8545 // Mask constant for checking if a name has a computed hash code
8546 // and if it is a string that is an array index. The least significant bit
8547 // indicates whether a hash code has been computed. If the hash code has
8548 // been computed the 2nd bit tells whether the string can be used as an
8550 static const int kHashNotComputedMask = 1;
8551 static const int kIsNotArrayIndexMask = 1 << 1;
8552 static const int kNofHashBitFields = 2;
8554 // Shift constant retrieving hash code from hash field.
8555 static const int kHashShift = kNofHashBitFields;
8557 // Only these bits are relevant in the hash, since the top two are shifted
8559 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8561 // Array index strings this short can keep their index in the hash field.
8562 static const int kMaxCachedArrayIndexLength = 7;
8564 // For strings which are array indexes the hash value has the string length
8565 // mixed into the hash, mainly to avoid a hash value of zero which would be
8566 // the case for the string '0'. 24 bits are used for the array index value.
8567 static const int kArrayIndexValueBits = 24;
8568 static const int kArrayIndexLengthBits =
8569 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8571 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8573 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8574 kArrayIndexValueBits> {}; // NOLINT
8575 class ArrayIndexLengthBits : public BitField<unsigned int,
8576 kNofHashBitFields + kArrayIndexValueBits,
8577 kArrayIndexLengthBits> {}; // NOLINT
8579 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8580 // could use a mask to test if the length of string is less than or equal to
8581 // kMaxCachedArrayIndexLength.
8582 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8584 static const unsigned int kContainsCachedArrayIndexMask =
8585 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8586 << ArrayIndexLengthBits::kShift) |
8587 kIsNotArrayIndexMask;
8589 // Value of empty hash field indicating that the hash is not computed.
8590 static const int kEmptyHashField =
8591 kIsNotArrayIndexMask | kHashNotComputedMask;
8594 static inline bool IsHashFieldComputed(uint32_t field);
8597 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8602 class Symbol: public Name {
8604 // [name]: The print name of a symbol, or undefined if none.
8605 DECL_ACCESSORS(name, Object)
8607 DECL_ACCESSORS(flags, Smi)
8609 // [is_private]: Whether this is a private symbol. Private symbols can only
8610 // be used to designate own properties of objects.
8611 DECL_BOOLEAN_ACCESSORS(is_private)
8613 DECLARE_CAST(Symbol)
8615 // Dispatched behavior.
8616 DECLARE_PRINTER(Symbol)
8617 DECLARE_VERIFIER(Symbol)
8619 // Layout description.
8620 static const int kNameOffset = Name::kSize;
8621 static const int kFlagsOffset = kNameOffset + kPointerSize;
8622 static const int kSize = kFlagsOffset + kPointerSize;
8624 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8626 void SymbolShortPrint(std::ostream& os);
8629 static const int kPrivateBit = 0;
8631 const char* PrivateSymbolToName() const;
8634 friend class Name; // For PrivateSymbolToName.
8637 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8643 // The String abstract class captures JavaScript string values:
8646 // 4.3.16 String Value
8647 // A string value is a member of the type String and is a finite
8648 // ordered sequence of zero or more 16-bit unsigned integer values.
8650 // All string values have a length field.
8651 class String: public Name {
8653 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8655 // Array index strings this short can keep their index in the hash field.
8656 static const int kMaxCachedArrayIndexLength = 7;
8658 // For strings which are array indexes the hash value has the string length
8659 // mixed into the hash, mainly to avoid a hash value of zero which would be
8660 // the case for the string '0'. 24 bits are used for the array index value.
8661 static const int kArrayIndexValueBits = 24;
8662 static const int kArrayIndexLengthBits =
8663 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8665 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8667 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8668 kArrayIndexValueBits> {}; // NOLINT
8669 class ArrayIndexLengthBits : public BitField<unsigned int,
8670 kNofHashBitFields + kArrayIndexValueBits,
8671 kArrayIndexLengthBits> {}; // NOLINT
8673 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8674 // could use a mask to test if the length of string is less than or equal to
8675 // kMaxCachedArrayIndexLength.
8676 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8678 static const unsigned int kContainsCachedArrayIndexMask =
8679 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8680 << ArrayIndexLengthBits::kShift) |
8681 kIsNotArrayIndexMask;
8683 class SubStringRange {
8685 explicit SubStringRange(String* string, int first = 0, int length = -1)
8688 length_(length == -1 ? string->length() : length) {}
8690 inline iterator begin();
8691 inline iterator end();
8699 // Representation of the flat content of a String.
8700 // A non-flat string doesn't have flat content.
8701 // A flat string has content that's encoded as a sequence of either
8702 // one-byte chars or two-byte UC16.
8703 // Returned by String::GetFlatContent().
8706 // Returns true if the string is flat and this structure contains content.
8707 bool IsFlat() { return state_ != NON_FLAT; }
8708 // Returns true if the structure contains one-byte content.
8709 bool IsOneByte() { return state_ == ONE_BYTE; }
8710 // Returns true if the structure contains two-byte content.
8711 bool IsTwoByte() { return state_ == TWO_BYTE; }
8713 // Return the one byte content of the string. Only use if IsOneByte()
8715 Vector<const uint8_t> ToOneByteVector() {
8716 DCHECK_EQ(ONE_BYTE, state_);
8717 return Vector<const uint8_t>(onebyte_start, length_);
8719 // Return the two-byte content of the string. Only use if IsTwoByte()
8721 Vector<const uc16> ToUC16Vector() {
8722 DCHECK_EQ(TWO_BYTE, state_);
8723 return Vector<const uc16>(twobyte_start, length_);
8727 DCHECK(i < length_);
8728 DCHECK(state_ != NON_FLAT);
8729 if (state_ == ONE_BYTE) return onebyte_start[i];
8730 return twobyte_start[i];
8733 bool UsesSameString(const FlatContent& other) const {
8734 return onebyte_start == other.onebyte_start;
8738 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8740 // Constructors only used by String::GetFlatContent().
8741 explicit FlatContent(const uint8_t* start, int length)
8742 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8743 explicit FlatContent(const uc16* start, int length)
8744 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8745 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8748 const uint8_t* onebyte_start;
8749 const uc16* twobyte_start;
8754 friend class String;
8755 friend class IterableSubString;
8758 template <typename Char>
8759 INLINE(Vector<const Char> GetCharVector());
8761 // Get and set the length of the string.
8762 inline int length() const;
8763 inline void set_length(int value);
8765 // Get and set the length of the string using acquire loads and release
8767 inline int synchronized_length() const;
8768 inline void synchronized_set_length(int value);
8770 // Returns whether this string has only one-byte chars, i.e. all of them can
8771 // be one-byte encoded. This might be the case even if the string is
8772 // two-byte. Such strings may appear when the embedder prefers
8773 // two-byte external representations even for one-byte data.
8774 inline bool IsOneByteRepresentation() const;
8775 inline bool IsTwoByteRepresentation() const;
8777 // Cons and slices have an encoding flag that may not represent the actual
8778 // encoding of the underlying string. This is taken into account here.
8779 // Requires: this->IsFlat()
8780 inline bool IsOneByteRepresentationUnderneath();
8781 inline bool IsTwoByteRepresentationUnderneath();
8783 // NOTE: this should be considered only a hint. False negatives are
8785 inline bool HasOnlyOneByteChars();
8787 // Get and set individual two byte chars in the string.
8788 inline void Set(int index, uint16_t value);
8789 // Get individual two byte char in the string. Repeated calls
8790 // to this method are not efficient unless the string is flat.
8791 INLINE(uint16_t Get(int index));
8793 // Flattens the string. Checks first inline to see if it is
8794 // necessary. Does nothing if the string is not a cons string.
8795 // Flattening allocates a sequential string with the same data as
8796 // the given string and mutates the cons string to a degenerate
8797 // form, where the first component is the new sequential string and
8798 // the second component is the empty string. If allocation fails,
8799 // this function returns a failure. If flattening succeeds, this
8800 // function returns the sequential string that is now the first
8801 // component of the cons string.
8803 // Degenerate cons strings are handled specially by the garbage
8804 // collector (see IsShortcutCandidate).
8806 static inline Handle<String> Flatten(Handle<String> string,
8807 PretenureFlag pretenure = NOT_TENURED);
8809 // Tries to return the content of a flat string as a structure holding either
8810 // a flat vector of char or of uc16.
8811 // If the string isn't flat, and therefore doesn't have flat content, the
8812 // returned structure will report so, and can't provide a vector of either
8814 FlatContent GetFlatContent();
8816 // Returns the parent of a sliced string or first part of a flat cons string.
8817 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8818 inline String* GetUnderlying();
8820 // String equality operations.
8821 inline bool Equals(String* other);
8822 inline static bool Equals(Handle<String> one, Handle<String> two);
8823 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8824 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8825 bool IsTwoByteEqualTo(Vector<const uc16> str);
8827 // Return a UTF8 representation of the string. The string is null
8828 // terminated but may optionally contain nulls. Length is returned
8829 // in length_output if length_output is not a null pointer The string
8830 // should be nearly flat, otherwise the performance of this method may
8831 // be very slow (quadratic in the length). Setting robustness_flag to
8832 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8833 // handles unexpected data without causing assert failures and it does not
8834 // do any heap allocations. This is useful when printing stack traces.
8835 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8836 RobustnessFlag robustness_flag,
8837 int offset, int length,
8838 int* length_output = 0);
8839 base::SmartArrayPointer<char> ToCString(
8840 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8841 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8842 int* length_output = 0);
8844 // Return a 16 bit Unicode representation of the string.
8845 // The string should be nearly flat, otherwise the performance of
8846 // of this method may be very bad. Setting robustness_flag to
8847 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8848 // handles unexpected data without causing assert failures and it does not
8849 // do any heap allocations. This is useful when printing stack traces.
8850 base::SmartArrayPointer<uc16> ToWideCString(
8851 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8853 bool ComputeArrayIndex(uint32_t* index);
8856 bool MakeExternal(v8::String::ExternalStringResource* resource);
8857 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8860 inline bool AsArrayIndex(uint32_t* index);
8862 DECLARE_CAST(String)
8864 void PrintOn(FILE* out);
8866 // For use during stack traces. Performs rudimentary sanity check.
8869 // Dispatched behavior.
8870 void StringShortPrint(StringStream* accumulator);
8871 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8872 #if defined(DEBUG) || defined(OBJECT_PRINT)
8873 char* ToAsciiArray();
8875 DECLARE_PRINTER(String)
8876 DECLARE_VERIFIER(String)
8878 inline bool IsFlat();
8880 // Layout description.
8881 static const int kLengthOffset = Name::kSize;
8882 static const int kSize = kLengthOffset + kPointerSize;
8884 // Maximum number of characters to consider when trying to convert a string
8885 // value into an array index.
8886 static const int kMaxArrayIndexSize = 10;
8887 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8890 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8891 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8892 static const int kMaxUtf16CodeUnit = 0xffff;
8893 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8895 // Value of hash field containing computed hash equal to zero.
8896 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8898 // Maximal string length.
8899 static const int kMaxLength = (1 << 28) - 16;
8901 // Max length for computing hash. For strings longer than this limit the
8902 // string length is used as the hash value.
8903 static const int kMaxHashCalcLength = 16383;
8905 // Limit for truncation in short printing.
8906 static const int kMaxShortPrintLength = 1024;
8908 // Support for regular expressions.
8909 const uc16* GetTwoByteData(unsigned start);
8911 // Helper function for flattening strings.
8912 template <typename sinkchar>
8913 static void WriteToFlat(String* source,
8918 // The return value may point to the first aligned word containing the first
8919 // non-one-byte character, rather than directly to the non-one-byte character.
8920 // If the return value is >= the passed length, the entire string was
8922 static inline int NonAsciiStart(const char* chars, int length) {
8923 const char* start = chars;
8924 const char* limit = chars + length;
8926 if (length >= kIntptrSize) {
8927 // Check unaligned bytes.
8928 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8929 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8930 return static_cast<int>(chars - start);
8934 // Check aligned words.
8935 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8936 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
8937 while (chars + sizeof(uintptr_t) <= limit) {
8938 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
8939 return static_cast<int>(chars - start);
8941 chars += sizeof(uintptr_t);
8944 // Check remaining unaligned bytes.
8945 while (chars < limit) {
8946 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8947 return static_cast<int>(chars - start);
8952 return static_cast<int>(chars - start);
8955 static inline bool IsAscii(const char* chars, int length) {
8956 return NonAsciiStart(chars, length) >= length;
8959 static inline bool IsAscii(const uint8_t* chars, int length) {
8961 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
8964 static inline int NonOneByteStart(const uc16* chars, int length) {
8965 const uc16* limit = chars + length;
8966 const uc16* start = chars;
8967 while (chars < limit) {
8968 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
8971 return static_cast<int>(chars - start);
8974 static inline bool IsOneByte(const uc16* chars, int length) {
8975 return NonOneByteStart(chars, length) >= length;
8978 template<class Visitor>
8979 static inline ConsString* VisitFlat(Visitor* visitor,
8983 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
8984 bool include_ending_line);
8986 // Use the hash field to forward to the canonical internalized string
8987 // when deserializing an internalized string.
8988 inline void SetForwardedInternalizedString(String* string);
8989 inline String* GetForwardedInternalizedString();
8993 friend class StringTableInsertionKey;
8995 static Handle<String> SlowFlatten(Handle<ConsString> cons,
8996 PretenureFlag tenure);
8998 // Slow case of String::Equals. This implementation works on any strings
8999 // but it is most efficient on strings that are almost flat.
9000 bool SlowEquals(String* other);
9002 static bool SlowEquals(Handle<String> one, Handle<String> two);
9004 // Slow case of AsArrayIndex.
9005 bool SlowAsArrayIndex(uint32_t* index);
9007 // Compute and set the hash code.
9008 uint32_t ComputeAndSetHash();
9010 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9014 // The SeqString abstract class captures sequential string values.
9015 class SeqString: public String {
9017 DECLARE_CAST(SeqString)
9019 // Layout description.
9020 static const int kHeaderSize = String::kSize;
9022 // Truncate the string in-place if possible and return the result.
9023 // In case of new_length == 0, the empty string is returned without
9024 // truncating the original string.
9025 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9028 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9032 // The OneByteString class captures sequential one-byte string objects.
9033 // Each character in the OneByteString is an one-byte character.
9034 class SeqOneByteString: public SeqString {
9036 static const bool kHasOneByteEncoding = true;
9038 // Dispatched behavior.
9039 inline uint16_t SeqOneByteStringGet(int index);
9040 inline void SeqOneByteStringSet(int index, uint16_t value);
9042 // Get the address of the characters in this string.
9043 inline Address GetCharsAddress();
9045 inline uint8_t* GetChars();
9047 DECLARE_CAST(SeqOneByteString)
9049 // Garbage collection support. This method is called by the
9050 // garbage collector to compute the actual size of an OneByteString
9052 inline int SeqOneByteStringSize(InstanceType instance_type);
9054 // Computes the size for an OneByteString instance of a given length.
9055 static int SizeFor(int length) {
9056 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9059 // Maximal memory usage for a single sequential one-byte string.
9060 static const int kMaxSize = 512 * MB - 1;
9061 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9064 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9068 // The TwoByteString class captures sequential unicode string objects.
9069 // Each character in the TwoByteString is a two-byte uint16_t.
9070 class SeqTwoByteString: public SeqString {
9072 static const bool kHasOneByteEncoding = false;
9074 // Dispatched behavior.
9075 inline uint16_t SeqTwoByteStringGet(int index);
9076 inline void SeqTwoByteStringSet(int index, uint16_t value);
9078 // Get the address of the characters in this string.
9079 inline Address GetCharsAddress();
9081 inline uc16* GetChars();
9084 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9086 DECLARE_CAST(SeqTwoByteString)
9088 // Garbage collection support. This method is called by the
9089 // garbage collector to compute the actual size of a TwoByteString
9091 inline int SeqTwoByteStringSize(InstanceType instance_type);
9093 // Computes the size for a TwoByteString instance of a given length.
9094 static int SizeFor(int length) {
9095 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9098 // Maximal memory usage for a single sequential two-byte string.
9099 static const int kMaxSize = 512 * MB - 1;
9100 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9101 String::kMaxLength);
9104 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9108 // The ConsString class describes string values built by using the
9109 // addition operator on strings. A ConsString is a pair where the
9110 // first and second components are pointers to other string values.
9111 // One or both components of a ConsString can be pointers to other
9112 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9113 // are non-ConsString string values. The string value represented by
9114 // a ConsString can be obtained by concatenating the leaf string
9115 // values in a left-to-right depth-first traversal of the tree.
9116 class ConsString: public String {
9118 // First string of the cons cell.
9119 inline String* first();
9120 // Doesn't check that the result is a string, even in debug mode. This is
9121 // useful during GC where the mark bits confuse the checks.
9122 inline Object* unchecked_first();
9123 inline void set_first(String* first,
9124 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9126 // Second string of the cons cell.
9127 inline String* second();
9128 // Doesn't check that the result is a string, even in debug mode. This is
9129 // useful during GC where the mark bits confuse the checks.
9130 inline Object* unchecked_second();
9131 inline void set_second(String* second,
9132 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9134 // Dispatched behavior.
9135 uint16_t ConsStringGet(int index);
9137 DECLARE_CAST(ConsString)
9139 // Layout description.
9140 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9141 static const int kSecondOffset = kFirstOffset + kPointerSize;
9142 static const int kSize = kSecondOffset + kPointerSize;
9144 // Minimum length for a cons string.
9145 static const int kMinLength = 13;
9147 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9150 DECLARE_VERIFIER(ConsString)
9153 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9157 // The Sliced String class describes strings that are substrings of another
9158 // sequential string. The motivation is to save time and memory when creating
9159 // a substring. A Sliced String is described as a pointer to the parent,
9160 // the offset from the start of the parent string and the length. Using
9161 // a Sliced String therefore requires unpacking of the parent string and
9162 // adding the offset to the start address. A substring of a Sliced String
9163 // are not nested since the double indirection is simplified when creating
9164 // such a substring.
9165 // Currently missing features are:
9166 // - handling externalized parent strings
9167 // - external strings as parent
9168 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9169 class SlicedString: public String {
9171 inline String* parent();
9172 inline void set_parent(String* parent,
9173 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9174 inline int offset() const;
9175 inline void set_offset(int offset);
9177 // Dispatched behavior.
9178 uint16_t SlicedStringGet(int index);
9180 DECLARE_CAST(SlicedString)
9182 // Layout description.
9183 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9184 static const int kOffsetOffset = kParentOffset + kPointerSize;
9185 static const int kSize = kOffsetOffset + kPointerSize;
9187 // Minimum length for a sliced string.
9188 static const int kMinLength = 13;
9190 typedef FixedBodyDescriptor<kParentOffset,
9191 kOffsetOffset + kPointerSize, kSize>
9194 DECLARE_VERIFIER(SlicedString)
9197 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9201 // The ExternalString class describes string values that are backed by
9202 // a string resource that lies outside the V8 heap. ExternalStrings
9203 // consist of the length field common to all strings, a pointer to the
9204 // external resource. It is important to ensure (externally) that the
9205 // resource is not deallocated while the ExternalString is live in the
9208 // The API expects that all ExternalStrings are created through the
9209 // API. Therefore, ExternalStrings should not be used internally.
9210 class ExternalString: public String {
9212 DECLARE_CAST(ExternalString)
9214 // Layout description.
9215 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9216 static const int kShortSize = kResourceOffset + kPointerSize;
9217 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9218 static const int kSize = kResourceDataOffset + kPointerSize;
9220 static const int kMaxShortLength =
9221 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9223 // Return whether external string is short (data pointer is not cached).
9224 inline bool is_short();
9226 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9229 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9233 // The ExternalOneByteString class is an external string backed by an
9235 class ExternalOneByteString : public ExternalString {
9237 static const bool kHasOneByteEncoding = true;
9239 typedef v8::String::ExternalOneByteStringResource Resource;
9241 // The underlying 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 uint8_t* GetChars();
9253 // Dispatched behavior.
9254 inline uint16_t ExternalOneByteStringGet(int index);
9256 DECLARE_CAST(ExternalOneByteString)
9258 // Garbage collection support.
9259 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9261 template <typename StaticVisitor>
9262 inline void ExternalOneByteStringIterateBody();
9265 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9269 // The ExternalTwoByteString class is an external string backed by a UTF-16
9271 class ExternalTwoByteString: public ExternalString {
9273 static const bool kHasOneByteEncoding = false;
9275 typedef v8::String::ExternalStringResource Resource;
9277 // The underlying string resource.
9278 inline const Resource* resource();
9279 inline void set_resource(const Resource* buffer);
9281 // Update the pointer cache to the external character array.
9282 // The cached pointer is always valid, as the external character array does =
9283 // not move during lifetime. Deserialization is the only exception, after
9284 // which the pointer cache has to be refreshed.
9285 inline void update_data_cache();
9287 inline const uint16_t* GetChars();
9289 // Dispatched behavior.
9290 inline uint16_t ExternalTwoByteStringGet(int index);
9293 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9295 DECLARE_CAST(ExternalTwoByteString)
9297 // Garbage collection support.
9298 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9300 template<typename StaticVisitor>
9301 inline void ExternalTwoByteStringIterateBody();
9304 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9308 // Utility superclass for stack-allocated objects that must be updated
9309 // on gc. It provides two ways for the gc to update instances, either
9310 // iterating or updating after gc.
9311 class Relocatable BASE_EMBEDDED {
9313 explicit inline Relocatable(Isolate* isolate);
9314 inline virtual ~Relocatable();
9315 virtual void IterateInstance(ObjectVisitor* v) { }
9316 virtual void PostGarbageCollection() { }
9318 static void PostGarbageCollectionProcessing(Isolate* isolate);
9319 static int ArchiveSpacePerThread();
9320 static char* ArchiveState(Isolate* isolate, char* to);
9321 static char* RestoreState(Isolate* isolate, char* from);
9322 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9323 static void Iterate(ObjectVisitor* v, Relocatable* top);
9324 static char* Iterate(ObjectVisitor* v, char* t);
9332 // A flat string reader provides random access to the contents of a
9333 // string independent of the character width of the string. The handle
9334 // must be valid as long as the reader is being used.
9335 class FlatStringReader : public Relocatable {
9337 FlatStringReader(Isolate* isolate, Handle<String> str);
9338 FlatStringReader(Isolate* isolate, Vector<const char> input);
9339 void PostGarbageCollection();
9340 inline uc32 Get(int index);
9341 template <typename Char>
9342 inline Char Get(int index);
9343 int length() { return length_; }
9352 // This maintains an off-stack representation of the stack frames required
9353 // to traverse a ConsString, allowing an entirely iterative and restartable
9354 // traversal of the entire string
9355 class ConsStringIterator {
9357 inline ConsStringIterator() {}
9358 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9359 Reset(cons_string, offset);
9361 inline void Reset(ConsString* cons_string, int offset = 0) {
9363 // Next will always return NULL.
9364 if (cons_string == NULL) return;
9365 Initialize(cons_string, offset);
9367 // Returns NULL when complete.
9368 inline String* Next(int* offset_out) {
9370 if (depth_ == 0) return NULL;
9371 return Continue(offset_out);
9375 static const int kStackSize = 32;
9376 // Use a mask instead of doing modulo operations for stack wrapping.
9377 static const int kDepthMask = kStackSize-1;
9378 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9379 static inline int OffsetForDepth(int depth);
9381 inline void PushLeft(ConsString* string);
9382 inline void PushRight(ConsString* string);
9383 inline void AdjustMaximumDepth();
9385 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9386 void Initialize(ConsString* cons_string, int offset);
9387 String* Continue(int* offset_out);
9388 String* NextLeaf(bool* blew_stack);
9389 String* Search(int* offset_out);
9391 // Stack must always contain only frames for which right traversal
9392 // has not yet been performed.
9393 ConsString* frames_[kStackSize];
9398 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9402 class StringCharacterStream {
9404 inline StringCharacterStream(String* string,
9406 inline uint16_t GetNext();
9407 inline bool HasMore();
9408 inline void Reset(String* string, int offset = 0);
9409 inline void VisitOneByteString(const uint8_t* chars, int length);
9410 inline void VisitTwoByteString(const uint16_t* chars, int length);
9413 ConsStringIterator iter_;
9416 const uint8_t* buffer8_;
9417 const uint16_t* buffer16_;
9419 const uint8_t* end_;
9420 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9424 template <typename T>
9425 class VectorIterator {
9427 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9428 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9429 T GetNext() { return data_[index_++]; }
9430 bool has_more() { return index_ < data_.length(); }
9432 Vector<const T> data_;
9437 // The Oddball describes objects null, undefined, true, and false.
9438 class Oddball: public HeapObject {
9440 // [to_string]: Cached to_string computed at startup.
9441 DECL_ACCESSORS(to_string, String)
9443 // [to_number]: Cached to_number computed at startup.
9444 DECL_ACCESSORS(to_number, Object)
9446 inline byte kind() const;
9447 inline void set_kind(byte kind);
9449 DECLARE_CAST(Oddball)
9451 // Dispatched behavior.
9452 DECLARE_VERIFIER(Oddball)
9454 // Initialize the fields.
9455 static void Initialize(Isolate* isolate,
9456 Handle<Oddball> oddball,
9457 const char* to_string,
9458 Handle<Object> to_number,
9461 // Layout description.
9462 static const int kToStringOffset = HeapObject::kHeaderSize;
9463 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9464 static const int kKindOffset = kToNumberOffset + kPointerSize;
9465 static const int kSize = kKindOffset + kPointerSize;
9467 static const byte kFalse = 0;
9468 static const byte kTrue = 1;
9469 static const byte kNotBooleanMask = ~1;
9470 static const byte kTheHole = 2;
9471 static const byte kNull = 3;
9472 static const byte kArgumentMarker = 4;
9473 static const byte kUndefined = 5;
9474 static const byte kUninitialized = 6;
9475 static const byte kOther = 7;
9476 static const byte kException = 8;
9478 typedef FixedBodyDescriptor<kToStringOffset,
9479 kToNumberOffset + kPointerSize,
9480 kSize> BodyDescriptor;
9482 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9483 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9484 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9487 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9491 class Cell: public HeapObject {
9493 // [value]: value of the cell.
9494 DECL_ACCESSORS(value, Object)
9498 static inline Cell* FromValueAddress(Address value) {
9499 Object* result = FromAddress(value - kValueOffset);
9500 return static_cast<Cell*>(result);
9503 inline Address ValueAddress() {
9504 return address() + kValueOffset;
9507 // Dispatched behavior.
9508 DECLARE_PRINTER(Cell)
9509 DECLARE_VERIFIER(Cell)
9511 // Layout description.
9512 static const int kValueOffset = HeapObject::kHeaderSize;
9513 static const int kSize = kValueOffset + kPointerSize;
9515 typedef FixedBodyDescriptor<kValueOffset,
9516 kValueOffset + kPointerSize,
9517 kSize> BodyDescriptor;
9520 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9524 class PropertyCell : public HeapObject {
9526 // [property_details]: details of the global property.
9527 DECL_ACCESSORS(property_details_raw, Object)
9528 // [value]: value of the global property.
9529 DECL_ACCESSORS(value, Object)
9530 // [dependent_code]: dependent code that depends on the type of the global
9532 DECL_ACCESSORS(dependent_code, DependentCode)
9534 PropertyDetails property_details() {
9535 return PropertyDetails(Smi::cast(property_details_raw()));
9538 void set_property_details(PropertyDetails details) {
9539 set_property_details_raw(details.AsSmi());
9542 PropertyCellConstantType GetConstantType();
9544 // Computes the new type of the cell's contents for the given value, but
9545 // without actually modifying the details.
9546 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9547 Handle<Object> value,
9548 PropertyDetails details);
9549 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9550 Handle<Object> value, PropertyDetails details);
9552 static Handle<PropertyCell> InvalidateEntry(
9553 Handle<GlobalDictionary> dictionary, int entry);
9555 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9556 Handle<Object> new_value);
9558 DECLARE_CAST(PropertyCell)
9560 // Dispatched behavior.
9561 DECLARE_PRINTER(PropertyCell)
9562 DECLARE_VERIFIER(PropertyCell)
9564 // Layout description.
9565 static const int kDetailsOffset = HeapObject::kHeaderSize;
9566 static const int kValueOffset = kDetailsOffset + kPointerSize;
9567 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9568 static const int kSize = kDependentCodeOffset + kPointerSize;
9570 static const int kPointerFieldsBeginOffset = kValueOffset;
9571 static const int kPointerFieldsEndOffset = kSize;
9573 typedef FixedBodyDescriptor<kValueOffset,
9575 kSize> BodyDescriptor;
9578 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9582 class WeakCell : public HeapObject {
9584 inline Object* value() const;
9586 // This should not be called by anyone except GC.
9587 inline void clear();
9589 // This should not be called by anyone except allocator.
9590 inline void initialize(HeapObject* value);
9592 inline bool cleared() const;
9594 DECL_ACCESSORS(next, Object)
9596 inline void clear_next(Heap* heap);
9598 inline bool next_cleared();
9600 DECLARE_CAST(WeakCell)
9602 DECLARE_PRINTER(WeakCell)
9603 DECLARE_VERIFIER(WeakCell)
9605 // Layout description.
9606 static const int kValueOffset = HeapObject::kHeaderSize;
9607 static const int kNextOffset = kValueOffset + kPointerSize;
9608 static const int kSize = kNextOffset + kPointerSize;
9610 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9613 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9617 // The JSProxy describes EcmaScript Harmony proxies
9618 class JSProxy: public JSReceiver {
9620 // [handler]: The handler property.
9621 DECL_ACCESSORS(handler, Object)
9623 // [hash]: The hash code property (undefined if not initialized yet).
9624 DECL_ACCESSORS(hash, Object)
9626 DECLARE_CAST(JSProxy)
9628 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9629 Handle<JSProxy> proxy,
9630 Handle<Object> receiver,
9633 // If the handler defines an accessor property with a setter, invoke it.
9634 // If it defines an accessor property without a setter, or a data property
9635 // that is read-only, throw. In all these cases set '*done' to true,
9636 // otherwise set it to false.
9638 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9639 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9640 Handle<Object> value, LanguageMode language_mode, bool* done);
9642 MUST_USE_RESULT static Maybe<PropertyAttributes>
9643 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9644 Handle<Object> receiver,
9646 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9647 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9648 Handle<Object> value, LanguageMode language_mode);
9650 // Turn the proxy into an (empty) JSObject.
9651 static void Fix(Handle<JSProxy> proxy);
9653 // Initializes the body after the handler slot.
9654 inline void InitializeBody(int object_size, Object* value);
9656 // Invoke a trap by name. If the trap does not exist on this's handler,
9657 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9658 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9659 Handle<JSProxy> proxy,
9661 Handle<Object> derived_trap,
9663 Handle<Object> args[]);
9665 // Dispatched behavior.
9666 DECLARE_PRINTER(JSProxy)
9667 DECLARE_VERIFIER(JSProxy)
9669 // Layout description. We add padding so that a proxy has the same
9670 // size as a virgin JSObject. This is essential for becoming a JSObject
9672 static const int kHandlerOffset = HeapObject::kHeaderSize;
9673 static const int kHashOffset = kHandlerOffset + kPointerSize;
9674 static const int kPaddingOffset = kHashOffset + kPointerSize;
9675 static const int kSize = JSObject::kHeaderSize;
9676 static const int kHeaderSize = kPaddingOffset;
9677 static const int kPaddingSize = kSize - kPaddingOffset;
9679 STATIC_ASSERT(kPaddingSize >= 0);
9681 typedef FixedBodyDescriptor<kHandlerOffset,
9683 kSize> BodyDescriptor;
9686 friend class JSReceiver;
9688 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9689 Handle<JSProxy> proxy, Handle<Name> name);
9691 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9692 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9694 MUST_USE_RESULT Object* GetIdentityHash();
9696 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9698 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9702 class JSFunctionProxy: public JSProxy {
9704 // [call_trap]: The call trap.
9705 DECL_ACCESSORS(call_trap, Object)
9707 // [construct_trap]: The construct trap.
9708 DECL_ACCESSORS(construct_trap, Object)
9710 DECLARE_CAST(JSFunctionProxy)
9712 // Dispatched behavior.
9713 DECLARE_PRINTER(JSFunctionProxy)
9714 DECLARE_VERIFIER(JSFunctionProxy)
9716 // Layout description.
9717 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9718 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9719 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9720 static const int kSize = JSFunction::kSize;
9721 static const int kPaddingSize = kSize - kPaddingOffset;
9723 STATIC_ASSERT(kPaddingSize >= 0);
9725 typedef FixedBodyDescriptor<kHandlerOffset,
9726 kConstructTrapOffset + kPointerSize,
9727 kSize> BodyDescriptor;
9730 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9734 class JSCollection : public JSObject {
9736 // [table]: the backing hash table
9737 DECL_ACCESSORS(table, Object)
9739 static const int kTableOffset = JSObject::kHeaderSize;
9740 static const int kSize = kTableOffset + kPointerSize;
9743 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9747 // The JSSet describes EcmaScript Harmony sets
9748 class JSSet : public JSCollection {
9752 // Dispatched behavior.
9753 DECLARE_PRINTER(JSSet)
9754 DECLARE_VERIFIER(JSSet)
9757 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9761 // The JSMap describes EcmaScript Harmony maps
9762 class JSMap : public JSCollection {
9766 // Dispatched behavior.
9767 DECLARE_PRINTER(JSMap)
9768 DECLARE_VERIFIER(JSMap)
9771 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9775 // OrderedHashTableIterator is an iterator that iterates over the keys and
9776 // values of an OrderedHashTable.
9778 // The iterator has a reference to the underlying OrderedHashTable data,
9779 // [table], as well as the current [index] the iterator is at.
9781 // When the OrderedHashTable is rehashed it adds a reference from the old table
9782 // to the new table as well as storing enough data about the changes so that the
9783 // iterator [index] can be adjusted accordingly.
9785 // When the [Next] result from the iterator is requested, the iterator checks if
9786 // there is a newer table that it needs to transition to.
9787 template<class Derived, class TableType>
9788 class OrderedHashTableIterator: public JSObject {
9790 // [table]: the backing hash table mapping keys to values.
9791 DECL_ACCESSORS(table, Object)
9793 // [index]: The index into the data table.
9794 DECL_ACCESSORS(index, Object)
9796 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9797 DECL_ACCESSORS(kind, Object)
9800 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9803 static const int kTableOffset = JSObject::kHeaderSize;
9804 static const int kIndexOffset = kTableOffset + kPointerSize;
9805 static const int kKindOffset = kIndexOffset + kPointerSize;
9806 static const int kSize = kKindOffset + kPointerSize;
9814 // Whether the iterator has more elements. This needs to be called before
9815 // calling |CurrentKey| and/or |CurrentValue|.
9818 // Move the index forward one.
9820 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9823 // Populates the array with the next key and value and then moves the iterator
9825 // This returns the |kind| or 0 if the iterator is already at the end.
9826 Smi* Next(JSArray* value_array);
9828 // Returns the current key of the iterator. This should only be called when
9829 // |HasMore| returns true.
9830 inline Object* CurrentKey();
9833 // Transitions the iterator to the non obsolete backing store. This is a NOP
9834 // if the [table] is not obsolete.
9837 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9841 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9844 // Dispatched behavior.
9845 DECLARE_PRINTER(JSSetIterator)
9846 DECLARE_VERIFIER(JSSetIterator)
9848 DECLARE_CAST(JSSetIterator)
9850 // Called by |Next| to populate the array. This allows the subclasses to
9851 // populate the array differently.
9852 inline void PopulateValueArray(FixedArray* array);
9855 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9859 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9862 // Dispatched behavior.
9863 DECLARE_PRINTER(JSMapIterator)
9864 DECLARE_VERIFIER(JSMapIterator)
9866 DECLARE_CAST(JSMapIterator)
9868 // Called by |Next| to populate the array. This allows the subclasses to
9869 // populate the array differently.
9870 inline void PopulateValueArray(FixedArray* array);
9873 // Returns the current value of the iterator. This should only be called when
9874 // |HasMore| returns true.
9875 inline Object* CurrentValue();
9877 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9881 // Base class for both JSWeakMap and JSWeakSet
9882 class JSWeakCollection: public JSObject {
9884 // [table]: the backing hash table mapping keys to values.
9885 DECL_ACCESSORS(table, Object)
9887 // [next]: linked list of encountered weak maps during GC.
9888 DECL_ACCESSORS(next, Object)
9890 static const int kTableOffset = JSObject::kHeaderSize;
9891 static const int kNextOffset = kTableOffset + kPointerSize;
9892 static const int kSize = kNextOffset + kPointerSize;
9895 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9899 // The JSWeakMap describes EcmaScript Harmony weak maps
9900 class JSWeakMap: public JSWeakCollection {
9902 DECLARE_CAST(JSWeakMap)
9904 // Dispatched behavior.
9905 DECLARE_PRINTER(JSWeakMap)
9906 DECLARE_VERIFIER(JSWeakMap)
9909 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9913 // The JSWeakSet describes EcmaScript Harmony weak sets
9914 class JSWeakSet: public JSWeakCollection {
9916 DECLARE_CAST(JSWeakSet)
9918 // Dispatched behavior.
9919 DECLARE_PRINTER(JSWeakSet)
9920 DECLARE_VERIFIER(JSWeakSet)
9923 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9927 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9928 enum class SharedFlag { kNotShared, kShared };
9931 class JSArrayBuffer: public JSObject {
9933 // [backing_store]: backing memory for this array
9934 DECL_ACCESSORS(backing_store, void)
9936 // [byte_length]: length in bytes
9937 DECL_ACCESSORS(byte_length, Object)
9939 inline uint32_t bit_field() const;
9940 inline void set_bit_field(uint32_t bits);
9942 inline bool is_external();
9943 inline void set_is_external(bool value);
9945 inline bool is_neuterable();
9946 inline void set_is_neuterable(bool value);
9948 inline bool was_neutered();
9949 inline void set_was_neutered(bool value);
9951 inline bool is_shared();
9952 inline void set_is_shared(bool value);
9954 DECLARE_CAST(JSArrayBuffer)
9958 // Dispatched behavior.
9959 DECLARE_PRINTER(JSArrayBuffer)
9960 DECLARE_VERIFIER(JSArrayBuffer)
9962 static const int kBackingStoreOffset = JSObject::kHeaderSize;
9963 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
9964 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
9965 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
9966 static const int kBitFieldOffset = kBitFieldSlot;
9968 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
9970 static const int kSize = kBitFieldSlot + kPointerSize;
9972 static const int kSizeWithInternalFields =
9973 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
9975 class IsExternal : public BitField<bool, 1, 1> {};
9976 class IsNeuterable : public BitField<bool, 2, 1> {};
9977 class WasNeutered : public BitField<bool, 3, 1> {};
9978 class IsShared : public BitField<bool, 4, 1> {};
9981 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
9985 class JSArrayBufferView: public JSObject {
9987 // [buffer]: ArrayBuffer that this typed array views.
9988 DECL_ACCESSORS(buffer, Object)
9990 // [byte_offset]: offset of typed array in bytes.
9991 DECL_ACCESSORS(byte_offset, Object)
9993 // [byte_length]: length of typed array in bytes.
9994 DECL_ACCESSORS(byte_length, Object)
9996 DECLARE_CAST(JSArrayBufferView)
9998 DECLARE_VERIFIER(JSArrayBufferView)
10000 inline bool WasNeutered() const;
10002 static const int kBufferOffset = JSObject::kHeaderSize;
10003 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10004 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10005 static const int kViewSize = kByteLengthOffset + kPointerSize;
10009 DECL_ACCESSORS(raw_byte_offset, Object)
10010 DECL_ACCESSORS(raw_byte_length, Object)
10013 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10017 class JSTypedArray: public JSArrayBufferView {
10019 // [length]: length of typed array in elements.
10020 DECL_ACCESSORS(length, Object)
10021 inline uint32_t length_value() const;
10023 DECLARE_CAST(JSTypedArray)
10025 ExternalArrayType type();
10026 size_t element_size();
10028 Handle<JSArrayBuffer> GetBuffer();
10030 // Dispatched behavior.
10031 DECLARE_PRINTER(JSTypedArray)
10032 DECLARE_VERIFIER(JSTypedArray)
10034 static const int kLengthOffset = kViewSize + kPointerSize;
10035 static const int kSize = kLengthOffset + kPointerSize;
10037 static const int kSizeWithInternalFields =
10038 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10041 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10042 Handle<JSTypedArray> typed_array);
10044 DECL_ACCESSORS(raw_length, Object)
10047 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10051 class JSDataView: public JSArrayBufferView {
10053 DECLARE_CAST(JSDataView)
10055 // Dispatched behavior.
10056 DECLARE_PRINTER(JSDataView)
10057 DECLARE_VERIFIER(JSDataView)
10059 static const int kSize = kViewSize;
10061 static const int kSizeWithInternalFields =
10062 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10065 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10069 // Foreign describes objects pointing from JavaScript to C structures.
10070 class Foreign: public HeapObject {
10072 // [address]: field containing the address.
10073 inline Address foreign_address();
10074 inline void set_foreign_address(Address value);
10076 DECLARE_CAST(Foreign)
10078 // Dispatched behavior.
10079 inline void ForeignIterateBody(ObjectVisitor* v);
10081 template<typename StaticVisitor>
10082 inline void ForeignIterateBody();
10084 // Dispatched behavior.
10085 DECLARE_PRINTER(Foreign)
10086 DECLARE_VERIFIER(Foreign)
10088 // Layout description.
10090 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10091 static const int kSize = kForeignAddressOffset + kPointerSize;
10093 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10096 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10100 // The JSArray describes JavaScript Arrays
10101 // Such an array can be in one of two modes:
10102 // - fast, backing storage is a FixedArray and length <= elements.length();
10103 // Please note: push and pop can be used to grow and shrink the array.
10104 // - slow, backing storage is a HashTable with numbers as keys.
10105 class JSArray: public JSObject {
10107 // [length]: The length property.
10108 DECL_ACCESSORS(length, Object)
10110 // Overload the length setter to skip write barrier when the length
10111 // is set to a smi. This matches the set function on FixedArray.
10112 inline void set_length(Smi* length);
10114 static bool HasReadOnlyLength(Handle<JSArray> array);
10115 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10116 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10118 // Initialize the array with the given capacity. The function may
10119 // fail due to out-of-memory situations, but only if the requested
10120 // capacity is non-zero.
10121 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10123 // If the JSArray has fast elements, and new_length would result in
10124 // normalization, returns true.
10125 bool SetLengthWouldNormalize(uint32_t new_length);
10126 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
10128 // Initializes the array to a certain length.
10129 inline bool AllowsSetLength();
10131 static void SetLength(Handle<JSArray> array, uint32_t length);
10132 // Same as above but will also queue splice records if |array| is observed.
10133 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
10136 // Set the content of the array to the content of storage.
10137 static inline void SetContent(Handle<JSArray> array,
10138 Handle<FixedArrayBase> storage);
10140 DECLARE_CAST(JSArray)
10142 // Dispatched behavior.
10143 DECLARE_PRINTER(JSArray)
10144 DECLARE_VERIFIER(JSArray)
10146 // Number of element slots to pre-allocate for an empty array.
10147 static const int kPreallocatedArrayElements = 4;
10149 // Layout description.
10150 static const int kLengthOffset = JSObject::kHeaderSize;
10151 static const int kSize = kLengthOffset + kPointerSize;
10154 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10158 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10159 Handle<Map> initial_map);
10162 // JSRegExpResult is just a JSArray with a specific initial map.
10163 // This initial map adds in-object properties for "index" and "input"
10164 // properties, as assigned by RegExp.prototype.exec, which allows
10165 // faster creation of RegExp exec results.
10166 // This class just holds constants used when creating the result.
10167 // After creation the result must be treated as a JSArray in all regards.
10168 class JSRegExpResult: public JSArray {
10170 // Offsets of object fields.
10171 static const int kIndexOffset = JSArray::kSize;
10172 static const int kInputOffset = kIndexOffset + kPointerSize;
10173 static const int kSize = kInputOffset + kPointerSize;
10174 // Indices of in-object properties.
10175 static const int kIndexIndex = 0;
10176 static const int kInputIndex = 1;
10178 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10182 class AccessorInfo: public Struct {
10184 DECL_ACCESSORS(name, Object)
10185 DECL_ACCESSORS(flag, Smi)
10186 DECL_ACCESSORS(expected_receiver_type, Object)
10188 inline bool all_can_read();
10189 inline void set_all_can_read(bool value);
10191 inline bool all_can_write();
10192 inline void set_all_can_write(bool value);
10194 inline bool is_special_data_property();
10195 inline void set_is_special_data_property(bool value);
10197 inline PropertyAttributes property_attributes();
10198 inline void set_property_attributes(PropertyAttributes attributes);
10200 // Checks whether the given receiver is compatible with this accessor.
10201 static bool IsCompatibleReceiverMap(Isolate* isolate,
10202 Handle<AccessorInfo> info,
10204 inline bool IsCompatibleReceiver(Object* receiver);
10206 DECLARE_CAST(AccessorInfo)
10208 // Dispatched behavior.
10209 DECLARE_VERIFIER(AccessorInfo)
10211 // Append all descriptors to the array that are not already there.
10212 // Return number added.
10213 static int AppendUnique(Handle<Object> descriptors,
10214 Handle<FixedArray> array,
10215 int valid_descriptors);
10217 static const int kNameOffset = HeapObject::kHeaderSize;
10218 static const int kFlagOffset = kNameOffset + kPointerSize;
10219 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10220 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10223 inline bool HasExpectedReceiverType() {
10224 return expected_receiver_type()->IsFunctionTemplateInfo();
10226 // Bit positions in flag.
10227 static const int kAllCanReadBit = 0;
10228 static const int kAllCanWriteBit = 1;
10229 static const int kSpecialDataProperty = 2;
10230 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10232 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10236 // An accessor must have a getter, but can have no setter.
10238 // When setting a property, V8 searches accessors in prototypes.
10239 // If an accessor was found and it does not have a setter,
10240 // the request is ignored.
10242 // If the accessor in the prototype has the READ_ONLY property attribute, then
10243 // a new value is added to the derived object when the property is set.
10244 // This shadows the accessor in the prototype.
10245 class ExecutableAccessorInfo: public AccessorInfo {
10247 DECL_ACCESSORS(getter, Object)
10248 DECL_ACCESSORS(setter, Object)
10249 DECL_ACCESSORS(data, Object)
10251 DECLARE_CAST(ExecutableAccessorInfo)
10253 // Dispatched behavior.
10254 DECLARE_PRINTER(ExecutableAccessorInfo)
10255 DECLARE_VERIFIER(ExecutableAccessorInfo)
10257 static const int kGetterOffset = AccessorInfo::kSize;
10258 static const int kSetterOffset = kGetterOffset + kPointerSize;
10259 static const int kDataOffset = kSetterOffset + kPointerSize;
10260 static const int kSize = kDataOffset + kPointerSize;
10262 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10265 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10269 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10270 // accessor can either be
10271 // * a pointer to a JavaScript function or proxy: a real accessor
10272 // * undefined: considered an accessor by the spec, too, strangely enough
10273 // * the hole: an accessor which has not been set
10274 // * a pointer to a map: a transition used to ensure map sharing
10275 class AccessorPair: public Struct {
10277 DECL_ACCESSORS(getter, Object)
10278 DECL_ACCESSORS(setter, Object)
10280 DECLARE_CAST(AccessorPair)
10282 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10284 Object* get(AccessorComponent component) {
10285 return component == ACCESSOR_GETTER ? getter() : setter();
10288 void set(AccessorComponent component, Object* value) {
10289 if (component == ACCESSOR_GETTER) {
10296 // Note: Returns undefined instead in case of a hole.
10297 Object* GetComponent(AccessorComponent component);
10299 // Set both components, skipping arguments which are a JavaScript null.
10300 void SetComponents(Object* getter, Object* setter) {
10301 if (!getter->IsNull()) set_getter(getter);
10302 if (!setter->IsNull()) set_setter(setter);
10305 bool Equals(AccessorPair* pair) {
10306 return (this == pair) || pair->Equals(getter(), setter());
10309 bool Equals(Object* getter_value, Object* setter_value) {
10310 return (getter() == getter_value) && (setter() == setter_value);
10313 bool ContainsAccessor() {
10314 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10317 // Dispatched behavior.
10318 DECLARE_PRINTER(AccessorPair)
10319 DECLARE_VERIFIER(AccessorPair)
10321 static const int kGetterOffset = HeapObject::kHeaderSize;
10322 static const int kSetterOffset = kGetterOffset + kPointerSize;
10323 static const int kSize = kSetterOffset + kPointerSize;
10326 // Strangely enough, in addition to functions and harmony proxies, the spec
10327 // requires us to consider undefined as a kind of accessor, too:
10329 // Object.defineProperty(obj, "foo", {get: undefined});
10330 // assertTrue("foo" in obj);
10331 bool IsJSAccessor(Object* obj) {
10332 return obj->IsSpecFunction() || obj->IsUndefined();
10335 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10339 class AccessCheckInfo: public Struct {
10341 DECL_ACCESSORS(named_callback, Object)
10342 DECL_ACCESSORS(indexed_callback, Object)
10343 DECL_ACCESSORS(data, Object)
10345 DECLARE_CAST(AccessCheckInfo)
10347 // Dispatched behavior.
10348 DECLARE_PRINTER(AccessCheckInfo)
10349 DECLARE_VERIFIER(AccessCheckInfo)
10351 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10352 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10353 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10354 static const int kSize = kDataOffset + kPointerSize;
10357 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10361 class InterceptorInfo: public Struct {
10363 DECL_ACCESSORS(getter, Object)
10364 DECL_ACCESSORS(setter, Object)
10365 DECL_ACCESSORS(query, Object)
10366 DECL_ACCESSORS(deleter, Object)
10367 DECL_ACCESSORS(enumerator, Object)
10368 DECL_ACCESSORS(data, Object)
10369 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10370 DECL_BOOLEAN_ACCESSORS(all_can_read)
10371 DECL_BOOLEAN_ACCESSORS(non_masking)
10373 inline int flags() const;
10374 inline void set_flags(int flags);
10376 DECLARE_CAST(InterceptorInfo)
10378 // Dispatched behavior.
10379 DECLARE_PRINTER(InterceptorInfo)
10380 DECLARE_VERIFIER(InterceptorInfo)
10382 static const int kGetterOffset = HeapObject::kHeaderSize;
10383 static const int kSetterOffset = kGetterOffset + kPointerSize;
10384 static const int kQueryOffset = kSetterOffset + kPointerSize;
10385 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10386 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10387 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10388 static const int kFlagsOffset = kDataOffset + kPointerSize;
10389 static const int kSize = kFlagsOffset + kPointerSize;
10391 static const int kCanInterceptSymbolsBit = 0;
10392 static const int kAllCanReadBit = 1;
10393 static const int kNonMasking = 2;
10396 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10400 class CallHandlerInfo: public Struct {
10402 DECL_ACCESSORS(callback, Object)
10403 DECL_ACCESSORS(data, Object)
10405 DECLARE_CAST(CallHandlerInfo)
10407 // Dispatched behavior.
10408 DECLARE_PRINTER(CallHandlerInfo)
10409 DECLARE_VERIFIER(CallHandlerInfo)
10411 static const int kCallbackOffset = HeapObject::kHeaderSize;
10412 static const int kDataOffset = kCallbackOffset + kPointerSize;
10413 static const int kSize = kDataOffset + kPointerSize;
10416 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10420 class TemplateInfo: public Struct {
10422 DECL_ACCESSORS(tag, Object)
10423 inline int number_of_properties() const;
10424 inline void set_number_of_properties(int value);
10425 DECL_ACCESSORS(property_list, Object)
10426 DECL_ACCESSORS(property_accessors, Object)
10428 DECLARE_VERIFIER(TemplateInfo)
10430 static const int kTagOffset = HeapObject::kHeaderSize;
10431 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10432 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10433 static const int kPropertyAccessorsOffset =
10434 kPropertyListOffset + kPointerSize;
10435 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10438 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10442 class FunctionTemplateInfo: public TemplateInfo {
10444 DECL_ACCESSORS(serial_number, Object)
10445 DECL_ACCESSORS(call_code, Object)
10446 DECL_ACCESSORS(prototype_template, Object)
10447 DECL_ACCESSORS(parent_template, Object)
10448 DECL_ACCESSORS(named_property_handler, Object)
10449 DECL_ACCESSORS(indexed_property_handler, Object)
10450 DECL_ACCESSORS(instance_template, Object)
10451 DECL_ACCESSORS(class_name, Object)
10452 DECL_ACCESSORS(signature, Object)
10453 DECL_ACCESSORS(instance_call_handler, Object)
10454 DECL_ACCESSORS(access_check_info, Object)
10455 DECL_ACCESSORS(flag, Smi)
10457 inline int length() const;
10458 inline void set_length(int value);
10460 // Following properties use flag bits.
10461 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10462 DECL_BOOLEAN_ACCESSORS(undetectable)
10463 // If the bit is set, object instances created by this function
10464 // requires access check.
10465 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10466 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10467 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10468 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10469 DECL_BOOLEAN_ACCESSORS(instantiated)
10470 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10472 DECLARE_CAST(FunctionTemplateInfo)
10474 // Dispatched behavior.
10475 DECLARE_PRINTER(FunctionTemplateInfo)
10476 DECLARE_VERIFIER(FunctionTemplateInfo)
10478 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10479 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10480 static const int kPrototypeTemplateOffset =
10481 kCallCodeOffset + kPointerSize;
10482 static const int kParentTemplateOffset =
10483 kPrototypeTemplateOffset + kPointerSize;
10484 static const int kNamedPropertyHandlerOffset =
10485 kParentTemplateOffset + kPointerSize;
10486 static const int kIndexedPropertyHandlerOffset =
10487 kNamedPropertyHandlerOffset + kPointerSize;
10488 static const int kInstanceTemplateOffset =
10489 kIndexedPropertyHandlerOffset + kPointerSize;
10490 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10491 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10492 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10493 static const int kAccessCheckInfoOffset =
10494 kInstanceCallHandlerOffset + kPointerSize;
10495 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10496 static const int kLengthOffset = kFlagOffset + kPointerSize;
10497 static const int kSize = kLengthOffset + kPointerSize;
10499 // Returns true if |object| is an instance of this function template.
10500 bool IsTemplateFor(Object* object);
10501 bool IsTemplateFor(Map* map);
10503 // Returns the holder JSObject if the function can legally be called with this
10504 // receiver. Returns Heap::null_value() if the call is illegal.
10505 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10508 // Bit position in the flag, from least significant bit position.
10509 static const int kHiddenPrototypeBit = 0;
10510 static const int kUndetectableBit = 1;
10511 static const int kNeedsAccessCheckBit = 2;
10512 static const int kReadOnlyPrototypeBit = 3;
10513 static const int kRemovePrototypeBit = 4;
10514 static const int kDoNotCacheBit = 5;
10515 static const int kInstantiatedBit = 6;
10516 static const int kAcceptAnyReceiver = 7;
10518 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10522 class ObjectTemplateInfo: public TemplateInfo {
10524 DECL_ACCESSORS(constructor, Object)
10525 DECL_ACCESSORS(internal_field_count, Object)
10527 DECLARE_CAST(ObjectTemplateInfo)
10529 // Dispatched behavior.
10530 DECLARE_PRINTER(ObjectTemplateInfo)
10531 DECLARE_VERIFIER(ObjectTemplateInfo)
10533 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10534 static const int kInternalFieldCountOffset =
10535 kConstructorOffset + kPointerSize;
10536 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10540 class TypeSwitchInfo: public Struct {
10542 DECL_ACCESSORS(types, Object)
10544 DECLARE_CAST(TypeSwitchInfo)
10546 // Dispatched behavior.
10547 DECLARE_PRINTER(TypeSwitchInfo)
10548 DECLARE_VERIFIER(TypeSwitchInfo)
10550 static const int kTypesOffset = Struct::kHeaderSize;
10551 static const int kSize = kTypesOffset + kPointerSize;
10555 // The DebugInfo class holds additional information for a function being
10557 class DebugInfo: public Struct {
10559 // The shared function info for the source being debugged.
10560 DECL_ACCESSORS(shared, SharedFunctionInfo)
10561 // Code object for the patched code. This code object is the code object
10562 // currently active for the function.
10563 DECL_ACCESSORS(code, Code)
10564 // Fixed array holding status information for each active break point.
10565 DECL_ACCESSORS(break_points, FixedArray)
10567 // Check if there is a break point at a code position.
10568 bool HasBreakPoint(int code_position);
10569 // Get the break point info object for a code position.
10570 Object* GetBreakPointInfo(int code_position);
10571 // Clear a break point.
10572 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10574 Handle<Object> break_point_object);
10575 // Set a break point.
10576 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10577 int source_position, int statement_position,
10578 Handle<Object> break_point_object);
10579 // Get the break point objects for a code position.
10580 Handle<Object> GetBreakPointObjects(int code_position);
10581 // Find the break point info holding this break point object.
10582 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10583 Handle<Object> break_point_object);
10584 // Get the number of break points for this function.
10585 int GetBreakPointCount();
10587 DECLARE_CAST(DebugInfo)
10589 // Dispatched behavior.
10590 DECLARE_PRINTER(DebugInfo)
10591 DECLARE_VERIFIER(DebugInfo)
10593 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10594 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10595 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10596 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10598 static const int kEstimatedNofBreakPointsInFunction = 16;
10601 static const int kNoBreakPointInfo = -1;
10603 // Lookup the index in the break_points array for a code position.
10604 int GetBreakPointInfoIndex(int code_position);
10606 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10610 // The BreakPointInfo class holds information for break points set in a
10611 // function. The DebugInfo object holds a BreakPointInfo object for each code
10612 // position with one or more break points.
10613 class BreakPointInfo: public Struct {
10615 // The position in the code for the break point.
10616 DECL_ACCESSORS(code_position, Smi)
10617 // The position in the source for the break position.
10618 DECL_ACCESSORS(source_position, Smi)
10619 // The position in the source for the last statement before this break
10621 DECL_ACCESSORS(statement_position, Smi)
10622 // List of related JavaScript break points.
10623 DECL_ACCESSORS(break_point_objects, Object)
10625 // Removes a break point.
10626 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10627 Handle<Object> break_point_object);
10628 // Set a break point.
10629 static void SetBreakPoint(Handle<BreakPointInfo> info,
10630 Handle<Object> break_point_object);
10631 // Check if break point info has this break point object.
10632 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10633 Handle<Object> break_point_object);
10634 // Get the number of break points for this code position.
10635 int GetBreakPointCount();
10637 DECLARE_CAST(BreakPointInfo)
10639 // Dispatched behavior.
10640 DECLARE_PRINTER(BreakPointInfo)
10641 DECLARE_VERIFIER(BreakPointInfo)
10643 static const int kCodePositionIndex = Struct::kHeaderSize;
10644 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10645 static const int kStatementPositionIndex =
10646 kSourcePositionIndex + kPointerSize;
10647 static const int kBreakPointObjectsIndex =
10648 kStatementPositionIndex + kPointerSize;
10649 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10652 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10656 #undef DECL_BOOLEAN_ACCESSORS
10657 #undef DECL_ACCESSORS
10658 #undef DECLARE_CAST
10659 #undef DECLARE_VERIFIER
10661 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10662 V(kStringTable, "string_table", "(Internalized strings)") \
10663 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10664 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10665 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10666 V(kInternalizedString, "internalized_string", "(Internal string)") \
10667 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10668 V(kTop, "top", "(Isolate)") \
10669 V(kRelocatable, "relocatable", "(Relocatable)") \
10670 V(kDebug, "debug", "(Debugger)") \
10671 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10672 V(kHandleScope, "handlescope", "(Handle scope)") \
10673 V(kBuiltins, "builtins", "(Builtins)") \
10674 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10675 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10676 V(kThreadManager, "threadmanager", "(Thread manager)") \
10677 V(kStrongRoots, "strong roots", "(Strong roots)") \
10678 V(kExtensions, "Extensions", "(Extensions)")
10680 class VisitorSynchronization : public AllStatic {
10682 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10684 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10687 #undef DECLARE_ENUM
10689 static const char* const kTags[kNumberOfSyncTags];
10690 static const char* const kTagNames[kNumberOfSyncTags];
10693 // Abstract base class for visiting, and optionally modifying, the
10694 // pointers contained in Objects. Used in GC and serialization/deserialization.
10695 class ObjectVisitor BASE_EMBEDDED {
10697 virtual ~ObjectVisitor() {}
10699 // Visits a contiguous arrays of pointers in the half-open range
10700 // [start, end). Any or all of the values may be modified on return.
10701 virtual void VisitPointers(Object** start, Object** end) = 0;
10703 // Handy shorthand for visiting a single pointer.
10704 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10706 // Visit weak next_code_link in Code object.
10707 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10709 // To allow lazy clearing of inline caches the visitor has
10710 // a rich interface for iterating over Code objects..
10712 // Visits a code target in the instruction stream.
10713 virtual void VisitCodeTarget(RelocInfo* rinfo);
10715 // Visits a code entry in a JS function.
10716 virtual void VisitCodeEntry(Address entry_address);
10718 // Visits a global property cell reference in the instruction stream.
10719 virtual void VisitCell(RelocInfo* rinfo);
10721 // Visits a runtime entry in the instruction stream.
10722 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10724 // Visits the resource of an one-byte or two-byte string.
10725 virtual void VisitExternalOneByteString(
10726 v8::String::ExternalOneByteStringResource** resource) {}
10727 virtual void VisitExternalTwoByteString(
10728 v8::String::ExternalStringResource** resource) {}
10730 // Visits a debug call target in the instruction stream.
10731 virtual void VisitDebugTarget(RelocInfo* rinfo);
10733 // Visits the byte sequence in a function's prologue that contains information
10734 // about the code's age.
10735 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10737 // Visit pointer embedded into a code object.
10738 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10740 // Visits an external reference embedded into a code object.
10741 virtual void VisitExternalReference(RelocInfo* rinfo);
10743 // Visits an external reference.
10744 virtual void VisitExternalReference(Address* p) {}
10746 // Visits an (encoded) internal reference.
10747 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10749 // Visits a handle that has an embedder-assigned class ID.
10750 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10752 // Intended for serialization/deserialization checking: insert, or
10753 // check for the presence of, a tag at this position in the stream.
10754 // Also used for marking up GC roots in heap snapshots.
10755 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10759 class StructBodyDescriptor : public
10760 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10762 static inline int SizeOf(Map* map, HeapObject* object) {
10763 return map->instance_size();
10768 // BooleanBit is a helper class for setting and getting a bit in an
10770 class BooleanBit : public AllStatic {
10772 static inline bool get(Smi* smi, int bit_position) {
10773 return get(smi->value(), bit_position);
10776 static inline bool get(int value, int bit_position) {
10777 return (value & (1 << bit_position)) != 0;
10780 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10781 return Smi::FromInt(set(smi->value(), bit_position, v));
10784 static inline int set(int value, int bit_position, bool v) {
10786 value |= (1 << bit_position);
10788 value &= ~(1 << bit_position);
10794 } } // namespace v8::internal
10796 #endif // V8_OBJECTS_H_