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 support for serialized scope info. Returns the
3996 // parameter index for a given parameter name if the parameter is present;
3997 // otherwise returns a value < 0. The name must be an internalized string.
3998 int ParameterIndex(String* name);
4000 // Lookup support for serialized scope info. Returns the function context
4001 // slot index if the function name is present and context-allocated (named
4002 // function expressions, only), otherwise returns a value < 0. The name
4003 // must be an internalized string.
4004 int FunctionContextSlotIndex(String* name, VariableMode* mode);
4006 // Lookup support for serialized scope info. Returns the receiver context
4007 // slot index if scope has a "this" binding, and the binding is
4008 // context-allocated. Otherwise returns a value < 0.
4009 int ReceiverContextSlotIndex();
4011 FunctionKind function_kind();
4013 // Copies all the context locals into an object used to materialize a scope.
4014 static void CopyContextLocalsToScopeObject(Handle<ScopeInfo> scope_info,
4015 Handle<Context> context,
4016 Handle<JSObject> scope_object);
4019 static Handle<ScopeInfo> Create(Isolate* isolate, Zone* zone, Scope* scope);
4020 static Handle<ScopeInfo> CreateGlobalThisBinding(Isolate* isolate);
4022 // Serializes empty scope info.
4023 static ScopeInfo* Empty(Isolate* isolate);
4029 // The layout of the static part of a ScopeInfo is as follows. Each entry is
4030 // numeric and occupies one array slot.
4031 // 1. A set of properties of the scope
4032 // 2. The number of parameters. This only applies to function scopes. For
4033 // non-function scopes this is 0.
4034 // 3. The number of non-parameter variables allocated on the stack.
4035 // 4. The number of non-parameter and parameter variables allocated in the
4037 #define FOR_EACH_NUMERIC_FIELD(V) \
4040 V(StackLocalCount) \
4041 V(ContextLocalCount) \
4042 V(ContextGlobalCount) \
4043 V(StrongModeFreeVariableCount)
4045 #define FIELD_ACCESSORS(name) \
4046 void Set##name(int value) { \
4047 set(k##name, Smi::FromInt(value)); \
4050 if (length() > 0) { \
4051 return Smi::cast(get(k##name))->value(); \
4056 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
4057 #undef FIELD_ACCESSORS
4061 #define DECL_INDEX(name) k##name,
4062 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
4064 #undef FOR_EACH_NUMERIC_FIELD
4068 // The layout of the variable part of a ScopeInfo is as follows:
4069 // 1. ParameterEntries:
4070 // This part stores the names of the parameters for function scopes. One
4071 // slot is used per parameter, so in total this part occupies
4072 // ParameterCount() slots in the array. For other scopes than function
4073 // scopes ParameterCount() is 0.
4074 // 2. StackLocalFirstSlot:
4075 // Index of a first stack slot for stack local. Stack locals belonging to
4076 // this scope are located on a stack at slots starting from this index.
4077 // 3. StackLocalEntries:
4078 // Contains the names of local variables that are allocated on the stack,
4079 // in increasing order of the stack slot index. First local variable has
4080 // a stack slot index defined in StackLocalFirstSlot (point 2 above).
4081 // One slot is used per stack local, so in total this part occupies
4082 // StackLocalCount() slots in the array.
4083 // 4. ContextLocalNameEntries:
4084 // Contains the names of local variables and parameters that are allocated
4085 // in the context. They are stored in increasing order of the context slot
4086 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
4087 // context local, so in total this part occupies ContextLocalCount() slots
4089 // 5. ContextLocalInfoEntries:
4090 // Contains the variable modes and initialization flags corresponding to
4091 // the context locals in ContextLocalNameEntries. One slot is used per
4092 // context local, so in total this part occupies ContextLocalCount()
4093 // slots in the array.
4094 // 6. StrongModeFreeVariableNameEntries:
4095 // Stores the names of strong mode free variables.
4096 // 7. StrongModeFreeVariablePositionEntries:
4097 // Stores the locations (start and end position) of strong mode free
4099 // 8. RecieverEntryIndex:
4100 // If the scope binds a "this" value, one slot is reserved to hold the
4101 // context or stack slot index for the variable.
4102 // 9. FunctionNameEntryIndex:
4103 // If the scope belongs to a named function expression this part contains
4104 // information about the function variable. It always occupies two array
4105 // slots: a. The name of the function variable.
4106 // b. The context or stack slot index for the variable.
4107 int ParameterEntriesIndex();
4108 int StackLocalFirstSlotIndex();
4109 int StackLocalEntriesIndex();
4110 int ContextLocalNameEntriesIndex();
4111 int ContextGlobalNameEntriesIndex();
4112 int ContextLocalInfoEntriesIndex();
4113 int ContextGlobalInfoEntriesIndex();
4114 int StrongModeFreeVariableNameEntriesIndex();
4115 int StrongModeFreeVariablePositionEntriesIndex();
4116 int ReceiverEntryIndex();
4117 int FunctionNameEntryIndex();
4119 int Lookup(Handle<String> name, int start, int end, VariableMode* mode,
4120 VariableLocation* location, InitializationFlag* init_flag,
4121 MaybeAssignedFlag* maybe_assigned_flag);
4123 // Used for the function name variable for named function expressions, and for
4125 enum VariableAllocationInfo { NONE, STACK, CONTEXT, UNUSED };
4127 // Properties of scopes.
4128 class ScopeTypeField : public BitField<ScopeType, 0, 4> {};
4129 class CallsEvalField : public BitField<bool, ScopeTypeField::kNext, 1> {};
4130 STATIC_ASSERT(LANGUAGE_END == 3);
4131 class LanguageModeField
4132 : public BitField<LanguageMode, CallsEvalField::kNext, 2> {};
4133 class ReceiverVariableField
4134 : public BitField<VariableAllocationInfo, LanguageModeField::kNext, 2> {};
4135 class FunctionVariableField
4136 : public BitField<VariableAllocationInfo, ReceiverVariableField::kNext,
4138 class FunctionVariableMode
4139 : public BitField<VariableMode, FunctionVariableField::kNext, 3> {};
4140 class AsmModuleField : public BitField<bool, FunctionVariableMode::kNext, 1> {
4142 class AsmFunctionField : public BitField<bool, AsmModuleField::kNext, 1> {};
4143 class IsSimpleParameterListField
4144 : public BitField<bool, AsmFunctionField::kNext, 1> {};
4145 class FunctionKindField
4146 : public BitField<FunctionKind, IsSimpleParameterListField::kNext, 8> {};
4148 // BitFields representing the encoded information for context locals in the
4149 // ContextLocalInfoEntries part.
4150 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
4151 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
4152 class ContextLocalMaybeAssignedFlag
4153 : public BitField<MaybeAssignedFlag, 4, 1> {};
4157 // The cache for maps used by normalized (dictionary mode) objects.
4158 // Such maps do not have property descriptors, so a typical program
4159 // needs very limited number of distinct normalized maps.
4160 class NormalizedMapCache: public FixedArray {
4162 static Handle<NormalizedMapCache> New(Isolate* isolate);
4164 MUST_USE_RESULT MaybeHandle<Map> Get(Handle<Map> fast_map,
4165 PropertyNormalizationMode mode);
4166 void Set(Handle<Map> fast_map, Handle<Map> normalized_map);
4170 DECLARE_CAST(NormalizedMapCache)
4172 static inline bool IsNormalizedMapCache(const Object* obj);
4174 DECLARE_VERIFIER(NormalizedMapCache)
4176 static const int kEntries = 64;
4178 static inline int GetIndex(Handle<Map> map);
4180 // The following declarations hide base class methods.
4181 Object* get(int index);
4182 void set(int index, Object* value);
4186 // ByteArray represents fixed sized byte arrays. Used for the relocation info
4187 // that is attached to code objects.
4188 class ByteArray: public FixedArrayBase {
4190 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
4192 // Setter and getter.
4193 inline byte get(int index);
4194 inline void set(int index, byte value);
4196 // Treat contents as an int array.
4197 inline int get_int(int index);
4199 static int SizeFor(int length) {
4200 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4202 // We use byte arrays for free blocks in the heap. Given a desired size in
4203 // bytes that is a multiple of the word size and big enough to hold a byte
4204 // array, this function returns the number of elements a byte array should
4206 static int LengthFor(int size_in_bytes) {
4207 DCHECK(IsAligned(size_in_bytes, kPointerSize));
4208 DCHECK(size_in_bytes >= kHeaderSize);
4209 return size_in_bytes - kHeaderSize;
4212 // Returns data start address.
4213 inline Address GetDataStartAddress();
4215 // Returns a pointer to the ByteArray object for a given data start address.
4216 static inline ByteArray* FromDataStartAddress(Address address);
4218 DECLARE_CAST(ByteArray)
4220 // Dispatched behavior.
4221 inline int ByteArraySize() {
4222 return SizeFor(this->length());
4224 DECLARE_PRINTER(ByteArray)
4225 DECLARE_VERIFIER(ByteArray)
4227 // Layout description.
4228 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
4230 // Maximal memory consumption for a single ByteArray.
4231 static const int kMaxSize = 512 * MB;
4232 // Maximal length of a single ByteArray.
4233 static const int kMaxLength = kMaxSize - kHeaderSize;
4236 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
4240 // BytecodeArray represents a sequence of interpreter bytecodes.
4241 class BytecodeArray : public FixedArrayBase {
4243 static int SizeFor(int length) {
4244 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
4247 // Setter and getter
4248 inline byte get(int index);
4249 inline void set(int index, byte value);
4251 // Returns data start address.
4252 inline Address GetFirstBytecodeAddress();
4254 // Accessors for frame size and the number of locals
4255 inline int frame_size() const;
4256 inline void set_frame_size(int value);
4257 inline int number_of_locals() const;
4258 inline void set_number_of_locals(int value);
4260 DECLARE_CAST(BytecodeArray)
4262 // Dispatched behavior.
4263 inline int BytecodeArraySize() { return SizeFor(this->length()); }
4265 DECLARE_PRINTER(BytecodeArray)
4266 DECLARE_VERIFIER(BytecodeArray)
4268 void Disassemble(std::ostream& os);
4270 // Layout description.
4271 static const int kFrameSizeOffset = FixedArrayBase::kHeaderSize;
4272 static const int kNumberOfLocalsOffset = kFrameSizeOffset + kIntSize;
4273 static const int kHeaderSize = kNumberOfLocalsOffset + 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 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
5064 // been compiled with IsOptimizing set to true.
5065 inline bool is_compiled_optimizable();
5066 inline void set_compiled_optimizable(bool value);
5068 // [has_reloc_info_for_serialization]: For FUNCTION kind, tells if its
5069 // reloc info includes runtime and external references to support
5070 // serialization/deserialization.
5071 inline bool has_reloc_info_for_serialization();
5072 inline void set_has_reloc_info_for_serialization(bool value);
5074 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
5075 // how long the function has been marked for OSR and therefore which
5076 // level of loop nesting we are willing to do on-stack replacement
5078 inline void set_allow_osr_at_loop_nesting_level(int level);
5079 inline int allow_osr_at_loop_nesting_level();
5081 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
5082 // the code object was seen on the stack with no IC patching going on.
5083 inline int profiler_ticks();
5084 inline void set_profiler_ticks(int ticks);
5086 // [builtin_index]: For BUILTIN kind, tells which builtin index it has.
5087 // For builtins, tells which builtin index it has.
5088 // Note that builtins can have a code kind other than BUILTIN, which means
5089 // that for arbitrary code objects, this index value may be random garbage.
5090 // To verify in that case, compare the code object to the indexed builtin.
5091 inline int builtin_index();
5092 inline void set_builtin_index(int id);
5094 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
5095 // reserved in the code prologue.
5096 inline unsigned stack_slots();
5097 inline void set_stack_slots(unsigned slots);
5099 // [safepoint_table_start]: For kind OPTIMIZED_FUNCTION, the offset in
5100 // the instruction stream where the safepoint table starts.
5101 inline unsigned safepoint_table_offset();
5102 inline void set_safepoint_table_offset(unsigned offset);
5104 // [back_edge_table_start]: For kind FUNCTION, the offset in the
5105 // instruction stream where the back edge table starts.
5106 inline unsigned back_edge_table_offset();
5107 inline void set_back_edge_table_offset(unsigned offset);
5109 inline bool back_edges_patched_for_osr();
5111 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
5112 inline uint16_t to_boolean_state();
5114 // [has_function_cache]: For kind STUB tells whether there is a function
5115 // cache is passed to the stub.
5116 inline bool has_function_cache();
5117 inline void set_has_function_cache(bool flag);
5120 // [marked_for_deoptimization]: For kind OPTIMIZED_FUNCTION tells whether
5121 // the code is going to be deoptimized because of dead embedded maps.
5122 inline bool marked_for_deoptimization();
5123 inline void set_marked_for_deoptimization(bool flag);
5125 // [constant_pool]: The constant pool for this function.
5126 inline Address constant_pool();
5128 // Get the safepoint entry for the given pc.
5129 SafepointEntry GetSafepointEntry(Address pc);
5131 // Find an object in a stub with a specified map
5132 Object* FindNthObject(int n, Map* match_map);
5134 // Find the first allocation site in an IC stub.
5135 AllocationSite* FindFirstAllocationSite();
5137 // Find the first map in an IC stub.
5138 Map* FindFirstMap();
5139 void FindAllMaps(MapHandleList* maps);
5141 // Find the first handler in an IC stub.
5142 Code* FindFirstHandler();
5144 // Find |length| handlers and put them into |code_list|. Returns false if not
5145 // enough handlers can be found.
5146 bool FindHandlers(CodeHandleList* code_list, int length = -1);
5148 // Find the handler for |map|.
5149 MaybeHandle<Code> FindHandlerForMap(Map* map);
5151 // Find the first name in an IC stub.
5152 Name* FindFirstName();
5154 class FindAndReplacePattern;
5155 // For each (map-to-find, object-to-replace) pair in the pattern, this
5156 // function replaces the corresponding placeholder in the code with the
5157 // object-to-replace. The function assumes that pairs in the pattern come in
5158 // the same order as the placeholders in the code.
5159 // If the placeholder is a weak cell, then the value of weak cell is matched
5160 // against the map-to-find.
5161 void FindAndReplace(const FindAndReplacePattern& pattern);
5163 // The entire code object including its header is copied verbatim to the
5164 // snapshot so that it can be written in one, fast, memcpy during
5165 // deserialization. The deserializer will overwrite some pointers, rather
5166 // like a runtime linker, but the random allocation addresses used in the
5167 // mksnapshot process would still be present in the unlinked snapshot data,
5168 // which would make snapshot production non-reproducible. This method wipes
5169 // out the to-be-overwritten header data for reproducible snapshots.
5170 inline void WipeOutHeader();
5172 // Flags operations.
5173 static inline Flags ComputeFlags(
5174 Kind kind, InlineCacheState ic_state = UNINITIALIZED,
5175 ExtraICState extra_ic_state = kNoExtraICState, StubType type = NORMAL,
5176 CacheHolderFlag holder = kCacheOnReceiver);
5178 static inline Flags ComputeMonomorphicFlags(
5179 Kind kind, ExtraICState extra_ic_state = kNoExtraICState,
5180 CacheHolderFlag holder = kCacheOnReceiver, StubType type = NORMAL);
5182 static inline Flags ComputeHandlerFlags(
5183 Kind handler_kind, StubType type = NORMAL,
5184 CacheHolderFlag holder = kCacheOnReceiver);
5186 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
5187 static inline StubType ExtractTypeFromFlags(Flags flags);
5188 static inline CacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
5189 static inline Kind ExtractKindFromFlags(Flags flags);
5190 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
5192 static inline Flags RemoveTypeFromFlags(Flags flags);
5193 static inline Flags RemoveTypeAndHolderFromFlags(Flags flags);
5195 // Convert a target address into a code object.
5196 static inline Code* GetCodeFromTargetAddress(Address address);
5198 // Convert an entry address into an object.
5199 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
5201 // Returns the address of the first instruction.
5202 inline byte* instruction_start();
5204 // Returns the address right after the last instruction.
5205 inline byte* instruction_end();
5207 // Returns the size of the instructions, padding, and relocation information.
5208 inline int body_size();
5210 // Returns the address of the first relocation info (read backwards!).
5211 inline byte* relocation_start();
5213 // Code entry point.
5214 inline byte* entry();
5216 // Returns true if pc is inside this object's instructions.
5217 inline bool contains(byte* pc);
5219 // Relocate the code by delta bytes. Called to signal that this code
5220 // object has been moved by delta bytes.
5221 void Relocate(intptr_t delta);
5223 // Migrate code described by desc.
5224 void CopyFrom(const CodeDesc& desc);
5226 // Returns the object size for a given body (used for allocation).
5227 static int SizeFor(int body_size) {
5228 DCHECK_SIZE_TAG_ALIGNED(body_size);
5229 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
5232 // Calculate the size of the code object to report for log events. This takes
5233 // the layout of the code object into account.
5234 int ExecutableSize() {
5235 // Check that the assumptions about the layout of the code object holds.
5236 DCHECK_EQ(static_cast<int>(instruction_start() - address()),
5238 return instruction_size() + Code::kHeaderSize;
5241 // Locating source position.
5242 int SourcePosition(Address pc);
5243 int SourceStatementPosition(Address pc);
5247 // Dispatched behavior.
5248 int CodeSize() { return SizeFor(body_size()); }
5249 inline void CodeIterateBody(ObjectVisitor* v);
5251 template<typename StaticVisitor>
5252 inline void CodeIterateBody(Heap* heap);
5254 DECLARE_PRINTER(Code)
5255 DECLARE_VERIFIER(Code)
5257 void ClearInlineCaches();
5258 void ClearInlineCaches(Kind kind);
5260 BailoutId TranslatePcOffsetToAstId(uint32_t pc_offset);
5261 uint32_t TranslateAstIdToPcOffset(BailoutId ast_id);
5263 #define DECLARE_CODE_AGE_ENUM(X) k##X##CodeAge,
5265 kToBeExecutedOnceCodeAge = -3,
5266 kNotExecutedCodeAge = -2,
5267 kExecutedOnceCodeAge = -1,
5269 CODE_AGE_LIST(DECLARE_CODE_AGE_ENUM)
5271 kFirstCodeAge = kToBeExecutedOnceCodeAge,
5272 kLastCodeAge = kAfterLastCodeAge - 1,
5273 kCodeAgeCount = kAfterLastCodeAge - kFirstCodeAge - 1,
5274 kIsOldCodeAge = kSexagenarianCodeAge,
5275 kPreAgedCodeAge = kIsOldCodeAge - 1
5277 #undef DECLARE_CODE_AGE_ENUM
5279 // Code aging. Indicates how many full GCs this code has survived without
5280 // being entered through the prologue. Used to determine when it is
5281 // relatively safe to flush this code object and replace it with the lazy
5282 // compilation stub.
5283 static void MakeCodeAgeSequenceYoung(byte* sequence, Isolate* isolate);
5284 static void MarkCodeAsExecuted(byte* sequence, Isolate* isolate);
5285 void MakeYoung(Isolate* isolate);
5286 void MarkToBeExecutedOnce(Isolate* isolate);
5287 void MakeOlder(MarkingParity);
5288 static bool IsYoungSequence(Isolate* isolate, byte* sequence);
5291 static inline Code* GetPreAgedCodeAgeStub(Isolate* isolate) {
5292 return GetCodeAgeStub(isolate, kNotExecutedCodeAge, NO_MARKING_PARITY);
5295 void PrintDeoptLocation(FILE* out, Address pc);
5296 bool CanDeoptAt(Address pc);
5299 void VerifyEmbeddedObjectsDependency();
5303 enum VerifyMode { kNoContextSpecificPointers, kNoContextRetainingPointers };
5304 void VerifyEmbeddedObjects(VerifyMode mode = kNoContextRetainingPointers);
5307 inline bool CanContainWeakObjects() {
5308 // is_turbofanned() implies !can_have_weak_objects().
5309 DCHECK(!is_optimized_code() || !is_turbofanned() ||
5310 !can_have_weak_objects());
5311 return is_optimized_code() && can_have_weak_objects();
5314 inline bool IsWeakObject(Object* object) {
5315 return (CanContainWeakObjects() && IsWeakObjectInOptimizedCode(object));
5318 static inline bool IsWeakObjectInOptimizedCode(Object* object);
5320 static Handle<WeakCell> WeakCellFor(Handle<Code> code);
5321 WeakCell* CachedWeakCell();
5323 // Max loop nesting marker used to postpose OSR. We don't take loop
5324 // nesting that is deeper than 5 levels into account.
5325 static const int kMaxLoopNestingMarker = 6;
5327 static const int kConstantPoolSize =
5328 FLAG_enable_embedded_constant_pool ? kIntSize : 0;
5330 // Layout description.
5331 static const int kRelocationInfoOffset = HeapObject::kHeaderSize;
5332 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
5333 static const int kDeoptimizationDataOffset =
5334 kHandlerTableOffset + kPointerSize;
5335 // For FUNCTION kind, we store the type feedback info here.
5336 static const int kTypeFeedbackInfoOffset =
5337 kDeoptimizationDataOffset + kPointerSize;
5338 static const int kNextCodeLinkOffset = kTypeFeedbackInfoOffset + kPointerSize;
5339 static const int kGCMetadataOffset = kNextCodeLinkOffset + kPointerSize;
5340 static const int kInstructionSizeOffset = kGCMetadataOffset + kPointerSize;
5341 static const int kICAgeOffset = kInstructionSizeOffset + kIntSize;
5342 static const int kFlagsOffset = kICAgeOffset + kIntSize;
5343 static const int kKindSpecificFlags1Offset = kFlagsOffset + kIntSize;
5344 static const int kKindSpecificFlags2Offset =
5345 kKindSpecificFlags1Offset + kIntSize;
5346 // Note: We might be able to squeeze this into the flags above.
5347 static const int kPrologueOffset = kKindSpecificFlags2Offset + kIntSize;
5348 static const int kConstantPoolOffset = kPrologueOffset + kIntSize;
5349 static const int kHeaderPaddingStart =
5350 kConstantPoolOffset + kConstantPoolSize;
5352 // Add padding to align the instruction start following right after
5353 // the Code object header.
5354 static const int kHeaderSize =
5355 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
5357 // Byte offsets within kKindSpecificFlags1Offset.
5358 static const int kFullCodeFlags = kKindSpecificFlags1Offset;
5359 class FullCodeFlagsHasDeoptimizationSupportField:
5360 public BitField<bool, 0, 1> {}; // NOLINT
5361 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
5362 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
5363 class FullCodeFlagsHasRelocInfoForSerialization
5364 : public BitField<bool, 3, 1> {};
5365 class ProfilerTicksField : public BitField<int, 4, 28> {};
5367 // Flags layout. BitField<type, shift, size>.
5368 class ICStateField : public BitField<InlineCacheState, 0, 4> {};
5369 class TypeField : public BitField<StubType, 4, 1> {};
5370 class CacheHolderField : public BitField<CacheHolderFlag, 5, 2> {};
5371 class KindField : public BitField<Kind, 7, 4> {};
5372 class ExtraICStateField: public BitField<ExtraICState, 11,
5373 PlatformSmiTagging::kSmiValueSize - 11 + 1> {}; // NOLINT
5375 // KindSpecificFlags1 layout (STUB and OPTIMIZED_FUNCTION)
5376 static const int kStackSlotsFirstBit = 0;
5377 static const int kStackSlotsBitCount = 24;
5378 static const int kHasFunctionCacheBit =
5379 kStackSlotsFirstBit + kStackSlotsBitCount;
5380 static const int kMarkedForDeoptimizationBit = kHasFunctionCacheBit + 1;
5381 static const int kIsTurbofannedBit = kMarkedForDeoptimizationBit + 1;
5382 static const int kCanHaveWeakObjects = kIsTurbofannedBit + 1;
5384 STATIC_ASSERT(kStackSlotsFirstBit + kStackSlotsBitCount <= 32);
5385 STATIC_ASSERT(kCanHaveWeakObjects + 1 <= 32);
5387 class StackSlotsField: public BitField<int,
5388 kStackSlotsFirstBit, kStackSlotsBitCount> {}; // NOLINT
5389 class HasFunctionCacheField : public BitField<bool, kHasFunctionCacheBit, 1> {
5391 class MarkedForDeoptimizationField
5392 : public BitField<bool, kMarkedForDeoptimizationBit, 1> {}; // NOLINT
5393 class IsTurbofannedField : public BitField<bool, kIsTurbofannedBit, 1> {
5395 class CanHaveWeakObjectsField
5396 : public BitField<bool, kCanHaveWeakObjects, 1> {}; // NOLINT
5398 // KindSpecificFlags2 layout (ALL)
5399 static const int kIsCrankshaftedBit = 0;
5400 class IsCrankshaftedField: public BitField<bool,
5401 kIsCrankshaftedBit, 1> {}; // NOLINT
5403 // KindSpecificFlags2 layout (STUB and OPTIMIZED_FUNCTION)
5404 static const int kSafepointTableOffsetFirstBit = kIsCrankshaftedBit + 1;
5405 static const int kSafepointTableOffsetBitCount = 24;
5407 STATIC_ASSERT(kSafepointTableOffsetFirstBit +
5408 kSafepointTableOffsetBitCount <= 32);
5409 STATIC_ASSERT(1 + kSafepointTableOffsetBitCount <= 32);
5411 class SafepointTableOffsetField: public BitField<int,
5412 kSafepointTableOffsetFirstBit,
5413 kSafepointTableOffsetBitCount> {}; // NOLINT
5415 // KindSpecificFlags2 layout (FUNCTION)
5416 class BackEdgeTableOffsetField: public BitField<int,
5417 kIsCrankshaftedBit + 1, 27> {}; // NOLINT
5418 class AllowOSRAtLoopNestingLevelField: public BitField<int,
5419 kIsCrankshaftedBit + 1 + 27, 4> {}; // NOLINT
5420 STATIC_ASSERT(AllowOSRAtLoopNestingLevelField::kMax >= kMaxLoopNestingMarker);
5422 static const int kArgumentsBits = 16;
5423 static const int kMaxArguments = (1 << kArgumentsBits) - 1;
5425 // This constant should be encodable in an ARM instruction.
5426 static const int kFlagsNotUsedInLookup =
5427 TypeField::kMask | CacheHolderField::kMask;
5430 friend class RelocIterator;
5431 friend class Deoptimizer; // For FindCodeAgeSequence.
5433 void ClearInlineCaches(Kind* kind);
5436 byte* FindCodeAgeSequence();
5437 static void GetCodeAgeAndParity(Code* code, Age* age,
5438 MarkingParity* parity);
5439 static void GetCodeAgeAndParity(Isolate* isolate, byte* sequence, Age* age,
5440 MarkingParity* parity);
5441 static Code* GetCodeAgeStub(Isolate* isolate, Age age, MarkingParity parity);
5443 // Code aging -- platform-specific
5444 static void PatchPlatformCodeAge(Isolate* isolate,
5445 byte* sequence, Age age,
5446 MarkingParity parity);
5448 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
5452 // This class describes the layout of dependent codes array of a map. The
5453 // array is partitioned into several groups of dependent codes. Each group
5454 // contains codes with the same dependency on the map. The array has the
5455 // following layout for n dependency groups:
5457 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5458 // | C1 | C2 | ... | Cn | group 1 | group 2 | ... | group n | undefined |
5459 // +----+----+-----+----+---------+----------+-----+---------+-----------+
5461 // The first n elements are Smis, each of them specifies the number of codes
5462 // in the corresponding group. The subsequent elements contain grouped code
5463 // objects in weak cells. The suffix of the array can be filled with the
5464 // undefined value if the number of codes is less than the length of the
5465 // array. The order of the code objects within a group is not preserved.
5467 // All code indexes used in the class are counted starting from the first
5468 // code object of the first group. In other words, code index 0 corresponds
5469 // to array index n = kCodesStartIndex.
5471 class DependentCode: public FixedArray {
5473 enum DependencyGroup {
5474 // Group of code that weakly embed this map and depend on being
5475 // deoptimized when the map is garbage collected.
5477 // Group of code that embed a transition to this map, and depend on being
5478 // deoptimized when the transition is replaced by a new version.
5480 // Group of code that omit run-time prototype checks for prototypes
5481 // described by this map. The group is deoptimized whenever an object
5482 // described by this map changes shape (and transitions to a new map),
5483 // possibly invalidating the assumptions embedded in the code.
5484 kPrototypeCheckGroup,
5485 // Group of code that depends on global property values in property cells
5486 // not being changed.
5487 kPropertyCellChangedGroup,
5488 // Group of code that omit run-time type checks for the field(s) introduced
5491 // Group of code that omit run-time type checks for initial maps of
5493 kInitialMapChangedGroup,
5494 // Group of code that depends on tenuring information in AllocationSites
5495 // not being changed.
5496 kAllocationSiteTenuringChangedGroup,
5497 // Group of code that depends on element transition information in
5498 // AllocationSites not being changed.
5499 kAllocationSiteTransitionChangedGroup
5502 static const int kGroupCount = kAllocationSiteTransitionChangedGroup + 1;
5504 // Array for holding the index of the first code object of each group.
5505 // The last element stores the total number of code objects.
5506 class GroupStartIndexes {
5508 explicit GroupStartIndexes(DependentCode* entries);
5509 void Recompute(DependentCode* entries);
5510 int at(int i) { return start_indexes_[i]; }
5511 int number_of_entries() { return start_indexes_[kGroupCount]; }
5513 int start_indexes_[kGroupCount + 1];
5516 bool Contains(DependencyGroup group, WeakCell* code_cell);
5518 static Handle<DependentCode> InsertCompilationDependencies(
5519 Handle<DependentCode> entries, DependencyGroup group,
5520 Handle<Foreign> info);
5522 static Handle<DependentCode> InsertWeakCode(Handle<DependentCode> entries,
5523 DependencyGroup group,
5524 Handle<WeakCell> code_cell);
5526 void UpdateToFinishedCode(DependencyGroup group, Foreign* info,
5527 WeakCell* code_cell);
5529 void RemoveCompilationDependencies(DependentCode::DependencyGroup group,
5532 void DeoptimizeDependentCodeGroup(Isolate* isolate,
5533 DependentCode::DependencyGroup group);
5535 bool MarkCodeForDeoptimization(Isolate* isolate,
5536 DependentCode::DependencyGroup group);
5538 // The following low-level accessors should only be used by this class
5539 // and the mark compact collector.
5540 inline int number_of_entries(DependencyGroup group);
5541 inline void set_number_of_entries(DependencyGroup group, int value);
5542 inline Object* object_at(int i);
5543 inline void set_object_at(int i, Object* object);
5544 inline void clear_at(int i);
5545 inline void copy(int from, int to);
5546 DECLARE_CAST(DependentCode)
5548 static const char* DependencyGroupName(DependencyGroup group);
5549 static void SetMarkedForDeoptimization(Code* code, DependencyGroup group);
5552 static Handle<DependentCode> Insert(Handle<DependentCode> entries,
5553 DependencyGroup group,
5554 Handle<Object> object);
5555 static Handle<DependentCode> EnsureSpace(Handle<DependentCode> entries);
5556 // Make a room at the end of the given group by moving out the first
5557 // code objects of the subsequent groups.
5558 inline void ExtendGroup(DependencyGroup group);
5559 // Compact by removing cleared weak cells and return true if there was
5560 // any cleared weak cell.
5562 static int Grow(int number_of_entries) {
5563 if (number_of_entries < 5) return number_of_entries + 1;
5564 return number_of_entries * 5 / 4;
5566 static const int kCodesStartIndex = kGroupCount;
5570 class PrototypeInfo;
5573 // All heap objects have a Map that describes their structure.
5574 // A Map contains information about:
5575 // - Size information about the object
5576 // - How to iterate over an object (for garbage collection)
5577 class Map: public HeapObject {
5580 // Size in bytes or kVariableSizeSentinel if instances do not have
5582 inline int instance_size();
5583 inline void set_instance_size(int value);
5585 // Only to clear an unused byte, remove once byte is used.
5586 inline void clear_unused();
5588 // Count of properties allocated in the object.
5589 inline int inobject_properties();
5590 inline void set_inobject_properties(int value);
5593 inline InstanceType instance_type();
5594 inline void set_instance_type(InstanceType value);
5596 // Tells how many unused property fields are available in the
5597 // instance (only used for JSObject in fast mode).
5598 inline int unused_property_fields();
5599 inline void set_unused_property_fields(int value);
5602 inline byte bit_field() const;
5603 inline void set_bit_field(byte value);
5606 inline byte bit_field2() const;
5607 inline void set_bit_field2(byte value);
5610 inline uint32_t bit_field3() const;
5611 inline void set_bit_field3(uint32_t bits);
5613 class EnumLengthBits: public BitField<int,
5614 0, kDescriptorIndexBitCount> {}; // NOLINT
5615 class NumberOfOwnDescriptorsBits: public BitField<int,
5616 kDescriptorIndexBitCount, kDescriptorIndexBitCount> {}; // NOLINT
5617 STATIC_ASSERT(kDescriptorIndexBitCount + kDescriptorIndexBitCount == 20);
5618 class DictionaryMap : public BitField<bool, 20, 1> {};
5619 class OwnsDescriptors : public BitField<bool, 21, 1> {};
5620 class HasInstanceCallHandler : public BitField<bool, 22, 1> {};
5621 class Deprecated : public BitField<bool, 23, 1> {};
5622 class IsUnstable : public BitField<bool, 24, 1> {};
5623 class IsMigrationTarget : public BitField<bool, 25, 1> {};
5624 class IsStrong : public BitField<bool, 26, 1> {};
5627 // Keep this bit field at the very end for better code in
5628 // Builtins::kJSConstructStubGeneric stub.
5629 // This counter is used for in-object slack tracking and for map aging.
5630 // The in-object slack tracking is considered enabled when the counter is
5631 // in the range [kSlackTrackingCounterStart, kSlackTrackingCounterEnd].
5632 class Counter : public BitField<int, 28, 4> {};
5633 static const int kSlackTrackingCounterStart = 14;
5634 static const int kSlackTrackingCounterEnd = 8;
5635 static const int kRetainingCounterStart = kSlackTrackingCounterEnd - 1;
5636 static const int kRetainingCounterEnd = 0;
5638 // Tells whether the object in the prototype property will be used
5639 // for instances created from this function. If the prototype
5640 // property is set to a value that is not a JSObject, the prototype
5641 // property will not be used to create instances of the function.
5642 // See ECMA-262, 13.2.2.
5643 inline void set_non_instance_prototype(bool value);
5644 inline bool has_non_instance_prototype();
5646 // Tells whether function has special prototype property. If not, prototype
5647 // property will not be created when accessed (will return undefined),
5648 // and construction from this function will not be allowed.
5649 inline void set_function_with_prototype(bool value);
5650 inline bool function_with_prototype();
5652 // Tells whether the instance with this map should be ignored by the
5653 // Object.getPrototypeOf() function and the __proto__ accessor.
5654 inline void set_is_hidden_prototype() {
5655 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
5658 inline bool is_hidden_prototype() {
5659 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
5662 // Records and queries whether the instance has a named interceptor.
5663 inline void set_has_named_interceptor() {
5664 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
5667 inline bool has_named_interceptor() {
5668 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
5671 // Records and queries whether the instance has an indexed interceptor.
5672 inline void set_has_indexed_interceptor() {
5673 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
5676 inline bool has_indexed_interceptor() {
5677 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
5680 // Tells whether the instance is undetectable.
5681 // An undetectable object is a special class of JSObject: 'typeof' operator
5682 // returns undefined, ToBoolean returns false. Otherwise it behaves like
5683 // a normal JS object. It is useful for implementing undetectable
5684 // document.all in Firefox & Safari.
5685 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
5686 inline void set_is_undetectable() {
5687 set_bit_field(bit_field() | (1 << kIsUndetectable));
5690 inline bool is_undetectable() {
5691 return ((1 << kIsUndetectable) & bit_field()) != 0;
5694 // Tells whether the instance has a call-as-function handler.
5695 inline void set_is_observed() {
5696 set_bit_field(bit_field() | (1 << kIsObserved));
5699 inline bool is_observed() {
5700 return ((1 << kIsObserved) & bit_field()) != 0;
5703 inline void set_is_strong();
5704 inline bool is_strong();
5705 inline void set_is_extensible(bool value);
5706 inline bool is_extensible();
5707 inline void set_is_prototype_map(bool value);
5708 inline bool is_prototype_map() const;
5710 inline void set_elements_kind(ElementsKind elements_kind) {
5711 DCHECK(static_cast<int>(elements_kind) < kElementsKindCount);
5712 DCHECK(kElementsKindCount <= (1 << Map::ElementsKindBits::kSize));
5713 set_bit_field2(Map::ElementsKindBits::update(bit_field2(), elements_kind));
5714 DCHECK(this->elements_kind() == elements_kind);
5717 inline ElementsKind elements_kind() {
5718 return Map::ElementsKindBits::decode(bit_field2());
5721 // Tells whether the instance has fast elements that are only Smis.
5722 inline bool has_fast_smi_elements() {
5723 return IsFastSmiElementsKind(elements_kind());
5726 // Tells whether the instance has fast elements.
5727 inline bool has_fast_object_elements() {
5728 return IsFastObjectElementsKind(elements_kind());
5731 inline bool has_fast_smi_or_object_elements() {
5732 return IsFastSmiOrObjectElementsKind(elements_kind());
5735 inline bool has_fast_double_elements() {
5736 return IsFastDoubleElementsKind(elements_kind());
5739 inline bool has_fast_elements() {
5740 return IsFastElementsKind(elements_kind());
5743 inline bool has_sloppy_arguments_elements() {
5744 return IsSloppyArgumentsElements(elements_kind());
5747 inline bool has_external_array_elements() {
5748 return IsExternalArrayElementsKind(elements_kind());
5751 inline bool has_fixed_typed_array_elements() {
5752 return IsFixedTypedArrayElementsKind(elements_kind());
5755 inline bool has_dictionary_elements() {
5756 return IsDictionaryElementsKind(elements_kind());
5759 static bool IsValidElementsTransition(ElementsKind from_kind,
5760 ElementsKind to_kind);
5762 // Returns true if the current map doesn't have DICTIONARY_ELEMENTS but if a
5763 // map with DICTIONARY_ELEMENTS was found in the prototype chain.
5764 bool DictionaryElementsInPrototypeChainOnly();
5766 inline Map* ElementsTransitionMap();
5768 inline FixedArrayBase* GetInitialElements();
5770 // [raw_transitions]: Provides access to the transitions storage field.
5771 // Don't call set_raw_transitions() directly to overwrite transitions, use
5772 // the TransitionArray::ReplaceTransitions() wrapper instead!
5773 DECL_ACCESSORS(raw_transitions, Object)
5774 // [prototype_info]: Per-prototype metadata. Aliased with transitions
5775 // (which prototype maps don't have).
5776 DECL_ACCESSORS(prototype_info, Object)
5777 // PrototypeInfo is created lazily using this helper (which installs it on
5778 // the given prototype's map).
5779 static Handle<PrototypeInfo> GetOrCreatePrototypeInfo(
5780 Handle<JSObject> prototype, Isolate* isolate);
5782 // [prototype chain validity cell]: Associated with a prototype object,
5783 // stored in that object's map's PrototypeInfo, indicates that prototype
5784 // chains through this object are currently valid. The cell will be
5785 // invalidated and replaced when the prototype chain changes.
5786 static Handle<Cell> GetOrCreatePrototypeChainValidityCell(Handle<Map> map,
5788 static const int kPrototypeChainValid = 0;
5789 static const int kPrototypeChainInvalid = 1;
5792 Map* FindFieldOwner(int descriptor);
5794 inline int GetInObjectPropertyOffset(int index);
5796 int NumberOfFields();
5798 // TODO(ishell): candidate with JSObject::MigrateToMap().
5799 bool InstancesNeedRewriting(Map* target, int target_number_of_fields,
5800 int target_inobject, int target_unused,
5801 int* old_number_of_fields);
5802 // TODO(ishell): moveit!
5803 static Handle<Map> GeneralizeAllFieldRepresentations(Handle<Map> map);
5804 MUST_USE_RESULT static Handle<HeapType> GeneralizeFieldType(
5805 Handle<HeapType> type1,
5806 Handle<HeapType> type2,
5808 static void GeneralizeFieldType(Handle<Map> map, int modify_index,
5809 Representation new_representation,
5810 Handle<HeapType> new_field_type);
5811 static Handle<Map> ReconfigureProperty(Handle<Map> map, int modify_index,
5812 PropertyKind new_kind,
5813 PropertyAttributes new_attributes,
5814 Representation new_representation,
5815 Handle<HeapType> new_field_type,
5816 StoreMode store_mode);
5817 static Handle<Map> CopyGeneralizeAllRepresentations(
5818 Handle<Map> map, int modify_index, StoreMode store_mode,
5819 PropertyKind kind, PropertyAttributes attributes, const char* reason);
5821 static Handle<Map> PrepareForDataProperty(Handle<Map> old_map,
5822 int descriptor_number,
5823 Handle<Object> value);
5825 static Handle<Map> Normalize(Handle<Map> map, PropertyNormalizationMode mode,
5826 const char* reason);
5828 // Returns the constructor name (the name (possibly, inferred name) of the
5829 // function that was used to instantiate the object).
5830 String* constructor_name();
5832 // Tells whether the map is used for JSObjects in dictionary mode (ie
5833 // normalized objects, ie objects for which HasFastProperties returns false).
5834 // A map can never be used for both dictionary mode and fast mode JSObjects.
5835 // False by default and for HeapObjects that are not JSObjects.
5836 inline void set_dictionary_map(bool value);
5837 inline bool is_dictionary_map();
5839 // Tells whether the instance needs security checks when accessing its
5841 inline void set_is_access_check_needed(bool access_check_needed);
5842 inline bool is_access_check_needed();
5844 // Returns true if map has a non-empty stub code cache.
5845 inline bool has_code_cache();
5847 // [prototype]: implicit prototype object.
5848 DECL_ACCESSORS(prototype, Object)
5849 // TODO(jkummerow): make set_prototype private.
5850 static void SetPrototype(
5851 Handle<Map> map, Handle<Object> prototype,
5852 PrototypeOptimizationMode proto_mode = FAST_PROTOTYPE);
5854 // [constructor]: points back to the function responsible for this map.
5855 // The field overlaps with the back pointer. All maps in a transition tree
5856 // have the same constructor, so maps with back pointers can walk the
5857 // back pointer chain until they find the map holding their constructor.
5858 DECL_ACCESSORS(constructor_or_backpointer, Object)
5859 inline Object* GetConstructor() const;
5860 inline void SetConstructor(Object* constructor,
5861 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5862 // [back pointer]: points back to the parent map from which a transition
5863 // leads to this map. The field overlaps with the constructor (see above).
5864 inline Object* GetBackPointer();
5865 inline void SetBackPointer(Object* value,
5866 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
5868 // [instance descriptors]: describes the object.
5869 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
5871 // [layout descriptor]: describes the object layout.
5872 DECL_ACCESSORS(layout_descriptor, LayoutDescriptor)
5873 // |layout descriptor| accessor which can be used from GC.
5874 inline LayoutDescriptor* layout_descriptor_gc_safe();
5875 inline bool HasFastPointerLayout() const;
5877 // |layout descriptor| accessor that is safe to call even when
5878 // FLAG_unbox_double_fields is disabled (in this case Map does not contain
5879 // |layout_descriptor| field at all).
5880 inline LayoutDescriptor* GetLayoutDescriptor();
5882 inline void UpdateDescriptors(DescriptorArray* descriptors,
5883 LayoutDescriptor* layout_descriptor);
5884 inline void InitializeDescriptors(DescriptorArray* descriptors,
5885 LayoutDescriptor* layout_descriptor);
5887 // [stub cache]: contains stubs compiled for this map.
5888 DECL_ACCESSORS(code_cache, Object)
5890 // [dependent code]: list of optimized codes that weakly embed this map.
5891 DECL_ACCESSORS(dependent_code, DependentCode)
5893 // [weak cell cache]: cache that stores a weak cell pointing to this map.
5894 DECL_ACCESSORS(weak_cell_cache, Object)
5896 inline PropertyDetails GetLastDescriptorDetails();
5899 int number_of_own_descriptors = NumberOfOwnDescriptors();
5900 DCHECK(number_of_own_descriptors > 0);
5901 return number_of_own_descriptors - 1;
5904 int NumberOfOwnDescriptors() {
5905 return NumberOfOwnDescriptorsBits::decode(bit_field3());
5908 void SetNumberOfOwnDescriptors(int number) {
5909 DCHECK(number <= instance_descriptors()->number_of_descriptors());
5910 set_bit_field3(NumberOfOwnDescriptorsBits::update(bit_field3(), number));
5913 inline Cell* RetrieveDescriptorsPointer();
5916 return EnumLengthBits::decode(bit_field3());
5919 void SetEnumLength(int length) {
5920 if (length != kInvalidEnumCacheSentinel) {
5921 DCHECK(length >= 0);
5922 DCHECK(length == 0 || instance_descriptors()->HasEnumCache());
5923 DCHECK(length <= NumberOfOwnDescriptors());
5925 set_bit_field3(EnumLengthBits::update(bit_field3(), length));
5928 inline bool owns_descriptors();
5929 inline void set_owns_descriptors(bool owns_descriptors);
5930 inline bool has_instance_call_handler();
5931 inline void set_has_instance_call_handler();
5932 inline void mark_unstable();
5933 inline bool is_stable();
5934 inline void set_migration_target(bool value);
5935 inline bool is_migration_target();
5936 inline void set_counter(int value);
5937 inline int counter();
5938 inline void deprecate();
5939 inline bool is_deprecated();
5940 inline bool CanBeDeprecated();
5941 // Returns a non-deprecated version of the input. If the input was not
5942 // deprecated, it is directly returned. Otherwise, the non-deprecated version
5943 // is found by re-transitioning from the root of the transition tree using the
5944 // descriptor array of the map. Returns MaybeHandle<Map>() if no updated map
5946 static MaybeHandle<Map> TryUpdate(Handle<Map> map) WARN_UNUSED_RESULT;
5948 // Returns a non-deprecated version of the input. This method may deprecate
5949 // existing maps along the way if encodings conflict. Not for use while
5950 // gathering type feedback. Use TryUpdate in those cases instead.
5951 static Handle<Map> Update(Handle<Map> map);
5953 static Handle<Map> CopyDropDescriptors(Handle<Map> map);
5954 static Handle<Map> CopyInsertDescriptor(Handle<Map> map,
5955 Descriptor* descriptor,
5956 TransitionFlag flag);
5958 MUST_USE_RESULT static MaybeHandle<Map> CopyWithField(
5961 Handle<HeapType> type,
5962 PropertyAttributes attributes,
5963 Representation representation,
5964 TransitionFlag flag);
5966 MUST_USE_RESULT static MaybeHandle<Map> CopyWithConstant(
5969 Handle<Object> constant,
5970 PropertyAttributes attributes,
5971 TransitionFlag flag);
5973 // Returns a new map with all transitions dropped from the given map and
5974 // the ElementsKind set.
5975 static Handle<Map> TransitionElementsTo(Handle<Map> map,
5976 ElementsKind to_kind);
5978 static Handle<Map> AsElementsKind(Handle<Map> map, ElementsKind kind);
5980 static Handle<Map> CopyAsElementsKind(Handle<Map> map,
5982 TransitionFlag flag);
5984 static Handle<Map> CopyForObserved(Handle<Map> map);
5986 static Handle<Map> CopyForPreventExtensions(Handle<Map> map,
5987 PropertyAttributes attrs_to_add,
5988 Handle<Symbol> transition_marker,
5989 const char* reason);
5991 static Handle<Map> FixProxy(Handle<Map> map, InstanceType type, int size);
5994 // Maximal number of fast properties. Used to restrict the number of map
5995 // transitions to avoid an explosion in the number of maps for objects used as
5997 inline bool TooManyFastProperties(StoreFromKeyed store_mode);
5998 static Handle<Map> TransitionToDataProperty(Handle<Map> map,
6000 Handle<Object> value,
6001 PropertyAttributes attributes,
6002 StoreFromKeyed store_mode);
6003 static Handle<Map> TransitionToAccessorProperty(
6004 Handle<Map> map, Handle<Name> name, AccessorComponent component,
6005 Handle<Object> accessor, PropertyAttributes attributes);
6006 static Handle<Map> ReconfigureExistingProperty(Handle<Map> map,
6009 PropertyAttributes attributes);
6011 inline void AppendDescriptor(Descriptor* desc);
6013 // Returns a copy of the map, prepared for inserting into the transition
6014 // tree (if the |map| owns descriptors then the new one will share
6015 // descriptors with |map|).
6016 static Handle<Map> CopyForTransition(Handle<Map> map, const char* reason);
6018 // Returns a copy of the map, with all transitions dropped from the
6019 // instance descriptors.
6020 static Handle<Map> Copy(Handle<Map> map, const char* reason);
6021 static Handle<Map> Create(Isolate* isolate, int inobject_properties);
6023 // Returns the next free property index (only valid for FAST MODE).
6024 int NextFreePropertyIndex();
6026 // Returns the number of properties described in instance_descriptors
6027 // filtering out properties with the specified attributes.
6028 int NumberOfDescribedProperties(DescriptorFlag which = OWN_DESCRIPTORS,
6029 PropertyAttributes filter = NONE);
6033 // Code cache operations.
6035 // Clears the code cache.
6036 inline void ClearCodeCache(Heap* heap);
6038 // Update code cache.
6039 static void UpdateCodeCache(Handle<Map> map,
6043 // Extend the descriptor array of the map with the list of descriptors.
6044 // In case of duplicates, the latest descriptor is used.
6045 static void AppendCallbackDescriptors(Handle<Map> map,
6046 Handle<Object> descriptors);
6048 static inline int SlackForArraySize(int old_size, int size_limit);
6050 static void EnsureDescriptorSlack(Handle<Map> map, int slack);
6052 // Returns the found code or undefined if absent.
6053 Object* FindInCodeCache(Name* name, Code::Flags flags);
6055 // Returns the non-negative index of the code object if it is in the
6056 // cache and -1 otherwise.
6057 int IndexInCodeCache(Object* name, Code* code);
6059 // Removes a code object from the code cache at the given index.
6060 void RemoveFromCodeCache(Name* name, Code* code, int index);
6062 // Computes a hash value for this map, to be used in HashTables and such.
6065 // Returns the map that this map transitions to if its elements_kind
6066 // is changed to |elements_kind|, or NULL if no such map is cached yet.
6067 // |safe_to_add_transitions| is set to false if adding transitions is not
6069 Map* LookupElementsTransitionMap(ElementsKind elements_kind);
6071 // Returns the transitioned map for this map with the most generic
6072 // elements_kind that's found in |candidates|, or null handle if no match is
6074 static Handle<Map> FindTransitionedMap(Handle<Map> map,
6075 MapHandleList* candidates);
6077 bool CanTransition() {
6078 // Only JSObject and subtypes have map transitions and back pointers.
6079 STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
6080 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6083 bool IsJSObjectMap() {
6084 return instance_type() >= FIRST_JS_OBJECT_TYPE;
6086 bool IsJSArrayMap() { return instance_type() == JS_ARRAY_TYPE; }
6087 bool IsStringMap() { return instance_type() < FIRST_NONSTRING_TYPE; }
6088 bool IsJSProxyMap() {
6089 InstanceType type = instance_type();
6090 return FIRST_JS_PROXY_TYPE <= type && type <= LAST_JS_PROXY_TYPE;
6092 bool IsJSGlobalProxyMap() {
6093 return instance_type() == JS_GLOBAL_PROXY_TYPE;
6095 bool IsJSGlobalObjectMap() {
6096 return instance_type() == JS_GLOBAL_OBJECT_TYPE;
6098 bool IsGlobalObjectMap() {
6099 const InstanceType type = instance_type();
6100 return type == JS_GLOBAL_OBJECT_TYPE || type == JS_BUILTINS_OBJECT_TYPE;
6103 inline bool CanOmitMapChecks();
6105 static void AddDependentCode(Handle<Map> map,
6106 DependentCode::DependencyGroup group,
6109 bool IsMapInArrayPrototypeChain();
6111 static Handle<WeakCell> WeakCellForMap(Handle<Map> map);
6113 // Dispatched behavior.
6114 DECLARE_PRINTER(Map)
6115 DECLARE_VERIFIER(Map)
6118 void DictionaryMapVerify();
6119 void VerifyOmittedMapChecks();
6122 inline int visitor_id();
6123 inline void set_visitor_id(int visitor_id);
6125 static Handle<Map> TransitionToPrototype(Handle<Map> map,
6126 Handle<Object> prototype,
6127 PrototypeOptimizationMode mode);
6129 static const int kMaxPreAllocatedPropertyFields = 255;
6131 // Layout description.
6132 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
6133 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
6134 static const int kBitField3Offset = kInstanceAttributesOffset + kIntSize;
6135 static const int kPrototypeOffset = kBitField3Offset + kPointerSize;
6136 static const int kConstructorOrBackPointerOffset =
6137 kPrototypeOffset + kPointerSize;
6138 // When there is only one transition, it is stored directly in this field;
6139 // otherwise a transition array is used.
6140 // For prototype maps, this slot is used to store this map's PrototypeInfo
6142 static const int kTransitionsOrPrototypeInfoOffset =
6143 kConstructorOrBackPointerOffset + kPointerSize;
6144 static const int kDescriptorsOffset =
6145 kTransitionsOrPrototypeInfoOffset + kPointerSize;
6146 #if V8_DOUBLE_FIELDS_UNBOXING
6147 static const int kLayoutDecriptorOffset = kDescriptorsOffset + kPointerSize;
6148 static const int kCodeCacheOffset = kLayoutDecriptorOffset + kPointerSize;
6150 static const int kLayoutDecriptorOffset = 1; // Must not be ever accessed.
6151 static const int kCodeCacheOffset = kDescriptorsOffset + kPointerSize;
6153 static const int kDependentCodeOffset = kCodeCacheOffset + kPointerSize;
6154 static const int kWeakCellCacheOffset = kDependentCodeOffset + kPointerSize;
6155 static const int kSize = kWeakCellCacheOffset + kPointerSize;
6157 // Layout of pointer fields. Heap iteration code relies on them
6158 // being continuously allocated.
6159 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
6160 static const int kPointerFieldsEndOffset = kSize;
6162 // Byte offsets within kInstanceSizesOffset.
6163 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
6164 static const int kInObjectPropertiesByte = 1;
6165 static const int kInObjectPropertiesOffset =
6166 kInstanceSizesOffset + kInObjectPropertiesByte;
6167 // Note there is one byte available for use here.
6168 static const int kUnusedByte = 2;
6169 static const int kUnusedOffset = kInstanceSizesOffset + kUnusedByte;
6170 static const int kVisitorIdByte = 3;
6171 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
6173 // Byte offsets within kInstanceAttributesOffset attributes.
6174 #if V8_TARGET_LITTLE_ENDIAN
6175 // Order instance type and bit field together such that they can be loaded
6176 // together as a 16-bit word with instance type in the lower 8 bits regardless
6177 // of endianess. Also provide endian-independent offset to that 16-bit word.
6178 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
6179 static const int kBitFieldOffset = kInstanceAttributesOffset + 1;
6181 static const int kBitFieldOffset = kInstanceAttributesOffset + 0;
6182 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 1;
6184 static const int kInstanceTypeAndBitFieldOffset =
6185 kInstanceAttributesOffset + 0;
6186 static const int kBitField2Offset = kInstanceAttributesOffset + 2;
6187 static const int kUnusedPropertyFieldsByte = 3;
6188 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 3;
6190 STATIC_ASSERT(kInstanceTypeAndBitFieldOffset ==
6191 Internals::kMapInstanceTypeAndBitFieldOffset);
6193 // Bit positions for bit field.
6194 static const int kHasNonInstancePrototype = 0;
6195 static const int kIsHiddenPrototype = 1;
6196 static const int kHasNamedInterceptor = 2;
6197 static const int kHasIndexedInterceptor = 3;
6198 static const int kIsUndetectable = 4;
6199 static const int kIsObserved = 5;
6200 static const int kIsAccessCheckNeeded = 6;
6201 class FunctionWithPrototype: public BitField<bool, 7, 1> {};
6203 // Bit positions for bit field 2
6204 static const int kIsExtensible = 0;
6205 static const int kStringWrapperSafeForDefaultValueOf = 1;
6206 class IsPrototypeMapBits : public BitField<bool, 2, 1> {};
6207 class ElementsKindBits: public BitField<ElementsKind, 3, 5> {};
6209 // Derived values from bit field 2
6210 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
6211 (FAST_ELEMENTS + 1) << Map::ElementsKindBits::kShift) - 1;
6212 static const int8_t kMaximumBitField2FastSmiElementValue =
6213 static_cast<int8_t>((FAST_SMI_ELEMENTS + 1) <<
6214 Map::ElementsKindBits::kShift) - 1;
6215 static const int8_t kMaximumBitField2FastHoleyElementValue =
6216 static_cast<int8_t>((FAST_HOLEY_ELEMENTS + 1) <<
6217 Map::ElementsKindBits::kShift) - 1;
6218 static const int8_t kMaximumBitField2FastHoleySmiElementValue =
6219 static_cast<int8_t>((FAST_HOLEY_SMI_ELEMENTS + 1) <<
6220 Map::ElementsKindBits::kShift) - 1;
6222 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
6223 kPointerFieldsEndOffset,
6224 kSize> BodyDescriptor;
6226 // Compares this map to another to see if they describe equivalent objects.
6227 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
6228 // it had exactly zero inobject properties.
6229 // The "shared" flags of both this map and |other| are ignored.
6230 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
6232 // Returns true if given field is unboxed double.
6233 inline bool IsUnboxedDoubleField(FieldIndex index);
6236 static void TraceTransition(const char* what, Map* from, Map* to, Name* name);
6237 static void TraceAllTransitions(Map* map);
6240 static inline Handle<Map> CopyInstallDescriptorsForTesting(
6241 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6242 Handle<LayoutDescriptor> layout_descriptor);
6245 static void ConnectTransition(Handle<Map> parent, Handle<Map> child,
6246 Handle<Name> name, SimpleTransitionFlag flag);
6248 bool EquivalentToForTransition(Map* other);
6249 static Handle<Map> RawCopy(Handle<Map> map, int instance_size);
6250 static Handle<Map> ShareDescriptor(Handle<Map> map,
6251 Handle<DescriptorArray> descriptors,
6252 Descriptor* descriptor);
6253 static Handle<Map> CopyInstallDescriptors(
6254 Handle<Map> map, int new_descriptor, Handle<DescriptorArray> descriptors,
6255 Handle<LayoutDescriptor> layout_descriptor);
6256 static Handle<Map> CopyAddDescriptor(Handle<Map> map,
6257 Descriptor* descriptor,
6258 TransitionFlag flag);
6259 static Handle<Map> CopyReplaceDescriptors(
6260 Handle<Map> map, Handle<DescriptorArray> descriptors,
6261 Handle<LayoutDescriptor> layout_descriptor, TransitionFlag flag,
6262 MaybeHandle<Name> maybe_name, const char* reason,
6263 SimpleTransitionFlag simple_flag);
6265 static Handle<Map> CopyReplaceDescriptor(Handle<Map> map,
6266 Handle<DescriptorArray> descriptors,
6267 Descriptor* descriptor,
6269 TransitionFlag flag);
6270 static MUST_USE_RESULT MaybeHandle<Map> TryReconfigureExistingProperty(
6271 Handle<Map> map, int descriptor, PropertyKind kind,
6272 PropertyAttributes attributes, const char** reason);
6274 static Handle<Map> CopyNormalized(Handle<Map> map,
6275 PropertyNormalizationMode mode);
6277 // Fires when the layout of an object with a leaf map changes.
6278 // This includes adding transitions to the leaf map or changing
6279 // the descriptor array.
6280 inline void NotifyLeafMapLayoutChange();
6282 void DeprecateTransitionTree();
6283 bool DeprecateTarget(PropertyKind kind, Name* key,
6284 PropertyAttributes attributes,
6285 DescriptorArray* new_descriptors,
6286 LayoutDescriptor* new_layout_descriptor);
6288 Map* FindLastMatchMap(int verbatim, int length, DescriptorArray* descriptors);
6290 // Update field type of the given descriptor to new representation and new
6291 // type. The type must be prepared for storing in descriptor array:
6292 // it must be either a simple type or a map wrapped in a weak cell.
6293 void UpdateFieldType(int descriptor_number, Handle<Name> name,
6294 Representation new_representation,
6295 Handle<Object> new_wrapped_type);
6297 void PrintReconfiguration(FILE* file, int modify_index, PropertyKind kind,
6298 PropertyAttributes attributes);
6299 void PrintGeneralization(FILE* file,
6304 bool constant_to_field,
6305 Representation old_representation,
6306 Representation new_representation,
6307 HeapType* old_field_type,
6308 HeapType* new_field_type);
6310 static const int kFastPropertiesSoftLimit = 12;
6311 static const int kMaxFastProperties = 128;
6313 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
6317 // An abstract superclass, a marker class really, for simple structure classes.
6318 // It doesn't carry much functionality but allows struct classes to be
6319 // identified in the type system.
6320 class Struct: public HeapObject {
6322 inline void InitializeBody(int object_size);
6323 DECLARE_CAST(Struct)
6327 // A simple one-element struct, useful where smis need to be boxed.
6328 class Box : public Struct {
6330 // [value]: the boxed contents.
6331 DECL_ACCESSORS(value, Object)
6335 // Dispatched behavior.
6336 DECLARE_PRINTER(Box)
6337 DECLARE_VERIFIER(Box)
6339 static const int kValueOffset = HeapObject::kHeaderSize;
6340 static const int kSize = kValueOffset + kPointerSize;
6343 DISALLOW_IMPLICIT_CONSTRUCTORS(Box);
6347 // Container for metadata stored on each prototype map.
6348 class PrototypeInfo : public Struct {
6350 // [prototype_users]: WeakFixedArray containing maps using this prototype,
6351 // or Smi(0) if uninitialized.
6352 DECL_ACCESSORS(prototype_users, Object)
6353 // [validity_cell]: Cell containing the validity bit for prototype chains
6354 // going through this object, or Smi(0) if uninitialized.
6355 DECL_ACCESSORS(validity_cell, Object)
6356 // [constructor_name]: User-friendly name of the original constructor.
6357 DECL_ACCESSORS(constructor_name, Object)
6359 DECLARE_CAST(PrototypeInfo)
6361 // Dispatched behavior.
6362 DECLARE_PRINTER(PrototypeInfo)
6363 DECLARE_VERIFIER(PrototypeInfo)
6365 static const int kPrototypeUsersOffset = HeapObject::kHeaderSize;
6366 static const int kValidityCellOffset = kPrototypeUsersOffset + kPointerSize;
6367 static const int kConstructorNameOffset = kValidityCellOffset + kPointerSize;
6368 static const int kSize = kConstructorNameOffset + kPointerSize;
6371 DISALLOW_IMPLICIT_CONSTRUCTORS(PrototypeInfo);
6375 // Script describes a script which has been added to the VM.
6376 class Script: public Struct {
6385 // Script compilation types.
6386 enum CompilationType {
6387 COMPILATION_TYPE_HOST = 0,
6388 COMPILATION_TYPE_EVAL = 1
6391 // Script compilation state.
6392 enum CompilationState {
6393 COMPILATION_STATE_INITIAL = 0,
6394 COMPILATION_STATE_COMPILED = 1
6397 // [source]: the script source.
6398 DECL_ACCESSORS(source, Object)
6400 // [name]: the script name.
6401 DECL_ACCESSORS(name, Object)
6403 // [id]: the script id.
6404 DECL_ACCESSORS(id, Smi)
6406 // [line_offset]: script line offset in resource from where it was extracted.
6407 DECL_ACCESSORS(line_offset, Smi)
6409 // [column_offset]: script column offset in resource from where it was
6411 DECL_ACCESSORS(column_offset, Smi)
6413 // [context_data]: context data for the context this script was compiled in.
6414 DECL_ACCESSORS(context_data, Object)
6416 // [wrapper]: the wrapper cache. This is either undefined or a WeakCell.
6417 DECL_ACCESSORS(wrapper, HeapObject)
6419 // [type]: the script type.
6420 DECL_ACCESSORS(type, Smi)
6422 // [line_ends]: FixedArray of line ends positions.
6423 DECL_ACCESSORS(line_ends, Object)
6425 // [eval_from_shared]: for eval scripts the shared funcion info for the
6426 // function from which eval was called.
6427 DECL_ACCESSORS(eval_from_shared, Object)
6429 // [eval_from_instructions_offset]: the instruction offset in the code for the
6430 // function from which eval was called where eval was called.
6431 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
6433 // [shared_function_infos]: weak fixed array containing all shared
6434 // function infos created from this script.
6435 DECL_ACCESSORS(shared_function_infos, Object)
6437 // [flags]: Holds an exciting bitfield.
6438 DECL_ACCESSORS(flags, Smi)
6440 // [source_url]: sourceURL from magic comment
6441 DECL_ACCESSORS(source_url, Object)
6443 // [source_url]: sourceMappingURL magic comment
6444 DECL_ACCESSORS(source_mapping_url, Object)
6446 // [compilation_type]: how the the script was compiled. Encoded in the
6448 inline CompilationType compilation_type();
6449 inline void set_compilation_type(CompilationType type);
6451 // [compilation_state]: determines whether the script has already been
6452 // compiled. Encoded in the 'flags' field.
6453 inline CompilationState compilation_state();
6454 inline void set_compilation_state(CompilationState state);
6456 // [origin_options]: optional attributes set by the embedder via ScriptOrigin,
6457 // and used by the embedder to make decisions about the script. V8 just passes
6458 // this through. Encoded in the 'flags' field.
6459 inline v8::ScriptOriginOptions origin_options();
6460 inline void set_origin_options(ScriptOriginOptions origin_options);
6462 DECLARE_CAST(Script)
6464 // If script source is an external string, check that the underlying
6465 // resource is accessible. Otherwise, always return true.
6466 inline bool HasValidSource();
6468 // Convert code position into column number.
6469 static int GetColumnNumber(Handle<Script> script, int code_pos);
6471 // Convert code position into (zero-based) line number.
6472 // The non-handlified version does not allocate, but may be much slower.
6473 static int GetLineNumber(Handle<Script> script, int code_pos);
6474 int GetLineNumber(int code_pos);
6476 static Handle<Object> GetNameOrSourceURL(Handle<Script> script);
6478 // Init line_ends array with code positions of line ends inside script source.
6479 static void InitLineEnds(Handle<Script> script);
6481 // Get the JS object wrapping the given script; create it if none exists.
6482 static Handle<JSObject> GetWrapper(Handle<Script> script);
6484 // Look through the list of existing shared function infos to find one
6485 // that matches the function literal. Return empty handle if not found.
6486 MaybeHandle<SharedFunctionInfo> FindSharedFunctionInfo(FunctionLiteral* fun);
6488 // Dispatched behavior.
6489 DECLARE_PRINTER(Script)
6490 DECLARE_VERIFIER(Script)
6492 static const int kSourceOffset = HeapObject::kHeaderSize;
6493 static const int kNameOffset = kSourceOffset + kPointerSize;
6494 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
6495 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
6496 static const int kContextOffset = kColumnOffsetOffset + kPointerSize;
6497 static const int kWrapperOffset = kContextOffset + kPointerSize;
6498 static const int kTypeOffset = kWrapperOffset + kPointerSize;
6499 static const int kLineEndsOffset = kTypeOffset + kPointerSize;
6500 static const int kIdOffset = kLineEndsOffset + kPointerSize;
6501 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
6502 static const int kEvalFrominstructionsOffsetOffset =
6503 kEvalFromSharedOffset + kPointerSize;
6504 static const int kSharedFunctionInfosOffset =
6505 kEvalFrominstructionsOffsetOffset + kPointerSize;
6506 static const int kFlagsOffset = kSharedFunctionInfosOffset + kPointerSize;
6507 static const int kSourceUrlOffset = kFlagsOffset + kPointerSize;
6508 static const int kSourceMappingUrlOffset = kSourceUrlOffset + kPointerSize;
6509 static const int kSize = kSourceMappingUrlOffset + kPointerSize;
6512 int GetLineNumberWithArray(int code_pos);
6514 // Bit positions in the flags field.
6515 static const int kCompilationTypeBit = 0;
6516 static const int kCompilationStateBit = 1;
6517 static const int kOriginOptionsShift = 2;
6518 static const int kOriginOptionsSize = 3;
6519 static const int kOriginOptionsMask = ((1 << kOriginOptionsSize) - 1)
6520 << kOriginOptionsShift;
6522 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
6526 // List of builtin functions we want to identify to improve code
6529 // Each entry has a name of a global object property holding an object
6530 // optionally followed by ".prototype", a name of a builtin function
6531 // on the object (the one the id is set for), and a label.
6533 // Installation of ids for the selected builtin functions is handled
6534 // by the bootstrapper.
6535 #define FUNCTIONS_WITH_ID_LIST(V) \
6536 V(Array.prototype, indexOf, ArrayIndexOf) \
6537 V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \
6538 V(Array.prototype, push, ArrayPush) \
6539 V(Array.prototype, pop, ArrayPop) \
6540 V(Array.prototype, shift, ArrayShift) \
6541 V(Function.prototype, apply, FunctionApply) \
6542 V(Function.prototype, call, FunctionCall) \
6543 V(String.prototype, charCodeAt, StringCharCodeAt) \
6544 V(String.prototype, charAt, StringCharAt) \
6545 V(String, fromCharCode, StringFromCharCode) \
6546 V(Math, random, MathRandom) \
6547 V(Math, floor, MathFloor) \
6548 V(Math, round, MathRound) \
6549 V(Math, ceil, MathCeil) \
6550 V(Math, abs, MathAbs) \
6551 V(Math, log, MathLog) \
6552 V(Math, exp, MathExp) \
6553 V(Math, sqrt, MathSqrt) \
6554 V(Math, pow, MathPow) \
6555 V(Math, max, MathMax) \
6556 V(Math, min, MathMin) \
6557 V(Math, cos, MathCos) \
6558 V(Math, sin, MathSin) \
6559 V(Math, tan, MathTan) \
6560 V(Math, acos, MathAcos) \
6561 V(Math, asin, MathAsin) \
6562 V(Math, atan, MathAtan) \
6563 V(Math, atan2, MathAtan2) \
6564 V(Math, imul, MathImul) \
6565 V(Math, clz32, MathClz32) \
6566 V(Math, fround, MathFround)
6568 #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \
6569 V(Atomics, load, AtomicsLoad) \
6570 V(Atomics, store, AtomicsStore)
6572 enum BuiltinFunctionId {
6574 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
6576 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6577 ATOMIC_FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
6578 #undef DECLARE_FUNCTION_ID
6579 // Fake id for a special case of Math.pow. Note, it continues the
6580 // list of math functions.
6585 // Result of searching in an optimized code map of a SharedFunctionInfo. Note
6586 // that both {code} and {literals} can be NULL to pass search result status.
6587 struct CodeAndLiterals {
6588 Code* code; // Cached optimized code.
6589 FixedArray* literals; // Cached literals array.
6593 // SharedFunctionInfo describes the JSFunction information that can be
6594 // shared by multiple instances of the function.
6595 class SharedFunctionInfo: public HeapObject {
6597 // [name]: Function name.
6598 DECL_ACCESSORS(name, Object)
6600 // [code]: Function code.
6601 DECL_ACCESSORS(code, Code)
6602 inline void ReplaceCode(Code* code);
6604 // [optimized_code_map]: Map from native context to optimized code
6605 // and a shared literals array or Smi(0) if none.
6606 DECL_ACCESSORS(optimized_code_map, Object)
6608 // Returns entry from optimized code map for specified context and OSR entry.
6609 // Note that {code == nullptr} indicates no matching entry has been found,
6610 // whereas {literals == nullptr} indicates the code is context-independent.
6611 CodeAndLiterals SearchOptimizedCodeMap(Context* native_context,
6612 BailoutId osr_ast_id);
6614 // Clear optimized code map.
6615 void ClearOptimizedCodeMap();
6617 // Removed a specific optimized code object from the optimized code map.
6618 void EvictFromOptimizedCodeMap(Code* optimized_code, const char* reason);
6620 // Trims the optimized code map after entries have been removed.
6621 void TrimOptimizedCodeMap(int shrink_by);
6623 // Add a new entry to the optimized code map for context-independent code.
6624 static void AddSharedCodeToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6627 // Add a new entry to the optimized code map for context-dependent code.
6628 static void AddToOptimizedCodeMap(Handle<SharedFunctionInfo> shared,
6629 Handle<Context> native_context,
6631 Handle<FixedArray> literals,
6632 BailoutId osr_ast_id);
6634 // Set up the link between shared function info and the script. The shared
6635 // function info is added to the list on the script.
6636 static void SetScript(Handle<SharedFunctionInfo> shared,
6637 Handle<Object> script_object);
6639 // Layout description of the optimized code map.
6640 static const int kNextMapIndex = 0;
6641 static const int kSharedCodeIndex = 1;
6642 static const int kEntriesStart = 2;
6643 static const int kContextOffset = 0;
6644 static const int kCachedCodeOffset = 1;
6645 static const int kLiteralsOffset = 2;
6646 static const int kOsrAstIdOffset = 3;
6647 static const int kEntryLength = 4;
6648 static const int kInitialLength = kEntriesStart + kEntryLength;
6650 // [scope_info]: Scope info.
6651 DECL_ACCESSORS(scope_info, ScopeInfo)
6653 // [construct stub]: Code stub for constructing instances of this function.
6654 DECL_ACCESSORS(construct_stub, Code)
6656 // Returns if this function has been compiled to native code yet.
6657 inline bool is_compiled();
6659 // [length]: The function length - usually the number of declared parameters.
6660 // Use up to 2^30 parameters.
6661 inline int length() const;
6662 inline void set_length(int value);
6664 // [internal formal parameter count]: The declared number of parameters.
6665 // For subclass constructors, also includes new.target.
6666 // The size of function's frame is internal_formal_parameter_count + 1.
6667 inline int internal_formal_parameter_count() const;
6668 inline void set_internal_formal_parameter_count(int value);
6670 // Set the formal parameter count so the function code will be
6671 // called without using argument adaptor frames.
6672 inline void DontAdaptArguments();
6674 // [expected_nof_properties]: Expected number of properties for the function.
6675 inline int expected_nof_properties() const;
6676 inline void set_expected_nof_properties(int value);
6678 // [feedback_vector] - accumulates ast node feedback from full-codegen and
6679 // (increasingly) from crankshafted code where sufficient feedback isn't
6681 DECL_ACCESSORS(feedback_vector, TypeFeedbackVector)
6683 // Unconditionally clear the type feedback vector (including vector ICs).
6684 void ClearTypeFeedbackInfo();
6686 // Clear the type feedback vector with a more subtle policy at GC time.
6687 void ClearTypeFeedbackInfoAtGCTime();
6690 // [unique_id] - For --trace-maps purposes, an identifier that's persistent
6691 // even if the GC moves this SharedFunctionInfo.
6692 inline int unique_id() const;
6693 inline void set_unique_id(int value);
6696 // [instance class name]: class name for instances.
6697 DECL_ACCESSORS(instance_class_name, Object)
6699 // [function data]: This field holds some additional data for function.
6700 // Currently it has one of:
6701 // - a FunctionTemplateInfo to make benefit the API [IsApiFunction()].
6702 // - a Smi identifying a builtin function [HasBuiltinFunctionId()].
6703 // - a BytecodeArray for the interpreter [HasBytecodeArray()].
6704 // In the long run we don't want all functions to have this field but
6705 // we can fix that when we have a better model for storing hidden data
6707 DECL_ACCESSORS(function_data, Object)
6709 inline bool IsApiFunction();
6710 inline FunctionTemplateInfo* get_api_func_data();
6711 inline bool HasBuiltinFunctionId();
6712 inline BuiltinFunctionId builtin_function_id();
6713 inline bool HasBytecodeArray();
6714 inline BytecodeArray* bytecode_array();
6716 // [script info]: Script from which the function originates.
6717 DECL_ACCESSORS(script, Object)
6719 // [num_literals]: Number of literals used by this function.
6720 inline int num_literals() const;
6721 inline void set_num_literals(int value);
6723 // [start_position_and_type]: Field used to store both the source code
6724 // position, whether or not the function is a function expression,
6725 // and whether or not the function is a toplevel function. The two
6726 // least significants bit indicates whether the function is an
6727 // expression and the rest contains the source code position.
6728 inline int start_position_and_type() const;
6729 inline void set_start_position_and_type(int value);
6731 // The function is subject to debugging if a debug info is attached.
6732 inline bool HasDebugInfo();
6733 inline DebugInfo* GetDebugInfo();
6735 // A function has debug code if the compiled code has debug break slots.
6736 inline bool HasDebugCode();
6738 // [debug info]: Debug information.
6739 DECL_ACCESSORS(debug_info, Object)
6741 // [inferred name]: Name inferred from variable or property
6742 // assignment of this function. Used to facilitate debugging and
6743 // profiling of JavaScript code written in OO style, where almost
6744 // all functions are anonymous but are assigned to object
6746 DECL_ACCESSORS(inferred_name, String)
6748 // The function's name if it is non-empty, otherwise the inferred name.
6749 String* DebugName();
6751 // Position of the 'function' token in the script source.
6752 inline int function_token_position() const;
6753 inline void set_function_token_position(int function_token_position);
6755 // Position of this function in the script source.
6756 inline int start_position() const;
6757 inline void set_start_position(int start_position);
6759 // End position of this function in the script source.
6760 inline int end_position() const;
6761 inline void set_end_position(int end_position);
6763 // Is this function a function expression in the source code.
6764 DECL_BOOLEAN_ACCESSORS(is_expression)
6766 // Is this function a top-level function (scripts, evals).
6767 DECL_BOOLEAN_ACCESSORS(is_toplevel)
6769 // Bit field containing various information collected by the compiler to
6770 // drive optimization.
6771 inline int compiler_hints() const;
6772 inline void set_compiler_hints(int value);
6774 inline int ast_node_count() const;
6775 inline void set_ast_node_count(int count);
6777 inline int profiler_ticks() const;
6778 inline void set_profiler_ticks(int ticks);
6780 // Inline cache age is used to infer whether the function survived a context
6781 // disposal or not. In the former case we reset the opt_count.
6782 inline int ic_age();
6783 inline void set_ic_age(int age);
6785 // Indicates if this function can be lazy compiled.
6786 // This is used to determine if we can safely flush code from a function
6787 // when doing GC if we expect that the function will no longer be used.
6788 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
6790 // Indicates if this function can be lazy compiled without a context.
6791 // This is used to determine if we can force compilation without reaching
6792 // the function through program execution but through other means (e.g. heap
6793 // iteration by the debugger).
6794 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation_without_context)
6796 // Indicates whether optimizations have been disabled for this
6797 // shared function info. If a function is repeatedly optimized or if
6798 // we cannot optimize the function we disable optimization to avoid
6799 // spending time attempting to optimize it again.
6800 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
6802 // Indicates the language mode.
6803 inline LanguageMode language_mode();
6804 inline void set_language_mode(LanguageMode language_mode);
6806 // False if the function definitely does not allocate an arguments object.
6807 DECL_BOOLEAN_ACCESSORS(uses_arguments)
6809 // Indicates that this function uses a super property (or an eval that may
6810 // use a super property).
6811 // This is needed to set up the [[HomeObject]] on the function instance.
6812 DECL_BOOLEAN_ACCESSORS(needs_home_object)
6814 // True if the function has any duplicated parameter names.
6815 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
6817 // Indicates whether the function is a native function.
6818 // These needs special treatment in .call and .apply since
6819 // null passed as the receiver should not be translated to the
6821 DECL_BOOLEAN_ACCESSORS(native)
6823 // Indicate that this function should always be inlined in optimized code.
6824 DECL_BOOLEAN_ACCESSORS(force_inline)
6826 // Indicates that the function was created by the Function function.
6827 // Though it's anonymous, toString should treat it as if it had the name
6828 // "anonymous". We don't set the name itself so that the system does not
6829 // see a binding for it.
6830 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
6832 // Indicates whether the function is a bound function created using
6833 // the bind function.
6834 DECL_BOOLEAN_ACCESSORS(bound)
6836 // Indicates that the function is anonymous (the name field can be set
6837 // through the API, which does not change this flag).
6838 DECL_BOOLEAN_ACCESSORS(is_anonymous)
6840 // Is this a function or top-level/eval code.
6841 DECL_BOOLEAN_ACCESSORS(is_function)
6843 // Indicates that code for this function cannot be compiled with Crankshaft.
6844 DECL_BOOLEAN_ACCESSORS(dont_crankshaft)
6846 // Indicates that code for this function cannot be flushed.
6847 DECL_BOOLEAN_ACCESSORS(dont_flush)
6849 // Indicates that this function is a generator.
6850 DECL_BOOLEAN_ACCESSORS(is_generator)
6852 // Indicates that this function is an arrow function.
6853 DECL_BOOLEAN_ACCESSORS(is_arrow)
6855 // Indicates that this function is a concise method.
6856 DECL_BOOLEAN_ACCESSORS(is_concise_method)
6858 // Indicates that this function is an accessor (getter or setter).
6859 DECL_BOOLEAN_ACCESSORS(is_accessor_function)
6861 // Indicates that this function is a default constructor.
6862 DECL_BOOLEAN_ACCESSORS(is_default_constructor)
6864 // Indicates that this function is an asm function.
6865 DECL_BOOLEAN_ACCESSORS(asm_function)
6867 // Indicates that the the shared function info is deserialized from cache.
6868 DECL_BOOLEAN_ACCESSORS(deserialized)
6870 // Indicates that the the shared function info has never been compiled before.
6871 DECL_BOOLEAN_ACCESSORS(never_compiled)
6873 inline FunctionKind kind();
6874 inline void set_kind(FunctionKind kind);
6876 // Indicates whether or not the code in the shared function support
6878 inline bool has_deoptimization_support();
6880 // Enable deoptimization support through recompiled code.
6881 void EnableDeoptimizationSupport(Code* recompiled);
6883 // Disable (further) attempted optimization of all functions sharing this
6884 // shared function info.
6885 void DisableOptimization(BailoutReason reason);
6887 inline BailoutReason disable_optimization_reason();
6889 // Lookup the bailout ID and DCHECK that it exists in the non-optimized
6890 // code, returns whether it asserted (i.e., always true if assertions are
6892 bool VerifyBailoutId(BailoutId id);
6894 // [source code]: Source code for the function.
6895 bool HasSourceCode() const;
6896 Handle<Object> GetSourceCode();
6898 // Number of times the function was optimized.
6899 inline int opt_count();
6900 inline void set_opt_count(int opt_count);
6902 // Number of times the function was deoptimized.
6903 inline void set_deopt_count(int value);
6904 inline int deopt_count();
6905 inline void increment_deopt_count();
6907 // Number of time we tried to re-enable optimization after it
6908 // was disabled due to high number of deoptimizations.
6909 inline void set_opt_reenable_tries(int value);
6910 inline int opt_reenable_tries();
6912 inline void TryReenableOptimization();
6914 // Stores deopt_count, opt_reenable_tries and ic_age as bit-fields.
6915 inline void set_counters(int value);
6916 inline int counters() const;
6918 // Stores opt_count and bailout_reason as bit-fields.
6919 inline void set_opt_count_and_bailout_reason(int value);
6920 inline int opt_count_and_bailout_reason() const;
6922 void set_disable_optimization_reason(BailoutReason reason) {
6923 set_opt_count_and_bailout_reason(
6924 DisabledOptimizationReasonBits::update(opt_count_and_bailout_reason(),
6928 // Tells whether this function should be subject to debugging.
6929 inline bool IsSubjectToDebugging();
6931 // Check whether or not this function is inlineable.
6932 bool IsInlineable();
6934 // Source size of this function.
6937 // Calculate the instance size.
6938 int CalculateInstanceSize();
6940 // Calculate the number of in-object properties.
6941 int CalculateInObjectProperties();
6943 inline bool is_simple_parameter_list();
6945 // Initialize a SharedFunctionInfo from a parsed function literal.
6946 static void InitFromFunctionLiteral(Handle<SharedFunctionInfo> shared_info,
6947 FunctionLiteral* lit);
6949 // Dispatched behavior.
6950 DECLARE_PRINTER(SharedFunctionInfo)
6951 DECLARE_VERIFIER(SharedFunctionInfo)
6953 void ResetForNewContext(int new_ic_age);
6955 DECLARE_CAST(SharedFunctionInfo)
6958 static const int kDontAdaptArgumentsSentinel = -1;
6960 // Layout description.
6962 static const int kNameOffset = HeapObject::kHeaderSize;
6963 static const int kCodeOffset = kNameOffset + kPointerSize;
6964 static const int kOptimizedCodeMapOffset = kCodeOffset + kPointerSize;
6965 static const int kScopeInfoOffset = kOptimizedCodeMapOffset + kPointerSize;
6966 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
6967 static const int kInstanceClassNameOffset =
6968 kConstructStubOffset + kPointerSize;
6969 static const int kFunctionDataOffset =
6970 kInstanceClassNameOffset + kPointerSize;
6971 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
6972 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
6973 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
6974 static const int kFeedbackVectorOffset =
6975 kInferredNameOffset + kPointerSize;
6977 static const int kUniqueIdOffset = kFeedbackVectorOffset + kPointerSize;
6978 static const int kLastPointerFieldOffset = kUniqueIdOffset;
6980 // Just to not break the postmortrem support with conditional offsets
6981 static const int kUniqueIdOffset = kFeedbackVectorOffset;
6982 static const int kLastPointerFieldOffset = kFeedbackVectorOffset;
6985 #if V8_HOST_ARCH_32_BIT
6987 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
6988 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
6989 static const int kExpectedNofPropertiesOffset =
6990 kFormalParameterCountOffset + kPointerSize;
6991 static const int kNumLiteralsOffset =
6992 kExpectedNofPropertiesOffset + kPointerSize;
6993 static const int kStartPositionAndTypeOffset =
6994 kNumLiteralsOffset + kPointerSize;
6995 static const int kEndPositionOffset =
6996 kStartPositionAndTypeOffset + kPointerSize;
6997 static const int kFunctionTokenPositionOffset =
6998 kEndPositionOffset + kPointerSize;
6999 static const int kCompilerHintsOffset =
7000 kFunctionTokenPositionOffset + kPointerSize;
7001 static const int kOptCountAndBailoutReasonOffset =
7002 kCompilerHintsOffset + kPointerSize;
7003 static const int kCountersOffset =
7004 kOptCountAndBailoutReasonOffset + kPointerSize;
7005 static const int kAstNodeCountOffset =
7006 kCountersOffset + kPointerSize;
7007 static const int kProfilerTicksOffset =
7008 kAstNodeCountOffset + kPointerSize;
7011 static const int kSize = kProfilerTicksOffset + kPointerSize;
7013 // The only reason to use smi fields instead of int fields
7014 // is to allow iteration without maps decoding during
7015 // garbage collections.
7016 // To avoid wasting space on 64-bit architectures we use
7017 // the following trick: we group integer fields into pairs
7018 // The least significant integer in each pair is shifted left by 1.
7019 // By doing this we guarantee that LSB of each kPointerSize aligned
7020 // word is not set and thus this word cannot be treated as pointer
7021 // to HeapObject during old space traversal.
7022 #if V8_TARGET_LITTLE_ENDIAN
7023 static const int kLengthOffset = kLastPointerFieldOffset + kPointerSize;
7024 static const int kFormalParameterCountOffset =
7025 kLengthOffset + kIntSize;
7027 static const int kExpectedNofPropertiesOffset =
7028 kFormalParameterCountOffset + kIntSize;
7029 static const int kNumLiteralsOffset =
7030 kExpectedNofPropertiesOffset + kIntSize;
7032 static const int kEndPositionOffset =
7033 kNumLiteralsOffset + kIntSize;
7034 static const int kStartPositionAndTypeOffset =
7035 kEndPositionOffset + kIntSize;
7037 static const int kFunctionTokenPositionOffset =
7038 kStartPositionAndTypeOffset + kIntSize;
7039 static const int kCompilerHintsOffset =
7040 kFunctionTokenPositionOffset + kIntSize;
7042 static const int kOptCountAndBailoutReasonOffset =
7043 kCompilerHintsOffset + kIntSize;
7044 static const int kCountersOffset =
7045 kOptCountAndBailoutReasonOffset + kIntSize;
7047 static const int kAstNodeCountOffset =
7048 kCountersOffset + kIntSize;
7049 static const int kProfilerTicksOffset =
7050 kAstNodeCountOffset + kIntSize;
7053 static const int kSize = kProfilerTicksOffset + kIntSize;
7055 #elif V8_TARGET_BIG_ENDIAN
7056 static const int kFormalParameterCountOffset =
7057 kLastPointerFieldOffset + kPointerSize;
7058 static const int kLengthOffset = kFormalParameterCountOffset + kIntSize;
7060 static const int kNumLiteralsOffset = kLengthOffset + kIntSize;
7061 static const int kExpectedNofPropertiesOffset = kNumLiteralsOffset + kIntSize;
7063 static const int kStartPositionAndTypeOffset =
7064 kExpectedNofPropertiesOffset + kIntSize;
7065 static const int kEndPositionOffset = kStartPositionAndTypeOffset + kIntSize;
7067 static const int kCompilerHintsOffset = kEndPositionOffset + kIntSize;
7068 static const int kFunctionTokenPositionOffset =
7069 kCompilerHintsOffset + kIntSize;
7071 static const int kCountersOffset = kFunctionTokenPositionOffset + kIntSize;
7072 static const int kOptCountAndBailoutReasonOffset = kCountersOffset + kIntSize;
7074 static const int kProfilerTicksOffset =
7075 kOptCountAndBailoutReasonOffset + kIntSize;
7076 static const int kAstNodeCountOffset = kProfilerTicksOffset + kIntSize;
7079 static const int kSize = kAstNodeCountOffset + kIntSize;
7082 #error Unknown byte ordering
7083 #endif // Big endian
7087 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
7089 typedef FixedBodyDescriptor<kNameOffset,
7090 kLastPointerFieldOffset + kPointerSize,
7091 kSize> BodyDescriptor;
7093 // Bit positions in start_position_and_type.
7094 // The source code start position is in the 30 most significant bits of
7095 // the start_position_and_type field.
7096 static const int kIsExpressionBit = 0;
7097 static const int kIsTopLevelBit = 1;
7098 static const int kStartPositionShift = 2;
7099 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
7101 // Bit positions in compiler_hints.
7102 enum CompilerHints {
7103 kAllowLazyCompilation,
7104 kAllowLazyCompilationWithoutContext,
7105 kOptimizationDisabled,
7106 kStrictModeFunction,
7107 kStrongModeFunction,
7110 kHasDuplicateParameters,
7115 kNameShouldPrintAsAnonymous,
7122 kIsAccessorFunction,
7123 kIsDefaultConstructor,
7124 kIsSubclassConstructor,
7130 kCompilerHintsCount // Pseudo entry
7132 // Add hints for other modes when they're added.
7133 STATIC_ASSERT(LANGUAGE_END == 3);
7135 class FunctionKindBits : public BitField<FunctionKind, kIsArrow, 8> {};
7137 class DeoptCountBits : public BitField<int, 0, 4> {};
7138 class OptReenableTriesBits : public BitField<int, 4, 18> {};
7139 class ICAgeBits : public BitField<int, 22, 8> {};
7141 class OptCountBits : public BitField<int, 0, 22> {};
7142 class DisabledOptimizationReasonBits : public BitField<int, 22, 8> {};
7145 #if V8_HOST_ARCH_32_BIT
7146 // On 32 bit platforms, compiler hints is a smi.
7147 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
7148 static const int kCompilerHintsSize = kPointerSize;
7150 // On 64 bit platforms, compiler hints is not a smi, see comment above.
7151 static const int kCompilerHintsSmiTagSize = 0;
7152 static const int kCompilerHintsSize = kIntSize;
7155 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
7156 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
7159 // Constants for optimizing codegen for strict mode function and
7161 // Allows to use byte-width instructions.
7162 static const int kStrictModeBitWithinByte =
7163 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7164 static const int kStrongModeBitWithinByte =
7165 (kStrongModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
7167 static const int kNativeBitWithinByte =
7168 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
7170 #if defined(V8_TARGET_LITTLE_ENDIAN)
7171 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7172 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7173 static const int kStrongModeByteOffset =
7174 kCompilerHintsOffset +
7175 (kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
7176 static const int kNativeByteOffset = kCompilerHintsOffset +
7177 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
7178 #elif defined(V8_TARGET_BIG_ENDIAN)
7179 static const int kStrictModeByteOffset = kCompilerHintsOffset +
7180 (kCompilerHintsSize - 1) -
7181 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7182 static const int kStrongModeByteOffset =
7183 kCompilerHintsOffset + (kCompilerHintsSize - 1) -
7184 ((kStrongModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
7185 static const int kNativeByteOffset = kCompilerHintsOffset +
7186 (kCompilerHintsSize - 1) -
7187 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
7189 #error Unknown byte ordering
7193 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
7197 // Printing support.
7198 struct SourceCodeOf {
7199 explicit SourceCodeOf(SharedFunctionInfo* v, int max = -1)
7200 : value(v), max_length(max) {}
7201 const SharedFunctionInfo* value;
7206 std::ostream& operator<<(std::ostream& os, const SourceCodeOf& v);
7209 class JSGeneratorObject: public JSObject {
7211 // [function]: The function corresponding to this generator object.
7212 DECL_ACCESSORS(function, JSFunction)
7214 // [context]: The context of the suspended computation.
7215 DECL_ACCESSORS(context, Context)
7217 // [receiver]: The receiver of the suspended computation.
7218 DECL_ACCESSORS(receiver, Object)
7220 // [continuation]: Offset into code of continuation.
7222 // A positive offset indicates a suspended generator. The special
7223 // kGeneratorExecuting and kGeneratorClosed values indicate that a generator
7224 // cannot be resumed.
7225 inline int continuation() const;
7226 inline void set_continuation(int continuation);
7227 inline bool is_closed();
7228 inline bool is_executing();
7229 inline bool is_suspended();
7231 // [operand_stack]: Saved operand stack.
7232 DECL_ACCESSORS(operand_stack, FixedArray)
7234 DECLARE_CAST(JSGeneratorObject)
7236 // Dispatched behavior.
7237 DECLARE_PRINTER(JSGeneratorObject)
7238 DECLARE_VERIFIER(JSGeneratorObject)
7240 // Magic sentinel values for the continuation.
7241 static const int kGeneratorExecuting = -1;
7242 static const int kGeneratorClosed = 0;
7244 // Layout description.
7245 static const int kFunctionOffset = JSObject::kHeaderSize;
7246 static const int kContextOffset = kFunctionOffset + kPointerSize;
7247 static const int kReceiverOffset = kContextOffset + kPointerSize;
7248 static const int kContinuationOffset = kReceiverOffset + kPointerSize;
7249 static const int kOperandStackOffset = kContinuationOffset + kPointerSize;
7250 static const int kSize = kOperandStackOffset + kPointerSize;
7252 // Resume mode, for use by runtime functions.
7253 enum ResumeMode { NEXT, THROW };
7255 // Yielding from a generator returns an object with the following inobject
7256 // properties. See Context::iterator_result_map() for the map.
7257 static const int kResultValuePropertyIndex = 0;
7258 static const int kResultDonePropertyIndex = 1;
7259 static const int kResultPropertyCount = 2;
7261 static const int kResultValuePropertyOffset = JSObject::kHeaderSize;
7262 static const int kResultDonePropertyOffset =
7263 kResultValuePropertyOffset + kPointerSize;
7264 static const int kResultSize = kResultDonePropertyOffset + kPointerSize;
7267 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGeneratorObject);
7271 // Representation for module instance objects.
7272 class JSModule: public JSObject {
7274 // [context]: the context holding the module's locals, or undefined if none.
7275 DECL_ACCESSORS(context, Object)
7277 // [scope_info]: Scope info.
7278 DECL_ACCESSORS(scope_info, ScopeInfo)
7280 DECLARE_CAST(JSModule)
7282 // Dispatched behavior.
7283 DECLARE_PRINTER(JSModule)
7284 DECLARE_VERIFIER(JSModule)
7286 // Layout description.
7287 static const int kContextOffset = JSObject::kHeaderSize;
7288 static const int kScopeInfoOffset = kContextOffset + kPointerSize;
7289 static const int kSize = kScopeInfoOffset + kPointerSize;
7292 DISALLOW_IMPLICIT_CONSTRUCTORS(JSModule);
7296 // JSFunction describes JavaScript functions.
7297 class JSFunction: public JSObject {
7299 // [prototype_or_initial_map]:
7300 DECL_ACCESSORS(prototype_or_initial_map, Object)
7302 // [shared]: The information about the function that
7303 // can be shared by instances.
7304 DECL_ACCESSORS(shared, SharedFunctionInfo)
7306 // [context]: The context for this function.
7307 inline Context* context();
7308 inline void set_context(Object* context);
7309 inline JSObject* global_proxy();
7311 // [code]: The generated code object for this function. Executed
7312 // when the function is invoked, e.g. foo() or new foo(). See
7313 // [[Call]] and [[Construct]] description in ECMA-262, section
7315 inline Code* code();
7316 inline void set_code(Code* code);
7317 inline void set_code_no_write_barrier(Code* code);
7318 inline void ReplaceCode(Code* code);
7320 // Tells whether this function is builtin.
7321 inline bool IsBuiltin();
7323 // Tells whether this function inlines the given shared function info.
7324 bool Inlines(SharedFunctionInfo* candidate);
7326 // Tells whether this function should be subject to debugging.
7327 inline bool IsSubjectToDebugging();
7329 // Tells whether or not the function needs arguments adaption.
7330 inline bool NeedsArgumentsAdaption();
7332 // Tells whether or not this function has been optimized.
7333 inline bool IsOptimized();
7335 // Mark this function for lazy recompilation. The function will be
7336 // recompiled the next time it is executed.
7337 void MarkForOptimization();
7338 void AttemptConcurrentOptimization();
7340 // Tells whether or not the function is already marked for lazy
7342 inline bool IsMarkedForOptimization();
7343 inline bool IsMarkedForConcurrentOptimization();
7345 // Tells whether or not the function is on the concurrent recompilation queue.
7346 inline bool IsInOptimizationQueue();
7348 // Inobject slack tracking is the way to reclaim unused inobject space.
7350 // The instance size is initially determined by adding some slack to
7351 // expected_nof_properties (to allow for a few extra properties added
7352 // after the constructor). There is no guarantee that the extra space
7353 // will not be wasted.
7355 // Here is the algorithm to reclaim the unused inobject space:
7356 // - Detect the first constructor call for this JSFunction.
7357 // When it happens enter the "in progress" state: initialize construction
7358 // counter in the initial_map.
7359 // - While the tracking is in progress create objects filled with
7360 // one_pointer_filler_map instead of undefined_value. This way they can be
7361 // resized quickly and safely.
7362 // - Once enough objects have been created compute the 'slack'
7363 // (traverse the map transition tree starting from the
7364 // initial_map and find the lowest value of unused_property_fields).
7365 // - Traverse the transition tree again and decrease the instance size
7366 // of every map. Existing objects will resize automatically (they are
7367 // filled with one_pointer_filler_map). All further allocations will
7368 // use the adjusted instance size.
7369 // - SharedFunctionInfo's expected_nof_properties left unmodified since
7370 // allocations made using different closures could actually create different
7371 // kind of objects (see prototype inheritance pattern).
7373 // Important: inobject slack tracking is not attempted during the snapshot
7376 // True if the initial_map is set and the object constructions countdown
7377 // counter is not zero.
7378 static const int kGenerousAllocationCount =
7379 Map::kSlackTrackingCounterStart - Map::kSlackTrackingCounterEnd + 1;
7380 inline bool IsInobjectSlackTrackingInProgress();
7382 // Starts the tracking.
7383 // Initializes object constructions countdown counter in the initial map.
7384 void StartInobjectSlackTracking();
7386 // Completes the tracking.
7387 void CompleteInobjectSlackTracking();
7389 // [literals_or_bindings]: Fixed array holding either
7390 // the materialized literals or the bindings of a bound function.
7392 // If the function contains object, regexp or array literals, the
7393 // literals array prefix contains the object, regexp, and array
7394 // function to be used when creating these literals. This is
7395 // necessary so that we do not dynamically lookup the object, regexp
7396 // or array functions. Performing a dynamic lookup, we might end up
7397 // using the functions from a new context that we should not have
7400 // On bound functions, the array is a (copy-on-write) fixed-array containing
7401 // the function that was bound, bound this-value and any bound
7402 // arguments. Bound functions never contain literals.
7403 DECL_ACCESSORS(literals_or_bindings, FixedArray)
7405 inline FixedArray* literals();
7406 inline void set_literals(FixedArray* literals);
7408 inline FixedArray* function_bindings();
7409 inline void set_function_bindings(FixedArray* bindings);
7411 // The initial map for an object created by this constructor.
7412 inline Map* initial_map();
7413 static void SetInitialMap(Handle<JSFunction> function, Handle<Map> map,
7414 Handle<Object> prototype);
7415 inline bool has_initial_map();
7416 static void EnsureHasInitialMap(Handle<JSFunction> function);
7418 // Get and set the prototype property on a JSFunction. If the
7419 // function has an initial map the prototype is set on the initial
7420 // map. Otherwise, the prototype is put in the initial map field
7421 // until an initial map is needed.
7422 inline bool has_prototype();
7423 inline bool has_instance_prototype();
7424 inline Object* prototype();
7425 inline Object* instance_prototype();
7426 static void SetPrototype(Handle<JSFunction> function,
7427 Handle<Object> value);
7428 static void SetInstancePrototype(Handle<JSFunction> function,
7429 Handle<Object> value);
7431 // Creates a new closure for the fucntion with the same bindings,
7432 // bound values, and prototype. An equivalent of spec operations
7433 // ``CloneMethod`` and ``CloneBoundFunction``.
7434 static Handle<JSFunction> CloneClosure(Handle<JSFunction> function);
7436 // After prototype is removed, it will not be created when accessed, and
7437 // [[Construct]] from this function will not be allowed.
7438 bool RemovePrototype();
7439 inline bool should_have_prototype();
7441 // Accessor for this function's initial map's [[class]]
7442 // property. This is primarily used by ECMA native functions. This
7443 // method sets the class_name field of this function's initial map
7444 // to a given value. It creates an initial map if this function does
7445 // not have one. Note that this method does not copy the initial map
7446 // if it has one already, but simply replaces it with the new value.
7447 // Instances created afterwards will have a map whose [[class]] is
7448 // set to 'value', but there is no guarantees on instances created
7450 void SetInstanceClassName(String* name);
7452 // Returns if this function has been compiled to native code yet.
7453 inline bool is_compiled();
7455 // Returns `false` if formal parameters include rest parameters, optional
7456 // parameters, or destructuring parameters.
7457 // TODO(caitp): make this a flag set during parsing
7458 inline bool is_simple_parameter_list();
7460 // [next_function_link]: Links functions into various lists, e.g. the list
7461 // of optimized functions hanging off the native_context. The CodeFlusher
7462 // uses this link to chain together flushing candidates. Treated weakly
7463 // by the garbage collector.
7464 DECL_ACCESSORS(next_function_link, Object)
7466 // Prints the name of the function using PrintF.
7467 void PrintName(FILE* out = stdout);
7469 DECLARE_CAST(JSFunction)
7471 // Iterates the objects, including code objects indirectly referenced
7472 // through pointers to the first instruction in the code object.
7473 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
7475 // Dispatched behavior.
7476 DECLARE_PRINTER(JSFunction)
7477 DECLARE_VERIFIER(JSFunction)
7479 // Returns the number of allocated literals.
7480 inline int NumberOfLiterals();
7482 // Used for flags such as --hydrogen-filter.
7483 bool PassesFilter(const char* raw_filter);
7485 // The function's name if it is configured, otherwise shared function info
7487 static Handle<String> GetDebugName(Handle<JSFunction> function);
7489 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
7490 // kSize) is weak and has special handling during garbage collection.
7491 static const int kCodeEntryOffset = JSObject::kHeaderSize;
7492 static const int kPrototypeOrInitialMapOffset =
7493 kCodeEntryOffset + kPointerSize;
7494 static const int kSharedFunctionInfoOffset =
7495 kPrototypeOrInitialMapOffset + kPointerSize;
7496 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
7497 static const int kLiteralsOffset = kContextOffset + kPointerSize;
7498 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
7499 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
7500 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
7502 // Layout of the bound-function binding array.
7503 static const int kBoundFunctionIndex = 0;
7504 static const int kBoundThisIndex = 1;
7505 static const int kBoundArgumentsStartIndex = 2;
7508 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
7512 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
7513 // and the prototype is hidden. JSGlobalProxy always delegates
7514 // property accesses to its prototype if the prototype is not null.
7516 // A JSGlobalProxy can be reinitialized which will preserve its identity.
7518 // Accessing a JSGlobalProxy requires security check.
7520 class JSGlobalProxy : public JSObject {
7522 // [native_context]: the owner native context of this global proxy object.
7523 // It is null value if this object is not used by any context.
7524 DECL_ACCESSORS(native_context, Object)
7526 // [hash]: The hash code property (undefined if not initialized yet).
7527 DECL_ACCESSORS(hash, Object)
7529 DECLARE_CAST(JSGlobalProxy)
7531 inline bool IsDetachedFrom(GlobalObject* global) const;
7533 // Dispatched behavior.
7534 DECLARE_PRINTER(JSGlobalProxy)
7535 DECLARE_VERIFIER(JSGlobalProxy)
7537 // Layout description.
7538 static const int kNativeContextOffset = JSObject::kHeaderSize;
7539 static const int kHashOffset = kNativeContextOffset + kPointerSize;
7540 static const int kSize = kHashOffset + kPointerSize;
7543 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
7547 // Common super class for JavaScript global objects and the special
7548 // builtins global objects.
7549 class GlobalObject: public JSObject {
7551 // [builtins]: the object holding the runtime routines written in JS.
7552 DECL_ACCESSORS(builtins, JSBuiltinsObject)
7554 // [native context]: the natives corresponding to this global object.
7555 DECL_ACCESSORS(native_context, Context)
7557 // [global proxy]: the global proxy object of the context
7558 DECL_ACCESSORS(global_proxy, JSObject)
7560 DECLARE_CAST(GlobalObject)
7562 static void InvalidatePropertyCell(Handle<GlobalObject> object,
7564 // Ensure that the global object has a cell for the given property name.
7565 static Handle<PropertyCell> EnsurePropertyCell(Handle<GlobalObject> global,
7568 // Layout description.
7569 static const int kBuiltinsOffset = JSObject::kHeaderSize;
7570 static const int kNativeContextOffset = kBuiltinsOffset + kPointerSize;
7571 static const int kGlobalProxyOffset = kNativeContextOffset + kPointerSize;
7572 static const int kHeaderSize = kGlobalProxyOffset + kPointerSize;
7575 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
7579 // JavaScript global object.
7580 class JSGlobalObject: public GlobalObject {
7582 DECLARE_CAST(JSGlobalObject)
7584 inline bool IsDetached();
7586 // Dispatched behavior.
7587 DECLARE_PRINTER(JSGlobalObject)
7588 DECLARE_VERIFIER(JSGlobalObject)
7590 // Layout description.
7591 static const int kSize = GlobalObject::kHeaderSize;
7594 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
7598 // Builtins global object which holds the runtime routines written in
7600 class JSBuiltinsObject: public GlobalObject {
7602 // Accessors for the runtime routines written in JavaScript.
7603 inline Object* javascript_builtin(Builtins::JavaScript id);
7604 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
7606 DECLARE_CAST(JSBuiltinsObject)
7608 // Dispatched behavior.
7609 DECLARE_PRINTER(JSBuiltinsObject)
7610 DECLARE_VERIFIER(JSBuiltinsObject)
7612 // Layout description. The size of the builtins object includes
7613 // room for two pointers per runtime routine written in javascript
7614 // (function and code object).
7615 static const int kJSBuiltinsCount = Builtins::id_count;
7616 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
7617 static const int kSize =
7618 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
7620 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
7621 return kJSBuiltinsOffset + id * kPointerSize;
7625 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
7629 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
7630 class JSValue: public JSObject {
7632 // [value]: the object being wrapped.
7633 DECL_ACCESSORS(value, Object)
7635 DECLARE_CAST(JSValue)
7637 // Dispatched behavior.
7638 DECLARE_PRINTER(JSValue)
7639 DECLARE_VERIFIER(JSValue)
7641 // Layout description.
7642 static const int kValueOffset = JSObject::kHeaderSize;
7643 static const int kSize = kValueOffset + kPointerSize;
7646 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
7652 // Representation for JS date objects.
7653 class JSDate: public JSObject {
7655 // If one component is NaN, all of them are, indicating a NaN time value.
7656 // [value]: the time value.
7657 DECL_ACCESSORS(value, Object)
7658 // [year]: caches year. Either undefined, smi, or NaN.
7659 DECL_ACCESSORS(year, Object)
7660 // [month]: caches month. Either undefined, smi, or NaN.
7661 DECL_ACCESSORS(month, Object)
7662 // [day]: caches day. Either undefined, smi, or NaN.
7663 DECL_ACCESSORS(day, Object)
7664 // [weekday]: caches day of week. Either undefined, smi, or NaN.
7665 DECL_ACCESSORS(weekday, Object)
7666 // [hour]: caches hours. Either undefined, smi, or NaN.
7667 DECL_ACCESSORS(hour, Object)
7668 // [min]: caches minutes. Either undefined, smi, or NaN.
7669 DECL_ACCESSORS(min, Object)
7670 // [sec]: caches seconds. Either undefined, smi, or NaN.
7671 DECL_ACCESSORS(sec, Object)
7672 // [cache stamp]: sample of the date cache stamp at the
7673 // moment when chached fields were cached.
7674 DECL_ACCESSORS(cache_stamp, Object)
7676 DECLARE_CAST(JSDate)
7678 // Returns the date field with the specified index.
7679 // See FieldIndex for the list of date fields.
7680 static Object* GetField(Object* date, Smi* index);
7682 void SetValue(Object* value, bool is_value_nan);
7685 // Dispatched behavior.
7686 DECLARE_PRINTER(JSDate)
7687 DECLARE_VERIFIER(JSDate)
7689 // The order is important. It must be kept in sync with date macros
7700 kFirstUncachedField,
7701 kMillisecond = kFirstUncachedField,
7705 kYearUTC = kFirstUTCField,
7718 // Layout description.
7719 static const int kValueOffset = JSObject::kHeaderSize;
7720 static const int kYearOffset = kValueOffset + kPointerSize;
7721 static const int kMonthOffset = kYearOffset + kPointerSize;
7722 static const int kDayOffset = kMonthOffset + kPointerSize;
7723 static const int kWeekdayOffset = kDayOffset + kPointerSize;
7724 static const int kHourOffset = kWeekdayOffset + kPointerSize;
7725 static const int kMinOffset = kHourOffset + kPointerSize;
7726 static const int kSecOffset = kMinOffset + kPointerSize;
7727 static const int kCacheStampOffset = kSecOffset + kPointerSize;
7728 static const int kSize = kCacheStampOffset + kPointerSize;
7731 inline Object* DoGetField(FieldIndex index);
7733 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
7735 // Computes and caches the cacheable fields of the date.
7736 inline void SetCachedFields(int64_t local_time_ms, DateCache* date_cache);
7739 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
7743 // Representation of message objects used for error reporting through
7744 // the API. The messages are formatted in JavaScript so this object is
7745 // a real JavaScript object. The information used for formatting the
7746 // error messages are not directly accessible from JavaScript to
7747 // prevent leaking information to user code called during error
7749 class JSMessageObject: public JSObject {
7751 // [type]: the type of error message.
7752 inline int type() const;
7753 inline void set_type(int value);
7755 // [arguments]: the arguments for formatting the error message.
7756 DECL_ACCESSORS(argument, Object)
7758 // [script]: the script from which the error message originated.
7759 DECL_ACCESSORS(script, Object)
7761 // [stack_frames]: an array of stack frames for this error object.
7762 DECL_ACCESSORS(stack_frames, Object)
7764 // [start_position]: the start position in the script for the error message.
7765 inline int start_position() const;
7766 inline void set_start_position(int value);
7768 // [end_position]: the end position in the script for the error message.
7769 inline int end_position() const;
7770 inline void set_end_position(int value);
7772 DECLARE_CAST(JSMessageObject)
7774 // Dispatched behavior.
7775 DECLARE_PRINTER(JSMessageObject)
7776 DECLARE_VERIFIER(JSMessageObject)
7778 // Layout description.
7779 static const int kTypeOffset = JSObject::kHeaderSize;
7780 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
7781 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
7782 static const int kStackFramesOffset = kScriptOffset + kPointerSize;
7783 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
7784 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
7785 static const int kSize = kEndPositionOffset + kPointerSize;
7787 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
7788 kStackFramesOffset + kPointerSize,
7789 kSize> BodyDescriptor;
7793 // Regular expressions
7794 // The regular expression holds a single reference to a FixedArray in
7795 // the kDataOffset field.
7796 // The FixedArray contains the following data:
7797 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
7798 // - reference to the original source string
7799 // - reference to the original flag string
7800 // If it is an atom regexp
7801 // - a reference to a literal string to search for
7802 // If it is an irregexp regexp:
7803 // - a reference to code for Latin1 inputs (bytecode or compiled), or a smi
7804 // used for tracking the last usage (used for code flushing).
7805 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
7806 // used for tracking the last usage (used for code flushing)..
7807 // - max number of registers used by irregexp implementations.
7808 // - number of capture registers (output values) of the regexp.
7809 class JSRegExp: public JSObject {
7812 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
7813 // ATOM: A simple string to match against using an indexOf operation.
7814 // IRREGEXP: Compiled with Irregexp.
7815 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
7816 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
7823 UNICODE_ESCAPES = 16
7828 explicit Flags(uint32_t value) : value_(value) { }
7829 bool is_global() { return (value_ & GLOBAL) != 0; }
7830 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
7831 bool is_multiline() { return (value_ & MULTILINE) != 0; }
7832 bool is_sticky() { return (value_ & STICKY) != 0; }
7833 bool is_unicode() { return (value_ & UNICODE_ESCAPES) != 0; }
7834 uint32_t value() { return value_; }
7839 DECL_ACCESSORS(data, Object)
7841 inline Type TypeTag();
7842 inline int CaptureCount();
7843 inline Flags GetFlags();
7844 inline String* Pattern();
7845 inline Object* DataAt(int index);
7846 // Set implementation data after the object has been prepared.
7847 inline void SetDataAt(int index, Object* value);
7849 static int code_index(bool is_latin1) {
7851 return kIrregexpLatin1CodeIndex;
7853 return kIrregexpUC16CodeIndex;
7857 static int saved_code_index(bool is_latin1) {
7859 return kIrregexpLatin1CodeSavedIndex;
7861 return kIrregexpUC16CodeSavedIndex;
7865 DECLARE_CAST(JSRegExp)
7867 // Dispatched behavior.
7868 DECLARE_VERIFIER(JSRegExp)
7870 static const int kDataOffset = JSObject::kHeaderSize;
7871 static const int kSize = kDataOffset + kPointerSize;
7873 // Indices in the data array.
7874 static const int kTagIndex = 0;
7875 static const int kSourceIndex = kTagIndex + 1;
7876 static const int kFlagsIndex = kSourceIndex + 1;
7877 static const int kDataIndex = kFlagsIndex + 1;
7878 // The data fields are used in different ways depending on the
7879 // value of the tag.
7880 // Atom regexps (literal strings).
7881 static const int kAtomPatternIndex = kDataIndex;
7883 static const int kAtomDataSize = kAtomPatternIndex + 1;
7885 // Irregexp compiled code or bytecode for Latin1. If compilation
7886 // fails, this fields hold an exception object that should be
7887 // thrown if the regexp is used again.
7888 static const int kIrregexpLatin1CodeIndex = kDataIndex;
7889 // Irregexp compiled code or bytecode for UC16. If compilation
7890 // fails, this fields hold an exception object that should be
7891 // thrown if the regexp is used again.
7892 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
7894 // Saved instance of Irregexp compiled code or bytecode for Latin1 that
7895 // is a potential candidate for flushing.
7896 static const int kIrregexpLatin1CodeSavedIndex = kDataIndex + 2;
7897 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
7898 // a potential candidate for flushing.
7899 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
7901 // Maximal number of registers used by either Latin1 or UC16.
7902 // Only used to check that there is enough stack space
7903 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
7904 // Number of captures in the compiled regexp.
7905 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
7907 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
7909 // Offsets directly into the data fixed array.
7910 static const int kDataTagOffset =
7911 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
7912 static const int kDataOneByteCodeOffset =
7913 FixedArray::kHeaderSize + kIrregexpLatin1CodeIndex * kPointerSize;
7914 static const int kDataUC16CodeOffset =
7915 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
7916 static const int kIrregexpCaptureCountOffset =
7917 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
7919 // In-object fields.
7920 static const int kSourceFieldIndex = 0;
7921 static const int kGlobalFieldIndex = 1;
7922 static const int kIgnoreCaseFieldIndex = 2;
7923 static const int kMultilineFieldIndex = 3;
7924 static const int kLastIndexFieldIndex = 4;
7925 static const int kInObjectFieldCount = 5;
7927 // The uninitialized value for a regexp code object.
7928 static const int kUninitializedValue = -1;
7930 // The compilation error value for the regexp code object. The real error
7931 // object is in the saved code field.
7932 static const int kCompilationErrorValue = -2;
7934 // When we store the sweep generation at which we moved the code from the
7935 // code index to the saved code index we mask it of to be in the [0:255]
7937 static const int kCodeAgeMask = 0xff;
7941 class CompilationCacheShape : public BaseShape<HashTableKey*> {
7943 static inline bool IsMatch(HashTableKey* key, Object* value) {
7944 return key->IsMatch(value);
7947 static inline uint32_t Hash(HashTableKey* key) {
7951 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
7952 return key->HashForObject(object);
7955 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
7957 static const int kPrefixSize = 0;
7958 static const int kEntrySize = 2;
7962 // This cache is used in two different variants. For regexp caching, it simply
7963 // maps identifying info of the regexp to the cached regexp object. Scripts and
7964 // eval code only gets cached after a second probe for the code object. To do
7965 // so, on first "put" only a hash identifying the source is entered into the
7966 // cache, mapping it to a lifetime count of the hash. On each call to Age all
7967 // such lifetimes get reduced, and removed once they reach zero. If a second put
7968 // is called while such a hash is live in the cache, the hash gets replaced by
7969 // an actual cache entry. Age also removes stale live entries from the cache.
7970 // Such entries are identified by SharedFunctionInfos pointing to either the
7971 // recompilation stub, or to "old" code. This avoids memory leaks due to
7972 // premature caching of scripts and eval strings that are never needed later.
7973 class CompilationCacheTable: public HashTable<CompilationCacheTable,
7974 CompilationCacheShape,
7977 // Find cached value for a string key, otherwise return null.
7978 Handle<Object> Lookup(
7979 Handle<String> src, Handle<Context> context, LanguageMode language_mode);
7980 Handle<Object> LookupEval(
7981 Handle<String> src, Handle<SharedFunctionInfo> shared,
7982 LanguageMode language_mode, int scope_position);
7983 Handle<Object> LookupRegExp(Handle<String> source, JSRegExp::Flags flags);
7984 static Handle<CompilationCacheTable> Put(
7985 Handle<CompilationCacheTable> cache, Handle<String> src,
7986 Handle<Context> context, LanguageMode language_mode,
7987 Handle<Object> value);
7988 static Handle<CompilationCacheTable> PutEval(
7989 Handle<CompilationCacheTable> cache, Handle<String> src,
7990 Handle<SharedFunctionInfo> context, Handle<SharedFunctionInfo> value,
7991 int scope_position);
7992 static Handle<CompilationCacheTable> PutRegExp(
7993 Handle<CompilationCacheTable> cache, Handle<String> src,
7994 JSRegExp::Flags flags, Handle<FixedArray> value);
7995 void Remove(Object* value);
7997 static const int kHashGenerations = 10;
7999 DECLARE_CAST(CompilationCacheTable)
8002 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
8006 class CodeCache: public Struct {
8008 DECL_ACCESSORS(default_cache, FixedArray)
8009 DECL_ACCESSORS(normal_type_cache, Object)
8011 // Add the code object to the cache.
8013 Handle<CodeCache> cache, Handle<Name> name, Handle<Code> code);
8015 // Lookup code object in the cache. Returns code object if found and undefined
8017 Object* Lookup(Name* name, Code::Flags flags);
8019 // Get the internal index of a code object in the cache. Returns -1 if the
8020 // code object is not in that cache. This index can be used to later call
8021 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
8023 int GetIndex(Object* name, Code* code);
8025 // Remove an object from the cache with the provided internal index.
8026 void RemoveByIndex(Object* name, Code* code, int index);
8028 DECLARE_CAST(CodeCache)
8030 // Dispatched behavior.
8031 DECLARE_PRINTER(CodeCache)
8032 DECLARE_VERIFIER(CodeCache)
8034 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
8035 static const int kNormalTypeCacheOffset =
8036 kDefaultCacheOffset + kPointerSize;
8037 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
8040 static void UpdateDefaultCache(
8041 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8042 static void UpdateNormalTypeCache(
8043 Handle<CodeCache> code_cache, Handle<Name> name, Handle<Code> code);
8044 Object* LookupDefaultCache(Name* name, Code::Flags flags);
8045 Object* LookupNormalTypeCache(Name* name, Code::Flags flags);
8047 // Code cache layout of the default cache. Elements are alternating name and
8048 // code objects for non normal load/store/call IC's.
8049 static const int kCodeCacheEntrySize = 2;
8050 static const int kCodeCacheEntryNameOffset = 0;
8051 static const int kCodeCacheEntryCodeOffset = 1;
8053 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
8057 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
8059 static inline bool IsMatch(HashTableKey* key, Object* value) {
8060 return key->IsMatch(value);
8063 static inline uint32_t Hash(HashTableKey* key) {
8067 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
8068 return key->HashForObject(object);
8071 static inline Handle<Object> AsHandle(Isolate* isolate, HashTableKey* key);
8073 static const int kPrefixSize = 0;
8074 static const int kEntrySize = 2;
8078 class CodeCacheHashTable: public HashTable<CodeCacheHashTable,
8079 CodeCacheHashTableShape,
8082 Object* Lookup(Name* name, Code::Flags flags);
8083 static Handle<CodeCacheHashTable> Put(
8084 Handle<CodeCacheHashTable> table,
8088 int GetIndex(Name* name, Code::Flags flags);
8089 void RemoveByIndex(int index);
8091 DECLARE_CAST(CodeCacheHashTable)
8093 // Initial size of the fixed array backing the hash table.
8094 static const int kInitialSize = 64;
8097 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
8101 class PolymorphicCodeCache: public Struct {
8103 DECL_ACCESSORS(cache, Object)
8105 static void Update(Handle<PolymorphicCodeCache> cache,
8106 MapHandleList* maps,
8111 // Returns an undefined value if the entry is not found.
8112 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
8114 DECLARE_CAST(PolymorphicCodeCache)
8116 // Dispatched behavior.
8117 DECLARE_PRINTER(PolymorphicCodeCache)
8118 DECLARE_VERIFIER(PolymorphicCodeCache)
8120 static const int kCacheOffset = HeapObject::kHeaderSize;
8121 static const int kSize = kCacheOffset + kPointerSize;
8124 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
8128 class PolymorphicCodeCacheHashTable
8129 : public HashTable<PolymorphicCodeCacheHashTable,
8130 CodeCacheHashTableShape,
8133 Object* Lookup(MapHandleList* maps, int code_kind);
8135 static Handle<PolymorphicCodeCacheHashTable> Put(
8136 Handle<PolymorphicCodeCacheHashTable> hash_table,
8137 MapHandleList* maps,
8141 DECLARE_CAST(PolymorphicCodeCacheHashTable)
8143 static const int kInitialSize = 64;
8145 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
8149 class TypeFeedbackInfo: public Struct {
8151 inline int ic_total_count();
8152 inline void set_ic_total_count(int count);
8154 inline int ic_with_type_info_count();
8155 inline void change_ic_with_type_info_count(int delta);
8157 inline int ic_generic_count();
8158 inline void change_ic_generic_count(int delta);
8160 inline void initialize_storage();
8162 inline void change_own_type_change_checksum();
8163 inline int own_type_change_checksum();
8165 inline void set_inlined_type_change_checksum(int checksum);
8166 inline bool matches_inlined_type_change_checksum(int checksum);
8168 DECLARE_CAST(TypeFeedbackInfo)
8170 // Dispatched behavior.
8171 DECLARE_PRINTER(TypeFeedbackInfo)
8172 DECLARE_VERIFIER(TypeFeedbackInfo)
8174 static const int kStorage1Offset = HeapObject::kHeaderSize;
8175 static const int kStorage2Offset = kStorage1Offset + kPointerSize;
8176 static const int kStorage3Offset = kStorage2Offset + kPointerSize;
8177 static const int kSize = kStorage3Offset + kPointerSize;
8180 static const int kTypeChangeChecksumBits = 7;
8182 class ICTotalCountField: public BitField<int, 0,
8183 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8184 class OwnTypeChangeChecksum: public BitField<int,
8185 kSmiValueSize - kTypeChangeChecksumBits,
8186 kTypeChangeChecksumBits> {}; // NOLINT
8187 class ICsWithTypeInfoCountField: public BitField<int, 0,
8188 kSmiValueSize - kTypeChangeChecksumBits> {}; // NOLINT
8189 class InlinedTypeChangeChecksum: public BitField<int,
8190 kSmiValueSize - kTypeChangeChecksumBits,
8191 kTypeChangeChecksumBits> {}; // NOLINT
8193 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
8197 enum AllocationSiteMode {
8198 DONT_TRACK_ALLOCATION_SITE,
8199 TRACK_ALLOCATION_SITE,
8200 LAST_ALLOCATION_SITE_MODE = TRACK_ALLOCATION_SITE
8204 class AllocationSite: public Struct {
8206 static const uint32_t kMaximumArrayBytesToPretransition = 8 * 1024;
8207 static const double kPretenureRatio;
8208 static const int kPretenureMinimumCreated = 100;
8210 // Values for pretenure decision field.
8211 enum PretenureDecision {
8217 kLastPretenureDecisionValue = kZombie
8220 const char* PretenureDecisionName(PretenureDecision decision);
8222 DECL_ACCESSORS(transition_info, Object)
8223 // nested_site threads a list of sites that represent nested literals
8224 // walked in a particular order. So [[1, 2], 1, 2] will have one
8225 // nested_site, but [[1, 2], 3, [4]] will have a list of two.
8226 DECL_ACCESSORS(nested_site, Object)
8227 DECL_ACCESSORS(pretenure_data, Smi)
8228 DECL_ACCESSORS(pretenure_create_count, Smi)
8229 DECL_ACCESSORS(dependent_code, DependentCode)
8230 DECL_ACCESSORS(weak_next, Object)
8232 inline void Initialize();
8234 // This method is expensive, it should only be called for reporting.
8235 bool IsNestedSite();
8237 // transition_info bitfields, for constructed array transition info.
8238 class ElementsKindBits: public BitField<ElementsKind, 0, 15> {};
8239 class UnusedBits: public BitField<int, 15, 14> {};
8240 class DoNotInlineBit: public BitField<bool, 29, 1> {};
8242 // Bitfields for pretenure_data
8243 class MementoFoundCountBits: public BitField<int, 0, 26> {};
8244 class PretenureDecisionBits: public BitField<PretenureDecision, 26, 3> {};
8245 class DeoptDependentCodeBit: public BitField<bool, 29, 1> {};
8246 STATIC_ASSERT(PretenureDecisionBits::kMax >= kLastPretenureDecisionValue);
8248 // Increments the mementos found counter and returns true when the first
8249 // memento was found for a given allocation site.
8250 inline bool IncrementMementoFoundCount();
8252 inline void IncrementMementoCreateCount();
8254 PretenureFlag GetPretenureMode();
8256 void ResetPretenureDecision();
8258 PretenureDecision pretenure_decision() {
8259 int value = pretenure_data()->value();
8260 return PretenureDecisionBits::decode(value);
8263 void set_pretenure_decision(PretenureDecision decision) {
8264 int value = pretenure_data()->value();
8266 Smi::FromInt(PretenureDecisionBits::update(value, decision)),
8267 SKIP_WRITE_BARRIER);
8270 bool deopt_dependent_code() {
8271 int value = pretenure_data()->value();
8272 return DeoptDependentCodeBit::decode(value);
8275 void set_deopt_dependent_code(bool deopt) {
8276 int value = pretenure_data()->value();
8278 Smi::FromInt(DeoptDependentCodeBit::update(value, deopt)),
8279 SKIP_WRITE_BARRIER);
8282 int memento_found_count() {
8283 int value = pretenure_data()->value();
8284 return MementoFoundCountBits::decode(value);
8287 inline void set_memento_found_count(int count);
8289 int memento_create_count() {
8290 return pretenure_create_count()->value();
8293 void set_memento_create_count(int count) {
8294 set_pretenure_create_count(Smi::FromInt(count), SKIP_WRITE_BARRIER);
8297 // The pretenuring decision is made during gc, and the zombie state allows
8298 // us to recognize when an allocation site is just being kept alive because
8299 // a later traversal of new space may discover AllocationMementos that point
8300 // to this AllocationSite.
8302 return pretenure_decision() == kZombie;
8305 bool IsMaybeTenure() {
8306 return pretenure_decision() == kMaybeTenure;
8309 inline void MarkZombie();
8311 inline bool MakePretenureDecision(PretenureDecision current_decision,
8313 bool maximum_size_scavenge);
8315 inline bool DigestPretenuringFeedback(bool maximum_size_scavenge);
8317 ElementsKind GetElementsKind() {
8318 DCHECK(!SitePointsToLiteral());
8319 int value = Smi::cast(transition_info())->value();
8320 return ElementsKindBits::decode(value);
8323 void SetElementsKind(ElementsKind kind) {
8324 int value = Smi::cast(transition_info())->value();
8325 set_transition_info(Smi::FromInt(ElementsKindBits::update(value, kind)),
8326 SKIP_WRITE_BARRIER);
8329 bool CanInlineCall() {
8330 int value = Smi::cast(transition_info())->value();
8331 return DoNotInlineBit::decode(value) == 0;
8334 void SetDoNotInlineCall() {
8335 int value = Smi::cast(transition_info())->value();
8336 set_transition_info(Smi::FromInt(DoNotInlineBit::update(value, true)),
8337 SKIP_WRITE_BARRIER);
8340 bool SitePointsToLiteral() {
8341 // If transition_info is a smi, then it represents an ElementsKind
8342 // for a constructed array. Otherwise, it must be a boilerplate
8343 // for an object or array literal.
8344 return transition_info()->IsJSArray() || transition_info()->IsJSObject();
8347 static void DigestTransitionFeedback(Handle<AllocationSite> site,
8348 ElementsKind to_kind);
8350 DECLARE_PRINTER(AllocationSite)
8351 DECLARE_VERIFIER(AllocationSite)
8353 DECLARE_CAST(AllocationSite)
8354 static inline AllocationSiteMode GetMode(
8355 ElementsKind boilerplate_elements_kind);
8356 static inline AllocationSiteMode GetMode(ElementsKind from, ElementsKind to);
8357 static inline bool CanTrack(InstanceType type);
8359 static const int kTransitionInfoOffset = HeapObject::kHeaderSize;
8360 static const int kNestedSiteOffset = kTransitionInfoOffset + kPointerSize;
8361 static const int kPretenureDataOffset = kNestedSiteOffset + kPointerSize;
8362 static const int kPretenureCreateCountOffset =
8363 kPretenureDataOffset + kPointerSize;
8364 static const int kDependentCodeOffset =
8365 kPretenureCreateCountOffset + kPointerSize;
8366 static const int kWeakNextOffset = kDependentCodeOffset + kPointerSize;
8367 static const int kSize = kWeakNextOffset + kPointerSize;
8369 // During mark compact we need to take special care for the dependent code
8371 static const int kPointerFieldsBeginOffset = kTransitionInfoOffset;
8372 static const int kPointerFieldsEndOffset = kWeakNextOffset;
8374 // For other visitors, use the fixed body descriptor below.
8375 typedef FixedBodyDescriptor<HeapObject::kHeaderSize,
8376 kDependentCodeOffset + kPointerSize,
8377 kSize> BodyDescriptor;
8380 bool PretenuringDecisionMade() {
8381 return pretenure_decision() != kUndecided;
8384 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationSite);
8388 class AllocationMemento: public Struct {
8390 static const int kAllocationSiteOffset = HeapObject::kHeaderSize;
8391 static const int kSize = kAllocationSiteOffset + kPointerSize;
8393 DECL_ACCESSORS(allocation_site, Object)
8396 return allocation_site()->IsAllocationSite() &&
8397 !AllocationSite::cast(allocation_site())->IsZombie();
8399 AllocationSite* GetAllocationSite() {
8401 return AllocationSite::cast(allocation_site());
8404 DECLARE_PRINTER(AllocationMemento)
8405 DECLARE_VERIFIER(AllocationMemento)
8407 DECLARE_CAST(AllocationMemento)
8410 DISALLOW_IMPLICIT_CONSTRUCTORS(AllocationMemento);
8414 // Representation of a slow alias as part of a sloppy arguments objects.
8415 // For fast aliases (if HasSloppyArgumentsElements()):
8416 // - the parameter map contains an index into the context
8417 // - all attributes of the element have default values
8418 // For slow aliases (if HasDictionaryArgumentsElements()):
8419 // - the parameter map contains no fast alias mapping (i.e. the hole)
8420 // - this struct (in the slow backing store) contains an index into the context
8421 // - all attributes are available as part if the property details
8422 class AliasedArgumentsEntry: public Struct {
8424 inline int aliased_context_slot() const;
8425 inline void set_aliased_context_slot(int count);
8427 DECLARE_CAST(AliasedArgumentsEntry)
8429 // Dispatched behavior.
8430 DECLARE_PRINTER(AliasedArgumentsEntry)
8431 DECLARE_VERIFIER(AliasedArgumentsEntry)
8433 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
8434 static const int kSize = kAliasedContextSlot + kPointerSize;
8437 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
8441 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
8442 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
8445 class StringHasher {
8447 explicit inline StringHasher(int length, uint32_t seed);
8449 template <typename schar>
8450 static inline uint32_t HashSequentialString(const schar* chars,
8454 // Reads all the data, even for long strings and computes the utf16 length.
8455 static uint32_t ComputeUtf8Hash(Vector<const char> chars,
8457 int* utf16_length_out);
8459 // Calculated hash value for a string consisting of 1 to
8460 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
8461 // value is represented decimal value.
8462 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
8464 // No string is allowed to have a hash of zero. That value is reserved
8465 // for internal properties. If the hash calculation yields zero then we
8467 static const int kZeroHash = 27;
8469 // Reusable parts of the hashing algorithm.
8470 INLINE(static uint32_t AddCharacterCore(uint32_t running_hash, uint16_t c));
8471 INLINE(static uint32_t GetHashCore(uint32_t running_hash));
8472 INLINE(static uint32_t ComputeRunningHash(uint32_t running_hash,
8473 const uc16* chars, int length));
8474 INLINE(static uint32_t ComputeRunningHashOneByte(uint32_t running_hash,
8479 // Returns the value to store in the hash field of a string with
8480 // the given length and contents.
8481 uint32_t GetHashField();
8482 // Returns true if the hash of this string can be computed without
8483 // looking at the contents.
8484 inline bool has_trivial_hash();
8485 // Adds a block of characters to the hash.
8486 template<typename Char>
8487 inline void AddCharacters(const Char* chars, int len);
8490 // Add a character to the hash.
8491 inline void AddCharacter(uint16_t c);
8492 // Update index. Returns true if string is still an index.
8493 inline bool UpdateIndex(uint16_t c);
8496 uint32_t raw_running_hash_;
8497 uint32_t array_index_;
8498 bool is_array_index_;
8499 bool is_first_char_;
8500 DISALLOW_COPY_AND_ASSIGN(StringHasher);
8504 class IteratingStringHasher : public StringHasher {
8506 static inline uint32_t Hash(String* string, uint32_t seed);
8507 inline void VisitOneByteString(const uint8_t* chars, int length);
8508 inline void VisitTwoByteString(const uint16_t* chars, int length);
8511 inline IteratingStringHasher(int len, uint32_t seed)
8512 : StringHasher(len, seed) {}
8513 void VisitConsString(ConsString* cons_string);
8514 DISALLOW_COPY_AND_ASSIGN(IteratingStringHasher);
8518 // The characteristics of a string are stored in its map. Retrieving these
8519 // few bits of information is moderately expensive, involving two memory
8520 // loads where the second is dependent on the first. To improve efficiency
8521 // the shape of the string is given its own class so that it can be retrieved
8522 // once and used for several string operations. A StringShape is small enough
8523 // to be passed by value and is immutable, but be aware that flattening a
8524 // string can potentially alter its shape. Also be aware that a GC caused by
8525 // something else can alter the shape of a string due to ConsString
8526 // shortcutting. Keeping these restrictions in mind has proven to be error-
8527 // prone and so we no longer put StringShapes in variables unless there is a
8528 // concrete performance benefit at that particular point in the code.
8529 class StringShape BASE_EMBEDDED {
8531 inline explicit StringShape(const String* s);
8532 inline explicit StringShape(Map* s);
8533 inline explicit StringShape(InstanceType t);
8534 inline bool IsSequential();
8535 inline bool IsExternal();
8536 inline bool IsCons();
8537 inline bool IsSliced();
8538 inline bool IsIndirect();
8539 inline bool IsExternalOneByte();
8540 inline bool IsExternalTwoByte();
8541 inline bool IsSequentialOneByte();
8542 inline bool IsSequentialTwoByte();
8543 inline bool IsInternalized();
8544 inline StringRepresentationTag representation_tag();
8545 inline uint32_t encoding_tag();
8546 inline uint32_t full_representation_tag();
8547 inline uint32_t size_tag();
8549 inline uint32_t type() { return type_; }
8550 inline void invalidate() { valid_ = false; }
8551 inline bool valid() { return valid_; }
8553 inline void invalidate() { }
8559 inline void set_valid() { valid_ = true; }
8562 inline void set_valid() { }
8567 // The Name abstract class captures anything that can be used as a property
8568 // name, i.e., strings and symbols. All names store a hash value.
8569 class Name: public HeapObject {
8571 // Get and set the hash field of the name.
8572 inline uint32_t hash_field();
8573 inline void set_hash_field(uint32_t value);
8575 // Tells whether the hash code has been computed.
8576 inline bool HasHashCode();
8578 // Returns a hash value used for the property table
8579 inline uint32_t Hash();
8581 // Equality operations.
8582 inline bool Equals(Name* other);
8583 inline static bool Equals(Handle<Name> one, Handle<Name> two);
8586 inline bool AsArrayIndex(uint32_t* index);
8588 // If the name is private, it can only name own properties.
8589 inline bool IsPrivate();
8591 // If the name is a non-flat string, this method returns a flat version of the
8592 // string. Otherwise it'll just return the input.
8593 static inline Handle<Name> Flatten(Handle<Name> name,
8594 PretenureFlag pretenure = NOT_TENURED);
8598 DECLARE_PRINTER(Name)
8600 void NameShortPrint();
8601 int NameShortPrint(Vector<char> str);
8604 // Layout description.
8605 static const int kHashFieldSlot = HeapObject::kHeaderSize;
8606 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
8607 static const int kHashFieldOffset = kHashFieldSlot;
8609 static const int kHashFieldOffset = kHashFieldSlot + kIntSize;
8611 static const int kSize = kHashFieldSlot + kPointerSize;
8613 // Mask constant for checking if a name has a computed hash code
8614 // and if it is a string that is an array index. The least significant bit
8615 // indicates whether a hash code has been computed. If the hash code has
8616 // been computed the 2nd bit tells whether the string can be used as an
8618 static const int kHashNotComputedMask = 1;
8619 static const int kIsNotArrayIndexMask = 1 << 1;
8620 static const int kNofHashBitFields = 2;
8622 // Shift constant retrieving hash code from hash field.
8623 static const int kHashShift = kNofHashBitFields;
8625 // Only these bits are relevant in the hash, since the top two are shifted
8627 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
8629 // Array index strings this short can keep their index in the hash field.
8630 static const int kMaxCachedArrayIndexLength = 7;
8632 // For strings which are array indexes the hash value has the string length
8633 // mixed into the hash, mainly to avoid a hash value of zero which would be
8634 // the case for the string '0'. 24 bits are used for the array index value.
8635 static const int kArrayIndexValueBits = 24;
8636 static const int kArrayIndexLengthBits =
8637 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8639 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8641 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8642 kArrayIndexValueBits> {}; // NOLINT
8643 class ArrayIndexLengthBits : public BitField<unsigned int,
8644 kNofHashBitFields + kArrayIndexValueBits,
8645 kArrayIndexLengthBits> {}; // NOLINT
8647 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8648 // could use a mask to test if the length of string is less than or equal to
8649 // kMaxCachedArrayIndexLength.
8650 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8652 static const unsigned int kContainsCachedArrayIndexMask =
8653 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8654 << ArrayIndexLengthBits::kShift) |
8655 kIsNotArrayIndexMask;
8657 // Value of empty hash field indicating that the hash is not computed.
8658 static const int kEmptyHashField =
8659 kIsNotArrayIndexMask | kHashNotComputedMask;
8662 static inline bool IsHashFieldComputed(uint32_t field);
8665 DISALLOW_IMPLICIT_CONSTRUCTORS(Name);
8670 class Symbol: public Name {
8672 // [name]: The print name of a symbol, or undefined if none.
8673 DECL_ACCESSORS(name, Object)
8675 DECL_ACCESSORS(flags, Smi)
8677 // [is_private]: Whether this is a private symbol. Private symbols can only
8678 // be used to designate own properties of objects.
8679 DECL_BOOLEAN_ACCESSORS(is_private)
8681 DECLARE_CAST(Symbol)
8683 // Dispatched behavior.
8684 DECLARE_PRINTER(Symbol)
8685 DECLARE_VERIFIER(Symbol)
8687 // Layout description.
8688 static const int kNameOffset = Name::kSize;
8689 static const int kFlagsOffset = kNameOffset + kPointerSize;
8690 static const int kSize = kFlagsOffset + kPointerSize;
8692 typedef FixedBodyDescriptor<kNameOffset, kFlagsOffset, kSize> BodyDescriptor;
8694 void SymbolShortPrint(std::ostream& os);
8697 static const int kPrivateBit = 0;
8699 const char* PrivateSymbolToName() const;
8702 friend class Name; // For PrivateSymbolToName.
8705 DISALLOW_IMPLICIT_CONSTRUCTORS(Symbol);
8711 // The String abstract class captures JavaScript string values:
8714 // 4.3.16 String Value
8715 // A string value is a member of the type String and is a finite
8716 // ordered sequence of zero or more 16-bit unsigned integer values.
8718 // All string values have a length field.
8719 class String: public Name {
8721 enum Encoding { ONE_BYTE_ENCODING, TWO_BYTE_ENCODING };
8723 // Array index strings this short can keep their index in the hash field.
8724 static const int kMaxCachedArrayIndexLength = 7;
8726 // For strings which are array indexes the hash value has the string length
8727 // mixed into the hash, mainly to avoid a hash value of zero which would be
8728 // the case for the string '0'. 24 bits are used for the array index value.
8729 static const int kArrayIndexValueBits = 24;
8730 static const int kArrayIndexLengthBits =
8731 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
8733 STATIC_ASSERT((kArrayIndexLengthBits > 0));
8735 class ArrayIndexValueBits : public BitField<unsigned int, kNofHashBitFields,
8736 kArrayIndexValueBits> {}; // NOLINT
8737 class ArrayIndexLengthBits : public BitField<unsigned int,
8738 kNofHashBitFields + kArrayIndexValueBits,
8739 kArrayIndexLengthBits> {}; // NOLINT
8741 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
8742 // could use a mask to test if the length of string is less than or equal to
8743 // kMaxCachedArrayIndexLength.
8744 STATIC_ASSERT(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
8746 static const unsigned int kContainsCachedArrayIndexMask =
8747 (~static_cast<unsigned>(kMaxCachedArrayIndexLength)
8748 << ArrayIndexLengthBits::kShift) |
8749 kIsNotArrayIndexMask;
8751 class SubStringRange {
8753 explicit SubStringRange(String* string, int first = 0, int length = -1)
8756 length_(length == -1 ? string->length() : length) {}
8758 inline iterator begin();
8759 inline iterator end();
8767 // Representation of the flat content of a String.
8768 // A non-flat string doesn't have flat content.
8769 // A flat string has content that's encoded as a sequence of either
8770 // one-byte chars or two-byte UC16.
8771 // Returned by String::GetFlatContent().
8774 // Returns true if the string is flat and this structure contains content.
8775 bool IsFlat() { return state_ != NON_FLAT; }
8776 // Returns true if the structure contains one-byte content.
8777 bool IsOneByte() { return state_ == ONE_BYTE; }
8778 // Returns true if the structure contains two-byte content.
8779 bool IsTwoByte() { return state_ == TWO_BYTE; }
8781 // Return the one byte content of the string. Only use if IsOneByte()
8783 Vector<const uint8_t> ToOneByteVector() {
8784 DCHECK_EQ(ONE_BYTE, state_);
8785 return Vector<const uint8_t>(onebyte_start, length_);
8787 // Return the two-byte content of the string. Only use if IsTwoByte()
8789 Vector<const uc16> ToUC16Vector() {
8790 DCHECK_EQ(TWO_BYTE, state_);
8791 return Vector<const uc16>(twobyte_start, length_);
8795 DCHECK(i < length_);
8796 DCHECK(state_ != NON_FLAT);
8797 if (state_ == ONE_BYTE) return onebyte_start[i];
8798 return twobyte_start[i];
8801 bool UsesSameString(const FlatContent& other) const {
8802 return onebyte_start == other.onebyte_start;
8806 enum State { NON_FLAT, ONE_BYTE, TWO_BYTE };
8808 // Constructors only used by String::GetFlatContent().
8809 explicit FlatContent(const uint8_t* start, int length)
8810 : onebyte_start(start), length_(length), state_(ONE_BYTE) {}
8811 explicit FlatContent(const uc16* start, int length)
8812 : twobyte_start(start), length_(length), state_(TWO_BYTE) { }
8813 FlatContent() : onebyte_start(NULL), length_(0), state_(NON_FLAT) { }
8816 const uint8_t* onebyte_start;
8817 const uc16* twobyte_start;
8822 friend class String;
8823 friend class IterableSubString;
8826 template <typename Char>
8827 INLINE(Vector<const Char> GetCharVector());
8829 // Get and set the length of the string.
8830 inline int length() const;
8831 inline void set_length(int value);
8833 // Get and set the length of the string using acquire loads and release
8835 inline int synchronized_length() const;
8836 inline void synchronized_set_length(int value);
8838 // Returns whether this string has only one-byte chars, i.e. all of them can
8839 // be one-byte encoded. This might be the case even if the string is
8840 // two-byte. Such strings may appear when the embedder prefers
8841 // two-byte external representations even for one-byte data.
8842 inline bool IsOneByteRepresentation() const;
8843 inline bool IsTwoByteRepresentation() const;
8845 // Cons and slices have an encoding flag that may not represent the actual
8846 // encoding of the underlying string. This is taken into account here.
8847 // Requires: this->IsFlat()
8848 inline bool IsOneByteRepresentationUnderneath();
8849 inline bool IsTwoByteRepresentationUnderneath();
8851 // NOTE: this should be considered only a hint. False negatives are
8853 inline bool HasOnlyOneByteChars();
8855 // Get and set individual two byte chars in the string.
8856 inline void Set(int index, uint16_t value);
8857 // Get individual two byte char in the string. Repeated calls
8858 // to this method are not efficient unless the string is flat.
8859 INLINE(uint16_t Get(int index));
8861 // Flattens the string. Checks first inline to see if it is
8862 // necessary. Does nothing if the string is not a cons string.
8863 // Flattening allocates a sequential string with the same data as
8864 // the given string and mutates the cons string to a degenerate
8865 // form, where the first component is the new sequential string and
8866 // the second component is the empty string. If allocation fails,
8867 // this function returns a failure. If flattening succeeds, this
8868 // function returns the sequential string that is now the first
8869 // component of the cons string.
8871 // Degenerate cons strings are handled specially by the garbage
8872 // collector (see IsShortcutCandidate).
8874 static inline Handle<String> Flatten(Handle<String> string,
8875 PretenureFlag pretenure = NOT_TENURED);
8877 // Tries to return the content of a flat string as a structure holding either
8878 // a flat vector of char or of uc16.
8879 // If the string isn't flat, and therefore doesn't have flat content, the
8880 // returned structure will report so, and can't provide a vector of either
8882 FlatContent GetFlatContent();
8884 // Returns the parent of a sliced string or first part of a flat cons string.
8885 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
8886 inline String* GetUnderlying();
8888 // String equality operations.
8889 inline bool Equals(String* other);
8890 inline static bool Equals(Handle<String> one, Handle<String> two);
8891 bool IsUtf8EqualTo(Vector<const char> str, bool allow_prefix_match = false);
8892 bool IsOneByteEqualTo(Vector<const uint8_t> str);
8893 bool IsTwoByteEqualTo(Vector<const uc16> str);
8895 // Return a UTF8 representation of the string. The string is null
8896 // terminated but may optionally contain nulls. Length is returned
8897 // in length_output if length_output is not a null pointer The string
8898 // should be nearly flat, otherwise the performance of this method may
8899 // be very slow (quadratic in the length). Setting robustness_flag to
8900 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8901 // handles unexpected data without causing assert failures and it does not
8902 // do any heap allocations. This is useful when printing stack traces.
8903 base::SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
8904 RobustnessFlag robustness_flag,
8905 int offset, int length,
8906 int* length_output = 0);
8907 base::SmartArrayPointer<char> ToCString(
8908 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
8909 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
8910 int* length_output = 0);
8912 // Return a 16 bit Unicode representation of the string.
8913 // The string should be nearly flat, otherwise the performance of
8914 // of this method may be very bad. Setting robustness_flag to
8915 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
8916 // handles unexpected data without causing assert failures and it does not
8917 // do any heap allocations. This is useful when printing stack traces.
8918 base::SmartArrayPointer<uc16> ToWideCString(
8919 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
8921 bool ComputeArrayIndex(uint32_t* index);
8924 bool MakeExternal(v8::String::ExternalStringResource* resource);
8925 bool MakeExternal(v8::String::ExternalOneByteStringResource* resource);
8928 inline bool AsArrayIndex(uint32_t* index);
8930 DECLARE_CAST(String)
8932 void PrintOn(FILE* out);
8934 // For use during stack traces. Performs rudimentary sanity check.
8937 // Dispatched behavior.
8938 void StringShortPrint(StringStream* accumulator);
8939 void PrintUC16(std::ostream& os, int start = 0, int end = -1); // NOLINT
8940 #if defined(DEBUG) || defined(OBJECT_PRINT)
8941 char* ToAsciiArray();
8943 DECLARE_PRINTER(String)
8944 DECLARE_VERIFIER(String)
8946 inline bool IsFlat();
8948 // Layout description.
8949 static const int kLengthOffset = Name::kSize;
8950 static const int kSize = kLengthOffset + kPointerSize;
8952 // Maximum number of characters to consider when trying to convert a string
8953 // value into an array index.
8954 static const int kMaxArrayIndexSize = 10;
8955 STATIC_ASSERT(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
8958 static const int32_t kMaxOneByteCharCode = unibrow::Latin1::kMaxChar;
8959 static const uint32_t kMaxOneByteCharCodeU = unibrow::Latin1::kMaxChar;
8960 static const int kMaxUtf16CodeUnit = 0xffff;
8961 static const uint32_t kMaxUtf16CodeUnitU = kMaxUtf16CodeUnit;
8963 // Value of hash field containing computed hash equal to zero.
8964 static const int kEmptyStringHash = kIsNotArrayIndexMask;
8966 // Maximal string length.
8967 static const int kMaxLength = (1 << 28) - 16;
8969 // Max length for computing hash. For strings longer than this limit the
8970 // string length is used as the hash value.
8971 static const int kMaxHashCalcLength = 16383;
8973 // Limit for truncation in short printing.
8974 static const int kMaxShortPrintLength = 1024;
8976 // Support for regular expressions.
8977 const uc16* GetTwoByteData(unsigned start);
8979 // Helper function for flattening strings.
8980 template <typename sinkchar>
8981 static void WriteToFlat(String* source,
8986 // The return value may point to the first aligned word containing the first
8987 // non-one-byte character, rather than directly to the non-one-byte character.
8988 // If the return value is >= the passed length, the entire string was
8990 static inline int NonAsciiStart(const char* chars, int length) {
8991 const char* start = chars;
8992 const char* limit = chars + length;
8994 if (length >= kIntptrSize) {
8995 // Check unaligned bytes.
8996 while (!IsAligned(reinterpret_cast<intptr_t>(chars), sizeof(uintptr_t))) {
8997 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
8998 return static_cast<int>(chars - start);
9002 // Check aligned words.
9003 DCHECK(unibrow::Utf8::kMaxOneByteChar == 0x7F);
9004 const uintptr_t non_one_byte_mask = kUintptrAllBitsSet / 0xFF * 0x80;
9005 while (chars + sizeof(uintptr_t) <= limit) {
9006 if (*reinterpret_cast<const uintptr_t*>(chars) & non_one_byte_mask) {
9007 return static_cast<int>(chars - start);
9009 chars += sizeof(uintptr_t);
9012 // Check remaining unaligned bytes.
9013 while (chars < limit) {
9014 if (static_cast<uint8_t>(*chars) > unibrow::Utf8::kMaxOneByteChar) {
9015 return static_cast<int>(chars - start);
9020 return static_cast<int>(chars - start);
9023 static inline bool IsAscii(const char* chars, int length) {
9024 return NonAsciiStart(chars, length) >= length;
9027 static inline bool IsAscii(const uint8_t* chars, int length) {
9029 NonAsciiStart(reinterpret_cast<const char*>(chars), length) >= length;
9032 static inline int NonOneByteStart(const uc16* chars, int length) {
9033 const uc16* limit = chars + length;
9034 const uc16* start = chars;
9035 while (chars < limit) {
9036 if (*chars > kMaxOneByteCharCodeU) return static_cast<int>(chars - start);
9039 return static_cast<int>(chars - start);
9042 static inline bool IsOneByte(const uc16* chars, int length) {
9043 return NonOneByteStart(chars, length) >= length;
9046 template<class Visitor>
9047 static inline ConsString* VisitFlat(Visitor* visitor,
9051 static Handle<FixedArray> CalculateLineEnds(Handle<String> string,
9052 bool include_ending_line);
9054 // Use the hash field to forward to the canonical internalized string
9055 // when deserializing an internalized string.
9056 inline void SetForwardedInternalizedString(String* string);
9057 inline String* GetForwardedInternalizedString();
9061 friend class StringTableInsertionKey;
9063 static Handle<String> SlowFlatten(Handle<ConsString> cons,
9064 PretenureFlag tenure);
9066 // Slow case of String::Equals. This implementation works on any strings
9067 // but it is most efficient on strings that are almost flat.
9068 bool SlowEquals(String* other);
9070 static bool SlowEquals(Handle<String> one, Handle<String> two);
9072 // Slow case of AsArrayIndex.
9073 bool SlowAsArrayIndex(uint32_t* index);
9075 // Compute and set the hash code.
9076 uint32_t ComputeAndSetHash();
9078 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
9082 // The SeqString abstract class captures sequential string values.
9083 class SeqString: public String {
9085 DECLARE_CAST(SeqString)
9087 // Layout description.
9088 static const int kHeaderSize = String::kSize;
9090 // Truncate the string in-place if possible and return the result.
9091 // In case of new_length == 0, the empty string is returned without
9092 // truncating the original string.
9093 MUST_USE_RESULT static Handle<String> Truncate(Handle<SeqString> string,
9096 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
9100 // The OneByteString class captures sequential one-byte string objects.
9101 // Each character in the OneByteString is an one-byte character.
9102 class SeqOneByteString: public SeqString {
9104 static const bool kHasOneByteEncoding = true;
9106 // Dispatched behavior.
9107 inline uint16_t SeqOneByteStringGet(int index);
9108 inline void SeqOneByteStringSet(int index, uint16_t value);
9110 // Get the address of the characters in this string.
9111 inline Address GetCharsAddress();
9113 inline uint8_t* GetChars();
9115 DECLARE_CAST(SeqOneByteString)
9117 // Garbage collection support. This method is called by the
9118 // garbage collector to compute the actual size of an OneByteString
9120 inline int SeqOneByteStringSize(InstanceType instance_type);
9122 // Computes the size for an OneByteString instance of a given length.
9123 static int SizeFor(int length) {
9124 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
9127 // Maximal memory usage for a single sequential one-byte string.
9128 static const int kMaxSize = 512 * MB - 1;
9129 STATIC_ASSERT((kMaxSize - kHeaderSize) >= String::kMaxLength);
9132 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqOneByteString);
9136 // The TwoByteString class captures sequential unicode string objects.
9137 // Each character in the TwoByteString is a two-byte uint16_t.
9138 class SeqTwoByteString: public SeqString {
9140 static const bool kHasOneByteEncoding = false;
9142 // Dispatched behavior.
9143 inline uint16_t SeqTwoByteStringGet(int index);
9144 inline void SeqTwoByteStringSet(int index, uint16_t value);
9146 // Get the address of the characters in this string.
9147 inline Address GetCharsAddress();
9149 inline uc16* GetChars();
9152 const uint16_t* SeqTwoByteStringGetData(unsigned start);
9154 DECLARE_CAST(SeqTwoByteString)
9156 // Garbage collection support. This method is called by the
9157 // garbage collector to compute the actual size of a TwoByteString
9159 inline int SeqTwoByteStringSize(InstanceType instance_type);
9161 // Computes the size for a TwoByteString instance of a given length.
9162 static int SizeFor(int length) {
9163 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
9166 // Maximal memory usage for a single sequential two-byte string.
9167 static const int kMaxSize = 512 * MB - 1;
9168 STATIC_ASSERT(static_cast<int>((kMaxSize - kHeaderSize)/sizeof(uint16_t)) >=
9169 String::kMaxLength);
9172 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
9176 // The ConsString class describes string values built by using the
9177 // addition operator on strings. A ConsString is a pair where the
9178 // first and second components are pointers to other string values.
9179 // One or both components of a ConsString can be pointers to other
9180 // ConsStrings, creating a binary tree of ConsStrings where the leaves
9181 // are non-ConsString string values. The string value represented by
9182 // a ConsString can be obtained by concatenating the leaf string
9183 // values in a left-to-right depth-first traversal of the tree.
9184 class ConsString: public String {
9186 // First string of the cons cell.
9187 inline String* first();
9188 // Doesn't check that the result is a string, even in debug mode. This is
9189 // useful during GC where the mark bits confuse the checks.
9190 inline Object* unchecked_first();
9191 inline void set_first(String* first,
9192 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9194 // Second string of the cons cell.
9195 inline String* second();
9196 // Doesn't check that the result is a string, even in debug mode. This is
9197 // useful during GC where the mark bits confuse the checks.
9198 inline Object* unchecked_second();
9199 inline void set_second(String* second,
9200 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9202 // Dispatched behavior.
9203 uint16_t ConsStringGet(int index);
9205 DECLARE_CAST(ConsString)
9207 // Layout description.
9208 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
9209 static const int kSecondOffset = kFirstOffset + kPointerSize;
9210 static const int kSize = kSecondOffset + kPointerSize;
9212 // Minimum length for a cons string.
9213 static const int kMinLength = 13;
9215 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
9218 DECLARE_VERIFIER(ConsString)
9221 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
9225 // The Sliced String class describes strings that are substrings of another
9226 // sequential string. The motivation is to save time and memory when creating
9227 // a substring. A Sliced String is described as a pointer to the parent,
9228 // the offset from the start of the parent string and the length. Using
9229 // a Sliced String therefore requires unpacking of the parent string and
9230 // adding the offset to the start address. A substring of a Sliced String
9231 // are not nested since the double indirection is simplified when creating
9232 // such a substring.
9233 // Currently missing features are:
9234 // - handling externalized parent strings
9235 // - external strings as parent
9236 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
9237 class SlicedString: public String {
9239 inline String* parent();
9240 inline void set_parent(String* parent,
9241 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
9242 inline int offset() const;
9243 inline void set_offset(int offset);
9245 // Dispatched behavior.
9246 uint16_t SlicedStringGet(int index);
9248 DECLARE_CAST(SlicedString)
9250 // Layout description.
9251 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
9252 static const int kOffsetOffset = kParentOffset + kPointerSize;
9253 static const int kSize = kOffsetOffset + kPointerSize;
9255 // Minimum length for a sliced string.
9256 static const int kMinLength = 13;
9258 typedef FixedBodyDescriptor<kParentOffset,
9259 kOffsetOffset + kPointerSize, kSize>
9262 DECLARE_VERIFIER(SlicedString)
9265 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
9269 // The ExternalString class describes string values that are backed by
9270 // a string resource that lies outside the V8 heap. ExternalStrings
9271 // consist of the length field common to all strings, a pointer to the
9272 // external resource. It is important to ensure (externally) that the
9273 // resource is not deallocated while the ExternalString is live in the
9276 // The API expects that all ExternalStrings are created through the
9277 // API. Therefore, ExternalStrings should not be used internally.
9278 class ExternalString: public String {
9280 DECLARE_CAST(ExternalString)
9282 // Layout description.
9283 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
9284 static const int kShortSize = kResourceOffset + kPointerSize;
9285 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
9286 static const int kSize = kResourceDataOffset + kPointerSize;
9288 static const int kMaxShortLength =
9289 (kShortSize - SeqString::kHeaderSize) / kCharSize;
9291 // Return whether external string is short (data pointer is not cached).
9292 inline bool is_short();
9294 STATIC_ASSERT(kResourceOffset == Internals::kStringResourceOffset);
9297 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
9301 // The ExternalOneByteString class is an external string backed by an
9303 class ExternalOneByteString : public ExternalString {
9305 static const bool kHasOneByteEncoding = true;
9307 typedef v8::String::ExternalOneByteStringResource Resource;
9309 // The underlying resource.
9310 inline const Resource* resource();
9311 inline void set_resource(const Resource* buffer);
9313 // Update the pointer cache to the external character array.
9314 // The cached pointer is always valid, as the external character array does =
9315 // not move during lifetime. Deserialization is the only exception, after
9316 // which the pointer cache has to be refreshed.
9317 inline void update_data_cache();
9319 inline const uint8_t* GetChars();
9321 // Dispatched behavior.
9322 inline uint16_t ExternalOneByteStringGet(int index);
9324 DECLARE_CAST(ExternalOneByteString)
9326 // Garbage collection support.
9327 inline void ExternalOneByteStringIterateBody(ObjectVisitor* v);
9329 template <typename StaticVisitor>
9330 inline void ExternalOneByteStringIterateBody();
9333 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalOneByteString);
9337 // The ExternalTwoByteString class is an external string backed by a UTF-16
9339 class ExternalTwoByteString: public ExternalString {
9341 static const bool kHasOneByteEncoding = false;
9343 typedef v8::String::ExternalStringResource Resource;
9345 // The underlying string resource.
9346 inline const Resource* resource();
9347 inline void set_resource(const Resource* buffer);
9349 // Update the pointer cache to the external character array.
9350 // The cached pointer is always valid, as the external character array does =
9351 // not move during lifetime. Deserialization is the only exception, after
9352 // which the pointer cache has to be refreshed.
9353 inline void update_data_cache();
9355 inline const uint16_t* GetChars();
9357 // Dispatched behavior.
9358 inline uint16_t ExternalTwoByteStringGet(int index);
9361 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
9363 DECLARE_CAST(ExternalTwoByteString)
9365 // Garbage collection support.
9366 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
9368 template<typename StaticVisitor>
9369 inline void ExternalTwoByteStringIterateBody();
9372 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
9376 // Utility superclass for stack-allocated objects that must be updated
9377 // on gc. It provides two ways for the gc to update instances, either
9378 // iterating or updating after gc.
9379 class Relocatable BASE_EMBEDDED {
9381 explicit inline Relocatable(Isolate* isolate);
9382 inline virtual ~Relocatable();
9383 virtual void IterateInstance(ObjectVisitor* v) { }
9384 virtual void PostGarbageCollection() { }
9386 static void PostGarbageCollectionProcessing(Isolate* isolate);
9387 static int ArchiveSpacePerThread();
9388 static char* ArchiveState(Isolate* isolate, char* to);
9389 static char* RestoreState(Isolate* isolate, char* from);
9390 static void Iterate(Isolate* isolate, ObjectVisitor* v);
9391 static void Iterate(ObjectVisitor* v, Relocatable* top);
9392 static char* Iterate(ObjectVisitor* v, char* t);
9400 // A flat string reader provides random access to the contents of a
9401 // string independent of the character width of the string. The handle
9402 // must be valid as long as the reader is being used.
9403 class FlatStringReader : public Relocatable {
9405 FlatStringReader(Isolate* isolate, Handle<String> str);
9406 FlatStringReader(Isolate* isolate, Vector<const char> input);
9407 void PostGarbageCollection();
9408 inline uc32 Get(int index);
9409 template <typename Char>
9410 inline Char Get(int index);
9411 int length() { return length_; }
9420 // This maintains an off-stack representation of the stack frames required
9421 // to traverse a ConsString, allowing an entirely iterative and restartable
9422 // traversal of the entire string
9423 class ConsStringIterator {
9425 inline ConsStringIterator() {}
9426 inline explicit ConsStringIterator(ConsString* cons_string, int offset = 0) {
9427 Reset(cons_string, offset);
9429 inline void Reset(ConsString* cons_string, int offset = 0) {
9431 // Next will always return NULL.
9432 if (cons_string == NULL) return;
9433 Initialize(cons_string, offset);
9435 // Returns NULL when complete.
9436 inline String* Next(int* offset_out) {
9438 if (depth_ == 0) return NULL;
9439 return Continue(offset_out);
9443 static const int kStackSize = 32;
9444 // Use a mask instead of doing modulo operations for stack wrapping.
9445 static const int kDepthMask = kStackSize-1;
9446 STATIC_ASSERT(IS_POWER_OF_TWO(kStackSize));
9447 static inline int OffsetForDepth(int depth);
9449 inline void PushLeft(ConsString* string);
9450 inline void PushRight(ConsString* string);
9451 inline void AdjustMaximumDepth();
9453 inline bool StackBlown() { return maximum_depth_ - depth_ == kStackSize; }
9454 void Initialize(ConsString* cons_string, int offset);
9455 String* Continue(int* offset_out);
9456 String* NextLeaf(bool* blew_stack);
9457 String* Search(int* offset_out);
9459 // Stack must always contain only frames for which right traversal
9460 // has not yet been performed.
9461 ConsString* frames_[kStackSize];
9466 DISALLOW_COPY_AND_ASSIGN(ConsStringIterator);
9470 class StringCharacterStream {
9472 inline StringCharacterStream(String* string,
9474 inline uint16_t GetNext();
9475 inline bool HasMore();
9476 inline void Reset(String* string, int offset = 0);
9477 inline void VisitOneByteString(const uint8_t* chars, int length);
9478 inline void VisitTwoByteString(const uint16_t* chars, int length);
9481 ConsStringIterator iter_;
9484 const uint8_t* buffer8_;
9485 const uint16_t* buffer16_;
9487 const uint8_t* end_;
9488 DISALLOW_COPY_AND_ASSIGN(StringCharacterStream);
9492 template <typename T>
9493 class VectorIterator {
9495 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
9496 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
9497 T GetNext() { return data_[index_++]; }
9498 bool has_more() { return index_ < data_.length(); }
9500 Vector<const T> data_;
9505 // The Oddball describes objects null, undefined, true, and false.
9506 class Oddball: public HeapObject {
9508 // [to_string]: Cached to_string computed at startup.
9509 DECL_ACCESSORS(to_string, String)
9511 // [to_number]: Cached to_number computed at startup.
9512 DECL_ACCESSORS(to_number, Object)
9514 inline byte kind() const;
9515 inline void set_kind(byte kind);
9517 DECLARE_CAST(Oddball)
9519 // Dispatched behavior.
9520 DECLARE_VERIFIER(Oddball)
9522 // Initialize the fields.
9523 static void Initialize(Isolate* isolate,
9524 Handle<Oddball> oddball,
9525 const char* to_string,
9526 Handle<Object> to_number,
9529 // Layout description.
9530 static const int kToStringOffset = HeapObject::kHeaderSize;
9531 static const int kToNumberOffset = kToStringOffset + kPointerSize;
9532 static const int kKindOffset = kToNumberOffset + kPointerSize;
9533 static const int kSize = kKindOffset + kPointerSize;
9535 static const byte kFalse = 0;
9536 static const byte kTrue = 1;
9537 static const byte kNotBooleanMask = ~1;
9538 static const byte kTheHole = 2;
9539 static const byte kNull = 3;
9540 static const byte kArgumentMarker = 4;
9541 static const byte kUndefined = 5;
9542 static const byte kUninitialized = 6;
9543 static const byte kOther = 7;
9544 static const byte kException = 8;
9546 typedef FixedBodyDescriptor<kToStringOffset,
9547 kToNumberOffset + kPointerSize,
9548 kSize> BodyDescriptor;
9550 STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset);
9551 STATIC_ASSERT(kNull == Internals::kNullOddballKind);
9552 STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind);
9555 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
9559 class Cell: public HeapObject {
9561 // [value]: value of the cell.
9562 DECL_ACCESSORS(value, Object)
9566 static inline Cell* FromValueAddress(Address value) {
9567 Object* result = FromAddress(value - kValueOffset);
9568 return static_cast<Cell*>(result);
9571 inline Address ValueAddress() {
9572 return address() + kValueOffset;
9575 // Dispatched behavior.
9576 DECLARE_PRINTER(Cell)
9577 DECLARE_VERIFIER(Cell)
9579 // Layout description.
9580 static const int kValueOffset = HeapObject::kHeaderSize;
9581 static const int kSize = kValueOffset + kPointerSize;
9583 typedef FixedBodyDescriptor<kValueOffset,
9584 kValueOffset + kPointerSize,
9585 kSize> BodyDescriptor;
9588 DISALLOW_IMPLICIT_CONSTRUCTORS(Cell);
9592 class PropertyCell : public HeapObject {
9594 // [property_details]: details of the global property.
9595 DECL_ACCESSORS(property_details_raw, Object)
9596 // [value]: value of the global property.
9597 DECL_ACCESSORS(value, Object)
9598 // [dependent_code]: dependent code that depends on the type of the global
9600 DECL_ACCESSORS(dependent_code, DependentCode)
9602 PropertyDetails property_details() {
9603 return PropertyDetails(Smi::cast(property_details_raw()));
9606 void set_property_details(PropertyDetails details) {
9607 set_property_details_raw(details.AsSmi());
9610 PropertyCellConstantType GetConstantType();
9612 // Computes the new type of the cell's contents for the given value, but
9613 // without actually modifying the details.
9614 static PropertyCellType UpdatedType(Handle<PropertyCell> cell,
9615 Handle<Object> value,
9616 PropertyDetails details);
9617 static void UpdateCell(Handle<GlobalDictionary> dictionary, int entry,
9618 Handle<Object> value, PropertyDetails details);
9620 static Handle<PropertyCell> InvalidateEntry(
9621 Handle<GlobalDictionary> dictionary, int entry);
9623 static void SetValueWithInvalidation(Handle<PropertyCell> cell,
9624 Handle<Object> new_value);
9626 DECLARE_CAST(PropertyCell)
9628 // Dispatched behavior.
9629 DECLARE_PRINTER(PropertyCell)
9630 DECLARE_VERIFIER(PropertyCell)
9632 // Layout description.
9633 static const int kDetailsOffset = HeapObject::kHeaderSize;
9634 static const int kValueOffset = kDetailsOffset + kPointerSize;
9635 static const int kDependentCodeOffset = kValueOffset + kPointerSize;
9636 static const int kSize = kDependentCodeOffset + kPointerSize;
9638 static const int kPointerFieldsBeginOffset = kValueOffset;
9639 static const int kPointerFieldsEndOffset = kSize;
9641 typedef FixedBodyDescriptor<kValueOffset,
9643 kSize> BodyDescriptor;
9646 DISALLOW_IMPLICIT_CONSTRUCTORS(PropertyCell);
9650 class WeakCell : public HeapObject {
9652 inline Object* value() const;
9654 // This should not be called by anyone except GC.
9655 inline void clear();
9657 // This should not be called by anyone except allocator.
9658 inline void initialize(HeapObject* value);
9660 inline bool cleared() const;
9662 DECL_ACCESSORS(next, Object)
9664 inline void clear_next(Heap* heap);
9666 inline bool next_cleared();
9668 DECLARE_CAST(WeakCell)
9670 DECLARE_PRINTER(WeakCell)
9671 DECLARE_VERIFIER(WeakCell)
9673 // Layout description.
9674 static const int kValueOffset = HeapObject::kHeaderSize;
9675 static const int kNextOffset = kValueOffset + kPointerSize;
9676 static const int kSize = kNextOffset + kPointerSize;
9678 typedef FixedBodyDescriptor<kValueOffset, kSize, kSize> BodyDescriptor;
9681 DISALLOW_IMPLICIT_CONSTRUCTORS(WeakCell);
9685 // The JSProxy describes EcmaScript Harmony proxies
9686 class JSProxy: public JSReceiver {
9688 // [handler]: The handler property.
9689 DECL_ACCESSORS(handler, Object)
9691 // [hash]: The hash code property (undefined if not initialized yet).
9692 DECL_ACCESSORS(hash, Object)
9694 DECLARE_CAST(JSProxy)
9696 MUST_USE_RESULT static MaybeHandle<Object> GetPropertyWithHandler(
9697 Handle<JSProxy> proxy,
9698 Handle<Object> receiver,
9701 // If the handler defines an accessor property with a setter, invoke it.
9702 // If it defines an accessor property without a setter, or a data property
9703 // that is read-only, throw. In all these cases set '*done' to true,
9704 // otherwise set it to false.
9706 static MaybeHandle<Object> SetPropertyViaPrototypesWithHandler(
9707 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9708 Handle<Object> value, LanguageMode language_mode, bool* done);
9710 MUST_USE_RESULT static Maybe<PropertyAttributes>
9711 GetPropertyAttributesWithHandler(Handle<JSProxy> proxy,
9712 Handle<Object> receiver,
9714 MUST_USE_RESULT static MaybeHandle<Object> SetPropertyWithHandler(
9715 Handle<JSProxy> proxy, Handle<Object> receiver, Handle<Name> name,
9716 Handle<Object> value, LanguageMode language_mode);
9718 // Turn the proxy into an (empty) JSObject.
9719 static void Fix(Handle<JSProxy> proxy);
9721 // Initializes the body after the handler slot.
9722 inline void InitializeBody(int object_size, Object* value);
9724 // Invoke a trap by name. If the trap does not exist on this's handler,
9725 // but derived_trap is non-NULL, invoke that instead. May cause GC.
9726 MUST_USE_RESULT static MaybeHandle<Object> CallTrap(
9727 Handle<JSProxy> proxy,
9729 Handle<Object> derived_trap,
9731 Handle<Object> args[]);
9733 // Dispatched behavior.
9734 DECLARE_PRINTER(JSProxy)
9735 DECLARE_VERIFIER(JSProxy)
9737 // Layout description. We add padding so that a proxy has the same
9738 // size as a virgin JSObject. This is essential for becoming a JSObject
9740 static const int kHandlerOffset = HeapObject::kHeaderSize;
9741 static const int kHashOffset = kHandlerOffset + kPointerSize;
9742 static const int kPaddingOffset = kHashOffset + kPointerSize;
9743 static const int kSize = JSObject::kHeaderSize;
9744 static const int kHeaderSize = kPaddingOffset;
9745 static const int kPaddingSize = kSize - kPaddingOffset;
9747 STATIC_ASSERT(kPaddingSize >= 0);
9749 typedef FixedBodyDescriptor<kHandlerOffset,
9751 kSize> BodyDescriptor;
9754 friend class JSReceiver;
9756 MUST_USE_RESULT static Maybe<bool> HasPropertyWithHandler(
9757 Handle<JSProxy> proxy, Handle<Name> name);
9759 MUST_USE_RESULT static MaybeHandle<Object> DeletePropertyWithHandler(
9760 Handle<JSProxy> proxy, Handle<Name> name, LanguageMode language_mode);
9762 MUST_USE_RESULT Object* GetIdentityHash();
9764 static Handle<Smi> GetOrCreateIdentityHash(Handle<JSProxy> proxy);
9766 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
9770 class JSFunctionProxy: public JSProxy {
9772 // [call_trap]: The call trap.
9773 DECL_ACCESSORS(call_trap, Object)
9775 // [construct_trap]: The construct trap.
9776 DECL_ACCESSORS(construct_trap, Object)
9778 DECLARE_CAST(JSFunctionProxy)
9780 // Dispatched behavior.
9781 DECLARE_PRINTER(JSFunctionProxy)
9782 DECLARE_VERIFIER(JSFunctionProxy)
9784 // Layout description.
9785 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
9786 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
9787 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
9788 static const int kSize = JSFunction::kSize;
9789 static const int kPaddingSize = kSize - kPaddingOffset;
9791 STATIC_ASSERT(kPaddingSize >= 0);
9793 typedef FixedBodyDescriptor<kHandlerOffset,
9794 kConstructTrapOffset + kPointerSize,
9795 kSize> BodyDescriptor;
9798 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
9802 class JSCollection : public JSObject {
9804 // [table]: the backing hash table
9805 DECL_ACCESSORS(table, Object)
9807 static const int kTableOffset = JSObject::kHeaderSize;
9808 static const int kSize = kTableOffset + kPointerSize;
9811 DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollection);
9815 // The JSSet describes EcmaScript Harmony sets
9816 class JSSet : public JSCollection {
9820 // Dispatched behavior.
9821 DECLARE_PRINTER(JSSet)
9822 DECLARE_VERIFIER(JSSet)
9825 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
9829 // The JSMap describes EcmaScript Harmony maps
9830 class JSMap : public JSCollection {
9834 // Dispatched behavior.
9835 DECLARE_PRINTER(JSMap)
9836 DECLARE_VERIFIER(JSMap)
9839 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
9843 // OrderedHashTableIterator is an iterator that iterates over the keys and
9844 // values of an OrderedHashTable.
9846 // The iterator has a reference to the underlying OrderedHashTable data,
9847 // [table], as well as the current [index] the iterator is at.
9849 // When the OrderedHashTable is rehashed it adds a reference from the old table
9850 // to the new table as well as storing enough data about the changes so that the
9851 // iterator [index] can be adjusted accordingly.
9853 // When the [Next] result from the iterator is requested, the iterator checks if
9854 // there is a newer table that it needs to transition to.
9855 template<class Derived, class TableType>
9856 class OrderedHashTableIterator: public JSObject {
9858 // [table]: the backing hash table mapping keys to values.
9859 DECL_ACCESSORS(table, Object)
9861 // [index]: The index into the data table.
9862 DECL_ACCESSORS(index, Object)
9864 // [kind]: The kind of iteration this is. One of the [Kind] enum values.
9865 DECL_ACCESSORS(kind, Object)
9868 void OrderedHashTableIteratorPrint(std::ostream& os); // NOLINT
9871 static const int kTableOffset = JSObject::kHeaderSize;
9872 static const int kIndexOffset = kTableOffset + kPointerSize;
9873 static const int kKindOffset = kIndexOffset + kPointerSize;
9874 static const int kSize = kKindOffset + kPointerSize;
9882 // Whether the iterator has more elements. This needs to be called before
9883 // calling |CurrentKey| and/or |CurrentValue|.
9886 // Move the index forward one.
9888 set_index(Smi::FromInt(Smi::cast(index())->value() + 1));
9891 // Populates the array with the next key and value and then moves the iterator
9893 // This returns the |kind| or 0 if the iterator is already at the end.
9894 Smi* Next(JSArray* value_array);
9896 // Returns the current key of the iterator. This should only be called when
9897 // |HasMore| returns true.
9898 inline Object* CurrentKey();
9901 // Transitions the iterator to the non obsolete backing store. This is a NOP
9902 // if the [table] is not obsolete.
9905 DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
9909 class JSSetIterator: public OrderedHashTableIterator<JSSetIterator,
9912 // Dispatched behavior.
9913 DECLARE_PRINTER(JSSetIterator)
9914 DECLARE_VERIFIER(JSSetIterator)
9916 DECLARE_CAST(JSSetIterator)
9918 // Called by |Next| to populate the array. This allows the subclasses to
9919 // populate the array differently.
9920 inline void PopulateValueArray(FixedArray* array);
9923 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSetIterator);
9927 class JSMapIterator: public OrderedHashTableIterator<JSMapIterator,
9930 // Dispatched behavior.
9931 DECLARE_PRINTER(JSMapIterator)
9932 DECLARE_VERIFIER(JSMapIterator)
9934 DECLARE_CAST(JSMapIterator)
9936 // Called by |Next| to populate the array. This allows the subclasses to
9937 // populate the array differently.
9938 inline void PopulateValueArray(FixedArray* array);
9941 // Returns the current value of the iterator. This should only be called when
9942 // |HasMore| returns true.
9943 inline Object* CurrentValue();
9945 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMapIterator);
9949 // Base class for both JSWeakMap and JSWeakSet
9950 class JSWeakCollection: public JSObject {
9952 // [table]: the backing hash table mapping keys to values.
9953 DECL_ACCESSORS(table, Object)
9955 // [next]: linked list of encountered weak maps during GC.
9956 DECL_ACCESSORS(next, Object)
9958 static const int kTableOffset = JSObject::kHeaderSize;
9959 static const int kNextOffset = kTableOffset + kPointerSize;
9960 static const int kSize = kNextOffset + kPointerSize;
9963 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakCollection);
9967 // The JSWeakMap describes EcmaScript Harmony weak maps
9968 class JSWeakMap: public JSWeakCollection {
9970 DECLARE_CAST(JSWeakMap)
9972 // Dispatched behavior.
9973 DECLARE_PRINTER(JSWeakMap)
9974 DECLARE_VERIFIER(JSWeakMap)
9977 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
9981 // The JSWeakSet describes EcmaScript Harmony weak sets
9982 class JSWeakSet: public JSWeakCollection {
9984 DECLARE_CAST(JSWeakSet)
9986 // Dispatched behavior.
9987 DECLARE_PRINTER(JSWeakSet)
9988 DECLARE_VERIFIER(JSWeakSet)
9991 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakSet);
9995 // Whether a JSArrayBuffer is a SharedArrayBuffer or not.
9996 enum class SharedFlag { kNotShared, kShared };
9999 class JSArrayBuffer: public JSObject {
10001 // [backing_store]: backing memory for this array
10002 DECL_ACCESSORS(backing_store, void)
10004 // [byte_length]: length in bytes
10005 DECL_ACCESSORS(byte_length, Object)
10007 inline uint32_t bit_field() const;
10008 inline void set_bit_field(uint32_t bits);
10010 inline bool is_external();
10011 inline void set_is_external(bool value);
10013 inline bool is_neuterable();
10014 inline void set_is_neuterable(bool value);
10016 inline bool was_neutered();
10017 inline void set_was_neutered(bool value);
10019 inline bool is_shared();
10020 inline void set_is_shared(bool value);
10022 DECLARE_CAST(JSArrayBuffer)
10026 // Dispatched behavior.
10027 DECLARE_PRINTER(JSArrayBuffer)
10028 DECLARE_VERIFIER(JSArrayBuffer)
10030 static const int kBackingStoreOffset = JSObject::kHeaderSize;
10031 static const int kByteLengthOffset = kBackingStoreOffset + kPointerSize;
10032 static const int kBitFieldSlot = kByteLengthOffset + kPointerSize;
10033 #if V8_TARGET_LITTLE_ENDIAN || !V8_HOST_ARCH_64_BIT
10034 static const int kBitFieldOffset = kBitFieldSlot;
10036 static const int kBitFieldOffset = kBitFieldSlot + kIntSize;
10038 static const int kSize = kBitFieldSlot + kPointerSize;
10040 static const int kSizeWithInternalFields =
10041 kSize + v8::ArrayBuffer::kInternalFieldCount * kPointerSize;
10043 class IsExternal : public BitField<bool, 1, 1> {};
10044 class IsNeuterable : public BitField<bool, 2, 1> {};
10045 class WasNeutered : public BitField<bool, 3, 1> {};
10046 class IsShared : public BitField<bool, 4, 1> {};
10049 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBuffer);
10053 class JSArrayBufferView: public JSObject {
10055 // [buffer]: ArrayBuffer that this typed array views.
10056 DECL_ACCESSORS(buffer, Object)
10058 // [byte_offset]: offset of typed array in bytes.
10059 DECL_ACCESSORS(byte_offset, Object)
10061 // [byte_length]: length of typed array in bytes.
10062 DECL_ACCESSORS(byte_length, Object)
10064 DECLARE_CAST(JSArrayBufferView)
10066 DECLARE_VERIFIER(JSArrayBufferView)
10068 inline bool WasNeutered() const;
10070 static const int kBufferOffset = JSObject::kHeaderSize;
10071 static const int kByteOffsetOffset = kBufferOffset + kPointerSize;
10072 static const int kByteLengthOffset = kByteOffsetOffset + kPointerSize;
10073 static const int kViewSize = kByteLengthOffset + kPointerSize;
10077 DECL_ACCESSORS(raw_byte_offset, Object)
10078 DECL_ACCESSORS(raw_byte_length, Object)
10081 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArrayBufferView);
10085 class JSTypedArray: public JSArrayBufferView {
10087 // [length]: length of typed array in elements.
10088 DECL_ACCESSORS(length, Object)
10089 inline uint32_t length_value() const;
10091 DECLARE_CAST(JSTypedArray)
10093 ExternalArrayType type();
10094 size_t element_size();
10096 Handle<JSArrayBuffer> GetBuffer();
10098 // Dispatched behavior.
10099 DECLARE_PRINTER(JSTypedArray)
10100 DECLARE_VERIFIER(JSTypedArray)
10102 static const int kLengthOffset = kViewSize + kPointerSize;
10103 static const int kSize = kLengthOffset + kPointerSize;
10105 static const int kSizeWithInternalFields =
10106 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10109 static Handle<JSArrayBuffer> MaterializeArrayBuffer(
10110 Handle<JSTypedArray> typed_array);
10112 DECL_ACCESSORS(raw_length, Object)
10115 DISALLOW_IMPLICIT_CONSTRUCTORS(JSTypedArray);
10119 class JSDataView: public JSArrayBufferView {
10121 DECLARE_CAST(JSDataView)
10123 // Dispatched behavior.
10124 DECLARE_PRINTER(JSDataView)
10125 DECLARE_VERIFIER(JSDataView)
10127 static const int kSize = kViewSize;
10129 static const int kSizeWithInternalFields =
10130 kSize + v8::ArrayBufferView::kInternalFieldCount * kPointerSize;
10133 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDataView);
10137 // Foreign describes objects pointing from JavaScript to C structures.
10138 class Foreign: public HeapObject {
10140 // [address]: field containing the address.
10141 inline Address foreign_address();
10142 inline void set_foreign_address(Address value);
10144 DECLARE_CAST(Foreign)
10146 // Dispatched behavior.
10147 inline void ForeignIterateBody(ObjectVisitor* v);
10149 template<typename StaticVisitor>
10150 inline void ForeignIterateBody();
10152 // Dispatched behavior.
10153 DECLARE_PRINTER(Foreign)
10154 DECLARE_VERIFIER(Foreign)
10156 // Layout description.
10158 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
10159 static const int kSize = kForeignAddressOffset + kPointerSize;
10161 STATIC_ASSERT(kForeignAddressOffset == Internals::kForeignAddressOffset);
10164 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
10168 // The JSArray describes JavaScript Arrays
10169 // Such an array can be in one of two modes:
10170 // - fast, backing storage is a FixedArray and length <= elements.length();
10171 // Please note: push and pop can be used to grow and shrink the array.
10172 // - slow, backing storage is a HashTable with numbers as keys.
10173 class JSArray: public JSObject {
10175 // [length]: The length property.
10176 DECL_ACCESSORS(length, Object)
10178 // Overload the length setter to skip write barrier when the length
10179 // is set to a smi. This matches the set function on FixedArray.
10180 inline void set_length(Smi* length);
10182 static bool HasReadOnlyLength(Handle<JSArray> array);
10183 static bool WouldChangeReadOnlyLength(Handle<JSArray> array, uint32_t index);
10184 static MaybeHandle<Object> ReadOnlyLengthError(Handle<JSArray> array);
10186 // Initialize the array with the given capacity. The function may
10187 // fail due to out-of-memory situations, but only if the requested
10188 // capacity is non-zero.
10189 static void Initialize(Handle<JSArray> array, int capacity, int length = 0);
10191 // If the JSArray has fast elements, and new_length would result in
10192 // normalization, returns true.
10193 bool SetLengthWouldNormalize(uint32_t new_length);
10194 static inline bool SetLengthWouldNormalize(Heap* heap, uint32_t new_length);
10196 // Initializes the array to a certain length.
10197 inline bool AllowsSetLength();
10199 static void SetLength(Handle<JSArray> array, uint32_t length);
10200 // Same as above but will also queue splice records if |array| is observed.
10201 static MaybeHandle<Object> ObservableSetLength(Handle<JSArray> array,
10204 // Set the content of the array to the content of storage.
10205 static inline void SetContent(Handle<JSArray> array,
10206 Handle<FixedArrayBase> storage);
10208 DECLARE_CAST(JSArray)
10210 // Dispatched behavior.
10211 DECLARE_PRINTER(JSArray)
10212 DECLARE_VERIFIER(JSArray)
10214 // Number of element slots to pre-allocate for an empty array.
10215 static const int kPreallocatedArrayElements = 4;
10217 // Layout description.
10218 static const int kLengthOffset = JSObject::kHeaderSize;
10219 static const int kSize = kLengthOffset + kPointerSize;
10222 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
10226 Handle<Object> CacheInitialJSArrayMaps(Handle<Context> native_context,
10227 Handle<Map> initial_map);
10230 // JSRegExpResult is just a JSArray with a specific initial map.
10231 // This initial map adds in-object properties for "index" and "input"
10232 // properties, as assigned by RegExp.prototype.exec, which allows
10233 // faster creation of RegExp exec results.
10234 // This class just holds constants used when creating the result.
10235 // After creation the result must be treated as a JSArray in all regards.
10236 class JSRegExpResult: public JSArray {
10238 // Offsets of object fields.
10239 static const int kIndexOffset = JSArray::kSize;
10240 static const int kInputOffset = kIndexOffset + kPointerSize;
10241 static const int kSize = kInputOffset + kPointerSize;
10242 // Indices of in-object properties.
10243 static const int kIndexIndex = 0;
10244 static const int kInputIndex = 1;
10246 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
10250 class AccessorInfo: public Struct {
10252 DECL_ACCESSORS(name, Object)
10253 DECL_ACCESSORS(flag, Smi)
10254 DECL_ACCESSORS(expected_receiver_type, Object)
10256 inline bool all_can_read();
10257 inline void set_all_can_read(bool value);
10259 inline bool all_can_write();
10260 inline void set_all_can_write(bool value);
10262 inline bool is_special_data_property();
10263 inline void set_is_special_data_property(bool value);
10265 inline PropertyAttributes property_attributes();
10266 inline void set_property_attributes(PropertyAttributes attributes);
10268 // Checks whether the given receiver is compatible with this accessor.
10269 static bool IsCompatibleReceiverMap(Isolate* isolate,
10270 Handle<AccessorInfo> info,
10272 inline bool IsCompatibleReceiver(Object* receiver);
10274 DECLARE_CAST(AccessorInfo)
10276 // Dispatched behavior.
10277 DECLARE_VERIFIER(AccessorInfo)
10279 // Append all descriptors to the array that are not already there.
10280 // Return number added.
10281 static int AppendUnique(Handle<Object> descriptors,
10282 Handle<FixedArray> array,
10283 int valid_descriptors);
10285 static const int kNameOffset = HeapObject::kHeaderSize;
10286 static const int kFlagOffset = kNameOffset + kPointerSize;
10287 static const int kExpectedReceiverTypeOffset = kFlagOffset + kPointerSize;
10288 static const int kSize = kExpectedReceiverTypeOffset + kPointerSize;
10291 inline bool HasExpectedReceiverType() {
10292 return expected_receiver_type()->IsFunctionTemplateInfo();
10294 // Bit positions in flag.
10295 static const int kAllCanReadBit = 0;
10296 static const int kAllCanWriteBit = 1;
10297 static const int kSpecialDataProperty = 2;
10298 class AttributesField : public BitField<PropertyAttributes, 3, 3> {};
10300 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
10304 // An accessor must have a getter, but can have no setter.
10306 // When setting a property, V8 searches accessors in prototypes.
10307 // If an accessor was found and it does not have a setter,
10308 // the request is ignored.
10310 // If the accessor in the prototype has the READ_ONLY property attribute, then
10311 // a new value is added to the derived object when the property is set.
10312 // This shadows the accessor in the prototype.
10313 class ExecutableAccessorInfo: public AccessorInfo {
10315 DECL_ACCESSORS(getter, Object)
10316 DECL_ACCESSORS(setter, Object)
10317 DECL_ACCESSORS(data, Object)
10319 DECLARE_CAST(ExecutableAccessorInfo)
10321 // Dispatched behavior.
10322 DECLARE_PRINTER(ExecutableAccessorInfo)
10323 DECLARE_VERIFIER(ExecutableAccessorInfo)
10325 static const int kGetterOffset = AccessorInfo::kSize;
10326 static const int kSetterOffset = kGetterOffset + kPointerSize;
10327 static const int kDataOffset = kSetterOffset + kPointerSize;
10328 static const int kSize = kDataOffset + kPointerSize;
10330 static void ClearSetter(Handle<ExecutableAccessorInfo> info);
10333 DISALLOW_IMPLICIT_CONSTRUCTORS(ExecutableAccessorInfo);
10337 // Support for JavaScript accessors: A pair of a getter and a setter. Each
10338 // accessor can either be
10339 // * a pointer to a JavaScript function or proxy: a real accessor
10340 // * undefined: considered an accessor by the spec, too, strangely enough
10341 // * the hole: an accessor which has not been set
10342 // * a pointer to a map: a transition used to ensure map sharing
10343 class AccessorPair: public Struct {
10345 DECL_ACCESSORS(getter, Object)
10346 DECL_ACCESSORS(setter, Object)
10348 DECLARE_CAST(AccessorPair)
10350 static Handle<AccessorPair> Copy(Handle<AccessorPair> pair);
10352 Object* get(AccessorComponent component) {
10353 return component == ACCESSOR_GETTER ? getter() : setter();
10356 void set(AccessorComponent component, Object* value) {
10357 if (component == ACCESSOR_GETTER) {
10364 // Note: Returns undefined instead in case of a hole.
10365 Object* GetComponent(AccessorComponent component);
10367 // Set both components, skipping arguments which are a JavaScript null.
10368 void SetComponents(Object* getter, Object* setter) {
10369 if (!getter->IsNull()) set_getter(getter);
10370 if (!setter->IsNull()) set_setter(setter);
10373 bool Equals(AccessorPair* pair) {
10374 return (this == pair) || pair->Equals(getter(), setter());
10377 bool Equals(Object* getter_value, Object* setter_value) {
10378 return (getter() == getter_value) && (setter() == setter_value);
10381 bool ContainsAccessor() {
10382 return IsJSAccessor(getter()) || IsJSAccessor(setter());
10385 // Dispatched behavior.
10386 DECLARE_PRINTER(AccessorPair)
10387 DECLARE_VERIFIER(AccessorPair)
10389 static const int kGetterOffset = HeapObject::kHeaderSize;
10390 static const int kSetterOffset = kGetterOffset + kPointerSize;
10391 static const int kSize = kSetterOffset + kPointerSize;
10394 // Strangely enough, in addition to functions and harmony proxies, the spec
10395 // requires us to consider undefined as a kind of accessor, too:
10397 // Object.defineProperty(obj, "foo", {get: undefined});
10398 // assertTrue("foo" in obj);
10399 bool IsJSAccessor(Object* obj) {
10400 return obj->IsSpecFunction() || obj->IsUndefined();
10403 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
10407 class AccessCheckInfo: public Struct {
10409 DECL_ACCESSORS(named_callback, Object)
10410 DECL_ACCESSORS(indexed_callback, Object)
10411 DECL_ACCESSORS(data, Object)
10413 DECLARE_CAST(AccessCheckInfo)
10415 // Dispatched behavior.
10416 DECLARE_PRINTER(AccessCheckInfo)
10417 DECLARE_VERIFIER(AccessCheckInfo)
10419 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
10420 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
10421 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
10422 static const int kSize = kDataOffset + kPointerSize;
10425 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
10429 class InterceptorInfo: public Struct {
10431 DECL_ACCESSORS(getter, Object)
10432 DECL_ACCESSORS(setter, Object)
10433 DECL_ACCESSORS(query, Object)
10434 DECL_ACCESSORS(deleter, Object)
10435 DECL_ACCESSORS(enumerator, Object)
10436 DECL_ACCESSORS(data, Object)
10437 DECL_BOOLEAN_ACCESSORS(can_intercept_symbols)
10438 DECL_BOOLEAN_ACCESSORS(all_can_read)
10439 DECL_BOOLEAN_ACCESSORS(non_masking)
10441 inline int flags() const;
10442 inline void set_flags(int flags);
10444 DECLARE_CAST(InterceptorInfo)
10446 // Dispatched behavior.
10447 DECLARE_PRINTER(InterceptorInfo)
10448 DECLARE_VERIFIER(InterceptorInfo)
10450 static const int kGetterOffset = HeapObject::kHeaderSize;
10451 static const int kSetterOffset = kGetterOffset + kPointerSize;
10452 static const int kQueryOffset = kSetterOffset + kPointerSize;
10453 static const int kDeleterOffset = kQueryOffset + kPointerSize;
10454 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
10455 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
10456 static const int kFlagsOffset = kDataOffset + kPointerSize;
10457 static const int kSize = kFlagsOffset + kPointerSize;
10459 static const int kCanInterceptSymbolsBit = 0;
10460 static const int kAllCanReadBit = 1;
10461 static const int kNonMasking = 2;
10464 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
10468 class CallHandlerInfo: public Struct {
10470 DECL_ACCESSORS(callback, Object)
10471 DECL_ACCESSORS(data, Object)
10473 DECLARE_CAST(CallHandlerInfo)
10475 // Dispatched behavior.
10476 DECLARE_PRINTER(CallHandlerInfo)
10477 DECLARE_VERIFIER(CallHandlerInfo)
10479 static const int kCallbackOffset = HeapObject::kHeaderSize;
10480 static const int kDataOffset = kCallbackOffset + kPointerSize;
10481 static const int kSize = kDataOffset + kPointerSize;
10484 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
10488 class TemplateInfo: public Struct {
10490 DECL_ACCESSORS(tag, Object)
10491 inline int number_of_properties() const;
10492 inline void set_number_of_properties(int value);
10493 DECL_ACCESSORS(property_list, Object)
10494 DECL_ACCESSORS(property_accessors, Object)
10496 DECLARE_VERIFIER(TemplateInfo)
10498 static const int kTagOffset = HeapObject::kHeaderSize;
10499 static const int kNumberOfProperties = kTagOffset + kPointerSize;
10500 static const int kPropertyListOffset = kNumberOfProperties + kPointerSize;
10501 static const int kPropertyAccessorsOffset =
10502 kPropertyListOffset + kPointerSize;
10503 static const int kHeaderSize = kPropertyAccessorsOffset + kPointerSize;
10506 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
10510 class FunctionTemplateInfo: public TemplateInfo {
10512 DECL_ACCESSORS(serial_number, Object)
10513 DECL_ACCESSORS(call_code, Object)
10514 DECL_ACCESSORS(prototype_template, Object)
10515 DECL_ACCESSORS(parent_template, Object)
10516 DECL_ACCESSORS(named_property_handler, Object)
10517 DECL_ACCESSORS(indexed_property_handler, Object)
10518 DECL_ACCESSORS(instance_template, Object)
10519 DECL_ACCESSORS(class_name, Object)
10520 DECL_ACCESSORS(signature, Object)
10521 DECL_ACCESSORS(instance_call_handler, Object)
10522 DECL_ACCESSORS(access_check_info, Object)
10523 DECL_ACCESSORS(flag, Smi)
10525 inline int length() const;
10526 inline void set_length(int value);
10528 // Following properties use flag bits.
10529 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
10530 DECL_BOOLEAN_ACCESSORS(undetectable)
10531 // If the bit is set, object instances created by this function
10532 // requires access check.
10533 DECL_BOOLEAN_ACCESSORS(needs_access_check)
10534 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
10535 DECL_BOOLEAN_ACCESSORS(remove_prototype)
10536 DECL_BOOLEAN_ACCESSORS(do_not_cache)
10537 DECL_BOOLEAN_ACCESSORS(instantiated)
10538 DECL_BOOLEAN_ACCESSORS(accept_any_receiver)
10540 DECLARE_CAST(FunctionTemplateInfo)
10542 // Dispatched behavior.
10543 DECLARE_PRINTER(FunctionTemplateInfo)
10544 DECLARE_VERIFIER(FunctionTemplateInfo)
10546 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
10547 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
10548 static const int kPrototypeTemplateOffset =
10549 kCallCodeOffset + kPointerSize;
10550 static const int kParentTemplateOffset =
10551 kPrototypeTemplateOffset + kPointerSize;
10552 static const int kNamedPropertyHandlerOffset =
10553 kParentTemplateOffset + kPointerSize;
10554 static const int kIndexedPropertyHandlerOffset =
10555 kNamedPropertyHandlerOffset + kPointerSize;
10556 static const int kInstanceTemplateOffset =
10557 kIndexedPropertyHandlerOffset + kPointerSize;
10558 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
10559 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
10560 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
10561 static const int kAccessCheckInfoOffset =
10562 kInstanceCallHandlerOffset + kPointerSize;
10563 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
10564 static const int kLengthOffset = kFlagOffset + kPointerSize;
10565 static const int kSize = kLengthOffset + kPointerSize;
10567 // Returns true if |object| is an instance of this function template.
10568 bool IsTemplateFor(Object* object);
10569 bool IsTemplateFor(Map* map);
10571 // Returns the holder JSObject if the function can legally be called with this
10572 // receiver. Returns Heap::null_value() if the call is illegal.
10573 Object* GetCompatibleReceiver(Isolate* isolate, Object* receiver);
10576 // Bit position in the flag, from least significant bit position.
10577 static const int kHiddenPrototypeBit = 0;
10578 static const int kUndetectableBit = 1;
10579 static const int kNeedsAccessCheckBit = 2;
10580 static const int kReadOnlyPrototypeBit = 3;
10581 static const int kRemovePrototypeBit = 4;
10582 static const int kDoNotCacheBit = 5;
10583 static const int kInstantiatedBit = 6;
10584 static const int kAcceptAnyReceiver = 7;
10586 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
10590 class ObjectTemplateInfo: public TemplateInfo {
10592 DECL_ACCESSORS(constructor, Object)
10593 DECL_ACCESSORS(internal_field_count, Object)
10595 DECLARE_CAST(ObjectTemplateInfo)
10597 // Dispatched behavior.
10598 DECLARE_PRINTER(ObjectTemplateInfo)
10599 DECLARE_VERIFIER(ObjectTemplateInfo)
10601 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
10602 static const int kInternalFieldCountOffset =
10603 kConstructorOffset + kPointerSize;
10604 static const int kSize = kInternalFieldCountOffset + kPointerSize;
10608 class TypeSwitchInfo: public Struct {
10610 DECL_ACCESSORS(types, Object)
10612 DECLARE_CAST(TypeSwitchInfo)
10614 // Dispatched behavior.
10615 DECLARE_PRINTER(TypeSwitchInfo)
10616 DECLARE_VERIFIER(TypeSwitchInfo)
10618 static const int kTypesOffset = Struct::kHeaderSize;
10619 static const int kSize = kTypesOffset + kPointerSize;
10623 // The DebugInfo class holds additional information for a function being
10625 class DebugInfo: public Struct {
10627 // The shared function info for the source being debugged.
10628 DECL_ACCESSORS(shared, SharedFunctionInfo)
10629 // Code object for the patched code. This code object is the code object
10630 // currently active for the function.
10631 DECL_ACCESSORS(code, Code)
10632 // Fixed array holding status information for each active break point.
10633 DECL_ACCESSORS(break_points, FixedArray)
10635 // Check if there is a break point at a code position.
10636 bool HasBreakPoint(int code_position);
10637 // Get the break point info object for a code position.
10638 Object* GetBreakPointInfo(int code_position);
10639 // Clear a break point.
10640 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
10642 Handle<Object> break_point_object);
10643 // Set a break point.
10644 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
10645 int source_position, int statement_position,
10646 Handle<Object> break_point_object);
10647 // Get the break point objects for a code position.
10648 Handle<Object> GetBreakPointObjects(int code_position);
10649 // Find the break point info holding this break point object.
10650 static Handle<Object> FindBreakPointInfo(Handle<DebugInfo> debug_info,
10651 Handle<Object> break_point_object);
10652 // Get the number of break points for this function.
10653 int GetBreakPointCount();
10655 DECLARE_CAST(DebugInfo)
10657 // Dispatched behavior.
10658 DECLARE_PRINTER(DebugInfo)
10659 DECLARE_VERIFIER(DebugInfo)
10661 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
10662 static const int kCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
10663 static const int kBreakPointsStateIndex = kCodeIndex + kPointerSize;
10664 static const int kSize = kBreakPointsStateIndex + kPointerSize;
10666 static const int kEstimatedNofBreakPointsInFunction = 16;
10669 static const int kNoBreakPointInfo = -1;
10671 // Lookup the index in the break_points array for a code position.
10672 int GetBreakPointInfoIndex(int code_position);
10674 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
10678 // The BreakPointInfo class holds information for break points set in a
10679 // function. The DebugInfo object holds a BreakPointInfo object for each code
10680 // position with one or more break points.
10681 class BreakPointInfo: public Struct {
10683 // The position in the code for the break point.
10684 DECL_ACCESSORS(code_position, Smi)
10685 // The position in the source for the break position.
10686 DECL_ACCESSORS(source_position, Smi)
10687 // The position in the source for the last statement before this break
10689 DECL_ACCESSORS(statement_position, Smi)
10690 // List of related JavaScript break points.
10691 DECL_ACCESSORS(break_point_objects, Object)
10693 // Removes a break point.
10694 static void ClearBreakPoint(Handle<BreakPointInfo> info,
10695 Handle<Object> break_point_object);
10696 // Set a break point.
10697 static void SetBreakPoint(Handle<BreakPointInfo> info,
10698 Handle<Object> break_point_object);
10699 // Check if break point info has this break point object.
10700 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
10701 Handle<Object> break_point_object);
10702 // Get the number of break points for this code position.
10703 int GetBreakPointCount();
10705 DECLARE_CAST(BreakPointInfo)
10707 // Dispatched behavior.
10708 DECLARE_PRINTER(BreakPointInfo)
10709 DECLARE_VERIFIER(BreakPointInfo)
10711 static const int kCodePositionIndex = Struct::kHeaderSize;
10712 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
10713 static const int kStatementPositionIndex =
10714 kSourcePositionIndex + kPointerSize;
10715 static const int kBreakPointObjectsIndex =
10716 kStatementPositionIndex + kPointerSize;
10717 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
10720 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
10724 #undef DECL_BOOLEAN_ACCESSORS
10725 #undef DECL_ACCESSORS
10726 #undef DECLARE_CAST
10727 #undef DECLARE_VERIFIER
10729 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
10730 V(kStringTable, "string_table", "(Internalized strings)") \
10731 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
10732 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
10733 V(kSmiRootList, "smi_root_list", "(Smi roots)") \
10734 V(kInternalizedString, "internalized_string", "(Internal string)") \
10735 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
10736 V(kTop, "top", "(Isolate)") \
10737 V(kRelocatable, "relocatable", "(Relocatable)") \
10738 V(kDebug, "debug", "(Debugger)") \
10739 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
10740 V(kHandleScope, "handlescope", "(Handle scope)") \
10741 V(kBuiltins, "builtins", "(Builtins)") \
10742 V(kGlobalHandles, "globalhandles", "(Global handles)") \
10743 V(kEternalHandles, "eternalhandles", "(Eternal handles)") \
10744 V(kThreadManager, "threadmanager", "(Thread manager)") \
10745 V(kStrongRoots, "strong roots", "(Strong roots)") \
10746 V(kExtensions, "Extensions", "(Extensions)")
10748 class VisitorSynchronization : public AllStatic {
10750 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
10752 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
10755 #undef DECLARE_ENUM
10757 static const char* const kTags[kNumberOfSyncTags];
10758 static const char* const kTagNames[kNumberOfSyncTags];
10761 // Abstract base class for visiting, and optionally modifying, the
10762 // pointers contained in Objects. Used in GC and serialization/deserialization.
10763 class ObjectVisitor BASE_EMBEDDED {
10765 virtual ~ObjectVisitor() {}
10767 // Visits a contiguous arrays of pointers in the half-open range
10768 // [start, end). Any or all of the values may be modified on return.
10769 virtual void VisitPointers(Object** start, Object** end) = 0;
10771 // Handy shorthand for visiting a single pointer.
10772 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
10774 // Visit weak next_code_link in Code object.
10775 virtual void VisitNextCodeLink(Object** p) { VisitPointers(p, p + 1); }
10777 // To allow lazy clearing of inline caches the visitor has
10778 // a rich interface for iterating over Code objects..
10780 // Visits a code target in the instruction stream.
10781 virtual void VisitCodeTarget(RelocInfo* rinfo);
10783 // Visits a code entry in a JS function.
10784 virtual void VisitCodeEntry(Address entry_address);
10786 // Visits a global property cell reference in the instruction stream.
10787 virtual void VisitCell(RelocInfo* rinfo);
10789 // Visits a runtime entry in the instruction stream.
10790 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
10792 // Visits the resource of an one-byte or two-byte string.
10793 virtual void VisitExternalOneByteString(
10794 v8::String::ExternalOneByteStringResource** resource) {}
10795 virtual void VisitExternalTwoByteString(
10796 v8::String::ExternalStringResource** resource) {}
10798 // Visits a debug call target in the instruction stream.
10799 virtual void VisitDebugTarget(RelocInfo* rinfo);
10801 // Visits the byte sequence in a function's prologue that contains information
10802 // about the code's age.
10803 virtual void VisitCodeAgeSequence(RelocInfo* rinfo);
10805 // Visit pointer embedded into a code object.
10806 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
10808 // Visits an external reference embedded into a code object.
10809 virtual void VisitExternalReference(RelocInfo* rinfo);
10811 // Visits an external reference.
10812 virtual void VisitExternalReference(Address* p) {}
10814 // Visits an (encoded) internal reference.
10815 virtual void VisitInternalReference(RelocInfo* rinfo) {}
10817 // Visits a handle that has an embedder-assigned class ID.
10818 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
10820 // Intended for serialization/deserialization checking: insert, or
10821 // check for the presence of, a tag at this position in the stream.
10822 // Also used for marking up GC roots in heap snapshots.
10823 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
10827 class StructBodyDescriptor : public
10828 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
10830 static inline int SizeOf(Map* map, HeapObject* object) {
10831 return map->instance_size();
10836 // BooleanBit is a helper class for setting and getting a bit in an
10838 class BooleanBit : public AllStatic {
10840 static inline bool get(Smi* smi, int bit_position) {
10841 return get(smi->value(), bit_position);
10844 static inline bool get(int value, int bit_position) {
10845 return (value & (1 << bit_position)) != 0;
10848 static inline Smi* set(Smi* smi, int bit_position, bool v) {
10849 return Smi::FromInt(set(smi->value(), bit_position, v));
10852 static inline int set(int value, int bit_position, bool v) {
10854 value |= (1 << bit_position);
10856 value &= ~(1 << bit_position);
10862 } } // namespace v8::internal
10864 #endif // V8_OBJECTS_H_