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
82 // - CompilationCacheTable
83 // - CodeCacheHashTable
89 // - TypeFeedbackVector
90 // - JSFunctionResultCache
93 // - ScriptContextTable
97 // - ExternalUint8ClampedArray
98 // - ExternalInt8Array
99 // - ExternalUint8Array
100 // - ExternalInt16Array
101 // - ExternalUint16Array
102 // - ExternalInt32Array
103 // - ExternalUint32Array
104 // - ExternalFloat32Array
108 // - SeqOneByteString
109 // - SeqTwoByteString
113 // - ExternalOneByteString
114 // - ExternalTwoByteString
115 // - InternalizedString
116 // - SeqInternalizedString
117 // - SeqOneByteInternalizedString
118 // - SeqTwoByteInternalizedString
119 // - ConsInternalizedString
120 // - ExternalInternalizedString
121 // - ExternalOneByteInternalizedString
122 // - ExternalTwoByteInternalizedString
132 // - SharedFunctionInfo
136 // - ExecutableAccessorInfo
142 // - FunctionTemplateInfo
143 // - ObjectTemplateInfo
152 // Formats of Object*:
153 // Smi: [31 bit signed int] 0
154 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
159 enum KeyedAccessStoreMode {
161 STORE_TRANSITION_SMI_TO_OBJECT,
162 STORE_TRANSITION_SMI_TO_DOUBLE,
163 STORE_TRANSITION_DOUBLE_TO_OBJECT,
164 STORE_TRANSITION_HOLEY_SMI_TO_OBJECT,
165 STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE,
166 STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
167 STORE_AND_GROW_NO_TRANSITION,
168 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT,
169 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE,
170 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT,
171 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT,
172 STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE,
173 STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT,
174 STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS,
175 STORE_NO_TRANSITION_HANDLE_COW
179 enum TypeofMode { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
188 enum ExternalArrayType {
189 kExternalInt8Array = 1,
192 kExternalUint16Array,
194 kExternalUint32Array,
195 kExternalFloat32Array,
196 kExternalFloat64Array,
197 kExternalUint8ClampedArray,
201 static const int kGrowICDelta = STORE_AND_GROW_NO_TRANSITION -
203 STATIC_ASSERT(STANDARD_STORE == 0);
204 STATIC_ASSERT(kGrowICDelta ==
205 STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT -
206 STORE_TRANSITION_SMI_TO_OBJECT);
207 STATIC_ASSERT(kGrowICDelta ==
208 STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE -
209 STORE_TRANSITION_SMI_TO_DOUBLE);
210 STATIC_ASSERT(kGrowICDelta ==
211 STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT -
212 STORE_TRANSITION_DOUBLE_TO_OBJECT);
215 static inline KeyedAccessStoreMode GetGrowStoreMode(
216 KeyedAccessStoreMode store_mode) {
217 if (store_mode < STORE_AND_GROW_NO_TRANSITION) {
218 store_mode = static_cast<KeyedAccessStoreMode>(
219 static_cast<int>(store_mode) + kGrowICDelta);
225 static inline bool IsTransitionStoreMode(KeyedAccessStoreMode store_mode) {
226 return store_mode > STANDARD_STORE &&
227 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT &&
228 store_mode != STORE_AND_GROW_NO_TRANSITION;
232 static inline KeyedAccessStoreMode GetNonTransitioningStoreMode(
233 KeyedAccessStoreMode store_mode) {
234 if (store_mode >= STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
237 if (store_mode >= STORE_AND_GROW_NO_TRANSITION) {
238 return STORE_AND_GROW_NO_TRANSITION;
240 return STANDARD_STORE;
244 static inline bool IsGrowStoreMode(KeyedAccessStoreMode store_mode) {
245 return store_mode >= STORE_AND_GROW_NO_TRANSITION &&
246 store_mode <= STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
250 enum IcCheckType { ELEMENT, PROPERTY };
253 // SKIP_WRITE_BARRIER skips the write barrier.
254 // UPDATE_WEAK_WRITE_BARRIER skips the marking part of the write barrier and
255 // only performs the generational part.
256 // UPDATE_WRITE_BARRIER is doing the full barrier, marking and generational.
257 enum WriteBarrierMode {
259 UPDATE_WEAK_WRITE_BARRIER,
264 // Indicates whether a value can be loaded as a constant.
265 enum StoreMode { ALLOW_IN_DESCRIPTOR, FORCE_FIELD };
268 // PropertyNormalizationMode is used to specify whether to keep
269 // inobject properties when normalizing properties of a JSObject.
270 enum PropertyNormalizationMode {
271 CLEAR_INOBJECT_PROPERTIES,
272 KEEP_INOBJECT_PROPERTIES
276 // Indicates how aggressively the prototype should be optimized. FAST_PROTOTYPE
277 // will give the fastest result by tailoring the map to the prototype, but that
278 // will cause polymorphism with other objects. REGULAR_PROTOTYPE is to be used
279 // (at least for now) when dynamically modifying the prototype chain of an
280 // object using __proto__ or Object.setPrototypeOf.
281 enum PrototypeOptimizationMode { REGULAR_PROTOTYPE, FAST_PROTOTYPE };
284 // Indicates whether transitions can be added to a source map or not.
285 enum TransitionFlag {
291 // Indicates whether the transition is simple: the target map of the transition
292 // either extends the current map with a new property, or it modifies the
293 // property that was added last to the current map.
294 enum SimpleTransitionFlag {
295 SIMPLE_PROPERTY_TRANSITION,
301 // Indicates whether we are only interested in the descriptors of a particular
302 // map, or in all descriptors in the descriptor array.
303 enum DescriptorFlag {
308 // The GC maintains a bit of information, the MarkingParity, which toggles
309 // from odd to even and back every time marking is completed. Incremental
310 // marking can visit an object twice during a marking phase, so algorithms that
311 // that piggy-back on marking can use the parity to ensure that they only
312 // perform an operation on an object once per marking phase: they record the
313 // MarkingParity when they visit an object, and only re-visit the object when it
314 // is marked again and the MarkingParity changes.
321 // ICs store extra state in a Code object. The default extra state is
323 typedef int ExtraICState;
324 static const ExtraICState kNoExtraICState = 0;
326 // Instance size sentinel for objects of variable size.
327 const int kVariableSizeSentinel = 0;
329 // We may store the unsigned bit field as signed Smi value and do not
331 const int kStubMajorKeyBits = 7;
332 const int kStubMinorKeyBits = kSmiValueSize - kStubMajorKeyBits - 1;
334 // All Maps have a field instance_type containing a InstanceType.
335 // It describes the type of the instances.
337 // As an example, a JavaScript object is a heap object and its map
338 // instance_type is JS_OBJECT_TYPE.
340 // The names of the string instance types are intended to systematically
341 // mirror their encoding in the instance_type field of the map. The default
342 // encoding is considered TWO_BYTE. It is not mentioned in the name. ONE_BYTE
343 // encoding is mentioned explicitly in the name. Likewise, the default
344 // representation is considered sequential. It is not mentioned in the
345 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
346 // mentioned. Finally, the string is either a STRING_TYPE (if it is a normal
347 // string) or a INTERNALIZED_STRING_TYPE (if it is a internalized string).
349 // NOTE: The following things are some that depend on the string types having
350 // instance_types that are less than those of all other types:
351 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
354 // NOTE: Everything following JS_VALUE_TYPE is considered a
355 // JSObject for GC purposes. The first four entries here have typeof
356 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
357 #define INSTANCE_TYPE_LIST(V) \
359 V(ONE_BYTE_STRING_TYPE) \
360 V(CONS_STRING_TYPE) \
361 V(CONS_ONE_BYTE_STRING_TYPE) \
362 V(SLICED_STRING_TYPE) \
363 V(SLICED_ONE_BYTE_STRING_TYPE) \
364 V(EXTERNAL_STRING_TYPE) \
365 V(EXTERNAL_ONE_BYTE_STRING_TYPE) \
366 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
367 V(SHORT_EXTERNAL_STRING_TYPE) \
368 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE) \
369 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE) \
371 V(INTERNALIZED_STRING_TYPE) \
372 V(ONE_BYTE_INTERNALIZED_STRING_TYPE) \
373 V(EXTERNAL_INTERNALIZED_STRING_TYPE) \
374 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
375 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
376 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE) \
377 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE) \
378 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE) \
387 V(PROPERTY_CELL_TYPE) \
389 V(HEAP_NUMBER_TYPE) \
390 V(MUTABLE_HEAP_NUMBER_TYPE) \
393 V(BYTECODE_ARRAY_TYPE) \
395 /* Note: the order of these external array */ \
396 /* types is relied upon in */ \
397 /* Object::IsExternalArray(). */ \
398 V(EXTERNAL_INT8_ARRAY_TYPE) \
399 V(EXTERNAL_UINT8_ARRAY_TYPE) \
400 V(EXTERNAL_INT16_ARRAY_TYPE) \
401 V(EXTERNAL_UINT16_ARRAY_TYPE) \
402 V(EXTERNAL_INT32_ARRAY_TYPE) \
403 V(EXTERNAL_UINT32_ARRAY_TYPE) \
404 V(EXTERNAL_FLOAT32_ARRAY_TYPE) \
405 V(EXTERNAL_FLOAT64_ARRAY_TYPE) \
406 V(EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE) \
408 V(FIXED_INT8_ARRAY_TYPE) \
409 V(FIXED_UINT8_ARRAY_TYPE) \
410 V(FIXED_INT16_ARRAY_TYPE) \
411 V(FIXED_UINT16_ARRAY_TYPE) \
412 V(FIXED_INT32_ARRAY_TYPE) \
413 V(FIXED_UINT32_ARRAY_TYPE) \
414 V(FIXED_FLOAT32_ARRAY_TYPE) \
415 V(FIXED_FLOAT64_ARRAY_TYPE) \
416 V(FIXED_UINT8_CLAMPED_ARRAY_TYPE) \
420 V(DECLARED_ACCESSOR_DESCRIPTOR_TYPE) \
421 V(DECLARED_ACCESSOR_INFO_TYPE) \
422 V(EXECUTABLE_ACCESSOR_INFO_TYPE) \
423 V(ACCESSOR_PAIR_TYPE) \
424 V(ACCESS_CHECK_INFO_TYPE) \
425 V(INTERCEPTOR_INFO_TYPE) \
426 V(CALL_HANDLER_INFO_TYPE) \
427 V(FUNCTION_TEMPLATE_INFO_TYPE) \
428 V(OBJECT_TEMPLATE_INFO_TYPE) \
429 V(SIGNATURE_INFO_TYPE) \
430 V(TYPE_SWITCH_INFO_TYPE) \
431 V(ALLOCATION_MEMENTO_TYPE) \
432 V(ALLOCATION_SITE_TYPE) \
435 V(POLYMORPHIC_CODE_CACHE_TYPE) \
436 V(TYPE_FEEDBACK_INFO_TYPE) \
437 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
439 V(PROTOTYPE_INFO_TYPE) \
441 V(FIXED_ARRAY_TYPE) \
442 V(FIXED_DOUBLE_ARRAY_TYPE) \
443 V(SHARED_FUNCTION_INFO_TYPE) \
446 V(JS_MESSAGE_OBJECT_TYPE) \
451 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
452 V(JS_GENERATOR_OBJECT_TYPE) \
454 V(JS_GLOBAL_OBJECT_TYPE) \
455 V(JS_BUILTINS_OBJECT_TYPE) \
456 V(JS_GLOBAL_PROXY_TYPE) \
458 V(JS_ARRAY_BUFFER_TYPE) \
459 V(JS_TYPED_ARRAY_TYPE) \
460 V(JS_DATA_VIEW_TYPE) \
464 V(JS_SET_ITERATOR_TYPE) \
465 V(JS_MAP_ITERATOR_TYPE) \
466 V(JS_WEAK_MAP_TYPE) \
467 V(JS_WEAK_SET_TYPE) \
470 V(JS_FUNCTION_TYPE) \
471 V(JS_FUNCTION_PROXY_TYPE) \
473 V(BREAK_POINT_INFO_TYPE)
476 // Since string types are not consecutive, this macro is used to
477 // iterate over them.
478 #define STRING_TYPE_LIST(V) \
479 V(STRING_TYPE, kVariableSizeSentinel, string, String) \
480 V(ONE_BYTE_STRING_TYPE, kVariableSizeSentinel, one_byte_string, \
482 V(CONS_STRING_TYPE, ConsString::kSize, cons_string, ConsString) \
483 V(CONS_ONE_BYTE_STRING_TYPE, ConsString::kSize, cons_one_byte_string, \
485 V(SLICED_STRING_TYPE, SlicedString::kSize, sliced_string, SlicedString) \
486 V(SLICED_ONE_BYTE_STRING_TYPE, SlicedString::kSize, sliced_one_byte_string, \
487 SlicedOneByteString) \
488 V(EXTERNAL_STRING_TYPE, ExternalTwoByteString::kSize, external_string, \
490 V(EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kSize, \
491 external_one_byte_string, ExternalOneByteString) \
492 V(EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, ExternalTwoByteString::kSize, \
493 external_string_with_one_byte_data, ExternalStringWithOneByteData) \
494 V(SHORT_EXTERNAL_STRING_TYPE, ExternalTwoByteString::kShortSize, \
495 short_external_string, ShortExternalString) \
496 V(SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE, ExternalOneByteString::kShortSize, \
497 short_external_one_byte_string, ShortExternalOneByteString) \
498 V(SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE, \
499 ExternalTwoByteString::kShortSize, \
500 short_external_string_with_one_byte_data, \
501 ShortExternalStringWithOneByteData) \
503 V(INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, internalized_string, \
504 InternalizedString) \
505 V(ONE_BYTE_INTERNALIZED_STRING_TYPE, kVariableSizeSentinel, \
506 one_byte_internalized_string, OneByteInternalizedString) \
507 V(EXTERNAL_INTERNALIZED_STRING_TYPE, ExternalTwoByteString::kSize, \
508 external_internalized_string, ExternalInternalizedString) \
509 V(EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, ExternalOneByteString::kSize, \
510 external_one_byte_internalized_string, ExternalOneByteInternalizedString) \
511 V(EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
512 ExternalTwoByteString::kSize, \
513 external_internalized_string_with_one_byte_data, \
514 ExternalInternalizedStringWithOneByteData) \
515 V(SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE, \
516 ExternalTwoByteString::kShortSize, short_external_internalized_string, \
517 ShortExternalInternalizedString) \
518 V(SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE, \
519 ExternalOneByteString::kShortSize, \
520 short_external_one_byte_internalized_string, \
521 ShortExternalOneByteInternalizedString) \
522 V(SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE, \
523 ExternalTwoByteString::kShortSize, \
524 short_external_internalized_string_with_one_byte_data, \
525 ShortExternalInternalizedStringWithOneByteData)
527 // A struct is a simple object a set of object-valued fields. Including an
528 // object type in this causes the compiler to generate most of the boilerplate
529 // code for the class including allocation and garbage collection routines,
530 // casts and predicates. All you need to define is the class, methods and
531 // object verification routines. Easy, no?
533 // Note that for subtle reasons related to the ordering or numerical values of
534 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
536 #define STRUCT_LIST(V) \
538 V(EXECUTABLE_ACCESSOR_INFO, ExecutableAccessorInfo, \
539 executable_accessor_info) \
540 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
541 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
542 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
543 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
544 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
545 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
546 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
547 V(SCRIPT, Script, script) \
548 V(ALLOCATION_SITE, AllocationSite, allocation_site) \
549 V(ALLOCATION_MEMENTO, AllocationMemento, allocation_memento) \
550 V(CODE_CACHE, CodeCache, code_cache) \
551 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
552 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
553 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry) \
554 V(DEBUG_INFO, DebugInfo, debug_info) \
555 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info) \
556 V(PROTOTYPE_INFO, PrototypeInfo, prototype_info)
558 // We use the full 8 bits of the instance_type field to encode heap object
559 // instance types. The high-order bit (bit 7) is set if the object is not a
560 // string, and cleared if it is a string.
561 const uint32_t kIsNotStringMask = 0x80;
562 const uint32_t kStringTag = 0x0;
563 const uint32_t kNotStringTag = 0x80;
565 // Bit 6 indicates that the object is an internalized string (if set) or not.
566 // Bit 7 has to be clear as well.
567 const uint32_t kIsNotInternalizedMask = 0x40;
568 const uint32_t kNotInternalizedTag = 0x40;
569 const uint32_t kInternalizedTag = 0x0;
571 // If bit 7 is clear then bit 2 indicates whether the string consists of
572 // two-byte characters or one-byte characters.
573 const uint32_t kStringEncodingMask = 0x4;
574 const uint32_t kTwoByteStringTag = 0x0;
575 const uint32_t kOneByteStringTag = 0x4;
577 // If bit 7 is clear, the low-order 2 bits indicate the representation
579 const uint32_t kStringRepresentationMask = 0x03;
580 enum StringRepresentationTag {
582 kConsStringTag = 0x1,
583 kExternalStringTag = 0x2,
584 kSlicedStringTag = 0x3
586 const uint32_t kIsIndirectStringMask = 0x1;
587 const uint32_t kIsIndirectStringTag = 0x1;
588 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0); // NOLINT
589 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0); // NOLINT
590 STATIC_ASSERT((kConsStringTag &
591 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
592 STATIC_ASSERT((kSlicedStringTag &
593 kIsIndirectStringMask) == kIsIndirectStringTag); // NOLINT
595 // Use this mask to distinguish between cons and slice only after making
596 // sure that the string is one of the two (an indirect string).
597 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
598 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask));
600 // If bit 7 is clear, then bit 3 indicates whether this two-byte
601 // string actually contains one byte data.
602 const uint32_t kOneByteDataHintMask = 0x08;
603 const uint32_t kOneByteDataHintTag = 0x08;
605 // If bit 7 is clear and string representation indicates an external string,
606 // then bit 4 indicates whether the data pointer is cached.
607 const uint32_t kShortExternalStringMask = 0x10;
608 const uint32_t kShortExternalStringTag = 0x10;
611 // A ConsString with an empty string as the right side is a candidate
612 // for being shortcut by the garbage collector. We don't allocate any
613 // non-flat internalized strings, so we do not shortcut them thereby
614 // avoiding turning internalized strings into strings. The bit-masks
615 // below contain the internalized bit as additional safety.
616 // See heap.cc, mark-compact.cc and objects-visiting.cc.
617 const uint32_t kShortcutTypeMask =
619 kIsNotInternalizedMask |
620 kStringRepresentationMask;
621 const uint32_t kShortcutTypeTag = kConsStringTag | kNotInternalizedTag;
623 static inline bool IsShortcutCandidate(int type) {
624 return ((type & kShortcutTypeMask) == kShortcutTypeTag);
630 INTERNALIZED_STRING_TYPE =
631 kTwoByteStringTag | kSeqStringTag | kInternalizedTag,
632 ONE_BYTE_INTERNALIZED_STRING_TYPE =
633 kOneByteStringTag | kSeqStringTag | kInternalizedTag,
634 EXTERNAL_INTERNALIZED_STRING_TYPE =
635 kTwoByteStringTag | kExternalStringTag | kInternalizedTag,
636 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
637 kOneByteStringTag | kExternalStringTag | kInternalizedTag,
638 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
639 EXTERNAL_INTERNALIZED_STRING_TYPE | kOneByteDataHintTag |
641 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE = EXTERNAL_INTERNALIZED_STRING_TYPE |
642 kShortExternalStringTag |
644 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE =
645 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kShortExternalStringTag |
647 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE =
648 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
649 kShortExternalStringTag | kInternalizedTag,
650 STRING_TYPE = INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
651 ONE_BYTE_STRING_TYPE =
652 ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
653 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag | kNotInternalizedTag,
654 CONS_ONE_BYTE_STRING_TYPE =
655 kOneByteStringTag | kConsStringTag | kNotInternalizedTag,
657 kTwoByteStringTag | kSlicedStringTag | kNotInternalizedTag,
658 SLICED_ONE_BYTE_STRING_TYPE =
659 kOneByteStringTag | kSlicedStringTag | kNotInternalizedTag,
660 EXTERNAL_STRING_TYPE =
661 EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
662 EXTERNAL_ONE_BYTE_STRING_TYPE =
663 EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
664 EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
665 EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
667 SHORT_EXTERNAL_STRING_TYPE =
668 SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
669 SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE =
670 SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE | kNotInternalizedTag,
671 SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE =
672 SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE |
676 SYMBOL_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE, LAST_NAME_TYPE
678 // Objects allocated in their own spaces (never in new space).
683 // "Data", objects that cannot contain non-map-word pointers to heap
686 MUTABLE_HEAP_NUMBER_TYPE,
687 FLOAT32X4_TYPE, // FIRST_SIMD_TYPE, LAST_SIMD_TYPE
692 EXTERNAL_INT8_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
693 EXTERNAL_UINT8_ARRAY_TYPE,
694 EXTERNAL_INT16_ARRAY_TYPE,
695 EXTERNAL_UINT16_ARRAY_TYPE,
696 EXTERNAL_INT32_ARRAY_TYPE,
697 EXTERNAL_UINT32_ARRAY_TYPE,
698 EXTERNAL_FLOAT32_ARRAY_TYPE,
699 EXTERNAL_FLOAT64_ARRAY_TYPE,
700 EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
701 FIXED_INT8_ARRAY_TYPE, // FIRST_FIXED_TYPED_ARRAY_TYPE
702 FIXED_UINT8_ARRAY_TYPE,
703 FIXED_INT16_ARRAY_TYPE,
704 FIXED_UINT16_ARRAY_TYPE,
705 FIXED_INT32_ARRAY_TYPE,
706 FIXED_UINT32_ARRAY_TYPE,
707 FIXED_FLOAT32_ARRAY_TYPE,
708 FIXED_FLOAT64_ARRAY_TYPE,
709 FIXED_UINT8_CLAMPED_ARRAY_TYPE, // LAST_FIXED_TYPED_ARRAY_TYPE
710 FIXED_DOUBLE_ARRAY_TYPE,
711 FILLER_TYPE, // LAST_DATA_TYPE
714 DECLARED_ACCESSOR_DESCRIPTOR_TYPE,
715 DECLARED_ACCESSOR_INFO_TYPE,
716 EXECUTABLE_ACCESSOR_INFO_TYPE,
718 ACCESS_CHECK_INFO_TYPE,
719 INTERCEPTOR_INFO_TYPE,
720 CALL_HANDLER_INFO_TYPE,
721 FUNCTION_TEMPLATE_INFO_TYPE,
722 OBJECT_TEMPLATE_INFO_TYPE,
724 TYPE_SWITCH_INFO_TYPE,
725 ALLOCATION_SITE_TYPE,
726 ALLOCATION_MEMENTO_TYPE,
729 POLYMORPHIC_CODE_CACHE_TYPE,
730 TYPE_FEEDBACK_INFO_TYPE,
731 ALIASED_ARGUMENTS_ENTRY_TYPE,
734 BREAK_POINT_INFO_TYPE,
736 SHARED_FUNCTION_INFO_TYPE,
742 // All the following types are subtypes of JSReceiver, which corresponds to
743 // objects in the JS sense. The first and the last type in this range are
744 // the two forms of function. This organization enables using the same
745 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
746 // NONCALLABLE_JS_OBJECT range.
747 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
748 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
749 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
750 JS_MESSAGE_OBJECT_TYPE,
753 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
754 JS_GENERATOR_OBJECT_TYPE,
756 JS_GLOBAL_OBJECT_TYPE,
757 JS_BUILTINS_OBJECT_TYPE,
758 JS_GLOBAL_PROXY_TYPE,
760 JS_ARRAY_BUFFER_TYPE,
765 JS_SET_ITERATOR_TYPE,
766 JS_MAP_ITERATOR_TYPE,
770 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
774 LAST_TYPE = JS_FUNCTION_TYPE,
775 FIRST_NAME_TYPE = FIRST_TYPE,
776 LAST_NAME_TYPE = SYMBOL_TYPE,
777 FIRST_UNIQUE_NAME_TYPE = INTERNALIZED_STRING_TYPE,
778 LAST_UNIQUE_NAME_TYPE = SYMBOL_TYPE,
779 FIRST_NONSTRING_TYPE = SYMBOL_TYPE,
780 // Boundaries for testing for a SIMD type.
781 FIRST_SIMD_TYPE = FLOAT32X4_TYPE,
782 LAST_SIMD_TYPE = FLOAT32X4_TYPE,
783 // Boundaries for testing for an external array.
784 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_INT8_ARRAY_TYPE,
785 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_UINT8_CLAMPED_ARRAY_TYPE,
786 // Boundaries for testing for a fixed typed array.
787 FIRST_FIXED_TYPED_ARRAY_TYPE = FIXED_INT8_ARRAY_TYPE,
788 LAST_FIXED_TYPED_ARRAY_TYPE = FIXED_UINT8_CLAMPED_ARRAY_TYPE,
789 // Boundary for promotion to old space.
790 LAST_DATA_TYPE = FILLER_TYPE,
791 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
792 // Note that there is no range for JSObject or JSProxy, since their subtypes
793 // are not continuous in this enum! The enum ranges instead reflect the
794 // external class names, where proxies are treated as either ordinary objects,
796 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
797 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
798 // Boundaries for testing the types represented as JSObject
799 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
800 LAST_JS_OBJECT_TYPE = LAST_TYPE,
801 // Boundaries for testing the types represented as JSProxy
802 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
803 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
804 // Boundaries for testing whether the type is a JavaScript object.
805 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
806 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
807 // Boundaries for testing the types for which typeof is "object".
808 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
809 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
810 // Note that the types for which typeof is "function" are not continuous.
811 // Define this so that we can put assertions on discrete checks.
812 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
815 const int kExternalArrayTypeCount =
816 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
818 STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
819 STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
820 STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
821 STATIC_ASSERT(FOREIGN_TYPE == Internals::kForeignType);
824 #define FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(V) \
825 V(FAST_ELEMENTS_SUB_TYPE) \
826 V(DICTIONARY_ELEMENTS_SUB_TYPE) \
827 V(FAST_PROPERTIES_SUB_TYPE) \
828 V(DICTIONARY_PROPERTIES_SUB_TYPE) \
829 V(MAP_CODE_CACHE_SUB_TYPE) \
830 V(SCOPE_INFO_SUB_TYPE) \
831 V(STRING_TABLE_SUB_TYPE) \
832 V(DESCRIPTOR_ARRAY_SUB_TYPE) \
833 V(TRANSITION_ARRAY_SUB_TYPE)
835 enum FixedArraySubInstanceType {
836 #define DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE(name) name,
837 FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE)
838 #undef DEFINE_FIXED_ARRAY_SUB_INSTANCE_TYPE
839 LAST_FIXED_ARRAY_SUB_TYPE = TRANSITION_ARRAY_SUB_TYPE
852 #define DECL_BOOLEAN_ACCESSORS(name) \
853 inline bool name() const; \
854 inline void set_##name(bool value); \
857 #define DECL_ACCESSORS(name, type) \
858 inline type* name() const; \
859 inline void set_##name(type* value, \
860 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
863 #define DECLARE_CAST(type) \
864 INLINE(static type* cast(Object* object)); \
865 INLINE(static const type* cast(const Object* object));
869 class AllocationSite;
870 class AllocationSiteCreationContext;
871 class AllocationSiteUsageContext;
874 class ElementsAccessor;
875 class FixedArrayBase;
876 class FunctionLiteral;
878 class JSBuiltinsObject;
879 class LayoutDescriptor;
880 class LookupIterator;
881 class ObjectHashTable;
884 class SafepointEntry;
885 class SharedFunctionInfo;
887 class TypeFeedbackInfo;
888 class TypeFeedbackVector;
891 // We cannot just say "class HeapType;" if it is created from a template... =8-?
892 template<class> class TypeImpl;
893 struct HeapTypeConfig;
894 typedef TypeImpl<HeapTypeConfig> HeapType;
897 // A template-ized version of the IsXXX functions.
898 template <class C> inline bool Is(Object* obj);
901 #define DECLARE_VERIFIER(Name) void Name##Verify();
903 #define DECLARE_VERIFIER(Name)
907 #define DECLARE_PRINTER(Name) void Name##Print(std::ostream& os); // NOLINT
909 #define DECLARE_PRINTER(Name)
913 #define OBJECT_TYPE_LIST(V) \
918 #define HEAP_OBJECT_TYPE_LIST(V) \
920 V(MutableHeapNumber) \
929 V(ExternalTwoByteString) \
930 V(ExternalOneByteString) \
931 V(SeqTwoByteString) \
932 V(SeqOneByteString) \
933 V(InternalizedString) \
937 V(ExternalInt8Array) \
938 V(ExternalUint8Array) \
939 V(ExternalInt16Array) \
940 V(ExternalUint16Array) \
941 V(ExternalInt32Array) \
942 V(ExternalUint32Array) \
943 V(ExternalFloat32Array) \
944 V(ExternalFloat64Array) \
945 V(ExternalUint8ClampedArray) \
946 V(FixedTypedArrayBase) \
949 V(FixedUint16Array) \
951 V(FixedUint32Array) \
953 V(FixedFloat32Array) \
954 V(FixedFloat64Array) \
955 V(FixedUint8ClampedArray) \
961 V(JSContextExtensionObject) \
962 V(JSGeneratorObject) \
964 V(LayoutDescriptor) \
968 V(TypeFeedbackVector) \
969 V(DeoptimizationInputData) \
970 V(DeoptimizationOutputData) \
974 V(FixedDoubleArray) \
978 V(ScriptContextTable) \
984 V(SharedFunctionInfo) \
993 V(JSArrayBufferView) \
1002 V(JSWeakCollection) \
1009 V(JSFunctionResultCache) \
1010 V(NormalizedMapCache) \
1011 V(CompilationCacheTable) \
1012 V(CodeCacheHashTable) \
1013 V(PolymorphicCodeCacheHashTable) \
1018 V(JSBuiltinsObject) \
1020 V(UndetectableObject) \
1021 V(AccessCheckNeeded) \
1025 V(ObjectHashTable) \
1027 V(WeakValueHashTable) \
1030 // Object is the abstract superclass for all classes in the
1031 // object hierarchy.
1032 // Object does not use any virtual functions to avoid the
1033 // allocation of the C++ vtable.
1034 // Since both Smi and HeapObject are subclasses of Object no
1035 // data members can be present in Object.
1039 bool IsObject() const { return true; }
1041 #define IS_TYPE_FUNCTION_DECL(type_) INLINE(bool Is##type_() const);
1042 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1043 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
1044 #undef IS_TYPE_FUNCTION_DECL
1046 // A non-keyed store is of the form a.x = foo or a["x"] = foo whereas
1047 // a keyed store is of the form a[expression] = foo.
1048 enum StoreFromKeyed {
1049 MAY_BE_STORE_FROM_KEYED,
1050 CERTAINLY_NOT_STORE_FROM_KEYED
1053 INLINE(bool IsFixedArrayBase() const);
1054 INLINE(bool IsExternal() const);
1055 INLINE(bool IsAccessorInfo() const);
1057 INLINE(bool IsStruct() const);
1058 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) \
1059 INLINE(bool Is##Name() const);
1060 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
1061 #undef DECLARE_STRUCT_PREDICATE
1063 INLINE(bool IsSpecObject()) const;
1064 INLINE(bool IsSpecFunction()) const;
1065 INLINE(bool IsTemplateInfo()) const;
1066 INLINE(bool IsNameDictionary() const);
1067 INLINE(bool IsGlobalDictionary() const);
1068 INLINE(bool IsSeededNumberDictionary() const);
1069 INLINE(bool IsUnseededNumberDictionary() const);
1070 INLINE(bool IsOrderedHashSet() const);
1071 INLINE(bool IsOrderedHashMap() const);
1072 bool IsCallable() const;
1073 static bool IsPromise(Handle<Object> object);
1076 INLINE(bool IsUndefined() const);
1077 INLINE(bool IsNull() const);
1078 INLINE(bool IsTheHole() const);
1079 INLINE(bool IsException() const);
1080 INLINE(bool IsUninitialized() const);
1081 INLINE(bool IsTrue() const);
1082 INLINE(bool IsFalse() const);
1083 INLINE(bool IsArgumentsMarker() const);
1085 // Filler objects (fillers and free space objects).
1086 INLINE(bool IsFiller() const);
1088 // Extract the number.
1089 inline double Number();
1090 INLINE(bool IsNaN() const);
1091 INLINE(bool IsMinusZero() const);
1092 bool ToInt32(int32_t* value);
1093 bool ToUint32(uint32_t* value);
1095 inline Representation OptimalRepresentation() {
1096 if (!FLAG_track_fields) return Representation::Tagged();
1098 return Representation::Smi();
1099 } else if (FLAG_track_double_fields && IsHeapNumber()) {
1100 return Representation::Double();
1101 } else if (FLAG_track_computed_fields && IsUninitialized()) {
1102 return Representation::None();
1103 } else if (FLAG_track_heap_object_fields) {
1104 DCHECK(IsHeapObject());
1105 return Representation::HeapObject();
1107 return Representation::Tagged();
1111 inline ElementsKind OptimalElementsKind() {
1112 if (IsSmi()) return FAST_SMI_ELEMENTS;
1113 if (IsNumber()) return FAST_DOUBLE_ELEMENTS;
1114 return FAST_ELEMENTS;
1117 inline bool FitsRepresentation(Representation representation) {
1118 if (FLAG_track_fields && representation.IsNone()) {
1120 } else if (FLAG_track_fields && representation.IsSmi()) {
1122 } else if (FLAG_track_double_fields && representation.IsDouble()) {
1123 return IsMutableHeapNumber() || IsNumber();
1124 } else if (FLAG_track_heap_object_fields && representation.IsHeapObject()) {
1125 return IsHeapObject();
1130 // Checks whether two valid primitive encodings of a property name resolve to
1131 // the same logical property. E.g., the smi 1, the string "1" and the double
1132 // 1 all refer to the same property, so this helper will return true.
1133 inline bool KeyEquals(Object* other);
1135 Handle<HeapType> OptimalType(Isolate* isolate, Representation representation);
1137 inline static Handle<Object> NewStorageFor(Isolate* isolate,
1138 Handle<Object> object,
1139 Representation representation);
1141 inline static Handle<Object> WrapForRead(Isolate* isolate,
1142 Handle<Object> object,
1143 Representation representation);
1145 // Returns true if the object is of the correct type to be used as a
1146 // implementation of a JSObject's elements.
1147 inline bool HasValidElements();
1149 inline bool HasSpecificClassOf(String* name);
1151 bool BooleanValue(); // ECMA-262 9.2.
1153 // Convert to a JSObject if needed.
1154 // native_context is used when creating wrapper object.
1155 static inline MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1156 Handle<Object> object);
1157 static MaybeHandle<JSReceiver> ToObject(Isolate* isolate,
1158 Handle<Object> object,
1159 Handle<Context> context);
1161 MUST_USE_RESULT static MaybeHandle<Object> GetProperty(
1162 LookupIterator* it, LanguageMode language_mode = SLOPPY);
1164 // Implementation of [[Put]], ECMA-262 5th edition, section 8.12.5.
1165 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1166 Handle<Object> object, Handle<Name> name, Handle<Object> value,
1167 LanguageMode language_mode,
1168 StoreFromKeyed store_mode = MAY_BE_STORE_FROM_KEYED);
1170 MUST_USE_RESULT static MaybeHandle<Object> SetProperty(
1171 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1172 StoreFromKeyed store_mode);
1174 MUST_USE_RESULT static MaybeHandle<Object> SetSuperProperty(
1175 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1176 StoreFromKeyed store_mode);
1178 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1179 LookupIterator* it, LanguageMode language_mode);
1180 MUST_USE_RESULT static MaybeHandle<Object> ReadAbsentProperty(
1181 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1182 LanguageMode language_mode);
1183 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1184 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1185 MUST_USE_RESULT static MaybeHandle<Object> WriteToReadOnlyProperty(
1186 Isolate* isolate, Handle<Object> receiver, Handle<Object> name,
1187 Handle<Object> value, LanguageMode language_mode);
1188 MUST_USE_RESULT static MaybeHandle<Object> RedefineNonconfigurableProperty(
1189 Isolate* isolate, Handle<Object> name, Handle<Object> value,
1190 LanguageMode language_mode);
1191 MUST_USE_RESULT static MaybeHandle<Object> SetDataProperty(
1192 LookupIterator* it, Handle<Object> value);
1193 MUST_USE_RESULT static MaybeHandle<Object> AddDataProperty(
1194 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1195 LanguageMode language_mode, StoreFromKeyed store_mode);
1196 MUST_USE_RESULT static inline MaybeHandle<Object> GetPropertyOrElement(
1197 Handle<Object> object, Handle<Name> name,
1198 LanguageMode language_mode = SLOPPY);
1199 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1200 Isolate* isolate, Handle<Object> object, const char* key,
1201 LanguageMode language_mode = SLOPPY);
1202 MUST_USE_RESULT static inline MaybeHandle<Object> GetProperty(
1203 Handle<Object> object, Handle<Name> name,
1204 LanguageMode language_mode = SLOPPY);
1206 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithAccessor(
1207 LookupIterator* it, LanguageMode language_mode);
1208 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithAccessor(
1209 LookupIterator* it, Handle<Object> value, LanguageMode language_mode);
1211 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithDefinedGetter(
1212 Handle<Object> receiver,
1213 Handle<JSReceiver> getter);
1214 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithDefinedSetter(
1215 Handle<Object> receiver,
1216 Handle<JSReceiver> setter,
1217 Handle<Object> value);
1219 MUST_USE_RESULT static inline MaybeHandle<Object> GetElement(
1220 Isolate* isolate, Handle<Object> object, uint32_t index,
1221 LanguageMode language_mode = SLOPPY);
1223 MUST_USE_RESULT static inline MaybeHandle<Object> SetElement(
1224 Isolate* isolate, Handle<Object> object, uint32_t index,
1225 Handle<Object> value, LanguageMode language_mode);
1227 static inline Handle<Object> GetPrototypeSkipHiddenPrototypes(
1228 Isolate* isolate, Handle<Object> receiver);
1230 // Returns the permanent hash code associated with this object. May return
1231 // undefined if not yet created.
1234 // Returns undefined for JSObjects, but returns the hash code for simple
1235 // objects. This avoids a double lookup in the cases where we know we will
1236 // add the hash to the JSObject if it does not already exist.
1237 Object* GetSimpleHash();
1239 // Returns the permanent hash code associated with this object depending on
1240 // the actual object type. May create and store a hash code if needed and none
1242 static Handle<Smi> GetOrCreateHash(Isolate* isolate, Handle<Object> object);
1244 // Checks whether this object has the same value as the given one. This
1245 // function is implemented according to ES5, section 9.12 and can be used
1246 // to implement the Harmony "egal" function.
1247 bool SameValue(Object* other);
1249 // Checks whether this object has the same value as the given one.
1250 // +0 and -0 are treated equal. Everything else is the same as SameValue.
1251 // This function is implemented according to ES6, section 7.2.4 and is used
1252 // by ES6 Map and Set.
1253 bool SameValueZero(Object* other);
1255 // Tries to convert an object to an array length. Returns true and sets the
1256 // output parameter if it succeeds.
1257 inline bool ToArrayLength(uint32_t* index);
1259 // Tries to convert an object to an array index. Returns true and sets the
1260 // output parameter if it succeeds. Equivalent to ToArrayLength, but does not
1261 // allow kMaxUInt32.
1262 inline bool ToArrayIndex(uint32_t* index);
1264 // Returns true if this is a JSValue containing a string and the index is
1265 // < the length of the string. Used to implement [] on strings.
1266 inline bool IsStringObjectWithCharacterAt(uint32_t index);
1268 DECLARE_VERIFIER(Object)
1270 // Verify a pointer is a valid object pointer.
1271 static void VerifyPointer(Object* p);
1274 inline void VerifyApiCallResultType();
1276 // Prints this object without details.
1277 void ShortPrint(FILE* out = stdout);
1279 // Prints this object without details to a message accumulator.
1280 void ShortPrint(StringStream* accumulator);
1282 void ShortPrint(std::ostream& os); // NOLINT
1284 DECLARE_CAST(Object)
1286 // Layout description.
1287 static const int kHeaderSize = 0; // Object does not take up any space.
1290 // For our gdb macros, we should perhaps change these in the future.
1293 // Prints this object with details.
1294 void Print(std::ostream& os); // NOLINT
1296 void Print() { ShortPrint(); }
1297 void Print(std::ostream& os) { ShortPrint(os); } // NOLINT
1301 friend class LookupIterator;
1302 friend class PrototypeIterator;
1304 // Return the map of the root of object's prototype chain.
1305 Map* GetRootMap(Isolate* isolate);
1307 // Helper for SetProperty and SetSuperProperty.
1308 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyInternal(
1309 LookupIterator* it, Handle<Object> value, LanguageMode language_mode,
1310 StoreFromKeyed store_mode, bool* found);
1312 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
1317 explicit Brief(const Object* const v) : value(v) {}
1318 const Object* value;
1322 std::ostream& operator<<(std::ostream& os, const Brief& v);
1325 // Smi represents integer Numbers that can be stored in 31 bits.
1326 // Smis are immediate which means they are NOT allocated in the heap.
1327 // The this pointer has the following format: [31 bit signed int] 0
1328 // For long smis it has the following format:
1329 // [32 bit signed int] [31 bits zero padding] 0
1330 // Smi stands for small integer.
1331 class Smi: public Object {
1333 // Returns the integer value.
1334 inline int value() const;
1336 // Convert a value to a Smi object.
1337 static inline Smi* FromInt(int value);
1339 static inline Smi* FromIntptr(intptr_t value);
1341 // Returns whether value can be represented in a Smi.
1342 static inline bool IsValid(intptr_t value);
1346 // Dispatched behavior.
1347 void SmiPrint(std::ostream& os) const; // NOLINT
1348 DECLARE_VERIFIER(Smi)
1350 static const int kMinValue =
1351 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1352 static const int kMaxValue = -(kMinValue + 1);
1355 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1359 // Heap objects typically have a map pointer in their first word. However,
1360 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1361 // encoded in the first word. The class MapWord is an abstraction of the
1362 // value in a heap object's first word.
1363 class MapWord BASE_EMBEDDED {
1365 // Normal state: the map word contains a map pointer.
1367 // Create a map word from a map pointer.
1368 static inline MapWord FromMap(const Map* map);
1370 // View this map word as a map pointer.
1371 inline Map* ToMap();
1374 // Scavenge collection: the map word of live objects in the from space
1375 // contains a forwarding address (a heap object pointer in the to space).
1377 // True if this map word is a forwarding address for a scavenge
1378 // collection. Only valid during a scavenge collection (specifically,
1379 // when all map words are heap object pointers, i.e. not during a full GC).
1380 inline bool IsForwardingAddress();
1382 // Create a map word from a forwarding address.
1383 static inline MapWord FromForwardingAddress(HeapObject* object);
1385 // View this map word as a forwarding address.
1386 inline HeapObject* ToForwardingAddress();
1388 static inline MapWord FromRawValue(uintptr_t value) {
1389 return MapWord(value);
1392 inline uintptr_t ToRawValue() {
1397 // HeapObject calls the private constructor and directly reads the value.
1398 friend class HeapObject;
1400 explicit MapWord(uintptr_t value) : value_(value) {}
1406 // The content of an heap object (except for the map pointer). kTaggedValues
1407 // objects can contain both heap pointers and Smis, kMixedValues can contain
1408 // heap pointers, Smis, and raw values (e.g. doubles or strings), and kRawValues
1409 // objects can contain raw values and Smis.
1410 enum class HeapObjectContents { kTaggedValues, kMixedValues, kRawValues };
1413 // HeapObject is the superclass for all classes describing heap allocated
1415 class HeapObject: public Object {
1417 // [map]: Contains a map which contains the object's reflective
1419 inline Map* map() const;
1420 inline void set_map(Map* value);
1421 // The no-write-barrier version. This is OK if the object is white and in
1422 // new space, or if the value is an immortal immutable object, like the maps
1423 // of primitive (non-JS) objects like strings, heap numbers etc.
1424 inline void set_map_no_write_barrier(Map* value);
1426 // Get the map using acquire load.
1427 inline Map* synchronized_map();
1428 inline MapWord synchronized_map_word() const;
1430 // Set the map using release store
1431 inline void synchronized_set_map(Map* value);
1432 inline void synchronized_set_map_no_write_barrier(Map* value);
1433 inline void synchronized_set_map_word(MapWord map_word);
1435 // During garbage collection, the map word of a heap object does not
1436 // necessarily contain a map pointer.
1437 inline MapWord map_word() const;
1438 inline void set_map_word(MapWord map_word);
1440 // The Heap the object was allocated in. Used also to access Isolate.
1441 inline Heap* GetHeap() const;
1443 // Convenience method to get current isolate.
1444 inline Isolate* GetIsolate() const;
1446 // Converts an address to a HeapObject pointer.
1447 static inline HeapObject* FromAddress(Address address);
1449 // Returns the address of this HeapObject.
1450 inline Address address();
1452 // Iterates over pointers contained in the object (including the Map)
1453 void Iterate(ObjectVisitor* v);
1455 // Iterates over all pointers contained in the object except the
1456 // first map pointer. The object type is given in the first
1457 // parameter. This function does not access the map pointer in the
1458 // object, and so is safe to call while the map pointer is modified.
1459 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1461 // Returns the heap object's size in bytes
1464 // Indicates what type of values this heap object may contain.
1465 inline HeapObjectContents ContentType();
1467 // Given a heap object's map pointer, returns the heap size in bytes
1468 // Useful when the map pointer field is used for other purposes.
1470 inline int SizeFromMap(Map* map);
1472 // Returns the field at offset in obj, as a read/write Object* reference.
1473 // Does no checking, and is safe to use during GC, while maps are invalid.
1474 // Does not invoke write barrier, so should only be assigned to
1475 // during marking GC.
1476 static inline Object** RawField(HeapObject* obj, int offset);
1478 // Adds the |code| object related to |name| to the code cache of this map. If
1479 // this map is a dictionary map that is shared, the map copied and installed
1481 static void UpdateMapCodeCache(Handle<HeapObject> object,
1485 DECLARE_CAST(HeapObject)
1487 // Return the write barrier mode for this. Callers of this function
1488 // must be able to present a reference to an DisallowHeapAllocation
1489 // object as a sign that they are not going to use this function
1490 // from code that allocates and thus invalidates the returned write
1492 inline WriteBarrierMode GetWriteBarrierMode(
1493 const DisallowHeapAllocation& promise);
1495 // Dispatched behavior.
1496 void HeapObjectShortPrint(std::ostream& os); // NOLINT
1498 void PrintHeader(std::ostream& os, const char* id); // NOLINT
1500 DECLARE_PRINTER(HeapObject)
1501 DECLARE_VERIFIER(HeapObject)
1503 inline void VerifyObjectField(int offset);
1504 inline void VerifySmiField(int offset);
1506 // Verify a pointer is a valid HeapObject pointer that points to object
1507 // areas in the heap.
1508 static void VerifyHeapPointer(Object* p);
1511 inline AllocationAlignment RequiredAlignment();
1513 // Layout description.
1514 // First field in a heap object is map.
1515 static const int kMapOffset = Object::kHeaderSize;
1516 static const int kHeaderSize = kMapOffset + kPointerSize;
1518 STATIC_ASSERT(kMapOffset == Internals::kHeapObjectMapOffset);
1521 // helpers for calling an ObjectVisitor to iterate over pointers in the
1522 // half-open range [start, end) specified as integer offsets
1523 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1524 // as above, for the single element at "offset"
1525 inline void IteratePointer(ObjectVisitor* v, int offset);
1526 // as above, for the next code link of a code object.
1527 inline void IterateNextCodeLink(ObjectVisitor* v, int offset);
1530 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1534 // This class describes a body of an object of a fixed size
1535 // in which all pointer fields are located in the [start_offset, end_offset)
1537 template<int start_offset, int end_offset, int size>
1538 class FixedBodyDescriptor {
1540 static const int kStartOffset = start_offset;
1541 static const int kEndOffset = end_offset;
1542 static const int kSize = size;
1544 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1546 template<typename StaticVisitor>
1547 static inline void IterateBody(HeapObject* obj) {
1548 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1549 HeapObject::RawField(obj, end_offset));
1554 // This class describes a body of an object of a variable size
1555 // in which all pointer fields are located in the [start_offset, object_size)
1557 template<int start_offset>
1558 class FlexibleBodyDescriptor {
1560 static const int kStartOffset = start_offset;
1562 static inline void IterateBody(HeapObject* obj,
1566 template<typename StaticVisitor>
1567 static inline void IterateBody(HeapObject* obj, int object_size) {
1568 StaticVisitor::VisitPointers(HeapObject::RawField(obj, start_offset),
1569 HeapObject::RawField(obj, object_size));
1574 // The HeapNumber class describes heap allocated numbers that cannot be
1575 // represented in a Smi (small integer)
1576 class HeapNumber: public HeapObject {
1578 // [value]: number value.
1579 inline double value() const;
1580 inline void set_value(double value);
1582 DECLARE_CAST(HeapNumber)
1584 // Dispatched behavior.
1585 bool HeapNumberBooleanValue();
1587 void HeapNumberPrint(std::ostream& os); // NOLINT
1588 DECLARE_VERIFIER(HeapNumber)
1590 inline int get_exponent();
1591 inline int get_sign();
1593 // Layout description.
1594 static const int kValueOffset = HeapObject::kHeaderSize;
1595 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1596 // is a mixture of sign, exponent and mantissa. The offsets of two 32 bit
1597 // words within double numbers are endian dependent and they are set
1599 #if defined(V8_TARGET_LITTLE_ENDIAN)
1600 static const int kMantissaOffset = kValueOffset;
1601 static const int kExponentOffset = kValueOffset + 4;
1602 #elif defined(V8_TARGET_BIG_ENDIAN)
1603 static const int kMantissaOffset = kValueOffset + 4;
1604 static const int kExponentOffset = kValueOffset;
1606 #error Unknown byte ordering
1609 static const int kSize = kValueOffset + kDoubleSize;
1610 static const uint32_t kSignMask = 0x80000000u;
1611 static const uint32_t kExponentMask = 0x7ff00000u;
1612 static const uint32_t kMantissaMask = 0xfffffu;
1613 static const int kMantissaBits = 52;
1614 static const int kExponentBits = 11;
1615 static const int kExponentBias = 1023;
1616 static const int kExponentShift = 20;
1617 static const int kInfinityOrNanExponent =
1618 (kExponentMask >> kExponentShift) - kExponentBias;
1619 static const int kMantissaBitsInTopWord = 20;
1620 static const int kNonMantissaBitsInTopWord = 12;
1623 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1627 // The Float32x4 class describes heap allocated SIMD values holding 4 32-bit
1629 class Float32x4 : public HeapObject {
1631 inline float get_lane(int lane) const;
1632 inline void set_lane(int lane, float value);
1634 DECLARE_CAST(Float32x4)
1636 // Dispatched behavior.
1637 void Float32x4Print(std::ostream& os); // NOLINT
1638 DECLARE_VERIFIER(Float32x4)
1640 // Layout description.
1641 static const int kValueOffset = HeapObject::kHeaderSize;
1642 static const int kSize = kValueOffset + kSimd128Size;
1645 DISALLOW_IMPLICIT_CONSTRUCTORS(Float32x4);
1649 enum EnsureElementsMode {
1650 DONT_ALLOW_DOUBLE_ELEMENTS,
1651 ALLOW_COPIED_DOUBLE_ELEMENTS,
1652 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1656 // Indicator for one component of an AccessorPair.
1657 enum AccessorComponent {
1663 // JSReceiver includes types on which properties can be defined, i.e.,
1664 // JSObject and JSProxy.
1665 class JSReceiver: public HeapObject {
1667 DECLARE_CAST(JSReceiver)
1669 // Implementation of [[HasProperty]], ECMA-262 5th edition, section 8.12.6.
1670 MUST_USE_RESULT static inline Maybe<bool> HasProperty(
1671 Handle<JSReceiver> object, Handle<Name> name);
1672 MUST_USE_RESULT static inline Maybe<bool> HasOwnProperty(Handle<JSReceiver>,
1674 MUST_USE_RESULT static inline Maybe<bool> HasElement(
1675 Handle<JSReceiver> object, uint32_t index);
1676 MUST_USE_RESULT static inline Maybe<bool> HasOwnElement(
1677 Handle<JSReceiver> object, uint32_t index);
1679 // Implementation of [[Delete]], ECMA-262 5th edition, section 8.12.7.
1680 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyOrElement(
1681 Handle<JSReceiver> object, Handle<Name> name,
1682 LanguageMode language_mode = SLOPPY);
1683 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1684 Handle<JSReceiver> object, Handle<Name> name,
1685 LanguageMode language_mode = SLOPPY);
1686 MUST_USE_RESULT static MaybeHandle<Object> DeleteProperty(
1687 LookupIterator* it, LanguageMode language_mode);
1688 MUST_USE_RESULT static MaybeHandle<Object> DeleteElement(
1689 Handle<JSReceiver> object, uint32_t index,
1690 LanguageMode language_mode = SLOPPY);
1692 // Tests for the fast common case for property enumeration.
1693 bool IsSimpleEnum();
1695 // Returns the class name ([[Class]] property in the specification).
1696 String* class_name();
1698 // Returns the constructor name (the name (possibly, inferred name) of the
1699 // function that was used to instantiate the object).
1700 String* constructor_name();
1702 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetPropertyAttributes(
1703 Handle<JSReceiver> object, Handle<Name> name);
1704 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1705 GetOwnPropertyAttributes(Handle<JSReceiver> object, Handle<Name> name);
1707 MUST_USE_RESULT static inline Maybe<PropertyAttributes> GetElementAttributes(
1708 Handle<JSReceiver> object, uint32_t index);
1709 MUST_USE_RESULT static inline Maybe<PropertyAttributes>
1710 GetOwnElementAttributes(Handle<JSReceiver> object, uint32_t index);
1712 MUST_USE_RESULT static Maybe<PropertyAttributes> GetPropertyAttributes(
1713 LookupIterator* it);
1716 static Handle<Object> GetDataProperty(Handle<JSReceiver> object,
1718 static Handle<Object> GetDataProperty(LookupIterator* it);
1721 // Retrieves a permanent object identity hash code. The undefined value might
1722 // be returned in case no hash was created yet.
1723 inline Object* GetIdentityHash();
1725 // Retrieves a permanent object identity hash code. May create and store a
1726 // hash code if needed and none exists.
1727 inline static Handle<Smi> GetOrCreateIdentityHash(
1728 Handle<JSReceiver> object);
1730 enum KeyCollectionType { OWN_ONLY, INCLUDE_PROTOS };
1732 // Computes the enumerable keys for a JSObject. Used for implementing
1733 // "for (n in object) { }".
1734 MUST_USE_RESULT static MaybeHandle<FixedArray> GetKeys(
1735 Handle<JSReceiver> object,
1736 KeyCollectionType type);
1739 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1743 // The JSObject describes real heap allocated JavaScript objects with
1745 // Note that the map of JSObject changes during execution to enable inline
1747 class JSObject: public JSReceiver {
1749 // [properties]: Backing storage for properties.
1750 // properties is a FixedArray in the fast case and a Dictionary in the
1752 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1753 inline void initialize_properties();
1754 inline bool HasFastProperties();
1755 // Gets slow properties for non-global objects.
1756 inline NameDictionary* property_dictionary();
1757 // Gets global object properties.
1758 inline GlobalDictionary* global_dictionary();
1760 // [elements]: The elements (properties with names that are integers).
1762 // Elements can be in two general modes: fast and slow. Each mode
1763 // corrensponds to a set of object representations of elements that
1764 // have something in common.
1766 // In the fast mode elements is a FixedArray and so each element can
1767 // be quickly accessed. This fact is used in the generated code. The
1768 // elements array can have one of three maps in this mode:
1769 // fixed_array_map, sloppy_arguments_elements_map or
1770 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1771 // the elements array may be shared by a few objects and so before
1772 // writing to any element the array must be copied. Use
1773 // EnsureWritableFastElements in this case.
1775 // In the slow mode the elements is either a NumberDictionary, an
1776 // ExternalArray, or a FixedArray parameter map for a (sloppy)
1777 // arguments object.
1778 DECL_ACCESSORS(elements, FixedArrayBase)
1779 inline void initialize_elements();
1780 static void ResetElements(Handle<JSObject> object);
1781 static inline void SetMapAndElements(Handle<JSObject> object,
1783 Handle<FixedArrayBase> elements);
1784 inline ElementsKind GetElementsKind();
1785 ElementsAccessor* GetElementsAccessor();
1786 // Returns true if an object has elements of FAST_SMI_ELEMENTS ElementsKind.
1787 inline bool HasFastSmiElements();
1788 // Returns true if an object has elements of FAST_ELEMENTS ElementsKind.
1789 inline bool HasFastObjectElements();
1790 // Returns true if an object has elements of FAST_ELEMENTS or
1791 // FAST_SMI_ONLY_ELEMENTS.
1792 inline bool HasFastSmiOrObjectElements();
1793 // Returns true if an object has any of the fast elements kinds.
1794 inline bool HasFastElements();
1795 // Returns true if an object has elements of FAST_DOUBLE_ELEMENTS
1797 inline bool HasFastDoubleElements();
1798 // Returns true if an object has elements of FAST_HOLEY_*_ELEMENTS
1800 inline bool HasFastHoleyElements();
1801 inline bool HasSloppyArgumentsElements();
1802 inline bool HasDictionaryElements();
1804 inline bool HasExternalUint8ClampedElements();
1805 inline bool HasExternalArrayElements();
1806 inline bool HasExternalInt8Elements();
1807 inline bool HasExternalUint8Elements();
1808 inline bool HasExternalInt16Elements();
1809 inline bool HasExternalUint16Elements();
1810 inline bool HasExternalInt32Elements();
1811 inline bool HasExternalUint32Elements();
1812 inline bool HasExternalFloat32Elements();
1813 inline bool HasExternalFloat64Elements();
1815 inline bool HasFixedTypedArrayElements();
1817 inline bool HasFixedUint8ClampedElements();
1818 inline bool HasFixedArrayElements();
1819 inline bool HasFixedInt8Elements();
1820 inline bool HasFixedUint8Elements();
1821 inline bool HasFixedInt16Elements();
1822 inline bool HasFixedUint16Elements();
1823 inline bool HasFixedInt32Elements();
1824 inline bool HasFixedUint32Elements();
1825 inline bool HasFixedFloat32Elements();
1826 inline bool HasFixedFloat64Elements();
1828 inline bool HasFastArgumentsElements();
1829 inline bool HasSlowArgumentsElements();
1830 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1832 // Requires: HasFastElements().
1833 static Handle<FixedArray> EnsureWritableFastElements(
1834 Handle<JSObject> object);
1836 // Collects elements starting at index 0.
1837 // Undefined values are placed after non-undefined values.
1838 // Returns the number of non-undefined values.
1839 static Handle<Object> PrepareElementsForSort(Handle<JSObject> object,
1841 // As PrepareElementsForSort, but only on objects where elements is
1842 // a dictionary, and it will stay a dictionary. Collates undefined and
1843 // unexisting elements below limit from position zero of the elements.
1844 static Handle<Object> PrepareSlowElementsForSort(Handle<JSObject> object,
1847 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithInterceptor(
1848 LookupIterator* it, Handle<Object> value);
1850 // SetLocalPropertyIgnoreAttributes converts callbacks to fields. We need to
1851 // grant an exemption to ExecutableAccessor callbacks in some cases.
1852 enum ExecutableAccessorInfoHandling { DEFAULT_HANDLING, DONT_FORCE_FIELD };
1854 MUST_USE_RESULT static MaybeHandle<Object> DefineOwnPropertyIgnoreAttributes(
1855 LookupIterator* it, Handle<Object> value, PropertyAttributes attributes,
1856 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1858 MUST_USE_RESULT static MaybeHandle<Object> SetOwnPropertyIgnoreAttributes(
1859 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1860 PropertyAttributes attributes,
1861 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1863 MUST_USE_RESULT static MaybeHandle<Object> SetOwnElementIgnoreAttributes(
1864 Handle<JSObject> object, uint32_t index, Handle<Object> value,
1865 PropertyAttributes attributes,
1866 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1868 // Equivalent to one of the above depending on whether |name| can be converted
1869 // to an array index.
1870 MUST_USE_RESULT static MaybeHandle<Object>
1871 DefinePropertyOrElementIgnoreAttributes(
1872 Handle<JSObject> object, Handle<Name> name, Handle<Object> value,
1873 PropertyAttributes attributes = NONE,
1874 ExecutableAccessorInfoHandling handling = DEFAULT_HANDLING);
1876 // Adds or reconfigures a property to attributes NONE. It will fail when it
1878 MUST_USE_RESULT static Maybe<bool> CreateDataProperty(LookupIterator* it,
1879 Handle<Object> value);
1881 static void AddProperty(Handle<JSObject> object, Handle<Name> name,
1882 Handle<Object> value, PropertyAttributes attributes);
1884 MUST_USE_RESULT static MaybeHandle<Object> AddDataElement(
1885 Handle<JSObject> receiver, uint32_t index, Handle<Object> value,
1886 PropertyAttributes attributes);
1888 // Extend the receiver with a single fast property appeared first in the
1889 // passed map. This also extends the property backing store if necessary.
1890 static void AllocateStorageForMap(Handle<JSObject> object, Handle<Map> map);
1892 // Migrates the given object to a map whose field representations are the
1893 // lowest upper bound of all known representations for that field.
1894 static void MigrateInstance(Handle<JSObject> instance);
1896 // Migrates the given object only if the target map is already available,
1897 // or returns false if such a map is not yet available.
1898 static bool TryMigrateInstance(Handle<JSObject> instance);
1900 // Sets the property value in a normalized object given (key, value, details).
1901 // Handles the special representation of JS global objects.
1902 static void SetNormalizedProperty(Handle<JSObject> object, Handle<Name> name,
1903 Handle<Object> value,
1904 PropertyDetails details);
1905 static void SetDictionaryElement(Handle<JSObject> object, uint32_t index,
1906 Handle<Object> value,
1907 PropertyAttributes attributes);
1908 static void SetDictionaryArgumentsElement(Handle<JSObject> object,
1910 Handle<Object> value,
1911 PropertyAttributes attributes);
1913 static void OptimizeAsPrototype(Handle<JSObject> object,
1914 PrototypeOptimizationMode mode);
1915 static void ReoptimizeIfPrototype(Handle<JSObject> object);
1916 static void LazyRegisterPrototypeUser(Handle<Map> user, Isolate* isolate);
1917 static bool RegisterPrototypeUserIfNotRegistered(Handle<JSObject> prototype,
1918 Handle<HeapObject> user,
1920 static bool UnregisterPrototypeUser(Handle<JSObject> prototype,
1921 Handle<HeapObject> user);
1922 static void InvalidatePrototypeChains(Map* map);
1924 // Retrieve interceptors.
1925 InterceptorInfo* GetNamedInterceptor();
1926 InterceptorInfo* GetIndexedInterceptor();
1928 // Used from JSReceiver.
1929 MUST_USE_RESULT static Maybe<PropertyAttributes>
1930 GetPropertyAttributesWithInterceptor(LookupIterator* it);
1931 MUST_USE_RESULT static Maybe<PropertyAttributes>
1932 GetPropertyAttributesWithFailedAccessCheck(LookupIterator* it);
1934 // Retrieves an AccessorPair property from the given object. Might return
1935 // undefined if the property doesn't exist or is of a different kind.
1936 MUST_USE_RESULT static MaybeHandle<Object> GetAccessor(
1937 Handle<JSObject> object,
1939 AccessorComponent component);
1941 // Defines an AccessorPair property on the given object.
1942 // TODO(mstarzinger): Rename to SetAccessor().
1943 static MaybeHandle<Object> DefineAccessor(Handle<JSObject> object,
1945 Handle<Object> getter,
1946 Handle<Object> setter,
1947 PropertyAttributes attributes);
1949 // Defines an AccessorInfo property on the given object.
1950 MUST_USE_RESULT static MaybeHandle<Object> SetAccessor(
1951 Handle<JSObject> object,
1952 Handle<AccessorInfo> info);
1954 // The result must be checked first for exceptions. If there's no exception,
1955 // the output parameter |done| indicates whether the interceptor has a result
1957 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithInterceptor(
1958 LookupIterator* it, bool* done);
1960 // Accessors for hidden properties object.
1962 // Hidden properties are not own properties of the object itself.
1963 // Instead they are stored in an auxiliary structure kept as an own
1964 // property with a special name Heap::hidden_string(). But if the
1965 // receiver is a JSGlobalProxy then the auxiliary object is a property
1966 // of its prototype, and if it's a detached proxy, then you can't have
1967 // hidden properties.
1969 // Sets a hidden property on this object. Returns this object if successful,
1970 // undefined if called on a detached proxy.
1971 static Handle<Object> SetHiddenProperty(Handle<JSObject> object,
1973 Handle<Object> value);
1974 // Gets the value of a hidden property with the given key. Returns the hole
1975 // if the property doesn't exist (or if called on a detached proxy),
1976 // otherwise returns the value set for the key.
1977 Object* GetHiddenProperty(Handle<Name> key);
1978 // Deletes a hidden property. Deleting a non-existing property is
1979 // considered successful.
1980 static void DeleteHiddenProperty(Handle<JSObject> object,
1982 // Returns true if the object has a property with the hidden string as name.
1983 static bool HasHiddenProperties(Handle<JSObject> object);
1985 static void SetIdentityHash(Handle<JSObject> object, Handle<Smi> hash);
1987 static void ValidateElements(Handle<JSObject> object);
1989 // Makes sure that this object can contain HeapObject as elements.
1990 static inline void EnsureCanContainHeapObjectElements(Handle<JSObject> obj);
1992 // Makes sure that this object can contain the specified elements.
1993 static inline void EnsureCanContainElements(
1994 Handle<JSObject> object,
1997 EnsureElementsMode mode);
1998 static inline void EnsureCanContainElements(
1999 Handle<JSObject> object,
2000 Handle<FixedArrayBase> elements,
2002 EnsureElementsMode mode);
2003 static void EnsureCanContainElements(
2004 Handle<JSObject> object,
2005 Arguments* arguments,
2008 EnsureElementsMode mode);
2010 // Would we convert a fast elements array to dictionary mode given
2011 // an access at key?
2012 bool WouldConvertToSlowElements(uint32_t index);
2014 // Computes the new capacity when expanding the elements of a JSObject.
2015 static uint32_t NewElementsCapacity(uint32_t old_capacity) {
2016 // (old_capacity + 50%) + 16
2017 return old_capacity + (old_capacity >> 1) + 16;
2020 // These methods do not perform access checks!
2021 static void UpdateAllocationSite(Handle<JSObject> object,
2022 ElementsKind to_kind);
2024 // Lookup interceptors are used for handling properties controlled by host
2026 inline bool HasNamedInterceptor();
2027 inline bool HasIndexedInterceptor();
2029 // Computes the enumerable keys from interceptors. Used for debug mirrors and
2030 // by JSReceiver::GetKeys.
2031 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForNamedInterceptor(
2032 Handle<JSObject> object,
2033 Handle<JSReceiver> receiver);
2034 MUST_USE_RESULT static MaybeHandle<JSObject> GetKeysForIndexedInterceptor(
2035 Handle<JSObject> object,
2036 Handle<JSReceiver> receiver);
2038 // Support functions for v8 api (needed for correct interceptor behavior).
2039 MUST_USE_RESULT static Maybe<bool> HasRealNamedProperty(
2040 Handle<JSObject> object, Handle<Name> name);
2041 MUST_USE_RESULT static Maybe<bool> HasRealElementProperty(
2042 Handle<JSObject> object, uint32_t index);
2043 MUST_USE_RESULT static Maybe<bool> HasRealNamedCallbackProperty(
2044 Handle<JSObject> object, Handle<Name> name);
2046 // Get the header size for a JSObject. Used to compute the index of
2047 // internal fields as well as the number of internal fields.
2048 inline int GetHeaderSize();
2050 inline int GetInternalFieldCount();
2051 inline int GetInternalFieldOffset(int index);
2052 inline Object* GetInternalField(int index);
2053 inline void SetInternalField(int index, Object* value);
2054 inline void SetInternalField(int index, Smi* value);
2056 // Returns the number of properties on this object filtering out properties
2057 // with the specified attributes (ignoring interceptors).
2058 int NumberOfOwnProperties(PropertyAttributes filter = NONE);
2059 // Fill in details for properties into storage starting at the specified
2060 // index. Returns the number of properties added.
2061 int GetOwnPropertyNames(FixedArray* storage, int index,
2062 PropertyAttributes filter = NONE);
2064 // Returns the number of properties on this object filtering out properties
2065 // with the specified attributes (ignoring interceptors).
2066 int NumberOfOwnElements(PropertyAttributes filter);
2067 // Returns the number of enumerable elements (ignoring interceptors).
2068 int NumberOfEnumElements();
2069 // Returns the number of elements on this object filtering out elements
2070 // with the specified attributes (ignoring interceptors).
2071 int GetOwnElementKeys(FixedArray* storage, PropertyAttributes filter);
2072 // Count and fill in the enumerable elements into storage.
2073 // (storage->length() == NumberOfEnumElements()).
2074 // If storage is NULL, will count the elements without adding
2075 // them to any storage.
2076 // Returns the number of enumerable elements.
2077 int GetEnumElementKeys(FixedArray* storage);
2079 static Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
2082 // Returns a new map with all transitions dropped from the object's current
2083 // map and the ElementsKind set.
2084 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
2085 ElementsKind to_kind);
2086 static void TransitionElementsKind(Handle<JSObject> object,
2087 ElementsKind to_kind);
2089 // Always use this to migrate an object to a new map.
2090 // |expected_additional_properties| is only used for fast-to-slow transitions
2091 // and ignored otherwise.
2092 static void MigrateToMap(Handle<JSObject> object, Handle<Map> new_map,
2093 int expected_additional_properties = 0);
2095 // Convert the object to use the canonical dictionary
2096 // representation. If the object is expected to have additional properties
2097 // added this number can be indicated to have the backing store allocated to
2098 // an initial capacity for holding these properties.
2099 static void NormalizeProperties(Handle<JSObject> object,
2100 PropertyNormalizationMode mode,
2101 int expected_additional_properties,
2102 const char* reason);
2104 // Convert and update the elements backing store to be a
2105 // SeededNumberDictionary dictionary. Returns the backing after conversion.
2106 static Handle<SeededNumberDictionary> NormalizeElements(
2107 Handle<JSObject> object);
2109 void RequireSlowElements(SeededNumberDictionary* dictionary);
2111 // Transform slow named properties to fast variants.
2112 static void MigrateSlowToFast(Handle<JSObject> object,
2113 int unused_property_fields, const char* reason);
2115 inline bool IsUnboxedDoubleField(FieldIndex index);
2117 // Access fast-case object properties at index.
2118 static Handle<Object> FastPropertyAt(Handle<JSObject> object,
2119 Representation representation,
2121 inline Object* RawFastPropertyAt(FieldIndex index);
2122 inline double RawFastDoublePropertyAt(FieldIndex index);
2124 inline void FastPropertyAtPut(FieldIndex index, Object* value);
2125 inline void RawFastPropertyAtPut(FieldIndex index, Object* value);
2126 inline void RawFastDoublePropertyAtPut(FieldIndex index, double value);
2127 inline void WriteToField(int descriptor, Object* value);
2129 // Access to in object properties.
2130 inline int GetInObjectPropertyOffset(int index);
2131 inline Object* InObjectPropertyAt(int index);
2132 inline Object* InObjectPropertyAtPut(int index,
2134 WriteBarrierMode mode
2135 = UPDATE_WRITE_BARRIER);
2137 // Set the object's prototype (only JSReceiver and null are allowed values).
2138 MUST_USE_RESULT static MaybeHandle<Object> SetPrototype(
2139 Handle<JSObject> object, Handle<Object> value, bool from_javascript);
2141 // Initializes the body after properties slot, properties slot is
2142 // initialized by set_properties. Fill the pre-allocated fields with
2143 // pre_allocated_value and the rest with filler_value.
2144 // Note: this call does not update write barrier, the caller is responsible
2145 // to ensure that |filler_value| can be collected without WB here.
2146 inline void InitializeBody(Map* map,
2147 Object* pre_allocated_value,
2148 Object* filler_value);
2150 // Check whether this object references another object
2151 bool ReferencesObject(Object* obj);
2153 // Disalow further properties to be added to the oject.
2154 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensions(
2155 Handle<JSObject> object);
2157 bool IsExtensible();
2160 MUST_USE_RESULT static MaybeHandle<Object> Seal(Handle<JSObject> object);
2162 // ES5 Object.freeze
2163 MUST_USE_RESULT static MaybeHandle<Object> Freeze(Handle<JSObject> object);
2165 // Called the first time an object is observed with ES7 Object.observe.
2166 static void SetObserved(Handle<JSObject> object);
2169 enum DeepCopyHints { kNoHints = 0, kObjectIsShallow = 1 };
2171 MUST_USE_RESULT static MaybeHandle<JSObject> DeepCopy(
2172 Handle<JSObject> object,
2173 AllocationSiteUsageContext* site_context,
2174 DeepCopyHints hints = kNoHints);
2175 MUST_USE_RESULT static MaybeHandle<JSObject> DeepWalk(
2176 Handle<JSObject> object,
2177 AllocationSiteCreationContext* site_context);
2179 DECLARE_CAST(JSObject)
2181 // Dispatched behavior.
2182 void JSObjectShortPrint(StringStream* accumulator);
2183 DECLARE_PRINTER(JSObject)
2184 DECLARE_VERIFIER(JSObject)
2186 void PrintProperties(std::ostream& os); // NOLINT
2187 void PrintElements(std::ostream& os); // NOLINT
2189 #if defined(DEBUG) || defined(OBJECT_PRINT)
2190 void PrintTransitions(std::ostream& os); // NOLINT
2193 static void PrintElementsTransition(
2194 FILE* file, Handle<JSObject> object,
2195 ElementsKind from_kind, Handle<FixedArrayBase> from_elements,
2196 ElementsKind to_kind, Handle<FixedArrayBase> to_elements);
2198 void PrintInstanceMigration(FILE* file, Map* original_map, Map* new_map);
2201 // Structure for collecting spill information about JSObjects.
2202 class SpillInformation {
2206 int number_of_objects_;
2207 int number_of_objects_with_fast_properties_;
2208 int number_of_objects_with_fast_elements_;
2209 int number_of_fast_used_fields_;
2210 int number_of_fast_unused_fields_;
2211 int number_of_slow_used_properties_;
2212 int number_of_slow_unused_properties_;
2213 int number_of_fast_used_elements_;
2214 int number_of_fast_unused_elements_;
2215 int number_of_slow_used_elements_;
2216 int number_of_slow_unused_elements_;
2219 void IncrementSpillStatistics(SpillInformation* info);
2223 // If a GC was caused while constructing this object, the elements pointer
2224 // may point to a one pointer filler map. The object won't be rooted, but
2225 // our heap verification code could stumble across it.
2226 bool ElementsAreSafeToExamine();
2229 Object* SlowReverseLookup(Object* value);
2231 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2232 // Also maximal value of JSArray's length property.
2233 static const uint32_t kMaxElementCount = 0xffffffffu;
2235 // Constants for heuristics controlling conversion of fast elements
2236 // to slow elements.
2238 // Maximal gap that can be introduced by adding an element beyond
2239 // the current elements length.
2240 static const uint32_t kMaxGap = 1024;
2242 // Maximal length of fast elements array that won't be checked for
2243 // being dense enough on expansion.
2244 static const int kMaxUncheckedFastElementsLength = 5000;
2246 // Same as above but for old arrays. This limit is more strict. We
2247 // don't want to be wasteful with long lived objects.
2248 static const int kMaxUncheckedOldFastElementsLength = 500;
2250 // Note that Page::kMaxRegularHeapObjectSize puts a limit on
2251 // permissible values (see the DCHECK in heap.cc).
2252 static const int kInitialMaxFastElementArray = 100000;
2254 // This constant applies only to the initial map of "global.Object" and
2255 // not to arbitrary other JSObject maps.
2256 static const int kInitialGlobalObjectUnusedPropertiesCount = 4;
2258 static const int kMaxInstanceSize = 255 * kPointerSize;
2259 // When extending the backing storage for property values, we increase
2260 // its size by more than the 1 entry necessary, so sequentially adding fields
2261 // to the same object requires fewer allocations and copies.
2262 static const int kFieldsAdded = 3;
2264 // Layout description.
2265 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2266 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2267 static const int kHeaderSize = kElementsOffset + kPointerSize;
2269 STATIC_ASSERT(kHeaderSize == Internals::kJSObjectHeaderSize);
2271 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2273 static inline int SizeOf(Map* map, HeapObject* object);
2276 Context* GetCreationContext();
2278 // Enqueue change record for Object.observe. May cause GC.
2279 MUST_USE_RESULT static MaybeHandle<Object> EnqueueChangeRecord(
2280 Handle<JSObject> object, const char* type, Handle<Name> name,
2281 Handle<Object> old_value);
2283 // Gets the number of currently used elements.
2284 int GetFastElementsUsage();
2286 // Deletes an existing named property in a normalized object.
2287 static void DeleteNormalizedProperty(Handle<JSObject> object,
2288 Handle<Name> name, int entry);
2290 static bool AllCanRead(LookupIterator* it);
2291 static bool AllCanWrite(LookupIterator* it);
2294 friend class JSReceiver;
2295 friend class Object;
2297 static void MigrateFastToFast(Handle<JSObject> object, Handle<Map> new_map);
2298 static void MigrateFastToSlow(Handle<JSObject> object,
2299 Handle<Map> new_map,
2300 int expected_additional_properties);
2302 // Used from Object::GetProperty().
2303 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithFailedAccessCheck(
2304 LookupIterator* it);
2306 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithFailedAccessCheck(
2307 LookupIterator* it, Handle<Object> value);
2309 // Add a property to a slow-case object.
2310 static void AddSlowProperty(Handle<JSObject> object,
2312 Handle<Object> value,
2313 PropertyAttributes attributes);
2315 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithInterceptor(
2316 LookupIterator* it);
2318 bool ReferencesObjectFromElements(FixedArray* elements,
2322 // Return the hash table backing store or the inline stored identity hash,
2323 // whatever is found.
2324 MUST_USE_RESULT Object* GetHiddenPropertiesHashTable();
2326 // Return the hash table backing store for hidden properties. If there is no
2327 // backing store, allocate one.
2328 static Handle<ObjectHashTable> GetOrCreateHiddenPropertiesHashtable(
2329 Handle<JSObject> object);
2331 // Set the hidden property backing store to either a hash table or
2332 // the inline-stored identity hash.
2333 static Handle<Object> SetHiddenPropertiesHashTable(
2334 Handle<JSObject> object,
2335 Handle<Object> value);
2337 MUST_USE_RESULT Object* GetIdentityHash();
2339 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSObject> object);
2341 static Handle<SeededNumberDictionary> GetNormalizedElementDictionary(
2342 Handle<JSObject> object, Handle<FixedArrayBase> elements);
2344 // Helper for fast versions of preventExtensions, seal, and freeze.
2345 // attrs is one of NONE, SEALED, or FROZEN (depending on the operation).
2346 template <PropertyAttributes attrs>
2347 MUST_USE_RESULT static MaybeHandle<Object> PreventExtensionsWithTransition(
2348 Handle<JSObject> object);
2350 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2354 // Common superclass for FixedArrays that allow implementations to share
2355 // common accessors and some code paths.
2356 class FixedArrayBase: public HeapObject {
2358 // [length]: length of the array.
2359 inline int length() const;
2360 inline void set_length(int value);
2362 // Get and set the length using acquire loads and release stores.
2363 inline int synchronized_length() const;
2364 inline void synchronized_set_length(int value);
2366 DECLARE_CAST(FixedArrayBase)
2368 // Layout description.
2369 // Length is smi tagged when it is stored.
2370 static const int kLengthOffset = HeapObject::kHeaderSize;
2371 static const int kHeaderSize = kLengthOffset + kPointerSize;
2375 class FixedDoubleArray;
2376 class IncrementalMarking;
2379 // FixedArray describes fixed-sized arrays with element type Object*.
2380 class FixedArray: public FixedArrayBase {
2382 // Setter and getter for elements.
2383 inline Object* get(int index) const;
2384 void SetValue(uint32_t index, Object* value);
2385 static inline Handle<Object> get(Handle<FixedArray> array, int index);
2386 // Setter that uses write barrier.
2387 inline void set(int index, Object* value);
2388 inline bool is_the_hole(int index);
2390 // Setter that doesn't need write barrier.
2391 inline void set(int index, Smi* value);
2392 // Setter with explicit barrier mode.
2393 inline void set(int index, Object* value, WriteBarrierMode mode);
2395 // Setters for frequently used oddballs located in old space.
2396 inline void set_undefined(int index);
2397 inline void set_null(int index);
2398 inline void set_the_hole(int index);
2400 inline Object** GetFirstElementAddress();
2401 inline bool ContainsOnlySmisOrHoles();
2403 // Gives access to raw memory which stores the array's data.
2404 inline Object** data_start();
2406 inline void FillWithHoles(int from, int to);
2408 // Shrink length and insert filler objects.
2409 void Shrink(int length);
2412 static Handle<FixedArray> CopySize(Handle<FixedArray> array,
2414 PretenureFlag pretenure = NOT_TENURED);
2416 enum KeyFilter { ALL_KEYS, NON_SYMBOL_KEYS };
2418 // Add the elements of a JSArray to this FixedArray.
2419 MUST_USE_RESULT static MaybeHandle<FixedArray> AddKeysFromArrayLike(
2420 Handle<FixedArray> content, Handle<JSObject> array,
2421 KeyFilter filter = ALL_KEYS);
2423 // Computes the union of keys and return the result.
2424 // Used for implementing "for (n in object) { }"
2425 MUST_USE_RESULT static MaybeHandle<FixedArray> UnionOfKeys(
2426 Handle<FixedArray> first,
2427 Handle<FixedArray> second);
2429 // Copy a sub array from the receiver to dest.
2430 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2432 // Garbage collection support.
2433 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2435 // Code Generation support.
2436 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2438 // Garbage collection support.
2439 Object** RawFieldOfElementAt(int index) {
2440 return HeapObject::RawField(this, OffsetOfElementAt(index));
2443 DECLARE_CAST(FixedArray)
2445 // Maximal allowed size, in bytes, of a single FixedArray.
2446 // Prevents overflowing size computations, as well as extreme memory
2448 static const int kMaxSize = 128 * MB * kPointerSize;
2449 // Maximally allowed length of a FixedArray.
2450 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2452 // Dispatched behavior.
2453 DECLARE_PRINTER(FixedArray)
2454 DECLARE_VERIFIER(FixedArray)
2456 // Checks if two FixedArrays have identical contents.
2457 bool IsEqualTo(FixedArray* other);
2460 // Swap two elements in a pair of arrays. If this array and the
2461 // numbers array are the same object, the elements are only swapped
2463 void SwapPairs(FixedArray* numbers, int i, int j);
2465 // Sort prefix of this array and the numbers array as pairs wrt. the
2466 // numbers. If the numbers array and the this array are the same
2467 // object, the prefix of this array is sorted.
2468 void SortPairs(FixedArray* numbers, uint32_t len);
2470 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2472 static inline int SizeOf(Map* map, HeapObject* object) {
2474 reinterpret_cast<FixedArray*>(object)->synchronized_length());
2479 // Set operation on FixedArray without using write barriers. Can
2480 // only be used for storing old space objects or smis.
2481 static inline void NoWriteBarrierSet(FixedArray* array,
2485 // Set operation on FixedArray without incremental write barrier. Can
2486 // only be used if the object is guaranteed to be white (whiteness witness
2488 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2493 STATIC_ASSERT(kHeaderSize == Internals::kFixedArrayHeaderSize);
2495 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2499 // FixedDoubleArray describes fixed-sized arrays with element type double.
2500 class FixedDoubleArray: public FixedArrayBase {
2502 // Setter and getter for elements.
2503 inline double get_scalar(int index);
2504 inline uint64_t get_representation(int index);
2505 static inline Handle<Object> get(Handle<FixedDoubleArray> array, int index);
2506 // This accessor has to get a Number as |value|.
2507 void SetValue(uint32_t index, Object* value);
2508 inline void set(int index, double value);
2509 inline void set_the_hole(int index);
2511 // Checking for the hole.
2512 inline bool is_the_hole(int index);
2514 // Garbage collection support.
2515 inline static int SizeFor(int length) {
2516 return kHeaderSize + length * kDoubleSize;
2519 // Gives access to raw memory which stores the array's data.
2520 inline double* data_start();
2522 inline void FillWithHoles(int from, int to);
2524 // Code Generation support.
2525 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2527 DECLARE_CAST(FixedDoubleArray)
2529 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2530 // Prevents overflowing size computations, as well as extreme memory
2532 static const int kMaxSize = 512 * MB;
2533 // Maximally allowed length of a FixedArray.
2534 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2536 // Dispatched behavior.
2537 DECLARE_PRINTER(FixedDoubleArray)
2538 DECLARE_VERIFIER(FixedDoubleArray)
2541 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2545 class WeakFixedArray : public FixedArray {
2547 enum SearchForDuplicates { kAlwaysAdd, kAddIfNotFound };
2549 // If |maybe_array| is not a WeakFixedArray, a fresh one will be allocated.
2550 static Handle<WeakFixedArray> Add(
2551 Handle<Object> maybe_array, Handle<HeapObject> value,
2552 SearchForDuplicates search_for_duplicates = kAlwaysAdd,
2553 bool* was_present = NULL);
2555 // Returns true if an entry was found and removed.
2556 bool Remove(Handle<HeapObject> value);
2560 inline Object* Get(int index) const;
2561 inline void Clear(int index);
2562 inline int Length() const;
2564 inline bool IsEmptySlot(int index) const;
2565 static Object* Empty() { return Smi::FromInt(0); }
2567 DECLARE_CAST(WeakFixedArray)
2570 static const int kLastUsedIndexIndex = 0;
2571 static const int kFirstIndex = 1;
2573 static Handle<WeakFixedArray> Allocate(
2574 Isolate* isolate, int size, Handle<WeakFixedArray> initialize_from);
2576 static void Set(Handle<WeakFixedArray> array, int index,
2577 Handle<HeapObject> value);
2578 inline void clear(int index);
2580 inline int last_used_index() const;
2581 inline void set_last_used_index(int index);
2583 // Disallow inherited setters.
2584 void set(int index, Smi* value);
2585 void set(int index, Object* value);
2586 void set(int index, Object* value, WriteBarrierMode mode);
2587 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakFixedArray);
2591 // Generic array grows dynamically with O(1) amortized insertion.
2592 class ArrayList : public FixedArray {
2596 // Use this if GC can delete elements from the array.
2597 kReloadLengthAfterAllocation,
2599 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj,
2600 AddMode mode = kNone);
2601 static Handle<ArrayList> Add(Handle<ArrayList> array, Handle<Object> obj1,
2602 Handle<Object> obj2, AddMode = kNone);
2603 inline int Length();
2604 inline void SetLength(int length);
2605 inline Object* Get(int index);
2606 inline Object** Slot(int index);
2607 inline void Set(int index, Object* obj);
2608 inline void Clear(int index, Object* undefined);
2609 DECLARE_CAST(ArrayList)
2612 static Handle<ArrayList> EnsureSpace(Handle<ArrayList> array, int length);
2613 static const int kLengthIndex = 0;
2614 static const int kFirstIndex = 1;
2615 DISALLOW_IMPLICIT_CONSTRUCTORS(ArrayList);
2619 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2620 // The format of the these objects is:
2621 // [0]: Number of descriptors
2622 // [1]: Either Smi(0) if uninitialized, or a pointer to small fixed array:
2623 // [0]: pointer to fixed array with enum cache
2624 // [1]: either Smi(0) or pointer to fixed array with indices
2626 // [2 + number of descriptors * kDescriptorSize]: start of slack
2627 class DescriptorArray: public FixedArray {
2629 // Returns true for both shared empty_descriptor_array and for smis, which the
2630 // map uses to encode additional bit fields when the descriptor array is not
2632 inline bool IsEmpty();
2634 // Returns the number of descriptors in the array.
2635 int number_of_descriptors() {
2636 DCHECK(length() >= kFirstIndex || IsEmpty());
2638 return len == 0 ? 0 : Smi::cast(get(kDescriptorLengthIndex))->value();
2641 int number_of_descriptors_storage() {
2643 return len == 0 ? 0 : (len - kFirstIndex) / kDescriptorSize;
2646 int NumberOfSlackDescriptors() {
2647 return number_of_descriptors_storage() - number_of_descriptors();
2650 inline void SetNumberOfDescriptors(int number_of_descriptors);
2651 inline int number_of_entries() { return number_of_descriptors(); }
2653 bool HasEnumCache() {
2654 return !IsEmpty() && !get(kEnumCacheIndex)->IsSmi();
2657 void CopyEnumCacheFrom(DescriptorArray* array) {
2658 set(kEnumCacheIndex, array->get(kEnumCacheIndex));
2661 FixedArray* GetEnumCache() {
2662 DCHECK(HasEnumCache());
2663 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2664 return FixedArray::cast(bridge->get(kEnumCacheBridgeCacheIndex));
2667 bool HasEnumIndicesCache() {
2668 if (IsEmpty()) return false;
2669 Object* object = get(kEnumCacheIndex);
2670 if (object->IsSmi()) return false;
2671 FixedArray* bridge = FixedArray::cast(object);
2672 return !bridge->get(kEnumCacheBridgeIndicesCacheIndex)->IsSmi();
2675 FixedArray* GetEnumIndicesCache() {
2676 DCHECK(HasEnumIndicesCache());
2677 FixedArray* bridge = FixedArray::cast(get(kEnumCacheIndex));
2678 return FixedArray::cast(bridge->get(kEnumCacheBridgeIndicesCacheIndex));
2681 Object** GetEnumCacheSlot() {
2682 DCHECK(HasEnumCache());
2683 return HeapObject::RawField(reinterpret_cast<HeapObject*>(this),
2687 void ClearEnumCache();
2689 // Initialize or change the enum cache,
2690 // using the supplied storage for the small "bridge".
2691 void SetEnumCache(FixedArray* bridge_storage,
2692 FixedArray* new_cache,
2693 Object* new_index_cache);
2695 bool CanHoldValue(int descriptor, Object* value);
2697 // Accessors for fetching instance descriptor at descriptor number.
2698 inline Name* GetKey(int descriptor_number);
2699 inline Object** GetKeySlot(int descriptor_number);
2700 inline Object* GetValue(int descriptor_number);
2701 inline void SetValue(int descriptor_number, Object* value);
2702 inline Object** GetValueSlot(int descriptor_number);
2703 static inline int GetValueOffset(int descriptor_number);
2704 inline Object** GetDescriptorStartSlot(int descriptor_number);
2705 inline Object** GetDescriptorEndSlot(int descriptor_number);
2706 inline PropertyDetails GetDetails(int descriptor_number);
2707 inline PropertyType GetType(int descriptor_number);
2708 inline int GetFieldIndex(int descriptor_number);
2709 inline HeapType* GetFieldType(int descriptor_number);
2710 inline Object* GetConstant(int descriptor_number);
2711 inline Object* GetCallbacksObject(int descriptor_number);
2712 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2714 inline Name* GetSortedKey(int descriptor_number);
2715 inline int GetSortedKeyIndex(int descriptor_number);
2716 inline void SetSortedKey(int pointer, int descriptor_number);
2717 inline void SetRepresentation(int descriptor_number,
2718 Representation representation);
2720 // Accessor for complete descriptor.
2721 inline void Get(int descriptor_number, Descriptor* desc);
2722 inline void Set(int descriptor_number, Descriptor* desc);
2723 void Replace(int descriptor_number, Descriptor* descriptor);
2725 // Append automatically sets the enumeration index. This should only be used
2726 // to add descriptors in bulk at the end, followed by sorting the descriptor
2728 inline void Append(Descriptor* desc);
2730 static Handle<DescriptorArray> CopyUpTo(Handle<DescriptorArray> desc,
2731 int enumeration_index,
2734 static Handle<DescriptorArray> CopyUpToAddAttributes(
2735 Handle<DescriptorArray> desc,
2736 int enumeration_index,
2737 PropertyAttributes attributes,
2740 // Sort the instance descriptors by the hash codes of their keys.
2743 // Search the instance descriptors for given name.
2744 INLINE(int Search(Name* name, int number_of_own_descriptors));
2746 // As the above, but uses DescriptorLookupCache and updates it when
2748 INLINE(int SearchWithCache(Name* name, Map* map));
2750 // Allocates a DescriptorArray, but returns the singleton
2751 // empty descriptor array object if number_of_descriptors is 0.
2752 static Handle<DescriptorArray> Allocate(Isolate* isolate,
2753 int number_of_descriptors,
2756 DECLARE_CAST(DescriptorArray)
2758 // Constant for denoting key was not found.
2759 static const int kNotFound = -1;
2761 static const int kDescriptorLengthIndex = 0;
2762 static const int kEnumCacheIndex = 1;
2763 static const int kFirstIndex = 2;
2765 // The length of the "bridge" to the enum cache.
2766 static const int kEnumCacheBridgeLength = 2;
2767 static const int kEnumCacheBridgeCacheIndex = 0;
2768 static const int kEnumCacheBridgeIndicesCacheIndex = 1;
2770 // Layout description.
2771 static const int kDescriptorLengthOffset = FixedArray::kHeaderSize;
2772 static const int kEnumCacheOffset = kDescriptorLengthOffset + kPointerSize;
2773 static const int kFirstOffset = kEnumCacheOffset + kPointerSize;
2775 // Layout description for the bridge array.
2776 static const int kEnumCacheBridgeCacheOffset = FixedArray::kHeaderSize;
2778 // Layout of descriptor.
2779 static const int kDescriptorKey = 0;
2780 static const int kDescriptorDetails = 1;
2781 static const int kDescriptorValue = 2;
2782 static const int kDescriptorSize = 3;
2784 #if defined(DEBUG) || defined(OBJECT_PRINT)
2785 // For our gdb macros, we should perhaps change these in the future.
2788 // Print all the descriptors.
2789 void PrintDescriptors(std::ostream& os); // NOLINT
2793 // Is the descriptor array sorted and without duplicates?
2794 bool IsSortedNoDuplicates(int valid_descriptors = -1);
2796 // Is the descriptor array consistent with the back pointers in targets?
2797 bool IsConsistentWithBackPointers(Map* current_map);
2799 // Are two DescriptorArrays equal?
2800 bool IsEqualTo(DescriptorArray* other);
2803 // Returns the fixed array length required to hold number_of_descriptors
2805 static int LengthFor(int number_of_descriptors) {
2806 return ToKeyIndex(number_of_descriptors);
2810 // WhitenessWitness is used to prove that a descriptor array is white
2811 // (unmarked), so incremental write barriers can be skipped because the
2812 // marking invariant cannot be broken and slots pointing into evacuation
2813 // candidates will be discovered when the object is scanned. A witness is
2814 // always stack-allocated right after creating an array. By allocating a
2815 // witness, incremental marking is globally disabled. The witness is then
2816 // passed along wherever needed to statically prove that the array is known to
2818 class WhitenessWitness {
2820 inline explicit WhitenessWitness(DescriptorArray* array);
2821 inline ~WhitenessWitness();
2824 IncrementalMarking* marking_;
2827 // An entry in a DescriptorArray, represented as an (array, index) pair.
2830 inline explicit Entry(DescriptorArray* descs, int index) :
2831 descs_(descs), index_(index) { }
2833 inline PropertyType type() { return descs_->GetType(index_); }
2834 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2837 DescriptorArray* descs_;
2841 // Conversion from descriptor number to array indices.
2842 static int ToKeyIndex(int descriptor_number) {
2843 return kFirstIndex +
2844 (descriptor_number * kDescriptorSize) +
2848 static int ToDetailsIndex(int descriptor_number) {
2849 return kFirstIndex +
2850 (descriptor_number * kDescriptorSize) +
2854 static int ToValueIndex(int descriptor_number) {
2855 return kFirstIndex +
2856 (descriptor_number * kDescriptorSize) +
2860 // Transfer a complete descriptor from the src descriptor array to this
2861 // descriptor array.
2862 void CopyFrom(int index, DescriptorArray* src, const WhitenessWitness&);
2864 inline void Set(int descriptor_number,
2866 const WhitenessWitness&);
2868 // Swap first and second descriptor.
2869 inline void SwapSortedKeys(int first, int second);
2871 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2875 enum SearchMode { ALL_ENTRIES, VALID_ENTRIES };
2877 template <SearchMode search_mode, typename T>
2878 inline int Search(T* array, Name* name, int valid_entries = 0,
2879 int* out_insertion_index = NULL);
2882 // HashTable is a subclass of FixedArray that implements a hash table
2883 // that uses open addressing and quadratic probing.
2885 // In order for the quadratic probing to work, elements that have not
2886 // yet been used and elements that have been deleted are
2887 // distinguished. Probing continues when deleted elements are
2888 // encountered and stops when unused elements are encountered.
2890 // - Elements with key == undefined have not been used yet.
2891 // - Elements with key == the_hole have been deleted.
2893 // The hash table class is parameterized with a Shape and a Key.
2894 // Shape must be a class with the following interface:
2895 // class ExampleShape {
2897 // // Tells whether key matches other.
2898 // static bool IsMatch(Key key, Object* other);
2899 // // Returns the hash value for key.
2900 // static uint32_t Hash(Key key);
2901 // // Returns the hash value for object.
2902 // static uint32_t HashForObject(Key key, Object* object);
2903 // // Convert key to an object.
2904 // static inline Handle<Object> AsHandle(Isolate* isolate, Key key);
2905 // // The prefix size indicates number of elements in the beginning
2906 // // of the backing storage.
2907 // static const int kPrefixSize = ..;
2908 // // The Element size indicates number of elements per entry.
2909 // static const int kEntrySize = ..;
2911 // The prefix size indicates an amount of memory in the
2912 // beginning of the backing storage that can be used for non-element
2913 // information by subclasses.
2915 template<typename Key>
2918 static const bool UsesSeed = false;
2919 static uint32_t Hash(Key key) { return 0; }
2920 static uint32_t SeededHash(Key key, uint32_t seed) {
2924 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2925 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2927 return HashForObject(key, object);
2932 class HashTableBase : public FixedArray {
2934 // Returns the number of elements in the hash table.
2935 int NumberOfElements() {
2936 return Smi::cast(get(kNumberOfElementsIndex))->value();
2939 // Returns the number of deleted elements in the hash table.
2940 int NumberOfDeletedElements() {
2941 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2944 // Returns the capacity of the hash table.
2946 return Smi::cast(get(kCapacityIndex))->value();
2949 // ElementAdded should be called whenever an element is added to a
2951 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2953 // ElementRemoved should be called whenever an element is removed from
2955 void ElementRemoved() {
2956 SetNumberOfElements(NumberOfElements() - 1);
2957 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2959 void ElementsRemoved(int n) {
2960 SetNumberOfElements(NumberOfElements() - n);
2961 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2964 // Computes the required capacity for a table holding the given
2965 // number of elements. May be more than HashTable::kMaxCapacity.
2966 static inline int ComputeCapacity(int at_least_space_for);
2968 // Use a different heuristic to compute capacity when serializing.
2969 static inline int ComputeCapacityForSerialization(int at_least_space_for);
2971 // Tells whether k is a real key. The hole and undefined are not allowed
2972 // as keys and can be used to indicate missing or deleted elements.
2973 bool IsKey(Object* k) {
2974 return !k->IsTheHole() && !k->IsUndefined();
2977 // Compute the probe offset (quadratic probing).
2978 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2979 return (n + n * n) >> 1;
2982 static const int kNumberOfElementsIndex = 0;
2983 static const int kNumberOfDeletedElementsIndex = 1;
2984 static const int kCapacityIndex = 2;
2985 static const int kPrefixStartIndex = 3;
2987 // Constant used for denoting a absent entry.
2988 static const int kNotFound = -1;
2991 // Update the number of elements in the hash table.
2992 void SetNumberOfElements(int nof) {
2993 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2996 // Update the number of deleted elements in the hash table.
2997 void SetNumberOfDeletedElements(int nod) {
2998 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
3001 // Returns probe entry.
3002 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
3003 DCHECK(base::bits::IsPowerOfTwo32(size));
3004 return (hash + GetProbeOffset(number)) & (size - 1);
3007 inline static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
3008 return hash & (size - 1);
3011 inline static uint32_t NextProbe(
3012 uint32_t last, uint32_t number, uint32_t size) {
3013 return (last + number) & (size - 1);
3018 template <typename Derived, typename Shape, typename Key>
3019 class HashTable : public HashTableBase {
3022 inline uint32_t Hash(Key key) {
3023 if (Shape::UsesSeed) {
3024 return Shape::SeededHash(key, GetHeap()->HashSeed());
3026 return Shape::Hash(key);
3030 inline uint32_t HashForObject(Key key, Object* object) {
3031 if (Shape::UsesSeed) {
3032 return Shape::SeededHashForObject(key, GetHeap()->HashSeed(), object);
3034 return Shape::HashForObject(key, object);
3038 // Returns a new HashTable object.
3039 MUST_USE_RESULT static Handle<Derived> New(
3040 Isolate* isolate, int at_least_space_for,
3041 MinimumCapacity capacity_option = USE_DEFAULT_MINIMUM_CAPACITY,
3042 PretenureFlag pretenure = NOT_TENURED);
3044 DECLARE_CAST(HashTable)
3046 // Garbage collection support.
3047 void IteratePrefix(ObjectVisitor* visitor);
3048 void IterateElements(ObjectVisitor* visitor);
3050 // Find entry for key otherwise return kNotFound.
3051 inline int FindEntry(Key key);
3052 inline int FindEntry(Isolate* isolate, Key key, int32_t hash);
3053 int FindEntry(Isolate* isolate, Key key);
3055 // Rehashes the table in-place.
3056 void Rehash(Key key);
3058 // Returns the key at entry.
3059 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3061 static const int kElementsStartIndex = kPrefixStartIndex + Shape::kPrefixSize;
3062 static const int kEntrySize = Shape::kEntrySize;
3063 static const int kElementsStartOffset =
3064 kHeaderSize + kElementsStartIndex * kPointerSize;
3065 static const int kCapacityOffset =
3066 kHeaderSize + kCapacityIndex * kPointerSize;
3068 // Returns the index for an entry (of the key)
3069 static inline int EntryToIndex(int entry) {
3070 return (entry * kEntrySize) + kElementsStartIndex;
3074 friend class ObjectHashTable;
3076 // Find the entry at which to insert element with the given key that
3077 // has the given hash value.
3078 uint32_t FindInsertionEntry(uint32_t hash);
3080 // Attempt to shrink hash table after removal of key.
3081 MUST_USE_RESULT static Handle<Derived> Shrink(Handle<Derived> table, Key key);
3083 // Ensure enough space for n additional elements.
3084 MUST_USE_RESULT static Handle<Derived> EnsureCapacity(
3085 Handle<Derived> table,
3088 PretenureFlag pretenure = NOT_TENURED);
3090 // Sets the capacity of the hash table.
3091 void SetCapacity(int capacity) {
3092 // To scale a computed hash code to fit within the hash table, we
3093 // use bit-wise AND with a mask, so the capacity must be positive
3095 DCHECK(capacity > 0);
3096 DCHECK(capacity <= kMaxCapacity);
3097 set(kCapacityIndex, Smi::FromInt(capacity));
3100 // Maximal capacity of HashTable. Based on maximal length of underlying
3101 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
3103 static const int kMaxCapacity =
3104 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
3107 // Returns _expected_ if one of entries given by the first _probe_ probes is
3108 // equal to _expected_. Otherwise, returns the entry given by the probe
3110 uint32_t EntryForProbe(Key key, Object* k, int probe, uint32_t expected);
3112 void Swap(uint32_t entry1, uint32_t entry2, WriteBarrierMode mode);
3114 // Rehashes this hash-table into the new table.
3115 void Rehash(Handle<Derived> new_table, Key key);
3119 // HashTableKey is an abstract superclass for virtual key behavior.
3120 class HashTableKey {
3122 // Returns whether the other object matches this key.
3123 virtual bool IsMatch(Object* other) = 0;
3124 // Returns the hash value for this key.
3125 virtual uint32_t Hash() = 0;
3126 // Returns the hash value for object.
3127 virtual uint32_t HashForObject(Object* key) = 0;
3128 // Returns the key object for storing into the hash table.
3129 MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) = 0;
3131 virtual ~HashTableKey() {}
3135 class StringTableShape : public BaseShape<HashTableKey*> {
3137 static inline bool IsMatch(HashTableKey* key, Object* value) {
3138 return key->IsMatch(value);
3141 static inline uint32_t Hash(HashTableKey* key) {
3145 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
3146 return key->HashForObject(object);
3149 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
3151 static const int kPrefixSize = 0;
3152 static const int kEntrySize = 1;
3155 class SeqOneByteString;
3159 // No special elements in the prefix and the element size is 1
3160 // because only the string itself (the key) needs to be stored.
3161 class StringTable: public HashTable<StringTable,
3165 // Find string in the string table. If it is not there yet, it is
3166 // added. The return value is the string found.
3167 static Handle<String> LookupString(Isolate* isolate, Handle<String> key);
3168 static Handle<String> LookupKey(Isolate* isolate, HashTableKey* key);
3169 static String* LookupKeyIfExists(Isolate* isolate, HashTableKey* key);
3171 // Tries to internalize given string and returns string handle on success
3172 // or an empty handle otherwise.
3173 MUST_USE_RESULT static MaybeHandle<String> InternalizeStringIfExists(
3175 Handle<String> string);
3177 // Looks up a string that is equal to the given string and returns
3178 // string handle if it is found, or an empty handle otherwise.
3179 MUST_USE_RESULT static MaybeHandle<String> LookupStringIfExists(
3181 Handle<String> str);
3182 MUST_USE_RESULT static MaybeHandle<String> LookupTwoCharsStringIfExists(
3187 static void EnsureCapacityForDeserialization(Isolate* isolate, int expected);
3189 DECLARE_CAST(StringTable)
3192 template <bool seq_one_byte>
3193 friend class JsonParser;
3195 DISALLOW_IMPLICIT_CONSTRUCTORS(StringTable);
3199 template <typename Derived, typename Shape, typename Key>
3200 class Dictionary: public HashTable<Derived, Shape, Key> {
3201 typedef HashTable<Derived, Shape, Key> DerivedHashTable;
3204 // Returns the value at entry.
3205 Object* ValueAt(int entry) {
3206 return this->get(Derived::EntryToIndex(entry) + 1);
3209 // Set the value for entry.
3210 void ValueAtPut(int entry, Object* value) {
3211 this->set(Derived::EntryToIndex(entry) + 1, value);
3214 // Returns the property details for the property at entry.
3215 PropertyDetails DetailsAt(int entry) {
3216 return Shape::DetailsAt(static_cast<Derived*>(this), entry);
3219 // Set the details for entry.
3220 void DetailsAtPut(int entry, PropertyDetails value) {
3221 Shape::DetailsAtPut(static_cast<Derived*>(this), entry, value);
3224 // Returns true if property at given entry is deleted.
3225 bool IsDeleted(int entry) {
3226 return Shape::IsDeleted(static_cast<Derived*>(this), entry);
3229 // Delete a property from the dictionary.
3230 static Handle<Object> DeleteProperty(Handle<Derived> dictionary, int entry);
3232 // Attempt to shrink the dictionary after deletion of key.
3233 MUST_USE_RESULT static inline Handle<Derived> Shrink(
3234 Handle<Derived> dictionary,
3236 return DerivedHashTable::Shrink(dictionary, key);
3240 // TODO(dcarney): templatize or move to SeededNumberDictionary
3241 void CopyValuesTo(FixedArray* elements);
3243 // Returns the number of elements in the dictionary filtering out properties
3244 // with the specified attributes.
3245 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3247 // Returns the number of enumerable elements in the dictionary.
3248 int NumberOfEnumElements() {
3249 return NumberOfElementsFilterAttributes(
3250 static_cast<PropertyAttributes>(DONT_ENUM | SYMBOLIC));
3253 // Returns true if the dictionary contains any elements that are non-writable,
3254 // non-configurable, non-enumerable, or have getters/setters.
3255 bool HasComplexElements();
3257 enum SortMode { UNSORTED, SORTED };
3259 // Fill in details for properties into storage.
3260 // Returns the number of properties added.
3261 int CopyKeysTo(FixedArray* storage, int index, PropertyAttributes filter,
3262 SortMode sort_mode);
3264 // Copies enumerable keys to preallocated fixed array.
3265 void CopyEnumKeysTo(FixedArray* storage);
3267 // Accessors for next enumeration index.
3268 void SetNextEnumerationIndex(int index) {
3270 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3273 int NextEnumerationIndex() {
3274 return Smi::cast(this->get(kNextEnumerationIndexIndex))->value();
3277 // Creates a new dictionary.
3278 MUST_USE_RESULT static Handle<Derived> New(
3280 int at_least_space_for,
3281 PretenureFlag pretenure = NOT_TENURED);
3283 // Ensure enough space for n additional elements.
3284 static Handle<Derived> EnsureCapacity(Handle<Derived> obj, int n, Key key);
3287 void Print(std::ostream& os); // NOLINT
3289 // Returns the key (slow).
3290 Object* SlowReverseLookup(Object* value);
3292 // Sets the entry to (key, value) pair.
3293 inline void SetEntry(int entry,
3295 Handle<Object> value);
3296 inline void SetEntry(int entry,
3298 Handle<Object> value,
3299 PropertyDetails details);
3301 MUST_USE_RESULT static Handle<Derived> Add(
3302 Handle<Derived> dictionary,
3304 Handle<Object> value,
3305 PropertyDetails details);
3307 // Returns iteration indices array for the |dictionary|.
3308 // Values are direct indices in the |HashTable| array.
3309 static Handle<FixedArray> BuildIterationIndicesArray(
3310 Handle<Derived> dictionary);
3313 // Generic at put operation.
3314 MUST_USE_RESULT static Handle<Derived> AtPut(
3315 Handle<Derived> dictionary,
3317 Handle<Object> value);
3319 // Add entry to dictionary.
3320 static void AddEntry(
3321 Handle<Derived> dictionary,
3323 Handle<Object> value,
3324 PropertyDetails details,
3327 // Generate new enumeration indices to avoid enumeration index overflow.
3328 // Returns iteration indices array for the |dictionary|.
3329 static Handle<FixedArray> GenerateNewEnumerationIndices(
3330 Handle<Derived> dictionary);
3331 static const int kMaxNumberKeyIndex = DerivedHashTable::kPrefixStartIndex;
3332 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3336 template <typename Derived, typename Shape>
3337 class NameDictionaryBase : public Dictionary<Derived, Shape, Handle<Name> > {
3338 typedef Dictionary<Derived, Shape, Handle<Name> > DerivedDictionary;
3341 // Find entry for key, otherwise return kNotFound. Optimized version of
3342 // HashTable::FindEntry.
3343 int FindEntry(Handle<Name> key);
3347 template <typename Key>
3348 class BaseDictionaryShape : public BaseShape<Key> {
3350 template <typename Dictionary>
3351 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry) {
3352 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3353 DCHECK(entry >= 0); // Not found is -1, which is not caught by get().
3354 return PropertyDetails(
3355 Smi::cast(dict->get(Dictionary::EntryToIndex(entry) + 2)));
3358 template <typename Dictionary>
3359 static inline void DetailsAtPut(Dictionary* dict, int entry,
3360 PropertyDetails value) {
3361 STATIC_ASSERT(Dictionary::kEntrySize == 3);
3362 dict->set(Dictionary::EntryToIndex(entry) + 2, value.AsSmi());
3365 template <typename Dictionary>
3366 static bool IsDeleted(Dictionary* dict, int entry) {
3370 template <typename Dictionary>
3371 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3372 Handle<Object> value, PropertyDetails details);
3376 class NameDictionaryShape : public BaseDictionaryShape<Handle<Name> > {
3378 static inline bool IsMatch(Handle<Name> key, Object* other);
3379 static inline uint32_t Hash(Handle<Name> key);
3380 static inline uint32_t HashForObject(Handle<Name> key, Object* object);
3381 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Name> key);
3382 static const int kPrefixSize = 2;
3383 static const int kEntrySize = 3;
3384 static const bool kIsEnumerable = true;
3388 class NameDictionary
3389 : public NameDictionaryBase<NameDictionary, NameDictionaryShape> {
3390 typedef NameDictionaryBase<NameDictionary, NameDictionaryShape>
3394 DECLARE_CAST(NameDictionary)
3396 inline static Handle<FixedArray> DoGenerateNewEnumerationIndices(
3397 Handle<NameDictionary> dictionary);
3401 class GlobalDictionaryShape : public NameDictionaryShape {
3403 static const int kEntrySize = 2; // Overrides NameDictionaryShape::kEntrySize
3405 template <typename Dictionary>
3406 static inline PropertyDetails DetailsAt(Dictionary* dict, int entry);
3408 template <typename Dictionary>
3409 static inline void DetailsAtPut(Dictionary* dict, int entry,
3410 PropertyDetails value);
3412 template <typename Dictionary>
3413 static bool IsDeleted(Dictionary* dict, int entry);
3415 template <typename Dictionary>
3416 static inline void SetEntry(Dictionary* dict, int entry, Handle<Object> key,
3417 Handle<Object> value, PropertyDetails details);
3421 class GlobalDictionary
3422 : public NameDictionaryBase<GlobalDictionary, GlobalDictionaryShape> {
3424 DECLARE_CAST(GlobalDictionary)
3428 class NumberDictionaryShape : public BaseDictionaryShape<uint32_t> {
3430 static inline bool IsMatch(uint32_t key, Object* other);
3431 static inline Handle<Object> AsHandle(Isolate* isolate, uint32_t key);
3432 static const int kEntrySize = 3;
3433 static const bool kIsEnumerable = false;
3437 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3439 static const bool UsesSeed = true;
3440 static const int kPrefixSize = 2;
3442 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3443 static inline uint32_t SeededHashForObject(uint32_t key,
3449 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3451 static const int kPrefixSize = 0;
3453 static inline uint32_t Hash(uint32_t key);
3454 static inline uint32_t HashForObject(uint32_t key, Object* object);
3458 class SeededNumberDictionary
3459 : public Dictionary<SeededNumberDictionary,
3460 SeededNumberDictionaryShape,
3463 DECLARE_CAST(SeededNumberDictionary)
3465 // Type specific at put (default NONE attributes is used when adding).
3466 MUST_USE_RESULT static Handle<SeededNumberDictionary> AtNumberPut(
3467 Handle<SeededNumberDictionary> dictionary,
3469 Handle<Object> value);
3470 MUST_USE_RESULT static Handle<SeededNumberDictionary> AddNumberEntry(
3471 Handle<SeededNumberDictionary> dictionary,
3473 Handle<Object> value,
3474 PropertyDetails details);
3476 // Set an existing entry or add a new one if needed.
3477 // Return the updated dictionary.
3478 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3479 Handle<SeededNumberDictionary> dictionary,
3481 Handle<Object> value,
3482 PropertyDetails details);
3484 void UpdateMaxNumberKey(uint32_t key);
3486 // If slow elements are required we will never go back to fast-case
3487 // for the elements kept in this dictionary. We require slow
3488 // elements if an element has been added at an index larger than
3489 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3490 // when defining a getter or setter with a number key.
3491 inline bool requires_slow_elements();
3492 inline void set_requires_slow_elements();
3494 // Get the value of the max number key that has been added to this
3495 // dictionary. max_number_key can only be called if
3496 // requires_slow_elements returns false.
3497 inline uint32_t max_number_key();
3500 static const int kRequiresSlowElementsMask = 1;
3501 static const int kRequiresSlowElementsTagSize = 1;
3502 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3506 class UnseededNumberDictionary
3507 : public Dictionary<UnseededNumberDictionary,
3508 UnseededNumberDictionaryShape,
3511 DECLARE_CAST(UnseededNumberDictionary)
3513 // Type specific at put (default NONE attributes is used when adding).
3514 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AtNumberPut(
3515 Handle<UnseededNumberDictionary> dictionary,
3517 Handle<Object> value);
3518 MUST_USE_RESULT static Handle<UnseededNumberDictionary> AddNumberEntry(
3519 Handle<UnseededNumberDictionary> dictionary,
3521 Handle<Object> value);
3523 // Set an existing entry or add a new one if needed.
3524 // Return the updated dictionary.
3525 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3526 Handle<UnseededNumberDictionary> dictionary,
3528 Handle<Object> value);
3532 class ObjectHashTableShape : public BaseShape<Handle<Object> > {
3534 static inline bool IsMatch(Handle<Object> key, Object* other);
3535 static inline uint32_t Hash(Handle<Object> key);
3536 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3537 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3538 static const int kPrefixSize = 0;
3539 static const int kEntrySize = 2;
3543 // ObjectHashTable maps keys that are arbitrary objects to object values by
3544 // using the identity hash of the key for hashing purposes.
3545 class ObjectHashTable: public HashTable<ObjectHashTable,
3546 ObjectHashTableShape,
3549 ObjectHashTable, ObjectHashTableShape, Handle<Object> > DerivedHashTable;
3551 DECLARE_CAST(ObjectHashTable)
3553 // Attempt to shrink hash table after removal of key.
3554 MUST_USE_RESULT static inline Handle<ObjectHashTable> Shrink(
3555 Handle<ObjectHashTable> table,
3556 Handle<Object> key);
3558 // Looks up the value associated with the given key. The hole value is
3559 // returned in case the key is not present.
3560 Object* Lookup(Handle<Object> key);
3561 Object* Lookup(Handle<Object> key, int32_t hash);
3562 Object* Lookup(Isolate* isolate, Handle<Object> key, int32_t hash);
3564 // Adds (or overwrites) the value associated with the given key.
3565 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3567 Handle<Object> value);
3568 static Handle<ObjectHashTable> Put(Handle<ObjectHashTable> table,
3569 Handle<Object> key, Handle<Object> value,
3572 // Returns an ObjectHashTable (possibly |table|) where |key| has been removed.
3573 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3576 static Handle<ObjectHashTable> Remove(Handle<ObjectHashTable> table,
3577 Handle<Object> key, bool* was_present,
3581 friend class MarkCompactCollector;
3583 void AddEntry(int entry, Object* key, Object* value);
3584 void RemoveEntry(int entry);
3586 // Returns the index to the value of an entry.
3587 static inline int EntryToValueIndex(int entry) {
3588 return EntryToIndex(entry) + 1;
3593 // OrderedHashTable is a HashTable with Object keys that preserves
3594 // insertion order. There are Map and Set interfaces (OrderedHashMap
3595 // and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
3597 // Only Object* keys are supported, with Object::SameValueZero() used as the
3598 // equality operator and Object::GetHash() for the hash function.
3600 // Based on the "Deterministic Hash Table" as described by Jason Orendorff at
3601 // https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
3602 // Originally attributed to Tyler Close.
3605 // [0]: bucket count
3606 // [1]: element count
3607 // [2]: deleted element count
3608 // [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
3609 // offset into the data table (see below) where the
3610 // first item in this bucket is stored.
3611 // [3 + NumberOfBuckets()..length]: "data table", an array of length
3612 // Capacity() * kEntrySize, where the first entrysize
3613 // items are handled by the derived class and the
3614 // item at kChainOffset is another entry into the
3615 // data table indicating the next entry in this hash
3618 // When we transition the table to a new version we obsolete it and reuse parts
3619 // of the memory to store information how to transition an iterator to the new
3622 // Memory layout for obsolete table:
3623 // [0]: bucket count
3624 // [1]: Next newer table
3625 // [2]: Number of removed holes or -1 when the table was cleared.
3626 // [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
3627 // [3 + NumberOfRemovedHoles()..length]: Not used
3629 template<class Derived, class Iterator, int entrysize>
3630 class OrderedHashTable: public FixedArray {
3632 // Returns an OrderedHashTable with a capacity of at least |capacity|.
3633 static Handle<Derived> Allocate(
3634 Isolate* isolate, int capacity, PretenureFlag pretenure = NOT_TENURED);
3636 // Returns an OrderedHashTable (possibly |table|) with enough space
3637 // to add at least one new element.
3638 static Handle<Derived> EnsureGrowable(Handle<Derived> table);
3640 // Returns an OrderedHashTable (possibly |table|) that's shrunken
3642 static Handle<Derived> Shrink(Handle<Derived> table);
3644 // Returns a new empty OrderedHashTable and records the clearing so that
3645 // exisiting iterators can be updated.
3646 static Handle<Derived> Clear(Handle<Derived> table);
3648 int NumberOfElements() {
3649 return Smi::cast(get(kNumberOfElementsIndex))->value();
3652 int NumberOfDeletedElements() {
3653 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
3656 int UsedCapacity() { return NumberOfElements() + NumberOfDeletedElements(); }
3658 int NumberOfBuckets() {
3659 return Smi::cast(get(kNumberOfBucketsIndex))->value();
3662 // Returns an index into |this| for the given entry.
3663 int EntryToIndex(int entry) {
3664 return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
3667 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
3670 return !get(kNextTableIndex)->IsSmi();
3673 // The next newer table. This is only valid if the table is obsolete.
3674 Derived* NextTable() {
3675 return Derived::cast(get(kNextTableIndex));
3678 // When the table is obsolete we store the indexes of the removed holes.
3679 int RemovedIndexAt(int index) {
3680 return Smi::cast(get(kRemovedHolesIndex + index))->value();
3683 static const int kNotFound = -1;
3684 static const int kMinCapacity = 4;
3686 static const int kNumberOfBucketsIndex = 0;
3687 static const int kNumberOfElementsIndex = kNumberOfBucketsIndex + 1;
3688 static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
3689 static const int kHashTableStartIndex = kNumberOfDeletedElementsIndex + 1;
3690 static const int kNextTableIndex = kNumberOfElementsIndex;
3692 static const int kNumberOfBucketsOffset =
3693 kHeaderSize + kNumberOfBucketsIndex * kPointerSize;
3694 static const int kNumberOfElementsOffset =
3695 kHeaderSize + kNumberOfElementsIndex * kPointerSize;
3696 static const int kNumberOfDeletedElementsOffset =
3697 kHeaderSize + kNumberOfDeletedElementsIndex * kPointerSize;
3698 static const int kHashTableStartOffset =
3699 kHeaderSize + kHashTableStartIndex * kPointerSize;
3700 static const int kNextTableOffset =
3701 kHeaderSize + kNextTableIndex * kPointerSize;
3703 static const int kEntrySize = entrysize + 1;
3704 static const int kChainOffset = entrysize;
3706 static const int kLoadFactor = 2;
3708 // NumberOfDeletedElements is set to kClearedTableSentinel when
3709 // the table is cleared, which allows iterator transitions to
3710 // optimize that case.
3711 static const int kClearedTableSentinel = -1;
3714 static Handle<Derived> Rehash(Handle<Derived> table, int new_capacity);
3716 void SetNumberOfBuckets(int num) {
3717 set(kNumberOfBucketsIndex, Smi::FromInt(num));
3720 void SetNumberOfElements(int num) {
3721 set(kNumberOfElementsIndex, Smi::FromInt(num));
3724 void SetNumberOfDeletedElements(int num) {
3725 set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
3729 return NumberOfBuckets() * kLoadFactor;
3732 void SetNextTable(Derived* next_table) {
3733 set(kNextTableIndex, next_table);
3736 void SetRemovedIndexAt(int index, int removed_index) {
3737 return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
3740 static const int kRemovedHolesIndex = kHashTableStartIndex;
3742 static const int kMaxCapacity =
3743 (FixedArray::kMaxLength - kHashTableStartIndex)
3744 / (1 + (kEntrySize * kLoadFactor));
3748 class JSSetIterator;
3751 class OrderedHashSet: public OrderedHashTable<
3752 OrderedHashSet, JSSetIterator, 1> {
3754 DECLARE_CAST(OrderedHashSet)
3758 class JSMapIterator;
3761 class OrderedHashMap
3762 : public OrderedHashTable<OrderedHashMap, JSMapIterator, 2> {
3764 DECLARE_CAST(OrderedHashMap)
3766 Object* ValueAt(int entry) {
3767 return get(EntryToIndex(entry) + kValueOffset);
3770 static const int kValueOffset = 1;
3774 template <int entrysize>
3775 class WeakHashTableShape : public BaseShape<Handle<Object> > {
3777 static inline bool IsMatch(Handle<Object> key, Object* other);
3778 static inline uint32_t Hash(Handle<Object> key);
3779 static inline uint32_t HashForObject(Handle<Object> key, Object* object);
3780 static inline Handle<Object> AsHandle(Isolate* isolate, Handle<Object> key);
3781 static const int kPrefixSize = 0;
3782 static const int kEntrySize = entrysize;
3786 // WeakHashTable maps keys that are arbitrary heap objects to heap object
3787 // values. The table wraps the keys in weak cells and store values directly.
3788 // Thus it references keys weakly and values strongly.
3789 class WeakHashTable: public HashTable<WeakHashTable,
3790 WeakHashTableShape<2>,
3793 WeakHashTable, WeakHashTableShape<2>, Handle<Object> > DerivedHashTable;
3795 DECLARE_CAST(WeakHashTable)
3797 // Looks up the value associated with the given key. The hole value is
3798 // returned in case the key is not present.
3799 Object* Lookup(Handle<HeapObject> key);
3801 // Adds (or overwrites) the value associated with the given key. Mapping a
3802 // key to the hole value causes removal of the whole entry.
3803 MUST_USE_RESULT static Handle<WeakHashTable> Put(Handle<WeakHashTable> table,
3804 Handle<HeapObject> key,
3805 Handle<HeapObject> value);
3807 static Handle<FixedArray> GetValues(Handle<WeakHashTable> table);
3810 friend class MarkCompactCollector;
3812 void AddEntry(int entry, Handle<WeakCell> key, Handle<HeapObject> value);
3814 // Returns the index to the value of an entry.
3815 static inline int EntryToValueIndex(int entry) {
3816 return EntryToIndex(entry) + 1;
3821 class WeakValueHashTable : public ObjectHashTable {
3823 DECLARE_CAST(WeakValueHashTable)
3826 // Looks up the value associated with the given key. The hole value is
3827 // returned in case the key is not present.
3828 Object* LookupWeak(Handle<Object> key);
3831 // Adds (or overwrites) the value associated with the given key. Mapping a
3832 // key to the hole value causes removal of the whole entry.
3833 MUST_USE_RESULT static Handle<WeakValueHashTable> PutWeak(
3834 Handle<WeakValueHashTable> table, Handle<Object> key,
3835 Handle<HeapObject> value);
3837 static Handle<FixedArray> GetWeakValues(Handle<WeakValueHashTable> table);
3841 // JSFunctionResultCache caches results of some JSFunction invocation.
3842 // It is a fixed array with fixed structure:
3843 // [0]: factory function
3844 // [1]: finger index
3845 // [2]: current cache size
3846 // [3]: dummy field.
3847 // The rest of array are key/value pairs.
3848 class JSFunctionResultCache : public FixedArray {
3850 static const int kFactoryIndex = 0;
3851 static const int kFingerIndex = kFactoryIndex + 1;
3852 static const int kCacheSizeIndex = kFingerIndex + 1;
3853 static const int kDummyIndex = kCacheSizeIndex + 1;
3854 static const int kEntriesIndex = kDummyIndex + 1;
3856 static const int kEntrySize = 2; // key + value
3858 static const int kFactoryOffset = kHeaderSize;
3859 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3860 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3862 inline void MakeZeroSize();
3863 inline void Clear();
3866 inline void set_size(int size);
3867 inline int finger_index();
3868 inline void set_finger_index(int finger_index);
3870 DECLARE_CAST(JSFunctionResultCache)
3872 DECLARE_VERIFIER(JSFunctionResultCache)
3876 // ScopeInfo represents information about different scopes of a source
3877 // program and the allocation of the scope's variables. Scope information
3878 // is stored in a compressed form in ScopeInfo objects and is used
3879 // at runtime (stack dumps, deoptimization, etc.).
3881 // This object provides quick access to scope info details for runtime
3883 class ScopeInfo : public FixedArray {
3885 DECLARE_CAST(ScopeInfo)
3887 // Return the type of this scope.
3888 ScopeType scope_type();
3890 // Does this scope call eval?
3893 // Return the language mode of this scope.
3894 LanguageMode language_mode();
3896 // Does this scope make a sloppy eval call?
3897 bool CallsSloppyEval() { return CallsEval() && is_sloppy(language_mode()); }
3899 // Return the total number of locals allocated on the stack and in the
3900 // context. This includes the parameters that are allocated in the context.
3903 // Return the number of stack slots for code. This number consists of two
3905 // 1. One stack slot per stack allocated local.
3906 // 2. One stack slot for the function name if it is stack allocated.
3907 int StackSlotCount();
3909 // Return the number of context slots for code if a context is allocated. This
3910 // number consists of three parts:
3911 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3912 // 2. One context slot per context allocated local.
3913 // 3. One context slot for the function name if it is context allocated.
3914 // Parameters allocated in the context count as context allocated locals. If
3915 // no contexts are allocated for this scope ContextLength returns 0.
3916 int ContextLength();
3918 // Does this scope declare a "this" binding?
3921 // Does this scope declare a "this" binding, and the "this" binding is stack-
3922 // or context-allocated?
3923 bool HasAllocatedReceiver();
3925 // Is this scope the scope of a named function expression?
3926 bool HasFunctionName();
3928 // Return if this has context allocated locals.
3929 bool HasHeapAllocatedLocals();
3931 // Return if contexts are allocated for this scope.
3934 // Return if this is a function scope with "use asm".
3935 bool IsAsmModule() { return AsmModuleField::decode(Flags()); }
3937 // Return if this is a nested function within an asm module scope.
3938 bool IsAsmFunction() { return AsmFunctionField::decode(Flags()); }
3940 bool IsSimpleParameterList() {
3941 return IsSimpleParameterListField::decode(Flags());
3944 // Return the function_name if present.
3945 String* FunctionName();
3947 // Return the name of the given parameter.
3948 String* ParameterName(int var);
3950 // Return the name of the given local.
3951 String* LocalName(int var);
3953 // Return the name of the given stack local.
3954 String* StackLocalName(int var);
3956 // Return the name of the given stack local.
3957 int StackLocalIndex(int var);
3959 // Return the name of the given context local.
3960 String* ContextLocalName(int var);
3962 // Return the mode of the given context local.
3963 VariableMode ContextLocalMode(int var);
3965 // Return the initialization flag of the given context local.
3966 InitializationFlag ContextLocalInitFlag(int var);
3968 // Return the initialization flag of the given context local.
3969 MaybeAssignedFlag ContextLocalMaybeAssignedFlag(int var);
3971 // Return true if this local was introduced by the compiler, and should not be
3972 // exposed to the user in a debugger.
3973 bool LocalIsSynthetic(int var);
3975 String* StrongModeFreeVariableName(int var);
3976 int StrongModeFreeVariableStartPosition(int var);
3977 int StrongModeFreeVariableEndPosition(int var);
3979 // Lookup support for serialized scope info. Returns the
3980 // the stack slot index for a given slot name if the slot is
3981 // present; otherwise returns a value < 0. The name must be an internalized
3983 int StackSlotIndex(String* name);
3985 // Lookup support for serialized scope info. Returns the
3986 // context slot index for a given slot name if the slot is present; otherwise
3987 // returns a value < 0. The name must be an internalized string.
3988 // If the slot is present and mode != NULL, sets *mode to the corresponding
3989 // mode for that variable.
3990 static int ContextSlotIndex(Handle<ScopeInfo> scope_info, Handle<String> name,
3991 VariableMode* mode, VariableLocation* location,
3992 InitializationFlag* init_flag,
3993 MaybeAssignedFlag* maybe_assigned_flag);
3995 // Lookup the name of a certain context slot by its index.
3996 String* ContextSlotName(int slot_index);
3998 // Lookup support for serialized scope info. Returns the
3999 // parameter index for a given parameter name if the parameter is present;
4000 // otherwise returns a value < 0. The name must be an internalized string.
4001 int ParameterIndex(String* name);
4003 // Lookup support for serialized scope info. Returns the function context
4004 // slot index if the function name is present and context-allocated (named
4005 // function expressions, only), otherwise returns a value < 0. The name
4006 // must be an internalized string.
4007 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4009 // Lookup support for serialized scope info. Returns the receiver context
4010 // slot index if scope has a "this" binding, and the binding is
4011 // context-allocated. Otherwise returns a value < 0.
4012 int ReceiverContextSlotIndex();
4014 FunctionKind function_kind();
4016 // Copies all the context locals into an object used to materialize a scope.
4017 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4018 Handle<Context> context,
4019 Handle<JSObject> scope_object);
4022 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4023 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4025 // Serializes empty scope info.
4026 static ScopeInfo* Empty(Isolate* isolate);
4032 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4033 // numeric and occupies one array slot.
4034 // 1. A set of properties of the scope
4035 // 2. The number of parameters. This only applies to function scopes. For
4036 // non-function scopes this is 0.
4037 // 3. The number of non-parameter variables allocated on the stack.
4038 // 4. The number of non-parameter and parameter variables allocated in the
4040 #define FOR_EACH_NUMERIC_FIELD(V) \
4043 V(StackLocalCount) \
4044 V(ContextLocalCount) \
4045 V(ContextGlobalCount) \
4046 V(StrongModeFreeVariableCount)
4048 #define FIELD_ACCESSORS(name) \
4049 void Set##name(int value) { \
4050 set(k##name, Smi::FromInt(value)); \
4053 if (length() > 0) { \
4054 return Smi::cast(get(k##name))->value(); \
4059 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4060 #undef FIELD_ACCESSORS
4064 #define DECL_INDEX(name) k##name,
4065 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4067 #undef FOR_EACH_NUMERIC_FIELD
4071 // The layout of the variable part of a ScopeInfo is as follows:
4072 // 1. ParameterEntries:
4073 // This part stores the names of the parameters for function scopes. One
4074 // slot is used per parameter, so in total this part occupies
4075 // ParameterCount() slots in the array. For other scopes than function
4076 // scopes ParameterCount() is 0.
4077 // 2. StackLocalFirstSlot:
4078 // Index of a first stack slot for stack local. Stack locals belonging to
4079 // this scope are located on a stack at slots starting from this index.
4080 // 3. StackLocalEntries:
4081 // Contains the names of local variables that are allocated on the stack,
4082 // in increasing order of the stack slot index. First local variable has
4083 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4084 // One slot is used per stack local, so in total this part occupies
4085 // StackLocalCount() slots in the array.
4086 // 4. ContextLocalNameEntries:
4087 // Contains the names of local variables and parameters that are allocated
4088 // in the context. They are stored in increasing order of the context slot
4089 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4090 // context local, so in total this part occupies ContextLocalCount() slots
4092 // 5. ContextLocalInfoEntries:
4093 // Contains the variable modes and initialization flags corresponding to
4094 // the context locals in ContextLocalNameEntries. One slot is used per
4095 // context local, so in total this part occupies ContextLocalCount()
4096 // slots in the array.
4097 // 6. StrongModeFreeVariableNameEntries:
4098 // Stores the names of strong mode free variables.
4099 // 7. StrongModeFreeVariablePositionEntries:
4100 // Stores the locations (start and end position) of strong mode free
4102 // 8. RecieverEntryIndex:
4103 // If the scope binds a "this" value, one slot is reserved to hold the
4104 // context or stack slot index for the variable.
4105 // 9. FunctionNameEntryIndex:
4106 // If the scope belongs to a named function expression this part contains
4107 // information about the function variable. It always occupies two array
4108 // slots: a. The name of the function variable.
4109 // b. The context or stack slot index for the variable.
4110 int ParameterEntriesIndex();
4111 int StackLocalFirstSlotIndex();
4112 int StackLocalEntriesIndex();
4113 int ContextLocalNameEntriesIndex();
4114 int ContextGlobalNameEntriesIndex();
4115 int ContextLocalInfoEntriesIndex();
4116 int ContextGlobalInfoEntriesIndex();
4117 int StrongModeFreeVariableNameEntriesIndex();
4118 int StrongModeFreeVariablePositionEntriesIndex();
4119 int ReceiverEntryIndex();
4120 int FunctionNameEntryIndex();
4122 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4123 VariableLocation* location, InitializationFlag* init_flag,
4124 MaybeAssignedFlag* maybe_assigned_flag);
4126 // Used for the function name variable for named function expressions, and for
4128 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4130 // Properties of scopes.
4131 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4132 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4133 STATIC_ASSERT(LANGUAGE_END == 3);
4134 class LanguageModeField
4135 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4136 class ReceiverVariableField
4137 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4138 class FunctionVariableField
4139 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4141 class FunctionVariableMode
4142 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4143 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4145 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4146 class IsSimpleParameterListField
4147 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4148 class FunctionKindField
4149 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4151 // BitFields representing the encoded information for context locals in the
4152 // ContextLocalInfoEntries part.
4153 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4154 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4155 class ContextLocalMaybeAssignedFlag
4156 : public BitField<MaybeAssignedFlag, 4, 1> {};
4160 // The cache for maps used by normalized (dictionary mode) objects.
4161 // Such maps do not have property descriptors, so a typical program
4162 // needs very limited number of distinct normalized maps.
4163 class NormalizedMapCache: public FixedArray {
4165 static Handle<NormalizedMapCache> New(Isolate* isolate);
4167 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4168 PropertyNormalizationMode mode);
4169 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4173 DECLARE_CAST(NormalizedMapCache)
4175 static inline bool IsNormalizedMapCache(const Object* obj);
4177 DECLARE_VERIFIER(NormalizedMapCache)
4179 static const int kEntries = 64;
4181 static inline int GetIndex(Handle<Map> map);
4183 // The following declarations hide base class methods.
4184 Object* get(int index);
4185 void set(int index, Object* value);
4189 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4190 // that is attached to code objects.
4191 class ByteArray: public FixedArrayBase {
4193 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4195 // Setter and getter.
4196 inline byte get(int index);
4197 inline void set(int index, byte value);
4199 // Treat contents as an int array.
4200 inline int get_int(int index);
4202 static int SizeFor(int length) {
4203 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4205 // We use byte arrays for free blocks in the heap. Given a desired size in
4206 // bytes that is a multiple of the word size and big enough to hold a byte
4207 // array, this function returns the number of elements a byte array should
4209 static int LengthFor(int size_in_bytes) {
4210 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4211 DCHECK(size_in_bytes >= kHeaderSize);
4212 return size_in_bytes - kHeaderSize;
4215 // Returns data start address.
4216 inline Address GetDataStartAddress();
4218 // Returns a pointer to the ByteArray object for a given data start address.
4219 static inline ByteArray* FromDataStartAddress(Address address);
4221 DECLARE_CAST(ByteArray)
4223 // Dispatched behavior.
4224 inline int ByteArraySize() {
4225 return SizeFor(this->length());
4227 DECLARE_PRINTER(ByteArray)
4228 DECLARE_VERIFIER(ByteArray)
4230 // Layout description.
4231 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4233 // Maximal memory consumption for a single ByteArray.
4234 static const int kMaxSize = 512 * MB;
4235 // Maximal length of a single ByteArray.
4236 static const int kMaxLength = kMaxSize - kHeaderSize;
4239 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4243 // BytecodeArray represents a sequence of interpreter bytecodes.
4244 class BytecodeArray : public FixedArrayBase {
4246 static int SizeFor(int length) {
4247 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4250 // Setter and getter
4251 inline byte get(int index);
4252 inline void set(int index, byte value);
4254 // Returns data start address.
4255 inline Address GetFirstBytecodeAddress();
4257 // Accessors for frame size and the number of locals
4258 inline int frame_size() const;
4259 inline void set_frame_size(int value);
4261 DECLARE_CAST(BytecodeArray)
4263 // Dispatched behavior.
4264 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4266 DECLARE_PRINTER(BytecodeArray)
4267 DECLARE_VERIFIER(BytecodeArray)
4269 void Disassemble(std::ostream& os);
4271 // Layout description.
4272 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4273 static const int kHeaderSize = kFrameSizeOffset + kIntSize;
4275 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4277 // Maximal memory consumption for a single BytecodeArray.
4278 static const int kMaxSize = 512 * MB;
4279 // Maximal length of a single BytecodeArray.
4280 static const int kMaxLength = kMaxSize - kHeaderSize;
4283 DISALLOW_IMPLICIT_CONSTRUCTORS(BytecodeArray);
4287 // FreeSpace are fixed-size free memory blocks used by the heap and GC.
4288 // They look like heap objects (are heap object tagged and have a map) so that
4289 // the heap remains iterable. They have a size and a next pointer.
4290 // The next pointer is the raw address of the next FreeSpace object (or NULL)
4291 // in the free list.
4292 class FreeSpace: public HeapObject {
4294 // [size]: size of the free space including the header.
4295 inline int size() const;
4296 inline void set_size(int value);
4298 inline int nobarrier_size() const;
4299 inline void nobarrier_set_size(int value);
4301 inline int Size() { return size(); }
4303 // Accessors for the next field.
4304 inline FreeSpace* next();
4305 inline FreeSpace** next_address();
4306 inline void set_next(FreeSpace* next);
4308 inline static FreeSpace* cast(HeapObject* obj);
4310 // Dispatched behavior.
4311 DECLARE_PRINTER(FreeSpace)
4312 DECLARE_VERIFIER(FreeSpace)
4314 // Layout description.
4315 // Size is smi tagged when it is stored.
4316 static const int kSizeOffset = HeapObject::kHeaderSize;
4317 static const int kNextOffset = POINTER_SIZE_ALIGN(kSizeOffset + kPointerSize);
4320 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
4324 // V has parameters (Type, type, TYPE, C type, element_size)
4325 #define TYPED_ARRAYS(V) \
4326 V(Uint8, uint8, UINT8, uint8_t, 1) \
4327 V(Int8, int8, INT8, int8_t, 1) \
4328 V(Uint16, uint16, UINT16, uint16_t, 2) \
4329 V(Int16, int16, INT16, int16_t, 2) \
4330 V(Uint32, uint32, UINT32, uint32_t, 4) \
4331 V(Int32, int32, INT32, int32_t, 4) \
4332 V(Float32, float32, FLOAT32, float, 4) \
4333 V(Float64, float64, FLOAT64, double, 8) \
4334 V(Uint8Clamped, uint8_clamped, UINT8_CLAMPED, uint8_t, 1)
4338 // An ExternalArray represents a fixed-size array of primitive values
4339 // which live outside the JavaScript heap. Its subclasses are used to
4340 // implement the CanvasArray types being defined in the WebGL
4341 // specification. As of this writing the first public draft is not yet
4342 // available, but Khronos members can access the draft at:
4343 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
4345 // The semantics of these arrays differ from CanvasPixelArray.
4346 // Out-of-range values passed to the setter are converted via a C
4347 // cast, not clamping. Out-of-range indices cause exceptions to be
4348 // raised rather than being silently ignored.
4349 class ExternalArray: public FixedArrayBase {
4351 inline bool is_the_hole(int index) { return false; }
4353 // [external_pointer]: The pointer to the external memory area backing this
4355 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
4357 DECLARE_CAST(ExternalArray)
4359 // Maximal acceptable length for an external array.
4360 static const int kMaxLength = 0x3fffffff;
4362 // ExternalArray headers are not quadword aligned.
4363 static const int kExternalPointerOffset =
4364 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
4365 static const int kSize = kExternalPointerOffset + kPointerSize;
4368 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
4372 // A ExternalUint8ClampedArray represents a fixed-size byte array with special
4373 // semantics used for implementing the CanvasPixelArray object. Please see the
4374 // specification at:
4376 // http://www.whatwg.org/specs/web-apps/current-work/
4377 // multipage/the-canvas-element.html#canvaspixelarray
4378 // In particular, write access clamps the value written to 0 or 255 if the
4379 // value written is outside this range.
4380 class ExternalUint8ClampedArray: public ExternalArray {
4382 inline uint8_t* external_uint8_clamped_pointer();
4384 // Setter and getter.
4385 inline uint8_t get_scalar(int index);
4386 static inline Handle<Object> get(Handle<ExternalUint8ClampedArray> array,
4388 inline void set(int index, uint8_t value);
4390 // This accessor applies the correct conversion from Smi, HeapNumber
4391 // and undefined and clamps the converted value between 0 and 255.
4392 void SetValue(uint32_t index, Object* value);
4394 DECLARE_CAST(ExternalUint8ClampedArray)
4396 // Dispatched behavior.
4397 DECLARE_PRINTER(ExternalUint8ClampedArray)
4398 DECLARE_VERIFIER(ExternalUint8ClampedArray)
4401 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8ClampedArray);
4405 class ExternalInt8Array: public ExternalArray {
4407 // Setter and getter.
4408 inline int8_t get_scalar(int index);
4409 static inline Handle<Object> get(Handle<ExternalInt8Array> array, int index);
4410 inline void set(int index, int8_t value);
4412 // This accessor applies the correct conversion from Smi, HeapNumber
4414 void SetValue(uint32_t index, Object* value);
4416 DECLARE_CAST(ExternalInt8Array)
4418 // Dispatched behavior.
4419 DECLARE_PRINTER(ExternalInt8Array)
4420 DECLARE_VERIFIER(ExternalInt8Array)
4423 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt8Array);
4427 class ExternalUint8Array: public ExternalArray {
4429 // Setter and getter.
4430 inline uint8_t get_scalar(int index);
4431 static inline Handle<Object> get(Handle<ExternalUint8Array> array, int index);
4432 inline void set(int index, uint8_t value);
4434 // This accessor applies the correct conversion from Smi, HeapNumber
4436 void SetValue(uint32_t index, Object* value);
4438 DECLARE_CAST(ExternalUint8Array)
4440 // Dispatched behavior.
4441 DECLARE_PRINTER(ExternalUint8Array)
4442 DECLARE_VERIFIER(ExternalUint8Array)
4445 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint8Array);
4449 class ExternalInt16Array: public ExternalArray {
4451 // Setter and getter.
4452 inline int16_t get_scalar(int index);
4453 static inline Handle<Object> get(Handle<ExternalInt16Array> array, int index);
4454 inline void set(int index, int16_t value);
4456 // This accessor applies the correct conversion from Smi, HeapNumber
4458 void SetValue(uint32_t index, Object* value);
4460 DECLARE_CAST(ExternalInt16Array)
4462 // Dispatched behavior.
4463 DECLARE_PRINTER(ExternalInt16Array)
4464 DECLARE_VERIFIER(ExternalInt16Array)
4467 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt16Array);
4471 class ExternalUint16Array: public ExternalArray {
4473 // Setter and getter.
4474 inline uint16_t get_scalar(int index);
4475 static inline Handle<Object> get(Handle<ExternalUint16Array> array,
4477 inline void set(int index, uint16_t value);
4479 // This accessor applies the correct conversion from Smi, HeapNumber
4481 void SetValue(uint32_t index, Object* value);
4483 DECLARE_CAST(ExternalUint16Array)
4485 // Dispatched behavior.
4486 DECLARE_PRINTER(ExternalUint16Array)
4487 DECLARE_VERIFIER(ExternalUint16Array)
4490 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint16Array);
4494 class ExternalInt32Array: public ExternalArray {
4496 // Setter and getter.
4497 inline int32_t get_scalar(int index);
4498 static inline Handle<Object> get(Handle<ExternalInt32Array> array, int index);
4499 inline void set(int index, int32_t value);
4501 // This accessor applies the correct conversion from Smi, HeapNumber
4503 void SetValue(uint32_t index, Object* value);
4505 DECLARE_CAST(ExternalInt32Array)
4507 // Dispatched behavior.
4508 DECLARE_PRINTER(ExternalInt32Array)
4509 DECLARE_VERIFIER(ExternalInt32Array)
4512 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalInt32Array);
4516 class ExternalUint32Array: public ExternalArray {
4518 // Setter and getter.
4519 inline uint32_t get_scalar(int index);
4520 static inline Handle<Object> get(Handle<ExternalUint32Array> array,
4522 inline void set(int index, uint32_t value);
4524 // This accessor applies the correct conversion from Smi, HeapNumber
4526 void SetValue(uint32_t index, Object* value);
4528 DECLARE_CAST(ExternalUint32Array)
4530 // Dispatched behavior.
4531 DECLARE_PRINTER(ExternalUint32Array)
4532 DECLARE_VERIFIER(ExternalUint32Array)
4535 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUint32Array);
4539 class ExternalFloat32Array: public ExternalArray {
4541 // Setter and getter.
4542 inline float get_scalar(int index);
4543 static inline Handle<Object> get(Handle<ExternalFloat32Array> array,
4545 inline void set(int index, float value);
4547 // This accessor applies the correct conversion from Smi, HeapNumber
4549 void SetValue(uint32_t index, Object* value);
4551 DECLARE_CAST(ExternalFloat32Array)
4553 // Dispatched behavior.
4554 DECLARE_PRINTER(ExternalFloat32Array)
4555 DECLARE_VERIFIER(ExternalFloat32Array)
4558 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat32Array);
4562 class ExternalFloat64Array: public ExternalArray {
4564 // Setter and getter.
4565 inline double get_scalar(int index);
4566 static inline Handle<Object> get(Handle<ExternalFloat64Array> array,
4568 inline void set(int index, double value);
4570 // This accessor applies the correct conversion from Smi, HeapNumber
4572 void SetValue(uint32_t index, Object* value);
4574 DECLARE_CAST(ExternalFloat64Array)
4576 // Dispatched behavior.
4577 DECLARE_PRINTER(ExternalFloat64Array)
4578 DECLARE_VERIFIER(ExternalFloat64Array)
4581 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloat64Array);
4585 class FixedTypedArrayBase: public FixedArrayBase {
4587 // [base_pointer]: For now, points to the FixedTypedArrayBase itself.
4588 DECL_ACCESSORS(base_pointer, Object)
4590 // [external_pointer]: For now, contains the offset between base_pointer and
4591 // the start of the data.
4592 DECL_ACCESSORS(external_pointer, void)
4594 // Dispatched behavior.
4595 inline void FixedTypedArrayBaseIterateBody(ObjectVisitor* v);
4597 template <typename StaticVisitor>
4598 inline void FixedTypedArrayBaseIterateBody();
4600 DECLARE_CAST(FixedTypedArrayBase)
4602 static const int kBasePointerOffset = FixedArrayBase::kHeaderSize;
4603 static const int kExternalPointerOffset = kBasePointerOffset + kPointerSize;
4604 static const int kHeaderSize =
4605 DOUBLE_POINTER_ALIGN(kExternalPointerOffset + kPointerSize);
4607 static const int kDataOffset = kHeaderSize;
4611 static inline int TypedArraySize(InstanceType type, int length);
4612 inline int TypedArraySize(InstanceType type);
4614 // Use with care: returns raw pointer into heap.
4615 inline void* DataPtr();
4617 inline int DataSize();
4620 static inline int ElementSize(InstanceType type);
4622 inline int DataSize(InstanceType type);
4624 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArrayBase);
4628 template <class Traits>
4629 class FixedTypedArray: public FixedTypedArrayBase {
4631 typedef typename Traits::ElementType ElementType;
4632 static const InstanceType kInstanceType = Traits::kInstanceType;
4634 DECLARE_CAST(FixedTypedArray<Traits>)
4636 inline ElementType get_scalar(int index);
4637 static inline Handle<Object> get(Handle<FixedTypedArray> array, int index);
4638 inline void set(int index, ElementType value);
4640 static inline ElementType from_int(int value);
4641 static inline ElementType from_double(double value);
4643 // This accessor applies the correct conversion from Smi, HeapNumber
4645 void SetValue(uint32_t index, Object* value);
4647 DECLARE_PRINTER(FixedTypedArray)
4648 DECLARE_VERIFIER(FixedTypedArray)
4651 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedTypedArray);
4654 #define FIXED_TYPED_ARRAY_TRAITS(Type, type, TYPE, elementType, size) \
4655 class Type##ArrayTraits { \
4656 public: /* NOLINT */ \
4657 typedef elementType ElementType; \
4658 static const InstanceType kInstanceType = FIXED_##TYPE##_ARRAY_TYPE; \
4659 static const char* Designator() { return #type " array"; } \
4660 static inline Handle<Object> ToHandle(Isolate* isolate, \
4661 elementType scalar); \
4662 static inline elementType defaultValue(); \
4665 typedef FixedTypedArray<Type##ArrayTraits> Fixed##Type##Array;
4667 TYPED_ARRAYS(FIXED_TYPED_ARRAY_TRAITS)
4669 #undef FIXED_TYPED_ARRAY_TRAITS
4672 // DeoptimizationInputData is a fixed array used to hold the deoptimization
4673 // data for code generated by the Hydrogen/Lithium compiler. It also
4674 // contains information about functions that were inlined. If N different
4675 // functions were inlined then first N elements of the literal array will
4676 // contain these functions.
4679 class DeoptimizationInputData: public FixedArray {
4681 // Layout description. Indices in the array.
4682 static const int kTranslationByteArrayIndex = 0;
4683 static const int kInlinedFunctionCountIndex = 1;
4684 static const int kLiteralArrayIndex = 2;
4685 static const int kOsrAstIdIndex = 3;
4686 static const int kOsrPcOffsetIndex = 4;
4687 static const int kOptimizationIdIndex = 5;
4688 static const int kSharedFunctionInfoIndex = 6;
4689 static const int kWeakCellCacheIndex = 7;
4690 static const int kFirstDeoptEntryIndex = 8;
4692 // Offsets of deopt entry elements relative to the start of the entry.
4693 static const int kAstIdRawOffset = 0;
4694 static const int kTranslationIndexOffset = 1;
4695 static const int kArgumentsStackHeightOffset = 2;
4696 static const int kPcOffset = 3;
4697 static const int kDeoptEntrySize = 4;
4699 // Simple element accessors.
4700 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
4702 return type::cast(get(k##name##Index)); \
4704 void Set##name(type* value) { \
4705 set(k##name##Index, value); \
4708 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
4709 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
4710 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
4711 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
4712 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
4713 DEFINE_ELEMENT_ACCESSORS(OptimizationId, Smi)
4714 DEFINE_ELEMENT_ACCESSORS(SharedFunctionInfo, Object)
4715 DEFINE_ELEMENT_ACCESSORS(WeakCellCache, Object)
4717 #undef DEFINE_ELEMENT_ACCESSORS
4719 // Accessors for elements of the ith deoptimization entry.
4720 #define DEFINE_ENTRY_ACCESSORS(name, type) \
4721 type* name(int i) { \
4722 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4724 void Set##name(int i, type* value) { \
4725 set(IndexForEntry(i) + k##name##Offset, value); \
4728 DEFINE_ENTRY_ACCESSORS(AstIdRaw, Smi)
4729 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4730 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4731 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4733 #undef DEFINE_DEOPT_ENTRY_ACCESSORS
4735 BailoutId AstId(int i) {
4736 return BailoutId(AstIdRaw(i)->value());
4739 void SetAstId(int i, BailoutId value) {
4740 SetAstIdRaw(i, Smi::FromInt(value.ToInt()));
4744 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4747 // Allocates a DeoptimizationInputData.
4748 static Handle<DeoptimizationInputData> New(Isolate* isolate,
4749 int deopt_entry_count,
4750 PretenureFlag pretenure);
4752 DECLARE_CAST(DeoptimizationInputData)
4754 #ifdef ENABLE_DISASSEMBLER
4755 void DeoptimizationInputDataPrint(std::ostream& os); // NOLINT
4759 static int IndexForEntry(int i) {
4760 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4764 static int LengthFor(int entry_count) { return IndexForEntry(entry_count); }
4768 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4769 // data for code generated by the full compiler.
4770 // The format of the these objects is
4771 // [i * 2]: Ast ID for ith deoptimization.
4772 // [i * 2 + 1]: PC and state of ith deoptimization
4773 class DeoptimizationOutputData: public FixedArray {
4775 int DeoptPoints() { return length() / 2; }
4777 BailoutId AstId(int index) {
4778 return BailoutId(Smi::cast(get(index * 2))->value());
4781 void SetAstId(int index, BailoutId id) {
4782 set(index * 2, Smi::FromInt(id.ToInt()));
4785 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4786 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4788 static int LengthOfFixedArray(int deopt_points) {
4789 return deopt_points * 2;
4792 // Allocates a DeoptimizationOutputData.
4793 static Handle<DeoptimizationOutputData> New(Isolate* isolate,
4794 int number_of_deopt_points,
4795 PretenureFlag pretenure);
4797 DECLARE_CAST(DeoptimizationOutputData)
4799 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4800 void DeoptimizationOutputDataPrint(std::ostream& os); // NOLINT
4805 // HandlerTable is a fixed array containing entries for exception handlers in
4806 // the code object it is associated with. The tables comes in two flavors:
4807 // 1) Based on ranges: Used for unoptimized code. Contains one entry per
4808 // exception handler and a range representing the try-block covered by that
4809 // handler. Layout looks as follows:
4810 // [ range-start , range-end , handler-offset , stack-depth ]
4811 // 2) Based on return addresses: Used for turbofanned code. Contains one entry
4812 // per call-site that could throw an exception. Layout looks as follows:
4813 // [ return-address-offset , handler-offset ]
4814 class HandlerTable : public FixedArray {
4816 // Conservative prediction whether a given handler will locally catch an
4817 // exception or cause a re-throw to outside the code boundary. Since this is
4818 // undecidable it is merely an approximation (e.g. useful for debugger).
4819 enum CatchPrediction { UNCAUGHT, CAUGHT };
4821 // Accessors for handler table based on ranges.
4822 void SetRangeStart(int index, int value) {
4823 set(index * kRangeEntrySize + kRangeStartIndex, Smi::FromInt(value));
4825 void SetRangeEnd(int index, int value) {
4826 set(index * kRangeEntrySize + kRangeEndIndex, Smi::FromInt(value));
4828 void SetRangeHandler(int index, int offset, CatchPrediction prediction) {
4829 int value = HandlerOffsetField::encode(offset) |
4830 HandlerPredictionField::encode(prediction);
4831 set(index * kRangeEntrySize + kRangeHandlerIndex, Smi::FromInt(value));
4833 void SetRangeDepth(int index, int value) {
4834 set(index * kRangeEntrySize + kRangeDepthIndex, Smi::FromInt(value));
4837 // Accessors for handler table based on return addresses.
4838 void SetReturnOffset(int index, int value) {
4839 set(index * kReturnEntrySize + kReturnOffsetIndex, Smi::FromInt(value));
4841 void SetReturnHandler(int index, int offset, CatchPrediction prediction) {
4842 int value = HandlerOffsetField::encode(offset) |
4843 HandlerPredictionField::encode(prediction);
4844 set(index * kReturnEntrySize + kReturnHandlerIndex, Smi::FromInt(value));
4847 // Lookup handler in a table based on ranges.
4848 int LookupRange(int pc_offset, int* stack_depth, CatchPrediction* prediction);
4850 // Lookup handler in a table based on return addresses.
4851 int LookupReturn(int pc_offset, CatchPrediction* prediction);
4853 // Returns the required length of the underlying fixed array.
4854 static int LengthForRange(int entries) { return entries * kRangeEntrySize; }
4855 static int LengthForReturn(int entries) { return entries * kReturnEntrySize; }
4857 DECLARE_CAST(HandlerTable)
4859 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4860 void HandlerTableRangePrint(std::ostream& os); // NOLINT
4861 void HandlerTableReturnPrint(std::ostream& os); // NOLINT
4865 // Layout description for handler table based on ranges.
4866 static const int kRangeStartIndex = 0;
4867 static const int kRangeEndIndex = 1;
4868 static const int kRangeHandlerIndex = 2;
4869 static const int kRangeDepthIndex = 3;
4870 static const int kRangeEntrySize = 4;
4872 // Layout description for handler table based on return addresses.
4873 static const int kReturnOffsetIndex = 0;
4874 static const int kReturnHandlerIndex = 1;
4875 static const int kReturnEntrySize = 2;
4877 // Encoding of the {handler} field.
4878 class HandlerPredictionField : public BitField<CatchPrediction, 0, 1> {};
4879 class HandlerOffsetField : public BitField<int, 1, 30> {};
4883 // Code describes objects with on-the-fly generated machine code.
4884 class Code: public HeapObject {
4886 // Opaque data type for encapsulating code flags like kind, inline
4887 // cache state, and arguments count.
4888 typedef uint32_t Flags;
4890 #define NON_IC_KIND_LIST(V) \
4892 V(OPTIMIZED_FUNCTION) \
4898 #define IC_KIND_LIST(V) \
4909 #define CODE_KIND_LIST(V) \
4910 NON_IC_KIND_LIST(V) \
4914 #define DEFINE_CODE_KIND_ENUM(name) name,
4915 CODE_KIND_LIST(DEFINE_CODE_KIND_ENUM)
4916 #undef DEFINE_CODE_KIND_ENUM
4920 // No more than 16 kinds. The value is currently encoded in four bits in
4922 STATIC_ASSERT(NUMBER_OF_KINDS <= 16);
4924 static const char* Kind2String(Kind kind);
4932 static const int kPrologueOffsetNotSet = -1;
4934 #ifdef ENABLE_DISASSEMBLER
4936 static const char* ICState2String(InlineCacheState state);
4937 static const char* StubType2String(StubType type);
4938 static void PrintExtraICState(std::ostream& os, // NOLINT
4939 Kind kind, ExtraICState extra);
4940 void Disassemble(const char* name, std::ostream& os); // NOLINT
4941 #endif // ENABLE_DISASSEMBLER
4943 // [instruction_size]: Size of the native instructions
4944 inline int instruction_size() const;
4945 inline void set_instruction_size(int value);
4947 // [relocation_info]: Code relocation information
4948 DECL_ACCESSORS(relocation_info, ByteArray)
4949 void InvalidateRelocation();
4950 void InvalidateEmbeddedObjects();
4952 // [handler_table]: Fixed array containing offsets of exception handlers.
4953 DECL_ACCESSORS(handler_table, FixedArray)
4955 // [deoptimization_data]: Array containing data for deopt.
4956 DECL_ACCESSORS(deoptimization_data, FixedArray)
4958 // [raw_type_feedback_info]: This field stores various things, depending on
4959 // the kind of the code object.
4960 // FUNCTION => type feedback information.
4961 // STUB and ICs => major/minor key as Smi.
4962 DECL_ACCESSORS(raw_type_feedback_info, Object)
4963 inline Object* type_feedback_info();
4964 inline void set_type_feedback_info(
4965 Object* value, WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
4966 inline uint32_t stub_key();
4967 inline void set_stub_key(uint32_t key);
4969 // [next_code_link]: Link for lists of optimized or deoptimized code.
4970 // Note that storage for this field is overlapped with typefeedback_info.
4971 DECL_ACCESSORS(next_code_link, Object)
4973 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4974 // field does not have to be traced during garbage collection since
4975 // it is only used by the garbage collector itself.
4976 DECL_ACCESSORS(gc_metadata, Object)
4978 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4979 // at the moment when this object was created.
4980 inline void set_ic_age(int count);
4981 inline int ic_age() const;
4983 // [prologue_offset]: Offset of the function prologue, used for aging
4984 // FUNCTIONs and OPTIMIZED_FUNCTIONs.
4985 inline int prologue_offset() const;
4986 inline void set_prologue_offset(int offset);
4988 // [constant_pool offset]: Offset of the constant pool.
4989 // Valid for FLAG_enable_embedded_constant_pool only
4990 inline int constant_pool_offset() const;
4991 inline void set_constant_pool_offset(int offset);
4993 // Unchecked accessors to be used during GC.
4994 inline ByteArray* unchecked_relocation_info();
4996 inline int relocation_size();
4998 // [flags]: Various code flags.
4999 inline Flags flags();
5000 inline void set_flags(Flags flags);
5002 // [flags]: Access to specific code flags.
5004 inline InlineCacheState ic_state(); // Only valid for IC stubs.
5005 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
5007 inline StubType type(); // Only valid for monomorphic IC stubs.
5009 // Testers for IC stub kinds.
5010 inline bool is_inline_cache_stub();
5011 inline bool is_debug_stub();
5012 inline bool is_handler() { return kind() == HANDLER; }
5013 inline bool is_load_stub() { return kind() == LOAD_IC; }
5014 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
5015 inline bool is_store_stub() { return kind() == STORE_IC; }
5016 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
5017 inline bool is_call_stub() { return kind() == CALL_IC; }
5018 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
5019 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
5020 inline bool is_compare_nil_ic_stub() { return kind() == COMPARE_NIL_IC; }
5021 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
5022 inline bool is_keyed_stub();
5023 inline bool is_optimized_code() { return kind() == OPTIMIZED_FUNCTION; }
5024 inline bool embeds_maps_weakly() {
5026 return (k == LOAD_IC || k == STORE_IC || k == KEYED_LOAD_IC ||
5027 k == KEYED_STORE_IC || k == COMPARE_NIL_IC) &&
5028 ic_state() == MONOMORPHIC;
5031 inline bool IsCodeStubOrIC();
5033 inline void set_raw_kind_specific_flags1(int value);
5034 inline void set_raw_kind_specific_flags2(int value);
5036 // [is_crankshafted]: For kind STUB or ICs, tells whether or not a code
5037 // object was generated by either the hydrogen or the TurboFan optimizing
5038 // compiler (but it may not be an optimized function).
5039 inline bool is_crankshafted();
5040 inline bool is_hydrogen_stub(); // Crankshafted, but not a function.
5041 inline void set_is_crankshafted(bool value);
5043 // [is_turbofanned]: For kind STUB or OPTIMIZED_FUNCTION, tells whether the
5044 // code object was generated by the TurboFan optimizing compiler.
5045 inline bool is_turbofanned();
5046 inline void set_is_turbofanned(bool value);
5048 // [can_have_weak_objects]: For kind OPTIMIZED_FUNCTION, tells whether the
5049 // embedded objects in code should be treated weakly.
5050 inline bool can_have_weak_objects();
5051 inline void set_can_have_weak_objects(bool value);
5053 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
5054 // deoptimization support.
5055 inline bool has_deoptimization_support();
5056 inline void set_has_deoptimization_support(bool value);
5058 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
5059 // been compiled with debug break slots.
5060 inline bool has_debug_break_slots();
5061 inline void set_has_debug_break_slots(bool value);
5063 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
5064 // reloc info includes runtime and external references to support
5065 // serialization/deserialization.
5066 inline bool has_reloc_info_for_serialization();
5067 inline void set_has_reloc_info_for_serialization(bool value);
5069 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5070 // how long the function has been marked for OSR and therefore which
5071 // level of loop nesting we are willing to do on-stack replacement
5073 inline void set_allow_osr_at_loop_nesting_level(int level);
5074 inline int allow_osr_at_loop_nesting_level();
5076 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5077 // the code object was seen on the stack with no IC patching going on.
5078 inline int profiler_ticks();
5079 inline void set_profiler_ticks(int ticks);
5081 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5082 // For builtins, tells which builtin index it has.
5083 // Note that builtins can have a code kind other than BUILTIN, which means
5084 // that for arbitrary code objects, this index value may be random garbage.
5085 // To verify in that case, compare the code object to the indexed builtin.
5086 inline int builtin_index();
5087 inline void set_builtin_index(int id);
5089 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5090 // reserved in the code prologue.
5091 inline unsigned stack_slots();
5092 inline void set_stack_slots(unsigned slots);
5094 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5095 // the instruction stream where the safepoint table starts.
5096 inline unsigned safepoint_table_offset();
5097 inline void set_safepoint_table_offset(unsigned offset);
5099 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5100 // instruction stream where the back edge table starts.
5101 inline unsigned back_edge_table_offset();
5102 inline void set_back_edge_table_offset(unsigned offset);
5104 inline bool back_edges_patched_for_osr();
5106 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5107 inline uint16_t to_boolean_state();
5109 // [has_function_cache]: For kind STUB tells whether there is a function
5110 // cache is passed to the stub.
5111 inline bool has_function_cache();
5112 inline void set_has_function_cache(bool flag);
5115 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5116 // the code is going to be deoptimized because of dead embedded maps.
5117 inline bool marked_for_deoptimization();
5118 inline void set_marked_for_deoptimization(bool flag);
5120 // [constant_pool]: The constant pool for this function.
5121 inline Address constant_pool();
5123 // Get the safepoint entry for the given pc.
5124 SafepointEntry GetSafepointEntry(Address pc);
5126 // Find an object in a stub with a specified map
5127 Object* FindNthObject(int n, Map* match_map);
5129 // Find the first allocation site in an IC stub.
5130 AllocationSite* FindFirstAllocationSite();
5132 // Find the first map in an IC stub.
5133 Map* FindFirstMap();
5134 void FindAllMaps(MapHandleList* maps);
5136 // Find the first handler in an IC stub.
5137 Code* FindFirstHandler();
5139 // Find |length| handlers and put them into |code_list|. Returns false if not
5140 // enough handlers can be found.
5141 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5143 // Find the handler for |map|.
5144 MaybeHandle<Code> FindHandlerForMap(Map* map);
5146 // Find the first name in an IC stub.
5147 Name* FindFirstName();
5149 class FindAndReplacePattern;
5150 // For each (map-to-find, object-to-replace) pair in the pattern, this
5151 // function replaces the corresponding placeholder in the code with the
5152 // object-to-replace. The function assumes that pairs in the pattern come in
5153 // the same order as the placeholders in the code.
5154 // If the placeholder is a weak cell, then the value of weak cell is matched
5155 // against the map-to-find.
5156 void FindAndReplace(const FindAndReplacePattern& pattern);
5158 // The entire code object including its header is copied verbatim to the
5159 // snapshot so that it can be written in one, fast, memcpy during
5160 // deserialization. The deserializer will overwrite some pointers, rather
5161 // like a runtime linker, but the random allocation addresses used in the
5162 // mksnapshot process would still be present in the unlinked snapshot data,
5163 // which would make snapshot production non-reproducible. This method wipes
5164 // out the to-be-overwritten header data for reproducible snapshots.
5165 inline void WipeOutHeader();
5167 // Flags operations.
5168 static inline Flags ComputeFlags(
5169 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5170 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5171 CacheHolderFlag holder = kCacheOnReceiver);
5173 static inline Flags ComputeMonomorphicFlags(
5174 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5175 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5177 static inline Flags ComputeHandlerFlags(
5178 Kind handler_kind, StubType type = NORMAL,
5179 CacheHolderFlag holder = kCacheOnReceiver);
5181 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5182 static inline StubType ExtractTypeFromFlags(Flags flags);
5183 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5184 static inline Kind ExtractKindFromFlags(Flags flags);
5185 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5187 static inline Flags RemoveTypeFromFlags(Flags flags);
5188 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5190 // Convert a target address into a code object.
5191 static inline Code* GetCodeFromTargetAddress(Address address);
5193 // Convert an entry address into an object.
5194 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5196 // Returns the address of the first instruction.
5197 inline byte* instruction_start();
5199 // Returns the address right after the last instruction.
5200 inline byte* instruction_end();
5202 // Returns the size of the instructions, padding, and relocation information.
5203 inline int body_size();
5205 // Returns the address of the first relocation info (read backwards!).
5206 inline byte* relocation_start();
5208 // Code entry point.
5209 inline byte* entry();
5211 // Returns true if pc is inside this object's instructions.
5212 inline bool contains(byte* pc);
5214 // Relocate the code by delta bytes. Called to signal that this code
5215 // object has been moved by delta bytes.
5216 void Relocate(intptr_t delta);
5218 // Migrate code described by desc.
5219 void CopyFrom(const CodeDesc& desc);
5221 // Returns the object size for a given body (used for allocation).
5222 static int SizeFor(int body_size) {
5223 DCHECK_SIZE_TAG_ALIGNED(body_size);
5224 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5227 // Calculate the size of the code object to report for log events. This takes
5228 // the layout of the code object into account.
5229 int ExecutableSize() {
5230 // Check that the assumptions about the layout of the code object holds.
5231 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5233 return instruction_size() + Code::kHeaderSize;
5236 // Locating source position.
5237 int SourcePosition(Address pc);
5238 int SourceStatementPosition(Address pc);
5242 // Dispatched behavior.
5243 int CodeSize() { return SizeFor(body_size()); }
5244 inline void CodeIterateBody(ObjectVisitor* v);
5246 template<typename StaticVisitor>
5247 inline void CodeIterateBody(Heap* heap);
5249 DECLARE_PRINTER(Code)
5250 DECLARE_VERIFIER(Code)
5252 void ClearInlineCaches();
5253 void ClearInlineCaches(Kind kind);
5255 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5256 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5258 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5260 kToBeExecutedOnceCodeAge = -3,
5261 kNotExecutedCodeAge = -2,
5262 kExecutedOnceCodeAge = -1,
5264 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5266 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5267 kLastCodeAge = kAfterLastCodeAge - 1,
5268 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5269 kIsOldCodeAge = kSexagenarianCodeAge,
5270 kPreAgedCodeAge = kIsOldCodeAge - 1
5272 #undef DECLARE_CODE_AGE_ENUM
5274 // Code aging. Indicates how many full GCs this code has survived without
5275 // being entered through the prologue. Used to determine when it is
5276 // relatively safe to flush this code object and replace it with the lazy
5277 // compilation stub.
5278 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5279 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5280 void MakeYoung(Isolate* isolate);
5281 void MarkToBeExecutedOnce(Isolate* isolate);
5282 void MakeOlder(MarkingParity);
5283 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5286 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5287 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5290 void PrintDeoptLocation(FILE* out, Address pc);
5291 bool CanDeoptAt(Address pc);
5294 void VerifyEmbeddedObjectsDependency();
5298 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5299 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5302 inline bool CanContainWeakObjects() {
5303 // is_turbofanned() implies !can_have_weak_objects().
5304 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5305 !can_have_weak_objects());
5306 return is_optimized_code() && can_have_weak_objects();
5309 inline bool IsWeakObject(Object* object) {
5310 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5313 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5315 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5316 WeakCell* CachedWeakCell();
5318 // Max loop nesting marker used to postpose OSR. We don't take loop
5319 // nesting that is deeper than 5 levels into account.
5320 static const int kMaxLoopNestingMarker = 6;
5322 static const int kConstantPoolSize =
5323 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5325 // Layout description.
5326 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5327 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5328 static const int kDeoptimizationDataOffset =
5329 kHandlerTableOffset + kPointerSize;
5330 // For FUNCTION kind, we store the type feedback info here.
5331 static const int kTypeFeedbackInfoOffset =
5332 kDeoptimizationDataOffset + kPointerSize;
5333 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5334 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5335 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5336 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5337 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5338 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5339 static const int kKindSpecificFlags2Offset =
5340 kKindSpecificFlags1Offset + kIntSize;
5341 // Note: We might be able to squeeze this into the flags above.
5342 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5343 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5344 static const int kHeaderPaddingStart =
5345 kConstantPoolOffset + kConstantPoolSize;
5347 // Add padding to align the instruction start following right after
5348 // the Code object header.
5349 static const int kHeaderSize =
5350 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5352 // Byte offsets within kKindSpecificFlags1Offset.
5353 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5354 class FullCodeFlagsHasDeoptimizationSupportField:
5355 public BitField<bool, 0, 1> {}; // NOLINT
5356 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5357 class FullCodeFlagsHasRelocInfoForSerialization
5358 : public BitField<bool, 2, 1> {};
5359 // Bit 3 in this bitfield is unused.
5360 class ProfilerTicksField : public BitField<int, 4, 28> {};
5362 // Flags layout. BitField<type, shift, size>.
5363 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5364 class TypeField : public BitField<StubType, 4, 1> {};
5365 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5366 class KindField : public BitField<Kind, 7, 4> {};
5367 class ExtraICStateField: public BitField<ExtraICState, 11,
5368 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5370 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5371 static const int kStackSlotsFirstBit = 0;
5372 static const int kStackSlotsBitCount = 24;
5373 static const int kHasFunctionCacheBit =
5374 kStackSlotsFirstBit + kStackSlotsBitCount;
5375 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5376 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5377 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5379 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5380 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5382 class StackSlotsField: public BitField<int,
5383 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5384 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5386 class MarkedForDeoptimizationField
5387 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5388 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5390 class CanHaveWeakObjectsField
5391 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5393 // KindSpecificFlags2 layout (ALL)
5394 static const int kIsCrankshaftedBit = 0;
5395 class IsCrankshaftedField: public BitField<bool,
5396 kIsCrankshaftedBit, 1> {}; // NOLINT
5398 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5399 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5400 static const int kSafepointTableOffsetBitCount = 24;
5402 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5403 kSafepointTableOffsetBitCount <= 32);
5404 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5406 class SafepointTableOffsetField: public BitField<int,
5407 kSafepointTableOffsetFirstBit,
5408 kSafepointTableOffsetBitCount> {}; // NOLINT
5410 // KindSpecificFlags2 layout (FUNCTION)
5411 class BackEdgeTableOffsetField: public BitField<int,
5412 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5413 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5414 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5415 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5417 static const int kArgumentsBits = 16;
5418 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5420 // This constant should be encodable in an ARM instruction.
5421 static const int kFlagsNotUsedInLookup =
5422 TypeField::kMask | CacheHolderField::kMask;
5425 friend class RelocIterator;
5426 friend class Deoptimizer; // For FindCodeAgeSequence.
5428 void ClearInlineCaches(Kind* kind);
5431 byte* FindCodeAgeSequence();
5432 static void GetCodeAgeAndParity(Code* code, Age* age,
5433 MarkingParity* parity);
5434 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5435 MarkingParity* parity);
5436 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5438 // Code aging -- platform-specific
5439 static void PatchPlatformCodeAge(Isolate* isolate,
5440 byte* sequence, Age age,
5441 MarkingParity parity);
5443 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5447 // This class describes the layout of dependent codes array of a map. The
5448 // array is partitioned into several groups of dependent codes. Each group
5449 // contains codes with the same dependency on the map. The array has the
5450 // following layout for n dependency groups:
5452 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5453 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5454 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5456 // The first n elements are Smis, each of them specifies the number of codes
5457 // in the corresponding group. The subsequent elements contain grouped code
5458 // objects in weak cells. The suffix of the array can be filled with the
5459 // undefined value if the number of codes is less than the length of the
5460 // array. The order of the code objects within a group is not preserved.
5462 // All code indexes used in the class are counted starting from the first
5463 // code object of the first group. In other words, code index 0 corresponds
5464 // to array index n = kCodesStartIndex.
5466 class DependentCode: public FixedArray {
5468 enum DependencyGroup {
5469 // Group of code that weakly embed this map and depend on being
5470 // deoptimized when the map is garbage collected.
5472 // Group of code that embed a transition to this map, and depend on being
5473 // deoptimized when the transition is replaced by a new version.
5475 // Group of code that omit run-time prototype checks for prototypes
5476 // described by this map. The group is deoptimized whenever an object
5477 // described by this map changes shape (and transitions to a new map),
5478 // possibly invalidating the assumptions embedded in the code.
5479 kPrototypeCheckGroup,
5480 // Group of code that depends on global property values in property cells
5481 // not being changed.
5482 kPropertyCellChangedGroup,
5483 // Group of code that omit run-time type checks for the field(s) introduced
5486 // Group of code that omit run-time type checks for initial maps of
5488 kInitialMapChangedGroup,
5489 // Group of code that depends on tenuring information in AllocationSites
5490 // not being changed.
5491 kAllocationSiteTenuringChangedGroup,
5492 // Group of code that depends on element transition information in
5493 // AllocationSites not being changed.
5494 kAllocationSiteTransitionChangedGroup
5497 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5499 // Array for holding the index of the first code object of each group.
5500 // The last element stores the total number of code objects.
5501 class GroupStartIndexes {
5503 explicit GroupStartIndexes(DependentCode* entries);
5504 void Recompute(DependentCode* entries);
5505 int at(int i) { return start_indexes_[i]; }
5506 int number_of_entries() { return start_indexes_[kGroupCount]; }
5508 int start_indexes_[kGroupCount + 1];
5511 bool Contains(DependencyGroup group, WeakCell* code_cell);
5513 static Handle<DependentCode> InsertCompilationDependencies(
5514 Handle<DependentCode> entries, DependencyGroup group,
5515 Handle<Foreign> info);
5517 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5518 DependencyGroup group,
5519 Handle<WeakCell> code_cell);
5521 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5522 WeakCell* code_cell);
5524 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5527 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5528 DependentCode::DependencyGroup group);
5530 bool MarkCodeForDeoptimization(Isolate* isolate,
5531 DependentCode::DependencyGroup group);
5533 // The following low-level accessors should only be used by this class
5534 // and the mark compact collector.
5535 inline int number_of_entries(DependencyGroup group);
5536 inline void set_number_of_entries(DependencyGroup group, int value);
5537 inline Object* object_at(int i);
5538 inline void set_object_at(int i, Object* object);
5539 inline void clear_at(int i);
5540 inline void copy(int from, int to);
5541 DECLARE_CAST(DependentCode)
5543 static const char* DependencyGroupName(DependencyGroup group);
5544 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5547 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5548 DependencyGroup group,
5549 Handle<Object> object);
5550 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5551 // Make a room at the end of the given group by moving out the first
5552 // code objects of the subsequent groups.
5553 inline void ExtendGroup(DependencyGroup group);
5554 // Compact by removing cleared weak cells and return true if there was
5555 // any cleared weak cell.
5557 static int Grow(int number_of_entries) {
5558 if (number_of_entries < 5) return number_of_entries + 1;
5559 return number_of_entries * 5 / 4;
5561 static const int kCodesStartIndex = kGroupCount;
5565 class PrototypeInfo;
5568 // All heap objects have a Map that describes their structure.
5569 // A Map contains information about:
5570 // - Size information about the object
5571 // - How to iterate over an object (for garbage collection)
5572 class Map: public HeapObject {
5575 // Size in bytes or kVariableSizeSentinel if instances do not have
5577 inline int instance_size();
5578 inline void set_instance_size(int value);
5580 // Only to clear an unused byte, remove once byte is used.
5581 inline void clear_unused();
5583 // Count of properties allocated in the object.
5584 inline int inobject_properties();
5585 inline void set_inobject_properties(int value);
5588 inline InstanceType instance_type();
5589 inline void set_instance_type(InstanceType value);
5591 // Tells how many unused property fields are available in the
5592 // instance (only used for JSObject in fast mode).
5593 inline int unused_property_fields();
5594 inline void set_unused_property_fields(int value);
5597 inline byte bit_field() const;
5598 inline void set_bit_field(byte value);
5601 inline byte bit_field2() const;
5602 inline void set_bit_field2(byte value);
5605 inline uint32_t bit_field3() const;
5606 inline void set_bit_field3(uint32_t bits);
5608 class EnumLengthBits: public BitField<int,
5609 0, kDescriptorIndexBitCount> {}; // NOLINT
5610 class NumberOfOwnDescriptorsBits: public BitField<int,
5611 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5612 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5613 class DictionaryMap : public BitField<bool, 20, 1> {};
5614 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5615 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5616 class Deprecated : public BitField<bool, 23, 1> {};
5617 class IsUnstable : public BitField<bool, 24, 1> {};
5618 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5619 class IsStrong : public BitField<bool, 26, 1> {};
5622 // Keep this bit field at the very end for better code in
5623 // Builtins::kJSConstructStubGeneric stub.
5624 // This counter is used for in-object slack tracking and for map aging.
5625 // The in-object slack tracking is considered enabled when the counter is
5626 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5627 class Counter : public BitField<int, 28, 4> {};
5628 static const int kSlackTrackingCounterStart = 14;
5629 static const int kSlackTrackingCounterEnd = 8;
5630 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5631 static const int kRetainingCounterEnd = 0;
5633 // Tells whether the object in the prototype property will be used
5634 // for instances created from this function. If the prototype
5635 // property is set to a value that is not a JSObject, the prototype
5636 // property will not be used to create instances of the function.
5637 // See ECMA-262, 13.2.2.
5638 inline void set_non_instance_prototype(bool value);
5639 inline bool has_non_instance_prototype();
5641 // Tells whether function has special prototype property. If not, prototype
5642 // property will not be created when accessed (will return undefined),
5643 // and construction from this function will not be allowed.
5644 inline void set_function_with_prototype(bool value);
5645 inline bool function_with_prototype();
5647 // Tells whether the instance with this map should be ignored by the
5648 // Object.getPrototypeOf() function and the __proto__ accessor.
5649 inline void set_is_hidden_prototype() {
5650 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5653 inline bool is_hidden_prototype() {
5654 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5657 // Records and queries whether the instance has a named interceptor.
5658 inline void set_has_named_interceptor() {
5659 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5662 inline bool has_named_interceptor() {
5663 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5666 // Records and queries whether the instance has an indexed interceptor.
5667 inline void set_has_indexed_interceptor() {
5668 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5671 inline bool has_indexed_interceptor() {
5672 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5675 // Tells whether the instance is undetectable.
5676 // An undetectable object is a special class of JSObject: 'typeof' operator
5677 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5678 // a normal JS object. It is useful for implementing undetectable
5679 // document.all in Firefox & Safari.
5680 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5681 inline void set_is_undetectable() {
5682 set_bit_field(bit_field() | (1 << kIsUndetectable));
5685 inline bool is_undetectable() {
5686 return ((1 << kIsUndetectable) & bit_field()) != 0;
5689 // Tells whether the instance has a call-as-function handler.
5690 inline void set_is_observed() {
5691 set_bit_field(bit_field() | (1 << kIsObserved));
5694 inline bool is_observed() {
5695 return ((1 << kIsObserved) & bit_field()) != 0;
5698 inline void set_is_strong();
5699 inline bool is_strong();
5700 inline void set_is_extensible(bool value);
5701 inline bool is_extensible();
5702 inline void set_is_prototype_map(bool value);
5703 inline bool is_prototype_map() const;
5705 inline void set_elements_kind(ElementsKind elements_kind) {
5706 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5707 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5708 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5709 DCHECK(this->elements_kind() == elements_kind);
5712 inline ElementsKind elements_kind() {
5713 return Map::ElementsKindBits::decode(bit_field2());
5716 // Tells whether the instance has fast elements that are only Smis.
5717 inline bool has_fast_smi_elements() {
5718 return IsFastSmiElementsKind(elements_kind());
5721 // Tells whether the instance has fast elements.
5722 inline bool has_fast_object_elements() {
5723 return IsFastObjectElementsKind(elements_kind());
5726 inline bool has_fast_smi_or_object_elements() {
5727 return IsFastSmiOrObjectElementsKind(elements_kind());
5730 inline bool has_fast_double_elements() {
5731 return IsFastDoubleElementsKind(elements_kind());
5734 inline bool has_fast_elements() {
5735 return IsFastElementsKind(elements_kind());
5738 inline bool has_sloppy_arguments_elements() {
5739 return IsSloppyArgumentsElements(elements_kind());
5742 inline bool has_external_array_elements() {
5743 return IsExternalArrayElementsKind(elements_kind());
5746 inline bool has_fixed_typed_array_elements() {
5747 return IsFixedTypedArrayElementsKind(elements_kind());
5750 inline bool has_dictionary_elements() {
5751 return IsDictionaryElementsKind(elements_kind());
5754 static bool IsValidElementsTransition(ElementsKind from_kind,
5755 ElementsKind to_kind);
5757 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5758 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5759 bool DictionaryElementsInPrototypeChainOnly();
5761 inline Map* ElementsTransitionMap();
5763 inline FixedArrayBase* GetInitialElements();
5765 // [raw_transitions]: Provides access to the transitions storage field.
5766 // Don't call set_raw_transitions() directly to overwrite transitions, use
5767 // the TransitionArray::ReplaceTransitions() wrapper instead!
5768 DECL_ACCESSORS(raw_transitions, Object)
5769 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5770 // (which prototype maps don't have).
5771 DECL_ACCESSORS(prototype_info, Object)
5772 // PrototypeInfo is created lazily using this helper (which installs it on
5773 // the given prototype's map).
5774 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5775 Handle<JSObject> prototype, Isolate* isolate);
5777 // [prototype chain validity cell]: Associated with a prototype object,
5778 // stored in that object's map's PrototypeInfo, indicates that prototype
5779 // chains through this object are currently valid. The cell will be
5780 // invalidated and replaced when the prototype chain changes.
5781 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5783 static const int kPrototypeChainValid = 0;
5784 static const int kPrototypeChainInvalid = 1;
5787 Map* FindFieldOwner(int descriptor);
5789 inline int GetInObjectPropertyOffset(int index);
5791 int NumberOfFields();
5793 // TODO(ishell): candidate with JSObject::MigrateToMap().
5794 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5795 int target_inobject, int target_unused,
5796 int* old_number_of_fields);
5797 // TODO(ishell): moveit!
5798 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5799 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5800 Handle<HeapType> type1,
5801 Handle<HeapType> type2,
5803 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5804 Representation new_representation,
5805 Handle<HeapType> new_field_type);
5806 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5807 PropertyKind new_kind,
5808 PropertyAttributes new_attributes,
5809 Representation new_representation,
5810 Handle<HeapType> new_field_type,
5811 StoreMode store_mode);
5812 static Handle<Map> CopyGeneralizeAllRepresentations(
5813 Handle<Map> map, int modify_index, StoreMode store_mode,
5814 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5816 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5817 int descriptor_number,
5818 Handle<Object> value);
5820 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5821 const char* reason);
5823 // Returns the constructor name (the name (possibly, inferred name) of the
5824 // function that was used to instantiate the object).
5825 String* constructor_name();
5827 // Tells whether the map is used for JSObjects in dictionary mode (ie
5828 // normalized objects, ie objects for which HasFastProperties returns false).
5829 // A map can never be used for both dictionary mode and fast mode JSObjects.
5830 // False by default and for HeapObjects that are not JSObjects.
5831 inline void set_dictionary_map(bool value);
5832 inline bool is_dictionary_map();
5834 // Tells whether the instance needs security checks when accessing its
5836 inline void set_is_access_check_needed(bool access_check_needed);
5837 inline bool is_access_check_needed();
5839 // Returns true if map has a non-empty stub code cache.
5840 inline bool has_code_cache();
5842 // [prototype]: implicit prototype object.
5843 DECL_ACCESSORS(prototype, Object)
5844 // TODO(jkummerow): make set_prototype private.
5845 static void SetPrototype(
5846 Handle<Map> map, Handle<Object> prototype,
5847 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5849 // [constructor]: points back to the function responsible for this map.
5850 // The field overlaps with the back pointer. All maps in a transition tree
5851 // have the same constructor, so maps with back pointers can walk the
5852 // back pointer chain until they find the map holding their constructor.
5853 DECL_ACCESSORS(constructor_or_backpointer, Object)
5854 inline Object* GetConstructor() const;
5855 inline void SetConstructor(Object* constructor,
5856 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5857 // [back pointer]: points back to the parent map from which a transition
5858 // leads to this map. The field overlaps with the constructor (see above).
5859 inline Object* GetBackPointer();
5860 inline void SetBackPointer(Object* value,
5861 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5863 // [instance descriptors]: describes the object.
5864 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5866 // [layout descriptor]: describes the object layout.
5867 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5868 // |layout descriptor| accessor which can be used from GC.
5869 inline LayoutDescriptor* layout_descriptor_gc_safe();
5870 inline bool HasFastPointerLayout() const;
5872 // |layout descriptor| accessor that is safe to call even when
5873 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5874 // |layout_descriptor| field at all).
5875 inline LayoutDescriptor* GetLayoutDescriptor();
5877 inline void UpdateDescriptors(DescriptorArray* descriptors,
5878 LayoutDescriptor* layout_descriptor);
5879 inline void InitializeDescriptors(DescriptorArray* descriptors,
5880 LayoutDescriptor* layout_descriptor);
5882 // [stub cache]: contains stubs compiled for this map.
5883 DECL_ACCESSORS(code_cache, Object)
5885 // [dependent code]: list of optimized codes that weakly embed this map.
5886 DECL_ACCESSORS(dependent_code, DependentCode)
5888 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5889 DECL_ACCESSORS(weak_cell_cache, Object)
5891 inline PropertyDetails GetLastDescriptorDetails();
5894 int number_of_own_descriptors = NumberOfOwnDescriptors();
5895 DCHECK(number_of_own_descriptors > 0);
5896 return number_of_own_descriptors - 1;
5899 int NumberOfOwnDescriptors() {
5900 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5903 void SetNumberOfOwnDescriptors(int number) {
5904 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5905 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5908 inline Cell* RetrieveDescriptorsPointer();
5911 return EnumLengthBits::decode(bit_field3());
5914 void SetEnumLength(int length) {
5915 if (length != kInvalidEnumCacheSentinel) {
5916 DCHECK(length >= 0);
5917 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5918 DCHECK(length <= NumberOfOwnDescriptors());
5920 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5923 inline bool owns_descriptors();
5924 inline void set_owns_descriptors(bool owns_descriptors);
5925 inline bool has_instance_call_handler();
5926 inline void set_has_instance_call_handler();
5927 inline void mark_unstable();
5928 inline bool is_stable();
5929 inline void set_migration_target(bool value);
5930 inline bool is_migration_target();
5931 inline void set_counter(int value);
5932 inline int counter();
5933 inline void deprecate();
5934 inline bool is_deprecated();
5935 inline bool CanBeDeprecated();
5936 // Returns a non-deprecated version of the input. If the input was not
5937 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5938 // is found by re-transitioning from the root of the transition tree using the
5939 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5941 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5943 // Returns a non-deprecated version of the input. This method may deprecate
5944 // existing maps along the way if encodings conflict. Not for use while
5945 // gathering type feedback. Use TryUpdate in those cases instead.
5946 static Handle<Map> Update(Handle<Map> map);
5948 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5949 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5950 Descriptor* descriptor,
5951 TransitionFlag flag);
5953 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5956 Handle<HeapType> type,
5957 PropertyAttributes attributes,
5958 Representation representation,
5959 TransitionFlag flag);
5961 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5964 Handle<Object> constant,
5965 PropertyAttributes attributes,
5966 TransitionFlag flag);
5968 // Returns a new map with all transitions dropped from the given map and
5969 // the ElementsKind set.
5970 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5971 ElementsKind to_kind);
5973 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5975 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5977 TransitionFlag flag);
5979 static Handle<Map> CopyForObserved(Handle<Map> map);
5981 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5982 PropertyAttributes attrs_to_add,
5983 Handle<Symbol> transition_marker,
5984 const char* reason);
5986 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5989 // Maximal number of fast properties. Used to restrict the number of map
5990 // transitions to avoid an explosion in the number of maps for objects used as
5992 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5993 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
5995 Handle<Object> value,
5996 PropertyAttributes attributes,
5997 StoreFromKeyed store_mode);
5998 static Handle<Map> TransitionToAccessorProperty(
5999 Handle<Map> map, Handle<Name> name, AccessorComponent component,
6000 Handle<Object> accessor, PropertyAttributes attributes);
6001 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
6004 PropertyAttributes attributes);
6006 inline void AppendDescriptor(Descriptor* desc);
6008 // Returns a copy of the map, prepared for inserting into the transition
6009 // tree (if the |map| owns descriptors then the new one will share
6010 // descriptors with |map|).
6011 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
6013 // Returns a copy of the map, with all transitions dropped from the
6014 // instance descriptors.
6015 static Handle<Map> Copy(Handle<Map> map, const char* reason);
6016 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
6018 // Returns the next free property index (only valid for FAST MODE).
6019 int NextFreePropertyIndex();
6021 // Returns the number of properties described in instance_descriptors
6022 // filtering out properties with the specified attributes.
6023 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6024 PropertyAttributes filter = NONE);
6028 // Code cache operations.
6030 // Clears the code cache.
6031 inline void ClearCodeCache(Heap* heap);
6033 // Update code cache.
6034 static void UpdateCodeCache(Handle<Map> map,
6038 // Extend the descriptor array of the map with the list of descriptors.
6039 // In case of duplicates, the latest descriptor is used.
6040 static void AppendCallbackDescriptors(Handle<Map> map,
6041 Handle<Object> descriptors);
6043 static inline int SlackForArraySize(int old_size, int size_limit);
6045 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6047 // Returns the found code or undefined if absent.
6048 Object* FindInCodeCache(Name* name, Code::Flags flags);
6050 // Returns the non-negative index of the code object if it is in the
6051 // cache and -1 otherwise.
6052 int IndexInCodeCache(Object* name, Code* code);
6054 // Removes a code object from the code cache at the given index.
6055 void RemoveFromCodeCache(Name* name, Code* code, int index);
6057 // Computes a hash value for this map, to be used in HashTables and such.
6060 // Returns the map that this map transitions to if its elements_kind
6061 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6062 // |safe_to_add_transitions| is set to false if adding transitions is not
6064 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6066 // Returns the transitioned map for this map with the most generic
6067 // elements_kind that's found in |candidates|, or null handle if no match is
6069 static Handle<Map> FindTransitionedMap(Handle<Map> map,
6070 MapHandleList* candidates);
6072 bool CanTransition() {
6073 // Only JSObject and subtypes have map transitions and back pointers.
6074 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6075 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6078 bool IsJSObjectMap() {
6079 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6081 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
6082 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6083 bool IsJSProxyMap() {
6084 InstanceType type = instance_type();
6085 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6087 bool IsJSGlobalProxyMap() {
6088 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6090 bool IsJSGlobalObjectMap() {
6091 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6093 bool IsGlobalObjectMap() {
6094 const InstanceType type = instance_type();
6095 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6098 inline bool CanOmitMapChecks();
6100 static void AddDependentCode(Handle<Map> map,
6101 DependentCode::DependencyGroup group,
6104 bool IsMapInArrayPrototypeChain();
6106 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
6108 // Dispatched behavior.
6109 DECLARE_PRINTER(Map)
6110 DECLARE_VERIFIER(Map)
6113 void DictionaryMapVerify();
6114 void VerifyOmittedMapChecks();
6117 inline int visitor_id();
6118 inline void set_visitor_id(int visitor_id);
6120 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6121 Handle<Object> prototype,
6122 PrototypeOptimizationMode mode);
6124 static const int kMaxPreAllocatedPropertyFields = 255;
6126 // Layout description.
6127 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6128 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6129 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6130 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6131 static const int kConstructorOrBackPointerOffset =
6132 kPrototypeOffset + kPointerSize;
6133 // When there is only one transition, it is stored directly in this field;
6134 // otherwise a transition array is used.
6135 // For prototype maps, this slot is used to store this map's PrototypeInfo
6137 static const int kTransitionsOrPrototypeInfoOffset =
6138 kConstructorOrBackPointerOffset + kPointerSize;
6139 static const int kDescriptorsOffset =
6140 kTransitionsOrPrototypeInfoOffset + kPointerSize;
6141 #if V8_DOUBLE_FIELDS_UNBOXING
6142 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
6143 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
6145 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
6146 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6148 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6149 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
6150 static const int kSize = kWeakCellCacheOffset + kPointerSize;
6152 // Layout of pointer fields. Heap iteration code relies on them
6153 // being continuously allocated.
6154 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6155 static const int kPointerFieldsEndOffset = kSize;
6157 // Byte offsets within kInstanceSizesOffset.
6158 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6159 static const int kInObjectPropertiesByte = 1;
6160 static const int kInObjectPropertiesOffset =
6161 kInstanceSizesOffset + kInObjectPropertiesByte;
6162 // Note there is one byte available for use here.
6163 static const int kUnusedByte = 2;
6164 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
6165 static const int kVisitorIdByte = 3;
6166 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6168 // Byte offsets within kInstanceAttributesOffset attributes.
6169 #if V8_TARGET_LITTLE_ENDIAN
6170 // Order instance type and bit field together such that they can be loaded
6171 // together as a 16-bit word with instance type in the lower 8 bits regardless
6172 // of endianess. Also provide endian-independent offset to that 16-bit word.
6173 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6174 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6176 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6177 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6179 static const int kInstanceTypeAndBitFieldOffset =
6180 kInstanceAttributesOffset + 0;
6181 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6182 static const int kUnusedPropertyFieldsByte = 3;
6183 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6185 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6186 Internals::kMapInstanceTypeAndBitFieldOffset);
6188 // Bit positions for bit field.
6189 static const int kHasNonInstancePrototype = 0;
6190 static const int kIsHiddenPrototype = 1;
6191 static const int kHasNamedInterceptor = 2;
6192 static const int kHasIndexedInterceptor = 3;
6193 static const int kIsUndetectable = 4;
6194 static const int kIsObserved = 5;
6195 static const int kIsAccessCheckNeeded = 6;
6196 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6198 // Bit positions for bit field 2
6199 static const int kIsExtensible = 0;
6200 static const int kStringWrapperSafeForDefaultValueOf = 1;
6201 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6202 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6204 // Derived values from bit field 2
6205 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6206 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6207 static const int8_t kMaximumBitField2FastSmiElementValue =
6208 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6209 Map::ElementsKindBits::kShift) - 1;
6210 static const int8_t kMaximumBitField2FastHoleyElementValue =
6211 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6212 Map::ElementsKindBits::kShift) - 1;
6213 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6214 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6215 Map::ElementsKindBits::kShift) - 1;
6217 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6218 kPointerFieldsEndOffset,
6219 kSize> BodyDescriptor;
6221 // Compares this map to another to see if they describe equivalent objects.
6222 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6223 // it had exactly zero inobject properties.
6224 // The "shared" flags of both this map and |other| are ignored.
6225 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6227 // Returns true if given field is unboxed double.
6228 inline bool IsUnboxedDoubleField(FieldIndex index);
6231 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
6232 static void TraceAllTransitions(Map* map);
6235 static inline Handle<Map> CopyInstallDescriptorsForTesting(
6236 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6237 Handle<LayoutDescriptor> layout_descriptor);
6240 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6241 Handle<Name> name, SimpleTransitionFlag flag);
6243 bool EquivalentToForTransition(Map* other);
6244 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6245 static Handle<Map> ShareDescriptor(Handle<Map> map,
6246 Handle<DescriptorArray> descriptors,
6247 Descriptor* descriptor);
6248 static Handle<Map> CopyInstallDescriptors(
6249 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6250 Handle<LayoutDescriptor> layout_descriptor);
6251 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6252 Descriptor* descriptor,
6253 TransitionFlag flag);
6254 static Handle<Map> CopyReplaceDescriptors(
6255 Handle<Map> map, Handle<DescriptorArray> descriptors,
6256 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
6257 MaybeHandle<Name> maybe_name, const char* reason,
6258 SimpleTransitionFlag simple_flag);
6260 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6261 Handle<DescriptorArray> descriptors,
6262 Descriptor* descriptor,
6264 TransitionFlag flag);
6265 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
6266 Handle<Map> map, int descriptor, PropertyKind kind,
6267 PropertyAttributes attributes, const char** reason);
6269 static Handle<Map> CopyNormalized(Handle<Map> map,
6270 PropertyNormalizationMode mode);
6272 // Fires when the layout of an object with a leaf map changes.
6273 // This includes adding transitions to the leaf map or changing
6274 // the descriptor array.
6275 inline void NotifyLeafMapLayoutChange();
6277 void DeprecateTransitionTree();
6278 bool DeprecateTarget(PropertyKind kind, Name* key,
6279 PropertyAttributes attributes,
6280 DescriptorArray* new_descriptors,
6281 LayoutDescriptor* new_layout_descriptor);
6283 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6285 // Update field type of the given descriptor to new representation and new
6286 // type. The type must be prepared for storing in descriptor array:
6287 // it must be either a simple type or a map wrapped in a weak cell.
6288 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6289 Representation new_representation,
6290 Handle<Object> new_wrapped_type);
6292 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6293 PropertyAttributes attributes);
6294 void PrintGeneralization(FILE* file,
6299 bool constant_to_field,
6300 Representation old_representation,
6301 Representation new_representation,
6302 HeapType* old_field_type,
6303 HeapType* new_field_type);
6305 static const int kFastPropertiesSoftLimit = 12;
6306 static const int kMaxFastProperties = 128;
6308 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6312 // An abstract superclass, a marker class really, for simple structure classes.
6313 // It doesn't carry much functionality but allows struct classes to be
6314 // identified in the type system.
6315 class Struct: public HeapObject {
6317 inline void InitializeBody(int object_size);
6318 DECLARE_CAST(Struct)
6322 // A simple one-element struct, useful where smis need to be boxed.
6323 class Box : public Struct {
6325 // [value]: the boxed contents.
6326 DECL_ACCESSORS(value, Object)
6330 // Dispatched behavior.
6331 DECLARE_PRINTER(Box)
6332 DECLARE_VERIFIER(Box)
6334 static const int kValueOffset = HeapObject::kHeaderSize;
6335 static const int kSize = kValueOffset + kPointerSize;
6338 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6342 // Container for metadata stored on each prototype map.
6343 class PrototypeInfo : public Struct {
6345 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6346 // or Smi(0) if uninitialized.
6347 DECL_ACCESSORS(prototype_users, Object)
6348 // [validity_cell]: Cell containing the validity bit for prototype chains
6349 // going through this object, or Smi(0) if uninitialized.
6350 DECL_ACCESSORS(validity_cell, Object)
6351 // [constructor_name]: User-friendly name of the original constructor.
6352 DECL_ACCESSORS(constructor_name, Object)
6354 DECLARE_CAST(PrototypeInfo)
6356 // Dispatched behavior.
6357 DECLARE_PRINTER(PrototypeInfo)
6358 DECLARE_VERIFIER(PrototypeInfo)
6360 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6361 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6362 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6363 static const int kSize = kConstructorNameOffset + kPointerSize;
6366 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6370 // Script describes a script which has been added to the VM.
6371 class Script: public Struct {
6380 // Script compilation types.
6381 enum CompilationType {
6382 COMPILATION_TYPE_HOST = 0,
6383 COMPILATION_TYPE_EVAL = 1
6386 // Script compilation state.
6387 enum CompilationState {
6388 COMPILATION_STATE_INITIAL = 0,
6389 COMPILATION_STATE_COMPILED = 1
6392 // [source]: the script source.
6393 DECL_ACCESSORS(source, Object)
6395 // [name]: the script name.
6396 DECL_ACCESSORS(name, Object)
6398 // [id]: the script id.
6399 DECL_ACCESSORS(id, Smi)
6401 // [line_offset]: script line offset in resource from where it was extracted.
6402 DECL_ACCESSORS(line_offset, Smi)
6404 // [column_offset]: script column offset in resource from where it was
6406 DECL_ACCESSORS(column_offset, Smi)
6408 // [context_data]: context data for the context this script was compiled in.
6409 DECL_ACCESSORS(context_data, Object)
6411 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6412 DECL_ACCESSORS(wrapper, HeapObject)
6414 // [type]: the script type.
6415 DECL_ACCESSORS(type, Smi)
6417 // [line_ends]: FixedArray of line ends positions.
6418 DECL_ACCESSORS(line_ends, Object)
6420 // [eval_from_shared]: for eval scripts the shared funcion info for the
6421 // function from which eval was called.
6422 DECL_ACCESSORS(eval_from_shared, Object)
6424 // [eval_from_instructions_offset]: the instruction offset in the code for the
6425 // function from which eval was called where eval was called.
6426 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6428 // [shared_function_infos]: weak fixed array containing all shared
6429 // function infos created from this script.
6430 DECL_ACCESSORS(shared_function_infos, Object)
6432 // [flags]: Holds an exciting bitfield.
6433 DECL_ACCESSORS(flags, Smi)
6435 // [source_url]: sourceURL from magic comment
6436 DECL_ACCESSORS(source_url, Object)
6438 // [source_url]: sourceMappingURL magic comment
6439 DECL_ACCESSORS(source_mapping_url, Object)
6441 // [compilation_type]: how the the script was compiled. Encoded in the
6443 inline CompilationType compilation_type();
6444 inline void set_compilation_type(CompilationType type);
6446 // [compilation_state]: determines whether the script has already been
6447 // compiled. Encoded in the 'flags' field.
6448 inline CompilationState compilation_state();
6449 inline void set_compilation_state(CompilationState state);
6451 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6452 // and used by the embedder to make decisions about the script. V8 just passes
6453 // this through. Encoded in the 'flags' field.
6454 inline v8::ScriptOriginOptions origin_options();
6455 inline void set_origin_options(ScriptOriginOptions origin_options);
6457 DECLARE_CAST(Script)
6459 // If script source is an external string, check that the underlying
6460 // resource is accessible. Otherwise, always return true.
6461 inline bool HasValidSource();
6463 // Convert code position into column number.
6464 static int GetColumnNumber(Handle<Script> script, int code_pos);
6466 // Convert code position into (zero-based) line number.
6467 // The non-handlified version does not allocate, but may be much slower.
6468 static int GetLineNumber(Handle<Script> script, int code_pos);
6469 int GetLineNumber(int code_pos);
6471 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6473 // Init line_ends array with code positions of line ends inside script source.
6474 static void InitLineEnds(Handle<Script> script);
6476 // Get the JS object wrapping the given script; create it if none exists.
6477 static Handle<JSObject> GetWrapper(Handle<Script> script);
6479 // Look through the list of existing shared function infos to find one
6480 // that matches the function literal. Return empty handle if not found.
6481 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6483 // Dispatched behavior.
6484 DECLARE_PRINTER(Script)
6485 DECLARE_VERIFIER(Script)
6487 static const int kSourceOffset = HeapObject::kHeaderSize;
6488 static const int kNameOffset = kSourceOffset + kPointerSize;
6489 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6490 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6491 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6492 static const int kWrapperOffset = kContextOffset + kPointerSize;
6493 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6494 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6495 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6496 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6497 static const int kEvalFrominstructionsOffsetOffset =
6498 kEvalFromSharedOffset + kPointerSize;
6499 static const int kSharedFunctionInfosOffset =
6500 kEvalFrominstructionsOffsetOffset + kPointerSize;
6501 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6502 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6503 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6504 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6507 int GetLineNumberWithArray(int code_pos);
6509 // Bit positions in the flags field.
6510 static const int kCompilationTypeBit = 0;
6511 static const int kCompilationStateBit = 1;
6512 static const int kOriginOptionsShift = 2;
6513 static const int kOriginOptionsSize = 3;
6514 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6515 << kOriginOptionsShift;
6517 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6521 // List of builtin functions we want to identify to improve code
6524 // Each entry has a name of a global object property holding an object
6525 // optionally followed by ".prototype", a name of a builtin function
6526 // on the object (the one the id is set for), and a label.
6528 // Installation of ids for the selected builtin functions is handled
6529 // by the bootstrapper.
6530 #define FUNCTIONS_WITH_ID_LIST(V) \
6531 V(Array.prototype, indexOf, ArrayIndexOf) \
6532 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6533 V(Array.prototype, push, ArrayPush) \
6534 V(Array.prototype, pop, ArrayPop) \
6535 V(Array.prototype, shift, ArrayShift) \
6536 V(Function.prototype, apply, FunctionApply) \
6537 V(Function.prototype, call, FunctionCall) \
6538 V(String.prototype, charCodeAt, StringCharCodeAt) \
6539 V(String.prototype, charAt, StringCharAt) \
6540 V(String, fromCharCode, StringFromCharCode) \
6541 V(Math, random, MathRandom) \
6542 V(Math, floor, MathFloor) \
6543 V(Math, round, MathRound) \
6544 V(Math, ceil, MathCeil) \
6545 V(Math, abs, MathAbs) \
6546 V(Math, log, MathLog) \
6547 V(Math, exp, MathExp) \
6548 V(Math, sqrt, MathSqrt) \
6549 V(Math, pow, MathPow) \
6550 V(Math, max, MathMax) \
6551 V(Math, min, MathMin) \
6552 V(Math, cos, MathCos) \
6553 V(Math, sin, MathSin) \
6554 V(Math, tan, MathTan) \
6555 V(Math, acos, MathAcos) \
6556 V(Math, asin, MathAsin) \
6557 V(Math, atan, MathAtan) \
6558 V(Math, atan2, MathAtan2) \
6559 V(Math, imul, MathImul) \
6560 V(Math, clz32, MathClz32) \
6561 V(Math, fround, MathFround)
6563 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6564 V(Atomics, load, AtomicsLoad) \
6565 V(Atomics, store, AtomicsStore)
6567 enum BuiltinFunctionId {
6569 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6571 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6572 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6573 #undef DECLARE_FUNCTION_ID
6574 // Fake id for a special case of Math.pow. Note, it continues the
6575 // list of math functions.
6580 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6581 // that both {code} and {literals} can be NULL to pass search result status.
6582 struct CodeAndLiterals {
6583 Code* code; // Cached optimized code.
6584 FixedArray* literals; // Cached literals array.
6588 // SharedFunctionInfo describes the JSFunction information that can be
6589 // shared by multiple instances of the function.
6590 class SharedFunctionInfo: public HeapObject {
6592 // [name]: Function name.
6593 DECL_ACCESSORS(name, Object)
6595 // [code]: Function code.
6596 DECL_ACCESSORS(code, Code)
6597 inline void ReplaceCode(Code* code);
6599 // [optimized_code_map]: Map from native context to optimized code
6600 // and a shared literals array or Smi(0) if none.
6601 DECL_ACCESSORS(optimized_code_map, Object)
6603 // Returns entry from optimized code map for specified context and OSR entry.
6604 // Note that {code == nullptr} indicates no matching entry has been found,
6605 // whereas {literals == nullptr} indicates the code is context-independent.
6606 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6607 BailoutId osr_ast_id);
6609 // Clear optimized code map.
6610 void ClearOptimizedCodeMap();
6612 // Removed a specific optimized code object from the optimized code map.
6613 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6615 // Trims the optimized code map after entries have been removed.
6616 void TrimOptimizedCodeMap(int shrink_by);
6618 // Add a new entry to the optimized code map for context-independent code.
6619 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6622 // Add a new entry to the optimized code map for context-dependent code.
6623 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6624 Handle<Context> native_context,
6626 Handle<FixedArray> literals,
6627 BailoutId osr_ast_id);
6629 // Set up the link between shared function info and the script. The shared
6630 // function info is added to the list on the script.
6631 static void SetScript(Handle<SharedFunctionInfo> shared,
6632 Handle<Object> script_object);
6634 // Layout description of the optimized code map.
6635 static const int kNextMapIndex = 0;
6636 static const int kSharedCodeIndex = 1;
6637 static const int kEntriesStart = 2;
6638 static const int kContextOffset = 0;
6639 static const int kCachedCodeOffset = 1;
6640 static const int kLiteralsOffset = 2;
6641 static const int kOsrAstIdOffset = 3;
6642 static const int kEntryLength = 4;
6643 static const int kInitialLength = kEntriesStart + kEntryLength;
6645 // [scope_info]: Scope info.
6646 DECL_ACCESSORS(scope_info, ScopeInfo)
6648 // [construct stub]: Code stub for constructing instances of this function.
6649 DECL_ACCESSORS(construct_stub, Code)
6651 // Returns if this function has been compiled to native code yet.
6652 inline bool is_compiled();
6654 // [length]: The function length - usually the number of declared parameters.
6655 // Use up to 2^30 parameters.
6656 inline int length() const;
6657 inline void set_length(int value);
6659 // [internal formal parameter count]: The declared number of parameters.
6660 // For subclass constructors, also includes new.target.
6661 // The size of function's frame is internal_formal_parameter_count + 1.
6662 inline int internal_formal_parameter_count() const;
6663 inline void set_internal_formal_parameter_count(int value);
6665 // Set the formal parameter count so the function code will be
6666 // called without using argument adaptor frames.
6667 inline void DontAdaptArguments();
6669 // [expected_nof_properties]: Expected number of properties for the function.
6670 inline int expected_nof_properties() const;
6671 inline void set_expected_nof_properties(int value);
6673 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6674 // (increasingly) from crankshafted code where sufficient feedback isn't
6676 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6678 // Unconditionally clear the type feedback vector (including vector ICs).
6679 void ClearTypeFeedbackInfo();
6681 // Clear the type feedback vector with a more subtle policy at GC time.
6682 void ClearTypeFeedbackInfoAtGCTime();
6685 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6686 // even if the GC moves this SharedFunctionInfo.
6687 inline int unique_id() const;
6688 inline void set_unique_id(int value);
6691 // [instance class name]: class name for instances.
6692 DECL_ACCESSORS(instance_class_name, Object)
6694 // [function data]: This field holds some additional data for function.
6695 // Currently it has one of:
6696 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6697 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6698 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6699 // In the long run we don't want all functions to have this field but
6700 // we can fix that when we have a better model for storing hidden data
6702 DECL_ACCESSORS(function_data, Object)
6704 inline bool IsApiFunction();
6705 inline FunctionTemplateInfo* get_api_func_data();
6706 inline bool HasBuiltinFunctionId();
6707 inline BuiltinFunctionId builtin_function_id();
6708 inline bool HasBytecodeArray();
6709 inline BytecodeArray* bytecode_array();
6711 // [script info]: Script from which the function originates.
6712 DECL_ACCESSORS(script, Object)
6714 // [num_literals]: Number of literals used by this function.
6715 inline int num_literals() const;
6716 inline void set_num_literals(int value);
6718 // [start_position_and_type]: Field used to store both the source code
6719 // position, whether or not the function is a function expression,
6720 // and whether or not the function is a toplevel function. The two
6721 // least significants bit indicates whether the function is an
6722 // expression and the rest contains the source code position.
6723 inline int start_position_and_type() const;
6724 inline void set_start_position_and_type(int value);
6726 // The function is subject to debugging if a debug info is attached.
6727 inline bool HasDebugInfo();
6728 inline DebugInfo* GetDebugInfo();
6730 // A function has debug code if the compiled code has debug break slots.
6731 inline bool HasDebugCode();
6733 // [debug info]: Debug information.
6734 DECL_ACCESSORS(debug_info, Object)
6736 // [inferred name]: Name inferred from variable or property
6737 // assignment of this function. Used to facilitate debugging and
6738 // profiling of JavaScript code written in OO style, where almost
6739 // all functions are anonymous but are assigned to object
6741 DECL_ACCESSORS(inferred_name, String)
6743 // The function's name if it is non-empty, otherwise the inferred name.
6744 String* DebugName();
6746 // Position of the 'function' token in the script source.
6747 inline int function_token_position() const;
6748 inline void set_function_token_position(int function_token_position);
6750 // Position of this function in the script source.
6751 inline int start_position() const;
6752 inline void set_start_position(int start_position);
6754 // End position of this function in the script source.
6755 inline int end_position() const;
6756 inline void set_end_position(int end_position);
6758 // Is this function a function expression in the source code.
6759 DECL_BOOLEAN_ACCESSORS(is_expression)
6761 // Is this function a top-level function (scripts, evals).
6762 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6764 // Bit field containing various information collected by the compiler to
6765 // drive optimization.
6766 inline int compiler_hints() const;
6767 inline void set_compiler_hints(int value);
6769 inline int ast_node_count() const;
6770 inline void set_ast_node_count(int count);
6772 inline int profiler_ticks() const;
6773 inline void set_profiler_ticks(int ticks);
6775 // Inline cache age is used to infer whether the function survived a context
6776 // disposal or not. In the former case we reset the opt_count.
6777 inline int ic_age();
6778 inline void set_ic_age(int age);
6780 // Indicates if this function can be lazy compiled.
6781 // This is used to determine if we can safely flush code from a function
6782 // when doing GC if we expect that the function will no longer be used.
6783 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6785 // Indicates if this function can be lazy compiled without a context.
6786 // This is used to determine if we can force compilation without reaching
6787 // the function through program execution but through other means (e.g. heap
6788 // iteration by the debugger).
6789 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6791 // Indicates whether optimizations have been disabled for this
6792 // shared function info. If a function is repeatedly optimized or if
6793 // we cannot optimize the function we disable optimization to avoid
6794 // spending time attempting to optimize it again.
6795 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6797 // Indicates the language mode.
6798 inline LanguageMode language_mode();
6799 inline void set_language_mode(LanguageMode language_mode);
6801 // False if the function definitely does not allocate an arguments object.
6802 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6804 // Indicates that this function uses a super property (or an eval that may
6805 // use a super property).
6806 // This is needed to set up the [[HomeObject]] on the function instance.
6807 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6809 // True if the function has any duplicated parameter names.
6810 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6812 // Indicates whether the function is a native function.
6813 // These needs special treatment in .call and .apply since
6814 // null passed as the receiver should not be translated to the
6816 DECL_BOOLEAN_ACCESSORS(native)
6818 // Indicate that this function should always be inlined in optimized code.
6819 DECL_BOOLEAN_ACCESSORS(force_inline)
6821 // Indicates that the function was created by the Function function.
6822 // Though it's anonymous, toString should treat it as if it had the name
6823 // "anonymous". We don't set the name itself so that the system does not
6824 // see a binding for it.
6825 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6827 // Indicates whether the function is a bound function created using
6828 // the bind function.
6829 DECL_BOOLEAN_ACCESSORS(bound)
6831 // Indicates that the function is anonymous (the name field can be set
6832 // through the API, which does not change this flag).
6833 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6835 // Is this a function or top-level/eval code.
6836 DECL_BOOLEAN_ACCESSORS(is_function)
6838 // Indicates that code for this function cannot be compiled with Crankshaft.
6839 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6841 // Indicates that code for this function cannot be flushed.
6842 DECL_BOOLEAN_ACCESSORS(dont_flush)
6844 // Indicates that this function is a generator.
6845 DECL_BOOLEAN_ACCESSORS(is_generator)
6847 // Indicates that this function is an arrow function.
6848 DECL_BOOLEAN_ACCESSORS(is_arrow)
6850 // Indicates that this function is a concise method.
6851 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6853 // Indicates that this function is an accessor (getter or setter).
6854 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6856 // Indicates that this function is a default constructor.
6857 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6859 // Indicates that this function is an asm function.
6860 DECL_BOOLEAN_ACCESSORS(asm_function)
6862 // Indicates that the the shared function info is deserialized from cache.
6863 DECL_BOOLEAN_ACCESSORS(deserialized)
6865 // Indicates that the the shared function info has never been compiled before.
6866 DECL_BOOLEAN_ACCESSORS(never_compiled)
6868 inline FunctionKind kind();
6869 inline void set_kind(FunctionKind kind);
6871 // Indicates whether or not the code in the shared function support
6873 inline bool has_deoptimization_support();
6875 // Enable deoptimization support through recompiled code.
6876 void EnableDeoptimizationSupport(Code* recompiled);
6878 // Disable (further) attempted optimization of all functions sharing this
6879 // shared function info.
6880 void DisableOptimization(BailoutReason reason);
6882 inline BailoutReason disable_optimization_reason();
6884 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6885 // code, returns whether it asserted (i.e., always true if assertions are
6887 bool VerifyBailoutId(BailoutId id);
6889 // [source code]: Source code for the function.
6890 bool HasSourceCode() const;
6891 Handle<Object> GetSourceCode();
6893 // Number of times the function was optimized.
6894 inline int opt_count();
6895 inline void set_opt_count(int opt_count);
6897 // Number of times the function was deoptimized.
6898 inline void set_deopt_count(int value);
6899 inline int deopt_count();
6900 inline void increment_deopt_count();
6902 // Number of time we tried to re-enable optimization after it
6903 // was disabled due to high number of deoptimizations.
6904 inline void set_opt_reenable_tries(int value);
6905 inline int opt_reenable_tries();
6907 inline void TryReenableOptimization();
6909 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6910 inline void set_counters(int value);
6911 inline int counters() const;
6913 // Stores opt_count and bailout_reason as bit-fields.
6914 inline void set_opt_count_and_bailout_reason(int value);
6915 inline int opt_count_and_bailout_reason() const;
6917 void set_disable_optimization_reason(BailoutReason reason) {
6918 set_opt_count_and_bailout_reason(
6919 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6923 // Tells whether this function should be subject to debugging.
6924 inline bool IsSubjectToDebugging();
6926 // Check whether or not this function is inlineable.
6927 bool IsInlineable();
6929 // Source size of this function.
6932 // Calculate the instance size.
6933 int CalculateInstanceSize();
6935 // Calculate the number of in-object properties.
6936 int CalculateInObjectProperties();
6938 inline bool is_simple_parameter_list();
6940 // Initialize a SharedFunctionInfo from a parsed function literal.
6941 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6942 FunctionLiteral* lit);
6944 // Dispatched behavior.
6945 DECLARE_PRINTER(SharedFunctionInfo)
6946 DECLARE_VERIFIER(SharedFunctionInfo)
6948 void ResetForNewContext(int new_ic_age);
6950 DECLARE_CAST(SharedFunctionInfo)
6953 static const int kDontAdaptArgumentsSentinel = -1;
6955 // Layout description.
6957 static const int kNameOffset = HeapObject::kHeaderSize;
6958 static const int kCodeOffset = kNameOffset + kPointerSize;
6959 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6960 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6961 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6962 static const int kInstanceClassNameOffset =
6963 kConstructStubOffset + kPointerSize;
6964 static const int kFunctionDataOffset =
6965 kInstanceClassNameOffset + kPointerSize;
6966 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6967 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6968 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6969 static const int kFeedbackVectorOffset =
6970 kInferredNameOffset + kPointerSize;
6972 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6973 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6975 // Just to not break the postmortrem support with conditional offsets
6976 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6977 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6980 #if V8_HOST_ARCH_32_BIT
6982 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6983 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6984 static const int kExpectedNofPropertiesOffset =
6985 kFormalParameterCountOffset + kPointerSize;
6986 static const int kNumLiteralsOffset =
6987 kExpectedNofPropertiesOffset + kPointerSize;
6988 static const int kStartPositionAndTypeOffset =
6989 kNumLiteralsOffset + kPointerSize;
6990 static const int kEndPositionOffset =
6991 kStartPositionAndTypeOffset + kPointerSize;
6992 static const int kFunctionTokenPositionOffset =
6993 kEndPositionOffset + kPointerSize;
6994 static const int kCompilerHintsOffset =
6995 kFunctionTokenPositionOffset + kPointerSize;
6996 static const int kOptCountAndBailoutReasonOffset =
6997 kCompilerHintsOffset + kPointerSize;
6998 static const int kCountersOffset =
6999 kOptCountAndBailoutReasonOffset + kPointerSize;
7000 static const int kAstNodeCountOffset =
7001 kCountersOffset + kPointerSize;
7002 static const int kProfilerTicksOffset =
7003 kAstNodeCountOffset + kPointerSize;
7006 static const int kSize = kProfilerTicksOffset + kPointerSize;
7008 // The only reason to use smi fields instead of int fields
7009 // is to allow iteration without maps decoding during
7010 // garbage collections.
7011 // To avoid wasting space on 64-bit architectures we use
7012 // the following trick: we group integer fields into pairs
7013 // The least significant integer in each pair is shifted left by 1.
7014 // By doing this we guarantee that LSB of each kPointerSize aligned
7015 // word is not set and thus this word cannot be treated as pointer
7016 // to HeapObject during old space traversal.
7017 #if V8_TARGET_LITTLE_ENDIAN
7018 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
7019 static const int kFormalParameterCountOffset =
7020 kLengthOffset + kIntSize;
7022 static const int kExpectedNofPropertiesOffset =
7023 kFormalParameterCountOffset + kIntSize;
7024 static const int kNumLiteralsOffset =
7025 kExpectedNofPropertiesOffset + kIntSize;
7027 static const int kEndPositionOffset =
7028 kNumLiteralsOffset + kIntSize;
7029 static const int kStartPositionAndTypeOffset =
7030 kEndPositionOffset + kIntSize;
7032 static const int kFunctionTokenPositionOffset =
7033 kStartPositionAndTypeOffset + kIntSize;
7034 static const int kCompilerHintsOffset =
7035 kFunctionTokenPositionOffset + kIntSize;
7037 static const int kOptCountAndBailoutReasonOffset =
7038 kCompilerHintsOffset + kIntSize;
7039 static const int kCountersOffset =
7040 kOptCountAndBailoutReasonOffset + kIntSize;
7042 static const int kAstNodeCountOffset =
7043 kCountersOffset + kIntSize;
7044 static const int kProfilerTicksOffset =
7045 kAstNodeCountOffset + kIntSize;
7048 static const int kSize = kProfilerTicksOffset + kIntSize;
7050 #elif V8_TARGET_BIG_ENDIAN
7051 static const int kFormalParameterCountOffset =
7052 kLastPointerFieldOffset + kPointerSize;
7053 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
7055 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
7056 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
7058 static const int kStartPositionAndTypeOffset =
7059 kExpectedNofPropertiesOffset + kIntSize;
7060 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
7062 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
7063 static const int kFunctionTokenPositionOffset =
7064 kCompilerHintsOffset + kIntSize;
7066 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7067 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7069 static const int kProfilerTicksOffset =
7070 kOptCountAndBailoutReasonOffset + kIntSize;
7071 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7074 static const int kSize = kAstNodeCountOffset + kIntSize;
7077 #error Unknown byte ordering
7078 #endif // Big endian
7082 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7084 typedef FixedBodyDescriptor<kNameOffset,
7085 kLastPointerFieldOffset + kPointerSize,
7086 kSize> BodyDescriptor;
7088 // Bit positions in start_position_and_type.
7089 // The source code start position is in the 30 most significant bits of
7090 // the start_position_and_type field.
7091 static const int kIsExpressionBit = 0;
7092 static const int kIsTopLevelBit = 1;
7093 static const int kStartPositionShift = 2;
7094 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7096 // Bit positions in compiler_hints.
7097 enum CompilerHints {
7098 kAllowLazyCompilation,
7099 kAllowLazyCompilationWithoutContext,
7100 kOptimizationDisabled,
7101 kStrictModeFunction,
7102 kStrongModeFunction,
7105 kHasDuplicateParameters,
7110 kNameShouldPrintAsAnonymous,
7117 kIsAccessorFunction,
7118 kIsDefaultConstructor,
7119 kIsSubclassConstructor,
7125 kCompilerHintsCount // Pseudo entry
7127 // Add hints for other modes when they're added.
7128 STATIC_ASSERT(LANGUAGE_END == 3);
7130 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
7132 class DeoptCountBits : public BitField<int, 0, 4> {};
7133 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7134 class ICAgeBits : public BitField<int, 22, 8> {};
7136 class OptCountBits : public BitField<int, 0, 22> {};
7137 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7140 #if V8_HOST_ARCH_32_BIT
7141 // On 32 bit platforms, compiler hints is a smi.
7142 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7143 static const int kCompilerHintsSize = kPointerSize;
7145 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7146 static const int kCompilerHintsSmiTagSize = 0;
7147 static const int kCompilerHintsSize = kIntSize;
7150 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7151 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7154 // Constants for optimizing codegen for strict mode function and
7156 // Allows to use byte-width instructions.
7157 static const int kStrictModeBitWithinByte =
7158 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7159 static const int kStrongModeBitWithinByte =
7160 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7162 static const int kNativeBitWithinByte =
7163 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7165 #if defined(V8_TARGET_LITTLE_ENDIAN)
7166 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7167 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7168 static const int kStrongModeByteOffset =
7169 kCompilerHintsOffset +
7170 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7171 static const int kNativeByteOffset = kCompilerHintsOffset +
7172 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7173 #elif defined(V8_TARGET_BIG_ENDIAN)
7174 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7175 (kCompilerHintsSize - 1) -
7176 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7177 static const int kStrongModeByteOffset =
7178 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
7179 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7180 static const int kNativeByteOffset = kCompilerHintsOffset +
7181 (kCompilerHintsSize - 1) -
7182 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7184 #error Unknown byte ordering
7188 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7192 // Printing support.
7193 struct SourceCodeOf {
7194 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7195 : value(v), max_length(max) {}
7196 const SharedFunctionInfo* value;
7201 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7204 class JSGeneratorObject: public JSObject {
7206 // [function]: The function corresponding to this generator object.
7207 DECL_ACCESSORS(function, JSFunction)
7209 // [context]: The context of the suspended computation.
7210 DECL_ACCESSORS(context, Context)
7212 // [receiver]: The receiver of the suspended computation.
7213 DECL_ACCESSORS(receiver, Object)
7215 // [continuation]: Offset into code of continuation.
7217 // A positive offset indicates a suspended generator. The special
7218 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7219 // cannot be resumed.
7220 inline int continuation() const;
7221 inline void set_continuation(int continuation);
7222 inline bool is_closed();
7223 inline bool is_executing();
7224 inline bool is_suspended();
7226 // [operand_stack]: Saved operand stack.
7227 DECL_ACCESSORS(operand_stack, FixedArray)
7229 DECLARE_CAST(JSGeneratorObject)
7231 // Dispatched behavior.
7232 DECLARE_PRINTER(JSGeneratorObject)
7233 DECLARE_VERIFIER(JSGeneratorObject)
7235 // Magic sentinel values for the continuation.
7236 static const int kGeneratorExecuting = -1;
7237 static const int kGeneratorClosed = 0;
7239 // Layout description.
7240 static const int kFunctionOffset = JSObject::kHeaderSize;
7241 static const int kContextOffset = kFunctionOffset + kPointerSize;
7242 static const int kReceiverOffset = kContextOffset + kPointerSize;
7243 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7244 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7245 static const int kSize = kOperandStackOffset + kPointerSize;
7247 // Resume mode, for use by runtime functions.
7248 enum ResumeMode { NEXT, THROW };
7250 // Yielding from a generator returns an object with the following inobject
7251 // properties. See Context::iterator_result_map() for the map.
7252 static const int kResultValuePropertyIndex = 0;
7253 static const int kResultDonePropertyIndex = 1;
7254 static const int kResultPropertyCount = 2;
7256 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7257 static const int kResultDonePropertyOffset =
7258 kResultValuePropertyOffset + kPointerSize;
7259 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7262 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7266 // Representation for module instance objects.
7267 class JSModule: public JSObject {
7269 // [context]: the context holding the module's locals, or undefined if none.
7270 DECL_ACCESSORS(context, Object)
7272 // [scope_info]: Scope info.
7273 DECL_ACCESSORS(scope_info, ScopeInfo)
7275 DECLARE_CAST(JSModule)
7277 // Dispatched behavior.
7278 DECLARE_PRINTER(JSModule)
7279 DECLARE_VERIFIER(JSModule)
7281 // Layout description.
7282 static const int kContextOffset = JSObject::kHeaderSize;
7283 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7284 static const int kSize = kScopeInfoOffset + kPointerSize;
7287 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7291 // JSFunction describes JavaScript functions.
7292 class JSFunction: public JSObject {
7294 // [prototype_or_initial_map]:
7295 DECL_ACCESSORS(prototype_or_initial_map, Object)
7297 // [shared]: The information about the function that
7298 // can be shared by instances.
7299 DECL_ACCESSORS(shared, SharedFunctionInfo)
7301 // [context]: The context for this function.
7302 inline Context* context();
7303 inline void set_context(Object* context);
7304 inline JSObject* global_proxy();
7306 // [code]: The generated code object for this function. Executed
7307 // when the function is invoked, e.g. foo() or new foo(). See
7308 // [[Call]] and [[Construct]] description in ECMA-262, section
7310 inline Code* code();
7311 inline void set_code(Code* code);
7312 inline void set_code_no_write_barrier(Code* code);
7313 inline void ReplaceCode(Code* code);
7315 // Tells whether this function is builtin.
7316 inline bool IsBuiltin();
7318 // Tells whether this function inlines the given shared function info.
7319 bool Inlines(SharedFunctionInfo* candidate);
7321 // Tells whether this function should be subject to debugging.
7322 inline bool IsSubjectToDebugging();
7324 // Tells whether or not the function needs arguments adaption.
7325 inline bool NeedsArgumentsAdaption();
7327 // Tells whether or not this function has been optimized.
7328 inline bool IsOptimized();
7330 // Mark this function for lazy recompilation. The function will be
7331 // recompiled the next time it is executed.
7332 void MarkForOptimization();
7333 void AttemptConcurrentOptimization();
7335 // Tells whether or not the function is already marked for lazy
7337 inline bool IsMarkedForOptimization();
7338 inline bool IsMarkedForConcurrentOptimization();
7340 // Tells whether or not the function is on the concurrent recompilation queue.
7341 inline bool IsInOptimizationQueue();
7343 // Inobject slack tracking is the way to reclaim unused inobject space.
7345 // The instance size is initially determined by adding some slack to
7346 // expected_nof_properties (to allow for a few extra properties added
7347 // after the constructor). There is no guarantee that the extra space
7348 // will not be wasted.
7350 // Here is the algorithm to reclaim the unused inobject space:
7351 // - Detect the first constructor call for this JSFunction.
7352 // When it happens enter the "in progress" state: initialize construction
7353 // counter in the initial_map.
7354 // - While the tracking is in progress create objects filled with
7355 // one_pointer_filler_map instead of undefined_value. This way they can be
7356 // resized quickly and safely.
7357 // - Once enough objects have been created compute the 'slack'
7358 // (traverse the map transition tree starting from the
7359 // initial_map and find the lowest value of unused_property_fields).
7360 // - Traverse the transition tree again and decrease the instance size
7361 // of every map. Existing objects will resize automatically (they are
7362 // filled with one_pointer_filler_map). All further allocations will
7363 // use the adjusted instance size.
7364 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7365 // allocations made using different closures could actually create different
7366 // kind of objects (see prototype inheritance pattern).
7368 // Important: inobject slack tracking is not attempted during the snapshot
7371 // True if the initial_map is set and the object constructions countdown
7372 // counter is not zero.
7373 static const int kGenerousAllocationCount =
7374 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7375 inline bool IsInobjectSlackTrackingInProgress();
7377 // Starts the tracking.
7378 // Initializes object constructions countdown counter in the initial map.
7379 void StartInobjectSlackTracking();
7381 // Completes the tracking.
7382 void CompleteInobjectSlackTracking();
7384 // [literals_or_bindings]: Fixed array holding either
7385 // the materialized literals or the bindings of a bound function.
7387 // If the function contains object, regexp or array literals, the
7388 // literals array prefix contains the object, regexp, and array
7389 // function to be used when creating these literals. This is
7390 // necessary so that we do not dynamically lookup the object, regexp
7391 // or array functions. Performing a dynamic lookup, we might end up
7392 // using the functions from a new context that we should not have
7395 // On bound functions, the array is a (copy-on-write) fixed-array containing
7396 // the function that was bound, bound this-value and any bound
7397 // arguments. Bound functions never contain literals.
7398 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7400 inline FixedArray* literals();
7401 inline void set_literals(FixedArray* literals);
7403 inline FixedArray* function_bindings();
7404 inline void set_function_bindings(FixedArray* bindings);
7406 // The initial map for an object created by this constructor.
7407 inline Map* initial_map();
7408 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7409 Handle<Object> prototype);
7410 inline bool has_initial_map();
7411 static void EnsureHasInitialMap(Handle<JSFunction> function);
7413 // Get and set the prototype property on a JSFunction. If the
7414 // function has an initial map the prototype is set on the initial
7415 // map. Otherwise, the prototype is put in the initial map field
7416 // until an initial map is needed.
7417 inline bool has_prototype();
7418 inline bool has_instance_prototype();
7419 inline Object* prototype();
7420 inline Object* instance_prototype();
7421 static void SetPrototype(Handle<JSFunction> function,
7422 Handle<Object> value);
7423 static void SetInstancePrototype(Handle<JSFunction> function,
7424 Handle<Object> value);
7426 // Creates a new closure for the fucntion with the same bindings,
7427 // bound values, and prototype. An equivalent of spec operations
7428 // ``CloneMethod`` and ``CloneBoundFunction``.
7429 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7431 // After prototype is removed, it will not be created when accessed, and
7432 // [[Construct]] from this function will not be allowed.
7433 bool RemovePrototype();
7434 inline bool should_have_prototype();
7436 // Accessor for this function's initial map's [[class]]
7437 // property. This is primarily used by ECMA native functions. This
7438 // method sets the class_name field of this function's initial map
7439 // to a given value. It creates an initial map if this function does
7440 // not have one. Note that this method does not copy the initial map
7441 // if it has one already, but simply replaces it with the new value.
7442 // Instances created afterwards will have a map whose [[class]] is
7443 // set to 'value', but there is no guarantees on instances created
7445 void SetInstanceClassName(String* name);
7447 // Returns if this function has been compiled to native code yet.
7448 inline bool is_compiled();
7450 // Returns `false` if formal parameters include rest parameters, optional
7451 // parameters, or destructuring parameters.
7452 // TODO(caitp): make this a flag set during parsing
7453 inline bool is_simple_parameter_list();
7455 // [next_function_link]: Links functions into various lists, e.g. the list
7456 // of optimized functions hanging off the native_context. The CodeFlusher
7457 // uses this link to chain together flushing candidates. Treated weakly
7458 // by the garbage collector.
7459 DECL_ACCESSORS(next_function_link, Object)
7461 // Prints the name of the function using PrintF.
7462 void PrintName(FILE* out = stdout);
7464 DECLARE_CAST(JSFunction)
7466 // Iterates the objects, including code objects indirectly referenced
7467 // through pointers to the first instruction in the code object.
7468 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7470 // Dispatched behavior.
7471 DECLARE_PRINTER(JSFunction)
7472 DECLARE_VERIFIER(JSFunction)
7474 // Returns the number of allocated literals.
7475 inline int NumberOfLiterals();
7477 // Used for flags such as --hydrogen-filter.
7478 bool PassesFilter(const char* raw_filter);
7480 // The function's name if it is configured, otherwise shared function info
7482 static Handle<String> GetDebugName(Handle<JSFunction> function);
7484 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7485 // kSize) is weak and has special handling during garbage collection.
7486 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7487 static const int kPrototypeOrInitialMapOffset =
7488 kCodeEntryOffset + kPointerSize;
7489 static const int kSharedFunctionInfoOffset =
7490 kPrototypeOrInitialMapOffset + kPointerSize;
7491 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7492 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7493 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7494 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7495 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7497 // Layout of the bound-function binding array.
7498 static const int kBoundFunctionIndex = 0;
7499 static const int kBoundThisIndex = 1;
7500 static const int kBoundArgumentsStartIndex = 2;
7503 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7507 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7508 // and the prototype is hidden. JSGlobalProxy always delegates
7509 // property accesses to its prototype if the prototype is not null.
7511 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7513 // Accessing a JSGlobalProxy requires security check.
7515 class JSGlobalProxy : public JSObject {
7517 // [native_context]: the owner native context of this global proxy object.
7518 // It is null value if this object is not used by any context.
7519 DECL_ACCESSORS(native_context, Object)
7521 // [hash]: The hash code property (undefined if not initialized yet).
7522 DECL_ACCESSORS(hash, Object)
7524 DECLARE_CAST(JSGlobalProxy)
7526 inline bool IsDetachedFrom(GlobalObject* global) const;
7528 // Dispatched behavior.
7529 DECLARE_PRINTER(JSGlobalProxy)
7530 DECLARE_VERIFIER(JSGlobalProxy)
7532 // Layout description.
7533 static const int kNativeContextOffset = JSObject::kHeaderSize;
7534 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7535 static const int kSize = kHashOffset + kPointerSize;
7538 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7542 // Common super class for JavaScript global objects and the special
7543 // builtins global objects.
7544 class GlobalObject: public JSObject {
7546 // [builtins]: the object holding the runtime routines written in JS.
7547 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7549 // [native context]: the natives corresponding to this global object.
7550 DECL_ACCESSORS(native_context, Context)
7552 // [global proxy]: the global proxy object of the context
7553 DECL_ACCESSORS(global_proxy, JSObject)
7555 DECLARE_CAST(GlobalObject)
7557 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7559 // Ensure that the global object has a cell for the given property name.
7560 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7563 // Layout description.
7564 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7565 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7566 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7567 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7570 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7574 // JavaScript global object.
7575 class JSGlobalObject: public GlobalObject {
7577 DECLARE_CAST(JSGlobalObject)
7579 inline bool IsDetached();
7581 // Dispatched behavior.
7582 DECLARE_PRINTER(JSGlobalObject)
7583 DECLARE_VERIFIER(JSGlobalObject)
7585 // Layout description.
7586 static const int kSize = GlobalObject::kHeaderSize;
7589 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7593 // Builtins global object which holds the runtime routines written in
7595 class JSBuiltinsObject: public GlobalObject {
7597 // Accessors for the runtime routines written in JavaScript.
7598 inline Object* javascript_builtin(Builtins::JavaScript id);
7599 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7601 DECLARE_CAST(JSBuiltinsObject)
7603 // Dispatched behavior.
7604 DECLARE_PRINTER(JSBuiltinsObject)
7605 DECLARE_VERIFIER(JSBuiltinsObject)
7607 // Layout description. The size of the builtins object includes
7608 // room for two pointers per runtime routine written in javascript
7609 // (function and code object).
7610 static const int kJSBuiltinsCount = Builtins::id_count;
7611 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7612 static const int kSize =
7613 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7615 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7616 return kJSBuiltinsOffset + id * kPointerSize;
7620 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7624 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7625 class JSValue: public JSObject {
7627 // [value]: the object being wrapped.
7628 DECL_ACCESSORS(value, Object)
7630 DECLARE_CAST(JSValue)
7632 // Dispatched behavior.
7633 DECLARE_PRINTER(JSValue)
7634 DECLARE_VERIFIER(JSValue)
7636 // Layout description.
7637 static const int kValueOffset = JSObject::kHeaderSize;
7638 static const int kSize = kValueOffset + kPointerSize;
7641 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7647 // Representation for JS date objects.
7648 class JSDate: public JSObject {
7650 // If one component is NaN, all of them are, indicating a NaN time value.
7651 // [value]: the time value.
7652 DECL_ACCESSORS(value, Object)
7653 // [year]: caches year. Either undefined, smi, or NaN.
7654 DECL_ACCESSORS(year, Object)
7655 // [month]: caches month. Either undefined, smi, or NaN.
7656 DECL_ACCESSORS(month, Object)
7657 // [day]: caches day. Either undefined, smi, or NaN.
7658 DECL_ACCESSORS(day, Object)
7659 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7660 DECL_ACCESSORS(weekday, Object)
7661 // [hour]: caches hours. Either undefined, smi, or NaN.
7662 DECL_ACCESSORS(hour, Object)
7663 // [min]: caches minutes. Either undefined, smi, or NaN.
7664 DECL_ACCESSORS(min, Object)
7665 // [sec]: caches seconds. Either undefined, smi, or NaN.
7666 DECL_ACCESSORS(sec, Object)
7667 // [cache stamp]: sample of the date cache stamp at the
7668 // moment when chached fields were cached.
7669 DECL_ACCESSORS(cache_stamp, Object)
7671 DECLARE_CAST(JSDate)
7673 // Returns the date field with the specified index.
7674 // See FieldIndex for the list of date fields.
7675 static Object* GetField(Object* date, Smi* index);
7677 void SetValue(Object* value, bool is_value_nan);
7680 // Dispatched behavior.
7681 DECLARE_PRINTER(JSDate)
7682 DECLARE_VERIFIER(JSDate)
7684 // The order is important. It must be kept in sync with date macros
7695 kFirstUncachedField,
7696 kMillisecond = kFirstUncachedField,
7700 kYearUTC = kFirstUTCField,
7713 // Layout description.
7714 static const int kValueOffset = JSObject::kHeaderSize;
7715 static const int kYearOffset = kValueOffset + kPointerSize;
7716 static const int kMonthOffset = kYearOffset + kPointerSize;
7717 static const int kDayOffset = kMonthOffset + kPointerSize;
7718 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7719 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7720 static const int kMinOffset = kHourOffset + kPointerSize;
7721 static const int kSecOffset = kMinOffset + kPointerSize;
7722 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7723 static const int kSize = kCacheStampOffset + kPointerSize;
7726 inline Object* DoGetField(FieldIndex index);
7728 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7730 // Computes and caches the cacheable fields of the date.
7731 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7734 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7738 // Representation of message objects used for error reporting through
7739 // the API. The messages are formatted in JavaScript so this object is
7740 // a real JavaScript object. The information used for formatting the
7741 // error messages are not directly accessible from JavaScript to
7742 // prevent leaking information to user code called during error
7744 class JSMessageObject: public JSObject {
7746 // [type]: the type of error message.
7747 inline int type() const;
7748 inline void set_type(int value);
7750 // [arguments]: the arguments for formatting the error message.
7751 DECL_ACCESSORS(argument, Object)
7753 // [script]: the script from which the error message originated.
7754 DECL_ACCESSORS(script, Object)
7756 // [stack_frames]: an array of stack frames for this error object.
7757 DECL_ACCESSORS(stack_frames, Object)
7759 // [start_position]: the start position in the script for the error message.
7760 inline int start_position() const;
7761 inline void set_start_position(int value);
7763 // [end_position]: the end position in the script for the error message.
7764 inline int end_position() const;
7765 inline void set_end_position(int value);
7767 DECLARE_CAST(JSMessageObject)
7769 // Dispatched behavior.
7770 DECLARE_PRINTER(JSMessageObject)
7771 DECLARE_VERIFIER(JSMessageObject)
7773 // Layout description.
7774 static const int kTypeOffset = JSObject::kHeaderSize;
7775 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7776 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7777 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7778 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7779 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7780 static const int kSize = kEndPositionOffset + kPointerSize;
7782 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7783 kStackFramesOffset + kPointerSize,
7784 kSize> BodyDescriptor;
7788 // Regular expressions
7789 // The regular expression holds a single reference to a FixedArray in
7790 // the kDataOffset field.
7791 // The FixedArray contains the following data:
7792 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7793 // - reference to the original source string
7794 // - reference to the original flag string
7795 // If it is an atom regexp
7796 // - a reference to a literal string to search for
7797 // If it is an irregexp regexp:
7798 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7799 // used for tracking the last usage (used for code flushing).
7800 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7801 // used for tracking the last usage (used for code flushing)..
7802 // - max number of registers used by irregexp implementations.
7803 // - number of capture registers (output values) of the regexp.
7804 class JSRegExp: public JSObject {
7807 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7808 // ATOM: A simple string to match against using an indexOf operation.
7809 // IRREGEXP: Compiled with Irregexp.
7810 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7811 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7818 UNICODE_ESCAPES = 16
7823 explicit Flags(uint32_t value) : value_(value) { }
7824 bool is_global() { return (value_ & GLOBAL) != 0; }
7825 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7826 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7827 bool is_sticky() { return (value_ & STICKY) != 0; }
7828 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7829 uint32_t value() { return value_; }
7834 DECL_ACCESSORS(data, Object)
7836 inline Type TypeTag();
7837 inline int CaptureCount();
7838 inline Flags GetFlags();
7839 inline String* Pattern();
7840 inline Object* DataAt(int index);
7841 // Set implementation data after the object has been prepared.
7842 inline void SetDataAt(int index, Object* value);
7844 static int code_index(bool is_latin1) {
7846 return kIrregexpLatin1CodeIndex;
7848 return kIrregexpUC16CodeIndex;
7852 static int saved_code_index(bool is_latin1) {
7854 return kIrregexpLatin1CodeSavedIndex;
7856 return kIrregexpUC16CodeSavedIndex;
7860 DECLARE_CAST(JSRegExp)
7862 // Dispatched behavior.
7863 DECLARE_VERIFIER(JSRegExp)
7865 static const int kDataOffset = JSObject::kHeaderSize;
7866 static const int kSize = kDataOffset + kPointerSize;
7868 // Indices in the data array.
7869 static const int kTagIndex = 0;
7870 static const int kSourceIndex = kTagIndex + 1;
7871 static const int kFlagsIndex = kSourceIndex + 1;
7872 static const int kDataIndex = kFlagsIndex + 1;
7873 // The data fields are used in different ways depending on the
7874 // value of the tag.
7875 // Atom regexps (literal strings).
7876 static const int kAtomPatternIndex = kDataIndex;
7878 static const int kAtomDataSize = kAtomPatternIndex + 1;
7880 // Irregexp compiled code or bytecode for Latin1. If compilation
7881 // fails, this fields hold an exception object that should be
7882 // thrown if the regexp is used again.
7883 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7884 // Irregexp compiled code or bytecode for UC16. If compilation
7885 // fails, this fields hold an exception object that should be
7886 // thrown if the regexp is used again.
7887 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7889 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7890 // is a potential candidate for flushing.
7891 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7892 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7893 // a potential candidate for flushing.
7894 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7896 // Maximal number of registers used by either Latin1 or UC16.
7897 // Only used to check that there is enough stack space
7898 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7899 // Number of captures in the compiled regexp.
7900 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7902 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7904 // Offsets directly into the data fixed array.
7905 static const int kDataTagOffset =
7906 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7907 static const int kDataOneByteCodeOffset =
7908 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7909 static const int kDataUC16CodeOffset =
7910 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7911 static const int kIrregexpCaptureCountOffset =
7912 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7914 // In-object fields.
7915 static const int kSourceFieldIndex = 0;
7916 static const int kGlobalFieldIndex = 1;
7917 static const int kIgnoreCaseFieldIndex = 2;
7918 static const int kMultilineFieldIndex = 3;
7919 static const int kLastIndexFieldIndex = 4;
7920 static const int kInObjectFieldCount = 5;
7922 // The uninitialized value for a regexp code object.
7923 static const int kUninitializedValue = -1;
7925 // The compilation error value for the regexp code object. The real error
7926 // object is in the saved code field.
7927 static const int kCompilationErrorValue = -2;
7929 // When we store the sweep generation at which we moved the code from the
7930 // code index to the saved code index we mask it of to be in the [0:255]
7932 static const int kCodeAgeMask = 0xff;
7936 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7938 static inline bool IsMatch(HashTableKey* key, Object* value) {
7939 return key->IsMatch(value);
7942 static inline uint32_t Hash(HashTableKey* key) {
7946 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7947 return key->HashForObject(object);
7950 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7952 static const int kPrefixSize = 0;
7953 static const int kEntrySize = 2;
7957 // This cache is used in two different variants. For regexp caching, it simply
7958 // maps identifying info of the regexp to the cached regexp object. Scripts and
7959 // eval code only gets cached after a second probe for the code object. To do
7960 // so, on first "put" only a hash identifying the source is entered into the
7961 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7962 // such lifetimes get reduced, and removed once they reach zero. If a second put
7963 // is called while such a hash is live in the cache, the hash gets replaced by
7964 // an actual cache entry. Age also removes stale live entries from the cache.
7965 // Such entries are identified by SharedFunctionInfos pointing to either the
7966 // recompilation stub, or to "old" code. This avoids memory leaks due to
7967 // premature caching of scripts and eval strings that are never needed later.
7968 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7969 CompilationCacheShape,
7972 // Find cached value for a string key, otherwise return null.
7973 Handle<Object> Lookup(
7974 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7975 Handle<Object> LookupEval(
7976 Handle<String> src, Handle<SharedFunctionInfo> shared,
7977 LanguageMode language_mode, int scope_position);
7978 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7979 static Handle<CompilationCacheTable> Put(
7980 Handle<CompilationCacheTable> cache, Handle<String> src,
7981 Handle<Context> context, LanguageMode language_mode,
7982 Handle<Object> value);
7983 static Handle<CompilationCacheTable> PutEval(
7984 Handle<CompilationCacheTable> cache, Handle<String> src,
7985 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7986 int scope_position);
7987 static Handle<CompilationCacheTable> PutRegExp(
7988 Handle<CompilationCacheTable> cache, Handle<String> src,
7989 JSRegExp::Flags flags, Handle<FixedArray> value);
7990 void Remove(Object* value);
7992 static const int kHashGenerations = 10;
7994 DECLARE_CAST(CompilationCacheTable)
7997 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8001 class CodeCache: public Struct {
8003 DECL_ACCESSORS(default_cache, FixedArray)
8004 DECL_ACCESSORS(normal_type_cache, Object)
8006 // Add the code object to the cache.
8008 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
8010 // Lookup code object in the cache. Returns code object if found and undefined
8012 Object* Lookup(Name* name, Code::Flags flags);
8014 // Get the internal index of a code object in the cache. Returns -1 if the
8015 // code object is not in that cache. This index can be used to later call
8016 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8018 int GetIndex(Object* name, Code* code);
8020 // Remove an object from the cache with the provided internal index.
8021 void RemoveByIndex(Object* name, Code* code, int index);
8023 DECLARE_CAST(CodeCache)
8025 // Dispatched behavior.
8026 DECLARE_PRINTER(CodeCache)
8027 DECLARE_VERIFIER(CodeCache)
8029 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8030 static const int kNormalTypeCacheOffset =
8031 kDefaultCacheOffset + kPointerSize;
8032 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8035 static void UpdateDefaultCache(
8036 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8037 static void UpdateNormalTypeCache(
8038 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8039 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8040 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8042 // Code cache layout of the default cache. Elements are alternating name and
8043 // code objects for non normal load/store/call IC's.
8044 static const int kCodeCacheEntrySize = 2;
8045 static const int kCodeCacheEntryNameOffset = 0;
8046 static const int kCodeCacheEntryCodeOffset = 1;
8048 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8052 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8054 static inline bool IsMatch(HashTableKey* key, Object* value) {
8055 return key->IsMatch(value);
8058 static inline uint32_t Hash(HashTableKey* key) {
8062 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8063 return key->HashForObject(object);
8066 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8068 static const int kPrefixSize = 0;
8069 static const int kEntrySize = 2;
8073 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8074 CodeCacheHashTableShape,
8077 Object* Lookup(Name* name, Code::Flags flags);
8078 static Handle<CodeCacheHashTable> Put(
8079 Handle<CodeCacheHashTable> table,
8083 int GetIndex(Name* name, Code::Flags flags);
8084 void RemoveByIndex(int index);
8086 DECLARE_CAST(CodeCacheHashTable)
8088 // Initial size of the fixed array backing the hash table.
8089 static const int kInitialSize = 64;
8092 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8096 class PolymorphicCodeCache: public Struct {
8098 DECL_ACCESSORS(cache, Object)
8100 static void Update(Handle<PolymorphicCodeCache> cache,
8101 MapHandleList* maps,
8106 // Returns an undefined value if the entry is not found.
8107 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8109 DECLARE_CAST(PolymorphicCodeCache)
8111 // Dispatched behavior.
8112 DECLARE_PRINTER(PolymorphicCodeCache)
8113 DECLARE_VERIFIER(PolymorphicCodeCache)
8115 static const int kCacheOffset = HeapObject::kHeaderSize;
8116 static const int kSize = kCacheOffset + kPointerSize;
8119 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8123 class PolymorphicCodeCacheHashTable
8124 : public HashTable<PolymorphicCodeCacheHashTable,
8125 CodeCacheHashTableShape,
8128 Object* Lookup(MapHandleList* maps, int code_kind);
8130 static Handle<PolymorphicCodeCacheHashTable> Put(
8131 Handle<PolymorphicCodeCacheHashTable> hash_table,
8132 MapHandleList* maps,
8136 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8138 static const int kInitialSize = 64;
8140 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8144 class TypeFeedbackInfo: public Struct {
8146 inline int ic_total_count();
8147 inline void set_ic_total_count(int count);
8149 inline int ic_with_type_info_count();
8150 inline void change_ic_with_type_info_count(int delta);
8152 inline int ic_generic_count();
8153 inline void change_ic_generic_count(int delta);
8155 inline void initialize_storage();
8157 inline void change_own_type_change_checksum();
8158 inline int own_type_change_checksum();
8160 inline void set_inlined_type_change_checksum(int checksum);
8161 inline bool matches_inlined_type_change_checksum(int checksum);
8163 DECLARE_CAST(TypeFeedbackInfo)
8165 // Dispatched behavior.
8166 DECLARE_PRINTER(TypeFeedbackInfo)
8167 DECLARE_VERIFIER(TypeFeedbackInfo)
8169 static const int kStorage1Offset = HeapObject::kHeaderSize;
8170 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8171 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8172 static const int kSize = kStorage3Offset + kPointerSize;
8175 static const int kTypeChangeChecksumBits = 7;
8177 class ICTotalCountField: public BitField<int, 0,
8178 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8179 class OwnTypeChangeChecksum: public BitField<int,
8180 kSmiValueSize - kTypeChangeChecksumBits,
8181 kTypeChangeChecksumBits> {}; // NOLINT
8182 class ICsWithTypeInfoCountField: public BitField<int, 0,
8183 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8184 class InlinedTypeChangeChecksum: public BitField<int,
8185 kSmiValueSize - kTypeChangeChecksumBits,
8186 kTypeChangeChecksumBits> {}; // NOLINT
8188 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8192 enum AllocationSiteMode {
8193 DONT_TRACK_ALLOCATION_SITE,
8194 TRACK_ALLOCATION_SITE,
8195 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8199 class AllocationSite: public Struct {
8201 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8202 static const double kPretenureRatio;
8203 static const int kPretenureMinimumCreated = 100;
8205 // Values for pretenure decision field.
8206 enum PretenureDecision {
8212 kLastPretenureDecisionValue = kZombie
8215 const char* PretenureDecisionName(PretenureDecision decision);
8217 DECL_ACCESSORS(transition_info, Object)
8218 // nested_site threads a list of sites that represent nested literals
8219 // walked in a particular order. So [[1, 2], 1, 2] will have one
8220 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8221 DECL_ACCESSORS(nested_site, Object)
8222 DECL_ACCESSORS(pretenure_data, Smi)
8223 DECL_ACCESSORS(pretenure_create_count, Smi)
8224 DECL_ACCESSORS(dependent_code, DependentCode)
8225 DECL_ACCESSORS(weak_next, Object)
8227 inline void Initialize();
8229 // This method is expensive, it should only be called for reporting.
8230 bool IsNestedSite();
8232 // transition_info bitfields, for constructed array transition info.
8233 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8234 class UnusedBits: public BitField<int, 15, 14> {};
8235 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8237 // Bitfields for pretenure_data
8238 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8239 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8240 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8241 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8243 // Increments the mementos found counter and returns true when the first
8244 // memento was found for a given allocation site.
8245 inline bool IncrementMementoFoundCount();
8247 inline void IncrementMementoCreateCount();
8249 PretenureFlag GetPretenureMode();
8251 void ResetPretenureDecision();
8253 PretenureDecision pretenure_decision() {
8254 int value = pretenure_data()->value();
8255 return PretenureDecisionBits::decode(value);
8258 void set_pretenure_decision(PretenureDecision decision) {
8259 int value = pretenure_data()->value();
8261 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8262 SKIP_WRITE_BARRIER);
8265 bool deopt_dependent_code() {
8266 int value = pretenure_data()->value();
8267 return DeoptDependentCodeBit::decode(value);
8270 void set_deopt_dependent_code(bool deopt) {
8271 int value = pretenure_data()->value();
8273 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8274 SKIP_WRITE_BARRIER);
8277 int memento_found_count() {
8278 int value = pretenure_data()->value();
8279 return MementoFoundCountBits::decode(value);
8282 inline void set_memento_found_count(int count);
8284 int memento_create_count() {
8285 return pretenure_create_count()->value();
8288 void set_memento_create_count(int count) {
8289 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8292 // The pretenuring decision is made during gc, and the zombie state allows
8293 // us to recognize when an allocation site is just being kept alive because
8294 // a later traversal of new space may discover AllocationMementos that point
8295 // to this AllocationSite.
8297 return pretenure_decision() == kZombie;
8300 bool IsMaybeTenure() {
8301 return pretenure_decision() == kMaybeTenure;
8304 inline void MarkZombie();
8306 inline bool MakePretenureDecision(PretenureDecision current_decision,
8308 bool maximum_size_scavenge);
8310 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8312 ElementsKind GetElementsKind() {
8313 DCHECK(!SitePointsToLiteral());
8314 int value = Smi::cast(transition_info())->value();
8315 return ElementsKindBits::decode(value);
8318 void SetElementsKind(ElementsKind kind) {
8319 int value = Smi::cast(transition_info())->value();
8320 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8321 SKIP_WRITE_BARRIER);
8324 bool CanInlineCall() {
8325 int value = Smi::cast(transition_info())->value();
8326 return DoNotInlineBit::decode(value) == 0;
8329 void SetDoNotInlineCall() {
8330 int value = Smi::cast(transition_info())->value();
8331 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8332 SKIP_WRITE_BARRIER);
8335 bool SitePointsToLiteral() {
8336 // If transition_info is a smi, then it represents an ElementsKind
8337 // for a constructed array. Otherwise, it must be a boilerplate
8338 // for an object or array literal.
8339 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8342 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8343 ElementsKind to_kind);
8345 DECLARE_PRINTER(AllocationSite)
8346 DECLARE_VERIFIER(AllocationSite)
8348 DECLARE_CAST(AllocationSite)
8349 static inline AllocationSiteMode GetMode(
8350 ElementsKind boilerplate_elements_kind);
8351 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8352 static inline bool CanTrack(InstanceType type);
8354 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8355 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8356 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8357 static const int kPretenureCreateCountOffset =
8358 kPretenureDataOffset + kPointerSize;
8359 static const int kDependentCodeOffset =
8360 kPretenureCreateCountOffset + kPointerSize;
8361 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8362 static const int kSize = kWeakNextOffset + kPointerSize;
8364 // During mark compact we need to take special care for the dependent code
8366 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8367 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8369 // For other visitors, use the fixed body descriptor below.
8370 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8371 kDependentCodeOffset + kPointerSize,
8372 kSize> BodyDescriptor;
8375 bool PretenuringDecisionMade() {
8376 return pretenure_decision() != kUndecided;
8379 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8383 class AllocationMemento: public Struct {
8385 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8386 static const int kSize = kAllocationSiteOffset + kPointerSize;
8388 DECL_ACCESSORS(allocation_site, Object)
8391 return allocation_site()->IsAllocationSite() &&
8392 !AllocationSite::cast(allocation_site())->IsZombie();
8394 AllocationSite* GetAllocationSite() {
8396 return AllocationSite::cast(allocation_site());
8399 DECLARE_PRINTER(AllocationMemento)
8400 DECLARE_VERIFIER(AllocationMemento)
8402 DECLARE_CAST(AllocationMemento)
8405 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8409 // Representation of a slow alias as part of a sloppy arguments objects.
8410 // For fast aliases (if HasSloppyArgumentsElements()):
8411 // - the parameter map contains an index into the context
8412 // - all attributes of the element have default values
8413 // For slow aliases (if HasDictionaryArgumentsElements()):
8414 // - the parameter map contains no fast alias mapping (i.e. the hole)
8415 // - this struct (in the slow backing store) contains an index into the context
8416 // - all attributes are available as part if the property details
8417 class AliasedArgumentsEntry: public Struct {
8419 inline int aliased_context_slot() const;
8420 inline void set_aliased_context_slot(int count);
8422 DECLARE_CAST(AliasedArgumentsEntry)
8424 // Dispatched behavior.
8425 DECLARE_PRINTER(AliasedArgumentsEntry)
8426 DECLARE_VERIFIER(AliasedArgumentsEntry)
8428 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8429 static const int kSize = kAliasedContextSlot + kPointerSize;
8432 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8436 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8437 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8440 class StringHasher {
8442 explicit inline StringHasher(int length, uint32_t seed);
8444 template <typename schar>
8445 static inline uint32_t HashSequentialString(const schar* chars,
8449 // Reads all the data, even for long strings and computes the utf16 length.
8450 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8452 int* utf16_length_out);
8454 // Calculated hash value for a string consisting of 1 to
8455 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8456 // value is represented decimal value.
8457 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8459 // No string is allowed to have a hash of zero. That value is reserved
8460 // for internal properties. If the hash calculation yields zero then we
8462 static const int kZeroHash = 27;
8464 // Reusable parts of the hashing algorithm.
8465 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8466 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8467 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8468 const uc16* chars, int length));
8469 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8474 // Returns the value to store in the hash field of a string with
8475 // the given length and contents.
8476 uint32_t GetHashField();
8477 // Returns true if the hash of this string can be computed without
8478 // looking at the contents.
8479 inline bool has_trivial_hash();
8480 // Adds a block of characters to the hash.
8481 template<typename Char>
8482 inline void AddCharacters(const Char* chars, int len);
8485 // Add a character to the hash.
8486 inline void AddCharacter(uint16_t c);
8487 // Update index. Returns true if string is still an index.
8488 inline bool UpdateIndex(uint16_t c);
8491 uint32_t raw_running_hash_;
8492 uint32_t array_index_;
8493 bool is_array_index_;
8494 bool is_first_char_;
8495 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8499 class IteratingStringHasher : public StringHasher {
8501 static inline uint32_t Hash(String* string, uint32_t seed);
8502 inline void VisitOneByteString(const uint8_t* chars, int length);
8503 inline void VisitTwoByteString(const uint16_t* chars, int length);
8506 inline IteratingStringHasher(int len, uint32_t seed)
8507 : StringHasher(len, seed) {}
8508 void VisitConsString(ConsString* cons_string);
8509 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8513 // The characteristics of a string are stored in its map. Retrieving these
8514 // few bits of information is moderately expensive, involving two memory
8515 // loads where the second is dependent on the first. To improve efficiency
8516 // the shape of the string is given its own class so that it can be retrieved
8517 // once and used for several string operations. A StringShape is small enough
8518 // to be passed by value and is immutable, but be aware that flattening a
8519 // string can potentially alter its shape. Also be aware that a GC caused by
8520 // something else can alter the shape of a string due to ConsString
8521 // shortcutting. Keeping these restrictions in mind has proven to be error-
8522 // prone and so we no longer put StringShapes in variables unless there is a
8523 // concrete performance benefit at that particular point in the code.
8524 class StringShape BASE_EMBEDDED {
8526 inline explicit StringShape(const String* s);
8527 inline explicit StringShape(Map* s);
8528 inline explicit StringShape(InstanceType t);
8529 inline bool IsSequential();
8530 inline bool IsExternal();
8531 inline bool IsCons();
8532 inline bool IsSliced();
8533 inline bool IsIndirect();
8534 inline bool IsExternalOneByte();
8535 inline bool IsExternalTwoByte();
8536 inline bool IsSequentialOneByte();
8537 inline bool IsSequentialTwoByte();
8538 inline bool IsInternalized();
8539 inline StringRepresentationTag representation_tag();
8540 inline uint32_t encoding_tag();
8541 inline uint32_t full_representation_tag();
8542 inline uint32_t size_tag();
8544 inline uint32_t type() { return type_; }
8545 inline void invalidate() { valid_ = false; }
8546 inline bool valid() { return valid_; }
8548 inline void invalidate() { }
8554 inline void set_valid() { valid_ = true; }
8557 inline void set_valid() { }
8562 // The Name abstract class captures anything that can be used as a property
8563 // name, i.e., strings and symbols. All names store a hash value.
8564 class Name: public HeapObject {
8566 // Get and set the hash field of the name.
8567 inline uint32_t hash_field();
8568 inline void set_hash_field(uint32_t value);
8570 // Tells whether the hash code has been computed.
8571 inline bool HasHashCode();
8573 // Returns a hash value used for the property table
8574 inline uint32_t Hash();
8576 // Equality operations.
8577 inline bool Equals(Name* other);
8578 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8581 inline bool AsArrayIndex(uint32_t* index);
8583 // If the name is private, it can only name own properties.
8584 inline bool IsPrivate();
8586 // If the name is a non-flat string, this method returns a flat version of the
8587 // string. Otherwise it'll just return the input.
8588 static inline Handle<Name> Flatten(Handle<Name> name,
8589 PretenureFlag pretenure = NOT_TENURED);
8593 DECLARE_PRINTER(Name)
8595 void NameShortPrint();
8596 int NameShortPrint(Vector<char> str);
8599 // Layout description.
8600 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8601 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8602 static const int kHashFieldOffset = kHashFieldSlot;
8604 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8606 static const int kSize = kHashFieldSlot + kPointerSize;
8608 // Mask constant for checking if a name has a computed hash code
8609 // and if it is a string that is an array index. The least significant bit
8610 // indicates whether a hash code has been computed. If the hash code has
8611 // been computed the 2nd bit tells whether the string can be used as an
8613 static const int kHashNotComputedMask = 1;
8614 static const int kIsNotArrayIndexMask = 1 << 1;
8615 static const int kNofHashBitFields = 2;
8617 // Shift constant retrieving hash code from hash field.
8618 static const int kHashShift = kNofHashBitFields;
8620 // Only these bits are relevant in the hash, since the top two are shifted
8622 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8624 // Array index strings this short can keep their index in the hash field.
8625 static const int kMaxCachedArrayIndexLength = 7;
8627 // For strings which are array indexes the hash value has the string length
8628 // mixed into the hash, mainly to avoid a hash value of zero which would be
8629 // the case for the string '0'. 24 bits are used for the array index value.
8630 static const int kArrayIndexValueBits = 24;
8631 static const int kArrayIndexLengthBits =
8632 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8634 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8636 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8637 kArrayIndexValueBits> {}; // NOLINT
8638 class ArrayIndexLengthBits : public BitField<unsigned int,
8639 kNofHashBitFields + kArrayIndexValueBits,
8640 kArrayIndexLengthBits> {}; // NOLINT
8642 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8643 // could use a mask to test if the length of string is less than or equal to
8644 // kMaxCachedArrayIndexLength.
8645 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8647 static const unsigned int kContainsCachedArrayIndexMask =
8648 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8649 << ArrayIndexLengthBits::kShift) |
8650 kIsNotArrayIndexMask;
8652 // Value of empty hash field indicating that the hash is not computed.
8653 static const int kEmptyHashField =
8654 kIsNotArrayIndexMask | kHashNotComputedMask;
8657 static inline bool IsHashFieldComputed(uint32_t field);
8660 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8665 class Symbol: public Name {
8667 // [name]: The print name of a symbol, or undefined if none.
8668 DECL_ACCESSORS(name, Object)
8670 DECL_ACCESSORS(flags, Smi)
8672 // [is_private]: Whether this is a private symbol. Private symbols can only
8673 // be used to designate own properties of objects.
8674 DECL_BOOLEAN_ACCESSORS(is_private)
8676 DECLARE_CAST(Symbol)
8678 // Dispatched behavior.
8679 DECLARE_PRINTER(Symbol)
8680 DECLARE_VERIFIER(Symbol)
8682 // Layout description.
8683 static const int kNameOffset = Name::kSize;
8684 static const int kFlagsOffset = kNameOffset + kPointerSize;
8685 static const int kSize = kFlagsOffset + kPointerSize;
8687 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8689 void SymbolShortPrint(std::ostream& os);
8692 static const int kPrivateBit = 0;
8694 const char* PrivateSymbolToName() const;
8697 friend class Name; // For PrivateSymbolToName.
8700 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8706 // The String abstract class captures JavaScript string values:
8709 // 4.3.16 String Value
8710 // A string value is a member of the type String and is a finite
8711 // ordered sequence of zero or more 16-bit unsigned integer values.
8713 // All string values have a length field.
8714 class String: public Name {
8716 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8718 // Array index strings this short can keep their index in the hash field.
8719 static const int kMaxCachedArrayIndexLength = 7;
8721 // For strings which are array indexes the hash value has the string length
8722 // mixed into the hash, mainly to avoid a hash value of zero which would be
8723 // the case for the string '0'. 24 bits are used for the array index value.
8724 static const int kArrayIndexValueBits = 24;
8725 static const int kArrayIndexLengthBits =
8726 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8728 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8730 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8731 kArrayIndexValueBits> {}; // NOLINT
8732 class ArrayIndexLengthBits : public BitField<unsigned int,
8733 kNofHashBitFields + kArrayIndexValueBits,
8734 kArrayIndexLengthBits> {}; // NOLINT
8736 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8737 // could use a mask to test if the length of string is less than or equal to
8738 // kMaxCachedArrayIndexLength.
8739 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8741 static const unsigned int kContainsCachedArrayIndexMask =
8742 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8743 << ArrayIndexLengthBits::kShift) |
8744 kIsNotArrayIndexMask;
8746 class SubStringRange {
8748 explicit SubStringRange(String* string, int first = 0, int length = -1)
8751 length_(length == -1 ? string->length() : length) {}
8753 inline iterator begin();
8754 inline iterator end();
8762 // Representation of the flat content of a String.
8763 // A non-flat string doesn't have flat content.
8764 // A flat string has content that's encoded as a sequence of either
8765 // one-byte chars or two-byte UC16.
8766 // Returned by String::GetFlatContent().
8769 // Returns true if the string is flat and this structure contains content.
8770 bool IsFlat() { return state_ != NON_FLAT; }
8771 // Returns true if the structure contains one-byte content.
8772 bool IsOneByte() { return state_ == ONE_BYTE; }
8773 // Returns true if the structure contains two-byte content.
8774 bool IsTwoByte() { return state_ == TWO_BYTE; }
8776 // Return the one byte content of the string. Only use if IsOneByte()
8778 Vector<const uint8_t> ToOneByteVector() {
8779 DCHECK_EQ(ONE_BYTE, state_);
8780 return Vector<const uint8_t>(onebyte_start, length_);
8782 // Return the two-byte content of the string. Only use if IsTwoByte()
8784 Vector<const uc16> ToUC16Vector() {
8785 DCHECK_EQ(TWO_BYTE, state_);
8786 return Vector<const uc16>(twobyte_start, length_);
8790 DCHECK(i < length_);
8791 DCHECK(state_ != NON_FLAT);
8792 if (state_ == ONE_BYTE) return onebyte_start[i];
8793 return twobyte_start[i];
8796 bool UsesSameString(const FlatContent& other) const {
8797 return onebyte_start == other.onebyte_start;
8801 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8803 // Constructors only used by String::GetFlatContent().
8804 explicit FlatContent(const uint8_t* start, int length)
8805 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8806 explicit FlatContent(const uc16* start, int length)
8807 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8808 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8811 const uint8_t* onebyte_start;
8812 const uc16* twobyte_start;
8817 friend class String;
8818 friend class IterableSubString;
8821 template <typename Char>
8822 INLINE(Vector<const Char> GetCharVector());
8824 // Get and set the length of the string.
8825 inline int length() const;
8826 inline void set_length(int value);
8828 // Get and set the length of the string using acquire loads and release
8830 inline int synchronized_length() const;
8831 inline void synchronized_set_length(int value);
8833 // Returns whether this string has only one-byte chars, i.e. all of them can
8834 // be one-byte encoded. This might be the case even if the string is
8835 // two-byte. Such strings may appear when the embedder prefers
8836 // two-byte external representations even for one-byte data.
8837 inline bool IsOneByteRepresentation() const;
8838 inline bool IsTwoByteRepresentation() const;
8840 // Cons and slices have an encoding flag that may not represent the actual
8841 // encoding of the underlying string. This is taken into account here.
8842 // Requires: this->IsFlat()
8843 inline bool IsOneByteRepresentationUnderneath();
8844 inline bool IsTwoByteRepresentationUnderneath();
8846 // NOTE: this should be considered only a hint. False negatives are
8848 inline bool HasOnlyOneByteChars();
8850 // Get and set individual two byte chars in the string.
8851 inline void Set(int index, uint16_t value);
8852 // Get individual two byte char in the string. Repeated calls
8853 // to this method are not efficient unless the string is flat.
8854 INLINE(uint16_t Get(int index));
8856 // Flattens the string. Checks first inline to see if it is
8857 // necessary. Does nothing if the string is not a cons string.
8858 // Flattening allocates a sequential string with the same data as
8859 // the given string and mutates the cons string to a degenerate
8860 // form, where the first component is the new sequential string and
8861 // the second component is the empty string. If allocation fails,
8862 // this function returns a failure. If flattening succeeds, this
8863 // function returns the sequential string that is now the first
8864 // component of the cons string.
8866 // Degenerate cons strings are handled specially by the garbage
8867 // collector (see IsShortcutCandidate).
8869 static inline Handle<String> Flatten(Handle<String> string,
8870 PretenureFlag pretenure = NOT_TENURED);
8872 // Tries to return the content of a flat string as a structure holding either
8873 // a flat vector of char or of uc16.
8874 // If the string isn't flat, and therefore doesn't have flat content, the
8875 // returned structure will report so, and can't provide a vector of either
8877 FlatContent GetFlatContent();
8879 // Returns the parent of a sliced string or first part of a flat cons string.
8880 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8881 inline String* GetUnderlying();
8883 // String equality operations.
8884 inline bool Equals(String* other);
8885 inline static bool Equals(Handle<String> one, Handle<String> two);
8886 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8887 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8888 bool IsTwoByteEqualTo(Vector<const uc16> str);
8890 // Return a UTF8 representation of the string. The string is null
8891 // terminated but may optionally contain nulls. Length is returned
8892 // in length_output if length_output is not a null pointer The string
8893 // should be nearly flat, otherwise the performance of this method may
8894 // be very slow (quadratic in the length). Setting robustness_flag to
8895 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8896 // handles unexpected data without causing assert failures and it does not
8897 // do any heap allocations. This is useful when printing stack traces.
8898 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8899 RobustnessFlag robustness_flag,
8900 int offset, int length,
8901 int* length_output = 0);
8902 base::SmartArrayPointer<char> ToCString(
8903 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8904 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8905 int* length_output = 0);
8907 // Return a 16 bit Unicode representation of the string.
8908 // The string should be nearly flat, otherwise the performance of
8909 // of this method may be very bad. Setting robustness_flag to
8910 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8911 // handles unexpected data without causing assert failures and it does not
8912 // do any heap allocations. This is useful when printing stack traces.
8913 base::SmartArrayPointer<uc16> ToWideCString(
8914 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8916 bool ComputeArrayIndex(uint32_t* index);
8919 bool MakeExternal(v8::String::ExternalStringResource* resource);
8920 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8923 inline bool AsArrayIndex(uint32_t* index);
8925 DECLARE_CAST(String)
8927 void PrintOn(FILE* out);
8929 // For use during stack traces. Performs rudimentary sanity check.
8932 // Dispatched behavior.
8933 void StringShortPrint(StringStream* accumulator);
8934 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8935 #if defined(DEBUG) || defined(OBJECT_PRINT)
8936 char* ToAsciiArray();
8938 DECLARE_PRINTER(String)
8939 DECLARE_VERIFIER(String)
8941 inline bool IsFlat();
8943 // Layout description.
8944 static const int kLengthOffset = Name::kSize;
8945 static const int kSize = kLengthOffset + kPointerSize;
8947 // Maximum number of characters to consider when trying to convert a string
8948 // value into an array index.
8949 static const int kMaxArrayIndexSize = 10;
8950 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8953 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8954 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8955 static const int kMaxUtf16CodeUnit = 0xffff;
8956 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8958 // Value of hash field containing computed hash equal to zero.
8959 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8961 // Maximal string length.
8962 static const int kMaxLength = (1 << 28) - 16;
8964 // Max length for computing hash. For strings longer than this limit the
8965 // string length is used as the hash value.
8966 static const int kMaxHashCalcLength = 16383;
8968 // Limit for truncation in short printing.
8969 static const int kMaxShortPrintLength = 1024;
8971 // Support for regular expressions.
8972 const uc16* GetTwoByteData(unsigned start);
8974 // Helper function for flattening strings.
8975 template <typename sinkchar>
8976 static void WriteToFlat(String* source,
8981 // The return value may point to the first aligned word containing the first
8982 // non-one-byte character, rather than directly to the non-one-byte character.
8983 // If the return value is >= the passed length, the entire string was
8985 static inline int NonAsciiStart(const char* chars, int length) {
8986 const char* start = chars;
8987 const char* limit = chars + length;
8989 if (length >= kIntptrSize) {
8990 // Check unaligned bytes.
8991 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8992 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8993 return static_cast<int>(chars - start);
8997 // Check aligned words.
8998 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
8999 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9000 while (chars + sizeof(uintptr_t) <= limit) {
9001 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
9002 return static_cast<int>(chars - start);
9004 chars += sizeof(uintptr_t);
9007 // Check remaining unaligned bytes.
9008 while (chars < limit) {
9009 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9010 return static_cast<int>(chars - start);
9015 return static_cast<int>(chars - start);
9018 static inline bool IsAscii(const char* chars, int length) {
9019 return NonAsciiStart(chars, length) >= length;
9022 static inline bool IsAscii(const uint8_t* chars, int length) {
9024 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9027 static inline int NonOneByteStart(const uc16* chars, int length) {
9028 const uc16* limit = chars + length;
9029 const uc16* start = chars;
9030 while (chars < limit) {
9031 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9034 return static_cast<int>(chars - start);
9037 static inline bool IsOneByte(const uc16* chars, int length) {
9038 return NonOneByteStart(chars, length) >= length;
9041 template<class Visitor>
9042 static inline ConsString* VisitFlat(Visitor* visitor,
9046 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9047 bool include_ending_line);
9049 // Use the hash field to forward to the canonical internalized string
9050 // when deserializing an internalized string.
9051 inline void SetForwardedInternalizedString(String* string);
9052 inline String* GetForwardedInternalizedString();
9056 friend class StringTableInsertionKey;
9058 static Handle<String> SlowFlatten(Handle<ConsString> cons,
9059 PretenureFlag tenure);
9061 // Slow case of String::Equals. This implementation works on any strings
9062 // but it is most efficient on strings that are almost flat.
9063 bool SlowEquals(String* other);
9065 static bool SlowEquals(Handle<String> one, Handle<String> two);
9067 // Slow case of AsArrayIndex.
9068 bool SlowAsArrayIndex(uint32_t* index);
9070 // Compute and set the hash code.
9071 uint32_t ComputeAndSetHash();
9073 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9077 // The SeqString abstract class captures sequential string values.
9078 class SeqString: public String {
9080 DECLARE_CAST(SeqString)
9082 // Layout description.
9083 static const int kHeaderSize = String::kSize;
9085 // Truncate the string in-place if possible and return the result.
9086 // In case of new_length == 0, the empty string is returned without
9087 // truncating the original string.
9088 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9091 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9095 // The OneByteString class captures sequential one-byte string objects.
9096 // Each character in the OneByteString is an one-byte character.
9097 class SeqOneByteString: public SeqString {
9099 static const bool kHasOneByteEncoding = true;
9101 // Dispatched behavior.
9102 inline uint16_t SeqOneByteStringGet(int index);
9103 inline void SeqOneByteStringSet(int index, uint16_t value);
9105 // Get the address of the characters in this string.
9106 inline Address GetCharsAddress();
9108 inline uint8_t* GetChars();
9110 DECLARE_CAST(SeqOneByteString)
9112 // Garbage collection support. This method is called by the
9113 // garbage collector to compute the actual size of an OneByteString
9115 inline int SeqOneByteStringSize(InstanceType instance_type);
9117 // Computes the size for an OneByteString instance of a given length.
9118 static int SizeFor(int length) {
9119 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9122 // Maximal memory usage for a single sequential one-byte string.
9123 static const int kMaxSize = 512 * MB - 1;
9124 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9127 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9131 // The TwoByteString class captures sequential unicode string objects.
9132 // Each character in the TwoByteString is a two-byte uint16_t.
9133 class SeqTwoByteString: public SeqString {
9135 static const bool kHasOneByteEncoding = false;
9137 // Dispatched behavior.
9138 inline uint16_t SeqTwoByteStringGet(int index);
9139 inline void SeqTwoByteStringSet(int index, uint16_t value);
9141 // Get the address of the characters in this string.
9142 inline Address GetCharsAddress();
9144 inline uc16* GetChars();
9147 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9149 DECLARE_CAST(SeqTwoByteString)
9151 // Garbage collection support. This method is called by the
9152 // garbage collector to compute the actual size of a TwoByteString
9154 inline int SeqTwoByteStringSize(InstanceType instance_type);
9156 // Computes the size for a TwoByteString instance of a given length.
9157 static int SizeFor(int length) {
9158 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9161 // Maximal memory usage for a single sequential two-byte string.
9162 static const int kMaxSize = 512 * MB - 1;
9163 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9164 String::kMaxLength);
9167 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9171 // The ConsString class describes string values built by using the
9172 // addition operator on strings. A ConsString is a pair where the
9173 // first and second components are pointers to other string values.
9174 // One or both components of a ConsString can be pointers to other
9175 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9176 // are non-ConsString string values. The string value represented by
9177 // a ConsString can be obtained by concatenating the leaf string
9178 // values in a left-to-right depth-first traversal of the tree.
9179 class ConsString: public String {
9181 // First string of the cons cell.
9182 inline String* first();
9183 // Doesn't check that the result is a string, even in debug mode. This is
9184 // useful during GC where the mark bits confuse the checks.
9185 inline Object* unchecked_first();
9186 inline void set_first(String* first,
9187 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9189 // Second string of the cons cell.
9190 inline String* second();
9191 // Doesn't check that the result is a string, even in debug mode. This is
9192 // useful during GC where the mark bits confuse the checks.
9193 inline Object* unchecked_second();
9194 inline void set_second(String* second,
9195 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9197 // Dispatched behavior.
9198 uint16_t ConsStringGet(int index);
9200 DECLARE_CAST(ConsString)
9202 // Layout description.
9203 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9204 static const int kSecondOffset = kFirstOffset + kPointerSize;
9205 static const int kSize = kSecondOffset + kPointerSize;
9207 // Minimum length for a cons string.
9208 static const int kMinLength = 13;
9210 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9213 DECLARE_VERIFIER(ConsString)
9216 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9220 // The Sliced String class describes strings that are substrings of another
9221 // sequential string. The motivation is to save time and memory when creating
9222 // a substring. A Sliced String is described as a pointer to the parent,
9223 // the offset from the start of the parent string and the length. Using
9224 // a Sliced String therefore requires unpacking of the parent string and
9225 // adding the offset to the start address. A substring of a Sliced String
9226 // are not nested since the double indirection is simplified when creating
9227 // such a substring.
9228 // Currently missing features are:
9229 // - handling externalized parent strings
9230 // - external strings as parent
9231 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9232 class SlicedString: public String {
9234 inline String* parent();
9235 inline void set_parent(String* parent,
9236 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9237 inline int offset() const;
9238 inline void set_offset(int offset);
9240 // Dispatched behavior.
9241 uint16_t SlicedStringGet(int index);
9243 DECLARE_CAST(SlicedString)
9245 // Layout description.
9246 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9247 static const int kOffsetOffset = kParentOffset + kPointerSize;
9248 static const int kSize = kOffsetOffset + kPointerSize;
9250 // Minimum length for a sliced string.
9251 static const int kMinLength = 13;
9253 typedef FixedBodyDescriptor<kParentOffset,
9254 kOffsetOffset + kPointerSize, kSize>
9257 DECLARE_VERIFIER(SlicedString)
9260 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9264 // The ExternalString class describes string values that are backed by
9265 // a string resource that lies outside the V8 heap. ExternalStrings
9266 // consist of the length field common to all strings, a pointer to the
9267 // external resource. It is important to ensure (externally) that the
9268 // resource is not deallocated while the ExternalString is live in the
9271 // The API expects that all ExternalStrings are created through the
9272 // API. Therefore, ExternalStrings should not be used internally.
9273 class ExternalString: public String {
9275 DECLARE_CAST(ExternalString)
9277 // Layout description.
9278 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9279 static const int kShortSize = kResourceOffset + kPointerSize;
9280 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9281 static const int kSize = kResourceDataOffset + kPointerSize;
9283 static const int kMaxShortLength =
9284 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9286 // Return whether external string is short (data pointer is not cached).
9287 inline bool is_short();
9289 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9292 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9296 // The ExternalOneByteString class is an external string backed by an
9298 class ExternalOneByteString : public ExternalString {
9300 static const bool kHasOneByteEncoding = true;
9302 typedef v8::String::ExternalOneByteStringResource Resource;
9304 // The underlying resource.
9305 inline const Resource* resource();
9306 inline void set_resource(const Resource* buffer);
9308 // Update the pointer cache to the external character array.
9309 // The cached pointer is always valid, as the external character array does =
9310 // not move during lifetime. Deserialization is the only exception, after
9311 // which the pointer cache has to be refreshed.
9312 inline void update_data_cache();
9314 inline const uint8_t* GetChars();
9316 // Dispatched behavior.
9317 inline uint16_t ExternalOneByteStringGet(int index);
9319 DECLARE_CAST(ExternalOneByteString)
9321 // Garbage collection support.
9322 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9324 template <typename StaticVisitor>
9325 inline void ExternalOneByteStringIterateBody();
9328 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9332 // The ExternalTwoByteString class is an external string backed by a UTF-16
9334 class ExternalTwoByteString: public ExternalString {
9336 static const bool kHasOneByteEncoding = false;
9338 typedef v8::String::ExternalStringResource Resource;
9340 // The underlying string resource.
9341 inline const Resource* resource();
9342 inline void set_resource(const Resource* buffer);
9344 // Update the pointer cache to the external character array.
9345 // The cached pointer is always valid, as the external character array does =
9346 // not move during lifetime. Deserialization is the only exception, after
9347 // which the pointer cache has to be refreshed.
9348 inline void update_data_cache();
9350 inline const uint16_t* GetChars();
9352 // Dispatched behavior.
9353 inline uint16_t ExternalTwoByteStringGet(int index);
9356 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9358 DECLARE_CAST(ExternalTwoByteString)
9360 // Garbage collection support.
9361 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9363 template<typename StaticVisitor>
9364 inline void ExternalTwoByteStringIterateBody();
9367 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9371 // Utility superclass for stack-allocated objects that must be updated
9372 // on gc. It provides two ways for the gc to update instances, either
9373 // iterating or updating after gc.
9374 class Relocatable BASE_EMBEDDED {
9376 explicit inline Relocatable(Isolate* isolate);
9377 inline virtual ~Relocatable();
9378 virtual void IterateInstance(ObjectVisitor* v) { }
9379 virtual void PostGarbageCollection() { }
9381 static void PostGarbageCollectionProcessing(Isolate* isolate);
9382 static int ArchiveSpacePerThread();
9383 static char* ArchiveState(Isolate* isolate, char* to);
9384 static char* RestoreState(Isolate* isolate, char* from);
9385 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9386 static void Iterate(ObjectVisitor* v, Relocatable* top);
9387 static char* Iterate(ObjectVisitor* v, char* t);
9395 // A flat string reader provides random access to the contents of a
9396 // string independent of the character width of the string. The handle
9397 // must be valid as long as the reader is being used.
9398 class FlatStringReader : public Relocatable {
9400 FlatStringReader(Isolate* isolate, Handle<String> str);
9401 FlatStringReader(Isolate* isolate, Vector<const char> input);
9402 void PostGarbageCollection();
9403 inline uc32 Get(int index);
9404 template <typename Char>
9405 inline Char Get(int index);
9406 int length() { return length_; }
9415 // This maintains an off-stack representation of the stack frames required
9416 // to traverse a ConsString, allowing an entirely iterative and restartable
9417 // traversal of the entire string
9418 class ConsStringIterator {
9420 inline ConsStringIterator() {}
9421 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9422 Reset(cons_string, offset);
9424 inline void Reset(ConsString* cons_string, int offset = 0) {
9426 // Next will always return NULL.
9427 if (cons_string == NULL) return;
9428 Initialize(cons_string, offset);
9430 // Returns NULL when complete.
9431 inline String* Next(int* offset_out) {
9433 if (depth_ == 0) return NULL;
9434 return Continue(offset_out);
9438 static const int kStackSize = 32;
9439 // Use a mask instead of doing modulo operations for stack wrapping.
9440 static const int kDepthMask = kStackSize-1;
9441 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9442 static inline int OffsetForDepth(int depth);
9444 inline void PushLeft(ConsString* string);
9445 inline void PushRight(ConsString* string);
9446 inline void AdjustMaximumDepth();
9448 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9449 void Initialize(ConsString* cons_string, int offset);
9450 String* Continue(int* offset_out);
9451 String* NextLeaf(bool* blew_stack);
9452 String* Search(int* offset_out);
9454 // Stack must always contain only frames for which right traversal
9455 // has not yet been performed.
9456 ConsString* frames_[kStackSize];
9461 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9465 class StringCharacterStream {
9467 inline StringCharacterStream(String* string,
9469 inline uint16_t GetNext();
9470 inline bool HasMore();
9471 inline void Reset(String* string, int offset = 0);
9472 inline void VisitOneByteString(const uint8_t* chars, int length);
9473 inline void VisitTwoByteString(const uint16_t* chars, int length);
9476 ConsStringIterator iter_;
9479 const uint8_t* buffer8_;
9480 const uint16_t* buffer16_;
9482 const uint8_t* end_;
9483 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9487 template <typename T>
9488 class VectorIterator {
9490 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9491 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9492 T GetNext() { return data_[index_++]; }
9493 bool has_more() { return index_ < data_.length(); }
9495 Vector<const T> data_;
9500 // The Oddball describes objects null, undefined, true, and false.
9501 class Oddball: public HeapObject {
9503 // [to_string]: Cached to_string computed at startup.
9504 DECL_ACCESSORS(to_string, String)
9506 // [to_number]: Cached to_number computed at startup.
9507 DECL_ACCESSORS(to_number, Object)
9509 inline byte kind() const;
9510 inline void set_kind(byte kind);
9512 DECLARE_CAST(Oddball)
9514 // Dispatched behavior.
9515 DECLARE_VERIFIER(Oddball)
9517 // Initialize the fields.
9518 static void Initialize(Isolate* isolate,
9519 Handle<Oddball> oddball,
9520 const char* to_string,
9521 Handle<Object> to_number,
9524 // Layout description.
9525 static const int kToStringOffset = HeapObject::kHeaderSize;
9526 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9527 static const int kKindOffset = kToNumberOffset + kPointerSize;
9528 static const int kSize = kKindOffset + kPointerSize;
9530 static const byte kFalse = 0;
9531 static const byte kTrue = 1;
9532 static const byte kNotBooleanMask = ~1;
9533 static const byte kTheHole = 2;
9534 static const byte kNull = 3;
9535 static const byte kArgumentMarker = 4;
9536 static const byte kUndefined = 5;
9537 static const byte kUninitialized = 6;
9538 static const byte kOther = 7;
9539 static const byte kException = 8;
9541 typedef FixedBodyDescriptor<kToStringOffset,
9542 kToNumberOffset + kPointerSize,
9543 kSize> BodyDescriptor;
9545 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9546 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9547 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9550 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9554 class Cell: public HeapObject {
9556 // [value]: value of the cell.
9557 DECL_ACCESSORS(value, Object)
9561 static inline Cell* FromValueAddress(Address value) {
9562 Object* result = FromAddress(value - kValueOffset);
9563 return static_cast<Cell*>(result);
9566 inline Address ValueAddress() {
9567 return address() + kValueOffset;
9570 // Dispatched behavior.
9571 DECLARE_PRINTER(Cell)
9572 DECLARE_VERIFIER(Cell)
9574 // Layout description.
9575 static const int kValueOffset = HeapObject::kHeaderSize;
9576 static const int kSize = kValueOffset + kPointerSize;
9578 typedef FixedBodyDescriptor<kValueOffset,
9579 kValueOffset + kPointerSize,
9580 kSize> BodyDescriptor;
9583 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9587 class PropertyCell : public HeapObject {
9589 // [property_details]: details of the global property.
9590 DECL_ACCESSORS(property_details_raw, Object)
9591 // [value]: value of the global property.
9592 DECL_ACCESSORS(value, Object)
9593 // [dependent_code]: dependent code that depends on the type of the global
9595 DECL_ACCESSORS(dependent_code, DependentCode)
9597 PropertyDetails property_details() {
9598 return PropertyDetails(Smi::cast(property_details_raw()));
9601 void set_property_details(PropertyDetails details) {
9602 set_property_details_raw(details.AsSmi());
9605 PropertyCellConstantType GetConstantType();
9607 // Computes the new type of the cell's contents for the given value, but
9608 // without actually modifying the details.
9609 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9610 Handle<Object> value,
9611 PropertyDetails details);
9612 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9613 Handle<Object> value, PropertyDetails details);
9615 static Handle<PropertyCell> InvalidateEntry(
9616 Handle<GlobalDictionary> dictionary, int entry);
9618 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9619 Handle<Object> new_value);
9621 DECLARE_CAST(PropertyCell)
9623 // Dispatched behavior.
9624 DECLARE_PRINTER(PropertyCell)
9625 DECLARE_VERIFIER(PropertyCell)
9627 // Layout description.
9628 static const int kDetailsOffset = HeapObject::kHeaderSize;
9629 static const int kValueOffset = kDetailsOffset + kPointerSize;
9630 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9631 static const int kSize = kDependentCodeOffset + kPointerSize;
9633 static const int kPointerFieldsBeginOffset = kValueOffset;
9634 static const int kPointerFieldsEndOffset = kSize;
9636 typedef FixedBodyDescriptor<kValueOffset,
9638 kSize> BodyDescriptor;
9641 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9645 class WeakCell : public HeapObject {
9647 inline Object* value() const;
9649 // This should not be called by anyone except GC.
9650 inline void clear();
9652 // This should not be called by anyone except allocator.
9653 inline void initialize(HeapObject* value);
9655 inline bool cleared() const;
9657 DECL_ACCESSORS(next, Object)
9659 inline void clear_next(Heap* heap);
9661 inline bool next_cleared();
9663 DECLARE_CAST(WeakCell)
9665 DECLARE_PRINTER(WeakCell)
9666 DECLARE_VERIFIER(WeakCell)
9668 // Layout description.
9669 static const int kValueOffset = HeapObject::kHeaderSize;
9670 static const int kNextOffset = kValueOffset + kPointerSize;
9671 static const int kSize = kNextOffset + kPointerSize;
9673 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9676 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9680 // The JSProxy describes EcmaScript Harmony proxies
9681 class JSProxy: public JSReceiver {
9683 // [handler]: The handler property.
9684 DECL_ACCESSORS(handler, Object)
9686 // [hash]: The hash code property (undefined if not initialized yet).
9687 DECL_ACCESSORS(hash, Object)
9689 DECLARE_CAST(JSProxy)
9691 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9692 Handle<JSProxy> proxy,
9693 Handle<Object> receiver,
9696 // If the handler defines an accessor property with a setter, invoke it.
9697 // If it defines an accessor property without a setter, or a data property
9698 // that is read-only, throw. In all these cases set '*done' to true,
9699 // otherwise set it to false.
9701 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9702 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9703 Handle<Object> value, LanguageMode language_mode, bool* done);
9705 MUST_USE_RESULT static Maybe<PropertyAttributes>
9706 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9707 Handle<Object> receiver,
9709 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9710 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9711 Handle<Object> value, LanguageMode language_mode);
9713 // Turn the proxy into an (empty) JSObject.
9714 static void Fix(Handle<JSProxy> proxy);
9716 // Initializes the body after the handler slot.
9717 inline void InitializeBody(int object_size, Object* value);
9719 // Invoke a trap by name. If the trap does not exist on this's handler,
9720 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9721 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9722 Handle<JSProxy> proxy,
9724 Handle<Object> derived_trap,
9726 Handle<Object> args[]);
9728 // Dispatched behavior.
9729 DECLARE_PRINTER(JSProxy)
9730 DECLARE_VERIFIER(JSProxy)
9732 // Layout description. We add padding so that a proxy has the same
9733 // size as a virgin JSObject. This is essential for becoming a JSObject
9735 static const int kHandlerOffset = HeapObject::kHeaderSize;
9736 static const int kHashOffset = kHandlerOffset + kPointerSize;
9737 static const int kPaddingOffset = kHashOffset + kPointerSize;
9738 static const int kSize = JSObject::kHeaderSize;
9739 static const int kHeaderSize = kPaddingOffset;
9740 static const int kPaddingSize = kSize - kPaddingOffset;
9742 STATIC_ASSERT(kPaddingSize >= 0);
9744 typedef FixedBodyDescriptor<kHandlerOffset,
9746 kSize> BodyDescriptor;
9749 friend class JSReceiver;
9751 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9752 Handle<JSProxy> proxy, Handle<Name> name);
9754 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9755 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9757 MUST_USE_RESULT Object* GetIdentityHash();
9759 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9761 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9765 class JSFunctionProxy: public JSProxy {
9767 // [call_trap]: The call trap.
9768 DECL_ACCESSORS(call_trap, Object)
9770 // [construct_trap]: The construct trap.
9771 DECL_ACCESSORS(construct_trap, Object)
9773 DECLARE_CAST(JSFunctionProxy)
9775 // Dispatched behavior.
9776 DECLARE_PRINTER(JSFunctionProxy)
9777 DECLARE_VERIFIER(JSFunctionProxy)
9779 // Layout description.
9780 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9781 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9782 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9783 static const int kSize = JSFunction::kSize;
9784 static const int kPaddingSize = kSize - kPaddingOffset;
9786 STATIC_ASSERT(kPaddingSize >= 0);
9788 typedef FixedBodyDescriptor<kHandlerOffset,
9789 kConstructTrapOffset + kPointerSize,
9790 kSize> BodyDescriptor;
9793 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9797 class JSCollection : public JSObject {
9799 // [table]: the backing hash table
9800 DECL_ACCESSORS(table, Object)
9802 static const int kTableOffset = JSObject::kHeaderSize;
9803 static const int kSize = kTableOffset + kPointerSize;
9806 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9810 // The JSSet describes EcmaScript Harmony sets
9811 class JSSet : public JSCollection {
9815 // Dispatched behavior.
9816 DECLARE_PRINTER(JSSet)
9817 DECLARE_VERIFIER(JSSet)
9820 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9824 // The JSMap describes EcmaScript Harmony maps
9825 class JSMap : public JSCollection {
9829 // Dispatched behavior.
9830 DECLARE_PRINTER(JSMap)
9831 DECLARE_VERIFIER(JSMap)
9834 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9838 // OrderedHashTableIterator is an iterator that iterates over the keys and
9839 // values of an OrderedHashTable.
9841 // The iterator has a reference to the underlying OrderedHashTable data,
9842 // [table], as well as the current [index] the iterator is at.
9844 // When the OrderedHashTable is rehashed it adds a reference from the old table
9845 // to the new table as well as storing enough data about the changes so that the
9846 // iterator [index] can be adjusted accordingly.
9848 // When the [Next] result from the iterator is requested, the iterator checks if
9849 // there is a newer table that it needs to transition to.
9850 template<class Derived, class TableType>
9851 class OrderedHashTableIterator: public JSObject {
9853 // [table]: the backing hash table mapping keys to values.
9854 DECL_ACCESSORS(table, Object)
9856 // [index]: The index into the data table.
9857 DECL_ACCESSORS(index, Object)
9859 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9860 DECL_ACCESSORS(kind, Object)
9863 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9866 static const int kTableOffset = JSObject::kHeaderSize;
9867 static const int kIndexOffset = kTableOffset + kPointerSize;
9868 static const int kKindOffset = kIndexOffset + kPointerSize;
9869 static const int kSize = kKindOffset + kPointerSize;
9877 // Whether the iterator has more elements. This needs to be called before
9878 // calling |CurrentKey| and/or |CurrentValue|.
9881 // Move the index forward one.
9883 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9886 // Populates the array with the next key and value and then moves the iterator
9888 // This returns the |kind| or 0 if the iterator is already at the end.
9889 Smi* Next(JSArray* value_array);
9891 // Returns the current key of the iterator. This should only be called when
9892 // |HasMore| returns true.
9893 inline Object* CurrentKey();
9896 // Transitions the iterator to the non obsolete backing store. This is a NOP
9897 // if the [table] is not obsolete.
9900 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9904 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9907 // Dispatched behavior.
9908 DECLARE_PRINTER(JSSetIterator)
9909 DECLARE_VERIFIER(JSSetIterator)
9911 DECLARE_CAST(JSSetIterator)
9913 // Called by |Next| to populate the array. This allows the subclasses to
9914 // populate the array differently.
9915 inline void PopulateValueArray(FixedArray* array);
9918 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9922 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9925 // Dispatched behavior.
9926 DECLARE_PRINTER(JSMapIterator)
9927 DECLARE_VERIFIER(JSMapIterator)
9929 DECLARE_CAST(JSMapIterator)
9931 // Called by |Next| to populate the array. This allows the subclasses to
9932 // populate the array differently.
9933 inline void PopulateValueArray(FixedArray* array);
9936 // Returns the current value of the iterator. This should only be called when
9937 // |HasMore| returns true.
9938 inline Object* CurrentValue();
9940 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9944 // Base class for both JSWeakMap and JSWeakSet
9945 class JSWeakCollection: public JSObject {
9947 // [table]: the backing hash table mapping keys to values.
9948 DECL_ACCESSORS(table, Object)
9950 // [next]: linked list of encountered weak maps during GC.
9951 DECL_ACCESSORS(next, Object)
9953 static const int kTableOffset = JSObject::kHeaderSize;
9954 static const int kNextOffset = kTableOffset + kPointerSize;
9955 static const int kSize = kNextOffset + kPointerSize;
9958 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9962 // The JSWeakMap describes EcmaScript Harmony weak maps
9963 class JSWeakMap: public JSWeakCollection {
9965 DECLARE_CAST(JSWeakMap)
9967 // Dispatched behavior.
9968 DECLARE_PRINTER(JSWeakMap)
9969 DECLARE_VERIFIER(JSWeakMap)
9972 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9976 // The JSWeakSet describes EcmaScript Harmony weak sets
9977 class JSWeakSet: public JSWeakCollection {
9979 DECLARE_CAST(JSWeakSet)
9981 // Dispatched behavior.
9982 DECLARE_PRINTER(JSWeakSet)
9983 DECLARE_VERIFIER(JSWeakSet)
9986 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9990 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9991 enum class SharedFlag { kNotShared, kShared };
9994 class JSArrayBuffer: public JSObject {
9996 // [backing_store]: backing memory for this array
9997 DECL_ACCESSORS(backing_store, void)
9999 // [byte_length]: length in bytes
10000 DECL_ACCESSORS(byte_length, Object)
10002 inline uint32_t bit_field() const;
10003 inline void set_bit_field(uint32_t bits);
10005 inline bool is_external();
10006 inline void set_is_external(bool value);
10008 inline bool is_neuterable();
10009 inline void set_is_neuterable(bool value);
10011 inline bool was_neutered();
10012 inline void set_was_neutered(bool value);
10014 inline bool is_shared();
10015 inline void set_is_shared(bool value);
10017 DECLARE_CAST(JSArrayBuffer)
10021 // Dispatched behavior.
10022 DECLARE_PRINTER(JSArrayBuffer)
10023 DECLARE_VERIFIER(JSArrayBuffer)
10025 static const int kBackingStoreOffset = JSObject::kHeaderSize;
10026 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10027 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
10028 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
10029 static const int kBitFieldOffset = kBitFieldSlot;
10031 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
10033 static const int kSize = kBitFieldSlot + kPointerSize;
10035 static const int kSizeWithInternalFields =
10036 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10038 class IsExternal : public BitField<bool, 1, 1> {};
10039 class IsNeuterable : public BitField<bool, 2, 1> {};
10040 class WasNeutered : public BitField<bool, 3, 1> {};
10041 class IsShared : public BitField<bool, 4, 1> {};
10044 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10048 class JSArrayBufferView: public JSObject {
10050 // [buffer]: ArrayBuffer that this typed array views.
10051 DECL_ACCESSORS(buffer, Object)
10053 // [byte_offset]: offset of typed array in bytes.
10054 DECL_ACCESSORS(byte_offset, Object)
10056 // [byte_length]: length of typed array in bytes.
10057 DECL_ACCESSORS(byte_length, Object)
10059 DECLARE_CAST(JSArrayBufferView)
10061 DECLARE_VERIFIER(JSArrayBufferView)
10063 inline bool WasNeutered() const;
10065 static const int kBufferOffset = JSObject::kHeaderSize;
10066 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10067 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10068 static const int kViewSize = kByteLengthOffset + kPointerSize;
10072 DECL_ACCESSORS(raw_byte_offset, Object)
10073 DECL_ACCESSORS(raw_byte_length, Object)
10076 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10080 class JSTypedArray: public JSArrayBufferView {
10082 // [length]: length of typed array in elements.
10083 DECL_ACCESSORS(length, Object)
10084 inline uint32_t length_value() const;
10086 DECLARE_CAST(JSTypedArray)
10088 ExternalArrayType type();
10089 size_t element_size();
10091 Handle<JSArrayBuffer> GetBuffer();
10093 // Dispatched behavior.
10094 DECLARE_PRINTER(JSTypedArray)
10095 DECLARE_VERIFIER(JSTypedArray)
10097 static const int kLengthOffset = kViewSize + kPointerSize;
10098 static const int kSize = kLengthOffset + kPointerSize;
10100 static const int kSizeWithInternalFields =
10101 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10104 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10105 Handle<JSTypedArray> typed_array);
10107 DECL_ACCESSORS(raw_length, Object)
10110 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10114 class JSDataView: public JSArrayBufferView {
10116 DECLARE_CAST(JSDataView)
10118 // Dispatched behavior.
10119 DECLARE_PRINTER(JSDataView)
10120 DECLARE_VERIFIER(JSDataView)
10122 static const int kSize = kViewSize;
10124 static const int kSizeWithInternalFields =
10125 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10128 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10132 // Foreign describes objects pointing from JavaScript to C structures.
10133 class Foreign: public HeapObject {
10135 // [address]: field containing the address.
10136 inline Address foreign_address();
10137 inline void set_foreign_address(Address value);
10139 DECLARE_CAST(Foreign)
10141 // Dispatched behavior.
10142 inline void ForeignIterateBody(ObjectVisitor* v);
10144 template<typename StaticVisitor>
10145 inline void ForeignIterateBody();
10147 // Dispatched behavior.
10148 DECLARE_PRINTER(Foreign)
10149 DECLARE_VERIFIER(Foreign)
10151 // Layout description.
10153 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10154 static const int kSize = kForeignAddressOffset + kPointerSize;
10156 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10159 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10163 // The JSArray describes JavaScript Arrays
10164 // Such an array can be in one of two modes:
10165 // - fast, backing storage is a FixedArray and length <= elements.length();
10166 // Please note: push and pop can be used to grow and shrink the array.
10167 // - slow, backing storage is a HashTable with numbers as keys.
10168 class JSArray: public JSObject {
10170 // [length]: The length property.
10171 DECL_ACCESSORS(length, Object)
10173 // Overload the length setter to skip write barrier when the length
10174 // is set to a smi. This matches the set function on FixedArray.
10175 inline void set_length(Smi* length);
10177 static bool HasReadOnlyLength(Handle<JSArray> array);
10178 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10179 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10181 // Initialize the array with the given capacity. The function may
10182 // fail due to out-of-memory situations, but only if the requested
10183 // capacity is non-zero.
10184 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10186 // If the JSArray has fast elements, and new_length would result in
10187 // normalization, returns true.
10188 bool SetLengthWouldNormalize(uint32_t new_length);
10189 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
10191 // Initializes the array to a certain length.
10192 inline bool AllowsSetLength();
10194 static void SetLength(Handle<JSArray> array, uint32_t length);
10195 // Same as above but will also queue splice records if |array| is observed.
10196 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
10199 // Set the content of the array to the content of storage.
10200 static inline void SetContent(Handle<JSArray> array,
10201 Handle<FixedArrayBase> storage);
10203 DECLARE_CAST(JSArray)
10205 // Dispatched behavior.
10206 DECLARE_PRINTER(JSArray)
10207 DECLARE_VERIFIER(JSArray)
10209 // Number of element slots to pre-allocate for an empty array.
10210 static const int kPreallocatedArrayElements = 4;
10212 // Layout description.
10213 static const int kLengthOffset = JSObject::kHeaderSize;
10214 static const int kSize = kLengthOffset + kPointerSize;
10217 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10221 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10222 Handle<Map> initial_map);
10225 // JSRegExpResult is just a JSArray with a specific initial map.
10226 // This initial map adds in-object properties for "index" and "input"
10227 // properties, as assigned by RegExp.prototype.exec, which allows
10228 // faster creation of RegExp exec results.
10229 // This class just holds constants used when creating the result.
10230 // After creation the result must be treated as a JSArray in all regards.
10231 class JSRegExpResult: public JSArray {
10233 // Offsets of object fields.
10234 static const int kIndexOffset = JSArray::kSize;
10235 static const int kInputOffset = kIndexOffset + kPointerSize;
10236 static const int kSize = kInputOffset + kPointerSize;
10237 // Indices of in-object properties.
10238 static const int kIndexIndex = 0;
10239 static const int kInputIndex = 1;
10241 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10245 class AccessorInfo: public Struct {
10247 DECL_ACCESSORS(name, Object)
10248 DECL_ACCESSORS(flag, Smi)
10249 DECL_ACCESSORS(expected_receiver_type, Object)
10251 inline bool all_can_read();
10252 inline void set_all_can_read(bool value);
10254 inline bool all_can_write();
10255 inline void set_all_can_write(bool value);
10257 inline bool is_special_data_property();
10258 inline void set_is_special_data_property(bool value);
10260 inline PropertyAttributes property_attributes();
10261 inline void set_property_attributes(PropertyAttributes attributes);
10263 // Checks whether the given receiver is compatible with this accessor.
10264 static bool IsCompatibleReceiverMap(Isolate* isolate,
10265 Handle<AccessorInfo> info,
10267 inline bool IsCompatibleReceiver(Object* receiver);
10269 DECLARE_CAST(AccessorInfo)
10271 // Dispatched behavior.
10272 DECLARE_VERIFIER(AccessorInfo)
10274 // Append all descriptors to the array that are not already there.
10275 // Return number added.
10276 static int AppendUnique(Handle<Object> descriptors,
10277 Handle<FixedArray> array,
10278 int valid_descriptors);
10280 static const int kNameOffset = HeapObject::kHeaderSize;
10281 static const int kFlagOffset = kNameOffset + kPointerSize;
10282 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10283 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10286 inline bool HasExpectedReceiverType() {
10287 return expected_receiver_type()->IsFunctionTemplateInfo();
10289 // Bit positions in flag.
10290 static const int kAllCanReadBit = 0;
10291 static const int kAllCanWriteBit = 1;
10292 static const int kSpecialDataProperty = 2;
10293 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10295 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10299 // An accessor must have a getter, but can have no setter.
10301 // When setting a property, V8 searches accessors in prototypes.
10302 // If an accessor was found and it does not have a setter,
10303 // the request is ignored.
10305 // If the accessor in the prototype has the READ_ONLY property attribute, then
10306 // a new value is added to the derived object when the property is set.
10307 // This shadows the accessor in the prototype.
10308 class ExecutableAccessorInfo: public AccessorInfo {
10310 DECL_ACCESSORS(getter, Object)
10311 DECL_ACCESSORS(setter, Object)
10312 DECL_ACCESSORS(data, Object)
10314 DECLARE_CAST(ExecutableAccessorInfo)
10316 // Dispatched behavior.
10317 DECLARE_PRINTER(ExecutableAccessorInfo)
10318 DECLARE_VERIFIER(ExecutableAccessorInfo)
10320 static const int kGetterOffset = AccessorInfo::kSize;
10321 static const int kSetterOffset = kGetterOffset + kPointerSize;
10322 static const int kDataOffset = kSetterOffset + kPointerSize;
10323 static const int kSize = kDataOffset + kPointerSize;
10325 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10328 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10332 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10333 // accessor can either be
10334 // * a pointer to a JavaScript function or proxy: a real accessor
10335 // * undefined: considered an accessor by the spec, too, strangely enough
10336 // * the hole: an accessor which has not been set
10337 // * a pointer to a map: a transition used to ensure map sharing
10338 class AccessorPair: public Struct {
10340 DECL_ACCESSORS(getter, Object)
10341 DECL_ACCESSORS(setter, Object)
10343 DECLARE_CAST(AccessorPair)
10345 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10347 Object* get(AccessorComponent component) {
10348 return component == ACCESSOR_GETTER ? getter() : setter();
10351 void set(AccessorComponent component, Object* value) {
10352 if (component == ACCESSOR_GETTER) {
10359 // Note: Returns undefined instead in case of a hole.
10360 Object* GetComponent(AccessorComponent component);
10362 // Set both components, skipping arguments which are a JavaScript null.
10363 void SetComponents(Object* getter, Object* setter) {
10364 if (!getter->IsNull()) set_getter(getter);
10365 if (!setter->IsNull()) set_setter(setter);
10368 bool Equals(AccessorPair* pair) {
10369 return (this == pair) || pair->Equals(getter(), setter());
10372 bool Equals(Object* getter_value, Object* setter_value) {
10373 return (getter() == getter_value) && (setter() == setter_value);
10376 bool ContainsAccessor() {
10377 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10380 // Dispatched behavior.
10381 DECLARE_PRINTER(AccessorPair)
10382 DECLARE_VERIFIER(AccessorPair)
10384 static const int kGetterOffset = HeapObject::kHeaderSize;
10385 static const int kSetterOffset = kGetterOffset + kPointerSize;
10386 static const int kSize = kSetterOffset + kPointerSize;
10389 // Strangely enough, in addition to functions and harmony proxies, the spec
10390 // requires us to consider undefined as a kind of accessor, too:
10392 // Object.defineProperty(obj, "foo", {get: undefined});
10393 // assertTrue("foo" in obj);
10394 bool IsJSAccessor(Object* obj) {
10395 return obj->IsSpecFunction() || obj->IsUndefined();
10398 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10402 class AccessCheckInfo: public Struct {
10404 DECL_ACCESSORS(named_callback, Object)
10405 DECL_ACCESSORS(indexed_callback, Object)
10406 DECL_ACCESSORS(data, Object)
10408 DECLARE_CAST(AccessCheckInfo)
10410 // Dispatched behavior.
10411 DECLARE_PRINTER(AccessCheckInfo)
10412 DECLARE_VERIFIER(AccessCheckInfo)
10414 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10415 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10416 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10417 static const int kSize = kDataOffset + kPointerSize;
10420 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10424 class InterceptorInfo: public Struct {
10426 DECL_ACCESSORS(getter, Object)
10427 DECL_ACCESSORS(setter, Object)
10428 DECL_ACCESSORS(query, Object)
10429 DECL_ACCESSORS(deleter, Object)
10430 DECL_ACCESSORS(enumerator, Object)
10431 DECL_ACCESSORS(data, Object)
10432 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10433 DECL_BOOLEAN_ACCESSORS(all_can_read)
10434 DECL_BOOLEAN_ACCESSORS(non_masking)
10436 inline int flags() const;
10437 inline void set_flags(int flags);
10439 DECLARE_CAST(InterceptorInfo)
10441 // Dispatched behavior.
10442 DECLARE_PRINTER(InterceptorInfo)
10443 DECLARE_VERIFIER(InterceptorInfo)
10445 static const int kGetterOffset = HeapObject::kHeaderSize;
10446 static const int kSetterOffset = kGetterOffset + kPointerSize;
10447 static const int kQueryOffset = kSetterOffset + kPointerSize;
10448 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10449 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10450 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10451 static const int kFlagsOffset = kDataOffset + kPointerSize;
10452 static const int kSize = kFlagsOffset + kPointerSize;
10454 static const int kCanInterceptSymbolsBit = 0;
10455 static const int kAllCanReadBit = 1;
10456 static const int kNonMasking = 2;
10459 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10463 class CallHandlerInfo: public Struct {
10465 DECL_ACCESSORS(callback, Object)
10466 DECL_ACCESSORS(data, Object)
10468 DECLARE_CAST(CallHandlerInfo)
10470 // Dispatched behavior.
10471 DECLARE_PRINTER(CallHandlerInfo)
10472 DECLARE_VERIFIER(CallHandlerInfo)
10474 static const int kCallbackOffset = HeapObject::kHeaderSize;
10475 static const int kDataOffset = kCallbackOffset + kPointerSize;
10476 static const int kSize = kDataOffset + kPointerSize;
10479 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10483 class TemplateInfo: public Struct {
10485 DECL_ACCESSORS(tag, Object)
10486 inline int number_of_properties() const;
10487 inline void set_number_of_properties(int value);
10488 DECL_ACCESSORS(property_list, Object)
10489 DECL_ACCESSORS(property_accessors, Object)
10491 DECLARE_VERIFIER(TemplateInfo)
10493 static const int kTagOffset = HeapObject::kHeaderSize;
10494 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10495 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10496 static const int kPropertyAccessorsOffset =
10497 kPropertyListOffset + kPointerSize;
10498 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10501 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10505 class FunctionTemplateInfo: public TemplateInfo {
10507 DECL_ACCESSORS(serial_number, Object)
10508 DECL_ACCESSORS(call_code, Object)
10509 DECL_ACCESSORS(prototype_template, Object)
10510 DECL_ACCESSORS(parent_template, Object)
10511 DECL_ACCESSORS(named_property_handler, Object)
10512 DECL_ACCESSORS(indexed_property_handler, Object)
10513 DECL_ACCESSORS(instance_template, Object)
10514 DECL_ACCESSORS(class_name, Object)
10515 DECL_ACCESSORS(signature, Object)
10516 DECL_ACCESSORS(instance_call_handler, Object)
10517 DECL_ACCESSORS(access_check_info, Object)
10518 DECL_ACCESSORS(flag, Smi)
10520 inline int length() const;
10521 inline void set_length(int value);
10523 // Following properties use flag bits.
10524 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10525 DECL_BOOLEAN_ACCESSORS(undetectable)
10526 // If the bit is set, object instances created by this function
10527 // requires access check.
10528 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10529 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10530 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10531 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10532 DECL_BOOLEAN_ACCESSORS(instantiated)
10533 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10535 DECLARE_CAST(FunctionTemplateInfo)
10537 // Dispatched behavior.
10538 DECLARE_PRINTER(FunctionTemplateInfo)
10539 DECLARE_VERIFIER(FunctionTemplateInfo)
10541 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10542 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10543 static const int kPrototypeTemplateOffset =
10544 kCallCodeOffset + kPointerSize;
10545 static const int kParentTemplateOffset =
10546 kPrototypeTemplateOffset + kPointerSize;
10547 static const int kNamedPropertyHandlerOffset =
10548 kParentTemplateOffset + kPointerSize;
10549 static const int kIndexedPropertyHandlerOffset =
10550 kNamedPropertyHandlerOffset + kPointerSize;
10551 static const int kInstanceTemplateOffset =
10552 kIndexedPropertyHandlerOffset + kPointerSize;
10553 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10554 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10555 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10556 static const int kAccessCheckInfoOffset =
10557 kInstanceCallHandlerOffset + kPointerSize;
10558 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10559 static const int kLengthOffset = kFlagOffset + kPointerSize;
10560 static const int kSize = kLengthOffset + kPointerSize;
10562 // Returns true if |object| is an instance of this function template.
10563 bool IsTemplateFor(Object* object);
10564 bool IsTemplateFor(Map* map);
10566 // Returns the holder JSObject if the function can legally be called with this
10567 // receiver. Returns Heap::null_value() if the call is illegal.
10568 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10571 // Bit position in the flag, from least significant bit position.
10572 static const int kHiddenPrototypeBit = 0;
10573 static const int kUndetectableBit = 1;
10574 static const int kNeedsAccessCheckBit = 2;
10575 static const int kReadOnlyPrototypeBit = 3;
10576 static const int kRemovePrototypeBit = 4;
10577 static const int kDoNotCacheBit = 5;
10578 static const int kInstantiatedBit = 6;
10579 static const int kAcceptAnyReceiver = 7;
10581 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10585 class ObjectTemplateInfo: public TemplateInfo {
10587 DECL_ACCESSORS(constructor, Object)
10588 DECL_ACCESSORS(internal_field_count, Object)
10590 DECLARE_CAST(ObjectTemplateInfo)
10592 // Dispatched behavior.
10593 DECLARE_PRINTER(ObjectTemplateInfo)
10594 DECLARE_VERIFIER(ObjectTemplateInfo)
10596 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10597 static const int kInternalFieldCountOffset =
10598 kConstructorOffset + kPointerSize;
10599 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10603 class TypeSwitchInfo: public Struct {
10605 DECL_ACCESSORS(types, Object)
10607 DECLARE_CAST(TypeSwitchInfo)
10609 // Dispatched behavior.
10610 DECLARE_PRINTER(TypeSwitchInfo)
10611 DECLARE_VERIFIER(TypeSwitchInfo)
10613 static const int kTypesOffset = Struct::kHeaderSize;
10614 static const int kSize = kTypesOffset + kPointerSize;
10618 // The DebugInfo class holds additional information for a function being
10620 class DebugInfo: public Struct {
10622 // The shared function info for the source being debugged.
10623 DECL_ACCESSORS(shared, SharedFunctionInfo)
10624 // Code object for the patched code. This code object is the code object
10625 // currently active for the function.
10626 DECL_ACCESSORS(code, Code)
10627 // Fixed array holding status information for each active break point.
10628 DECL_ACCESSORS(break_points, FixedArray)
10630 // Check if there is a break point at a code position.
10631 bool HasBreakPoint(int code_position);
10632 // Get the break point info object for a code position.
10633 Object* GetBreakPointInfo(int code_position);
10634 // Clear a break point.
10635 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10637 Handle<Object> break_point_object);
10638 // Set a break point.
10639 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10640 int source_position, int statement_position,
10641 Handle<Object> break_point_object);
10642 // Get the break point objects for a code position.
10643 Handle<Object> GetBreakPointObjects(int code_position);
10644 // Find the break point info holding this break point object.
10645 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10646 Handle<Object> break_point_object);
10647 // Get the number of break points for this function.
10648 int GetBreakPointCount();
10650 DECLARE_CAST(DebugInfo)
10652 // Dispatched behavior.
10653 DECLARE_PRINTER(DebugInfo)
10654 DECLARE_VERIFIER(DebugInfo)
10656 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10657 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10658 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10659 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10661 static const int kEstimatedNofBreakPointsInFunction = 16;
10664 static const int kNoBreakPointInfo = -1;
10666 // Lookup the index in the break_points array for a code position.
10667 int GetBreakPointInfoIndex(int code_position);
10669 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10673 // The BreakPointInfo class holds information for break points set in a
10674 // function. The DebugInfo object holds a BreakPointInfo object for each code
10675 // position with one or more break points.
10676 class BreakPointInfo: public Struct {
10678 // The position in the code for the break point.
10679 DECL_ACCESSORS(code_position, Smi)
10680 // The position in the source for the break position.
10681 DECL_ACCESSORS(source_position, Smi)
10682 // The position in the source for the last statement before this break
10684 DECL_ACCESSORS(statement_position, Smi)
10685 // List of related JavaScript break points.
10686 DECL_ACCESSORS(break_point_objects, Object)
10688 // Removes a break point.
10689 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10690 Handle<Object> break_point_object);
10691 // Set a break point.
10692 static void SetBreakPoint(Handle<BreakPointInfo> info,
10693 Handle<Object> break_point_object);
10694 // Check if break point info has this break point object.
10695 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10696 Handle<Object> break_point_object);
10697 // Get the number of break points for this code position.
10698 int GetBreakPointCount();
10700 DECLARE_CAST(BreakPointInfo)
10702 // Dispatched behavior.
10703 DECLARE_PRINTER(BreakPointInfo)
10704 DECLARE_VERIFIER(BreakPointInfo)
10706 static const int kCodePositionIndex = Struct::kHeaderSize;
10707 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10708 static const int kStatementPositionIndex =
10709 kSourcePositionIndex + kPointerSize;
10710 static const int kBreakPointObjectsIndex =
10711 kStatementPositionIndex + kPointerSize;
10712 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10715 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10719 #undef DECL_BOOLEAN_ACCESSORS
10720 #undef DECL_ACCESSORS
10721 #undef DECLARE_CAST
10722 #undef DECLARE_VERIFIER
10724 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10725 V(kStringTable, "string_table", "(Internalized strings)") \
10726 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10727 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10728 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10729 V(kInternalizedString, "internalized_string", "(Internal string)") \
10730 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10731 V(kTop, "top", "(Isolate)") \
10732 V(kRelocatable, "relocatable", "(Relocatable)") \
10733 V(kDebug, "debug", "(Debugger)") \
10734 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10735 V(kHandleScope, "handlescope", "(Handle scope)") \
10736 V(kBuiltins, "builtins", "(Builtins)") \
10737 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10738 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10739 V(kThreadManager, "threadmanager", "(Thread manager)") \
10740 V(kStrongRoots, "strong roots", "(Strong roots)") \
10741 V(kExtensions, "Extensions", "(Extensions)")
10743 class VisitorSynchronization : public AllStatic {
10745 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10747 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10750 #undef DECLARE_ENUM
10752 static const char* const kTags[kNumberOfSyncTags];
10753 static const char* const kTagNames[kNumberOfSyncTags];
10756 // Abstract base class for visiting, and optionally modifying, the
10757 // pointers contained in Objects. Used in GC and serialization/deserialization.
10758 class ObjectVisitor BASE_EMBEDDED {
10760 virtual ~ObjectVisitor() {}
10762 // Visits a contiguous arrays of pointers in the half-open range
10763 // [start, end). Any or all of the values may be modified on return.
10764 virtual void VisitPointers(Object** start, Object** end) = 0;
10766 // Handy shorthand for visiting a single pointer.
10767 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10769 // Visit weak next_code_link in Code object.
10770 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10772 // To allow lazy clearing of inline caches the visitor has
10773 // a rich interface for iterating over Code objects..
10775 // Visits a code target in the instruction stream.
10776 virtual void VisitCodeTarget(RelocInfo* rinfo);
10778 // Visits a code entry in a JS function.
10779 virtual void VisitCodeEntry(Address entry_address);
10781 // Visits a global property cell reference in the instruction stream.
10782 virtual void VisitCell(RelocInfo* rinfo);
10784 // Visits a runtime entry in the instruction stream.
10785 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10787 // Visits the resource of an one-byte or two-byte string.
10788 virtual void VisitExternalOneByteString(
10789 v8::String::ExternalOneByteStringResource** resource) {}
10790 virtual void VisitExternalTwoByteString(
10791 v8::String::ExternalStringResource** resource) {}
10793 // Visits a debug call target in the instruction stream.
10794 virtual void VisitDebugTarget(RelocInfo* rinfo);
10796 // Visits the byte sequence in a function's prologue that contains information
10797 // about the code's age.
10798 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10800 // Visit pointer embedded into a code object.
10801 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10803 // Visits an external reference embedded into a code object.
10804 virtual void VisitExternalReference(RelocInfo* rinfo);
10806 // Visits an external reference.
10807 virtual void VisitExternalReference(Address* p) {}
10809 // Visits an (encoded) internal reference.
10810 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10812 // Visits a handle that has an embedder-assigned class ID.
10813 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10815 // Intended for serialization/deserialization checking: insert, or
10816 // check for the presence of, a tag at this position in the stream.
10817 // Also used for marking up GC roots in heap snapshots.
10818 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10822 class StructBodyDescriptor : public
10823 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10825 static inline int SizeOf(Map* map, HeapObject* object) {
10826 return map->instance_size();
10831 // BooleanBit is a helper class for setting and getting a bit in an
10833 class BooleanBit : public AllStatic {
10835 static inline bool get(Smi* smi, int bit_position) {
10836 return get(smi->value(), bit_position);
10839 static inline bool get(int value, int bit_position) {
10840 return (value & (1 << bit_position)) != 0;
10843 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10844 return Smi::FromInt(set(smi->value(), bit_position, v));
10847 static inline int set(int value, int bit_position, bool v) {
10849 value |= (1 << bit_position);
10851 value &= ~(1 << bit_position);
10857 } } // namespace v8::internal
10859 #endif // V8_OBJECTS_H_