1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "allocation.h"
34 #include "property-details.h"
35 #include "smart-array-pointer.h"
36 #include "unicode-inl.h"
37 #if V8_TARGET_ARCH_ARM
38 #include "arm/constants-arm.h"
39 #elif V8_TARGET_ARCH_MIPS
40 #include "mips/constants-mips.h"
46 // Most object types in the V8 JavaScript are described in this file.
48 // Inheritance hierarchy:
49 // - MaybeObject (an object or a failure)
50 // - Failure (immediate for marking failed operation)
52 // - Smi (immediate small integer)
53 // - HeapObject (superclass for everything allocated in the heap)
54 // - JSReceiver (suitable for property access)
78 // - CompilationCacheTable
79 // - CodeCacheHashTable
82 // - JSFunctionResultCache
86 // - ExternalPixelArray
87 // - ExternalByteArray
88 // - ExternalUnsignedByteArray
89 // - ExternalShortArray
90 // - ExternalUnsignedShortArray
92 // - ExternalUnsignedIntArray
93 // - ExternalFloatArray
101 // - ExternalAsciiString
102 // - ExternalTwoByteString
108 // - SharedFunctionInfo
116 // - FunctionTemplateInfo
117 // - ObjectTemplateInfo
125 // Formats of Object*:
126 // Smi: [31 bit signed int] 0
127 // HeapObject: [32 bit direct pointer] (4 byte aligned) | 01
128 // Failure: [30 bit signed int] 11
134 // The "fast" kind for elements that only contain SMI values. Must be first
135 // to make it possible to efficiently check maps for this kind.
136 FAST_SMI_ONLY_ELEMENTS,
138 // The "fast" kind for tagged values. Must be second to make it possible to
139 // efficiently check maps for this and the FAST_SMI_ONLY_ELEMENTS kind
143 // The "fast" kind for unwrapped, non-tagged double values.
144 FAST_DOUBLE_ELEMENTS,
148 NON_STRICT_ARGUMENTS_ELEMENTS,
149 // The "fast" kind for external arrays
150 EXTERNAL_BYTE_ELEMENTS,
151 EXTERNAL_UNSIGNED_BYTE_ELEMENTS,
152 EXTERNAL_SHORT_ELEMENTS,
153 EXTERNAL_UNSIGNED_SHORT_ELEMENTS,
154 EXTERNAL_INT_ELEMENTS,
155 EXTERNAL_UNSIGNED_INT_ELEMENTS,
156 EXTERNAL_FLOAT_ELEMENTS,
157 EXTERNAL_DOUBLE_ELEMENTS,
158 EXTERNAL_PIXEL_ELEMENTS,
160 // Derived constants from ElementsKind
161 FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND = EXTERNAL_BYTE_ELEMENTS,
162 LAST_EXTERNAL_ARRAY_ELEMENTS_KIND = EXTERNAL_PIXEL_ELEMENTS,
163 FIRST_ELEMENTS_KIND = FAST_SMI_ONLY_ELEMENTS,
164 LAST_ELEMENTS_KIND = EXTERNAL_PIXEL_ELEMENTS
167 enum CompareMapMode {
169 ALLOW_ELEMENT_TRANSITION_MAPS
172 enum KeyedAccessGrowMode {
173 DO_NOT_ALLOW_JSARRAY_GROWTH,
177 const int kElementsKindCount = LAST_ELEMENTS_KIND - FIRST_ELEMENTS_KIND + 1;
179 void PrintElementsKind(FILE* out, ElementsKind kind);
181 inline bool IsMoreGeneralElementsKindTransition(ElementsKind from_kind,
182 ElementsKind to_kind);
184 // Setter that skips the write barrier if mode is SKIP_WRITE_BARRIER.
185 enum WriteBarrierMode { SKIP_WRITE_BARRIER, UPDATE_WRITE_BARRIER };
188 // PropertyNormalizationMode is used to specify whether to keep
189 // inobject properties when normalizing properties of a JSObject.
190 enum PropertyNormalizationMode {
191 CLEAR_INOBJECT_PROPERTIES,
192 KEEP_INOBJECT_PROPERTIES
196 // NormalizedMapSharingMode is used to specify whether a map may be shared
197 // by different objects with normalized properties.
198 enum NormalizedMapSharingMode {
199 UNIQUE_NORMALIZED_MAP,
200 SHARED_NORMALIZED_MAP
204 // Indicates whether a get method should implicitly create the object looked up.
211 // Instance size sentinel for objects of variable size.
212 const int kVariableSizeSentinel = 0;
215 // All Maps have a field instance_type containing a InstanceType.
216 // It describes the type of the instances.
218 // As an example, a JavaScript object is a heap object and its map
219 // instance_type is JS_OBJECT_TYPE.
221 // The names of the string instance types are intended to systematically
222 // mirror their encoding in the instance_type field of the map. The default
223 // encoding is considered TWO_BYTE. It is not mentioned in the name. ASCII
224 // encoding is mentioned explicitly in the name. Likewise, the default
225 // representation is considered sequential. It is not mentioned in the
226 // name. The other representations (e.g. CONS, EXTERNAL) are explicitly
227 // mentioned. Finally, the string is either a SYMBOL_TYPE (if it is a
228 // symbol) or a STRING_TYPE (if it is not a symbol).
230 // NOTE: The following things are some that depend on the string types having
231 // instance_types that are less than those of all other types:
232 // HeapObject::Size, HeapObject::IterateBody, the typeof operator, and
235 // NOTE: Everything following JS_VALUE_TYPE is considered a
236 // JSObject for GC purposes. The first four entries here have typeof
237 // 'object', whereas JS_FUNCTION_TYPE has typeof 'function'.
238 #define INSTANCE_TYPE_LIST_ALL(V) \
240 V(ASCII_SYMBOL_TYPE) \
241 V(CONS_SYMBOL_TYPE) \
242 V(CONS_ASCII_SYMBOL_TYPE) \
243 V(EXTERNAL_SYMBOL_TYPE) \
244 V(EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE) \
245 V(EXTERNAL_ASCII_SYMBOL_TYPE) \
246 V(SHORT_EXTERNAL_SYMBOL_TYPE) \
247 V(SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE) \
248 V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE) \
250 V(ASCII_STRING_TYPE) \
251 V(CONS_STRING_TYPE) \
252 V(CONS_ASCII_STRING_TYPE) \
253 V(SLICED_STRING_TYPE) \
254 V(EXTERNAL_STRING_TYPE) \
255 V(EXTERNAL_STRING_WITH_ASCII_DATA_TYPE) \
256 V(EXTERNAL_ASCII_STRING_TYPE) \
257 V(SHORT_EXTERNAL_STRING_TYPE) \
258 V(SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE) \
259 V(SHORT_EXTERNAL_ASCII_STRING_TYPE) \
260 V(PRIVATE_EXTERNAL_ASCII_STRING_TYPE) \
265 V(JS_GLOBAL_PROPERTY_CELL_TYPE) \
267 V(HEAP_NUMBER_TYPE) \
271 /* Note: the order of these external array */ \
272 /* types is relied upon in */ \
273 /* Object::IsExternalArray(). */ \
274 V(EXTERNAL_BYTE_ARRAY_TYPE) \
275 V(EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE) \
276 V(EXTERNAL_SHORT_ARRAY_TYPE) \
277 V(EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE) \
278 V(EXTERNAL_INT_ARRAY_TYPE) \
279 V(EXTERNAL_UNSIGNED_INT_ARRAY_TYPE) \
280 V(EXTERNAL_FLOAT_ARRAY_TYPE) \
281 V(EXTERNAL_PIXEL_ARRAY_TYPE) \
284 V(ACCESSOR_INFO_TYPE) \
285 V(ACCESSOR_PAIR_TYPE) \
286 V(ACCESS_CHECK_INFO_TYPE) \
287 V(INTERCEPTOR_INFO_TYPE) \
288 V(CALL_HANDLER_INFO_TYPE) \
289 V(FUNCTION_TEMPLATE_INFO_TYPE) \
290 V(OBJECT_TEMPLATE_INFO_TYPE) \
291 V(SIGNATURE_INFO_TYPE) \
292 V(TYPE_SWITCH_INFO_TYPE) \
295 V(POLYMORPHIC_CODE_CACHE_TYPE) \
296 V(TYPE_FEEDBACK_INFO_TYPE) \
297 V(ALIASED_ARGUMENTS_ENTRY_TYPE) \
299 V(FIXED_ARRAY_TYPE) \
300 V(FIXED_DOUBLE_ARRAY_TYPE) \
301 V(SHARED_FUNCTION_INFO_TYPE) \
303 V(JS_MESSAGE_OBJECT_TYPE) \
308 V(JS_CONTEXT_EXTENSION_OBJECT_TYPE) \
309 V(JS_GLOBAL_OBJECT_TYPE) \
310 V(JS_BUILTINS_OBJECT_TYPE) \
311 V(JS_GLOBAL_PROXY_TYPE) \
314 V(JS_WEAK_MAP_TYPE) \
317 V(JS_FUNCTION_TYPE) \
318 V(JS_FUNCTION_PROXY_TYPE) \
320 #ifdef ENABLE_DEBUGGER_SUPPORT
321 #define INSTANCE_TYPE_LIST_DEBUGGER(V) \
323 V(BREAK_POINT_INFO_TYPE)
325 #define INSTANCE_TYPE_LIST_DEBUGGER(V)
328 #define INSTANCE_TYPE_LIST(V) \
329 INSTANCE_TYPE_LIST_ALL(V) \
330 INSTANCE_TYPE_LIST_DEBUGGER(V)
333 // Since string types are not consecutive, this macro is used to
334 // iterate over them.
335 #define STRING_TYPE_LIST(V) \
337 kVariableSizeSentinel, \
340 V(ASCII_SYMBOL_TYPE, \
341 kVariableSizeSentinel, \
344 V(CONS_SYMBOL_TYPE, \
348 V(CONS_ASCII_SYMBOL_TYPE, \
352 V(EXTERNAL_SYMBOL_TYPE, \
353 ExternalTwoByteString::kSize, \
356 V(EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE, \
357 ExternalTwoByteString::kSize, \
358 external_symbol_with_ascii_data, \
359 ExternalSymbolWithAsciiData) \
360 V(EXTERNAL_ASCII_SYMBOL_TYPE, \
361 ExternalAsciiString::kSize, \
362 external_ascii_symbol, \
363 ExternalAsciiSymbol) \
364 V(SHORT_EXTERNAL_SYMBOL_TYPE, \
365 ExternalTwoByteString::kShortSize, \
366 short_external_symbol, \
367 ShortExternalSymbol) \
368 V(SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE, \
369 ExternalTwoByteString::kShortSize, \
370 short_external_symbol_with_ascii_data, \
371 ShortExternalSymbolWithAsciiData) \
372 V(SHORT_EXTERNAL_ASCII_SYMBOL_TYPE, \
373 ExternalAsciiString::kShortSize, \
374 short_external_ascii_symbol, \
375 ShortExternalAsciiSymbol) \
377 kVariableSizeSentinel, \
380 V(ASCII_STRING_TYPE, \
381 kVariableSizeSentinel, \
384 V(CONS_STRING_TYPE, \
388 V(CONS_ASCII_STRING_TYPE, \
392 V(SLICED_STRING_TYPE, \
393 SlicedString::kSize, \
396 V(SLICED_ASCII_STRING_TYPE, \
397 SlicedString::kSize, \
398 sliced_ascii_string, \
400 V(EXTERNAL_STRING_TYPE, \
401 ExternalTwoByteString::kSize, \
404 V(EXTERNAL_STRING_WITH_ASCII_DATA_TYPE, \
405 ExternalTwoByteString::kSize, \
406 external_string_with_ascii_data, \
407 ExternalStringWithAsciiData) \
408 V(EXTERNAL_ASCII_STRING_TYPE, \
409 ExternalAsciiString::kSize, \
410 external_ascii_string, \
411 ExternalAsciiString) \
412 V(SHORT_EXTERNAL_STRING_TYPE, \
413 ExternalTwoByteString::kShortSize, \
414 short_external_string, \
415 ShortExternalString) \
416 V(SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE, \
417 ExternalTwoByteString::kShortSize, \
418 short_external_string_with_ascii_data, \
419 ShortExternalStringWithAsciiData) \
420 V(SHORT_EXTERNAL_ASCII_STRING_TYPE, \
421 ExternalAsciiString::kShortSize, \
422 short_external_ascii_string, \
423 ShortExternalAsciiString)
425 // A struct is a simple object a set of object-valued fields. Including an
426 // object type in this causes the compiler to generate most of the boilerplate
427 // code for the class including allocation and garbage collection routines,
428 // casts and predicates. All you need to define is the class, methods and
429 // object verification routines. Easy, no?
431 // Note that for subtle reasons related to the ordering or numerical values of
432 // type tags, elements in this list have to be added to the INSTANCE_TYPE_LIST
434 #define STRUCT_LIST_ALL(V) \
435 V(ACCESSOR_INFO, AccessorInfo, accessor_info) \
436 V(ACCESSOR_PAIR, AccessorPair, accessor_pair) \
437 V(ACCESS_CHECK_INFO, AccessCheckInfo, access_check_info) \
438 V(INTERCEPTOR_INFO, InterceptorInfo, interceptor_info) \
439 V(CALL_HANDLER_INFO, CallHandlerInfo, call_handler_info) \
440 V(FUNCTION_TEMPLATE_INFO, FunctionTemplateInfo, function_template_info) \
441 V(OBJECT_TEMPLATE_INFO, ObjectTemplateInfo, object_template_info) \
442 V(SIGNATURE_INFO, SignatureInfo, signature_info) \
443 V(TYPE_SWITCH_INFO, TypeSwitchInfo, type_switch_info) \
444 V(SCRIPT, Script, script) \
445 V(CODE_CACHE, CodeCache, code_cache) \
446 V(POLYMORPHIC_CODE_CACHE, PolymorphicCodeCache, polymorphic_code_cache) \
447 V(TYPE_FEEDBACK_INFO, TypeFeedbackInfo, type_feedback_info) \
448 V(ALIASED_ARGUMENTS_ENTRY, AliasedArgumentsEntry, aliased_arguments_entry)
450 #ifdef ENABLE_DEBUGGER_SUPPORT
451 #define STRUCT_LIST_DEBUGGER(V) \
452 V(DEBUG_INFO, DebugInfo, debug_info) \
453 V(BREAK_POINT_INFO, BreakPointInfo, break_point_info)
455 #define STRUCT_LIST_DEBUGGER(V)
458 #define STRUCT_LIST(V) \
460 STRUCT_LIST_DEBUGGER(V)
462 // We use the full 8 bits of the instance_type field to encode heap object
463 // instance types. The high-order bit (bit 7) is set if the object is not a
464 // string, and cleared if it is a string.
465 const uint32_t kIsNotStringMask = 0x80;
466 const uint32_t kStringTag = 0x0;
467 const uint32_t kNotStringTag = 0x80;
469 // Bit 6 indicates that the object is a symbol (if set) or not (if cleared).
470 // There are not enough types that the non-string types (with bit 7 set) can
471 // have bit 6 set too.
472 const uint32_t kIsSymbolMask = 0x40;
473 const uint32_t kNotSymbolTag = 0x0;
474 const uint32_t kSymbolTag = 0x40;
476 // If bit 7 is clear then bit 2 indicates whether the string consists of
477 // two-byte characters or one-byte characters.
478 const uint32_t kStringEncodingMask = 0x4;
479 const uint32_t kTwoByteStringTag = 0x0;
480 const uint32_t kAsciiStringTag = 0x4;
482 // If bit 7 is clear, the low-order 2 bits indicate the representation
484 const uint32_t kStringRepresentationMask = 0x03;
485 enum StringRepresentationTag {
487 kConsStringTag = 0x1,
488 kExternalStringTag = 0x2,
489 kSlicedStringTag = 0x3
491 const uint32_t kIsIndirectStringMask = 0x1;
492 const uint32_t kIsIndirectStringTag = 0x1;
493 STATIC_ASSERT((kSeqStringTag & kIsIndirectStringMask) == 0);
494 STATIC_ASSERT((kExternalStringTag & kIsIndirectStringMask) == 0);
496 (kConsStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
498 (kSlicedStringTag & kIsIndirectStringMask) == kIsIndirectStringTag);
500 // Use this mask to distinguish between cons and slice only after making
501 // sure that the string is one of the two (an indirect string).
502 const uint32_t kSlicedNotConsMask = kSlicedStringTag & ~kConsStringTag;
503 STATIC_ASSERT(IS_POWER_OF_TWO(kSlicedNotConsMask) && kSlicedNotConsMask != 0);
505 // If bit 7 is clear, then bit 3 indicates whether this two-byte
506 // string actually contains ASCII data.
507 const uint32_t kAsciiDataHintMask = 0x08;
508 const uint32_t kAsciiDataHintTag = 0x08;
510 // If bit 7 is clear and string representation indicates an external string,
511 // then bit 4 indicates whether the data pointer is cached.
512 const uint32_t kShortExternalStringMask = 0x10;
513 const uint32_t kShortExternalStringTag = 0x10;
516 // A ConsString with an empty string as the right side is a candidate
517 // for being shortcut by the garbage collector unless it is a
518 // symbol. It's not common to have non-flat symbols, so we do not
519 // shortcut them thereby avoiding turning symbols into strings. See
520 // heap.cc and mark-compact.cc.
521 const uint32_t kShortcutTypeMask =
524 kStringRepresentationMask;
525 const uint32_t kShortcutTypeTag = kConsStringTag;
530 SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kSeqStringTag,
531 ASCII_SYMBOL_TYPE = kAsciiStringTag | kSymbolTag | kSeqStringTag,
532 CONS_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kConsStringTag,
533 CONS_ASCII_SYMBOL_TYPE = kAsciiStringTag | kSymbolTag | kConsStringTag,
534 SHORT_EXTERNAL_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag |
535 kExternalStringTag | kShortExternalStringTag,
536 SHORT_EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE =
537 kTwoByteStringTag | kSymbolTag | kExternalStringTag |
538 kAsciiDataHintTag | kShortExternalStringTag,
539 SHORT_EXTERNAL_ASCII_SYMBOL_TYPE = kAsciiStringTag | kExternalStringTag |
540 kSymbolTag | kShortExternalStringTag,
541 EXTERNAL_SYMBOL_TYPE = kTwoByteStringTag | kSymbolTag | kExternalStringTag,
542 EXTERNAL_SYMBOL_WITH_ASCII_DATA_TYPE =
543 kTwoByteStringTag | kSymbolTag | kExternalStringTag | kAsciiDataHintTag,
544 EXTERNAL_ASCII_SYMBOL_TYPE =
545 kAsciiStringTag | kSymbolTag | kExternalStringTag,
546 STRING_TYPE = kTwoByteStringTag | kSeqStringTag,
547 ASCII_STRING_TYPE = kAsciiStringTag | kSeqStringTag,
548 CONS_STRING_TYPE = kTwoByteStringTag | kConsStringTag,
549 CONS_ASCII_STRING_TYPE = kAsciiStringTag | kConsStringTag,
550 SLICED_STRING_TYPE = kTwoByteStringTag | kSlicedStringTag,
551 SLICED_ASCII_STRING_TYPE = kAsciiStringTag | kSlicedStringTag,
552 SHORT_EXTERNAL_STRING_TYPE =
553 kTwoByteStringTag | kExternalStringTag | kShortExternalStringTag,
554 SHORT_EXTERNAL_STRING_WITH_ASCII_DATA_TYPE =
555 kTwoByteStringTag | kExternalStringTag |
556 kAsciiDataHintTag | kShortExternalStringTag,
557 SHORT_EXTERNAL_ASCII_STRING_TYPE =
558 kAsciiStringTag | kExternalStringTag | kShortExternalStringTag,
559 EXTERNAL_STRING_TYPE = kTwoByteStringTag | kExternalStringTag,
560 EXTERNAL_STRING_WITH_ASCII_DATA_TYPE =
561 kTwoByteStringTag | kExternalStringTag | kAsciiDataHintTag,
563 EXTERNAL_ASCII_STRING_TYPE = kAsciiStringTag | kExternalStringTag,
564 PRIVATE_EXTERNAL_ASCII_STRING_TYPE = EXTERNAL_ASCII_STRING_TYPE,
566 // Objects allocated in their own spaces (never in new space).
567 MAP_TYPE = kNotStringTag, // FIRST_NONSTRING_TYPE
570 JS_GLOBAL_PROPERTY_CELL_TYPE,
572 // "Data", objects that cannot contain non-map-word pointers to heap
578 EXTERNAL_BYTE_ARRAY_TYPE, // FIRST_EXTERNAL_ARRAY_TYPE
579 EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE,
580 EXTERNAL_SHORT_ARRAY_TYPE,
581 EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE,
582 EXTERNAL_INT_ARRAY_TYPE,
583 EXTERNAL_UNSIGNED_INT_ARRAY_TYPE,
584 EXTERNAL_FLOAT_ARRAY_TYPE,
585 EXTERNAL_DOUBLE_ARRAY_TYPE,
586 EXTERNAL_PIXEL_ARRAY_TYPE, // LAST_EXTERNAL_ARRAY_TYPE
587 FIXED_DOUBLE_ARRAY_TYPE,
588 FILLER_TYPE, // LAST_DATA_TYPE
593 ACCESS_CHECK_INFO_TYPE,
594 INTERCEPTOR_INFO_TYPE,
595 CALL_HANDLER_INFO_TYPE,
596 FUNCTION_TEMPLATE_INFO_TYPE,
597 OBJECT_TEMPLATE_INFO_TYPE,
599 TYPE_SWITCH_INFO_TYPE,
602 POLYMORPHIC_CODE_CACHE_TYPE,
603 TYPE_FEEDBACK_INFO_TYPE,
604 ALIASED_ARGUMENTS_ENTRY_TYPE,
605 // The following two instance types are only used when ENABLE_DEBUGGER_SUPPORT
606 // is defined. However as include/v8.h contain some of the instance type
607 // constants always having them avoids them getting different numbers
608 // depending on whether ENABLE_DEBUGGER_SUPPORT is defined or not.
610 BREAK_POINT_INFO_TYPE,
613 SHARED_FUNCTION_INFO_TYPE,
615 JS_MESSAGE_OBJECT_TYPE,
617 // All the following types are subtypes of JSReceiver, which corresponds to
618 // objects in the JS sense. The first and the last type in this range are
619 // the two forms of function. This organization enables using the same
620 // compares for checking the JS_RECEIVER/SPEC_OBJECT range and the
621 // NONCALLABLE_JS_OBJECT range.
622 JS_FUNCTION_PROXY_TYPE, // FIRST_JS_RECEIVER_TYPE, FIRST_JS_PROXY_TYPE
623 JS_PROXY_TYPE, // LAST_JS_PROXY_TYPE
625 JS_VALUE_TYPE, // FIRST_JS_OBJECT_TYPE
628 JS_CONTEXT_EXTENSION_OBJECT_TYPE,
629 JS_GLOBAL_OBJECT_TYPE,
630 JS_BUILTINS_OBJECT_TYPE,
631 JS_GLOBAL_PROXY_TYPE,
639 JS_FUNCTION_TYPE, // LAST_JS_OBJECT_TYPE, LAST_JS_RECEIVER_TYPE
643 LAST_TYPE = JS_FUNCTION_TYPE,
644 INVALID_TYPE = FIRST_TYPE - 1,
645 FIRST_NONSTRING_TYPE = MAP_TYPE,
646 // Boundaries for testing for an external array.
647 FIRST_EXTERNAL_ARRAY_TYPE = EXTERNAL_BYTE_ARRAY_TYPE,
648 LAST_EXTERNAL_ARRAY_TYPE = EXTERNAL_PIXEL_ARRAY_TYPE,
649 // Boundary for promotion to old data space/old pointer space.
650 LAST_DATA_TYPE = FILLER_TYPE,
651 // Boundary for objects represented as JSReceiver (i.e. JSObject or JSProxy).
652 // Note that there is no range for JSObject or JSProxy, since their subtypes
653 // are not continuous in this enum! The enum ranges instead reflect the
654 // external class names, where proxies are treated as either ordinary objects,
656 FIRST_JS_RECEIVER_TYPE = JS_FUNCTION_PROXY_TYPE,
657 LAST_JS_RECEIVER_TYPE = LAST_TYPE,
658 // Boundaries for testing the types represented as JSObject
659 FIRST_JS_OBJECT_TYPE = JS_VALUE_TYPE,
660 LAST_JS_OBJECT_TYPE = LAST_TYPE,
661 // Boundaries for testing the types represented as JSProxy
662 FIRST_JS_PROXY_TYPE = JS_FUNCTION_PROXY_TYPE,
663 LAST_JS_PROXY_TYPE = JS_PROXY_TYPE,
664 // Boundaries for testing whether the type is a JavaScript object.
665 FIRST_SPEC_OBJECT_TYPE = FIRST_JS_RECEIVER_TYPE,
666 LAST_SPEC_OBJECT_TYPE = LAST_JS_RECEIVER_TYPE,
667 // Boundaries for testing the types for which typeof is "object".
668 FIRST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_PROXY_TYPE,
669 LAST_NONCALLABLE_SPEC_OBJECT_TYPE = JS_REGEXP_TYPE,
670 // Note that the types for which typeof is "function" are not continuous.
671 // Define this so that we can put assertions on discrete checks.
672 NUM_OF_CALLABLE_SPEC_OBJECT_TYPES = 2
675 const int kExternalArrayTypeCount =
676 LAST_EXTERNAL_ARRAY_TYPE - FIRST_EXTERNAL_ARRAY_TYPE + 1;
678 STATIC_CHECK(JS_OBJECT_TYPE == Internals::kJSObjectType);
679 STATIC_CHECK(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
680 STATIC_CHECK(FOREIGN_TYPE == Internals::kForeignType);
692 #define DECL_BOOLEAN_ACCESSORS(name) \
693 inline bool name(); \
694 inline void set_##name(bool value); \
697 #define DECL_ACCESSORS(name, type) \
698 inline type* name(); \
699 inline void set_##name(type* value, \
700 WriteBarrierMode mode = UPDATE_WRITE_BARRIER); \
703 class DictionaryElementsAccessor;
704 class ElementsAccessor;
705 class FixedArrayBase;
710 struct ValueInfo : public Malloced {
711 ValueInfo() : type(FIRST_TYPE), ptr(NULL), str(NULL), number(0) { }
719 // A template-ized version of the IsXXX functions.
720 template <class C> static inline bool Is(Object* obj);
723 class MaybeObject BASE_EMBEDDED {
725 inline bool IsFailure();
726 inline bool IsRetryAfterGC();
727 inline bool IsOutOfMemory();
728 inline bool IsException();
729 INLINE(bool IsTheHole());
730 inline bool ToObject(Object** obj) {
731 if (IsFailure()) return false;
732 *obj = reinterpret_cast<Object*>(this);
735 inline Failure* ToFailureUnchecked() {
737 return reinterpret_cast<Failure*>(this);
739 inline Object* ToObjectUnchecked() {
740 ASSERT(!IsFailure());
741 return reinterpret_cast<Object*>(this);
743 inline Object* ToObjectChecked() {
745 return reinterpret_cast<Object*>(this);
749 inline bool To(T** obj) {
750 if (IsFailure()) return false;
751 *obj = T::cast(reinterpret_cast<Object*>(this));
756 // Prints this object with details.
757 inline void Print() {
760 inline void PrintLn() {
763 void Print(FILE* out);
764 void PrintLn(FILE* out);
767 // Verifies the object.
773 #define OBJECT_TYPE_LIST(V) \
778 #define HEAP_OBJECT_TYPE_LIST(V) \
786 V(ExternalTwoByteString) \
787 V(ExternalAsciiString) \
788 V(SeqTwoByteString) \
792 V(ExternalByteArray) \
793 V(ExternalUnsignedByteArray) \
794 V(ExternalShortArray) \
795 V(ExternalUnsignedShortArray) \
796 V(ExternalIntArray) \
797 V(ExternalUnsignedIntArray) \
798 V(ExternalFloatArray) \
799 V(ExternalDoubleArray) \
800 V(ExternalPixelArray) \
805 V(JSContextExtensionObject) \
808 V(DeoptimizationInputData) \
809 V(DeoptimizationOutputData) \
810 V(TypeFeedbackCells) \
812 V(FixedDoubleArray) \
819 V(SharedFunctionInfo) \
836 V(JSFunctionResultCache) \
837 V(NormalizedMapCache) \
838 V(CompilationCacheTable) \
839 V(CodeCacheHashTable) \
840 V(PolymorphicCodeCacheHashTable) \
845 V(JSBuiltinsObject) \
847 V(UndetectableObject) \
848 V(AccessCheckNeeded) \
849 V(JSGlobalPropertyCell) \
854 // Object is the abstract superclass for all classes in the
856 // Object does not use any virtual functions to avoid the
857 // allocation of the C++ vtable.
858 // Since Smi and Failure are subclasses of Object no
859 // data members can be present in Object.
860 class Object : public MaybeObject {
863 bool IsObject() { return true; }
865 #define IS_TYPE_FUNCTION_DECL(type_) inline bool Is##type_();
866 OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
867 HEAP_OBJECT_TYPE_LIST(IS_TYPE_FUNCTION_DECL)
868 #undef IS_TYPE_FUNCTION_DECL
870 inline bool IsFixedArrayBase();
872 // Returns true if this object is an instance of the specified
873 // function template.
874 inline bool IsInstanceOf(FunctionTemplateInfo* type);
876 inline bool IsStruct();
877 #define DECLARE_STRUCT_PREDICATE(NAME, Name, name) inline bool Is##Name();
878 STRUCT_LIST(DECLARE_STRUCT_PREDICATE)
879 #undef DECLARE_STRUCT_PREDICATE
881 INLINE(bool IsSpecObject());
882 INLINE(bool IsSpecFunction());
885 INLINE(bool IsUndefined());
886 INLINE(bool IsNull());
887 INLINE(bool IsTheHole()); // Shadows MaybeObject's implementation.
888 INLINE(bool IsTrue());
889 INLINE(bool IsFalse());
890 inline bool IsArgumentsMarker();
891 inline bool NonFailureIsHeapObject();
893 // Filler objects (fillers and free space objects).
894 inline bool IsFiller();
896 // Extract the number.
897 inline double Number();
900 // Returns true if the object is of the correct type to be used as a
901 // implementation of a JSObject's elements.
902 inline bool HasValidElements();
904 inline bool HasSpecificClassOf(String* name);
906 MUST_USE_RESULT MaybeObject* ToObject(); // ECMA-262 9.9.
907 Object* ToBoolean(); // ECMA-262 9.2.
909 // Convert to a JSObject if needed.
910 // global_context is used when creating wrapper object.
911 MUST_USE_RESULT MaybeObject* ToObject(Context* global_context);
913 // Converts this to a Smi if possible.
914 // Failure is returned otherwise.
915 MUST_USE_RESULT inline MaybeObject* ToSmi();
917 void Lookup(String* name, LookupResult* result);
920 MUST_USE_RESULT inline MaybeObject* GetProperty(String* key);
921 MUST_USE_RESULT inline MaybeObject* GetProperty(
923 PropertyAttributes* attributes);
924 MUST_USE_RESULT MaybeObject* GetPropertyWithReceiver(
927 PropertyAttributes* attributes);
929 static Handle<Object> GetProperty(Handle<Object> object,
930 Handle<Object> receiver,
931 LookupResult* result,
933 PropertyAttributes* attributes);
935 MUST_USE_RESULT MaybeObject* GetProperty(Object* receiver,
936 LookupResult* result,
938 PropertyAttributes* attributes);
940 MUST_USE_RESULT MaybeObject* GetPropertyWithDefinedGetter(Object* receiver,
943 static Handle<Object> GetElement(Handle<Object> object, uint32_t index);
944 MUST_USE_RESULT inline MaybeObject* GetElement(uint32_t index);
945 // For use when we know that no exception can be thrown.
946 inline Object* GetElementNoExceptionThrown(uint32_t index);
947 MUST_USE_RESULT MaybeObject* GetElementWithReceiver(Object* receiver,
950 // Return the object's prototype (might be Heap::null_value()).
951 Object* GetPrototype();
953 // Returns the permanent hash code associated with this object depending on
954 // the actual object type. Might return a failure in case no hash was
955 // created yet or GC was caused by creation.
956 MUST_USE_RESULT MaybeObject* GetHash(CreationFlag flag);
958 // Checks whether this object has the same value as the given one. This
959 // function is implemented according to ES5, section 9.12 and can be used
960 // to implement the Harmony "egal" function.
961 bool SameValue(Object* other);
963 // Tries to convert an object to an array index. Returns true and sets
964 // the output parameter if it succeeds.
965 inline bool ToArrayIndex(uint32_t* index);
967 // Returns true if this is a JSValue containing a string and the index is
968 // < the length of the string. Used to implement [] on strings.
969 inline bool IsStringObjectWithCharacterAt(uint32_t index);
972 // Verify a pointer is a valid object pointer.
973 static void VerifyPointer(Object* p);
976 // Prints this object without details.
977 inline void ShortPrint() {
980 void ShortPrint(FILE* out);
982 // Prints this object without details to a message accumulator.
983 void ShortPrint(StringStream* accumulator);
985 // Casting: This cast is only needed to satisfy macros in objects-inl.h.
986 static Object* cast(Object* value) { return value; }
988 // Layout description.
989 static const int kHeaderSize = 0; // Object does not take up any space.
992 DISALLOW_IMPLICIT_CONSTRUCTORS(Object);
996 // Smi represents integer Numbers that can be stored in 31 bits.
997 // Smis are immediate which means they are NOT allocated in the heap.
998 // The this pointer has the following format: [31 bit signed int] 0
999 // For long smis it has the following format:
1000 // [32 bit signed int] [31 bits zero padding] 0
1001 // Smi stands for small integer.
1002 class Smi: public Object {
1004 // Returns the integer value.
1007 // Convert a value to a Smi object.
1008 static inline Smi* FromInt(int value);
1010 static inline Smi* FromIntptr(intptr_t value);
1012 // Returns whether value can be represented in a Smi.
1013 static inline bool IsValid(intptr_t value);
1016 static inline Smi* cast(Object* object);
1018 // Dispatched behavior.
1019 inline void SmiPrint() {
1022 void SmiPrint(FILE* out);
1023 void SmiPrint(StringStream* accumulator);
1028 static const int kMinValue =
1029 (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
1030 static const int kMaxValue = -(kMinValue + 1);
1033 DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
1037 // Failure is used for reporting out of memory situations and
1038 // propagating exceptions through the runtime system. Failure objects
1039 // are transient and cannot occur as part of the object graph.
1041 // Failures are a single word, encoded as follows:
1042 // +-------------------------+---+--+--+
1043 // |.........unused..........|sss|tt|11|
1044 // +-------------------------+---+--+--+
1048 // The low two bits, 0-1, are the failure tag, 11. The next two bits,
1049 // 2-3, are a failure type tag 'tt' with possible values:
1050 // 00 RETRY_AFTER_GC
1052 // 10 INTERNAL_ERROR
1053 // 11 OUT_OF_MEMORY_EXCEPTION
1055 // The next three bits, 4-6, are an allocation space tag 'sss'. The
1056 // allocation space tag is 000 for all failure types except
1057 // RETRY_AFTER_GC. For RETRY_AFTER_GC, the possible values are the
1058 // allocation spaces (the encoding is found in globals.h).
1060 // Failure type tag info.
1061 const int kFailureTypeTagSize = 2;
1062 const int kFailureTypeTagMask = (1 << kFailureTypeTagSize) - 1;
1064 class Failure: public MaybeObject {
1066 // RuntimeStubs assumes EXCEPTION = 1 in the compiler-generated code.
1069 EXCEPTION = 1, // Returning this marker tells the real exception
1070 // is in Isolate::pending_exception.
1072 OUT_OF_MEMORY_EXCEPTION = 3
1075 inline Type type() const;
1077 // Returns the space that needs to be collected for RetryAfterGC failures.
1078 inline AllocationSpace allocation_space() const;
1080 inline bool IsInternalError() const;
1081 inline bool IsOutOfMemoryException() const;
1083 static inline Failure* RetryAfterGC(AllocationSpace space);
1084 static inline Failure* RetryAfterGC(); // NEW_SPACE
1085 static inline Failure* Exception();
1086 static inline Failure* InternalError();
1087 static inline Failure* OutOfMemoryException();
1089 static inline Failure* cast(MaybeObject* object);
1091 // Dispatched behavior.
1092 inline void FailurePrint() {
1093 FailurePrint(stdout);
1095 void FailurePrint(FILE* out);
1096 void FailurePrint(StringStream* accumulator);
1098 void FailureVerify();
1102 inline intptr_t value() const;
1103 static inline Failure* Construct(Type type, intptr_t value = 0);
1105 DISALLOW_IMPLICIT_CONSTRUCTORS(Failure);
1109 // Heap objects typically have a map pointer in their first word. However,
1110 // during GC other data (e.g. mark bits, forwarding addresses) is sometimes
1111 // encoded in the first word. The class MapWord is an abstraction of the
1112 // value in a heap object's first word.
1113 class MapWord BASE_EMBEDDED {
1115 // Normal state: the map word contains a map pointer.
1117 // Create a map word from a map pointer.
1118 static inline MapWord FromMap(Map* map);
1120 // View this map word as a map pointer.
1121 inline Map* ToMap();
1124 // Scavenge collection: the map word of live objects in the from space
1125 // contains a forwarding address (a heap object pointer in the to space).
1127 // True if this map word is a forwarding address for a scavenge
1128 // collection. Only valid during a scavenge collection (specifically,
1129 // when all map words are heap object pointers, i.e. not during a full GC).
1130 inline bool IsForwardingAddress();
1132 // Create a map word from a forwarding address.
1133 static inline MapWord FromForwardingAddress(HeapObject* object);
1135 // View this map word as a forwarding address.
1136 inline HeapObject* ToForwardingAddress();
1138 static inline MapWord FromRawValue(uintptr_t value) {
1139 return MapWord(value);
1142 inline uintptr_t ToRawValue() {
1147 // HeapObject calls the private constructor and directly reads the value.
1148 friend class HeapObject;
1150 explicit MapWord(uintptr_t value) : value_(value) {}
1156 // HeapObject is the superclass for all classes describing heap allocated
1158 class HeapObject: public Object {
1160 // [map]: Contains a map which contains the object's reflective
1163 inline void set_map(Map* value);
1164 // The no-write-barrier version. This is OK if the object is white and in
1165 // new space, or if the value is an immortal immutable object, like the maps
1166 // of primitive (non-JS) objects like strings, heap numbers etc.
1167 inline void set_map_no_write_barrier(Map* value);
1169 // During garbage collection, the map word of a heap object does not
1170 // necessarily contain a map pointer.
1171 inline MapWord map_word();
1172 inline void set_map_word(MapWord map_word);
1174 // The Heap the object was allocated in. Used also to access Isolate.
1175 inline Heap* GetHeap();
1177 // Convenience method to get current isolate. This method can be
1178 // accessed only when its result is the same as
1179 // Isolate::Current(), it ASSERTs this. See also comment for GetHeap.
1180 inline Isolate* GetIsolate();
1182 // Converts an address to a HeapObject pointer.
1183 static inline HeapObject* FromAddress(Address address);
1185 // Returns the address of this HeapObject.
1186 inline Address address();
1188 // Iterates over pointers contained in the object (including the Map)
1189 void Iterate(ObjectVisitor* v);
1191 // Iterates over all pointers contained in the object except the
1192 // first map pointer. The object type is given in the first
1193 // parameter. This function does not access the map pointer in the
1194 // object, and so is safe to call while the map pointer is modified.
1195 void IterateBody(InstanceType type, int object_size, ObjectVisitor* v);
1197 // Returns the heap object's size in bytes
1200 // Given a heap object's map pointer, returns the heap size in bytes
1201 // Useful when the map pointer field is used for other purposes.
1203 inline int SizeFromMap(Map* map);
1205 // Returns the field at offset in obj, as a read/write Object* reference.
1206 // Does no checking, and is safe to use during GC, while maps are invalid.
1207 // Does not invoke write barrier, so should only be assigned to
1208 // during marking GC.
1209 static inline Object** RawField(HeapObject* obj, int offset);
1212 static inline HeapObject* cast(Object* obj);
1214 // Return the write barrier mode for this. Callers of this function
1215 // must be able to present a reference to an AssertNoAllocation
1216 // object as a sign that they are not going to use this function
1217 // from code that allocates and thus invalidates the returned write
1219 inline WriteBarrierMode GetWriteBarrierMode(const AssertNoAllocation&);
1221 // Dispatched behavior.
1222 void HeapObjectShortPrint(StringStream* accumulator);
1224 inline void HeapObjectPrint() {
1225 HeapObjectPrint(stdout);
1227 void HeapObjectPrint(FILE* out);
1228 void PrintHeader(FILE* out, const char* id);
1232 void HeapObjectVerify();
1233 inline void VerifyObjectField(int offset);
1234 inline void VerifySmiField(int offset);
1236 // Verify a pointer is a valid HeapObject pointer that points to object
1237 // areas in the heap.
1238 static void VerifyHeapPointer(Object* p);
1241 // Layout description.
1242 // First field in a heap object is map.
1243 static const int kMapOffset = Object::kHeaderSize;
1244 static const int kHeaderSize = kMapOffset + kPointerSize;
1246 STATIC_CHECK(kMapOffset == Internals::kHeapObjectMapOffset);
1249 // helpers for calling an ObjectVisitor to iterate over pointers in the
1250 // half-open range [start, end) specified as integer offsets
1251 inline void IteratePointers(ObjectVisitor* v, int start, int end);
1252 // as above, for the single element at "offset"
1253 inline void IteratePointer(ObjectVisitor* v, int offset);
1256 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapObject);
1260 #define SLOT_ADDR(obj, offset) \
1261 reinterpret_cast<Object**>((obj)->address() + offset)
1263 // This class describes a body of an object of a fixed size
1264 // in which all pointer fields are located in the [start_offset, end_offset)
1266 template<int start_offset, int end_offset, int size>
1267 class FixedBodyDescriptor {
1269 static const int kStartOffset = start_offset;
1270 static const int kEndOffset = end_offset;
1271 static const int kSize = size;
1273 static inline void IterateBody(HeapObject* obj, ObjectVisitor* v);
1275 template<typename StaticVisitor>
1276 static inline void IterateBody(HeapObject* obj) {
1277 StaticVisitor::VisitPointers(SLOT_ADDR(obj, start_offset),
1278 SLOT_ADDR(obj, end_offset));
1283 // This class describes a body of an object of a variable size
1284 // in which all pointer fields are located in the [start_offset, object_size)
1286 template<int start_offset>
1287 class FlexibleBodyDescriptor {
1289 static const int kStartOffset = start_offset;
1291 static inline void IterateBody(HeapObject* obj,
1295 template<typename StaticVisitor>
1296 static inline void IterateBody(HeapObject* obj, int object_size) {
1297 StaticVisitor::VisitPointers(SLOT_ADDR(obj, start_offset),
1298 SLOT_ADDR(obj, object_size));
1305 // The HeapNumber class describes heap allocated numbers that cannot be
1306 // represented in a Smi (small integer)
1307 class HeapNumber: public HeapObject {
1309 // [value]: number value.
1310 inline double value();
1311 inline void set_value(double value);
1314 static inline HeapNumber* cast(Object* obj);
1316 // Dispatched behavior.
1317 Object* HeapNumberToBoolean();
1318 inline void HeapNumberPrint() {
1319 HeapNumberPrint(stdout);
1321 void HeapNumberPrint(FILE* out);
1322 void HeapNumberPrint(StringStream* accumulator);
1324 void HeapNumberVerify();
1327 inline int get_exponent();
1328 inline int get_sign();
1330 // Layout description.
1331 static const int kValueOffset = HeapObject::kHeaderSize;
1332 // IEEE doubles are two 32 bit words. The first is just mantissa, the second
1333 // is a mixture of sign, exponent and mantissa. Our current platforms are all
1334 // little endian apart from non-EABI arm which is little endian with big
1335 // endian floating point word ordering!
1336 static const int kMantissaOffset = kValueOffset;
1337 static const int kExponentOffset = kValueOffset + 4;
1339 static const int kSize = kValueOffset + kDoubleSize;
1340 static const uint32_t kSignMask = 0x80000000u;
1341 static const uint32_t kExponentMask = 0x7ff00000u;
1342 static const uint32_t kMantissaMask = 0xfffffu;
1343 static const int kMantissaBits = 52;
1344 static const int kExponentBits = 11;
1345 static const int kExponentBias = 1023;
1346 static const int kExponentShift = 20;
1347 static const int kMantissaBitsInTopWord = 20;
1348 static const int kNonMantissaBitsInTopWord = 12;
1351 DISALLOW_IMPLICIT_CONSTRUCTORS(HeapNumber);
1355 enum EnsureElementsMode {
1356 DONT_ALLOW_DOUBLE_ELEMENTS,
1357 ALLOW_COPIED_DOUBLE_ELEMENTS,
1358 ALLOW_CONVERTED_DOUBLE_ELEMENTS
1362 // Indicates whether a property should be set or (re)defined. Setting of a
1363 // property causes attributes to remain unchanged, writability to be checked
1364 // and callbacks to be called. Defining of a property causes attributes to
1365 // be updated and callbacks to be overridden.
1366 enum SetPropertyMode {
1372 // Indicator for one component of an AccessorPair.
1373 enum AccessorComponent {
1379 // JSReceiver includes types on which properties can be defined, i.e.,
1380 // JSObject and JSProxy.
1381 class JSReceiver: public HeapObject {
1390 static inline JSReceiver* cast(Object* obj);
1392 static Handle<Object> SetProperty(Handle<JSReceiver> object,
1394 Handle<Object> value,
1395 PropertyAttributes attributes,
1396 StrictModeFlag strict_mode,
1397 bool skip_fallback_interceptor = false);
1399 MUST_USE_RESULT MaybeObject* SetProperty(String* key,
1401 PropertyAttributes attributes,
1402 StrictModeFlag strict_mode,
1403 bool skip_fallback_interceptor = false);
1404 MUST_USE_RESULT MaybeObject* SetProperty(LookupResult* result,
1407 PropertyAttributes attributes,
1408 StrictModeFlag strict_mode);
1409 MUST_USE_RESULT MaybeObject* SetPropertyWithDefinedSetter(JSReceiver* setter,
1412 MUST_USE_RESULT MaybeObject* DeleteProperty(String* name, DeleteMode mode);
1413 MUST_USE_RESULT MaybeObject* DeleteElement(uint32_t index, DeleteMode mode);
1415 // Set the index'th array element.
1416 // Can cause GC, or return failure if GC is required.
1417 MUST_USE_RESULT MaybeObject* SetElement(uint32_t index,
1419 PropertyAttributes attributes,
1420 StrictModeFlag strict_mode,
1421 bool check_prototype);
1423 // Tests for the fast common case for property enumeration.
1424 bool IsSimpleEnum();
1426 // Returns the class name ([[Class]] property in the specification).
1427 String* class_name();
1429 // Returns the constructor name (the name (possibly, inferred name) of the
1430 // function that was used to instantiate the object).
1431 String* constructor_name();
1433 inline PropertyAttributes GetPropertyAttribute(String* name);
1434 PropertyAttributes GetPropertyAttributeWithReceiver(JSReceiver* receiver,
1436 PropertyAttributes GetLocalPropertyAttribute(String* name);
1439 inline bool HasProperty(String* name);
1440 inline bool HasLocalProperty(String* name);
1441 inline bool HasElement(uint32_t index);
1443 // Return the object's prototype (might be Heap::null_value()).
1444 inline Object* GetPrototype();
1446 // Set the object's prototype (only JSReceiver and null are allowed).
1447 MUST_USE_RESULT MaybeObject* SetPrototype(Object* value,
1448 bool skip_hidden_prototypes);
1450 // Retrieves a permanent object identity hash code. The undefined value might
1451 // be returned in case no hash was created yet and OMIT_CREATION was used.
1452 inline MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
1454 // Lookup a property. If found, the result is valid and has
1455 // detailed information.
1456 void LocalLookup(String* name,
1457 LookupResult* result,
1458 bool skip_fallback_interceptor = false);
1459 void Lookup(String* name,
1460 LookupResult* result,
1461 bool skip_fallback_interceptor = false);
1464 Smi* GenerateIdentityHash();
1467 PropertyAttributes GetPropertyAttribute(JSReceiver* receiver,
1468 LookupResult* result,
1470 bool continue_search);
1472 DISALLOW_IMPLICIT_CONSTRUCTORS(JSReceiver);
1475 // The JSObject describes real heap allocated JavaScript objects with
1477 // Note that the map of JSObject changes during execution to enable inline
1479 class JSObject: public JSReceiver {
1481 // [properties]: Backing storage for properties.
1482 // properties is a FixedArray in the fast case and a Dictionary in the
1484 DECL_ACCESSORS(properties, FixedArray) // Get and set fast properties.
1485 inline void initialize_properties();
1486 inline bool HasFastProperties();
1487 inline StringDictionary* property_dictionary(); // Gets slow properties.
1489 // [elements]: The elements (properties with names that are integers).
1491 // Elements can be in two general modes: fast and slow. Each mode
1492 // corrensponds to a set of object representations of elements that
1493 // have something in common.
1495 // In the fast mode elements is a FixedArray and so each element can
1496 // be quickly accessed. This fact is used in the generated code. The
1497 // elements array can have one of three maps in this mode:
1498 // fixed_array_map, non_strict_arguments_elements_map or
1499 // fixed_cow_array_map (for copy-on-write arrays). In the latter case
1500 // the elements array may be shared by a few objects and so before
1501 // writing to any element the array must be copied. Use
1502 // EnsureWritableFastElements in this case.
1504 // In the slow mode the elements is either a NumberDictionary, an
1505 // ExternalArray, or a FixedArray parameter map for a (non-strict)
1506 // arguments object.
1507 DECL_ACCESSORS(elements, FixedArrayBase)
1508 inline void initialize_elements();
1509 MUST_USE_RESULT inline MaybeObject* ResetElements();
1510 inline ElementsKind GetElementsKind();
1511 inline ElementsAccessor* GetElementsAccessor();
1512 inline bool HasFastSmiOnlyElements();
1513 inline bool HasFastElements();
1514 // Returns if an object has either FAST_ELEMENT or FAST_SMI_ONLY_ELEMENT
1515 // elements. TODO(danno): Rename HasFastTypeElements to HasFastElements() and
1516 // HasFastElements to HasFastObjectElements.
1517 inline bool HasFastTypeElements();
1518 inline bool HasFastDoubleElements();
1519 inline bool HasNonStrictArgumentsElements();
1520 inline bool HasDictionaryElements();
1521 inline bool HasExternalPixelElements();
1522 inline bool HasExternalArrayElements();
1523 inline bool HasExternalByteElements();
1524 inline bool HasExternalUnsignedByteElements();
1525 inline bool HasExternalShortElements();
1526 inline bool HasExternalUnsignedShortElements();
1527 inline bool HasExternalIntElements();
1528 inline bool HasExternalUnsignedIntElements();
1529 inline bool HasExternalFloatElements();
1530 inline bool HasExternalDoubleElements();
1531 bool HasFastArgumentsElements();
1532 bool HasDictionaryArgumentsElements();
1533 inline SeededNumberDictionary* element_dictionary(); // Gets slow elements.
1535 inline void set_map_and_elements(
1537 FixedArrayBase* value,
1538 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
1540 // Requires: HasFastElements().
1541 MUST_USE_RESULT inline MaybeObject* EnsureWritableFastElements();
1543 // Collects elements starting at index 0.
1544 // Undefined values are placed after non-undefined values.
1545 // Returns the number of non-undefined values.
1546 MUST_USE_RESULT MaybeObject* PrepareElementsForSort(uint32_t limit);
1547 // As PrepareElementsForSort, but only on objects where elements is
1548 // a dictionary, and it will stay a dictionary.
1549 MUST_USE_RESULT MaybeObject* PrepareSlowElementsForSort(uint32_t limit);
1551 MUST_USE_RESULT MaybeObject* GetPropertyWithCallback(Object* receiver,
1556 MUST_USE_RESULT MaybeObject* SetPropertyForResult(LookupResult* result,
1559 PropertyAttributes attributes,
1560 StrictModeFlag strict_mode);
1561 MUST_USE_RESULT MaybeObject* SetPropertyWithFailedAccessCheck(
1562 LookupResult* result,
1565 bool check_prototype,
1566 StrictModeFlag strict_mode);
1567 MUST_USE_RESULT MaybeObject* SetPropertyWithCallback(
1572 StrictModeFlag strict_mode);
1573 MUST_USE_RESULT MaybeObject* SetPropertyWithInterceptor(
1576 PropertyAttributes attributes,
1577 StrictModeFlag strict_mode);
1578 MUST_USE_RESULT MaybeObject* SetPropertyPostInterceptor(
1581 PropertyAttributes attributes,
1582 StrictModeFlag strict_mode);
1584 static Handle<Object> SetLocalPropertyIgnoreAttributes(
1585 Handle<JSObject> object,
1587 Handle<Object> value,
1588 PropertyAttributes attributes);
1591 MUST_USE_RESULT MaybeObject* SetLocalPropertyIgnoreAttributes(
1594 PropertyAttributes attributes);
1596 // Retrieve a value in a normalized object given a lookup result.
1597 // Handles the special representation of JS global objects.
1598 Object* GetNormalizedProperty(LookupResult* result);
1600 // Sets the property value in a normalized object given a lookup result.
1601 // Handles the special representation of JS global objects.
1602 Object* SetNormalizedProperty(LookupResult* result, Object* value);
1604 // Sets the property value in a normalized object given (key, value, details).
1605 // Handles the special representation of JS global objects.
1606 static Handle<Object> SetNormalizedProperty(Handle<JSObject> object,
1608 Handle<Object> value,
1609 PropertyDetails details);
1611 MUST_USE_RESULT MaybeObject* SetNormalizedProperty(String* name,
1613 PropertyDetails details);
1615 // Deletes the named property in a normalized object.
1616 MUST_USE_RESULT MaybeObject* DeleteNormalizedProperty(String* name,
1619 // Retrieve interceptors.
1620 InterceptorInfo* GetNamedInterceptor();
1621 InterceptorInfo* GetIndexedInterceptor();
1623 // Used from JSReceiver.
1624 PropertyAttributes GetPropertyAttributePostInterceptor(JSObject* receiver,
1626 bool continue_search);
1627 PropertyAttributes GetPropertyAttributeWithInterceptor(JSObject* receiver,
1629 bool continue_search);
1630 PropertyAttributes GetPropertyAttributeWithFailedAccessCheck(
1632 LookupResult* result,
1634 bool continue_search);
1636 static void DefineAccessor(Handle<JSObject> object,
1637 Handle<String> name,
1638 Handle<Object> getter,
1639 Handle<Object> setter,
1640 PropertyAttributes attributes);
1641 MUST_USE_RESULT MaybeObject* DefineAccessor(String* name,
1644 PropertyAttributes attributes);
1645 Object* LookupAccessor(String* name, AccessorComponent component);
1647 MUST_USE_RESULT MaybeObject* DefineAccessor(AccessorInfo* info);
1649 // Used from Object::GetProperty().
1650 MUST_USE_RESULT MaybeObject* GetPropertyWithFailedAccessCheck(
1652 LookupResult* result,
1654 PropertyAttributes* attributes);
1655 MUST_USE_RESULT MaybeObject* GetPropertyWithInterceptor(
1656 JSReceiver* receiver,
1658 PropertyAttributes* attributes);
1659 MUST_USE_RESULT MaybeObject* GetPropertyPostInterceptor(
1660 JSReceiver* receiver,
1662 PropertyAttributes* attributes);
1663 MUST_USE_RESULT MaybeObject* GetLocalPropertyPostInterceptor(
1664 JSReceiver* receiver,
1666 PropertyAttributes* attributes);
1668 // Returns true if this is an instance of an api function and has
1669 // been modified since it was created. May give false positives.
1672 // If the receiver is a JSGlobalProxy this method will return its prototype,
1673 // otherwise the result is the receiver itself.
1674 inline Object* BypassGlobalProxy();
1676 // Accessors for hidden properties object.
1678 // Hidden properties are not local properties of the object itself.
1679 // Instead they are stored in an auxiliary structure kept as a local
1680 // property with a special name Heap::hidden_symbol(). But if the
1681 // receiver is a JSGlobalProxy then the auxiliary object is a property
1682 // of its prototype, and if it's a detached proxy, then you can't have
1683 // hidden properties.
1685 // Sets a hidden property on this object. Returns this object if successful,
1686 // undefined if called on a detached proxy.
1687 static Handle<Object> SetHiddenProperty(Handle<JSObject> obj,
1689 Handle<Object> value);
1690 // Returns a failure if a GC is required.
1691 MUST_USE_RESULT MaybeObject* SetHiddenProperty(String* key, Object* value);
1692 // Gets the value of a hidden property with the given key. Returns undefined
1693 // if the property doesn't exist (or if called on a detached proxy),
1694 // otherwise returns the value set for the key.
1695 Object* GetHiddenProperty(String* key);
1696 // Deletes a hidden property. Deleting a non-existing property is
1697 // considered successful.
1698 void DeleteHiddenProperty(String* key);
1699 // Returns true if the object has a property with the hidden symbol as name.
1700 bool HasHiddenProperties();
1702 static int GetIdentityHash(Handle<JSObject> obj);
1703 MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
1704 MUST_USE_RESULT MaybeObject* SetIdentityHash(Object* hash, CreationFlag flag);
1706 static Handle<Object> DeleteProperty(Handle<JSObject> obj,
1707 Handle<String> name);
1708 MUST_USE_RESULT MaybeObject* DeleteProperty(String* name, DeleteMode mode);
1710 static Handle<Object> DeleteElement(Handle<JSObject> obj, uint32_t index);
1711 MUST_USE_RESULT MaybeObject* DeleteElement(uint32_t index, DeleteMode mode);
1713 inline void ValidateSmiOnlyElements();
1715 // Makes sure that this object can contain HeapObject as elements.
1716 MUST_USE_RESULT inline MaybeObject* EnsureCanContainHeapObjectElements();
1718 // Makes sure that this object can contain the specified elements.
1719 MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
1722 EnsureElementsMode mode);
1723 MUST_USE_RESULT inline MaybeObject* EnsureCanContainElements(
1724 FixedArrayBase* elements,
1725 EnsureElementsMode mode);
1726 MUST_USE_RESULT MaybeObject* EnsureCanContainElements(
1727 Arguments* arguments,
1730 EnsureElementsMode mode);
1732 // Do we want to keep the elements in fast case when increasing the
1734 bool ShouldConvertToSlowElements(int new_capacity);
1735 // Returns true if the backing storage for the slow-case elements of
1736 // this object takes up nearly as much space as a fast-case backing
1737 // storage would. In that case the JSObject should have fast
1739 bool ShouldConvertToFastElements();
1740 // Returns true if the elements of JSObject contains only values that can be
1741 // represented in a FixedDoubleArray and has at least one value that can only
1742 // be represented as a double and not a Smi.
1743 bool ShouldConvertToFastDoubleElements(bool* has_smi_only_elements);
1745 // Tells whether the index'th element is present.
1746 bool HasElementWithReceiver(JSReceiver* receiver, uint32_t index);
1748 // Computes the new capacity when expanding the elements of a JSObject.
1749 static int NewElementsCapacity(int old_capacity) {
1750 // (old_capacity + 50%) + 16
1751 return old_capacity + (old_capacity >> 1) + 16;
1754 // Tells whether the index'th element is present and how it is stored.
1755 enum LocalElementType {
1756 // There is no element with given index.
1759 // Element with given index is handled by interceptor.
1760 INTERCEPTED_ELEMENT,
1762 // Element with given index is character in string.
1763 STRING_CHARACTER_ELEMENT,
1765 // Element with given index is stored in fast backing store.
1768 // Element with given index is stored in slow backing store.
1772 LocalElementType HasLocalElement(uint32_t index);
1774 bool HasElementWithInterceptor(JSReceiver* receiver, uint32_t index);
1776 MUST_USE_RESULT MaybeObject* SetFastElement(uint32_t index,
1778 StrictModeFlag strict_mode,
1779 bool check_prototype);
1781 MUST_USE_RESULT MaybeObject* SetDictionaryElement(
1784 PropertyAttributes attributes,
1785 StrictModeFlag strict_mode,
1786 bool check_prototype,
1787 SetPropertyMode set_mode = SET_PROPERTY);
1789 MUST_USE_RESULT MaybeObject* SetFastDoubleElement(
1792 StrictModeFlag strict_mode,
1793 bool check_prototype = true);
1795 static Handle<Object> SetOwnElement(Handle<JSObject> object,
1797 Handle<Object> value,
1798 StrictModeFlag strict_mode);
1800 // Empty handle is returned if the element cannot be set to the given value.
1801 static MUST_USE_RESULT Handle<Object> SetElement(
1802 Handle<JSObject> object,
1804 Handle<Object> value,
1805 PropertyAttributes attr,
1806 StrictModeFlag strict_mode,
1807 SetPropertyMode set_mode = SET_PROPERTY);
1809 // A Failure object is returned if GC is needed.
1810 MUST_USE_RESULT MaybeObject* SetElement(
1813 PropertyAttributes attributes,
1814 StrictModeFlag strict_mode,
1815 bool check_prototype = true,
1816 SetPropertyMode set_mode = SET_PROPERTY);
1818 // Returns the index'th element.
1819 // The undefined object if index is out of bounds.
1820 MUST_USE_RESULT MaybeObject* GetElementWithInterceptor(Object* receiver,
1823 enum SetFastElementsCapacityMode {
1824 kAllowSmiOnlyElements,
1825 kForceSmiOnlyElements,
1826 kDontAllowSmiOnlyElements
1829 // Replace the elements' backing store with fast elements of the given
1830 // capacity. Update the length for JSArrays. Returns the new backing
1832 MUST_USE_RESULT MaybeObject* SetFastElementsCapacityAndLength(
1835 SetFastElementsCapacityMode set_capacity_mode);
1836 MUST_USE_RESULT MaybeObject* SetFastDoubleElementsCapacityAndLength(
1840 // Lookup interceptors are used for handling properties controlled by host
1842 inline bool HasNamedInterceptor();
1843 inline bool HasIndexedInterceptor();
1845 // Support functions for v8 api (needed for correct interceptor behavior).
1846 bool HasRealNamedProperty(String* key);
1847 bool HasRealElementProperty(uint32_t index);
1848 bool HasRealNamedCallbackProperty(String* key);
1850 // Get the header size for a JSObject. Used to compute the index of
1851 // internal fields as well as the number of internal fields.
1852 inline int GetHeaderSize();
1854 inline int GetInternalFieldCount();
1855 inline int GetInternalFieldOffset(int index);
1856 inline Object* GetInternalField(int index);
1857 inline void SetInternalField(int index, Object* value);
1858 inline void SetInternalField(int index, Smi* value);
1860 // The following lookup functions skip interceptors.
1861 void LocalLookupRealNamedProperty(String* name, LookupResult* result);
1862 void LookupRealNamedProperty(String* name, LookupResult* result);
1863 void LookupRealNamedPropertyInPrototypes(String* name, LookupResult* result);
1864 void LookupCallbackSetterInPrototypes(String* name, LookupResult* result);
1865 MUST_USE_RESULT MaybeObject* SetElementWithCallbackSetterInPrototypes(
1866 uint32_t index, Object* value, bool* found, StrictModeFlag strict_mode);
1867 void LookupCallback(String* name, LookupResult* result);
1869 // Returns the number of properties on this object filtering out properties
1870 // with the specified attributes (ignoring interceptors).
1871 int NumberOfLocalProperties(PropertyAttributes filter = NONE);
1872 // Fill in details for properties into storage starting at the specified
1874 void GetLocalPropertyNames(FixedArray* storage, int index);
1876 // Returns the number of properties on this object filtering out properties
1877 // with the specified attributes (ignoring interceptors).
1878 int NumberOfLocalElements(PropertyAttributes filter);
1879 // Returns the number of enumerable elements (ignoring interceptors).
1880 int NumberOfEnumElements();
1881 // Returns the number of elements on this object filtering out elements
1882 // with the specified attributes (ignoring interceptors).
1883 int GetLocalElementKeys(FixedArray* storage, PropertyAttributes filter);
1884 // Count and fill in the enumerable elements into storage.
1885 // (storage->length() == NumberOfEnumElements()).
1886 // If storage is NULL, will count the elements without adding
1887 // them to any storage.
1888 // Returns the number of enumerable elements.
1889 int GetEnumElementKeys(FixedArray* storage);
1891 // Add a property to a fast-case object using a map transition to
1893 MUST_USE_RESULT MaybeObject* AddFastPropertyUsingMap(Map* new_map,
1897 // Add a constant function property to a fast-case object.
1898 // This leaves a CONSTANT_TRANSITION in the old map, and
1899 // if it is called on a second object with this map, a
1900 // normal property is added instead, with a map transition.
1901 // This avoids the creation of many maps with the same constant
1902 // function, all orphaned.
1903 MUST_USE_RESULT MaybeObject* AddConstantFunctionProperty(
1905 JSFunction* function,
1906 PropertyAttributes attributes);
1908 MUST_USE_RESULT MaybeObject* ReplaceSlowProperty(
1911 PropertyAttributes attributes);
1913 // Returns a new map with all transitions dropped from the object's current
1914 // map and the ElementsKind set.
1915 static Handle<Map> GetElementsTransitionMap(Handle<JSObject> object,
1916 ElementsKind to_kind);
1917 inline MUST_USE_RESULT MaybeObject* GetElementsTransitionMap(
1919 ElementsKind elements_kind);
1920 MUST_USE_RESULT MaybeObject* GetElementsTransitionMapSlow(
1921 ElementsKind elements_kind);
1923 static Handle<Object> TransitionElementsKind(Handle<JSObject> object,
1924 ElementsKind to_kind);
1926 MUST_USE_RESULT MaybeObject* TransitionElementsKind(ElementsKind to_kind);
1928 // Converts a descriptor of any other type to a real field,
1929 // backed by the properties array. Descriptors of visible
1930 // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1931 // Converts the descriptor on the original object's map to a
1932 // map transition, and the the new field is on the object's new map.
1933 MUST_USE_RESULT MaybeObject* ConvertDescriptorToFieldAndMapTransition(
1936 PropertyAttributes attributes);
1938 // Converts a descriptor of any other type to a real field,
1939 // backed by the properties array. Descriptors of visible
1940 // types, such as CONSTANT_FUNCTION, keep their enumeration order.
1941 MUST_USE_RESULT MaybeObject* ConvertDescriptorToField(
1944 PropertyAttributes attributes);
1946 // Add a property to a fast-case object.
1947 MUST_USE_RESULT MaybeObject* AddFastProperty(String* name,
1949 PropertyAttributes attributes);
1951 // Add a property to a slow-case object.
1952 MUST_USE_RESULT MaybeObject* AddSlowProperty(String* name,
1954 PropertyAttributes attributes);
1956 // Add a property to an object.
1957 MUST_USE_RESULT MaybeObject* AddProperty(String* name,
1959 PropertyAttributes attributes,
1960 StrictModeFlag strict_mode);
1962 // Convert the object to use the canonical dictionary
1963 // representation. If the object is expected to have additional properties
1964 // added this number can be indicated to have the backing store allocated to
1965 // an initial capacity for holding these properties.
1966 static void NormalizeProperties(Handle<JSObject> object,
1967 PropertyNormalizationMode mode,
1968 int expected_additional_properties);
1970 MUST_USE_RESULT MaybeObject* NormalizeProperties(
1971 PropertyNormalizationMode mode,
1972 int expected_additional_properties);
1974 // Convert and update the elements backing store to be a
1975 // SeededNumberDictionary dictionary. Returns the backing after conversion.
1976 static Handle<SeededNumberDictionary> NormalizeElements(
1977 Handle<JSObject> object);
1979 MUST_USE_RESULT MaybeObject* NormalizeElements();
1981 static void UpdateMapCodeCache(Handle<JSObject> object,
1982 Handle<String> name,
1985 MUST_USE_RESULT MaybeObject* UpdateMapCodeCache(String* name, Code* code);
1987 // Transform slow named properties to fast variants.
1988 // Returns failure if allocation failed.
1989 static void TransformToFastProperties(Handle<JSObject> object,
1990 int unused_property_fields);
1992 MUST_USE_RESULT MaybeObject* TransformToFastProperties(
1993 int unused_property_fields);
1995 // Access fast-case object properties at index.
1996 inline Object* FastPropertyAt(int index);
1997 inline Object* FastPropertyAtPut(int index, Object* value);
1999 // Access to in object properties.
2000 inline int GetInObjectPropertyOffset(int index);
2001 inline Object* InObjectPropertyAt(int index);
2002 inline Object* InObjectPropertyAtPut(int index,
2004 WriteBarrierMode mode
2005 = UPDATE_WRITE_BARRIER);
2007 // Initializes the body after properties slot, properties slot is
2008 // initialized by set_properties. Fill the pre-allocated fields with
2009 // pre_allocated_value and the rest with filler_value.
2010 // Note: this call does not update write barrier, the caller is responsible
2011 // to ensure that |filler_value| can be collected without WB here.
2012 inline void InitializeBody(Map* map,
2013 Object* pre_allocated_value,
2014 Object* filler_value);
2016 // Check whether this object references another object
2017 bool ReferencesObject(Object* obj);
2020 static inline JSObject* cast(Object* obj);
2022 // Disalow further properties to be added to the object.
2023 static Handle<Object> PreventExtensions(Handle<JSObject> object);
2024 MUST_USE_RESULT MaybeObject* PreventExtensions();
2027 // Dispatched behavior.
2028 void JSObjectShortPrint(StringStream* accumulator);
2030 inline void JSObjectPrint() {
2031 JSObjectPrint(stdout);
2033 void JSObjectPrint(FILE* out);
2036 void JSObjectVerify();
2039 inline void PrintProperties() {
2040 PrintProperties(stdout);
2042 void PrintProperties(FILE* out);
2044 inline void PrintElements() {
2045 PrintElements(stdout);
2047 void PrintElements(FILE* out);
2050 void PrintElementsTransition(
2051 FILE* file, ElementsKind from_kind, FixedArrayBase* from_elements,
2052 ElementsKind to_kind, FixedArrayBase* to_elements);
2055 // Structure for collecting spill information about JSObjects.
2056 class SpillInformation {
2060 int number_of_objects_;
2061 int number_of_objects_with_fast_properties_;
2062 int number_of_objects_with_fast_elements_;
2063 int number_of_fast_used_fields_;
2064 int number_of_fast_unused_fields_;
2065 int number_of_slow_used_properties_;
2066 int number_of_slow_unused_properties_;
2067 int number_of_fast_used_elements_;
2068 int number_of_fast_unused_elements_;
2069 int number_of_slow_used_elements_;
2070 int number_of_slow_unused_elements_;
2073 void IncrementSpillStatistics(SpillInformation* info);
2075 Object* SlowReverseLookup(Object* value);
2077 // Maximal number of fast properties for the JSObject. Used to
2078 // restrict the number of map transitions to avoid an explosion in
2079 // the number of maps for objects used as dictionaries.
2080 inline int MaxFastProperties();
2082 // Maximal number of elements (numbered 0 .. kMaxElementCount - 1).
2083 // Also maximal value of JSArray's length property.
2084 static const uint32_t kMaxElementCount = 0xffffffffu;
2086 // Constants for heuristics controlling conversion of fast elements
2087 // to slow elements.
2089 // Maximal gap that can be introduced by adding an element beyond
2090 // the current elements length.
2091 static const uint32_t kMaxGap = 1024;
2093 // Maximal length of fast elements array that won't be checked for
2094 // being dense enough on expansion.
2095 static const int kMaxUncheckedFastElementsLength = 5000;
2097 // Same as above but for old arrays. This limit is more strict. We
2098 // don't want to be wasteful with long lived objects.
2099 static const int kMaxUncheckedOldFastElementsLength = 500;
2101 static const int kInitialMaxFastElementArray = 100000;
2102 static const int kMaxFastProperties = 12;
2103 static const int kMaxInstanceSize = 255 * kPointerSize;
2104 // When extending the backing storage for property values, we increase
2105 // its size by more than the 1 entry necessary, so sequentially adding fields
2106 // to the same object requires fewer allocations and copies.
2107 static const int kFieldsAdded = 3;
2109 // Layout description.
2110 static const int kPropertiesOffset = HeapObject::kHeaderSize;
2111 static const int kElementsOffset = kPropertiesOffset + kPointerSize;
2112 static const int kHeaderSize = kElementsOffset + kPointerSize;
2114 STATIC_CHECK(kHeaderSize == Internals::kJSObjectHeaderSize);
2116 class BodyDescriptor : public FlexibleBodyDescriptor<kPropertiesOffset> {
2118 static inline int SizeOf(Map* map, HeapObject* object);
2122 friend class DictionaryElementsAccessor;
2124 MUST_USE_RESULT MaybeObject* GetElementWithCallback(Object* receiver,
2128 MUST_USE_RESULT MaybeObject* SetElementWithCallback(
2133 StrictModeFlag strict_mode);
2134 MUST_USE_RESULT MaybeObject* SetElementWithInterceptor(
2137 PropertyAttributes attributes,
2138 StrictModeFlag strict_mode,
2139 bool check_prototype,
2140 SetPropertyMode set_mode);
2141 MUST_USE_RESULT MaybeObject* SetElementWithoutInterceptor(
2144 PropertyAttributes attributes,
2145 StrictModeFlag strict_mode,
2146 bool check_prototype,
2147 SetPropertyMode set_mode);
2149 // Searches the prototype chain for a callback setter and sets the property
2150 // with the setter if it finds one. The '*found' flag indicates whether
2151 // a setter was found or not.
2152 // This function can cause GC and can return a failure result with
2154 MUST_USE_RESULT MaybeObject* SetPropertyWithCallbackSetterInPrototypes(
2157 PropertyAttributes attributes,
2159 StrictModeFlag strict_mode);
2161 MUST_USE_RESULT MaybeObject* DeletePropertyPostInterceptor(String* name,
2163 MUST_USE_RESULT MaybeObject* DeletePropertyWithInterceptor(String* name);
2165 MUST_USE_RESULT MaybeObject* DeleteElementWithInterceptor(uint32_t index);
2167 MUST_USE_RESULT MaybeObject* DeleteFastElement(uint32_t index);
2168 MUST_USE_RESULT MaybeObject* DeleteDictionaryElement(uint32_t index,
2171 bool ReferencesObjectFromElements(FixedArray* elements,
2175 // Returns true if most of the elements backing storage is used.
2176 bool HasDenseElements();
2178 // Gets the current elements capacity and the number of used elements.
2179 void GetElementsCapacityAndUsage(int* capacity, int* used);
2181 bool CanSetCallback(String* name);
2182 MUST_USE_RESULT MaybeObject* SetElementCallback(
2185 PropertyAttributes attributes);
2186 MUST_USE_RESULT MaybeObject* SetPropertyCallback(
2189 PropertyAttributes attributes);
2190 MUST_USE_RESULT MaybeObject* DefineElementAccessor(
2194 PropertyAttributes attributes);
2195 MUST_USE_RESULT MaybeObject* DefinePropertyAccessor(
2199 PropertyAttributes attributes);
2200 void LookupInDescriptor(String* name, LookupResult* result);
2202 // Returns the hidden properties backing store object, currently
2203 // a StringDictionary, stored on this object.
2204 // If no hidden properties object has been put on this object,
2205 // return undefined, unless create_if_absent is true, in which case
2206 // a new dictionary is created, added to this object, and returned.
2207 MUST_USE_RESULT MaybeObject* GetHiddenPropertiesDictionary(
2208 bool create_if_absent);
2209 // Updates the existing hidden properties dictionary.
2210 MUST_USE_RESULT MaybeObject* SetHiddenPropertiesDictionary(
2211 StringDictionary* dictionary);
2213 DISALLOW_IMPLICIT_CONSTRUCTORS(JSObject);
2217 // Common superclass for FixedArrays that allow implementations to share
2218 // common accessors and some code paths.
2219 class FixedArrayBase: public HeapObject {
2221 // [length]: length of the array.
2222 inline int length();
2223 inline void set_length(int value);
2225 inline static FixedArrayBase* cast(Object* object);
2227 // Layout description.
2228 // Length is smi tagged when it is stored.
2229 static const int kLengthOffset = HeapObject::kHeaderSize;
2230 static const int kHeaderSize = kLengthOffset + kPointerSize;
2234 class FixedDoubleArray;
2236 // FixedArray describes fixed-sized arrays with element type Object*.
2237 class FixedArray: public FixedArrayBase {
2239 // Setter and getter for elements.
2240 inline Object* get(int index);
2241 // Setter that uses write barrier.
2242 inline void set(int index, Object* value);
2243 inline bool is_the_hole(int index);
2245 // Setter that doesn't need write barrier).
2246 inline void set(int index, Smi* value);
2247 // Setter with explicit barrier mode.
2248 inline void set(int index, Object* value, WriteBarrierMode mode);
2250 // Setters for frequently used oddballs located in old space.
2251 inline void set_undefined(int index);
2252 // TODO(isolates): duplicate.
2253 inline void set_undefined(Heap* heap, int index);
2254 inline void set_null(int index);
2255 // TODO(isolates): duplicate.
2256 inline void set_null(Heap* heap, int index);
2257 inline void set_the_hole(int index);
2259 // Setters with less debug checks for the GC to use.
2260 inline void set_unchecked(int index, Smi* value);
2261 inline void set_null_unchecked(Heap* heap, int index);
2262 inline void set_unchecked(Heap* heap, int index, Object* value,
2263 WriteBarrierMode mode);
2265 // Gives access to raw memory which stores the array's data.
2266 inline Object** data_start();
2268 inline Object** GetFirstElementAddress();
2269 inline bool ContainsOnlySmisOrHoles();
2272 MUST_USE_RESULT inline MaybeObject* Copy();
2273 MUST_USE_RESULT MaybeObject* CopySize(int new_length);
2275 // Add the elements of a JSArray to this FixedArray.
2276 MUST_USE_RESULT MaybeObject* AddKeysFromJSArray(JSArray* array);
2278 // Compute the union of this and other.
2279 MUST_USE_RESULT MaybeObject* UnionOfKeys(FixedArray* other);
2281 // Copy a sub array from the receiver to dest.
2282 void CopyTo(int pos, FixedArray* dest, int dest_pos, int len);
2284 // Garbage collection support.
2285 static int SizeFor(int length) { return kHeaderSize + length * kPointerSize; }
2287 // Code Generation support.
2288 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2291 static inline FixedArray* cast(Object* obj);
2293 // Maximal allowed size, in bytes, of a single FixedArray.
2294 // Prevents overflowing size computations, as well as extreme memory
2296 static const int kMaxSize = 128 * MB * kPointerSize;
2297 // Maximally allowed length of a FixedArray.
2298 static const int kMaxLength = (kMaxSize - kHeaderSize) / kPointerSize;
2300 // Dispatched behavior.
2302 inline void FixedArrayPrint() {
2303 FixedArrayPrint(stdout);
2305 void FixedArrayPrint(FILE* out);
2308 void FixedArrayVerify();
2309 // Checks if two FixedArrays have identical contents.
2310 bool IsEqualTo(FixedArray* other);
2313 // Swap two elements in a pair of arrays. If this array and the
2314 // numbers array are the same object, the elements are only swapped
2316 void SwapPairs(FixedArray* numbers, int i, int j);
2318 // Sort prefix of this array and the numbers array as pairs wrt. the
2319 // numbers. If the numbers array and the this array are the same
2320 // object, the prefix of this array is sorted.
2321 void SortPairs(FixedArray* numbers, uint32_t len);
2323 class BodyDescriptor : public FlexibleBodyDescriptor<kHeaderSize> {
2325 static inline int SizeOf(Map* map, HeapObject* object) {
2326 return SizeFor(reinterpret_cast<FixedArray*>(object)->length());
2331 // Set operation on FixedArray without using write barriers. Can
2332 // only be used for storing old space objects or smis.
2333 static inline void NoWriteBarrierSet(FixedArray* array,
2337 // Set operation on FixedArray without incremental write barrier. Can
2338 // only be used if the object is guaranteed to be white (whiteness witness
2340 static inline void NoIncrementalWriteBarrierSet(FixedArray* array,
2345 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedArray);
2349 // FixedDoubleArray describes fixed-sized arrays with element type double.
2350 class FixedDoubleArray: public FixedArrayBase {
2352 // Setter and getter for elements.
2353 inline double get_scalar(int index);
2354 inline int64_t get_representation(int index);
2355 MUST_USE_RESULT inline MaybeObject* get(int index);
2356 inline void set(int index, double value);
2357 inline void set_the_hole(int index);
2359 // Checking for the hole.
2360 inline bool is_the_hole(int index);
2363 MUST_USE_RESULT inline MaybeObject* Copy();
2365 // Garbage collection support.
2366 inline static int SizeFor(int length) {
2367 return kHeaderSize + length * kDoubleSize;
2370 // Code Generation support.
2371 static int OffsetOfElementAt(int index) { return SizeFor(index); }
2373 inline static bool is_the_hole_nan(double value);
2374 inline static double hole_nan_as_double();
2375 inline static double canonical_not_the_hole_nan_as_double();
2378 static inline FixedDoubleArray* cast(Object* obj);
2380 // Maximal allowed size, in bytes, of a single FixedDoubleArray.
2381 // Prevents overflowing size computations, as well as extreme memory
2383 static const int kMaxSize = 512 * MB;
2384 // Maximally allowed length of a FixedArray.
2385 static const int kMaxLength = (kMaxSize - kHeaderSize) / kDoubleSize;
2387 // Dispatched behavior.
2389 inline void FixedDoubleArrayPrint() {
2390 FixedDoubleArrayPrint(stdout);
2392 void FixedDoubleArrayPrint(FILE* out);
2396 void FixedDoubleArrayVerify();
2400 DISALLOW_IMPLICIT_CONSTRUCTORS(FixedDoubleArray);
2404 class IncrementalMarking;
2407 // DescriptorArrays are fixed arrays used to hold instance descriptors.
2408 // The format of the these objects is:
2409 // TODO(1399): It should be possible to make room for bit_field3 in the map
2410 // without overloading the instance descriptors field in the map
2411 // (and storing it in the DescriptorArray when the map has one).
2412 // [0]: storage for bit_field3 for Map owning this object (Smi)
2413 // [1]: point to a fixed array with (value, detail) pairs.
2414 // [2]: next enumeration index (Smi), or pointer to small fixed array:
2415 // [0]: next enumeration index (Smi)
2416 // [1]: pointer to fixed array with enum cache
2418 // [length() - 1]: last key
2420 class DescriptorArray: public FixedArray {
2422 // Returns true for both shared empty_descriptor_array and for smis, which the
2423 // map uses to encode additional bit fields when the descriptor array is not
2425 inline bool IsEmpty();
2427 // Returns the number of descriptors in the array.
2428 int number_of_descriptors() {
2429 ASSERT(length() > kFirstIndex || IsEmpty());
2431 return len <= kFirstIndex ? 0 : len - kFirstIndex;
2434 int NextEnumerationIndex() {
2435 if (IsEmpty()) return PropertyDetails::kInitialIndex;
2436 Object* obj = get(kEnumerationIndexIndex);
2438 return Smi::cast(obj)->value();
2440 Object* index = FixedArray::cast(obj)->get(kEnumCacheBridgeEnumIndex);
2441 return Smi::cast(index)->value();
2445 // Set next enumeration index and flush any enum cache.
2446 void SetNextEnumerationIndex(int value) {
2448 set(kEnumerationIndexIndex, Smi::FromInt(value));
2451 bool HasEnumCache() {
2452 return !IsEmpty() && !get(kEnumerationIndexIndex)->IsSmi();
2455 Object* GetEnumCache() {
2456 ASSERT(HasEnumCache());
2457 FixedArray* bridge = FixedArray::cast(get(kEnumerationIndexIndex));
2458 return bridge->get(kEnumCacheBridgeCacheIndex);
2461 // TODO(1399): It should be possible to make room for bit_field3 in the map
2462 // without overloading the instance descriptors field in the map
2463 // (and storing it in the DescriptorArray when the map has one).
2464 inline int bit_field3_storage();
2465 inline void set_bit_field3_storage(int value);
2467 // Initialize or change the enum cache,
2468 // using the supplied storage for the small "bridge".
2469 void SetEnumCache(FixedArray* bridge_storage,
2470 FixedArray* new_cache,
2471 Object* new_index_cache);
2473 // Accessors for fetching instance descriptor at descriptor number.
2474 inline String* GetKey(int descriptor_number);
2475 inline Object* GetValue(int descriptor_number);
2476 inline Smi* GetDetails(int descriptor_number);
2477 inline PropertyType GetType(int descriptor_number);
2478 inline int GetFieldIndex(int descriptor_number);
2479 inline JSFunction* GetConstantFunction(int descriptor_number);
2480 inline Object* GetCallbacksObject(int descriptor_number);
2481 inline AccessorDescriptor* GetCallbacks(int descriptor_number);
2482 inline bool IsProperty(int descriptor_number);
2483 inline bool IsTransitionOnly(int descriptor_number);
2484 inline bool IsNullDescriptor(int descriptor_number);
2485 inline bool IsDontEnum(int descriptor_number);
2487 class WhitenessWitness {
2489 inline explicit WhitenessWitness(DescriptorArray* array);
2490 inline ~WhitenessWitness();
2493 IncrementalMarking* marking_;
2496 // Accessor for complete descriptor.
2497 inline void Get(int descriptor_number, Descriptor* desc);
2498 inline void Set(int descriptor_number,
2500 const WhitenessWitness&);
2502 // Transfer a complete descriptor from the src descriptor array to the dst
2503 // one, dropping map transitions in CALLBACKS.
2504 static void CopyFrom(Handle<DescriptorArray> dst,
2506 Handle<DescriptorArray> src,
2508 const WhitenessWitness& witness);
2510 // Transfer a complete descriptor from the src descriptor array to this
2511 // descriptor array, dropping map transitions in CALLBACKS.
2512 MUST_USE_RESULT MaybeObject* CopyFrom(int dst_index,
2513 DescriptorArray* src,
2515 const WhitenessWitness&);
2517 // Copy the descriptor array, insert a new descriptor and optionally
2518 // remove map transitions. If the descriptor is already present, it is
2519 // replaced. If a replaced descriptor is a real property (not a transition
2520 // or null), its enumeration index is kept as is.
2521 // If adding a real property, map transitions must be removed. If adding
2522 // a transition, they must not be removed. All null descriptors are removed.
2523 MUST_USE_RESULT MaybeObject* CopyInsert(Descriptor* descriptor,
2524 TransitionFlag transition_flag);
2526 // Return a copy of the array with all transitions and null descriptors
2527 // removed. Return a Failure object in case of an allocation failure.
2528 MUST_USE_RESULT MaybeObject* RemoveTransitions();
2530 // Sort the instance descriptors by the hash codes of their keys.
2531 // Does not check for duplicates.
2532 void SortUnchecked(const WhitenessWitness&);
2534 // Sort the instance descriptors by the hash codes of their keys.
2535 // Checks the result for duplicates.
2536 void Sort(const WhitenessWitness&);
2538 // Search the instance descriptors for given name.
2539 inline int Search(String* name);
2541 // As the above, but uses DescriptorLookupCache and updates it when
2543 inline int SearchWithCache(String* name);
2545 // Tells whether the name is present int the array.
2546 bool Contains(String* name) { return kNotFound != Search(name); }
2548 // Perform a binary search in the instance descriptors represented
2549 // by this fixed array. low and high are descriptor indices. If there
2550 // are three instance descriptors in this array it should be called
2551 // with low=0 and high=2.
2552 int BinarySearch(String* name, int low, int high);
2554 // Perform a linear search in the instance descriptors represented
2555 // by this fixed array. len is the number of descriptor indices that are
2556 // valid. Does not require the descriptors to be sorted.
2557 int LinearSearch(String* name, int len);
2559 // Allocates a DescriptorArray, but returns the singleton
2560 // empty descriptor array object if number_of_descriptors is 0.
2561 MUST_USE_RESULT static MaybeObject* Allocate(int number_of_descriptors);
2564 static inline DescriptorArray* cast(Object* obj);
2566 // Constant for denoting key was not found.
2567 static const int kNotFound = -1;
2569 static const int kBitField3StorageIndex = 0;
2570 static const int kContentArrayIndex = 1;
2571 static const int kEnumerationIndexIndex = 2;
2572 static const int kFirstIndex = 3;
2574 // The length of the "bridge" to the enum cache.
2575 static const int kEnumCacheBridgeLength = 3;
2576 static const int kEnumCacheBridgeEnumIndex = 0;
2577 static const int kEnumCacheBridgeCacheIndex = 1;
2578 static const int kEnumCacheBridgeIndicesCacheIndex = 2;
2580 // Layout description.
2581 static const int kBitField3StorageOffset = FixedArray::kHeaderSize;
2582 static const int kContentArrayOffset = kBitField3StorageOffset + kPointerSize;
2583 static const int kEnumerationIndexOffset = kContentArrayOffset + kPointerSize;
2584 static const int kFirstOffset = kEnumerationIndexOffset + kPointerSize;
2586 // Layout description for the bridge array.
2587 static const int kEnumCacheBridgeEnumOffset = FixedArray::kHeaderSize;
2588 static const int kEnumCacheBridgeCacheOffset =
2589 kEnumCacheBridgeEnumOffset + kPointerSize;
2592 // Print all the descriptors.
2593 inline void PrintDescriptors() {
2594 PrintDescriptors(stdout);
2596 void PrintDescriptors(FILE* out);
2600 // Is the descriptor array sorted and without duplicates?
2601 bool IsSortedNoDuplicates();
2603 // Are two DescriptorArrays equal?
2604 bool IsEqualTo(DescriptorArray* other);
2607 // The maximum number of descriptors we want in a descriptor array (should
2609 static const int kMaxNumberOfDescriptors = 1024 + 512;
2612 // An entry in a DescriptorArray, represented as an (array, index) pair.
2615 inline explicit Entry(DescriptorArray* descs, int index) :
2616 descs_(descs), index_(index) { }
2618 inline PropertyType type() { return descs_->GetType(index_); }
2619 inline Object* GetCallbackObject() { return descs_->GetValue(index_); }
2622 DescriptorArray* descs_;
2626 // Conversion from descriptor number to array indices.
2627 static int ToKeyIndex(int descriptor_number) {
2628 return descriptor_number+kFirstIndex;
2631 static int ToDetailsIndex(int descriptor_number) {
2632 return (descriptor_number << 1) + 1;
2635 static int ToValueIndex(int descriptor_number) {
2636 return descriptor_number << 1;
2639 bool is_null_descriptor(int descriptor_number) {
2640 return PropertyDetails(GetDetails(descriptor_number)).type() ==
2643 // Swap operation on FixedArray without using write barriers.
2644 static inline void NoIncrementalWriteBarrierSwap(
2645 FixedArray* array, int first, int second);
2647 // Swap descriptor first and second.
2648 inline void NoIncrementalWriteBarrierSwapDescriptors(
2649 int first, int second);
2651 FixedArray* GetContentArray() {
2652 return FixedArray::cast(get(kContentArrayIndex));
2654 DISALLOW_IMPLICIT_CONSTRUCTORS(DescriptorArray);
2658 // HashTable is a subclass of FixedArray that implements a hash table
2659 // that uses open addressing and quadratic probing.
2661 // In order for the quadratic probing to work, elements that have not
2662 // yet been used and elements that have been deleted are
2663 // distinguished. Probing continues when deleted elements are
2664 // encountered and stops when unused elements are encountered.
2666 // - Elements with key == undefined have not been used yet.
2667 // - Elements with key == the_hole have been deleted.
2669 // The hash table class is parameterized with a Shape and a Key.
2670 // Shape must be a class with the following interface:
2671 // class ExampleShape {
2673 // // Tells whether key matches other.
2674 // static bool IsMatch(Key key, Object* other);
2675 // // Returns the hash value for key.
2676 // static uint32_t Hash(Key key);
2677 // // Returns the hash value for object.
2678 // static uint32_t HashForObject(Key key, Object* object);
2679 // // Convert key to an object.
2680 // static inline Object* AsObject(Key key);
2681 // // The prefix size indicates number of elements in the beginning
2682 // // of the backing storage.
2683 // static const int kPrefixSize = ..;
2684 // // The Element size indicates number of elements per entry.
2685 // static const int kEntrySize = ..;
2687 // The prefix size indicates an amount of memory in the
2688 // beginning of the backing storage that can be used for non-element
2689 // information by subclasses.
2691 template<typename Key>
2694 static const bool UsesSeed = false;
2695 static uint32_t Hash(Key key) { return 0; }
2696 static uint32_t SeededHash(Key key, uint32_t seed) {
2700 static uint32_t HashForObject(Key key, Object* object) { return 0; }
2701 static uint32_t SeededHashForObject(Key key, uint32_t seed, Object* object) {
2703 return HashForObject(key, object);
2707 template<typename Shape, typename Key>
2708 class HashTable: public FixedArray {
2711 inline uint32_t Hash(Key key) {
2712 if (Shape::UsesSeed) {
2713 return Shape::SeededHash(key,
2714 GetHeap()->HashSeed());
2716 return Shape::Hash(key);
2720 inline uint32_t HashForObject(Key key, Object* object) {
2721 if (Shape::UsesSeed) {
2722 return Shape::SeededHashForObject(key,
2723 GetHeap()->HashSeed(), object);
2725 return Shape::HashForObject(key, object);
2729 // Returns the number of elements in the hash table.
2730 int NumberOfElements() {
2731 return Smi::cast(get(kNumberOfElementsIndex))->value();
2734 // Returns the number of deleted elements in the hash table.
2735 int NumberOfDeletedElements() {
2736 return Smi::cast(get(kNumberOfDeletedElementsIndex))->value();
2739 // Returns the capacity of the hash table.
2741 return Smi::cast(get(kCapacityIndex))->value();
2744 // ElementAdded should be called whenever an element is added to a
2746 void ElementAdded() { SetNumberOfElements(NumberOfElements() + 1); }
2748 // ElementRemoved should be called whenever an element is removed from
2750 void ElementRemoved() {
2751 SetNumberOfElements(NumberOfElements() - 1);
2752 SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
2754 void ElementsRemoved(int n) {
2755 SetNumberOfElements(NumberOfElements() - n);
2756 SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
2759 // Returns a new HashTable object. Might return Failure.
2760 MUST_USE_RESULT static MaybeObject* Allocate(
2761 int at_least_space_for,
2762 PretenureFlag pretenure = NOT_TENURED);
2764 // Computes the required capacity for a table holding the given
2765 // number of elements. May be more than HashTable::kMaxCapacity.
2766 static int ComputeCapacity(int at_least_space_for);
2768 // Returns the key at entry.
2769 Object* KeyAt(int entry) { return get(EntryToIndex(entry)); }
2771 // Tells whether k is a real key. The hole and undefined are not allowed
2772 // as keys and can be used to indicate missing or deleted elements.
2773 bool IsKey(Object* k) {
2774 return !k->IsTheHole() && !k->IsUndefined();
2777 // Garbage collection support.
2778 void IteratePrefix(ObjectVisitor* visitor);
2779 void IterateElements(ObjectVisitor* visitor);
2782 static inline HashTable* cast(Object* obj);
2784 // Compute the probe offset (quadratic probing).
2785 INLINE(static uint32_t GetProbeOffset(uint32_t n)) {
2786 return (n + n * n) >> 1;
2789 static const int kNumberOfElementsIndex = 0;
2790 static const int kNumberOfDeletedElementsIndex = 1;
2791 static const int kCapacityIndex = 2;
2792 static const int kPrefixStartIndex = 3;
2793 static const int kElementsStartIndex =
2794 kPrefixStartIndex + Shape::kPrefixSize;
2795 static const int kEntrySize = Shape::kEntrySize;
2796 static const int kElementsStartOffset =
2797 kHeaderSize + kElementsStartIndex * kPointerSize;
2798 static const int kCapacityOffset =
2799 kHeaderSize + kCapacityIndex * kPointerSize;
2801 // Constant used for denoting a absent entry.
2802 static const int kNotFound = -1;
2804 // Maximal capacity of HashTable. Based on maximal length of underlying
2805 // FixedArray. Staying below kMaxCapacity also ensures that EntryToIndex
2807 static const int kMaxCapacity =
2808 (FixedArray::kMaxLength - kElementsStartOffset) / kEntrySize;
2810 // Find entry for key otherwise return kNotFound.
2811 inline int FindEntry(Key key);
2812 int FindEntry(Isolate* isolate, Key key);
2815 // Find the entry at which to insert element with the given key that
2816 // has the given hash value.
2817 uint32_t FindInsertionEntry(uint32_t hash);
2819 // Returns the index for an entry (of the key)
2820 static inline int EntryToIndex(int entry) {
2821 return (entry * kEntrySize) + kElementsStartIndex;
2824 // Update the number of elements in the hash table.
2825 void SetNumberOfElements(int nof) {
2826 set(kNumberOfElementsIndex, Smi::FromInt(nof));
2829 // Update the number of deleted elements in the hash table.
2830 void SetNumberOfDeletedElements(int nod) {
2831 set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
2834 // Sets the capacity of the hash table.
2835 void SetCapacity(int capacity) {
2836 // To scale a computed hash code to fit within the hash table, we
2837 // use bit-wise AND with a mask, so the capacity must be positive
2839 ASSERT(capacity > 0);
2840 ASSERT(capacity <= kMaxCapacity);
2841 set(kCapacityIndex, Smi::FromInt(capacity));
2845 // Returns probe entry.
2846 static uint32_t GetProbe(uint32_t hash, uint32_t number, uint32_t size) {
2847 ASSERT(IsPowerOf2(size));
2848 return (hash + GetProbeOffset(number)) & (size - 1);
2851 static uint32_t FirstProbe(uint32_t hash, uint32_t size) {
2852 return hash & (size - 1);
2855 static uint32_t NextProbe(uint32_t last, uint32_t number, uint32_t size) {
2856 return (last + number) & (size - 1);
2859 // Rehashes this hash-table into the new table.
2860 MUST_USE_RESULT MaybeObject* Rehash(HashTable* new_table, Key key);
2862 // Attempt to shrink hash table after removal of key.
2863 MUST_USE_RESULT MaybeObject* Shrink(Key key);
2865 // Ensure enough space for n additional elements.
2866 MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
2870 // HashTableKey is an abstract superclass for virtual key behavior.
2871 class HashTableKey {
2873 // Returns whether the other object matches this key.
2874 virtual bool IsMatch(Object* other) = 0;
2875 // Returns the hash value for this key.
2876 virtual uint32_t Hash() = 0;
2877 // Returns the hash value for object.
2878 virtual uint32_t HashForObject(Object* key) = 0;
2879 // Returns the key object for storing into the hash table.
2880 // If allocations fails a failure object is returned.
2881 MUST_USE_RESULT virtual MaybeObject* AsObject() = 0;
2883 virtual ~HashTableKey() {}
2887 class SymbolTableShape : public BaseShape<HashTableKey*> {
2889 static inline bool IsMatch(HashTableKey* key, Object* value) {
2890 return key->IsMatch(value);
2892 static inline uint32_t Hash(HashTableKey* key) {
2895 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
2896 return key->HashForObject(object);
2898 MUST_USE_RESULT static inline MaybeObject* AsObject(HashTableKey* key) {
2899 return key->AsObject();
2902 static const int kPrefixSize = 0;
2903 static const int kEntrySize = 1;
2906 class SeqAsciiString;
2910 // No special elements in the prefix and the element size is 1
2911 // because only the symbol itself (the key) needs to be stored.
2912 class SymbolTable: public HashTable<SymbolTableShape, HashTableKey*> {
2914 // Find symbol in the symbol table. If it is not there yet, it is
2915 // added. The return value is the symbol table which might have
2916 // been enlarged. If the return value is not a failure, the symbol
2917 // pointer *s is set to the symbol found.
2918 MUST_USE_RESULT MaybeObject* LookupSymbol(Vector<const char> str, Object** s);
2919 MUST_USE_RESULT MaybeObject* LookupAsciiSymbol(Vector<const char> str,
2921 MUST_USE_RESULT MaybeObject* LookupSubStringAsciiSymbol(
2922 Handle<SeqAsciiString> str,
2926 MUST_USE_RESULT MaybeObject* LookupTwoByteSymbol(Vector<const uc16> str,
2928 MUST_USE_RESULT MaybeObject* LookupString(String* key, Object** s);
2930 // Looks up a symbol that is equal to the given string and returns
2931 // true if it is found, assigning the symbol to the given output
2933 bool LookupSymbolIfExists(String* str, String** symbol);
2934 bool LookupTwoCharsSymbolIfExists(uint32_t c1, uint32_t c2, String** symbol);
2937 static inline SymbolTable* cast(Object* obj);
2940 MUST_USE_RESULT MaybeObject* LookupKey(HashTableKey* key, Object** s);
2942 DISALLOW_IMPLICIT_CONSTRUCTORS(SymbolTable);
2946 class MapCacheShape : public BaseShape<HashTableKey*> {
2948 static inline bool IsMatch(HashTableKey* key, Object* value) {
2949 return key->IsMatch(value);
2951 static inline uint32_t Hash(HashTableKey* key) {
2955 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
2956 return key->HashForObject(object);
2959 MUST_USE_RESULT static inline MaybeObject* AsObject(HashTableKey* key) {
2960 return key->AsObject();
2963 static const int kPrefixSize = 0;
2964 static const int kEntrySize = 2;
2970 // Maps keys that are a fixed array of symbols to a map.
2971 // Used for canonicalize maps for object literals.
2972 class MapCache: public HashTable<MapCacheShape, HashTableKey*> {
2974 // Find cached value for a string key, otherwise return null.
2975 Object* Lookup(FixedArray* key);
2976 MUST_USE_RESULT MaybeObject* Put(FixedArray* key, Map* value);
2977 static inline MapCache* cast(Object* obj);
2980 DISALLOW_IMPLICIT_CONSTRUCTORS(MapCache);
2984 template <typename Shape, typename Key>
2985 class Dictionary: public HashTable<Shape, Key> {
2987 static inline Dictionary<Shape, Key>* cast(Object* obj) {
2988 return reinterpret_cast<Dictionary<Shape, Key>*>(obj);
2991 // Returns the value at entry.
2992 Object* ValueAt(int entry) {
2993 return this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 1);
2996 // Set the value for entry.
2997 void ValueAtPut(int entry, Object* value) {
2998 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 1, value);
3001 // Returns the property details for the property at entry.
3002 PropertyDetails DetailsAt(int entry) {
3003 ASSERT(entry >= 0); // Not found is -1, which is not caught by get().
3004 return PropertyDetails(
3005 Smi::cast(this->get(HashTable<Shape, Key>::EntryToIndex(entry) + 2)));
3008 // Set the details for entry.
3009 void DetailsAtPut(int entry, PropertyDetails value) {
3010 this->set(HashTable<Shape, Key>::EntryToIndex(entry) + 2, value.AsSmi());
3014 void CopyValuesTo(FixedArray* elements);
3016 // Delete a property from the dictionary.
3017 Object* DeleteProperty(int entry, JSObject::DeleteMode mode);
3019 // Attempt to shrink the dictionary after deletion of key.
3020 MUST_USE_RESULT MaybeObject* Shrink(Key key);
3022 // Returns the number of elements in the dictionary filtering out properties
3023 // with the specified attributes.
3024 int NumberOfElementsFilterAttributes(PropertyAttributes filter);
3026 // Returns the number of enumerable elements in the dictionary.
3027 int NumberOfEnumElements();
3029 enum SortMode { UNSORTED, SORTED };
3030 // Copies keys to preallocated fixed array.
3031 void CopyKeysTo(FixedArray* storage,
3032 PropertyAttributes filter,
3033 SortMode sort_mode);
3034 // Fill in details for properties into storage.
3035 void CopyKeysTo(FixedArray* storage, int index, SortMode sort_mode);
3037 // Accessors for next enumeration index.
3038 void SetNextEnumerationIndex(int index) {
3039 this->set(kNextEnumerationIndexIndex, Smi::FromInt(index));
3042 int NextEnumerationIndex() {
3043 return Smi::cast(FixedArray::get(kNextEnumerationIndexIndex))->value();
3046 // Returns a new array for dictionary usage. Might return Failure.
3047 MUST_USE_RESULT static MaybeObject* Allocate(int at_least_space_for);
3049 // Ensure enough space for n additional elements.
3050 MUST_USE_RESULT MaybeObject* EnsureCapacity(int n, Key key);
3053 inline void Print() {
3056 void Print(FILE* out);
3058 // Returns the key (slow).
3059 Object* SlowReverseLookup(Object* value);
3061 // Sets the entry to (key, value) pair.
3062 inline void SetEntry(int entry,
3065 inline void SetEntry(int entry,
3068 PropertyDetails details);
3070 MUST_USE_RESULT MaybeObject* Add(Key key,
3072 PropertyDetails details);
3075 // Generic at put operation.
3076 MUST_USE_RESULT MaybeObject* AtPut(Key key, Object* value);
3078 // Add entry to dictionary.
3079 MUST_USE_RESULT MaybeObject* AddEntry(Key key,
3081 PropertyDetails details,
3084 // Generate new enumeration indices to avoid enumeration index overflow.
3085 MUST_USE_RESULT MaybeObject* GenerateNewEnumerationIndices();
3086 static const int kMaxNumberKeyIndex =
3087 HashTable<Shape, Key>::kPrefixStartIndex;
3088 static const int kNextEnumerationIndexIndex = kMaxNumberKeyIndex + 1;
3092 class StringDictionaryShape : public BaseShape<String*> {
3094 static inline bool IsMatch(String* key, Object* other);
3095 static inline uint32_t Hash(String* key);
3096 static inline uint32_t HashForObject(String* key, Object* object);
3097 MUST_USE_RESULT static inline MaybeObject* AsObject(String* key);
3098 static const int kPrefixSize = 2;
3099 static const int kEntrySize = 3;
3100 static const bool kIsEnumerable = true;
3104 class StringDictionary: public Dictionary<StringDictionaryShape, String*> {
3106 static inline StringDictionary* cast(Object* obj) {
3107 ASSERT(obj->IsDictionary());
3108 return reinterpret_cast<StringDictionary*>(obj);
3111 // Copies enumerable keys to preallocated fixed array.
3112 void CopyEnumKeysTo(FixedArray* storage, FixedArray* sort_array);
3114 // For transforming properties of a JSObject.
3115 MUST_USE_RESULT MaybeObject* TransformPropertiesToFastFor(
3117 int unused_property_fields);
3119 // Find entry for key, otherwise return kNotFound. Optimized version of
3120 // HashTable::FindEntry.
3121 int FindEntry(String* key);
3123 bool ContainsTransition(int entry);
3127 class NumberDictionaryShape : public BaseShape<uint32_t> {
3129 static inline bool IsMatch(uint32_t key, Object* other);
3130 MUST_USE_RESULT static inline MaybeObject* AsObject(uint32_t key);
3131 static const int kEntrySize = 3;
3132 static const bool kIsEnumerable = false;
3136 class SeededNumberDictionaryShape : public NumberDictionaryShape {
3138 static const bool UsesSeed = true;
3139 static const int kPrefixSize = 2;
3141 static inline uint32_t SeededHash(uint32_t key, uint32_t seed);
3142 static inline uint32_t SeededHashForObject(uint32_t key,
3148 class UnseededNumberDictionaryShape : public NumberDictionaryShape {
3150 static const int kPrefixSize = 0;
3152 static inline uint32_t Hash(uint32_t key);
3153 static inline uint32_t HashForObject(uint32_t key, Object* object);
3157 class SeededNumberDictionary
3158 : public Dictionary<SeededNumberDictionaryShape, uint32_t> {
3160 static SeededNumberDictionary* cast(Object* obj) {
3161 ASSERT(obj->IsDictionary());
3162 return reinterpret_cast<SeededNumberDictionary*>(obj);
3165 // Type specific at put (default NONE attributes is used when adding).
3166 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
3167 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key,
3169 PropertyDetails details);
3171 // Set an existing entry or add a new one if needed.
3172 // Return the updated dictionary.
3173 MUST_USE_RESULT static Handle<SeededNumberDictionary> Set(
3174 Handle<SeededNumberDictionary> dictionary,
3176 Handle<Object> value,
3177 PropertyDetails details);
3179 MUST_USE_RESULT MaybeObject* Set(uint32_t key,
3181 PropertyDetails details);
3183 void UpdateMaxNumberKey(uint32_t key);
3185 // If slow elements are required we will never go back to fast-case
3186 // for the elements kept in this dictionary. We require slow
3187 // elements if an element has been added at an index larger than
3188 // kRequiresSlowElementsLimit or set_requires_slow_elements() has been called
3189 // when defining a getter or setter with a number key.
3190 inline bool requires_slow_elements();
3191 inline void set_requires_slow_elements();
3193 // Get the value of the max number key that has been added to this
3194 // dictionary. max_number_key can only be called if
3195 // requires_slow_elements returns false.
3196 inline uint32_t max_number_key();
3199 static const int kRequiresSlowElementsMask = 1;
3200 static const int kRequiresSlowElementsTagSize = 1;
3201 static const uint32_t kRequiresSlowElementsLimit = (1 << 29) - 1;
3205 class UnseededNumberDictionary
3206 : public Dictionary<UnseededNumberDictionaryShape, uint32_t> {
3208 static UnseededNumberDictionary* cast(Object* obj) {
3209 ASSERT(obj->IsDictionary());
3210 return reinterpret_cast<UnseededNumberDictionary*>(obj);
3213 // Type specific at put (default NONE attributes is used when adding).
3214 MUST_USE_RESULT MaybeObject* AtNumberPut(uint32_t key, Object* value);
3215 MUST_USE_RESULT MaybeObject* AddNumberEntry(uint32_t key, Object* value);
3217 // Set an existing entry or add a new one if needed.
3218 // Return the updated dictionary.
3219 MUST_USE_RESULT static Handle<UnseededNumberDictionary> Set(
3220 Handle<UnseededNumberDictionary> dictionary,
3222 Handle<Object> value);
3224 MUST_USE_RESULT MaybeObject* Set(uint32_t key, Object* value);
3228 template <int entrysize>
3229 class ObjectHashTableShape : public BaseShape<Object*> {
3231 static inline bool IsMatch(Object* key, Object* other);
3232 static inline uint32_t Hash(Object* key);
3233 static inline uint32_t HashForObject(Object* key, Object* object);
3234 MUST_USE_RESULT static inline MaybeObject* AsObject(Object* key);
3235 static const int kPrefixSize = 0;
3236 static const int kEntrySize = entrysize;
3240 // ObjectHashSet holds keys that are arbitrary objects by using the identity
3241 // hash of the key for hashing purposes.
3242 class ObjectHashSet: public HashTable<ObjectHashTableShape<1>, Object*> {
3244 static inline ObjectHashSet* cast(Object* obj) {
3245 ASSERT(obj->IsHashTable());
3246 return reinterpret_cast<ObjectHashSet*>(obj);
3249 // Looks up whether the given key is part of this hash set.
3250 bool Contains(Object* key);
3252 // Adds the given key to this hash set.
3253 MUST_USE_RESULT MaybeObject* Add(Object* key);
3255 // Removes the given key from this hash set.
3256 MUST_USE_RESULT MaybeObject* Remove(Object* key);
3260 // ObjectHashTable maps keys that are arbitrary objects to object values by
3261 // using the identity hash of the key for hashing purposes.
3262 class ObjectHashTable: public HashTable<ObjectHashTableShape<2>, Object*> {
3264 static inline ObjectHashTable* cast(Object* obj) {
3265 ASSERT(obj->IsHashTable());
3266 return reinterpret_cast<ObjectHashTable*>(obj);
3269 // Looks up the value associated with the given key. The undefined value is
3270 // returned in case the key is not present.
3271 Object* Lookup(Object* key);
3273 // Adds (or overwrites) the value associated with the given key. Mapping a
3274 // key to the undefined value causes removal of the whole entry.
3275 MUST_USE_RESULT MaybeObject* Put(Object* key, Object* value);
3278 friend class MarkCompactCollector;
3280 void AddEntry(int entry, Object* key, Object* value);
3281 void RemoveEntry(int entry);
3283 // Returns the index to the value of an entry.
3284 static inline int EntryToValueIndex(int entry) {
3285 return EntryToIndex(entry) + 1;
3290 // JSFunctionResultCache caches results of some JSFunction invocation.
3291 // It is a fixed array with fixed structure:
3292 // [0]: factory function
3293 // [1]: finger index
3294 // [2]: current cache size
3295 // [3]: dummy field.
3296 // The rest of array are key/value pairs.
3297 class JSFunctionResultCache: public FixedArray {
3299 static const int kFactoryIndex = 0;
3300 static const int kFingerIndex = kFactoryIndex + 1;
3301 static const int kCacheSizeIndex = kFingerIndex + 1;
3302 static const int kDummyIndex = kCacheSizeIndex + 1;
3303 static const int kEntriesIndex = kDummyIndex + 1;
3305 static const int kEntrySize = 2; // key + value
3307 static const int kFactoryOffset = kHeaderSize;
3308 static const int kFingerOffset = kFactoryOffset + kPointerSize;
3309 static const int kCacheSizeOffset = kFingerOffset + kPointerSize;
3311 inline void MakeZeroSize();
3312 inline void Clear();
3315 inline void set_size(int size);
3316 inline int finger_index();
3317 inline void set_finger_index(int finger_index);
3320 static inline JSFunctionResultCache* cast(Object* obj);
3323 void JSFunctionResultCacheVerify();
3328 // ScopeInfo represents information about different scopes of a source
3329 // program and the allocation of the scope's variables. Scope information
3330 // is stored in a compressed form in ScopeInfo objects and is used
3331 // at runtime (stack dumps, deoptimization, etc.).
3333 // This object provides quick access to scope info details for runtime
3335 class ScopeInfo : public FixedArray {
3337 static inline ScopeInfo* cast(Object* object);
3339 // Return the type of this scope.
3342 // Does this scope call eval?
3345 // Return the language mode of this scope.
3346 LanguageMode language_mode();
3348 // Does this scope make a non-strict eval call?
3349 bool CallsNonStrictEval() {
3350 return CallsEval() && (language_mode() == CLASSIC_MODE);
3353 // Return the total number of locals allocated on the stack and in the
3354 // context. This includes the parameters that are allocated in the context.
3357 // Return the number of stack slots for code. This number consists of two
3359 // 1. One stack slot per stack allocated local.
3360 // 2. One stack slot for the function name if it is stack allocated.
3361 int StackSlotCount();
3363 // Return the number of context slots for code if a context is allocated. This
3364 // number consists of three parts:
3365 // 1. Size of fixed header for every context: Context::MIN_CONTEXT_SLOTS
3366 // 2. One context slot per context allocated local.
3367 // 3. One context slot for the function name if it is context allocated.
3368 // Parameters allocated in the context count as context allocated locals. If
3369 // no contexts are allocated for this scope ContextLength returns 0.
3370 int ContextLength();
3372 // Is this scope the scope of a named function expression?
3373 bool HasFunctionName();
3375 // Return if this has context allocated locals.
3376 bool HasHeapAllocatedLocals();
3378 // Return if contexts are allocated for this scope.
3381 // Return the function_name if present.
3382 String* FunctionName();
3384 // Return the name of the given parameter.
3385 String* ParameterName(int var);
3387 // Return the name of the given local.
3388 String* LocalName(int var);
3390 // Return the name of the given stack local.
3391 String* StackLocalName(int var);
3393 // Return the name of the given context local.
3394 String* ContextLocalName(int var);
3396 // Return the mode of the given context local.
3397 VariableMode ContextLocalMode(int var);
3399 // Return the initialization flag of the given context local.
3400 InitializationFlag ContextLocalInitFlag(int var);
3402 // Lookup support for serialized scope info. Returns the
3403 // the stack slot index for a given slot name if the slot is
3404 // present; otherwise returns a value < 0. The name must be a symbol
3406 int StackSlotIndex(String* name);
3408 // Lookup support for serialized scope info. Returns the
3409 // context slot index for a given slot name if the slot is present; otherwise
3410 // returns a value < 0. The name must be a symbol (canonicalized).
3411 // If the slot is present and mode != NULL, sets *mode to the corresponding
3412 // mode for that variable.
3413 int ContextSlotIndex(String* name,
3415 InitializationFlag* init_flag);
3417 // Lookup support for serialized scope info. Returns the
3418 // parameter index for a given parameter name if the parameter is present;
3419 // otherwise returns a value < 0. The name must be a symbol (canonicalized).
3420 int ParameterIndex(String* name);
3422 // Lookup support for serialized scope info. Returns the
3423 // function context slot index if the function name is present (named
3424 // function expressions, only), otherwise returns a value < 0. The name
3425 // must be a symbol (canonicalized).
3426 int FunctionContextSlotIndex(String* name, VariableMode* mode);
3428 static Handle<ScopeInfo> Create(Scope* scope);
3430 // Serializes empty scope info.
3431 static ScopeInfo* Empty();
3437 // The layout of the static part of a ScopeInfo is as follows. Each entry is
3438 // numeric and occupies one array slot.
3439 // 1. A set of properties of the scope
3440 // 2. The number of parameters. This only applies to function scopes. For
3441 // non-function scopes this is 0.
3442 // 3. The number of non-parameter variables allocated on the stack.
3443 // 4. The number of non-parameter and parameter variables allocated in the
3445 #define FOR_EACH_NUMERIC_FIELD(V) \
3448 V(StackLocalCount) \
3449 V(ContextLocalCount)
3451 #define FIELD_ACCESSORS(name) \
3452 void Set##name(int value) { \
3453 set(k##name, Smi::FromInt(value)); \
3456 if (length() > 0) { \
3457 return Smi::cast(get(k##name))->value(); \
3462 FOR_EACH_NUMERIC_FIELD(FIELD_ACCESSORS)
3463 #undef FIELD_ACCESSORS
3467 #define DECL_INDEX(name) k##name,
3468 FOR_EACH_NUMERIC_FIELD(DECL_INDEX)
3470 #undef FOR_EACH_NUMERIC_FIELD
3474 // The layout of the variable part of a ScopeInfo is as follows:
3475 // 1. ParameterEntries:
3476 // This part stores the names of the parameters for function scopes. One
3477 // slot is used per parameter, so in total this part occupies
3478 // ParameterCount() slots in the array. For other scopes than function
3479 // scopes ParameterCount() is 0.
3480 // 2. StackLocalEntries:
3481 // Contains the names of local variables that are allocated on the stack,
3482 // in increasing order of the stack slot index. One slot is used per stack
3483 // local, so in total this part occupies StackLocalCount() slots in the
3485 // 3. ContextLocalNameEntries:
3486 // Contains the names of local variables and parameters that are allocated
3487 // in the context. They are stored in increasing order of the context slot
3488 // index starting with Context::MIN_CONTEXT_SLOTS. One slot is used per
3489 // context local, so in total this part occupies ContextLocalCount() slots
3491 // 4. ContextLocalInfoEntries:
3492 // Contains the variable modes and initialization flags corresponding to
3493 // the context locals in ContextLocalNameEntries. One slot is used per
3494 // context local, so in total this part occupies ContextLocalCount()
3495 // slots in the array.
3496 // 5. FunctionNameEntryIndex:
3497 // If the scope belongs to a named function expression this part contains
3498 // information about the function variable. It always occupies two array
3499 // slots: a. The name of the function variable.
3500 // b. The context or stack slot index for the variable.
3501 int ParameterEntriesIndex();
3502 int StackLocalEntriesIndex();
3503 int ContextLocalNameEntriesIndex();
3504 int ContextLocalInfoEntriesIndex();
3505 int FunctionNameEntryIndex();
3507 // Location of the function variable for named function expressions.
3508 enum FunctionVariableInfo {
3509 NONE, // No function name present.
3515 // Properties of scopes.
3516 class TypeField: public BitField<ScopeType, 0, 3> {};
3517 class CallsEvalField: public BitField<bool, 3, 1> {};
3518 class LanguageModeField: public BitField<LanguageMode, 4, 2> {};
3519 class FunctionVariableField: public BitField<FunctionVariableInfo, 6, 2> {};
3520 class FunctionVariableMode: public BitField<VariableMode, 8, 3> {};
3522 // BitFields representing the encoded information for context locals in the
3523 // ContextLocalInfoEntries part.
3524 class ContextLocalMode: public BitField<VariableMode, 0, 3> {};
3525 class ContextLocalInitFlag: public BitField<InitializationFlag, 3, 1> {};
3529 // The cache for maps used by normalized (dictionary mode) objects.
3530 // Such maps do not have property descriptors, so a typical program
3531 // needs very limited number of distinct normalized maps.
3532 class NormalizedMapCache: public FixedArray {
3534 static const int kEntries = 64;
3536 MUST_USE_RESULT MaybeObject* Get(JSObject* object,
3537 PropertyNormalizationMode mode);
3542 static inline NormalizedMapCache* cast(Object* obj);
3545 void NormalizedMapCacheVerify();
3550 // ByteArray represents fixed sized byte arrays. Used for the relocation info
3551 // that is attached to code objects.
3552 class ByteArray: public FixedArrayBase {
3554 inline int Size() { return RoundUp(length() + kHeaderSize, kPointerSize); }
3556 // Setter and getter.
3557 inline byte get(int index);
3558 inline void set(int index, byte value);
3560 // Treat contents as an int array.
3561 inline int get_int(int index);
3563 static int SizeFor(int length) {
3564 return OBJECT_POINTER_ALIGN(kHeaderSize + length);
3566 // We use byte arrays for free blocks in the heap. Given a desired size in
3567 // bytes that is a multiple of the word size and big enough to hold a byte
3568 // array, this function returns the number of elements a byte array should
3570 static int LengthFor(int size_in_bytes) {
3571 ASSERT(IsAligned(size_in_bytes, kPointerSize));
3572 ASSERT(size_in_bytes >= kHeaderSize);
3573 return size_in_bytes - kHeaderSize;
3576 // Returns data start address.
3577 inline Address GetDataStartAddress();
3579 // Returns a pointer to the ByteArray object for a given data start address.
3580 static inline ByteArray* FromDataStartAddress(Address address);
3583 static inline ByteArray* cast(Object* obj);
3585 // Dispatched behavior.
3586 inline int ByteArraySize() {
3587 return SizeFor(this->length());
3590 inline void ByteArrayPrint() {
3591 ByteArrayPrint(stdout);
3593 void ByteArrayPrint(FILE* out);
3596 void ByteArrayVerify();
3599 // Layout description.
3600 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3602 // Maximal memory consumption for a single ByteArray.
3603 static const int kMaxSize = 512 * MB;
3604 // Maximal length of a single ByteArray.
3605 static const int kMaxLength = kMaxSize - kHeaderSize;
3608 DISALLOW_IMPLICIT_CONSTRUCTORS(ByteArray);
3612 // FreeSpace represents fixed sized areas of the heap that are not currently in
3613 // use. Used by the heap and GC.
3614 class FreeSpace: public HeapObject {
3616 // [size]: size of the free space including the header.
3618 inline void set_size(int value);
3620 inline int Size() { return size(); }
3623 static inline FreeSpace* cast(Object* obj);
3626 inline void FreeSpacePrint() {
3627 FreeSpacePrint(stdout);
3629 void FreeSpacePrint(FILE* out);
3632 void FreeSpaceVerify();
3635 // Layout description.
3636 // Size is smi tagged when it is stored.
3637 static const int kSizeOffset = HeapObject::kHeaderSize;
3638 static const int kHeaderSize = kSizeOffset + kPointerSize;
3640 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3643 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeSpace);
3647 // An ExternalArray represents a fixed-size array of primitive values
3648 // which live outside the JavaScript heap. Its subclasses are used to
3649 // implement the CanvasArray types being defined in the WebGL
3650 // specification. As of this writing the first public draft is not yet
3651 // available, but Khronos members can access the draft at:
3652 // https://cvs.khronos.org/svn/repos/3dweb/trunk/doc/spec/WebGL-spec.html
3654 // The semantics of these arrays differ from CanvasPixelArray.
3655 // Out-of-range values passed to the setter are converted via a C
3656 // cast, not clamping. Out-of-range indices cause exceptions to be
3657 // raised rather than being silently ignored.
3658 class ExternalArray: public FixedArrayBase {
3660 inline bool is_the_hole(int index) { return false; }
3662 // [external_pointer]: The pointer to the external memory area backing this
3664 DECL_ACCESSORS(external_pointer, void) // Pointer to the data store.
3667 static inline ExternalArray* cast(Object* obj);
3669 // Maximal acceptable length for an external array.
3670 static const int kMaxLength = 0x3fffffff;
3672 // ExternalArray headers are not quadword aligned.
3673 static const int kExternalPointerOffset =
3674 POINTER_SIZE_ALIGN(FixedArrayBase::kLengthOffset + kPointerSize);
3675 static const int kHeaderSize = kExternalPointerOffset + kPointerSize;
3676 static const int kAlignedSize = OBJECT_POINTER_ALIGN(kHeaderSize);
3679 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalArray);
3683 // A ExternalPixelArray represents a fixed-size byte array with special
3684 // semantics used for implementing the CanvasPixelArray object. Please see the
3685 // specification at:
3687 // http://www.whatwg.org/specs/web-apps/current-work/
3688 // multipage/the-canvas-element.html#canvaspixelarray
3689 // In particular, write access clamps the value written to 0 or 255 if the
3690 // value written is outside this range.
3691 class ExternalPixelArray: public ExternalArray {
3693 inline uint8_t* external_pixel_pointer();
3695 // Setter and getter.
3696 inline uint8_t get_scalar(int index);
3697 MUST_USE_RESULT inline MaybeObject* get(int index);
3698 inline void set(int index, uint8_t value);
3700 // This accessor applies the correct conversion from Smi, HeapNumber and
3701 // undefined and clamps the converted value between 0 and 255.
3702 Object* SetValue(uint32_t index, Object* value);
3705 static inline ExternalPixelArray* cast(Object* obj);
3708 inline void ExternalPixelArrayPrint() {
3709 ExternalPixelArrayPrint(stdout);
3711 void ExternalPixelArrayPrint(FILE* out);
3714 void ExternalPixelArrayVerify();
3718 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalPixelArray);
3722 class ExternalByteArray: public ExternalArray {
3724 // Setter and getter.
3725 inline int8_t get_scalar(int index);
3726 MUST_USE_RESULT inline MaybeObject* get(int index);
3727 inline void set(int index, int8_t value);
3729 // This accessor applies the correct conversion from Smi, HeapNumber
3731 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3734 static inline ExternalByteArray* cast(Object* obj);
3737 inline void ExternalByteArrayPrint() {
3738 ExternalByteArrayPrint(stdout);
3740 void ExternalByteArrayPrint(FILE* out);
3743 void ExternalByteArrayVerify();
3747 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalByteArray);
3751 class ExternalUnsignedByteArray: public ExternalArray {
3753 // Setter and getter.
3754 inline uint8_t get_scalar(int index);
3755 MUST_USE_RESULT inline MaybeObject* get(int index);
3756 inline void set(int index, uint8_t value);
3758 // This accessor applies the correct conversion from Smi, HeapNumber
3760 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3763 static inline ExternalUnsignedByteArray* cast(Object* obj);
3766 inline void ExternalUnsignedByteArrayPrint() {
3767 ExternalUnsignedByteArrayPrint(stdout);
3769 void ExternalUnsignedByteArrayPrint(FILE* out);
3772 void ExternalUnsignedByteArrayVerify();
3776 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedByteArray);
3780 class ExternalShortArray: public ExternalArray {
3782 // Setter and getter.
3783 inline int16_t get_scalar(int index);
3784 MUST_USE_RESULT inline MaybeObject* get(int index);
3785 inline void set(int index, int16_t value);
3787 // This accessor applies the correct conversion from Smi, HeapNumber
3789 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3792 static inline ExternalShortArray* cast(Object* obj);
3795 inline void ExternalShortArrayPrint() {
3796 ExternalShortArrayPrint(stdout);
3798 void ExternalShortArrayPrint(FILE* out);
3801 void ExternalShortArrayVerify();
3805 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalShortArray);
3809 class ExternalUnsignedShortArray: public ExternalArray {
3811 // Setter and getter.
3812 inline uint16_t get_scalar(int index);
3813 MUST_USE_RESULT inline MaybeObject* get(int index);
3814 inline void set(int index, uint16_t value);
3816 // This accessor applies the correct conversion from Smi, HeapNumber
3818 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3821 static inline ExternalUnsignedShortArray* cast(Object* obj);
3824 inline void ExternalUnsignedShortArrayPrint() {
3825 ExternalUnsignedShortArrayPrint(stdout);
3827 void ExternalUnsignedShortArrayPrint(FILE* out);
3830 void ExternalUnsignedShortArrayVerify();
3834 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedShortArray);
3838 class ExternalIntArray: public ExternalArray {
3840 // Setter and getter.
3841 inline int32_t get_scalar(int index);
3842 MUST_USE_RESULT inline MaybeObject* get(int index);
3843 inline void set(int index, int32_t value);
3845 // This accessor applies the correct conversion from Smi, HeapNumber
3847 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3850 static inline ExternalIntArray* cast(Object* obj);
3853 inline void ExternalIntArrayPrint() {
3854 ExternalIntArrayPrint(stdout);
3856 void ExternalIntArrayPrint(FILE* out);
3859 void ExternalIntArrayVerify();
3863 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalIntArray);
3867 class ExternalUnsignedIntArray: public ExternalArray {
3869 // Setter and getter.
3870 inline uint32_t get_scalar(int index);
3871 MUST_USE_RESULT inline MaybeObject* get(int index);
3872 inline void set(int index, uint32_t value);
3874 // This accessor applies the correct conversion from Smi, HeapNumber
3876 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3879 static inline ExternalUnsignedIntArray* cast(Object* obj);
3882 inline void ExternalUnsignedIntArrayPrint() {
3883 ExternalUnsignedIntArrayPrint(stdout);
3885 void ExternalUnsignedIntArrayPrint(FILE* out);
3888 void ExternalUnsignedIntArrayVerify();
3892 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalUnsignedIntArray);
3896 class ExternalFloatArray: public ExternalArray {
3898 // Setter and getter.
3899 inline float get_scalar(int index);
3900 MUST_USE_RESULT inline MaybeObject* get(int index);
3901 inline void set(int index, float value);
3903 // This accessor applies the correct conversion from Smi, HeapNumber
3905 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3908 static inline ExternalFloatArray* cast(Object* obj);
3911 inline void ExternalFloatArrayPrint() {
3912 ExternalFloatArrayPrint(stdout);
3914 void ExternalFloatArrayPrint(FILE* out);
3917 void ExternalFloatArrayVerify();
3921 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalFloatArray);
3925 class ExternalDoubleArray: public ExternalArray {
3927 // Setter and getter.
3928 inline double get_scalar(int index);
3929 MUST_USE_RESULT inline MaybeObject* get(int index);
3930 inline void set(int index, double value);
3932 // This accessor applies the correct conversion from Smi, HeapNumber
3934 MUST_USE_RESULT MaybeObject* SetValue(uint32_t index, Object* value);
3937 static inline ExternalDoubleArray* cast(Object* obj);
3940 inline void ExternalDoubleArrayPrint() {
3941 ExternalDoubleArrayPrint(stdout);
3943 void ExternalDoubleArrayPrint(FILE* out);
3944 #endif // OBJECT_PRINT
3946 void ExternalDoubleArrayVerify();
3950 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalDoubleArray);
3954 // DeoptimizationInputData is a fixed array used to hold the deoptimization
3955 // data for code generated by the Hydrogen/Lithium compiler. It also
3956 // contains information about functions that were inlined. If N different
3957 // functions were inlined then first N elements of the literal array will
3958 // contain these functions.
3961 class DeoptimizationInputData: public FixedArray {
3963 // Layout description. Indices in the array.
3964 static const int kTranslationByteArrayIndex = 0;
3965 static const int kInlinedFunctionCountIndex = 1;
3966 static const int kLiteralArrayIndex = 2;
3967 static const int kOsrAstIdIndex = 3;
3968 static const int kOsrPcOffsetIndex = 4;
3969 static const int kFirstDeoptEntryIndex = 5;
3971 // Offsets of deopt entry elements relative to the start of the entry.
3972 static const int kAstIdOffset = 0;
3973 static const int kTranslationIndexOffset = 1;
3974 static const int kArgumentsStackHeightOffset = 2;
3975 static const int kPcOffset = 3;
3976 static const int kDeoptEntrySize = 4;
3978 // Simple element accessors.
3979 #define DEFINE_ELEMENT_ACCESSORS(name, type) \
3981 return type::cast(get(k##name##Index)); \
3983 void Set##name(type* value) { \
3984 set(k##name##Index, value); \
3987 DEFINE_ELEMENT_ACCESSORS(TranslationByteArray, ByteArray)
3988 DEFINE_ELEMENT_ACCESSORS(InlinedFunctionCount, Smi)
3989 DEFINE_ELEMENT_ACCESSORS(LiteralArray, FixedArray)
3990 DEFINE_ELEMENT_ACCESSORS(OsrAstId, Smi)
3991 DEFINE_ELEMENT_ACCESSORS(OsrPcOffset, Smi)
3993 #undef DEFINE_ELEMENT_ACCESSORS
3995 // Accessors for elements of the ith deoptimization entry.
3996 #define DEFINE_ENTRY_ACCESSORS(name, type) \
3997 type* name(int i) { \
3998 return type::cast(get(IndexForEntry(i) + k##name##Offset)); \
4000 void Set##name(int i, type* value) { \
4001 set(IndexForEntry(i) + k##name##Offset, value); \
4004 DEFINE_ENTRY_ACCESSORS(AstId, Smi)
4005 DEFINE_ENTRY_ACCESSORS(TranslationIndex, Smi)
4006 DEFINE_ENTRY_ACCESSORS(ArgumentsStackHeight, Smi)
4007 DEFINE_ENTRY_ACCESSORS(Pc, Smi)
4009 #undef DEFINE_ENTRY_ACCESSORS
4012 return (length() - kFirstDeoptEntryIndex) / kDeoptEntrySize;
4015 // Allocates a DeoptimizationInputData.
4016 MUST_USE_RESULT static MaybeObject* Allocate(int deopt_entry_count,
4017 PretenureFlag pretenure);
4020 static inline DeoptimizationInputData* cast(Object* obj);
4022 #ifdef ENABLE_DISASSEMBLER
4023 void DeoptimizationInputDataPrint(FILE* out);
4027 static int IndexForEntry(int i) {
4028 return kFirstDeoptEntryIndex + (i * kDeoptEntrySize);
4031 static int LengthFor(int entry_count) {
4032 return IndexForEntry(entry_count);
4037 // DeoptimizationOutputData is a fixed array used to hold the deoptimization
4038 // data for code generated by the full compiler.
4039 // The format of the these objects is
4040 // [i * 2]: Ast ID for ith deoptimization.
4041 // [i * 2 + 1]: PC and state of ith deoptimization
4042 class DeoptimizationOutputData: public FixedArray {
4044 int DeoptPoints() { return length() / 2; }
4045 Smi* AstId(int index) { return Smi::cast(get(index * 2)); }
4046 void SetAstId(int index, Smi* id) { set(index * 2, id); }
4047 Smi* PcAndState(int index) { return Smi::cast(get(1 + index * 2)); }
4048 void SetPcAndState(int index, Smi* offset) { set(1 + index * 2, offset); }
4050 static int LengthOfFixedArray(int deopt_points) {
4051 return deopt_points * 2;
4054 // Allocates a DeoptimizationOutputData.
4055 MUST_USE_RESULT static MaybeObject* Allocate(int number_of_deopt_points,
4056 PretenureFlag pretenure);
4059 static inline DeoptimizationOutputData* cast(Object* obj);
4061 #if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
4062 void DeoptimizationOutputDataPrint(FILE* out);
4067 // Forward declaration.
4068 class JSGlobalPropertyCell;
4070 // TypeFeedbackCells is a fixed array used to hold the association between
4071 // cache cells and AST ids for code generated by the full compiler.
4072 // The format of the these objects is
4073 // [i * 2]: Global property cell of ith cache cell.
4074 // [i * 2 + 1]: Ast ID for ith cache cell.
4075 class TypeFeedbackCells: public FixedArray {
4077 int CellCount() { return length() / 2; }
4078 static int LengthOfFixedArray(int cell_count) { return cell_count * 2; }
4080 // Accessors for AST ids associated with cache values.
4081 inline Smi* AstId(int index);
4082 inline void SetAstId(int index, Smi* id);
4084 // Accessors for global property cells holding the cache values.
4085 inline JSGlobalPropertyCell* Cell(int index);
4086 inline void SetCell(int index, JSGlobalPropertyCell* cell);
4088 // The object that indicates an uninitialized cache.
4089 static inline Handle<Object> UninitializedSentinel(Isolate* isolate);
4091 // The object that indicates a megamorphic state.
4092 static inline Handle<Object> MegamorphicSentinel(Isolate* isolate);
4094 // A raw version of the uninitialized sentinel that's safe to read during
4095 // garbage collection (e.g., for patching the cache).
4096 static inline Object* RawUninitializedSentinel(Heap* heap);
4099 static inline TypeFeedbackCells* cast(Object* obj);
4101 static const int kForInFastCaseMarker = 0;
4102 static const int kForInSlowCaseMarker = 1;
4106 // Forward declaration.
4107 class SafepointEntry;
4108 class TypeFeedbackInfo;
4110 // Code describes objects with on-the-fly generated machine code.
4111 class Code: public HeapObject {
4113 // Opaque data type for encapsulating code flags like kind, inline
4114 // cache state, and arguments count.
4115 // FLAGS_MIN_VALUE and FLAGS_MAX_VALUE are specified to ensure that
4116 // enumeration type has correct value range (see Issue 830 for more details).
4118 FLAGS_MIN_VALUE = kMinInt,
4119 FLAGS_MAX_VALUE = kMaxInt
4137 // No more than 16 kinds. The value currently encoded in four bits in
4142 FIRST_IC_KIND = LOAD_IC,
4143 LAST_IC_KIND = TO_BOOLEAN_IC
4147 NUMBER_OF_KINDS = LAST_IC_KIND + 1
4150 typedef int ExtraICState;
4152 static const ExtraICState kNoExtraICState = 0;
4154 #ifdef ENABLE_DISASSEMBLER
4156 static const char* Kind2String(Kind kind);
4157 static const char* ICState2String(InlineCacheState state);
4158 static const char* PropertyType2String(PropertyType type);
4159 static void PrintExtraICState(FILE* out, Kind kind, ExtraICState extra);
4160 inline void Disassemble(const char* name) {
4161 Disassemble(name, stdout);
4163 void Disassemble(const char* name, FILE* out);
4164 #endif // ENABLE_DISASSEMBLER
4166 // [instruction_size]: Size of the native instructions
4167 inline int instruction_size();
4168 inline void set_instruction_size(int value);
4170 // [relocation_info]: Code relocation information
4171 DECL_ACCESSORS(relocation_info, ByteArray)
4172 void InvalidateRelocation();
4174 // [handler_table]: Fixed array containing offsets of exception handlers.
4175 DECL_ACCESSORS(handler_table, FixedArray)
4177 // [deoptimization_data]: Array containing data for deopt.
4178 DECL_ACCESSORS(deoptimization_data, FixedArray)
4180 // [type_feedback_info]: Struct containing type feedback information.
4181 // Will contain either a TypeFeedbackInfo object, or undefined.
4182 DECL_ACCESSORS(type_feedback_info, Object)
4184 // [gc_metadata]: Field used to hold GC related metadata. The contents of this
4185 // field does not have to be traced during garbage collection since
4186 // it is only used by the garbage collector itself.
4187 DECL_ACCESSORS(gc_metadata, Object)
4189 // [ic_age]: Inline caching age: the value of the Heap::global_ic_age
4190 // at the moment when this object was created.
4191 inline void set_ic_age(int count);
4192 inline int ic_age();
4194 // Unchecked accessors to be used during GC.
4195 inline ByteArray* unchecked_relocation_info();
4196 inline FixedArray* unchecked_deoptimization_data();
4198 inline int relocation_size();
4200 // [flags]: Various code flags.
4201 inline Flags flags();
4202 inline void set_flags(Flags flags);
4204 // [flags]: Access to specific code flags.
4206 inline InlineCacheState ic_state(); // Only valid for IC stubs.
4207 inline ExtraICState extra_ic_state(); // Only valid for IC stubs.
4208 inline PropertyType type(); // Only valid for monomorphic IC stubs.
4209 inline int arguments_count(); // Only valid for call IC stubs.
4211 // Testers for IC stub kinds.
4212 inline bool is_inline_cache_stub();
4213 inline bool is_load_stub() { return kind() == LOAD_IC; }
4214 inline bool is_keyed_load_stub() { return kind() == KEYED_LOAD_IC; }
4215 inline bool is_store_stub() { return kind() == STORE_IC; }
4216 inline bool is_keyed_store_stub() { return kind() == KEYED_STORE_IC; }
4217 inline bool is_call_stub() { return kind() == CALL_IC; }
4218 inline bool is_keyed_call_stub() { return kind() == KEYED_CALL_IC; }
4219 inline bool is_unary_op_stub() { return kind() == UNARY_OP_IC; }
4220 inline bool is_binary_op_stub() { return kind() == BINARY_OP_IC; }
4221 inline bool is_compare_ic_stub() { return kind() == COMPARE_IC; }
4222 inline bool is_to_boolean_ic_stub() { return kind() == TO_BOOLEAN_IC; }
4224 // [major_key]: For kind STUB or BINARY_OP_IC, the major key.
4225 inline int major_key();
4226 inline void set_major_key(int value);
4228 // For stubs, tells whether they should always exist, so that they can be
4229 // called from other stubs.
4230 inline bool is_pregenerated();
4231 inline void set_is_pregenerated(bool value);
4233 // [optimizable]: For FUNCTION kind, tells if it is optimizable.
4234 inline bool optimizable();
4235 inline void set_optimizable(bool value);
4237 // [has_deoptimization_support]: For FUNCTION kind, tells if it has
4238 // deoptimization support.
4239 inline bool has_deoptimization_support();
4240 inline void set_has_deoptimization_support(bool value);
4242 // [has_debug_break_slots]: For FUNCTION kind, tells if it has
4243 // been compiled with debug break slots.
4244 inline bool has_debug_break_slots();
4245 inline void set_has_debug_break_slots(bool value);
4247 // [compiled_with_optimizing]: For FUNCTION kind, tells if it has
4248 // been compiled with IsOptimizing set to true.
4249 inline bool is_compiled_optimizable();
4250 inline void set_compiled_optimizable(bool value);
4252 // [allow_osr_at_loop_nesting_level]: For FUNCTION kind, tells for
4253 // how long the function has been marked for OSR and therefore which
4254 // level of loop nesting we are willing to do on-stack replacement
4256 inline void set_allow_osr_at_loop_nesting_level(int level);
4257 inline int allow_osr_at_loop_nesting_level();
4259 // [profiler_ticks]: For FUNCTION kind, tells for how many profiler ticks
4260 // the code object was seen on the stack with no IC patching going on.
4261 inline int profiler_ticks();
4262 inline void set_profiler_ticks(int ticks);
4264 // [stack_slots]: For kind OPTIMIZED_FUNCTION, the number of stack slots
4265 // reserved in the code prologue.
4266 inline unsigned stack_slots();
4267 inline void set_stack_slots(unsigned slots);
4269 // [safepoint_table_start]: For kind OPTIMIZED_CODE, the offset in
4270 // the instruction stream where the safepoint table starts.
4271 inline unsigned safepoint_table_offset();
4272 inline void set_safepoint_table_offset(unsigned offset);
4274 // [stack_check_table_start]: For kind FUNCTION, the offset in the
4275 // instruction stream where the stack check table starts.
4276 inline unsigned stack_check_table_offset();
4277 inline void set_stack_check_table_offset(unsigned offset);
4279 // [check type]: For kind CALL_IC, tells how to check if the
4280 // receiver is valid for the given call.
4281 inline CheckType check_type();
4282 inline void set_check_type(CheckType value);
4284 // [type-recording unary op type]: For kind UNARY_OP_IC.
4285 inline byte unary_op_type();
4286 inline void set_unary_op_type(byte value);
4288 // [type-recording binary op type]: For kind BINARY_OP_IC.
4289 inline byte binary_op_type();
4290 inline void set_binary_op_type(byte value);
4291 inline byte binary_op_result_type();
4292 inline void set_binary_op_result_type(byte value);
4294 // [compare state]: For kind COMPARE_IC, tells what state the stub is in.
4295 inline byte compare_state();
4296 inline void set_compare_state(byte value);
4298 // [to_boolean_foo]: For kind TO_BOOLEAN_IC tells what state the stub is in.
4299 inline byte to_boolean_state();
4300 inline void set_to_boolean_state(byte value);
4302 // [has_function_cache]: For kind STUB tells whether there is a function
4303 // cache is passed to the stub.
4304 inline bool has_function_cache();
4305 inline void set_has_function_cache(bool flag);
4307 // Get the safepoint entry for the given pc.
4308 SafepointEntry GetSafepointEntry(Address pc);
4310 // Mark this code object as not having a stack check table. Assumes kind
4312 void SetNoStackCheckTable();
4314 // Find the first map in an IC stub.
4315 Map* FindFirstMap();
4317 class ExtraICStateStrictMode: public BitField<StrictModeFlag, 0, 1> {};
4318 class ExtraICStateKeyedAccessGrowMode:
4319 public BitField<KeyedAccessGrowMode, 1, 1> {}; // NOLINT
4321 static const int kExtraICStateGrowModeShift = 1;
4323 static inline StrictModeFlag GetStrictMode(ExtraICState extra_ic_state) {
4324 return ExtraICStateStrictMode::decode(extra_ic_state);
4327 static inline KeyedAccessGrowMode GetKeyedAccessGrowMode(
4328 ExtraICState extra_ic_state) {
4329 return ExtraICStateKeyedAccessGrowMode::decode(extra_ic_state);
4332 static inline ExtraICState ComputeExtraICState(
4333 KeyedAccessGrowMode grow_mode,
4334 StrictModeFlag strict_mode) {
4335 return ExtraICStateKeyedAccessGrowMode::encode(grow_mode) |
4336 ExtraICStateStrictMode::encode(strict_mode);
4339 // Flags operations.
4340 static inline Flags ComputeFlags(
4342 InlineCacheState ic_state = UNINITIALIZED,
4343 ExtraICState extra_ic_state = kNoExtraICState,
4344 PropertyType type = NORMAL,
4346 InlineCacheHolderFlag holder = OWN_MAP);
4348 static inline Flags ComputeMonomorphicFlags(
4351 ExtraICState extra_ic_state = kNoExtraICState,
4352 InlineCacheHolderFlag holder = OWN_MAP,
4355 static inline InlineCacheState ExtractICStateFromFlags(Flags flags);
4356 static inline PropertyType ExtractTypeFromFlags(Flags flags);
4357 static inline Kind ExtractKindFromFlags(Flags flags);
4358 static inline InlineCacheHolderFlag ExtractCacheHolderFromFlags(Flags flags);
4359 static inline ExtraICState ExtractExtraICStateFromFlags(Flags flags);
4360 static inline int ExtractArgumentsCountFromFlags(Flags flags);
4362 static inline Flags RemoveTypeFromFlags(Flags flags);
4364 // Convert a target address into a code object.
4365 static inline Code* GetCodeFromTargetAddress(Address address);
4367 // Convert an entry address into an object.
4368 static inline Object* GetObjectFromEntryAddress(Address location_of_address);
4370 // Returns the address of the first instruction.
4371 inline byte* instruction_start();
4373 // Returns the address right after the last instruction.
4374 inline byte* instruction_end();
4376 // Returns the size of the instructions, padding, and relocation information.
4377 inline int body_size();
4379 // Returns the address of the first relocation info (read backwards!).
4380 inline byte* relocation_start();
4382 // Code entry point.
4383 inline byte* entry();
4385 // Returns true if pc is inside this object's instructions.
4386 inline bool contains(byte* pc);
4388 // Relocate the code by delta bytes. Called to signal that this code
4389 // object has been moved by delta bytes.
4390 void Relocate(intptr_t delta);
4392 // Migrate code described by desc.
4393 void CopyFrom(const CodeDesc& desc);
4395 // Returns the object size for a given body (used for allocation).
4396 static int SizeFor(int body_size) {
4397 ASSERT_SIZE_TAG_ALIGNED(body_size);
4398 return RoundUp(kHeaderSize + body_size, kCodeAlignment);
4401 // Calculate the size of the code object to report for log events. This takes
4402 // the layout of the code object into account.
4403 int ExecutableSize() {
4404 // Check that the assumptions about the layout of the code object holds.
4405 ASSERT_EQ(static_cast<int>(instruction_start() - address()),
4407 return instruction_size() + Code::kHeaderSize;
4410 // Locating source position.
4411 int SourcePosition(Address pc);
4412 int SourceStatementPosition(Address pc);
4415 static inline Code* cast(Object* obj);
4417 // Dispatched behavior.
4418 int CodeSize() { return SizeFor(body_size()); }
4419 inline void CodeIterateBody(ObjectVisitor* v);
4421 template<typename StaticVisitor>
4422 inline void CodeIterateBody(Heap* heap);
4424 inline void CodePrint() {
4427 void CodePrint(FILE* out);
4432 void ClearInlineCaches();
4434 // Max loop nesting marker used to postpose OSR. We don't take loop
4435 // nesting that is deeper than 5 levels into account.
4436 static const int kMaxLoopNestingMarker = 6;
4438 // Layout description.
4439 static const int kInstructionSizeOffset = HeapObject::kHeaderSize;
4440 static const int kRelocationInfoOffset = kInstructionSizeOffset + kIntSize;
4441 static const int kHandlerTableOffset = kRelocationInfoOffset + kPointerSize;
4442 static const int kDeoptimizationDataOffset =
4443 kHandlerTableOffset + kPointerSize;
4444 static const int kTypeFeedbackInfoOffset =
4445 kDeoptimizationDataOffset + kPointerSize;
4446 static const int kGCMetadataOffset = kTypeFeedbackInfoOffset + kPointerSize;
4447 static const int kICAgeOffset =
4448 kGCMetadataOffset + kPointerSize;
4449 static const int kFlagsOffset = kICAgeOffset + kIntSize;
4450 static const int kKindSpecificFlagsOffset = kFlagsOffset + kIntSize;
4451 static const int kKindSpecificFlagsSize = 2 * kIntSize;
4453 static const int kHeaderPaddingStart = kKindSpecificFlagsOffset +
4454 kKindSpecificFlagsSize;
4456 // Add padding to align the instruction start following right after
4457 // the Code object header.
4458 static const int kHeaderSize =
4459 (kHeaderPaddingStart + kCodeAlignmentMask) & ~kCodeAlignmentMask;
4461 // Byte offsets within kKindSpecificFlagsOffset.
4462 static const int kStubMajorKeyOffset = kKindSpecificFlagsOffset;
4463 static const int kOptimizableOffset = kKindSpecificFlagsOffset;
4464 static const int kStackSlotsOffset = kKindSpecificFlagsOffset;
4465 static const int kCheckTypeOffset = kKindSpecificFlagsOffset;
4467 static const int kUnaryOpTypeOffset = kStubMajorKeyOffset + 1;
4468 static const int kBinaryOpTypeOffset = kStubMajorKeyOffset + 1;
4469 static const int kCompareStateOffset = kStubMajorKeyOffset + 1;
4470 static const int kToBooleanTypeOffset = kStubMajorKeyOffset + 1;
4471 static const int kHasFunctionCacheOffset = kStubMajorKeyOffset + 1;
4473 static const int kFullCodeFlags = kOptimizableOffset + 1;
4474 class FullCodeFlagsHasDeoptimizationSupportField:
4475 public BitField<bool, 0, 1> {}; // NOLINT
4476 class FullCodeFlagsHasDebugBreakSlotsField: public BitField<bool, 1, 1> {};
4477 class FullCodeFlagsIsCompiledOptimizable: public BitField<bool, 2, 1> {};
4479 static const int kBinaryOpReturnTypeOffset = kBinaryOpTypeOffset + 1;
4481 static const int kAllowOSRAtLoopNestingLevelOffset = kFullCodeFlags + 1;
4482 static const int kProfilerTicksOffset = kAllowOSRAtLoopNestingLevelOffset + 1;
4484 static const int kSafepointTableOffsetOffset = kStackSlotsOffset + kIntSize;
4485 static const int kStackCheckTableOffsetOffset = kStackSlotsOffset + kIntSize;
4487 // Flags layout. BitField<type, shift, size>.
4488 class ICStateField: public BitField<InlineCacheState, 0, 3> {};
4489 class TypeField: public BitField<PropertyType, 3, 4> {};
4490 class CacheHolderField: public BitField<InlineCacheHolderFlag, 7, 1> {};
4491 class KindField: public BitField<Kind, 8, 4> {};
4492 class ExtraICStateField: public BitField<ExtraICState, 12, 2> {};
4493 class IsPregeneratedField: public BitField<bool, 14, 1> {};
4495 // Signed field cannot be encoded using the BitField class.
4496 static const int kArgumentsCountShift = 15;
4497 static const int kArgumentsCountMask = ~((1 << kArgumentsCountShift) - 1);
4499 // This constant should be encodable in an ARM instruction.
4500 static const int kFlagsNotUsedInLookup =
4501 TypeField::kMask | CacheHolderField::kMask;
4504 DISALLOW_IMPLICIT_CONSTRUCTORS(Code);
4508 // All heap objects have a Map that describes their structure.
4509 // A Map contains information about:
4510 // - Size information about the object
4511 // - How to iterate over an object (for garbage collection)
4512 class Map: public HeapObject {
4515 // Size in bytes or kVariableSizeSentinel if instances do not have
4517 inline int instance_size();
4518 inline void set_instance_size(int value);
4520 // Count of properties allocated in the object.
4521 inline int inobject_properties();
4522 inline void set_inobject_properties(int value);
4524 // Count of property fields pre-allocated in the object when first allocated.
4525 inline int pre_allocated_property_fields();
4526 inline void set_pre_allocated_property_fields(int value);
4529 inline InstanceType instance_type();
4530 inline void set_instance_type(InstanceType value);
4532 // Tells how many unused property fields are available in the
4533 // instance (only used for JSObject in fast mode).
4534 inline int unused_property_fields();
4535 inline void set_unused_property_fields(int value);
4538 inline byte bit_field();
4539 inline void set_bit_field(byte value);
4542 inline byte bit_field2();
4543 inline void set_bit_field2(byte value);
4546 // TODO(1399): It should be possible to make room for bit_field3 in the map
4547 // without overloading the instance descriptors field (and storing it in the
4548 // DescriptorArray when the map has one).
4549 inline int bit_field3();
4550 inline void set_bit_field3(int value);
4552 // Tells whether the object in the prototype property will be used
4553 // for instances created from this function. If the prototype
4554 // property is set to a value that is not a JSObject, the prototype
4555 // property will not be used to create instances of the function.
4556 // See ECMA-262, 13.2.2.
4557 inline void set_non_instance_prototype(bool value);
4558 inline bool has_non_instance_prototype();
4560 // Tells whether function has special prototype property. If not, prototype
4561 // property will not be created when accessed (will return undefined),
4562 // and construction from this function will not be allowed.
4563 inline void set_function_with_prototype(bool value);
4564 inline bool function_with_prototype();
4566 // Tells whether the instance with this map should be ignored by the
4567 // __proto__ accessor.
4568 inline void set_is_hidden_prototype() {
4569 set_bit_field(bit_field() | (1 << kIsHiddenPrototype));
4572 inline bool is_hidden_prototype() {
4573 return ((1 << kIsHiddenPrototype) & bit_field()) != 0;
4576 // Records and queries whether the instance has a named interceptor.
4577 inline void set_has_named_interceptor() {
4578 set_bit_field(bit_field() | (1 << kHasNamedInterceptor));
4581 inline bool has_named_interceptor() {
4582 return ((1 << kHasNamedInterceptor) & bit_field()) != 0;
4585 // Records and queries whether the instance has an indexed interceptor.
4586 inline void set_has_indexed_interceptor() {
4587 set_bit_field(bit_field() | (1 << kHasIndexedInterceptor));
4590 inline bool has_indexed_interceptor() {
4591 return ((1 << kHasIndexedInterceptor) & bit_field()) != 0;
4594 // Tells whether the instance is undetectable.
4595 // An undetectable object is a special class of JSObject: 'typeof' operator
4596 // returns undefined, ToBoolean returns false. Otherwise it behaves like
4597 // a normal JS object. It is useful for implementing undetectable
4598 // document.all in Firefox & Safari.
4599 // See https://bugzilla.mozilla.org/show_bug.cgi?id=248549.
4600 inline void set_is_undetectable() {
4601 set_bit_field(bit_field() | (1 << kIsUndetectable));
4604 inline bool is_undetectable() {
4605 return ((1 << kIsUndetectable) & bit_field()) != 0;
4608 // Tells whether the instance has a call-as-function handler.
4609 inline void set_has_instance_call_handler() {
4610 set_bit_field(bit_field() | (1 << kHasInstanceCallHandler));
4613 inline bool has_instance_call_handler() {
4614 return ((1 << kHasInstanceCallHandler) & bit_field()) != 0;
4617 inline void set_is_extensible(bool value);
4618 inline bool is_extensible();
4620 inline void set_elements_kind(ElementsKind elements_kind) {
4621 ASSERT(elements_kind < kElementsKindCount);
4622 ASSERT(kElementsKindCount <= (1 << kElementsKindBitCount));
4623 set_bit_field2((bit_field2() & ~kElementsKindMask) |
4624 (elements_kind << kElementsKindShift));
4625 ASSERT(this->elements_kind() == elements_kind);
4628 inline ElementsKind elements_kind() {
4629 return static_cast<ElementsKind>(
4630 (bit_field2() & kElementsKindMask) >> kElementsKindShift);
4633 // Tells whether the instance has fast elements that are only Smis.
4634 inline bool has_fast_smi_only_elements() {
4635 return elements_kind() == FAST_SMI_ONLY_ELEMENTS;
4638 // Tells whether the instance has fast elements.
4639 inline bool has_fast_elements() {
4640 return elements_kind() == FAST_ELEMENTS;
4643 inline bool has_fast_double_elements() {
4644 return elements_kind() == FAST_DOUBLE_ELEMENTS;
4647 inline bool has_non_strict_arguments_elements() {
4648 return elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
4651 inline bool has_external_array_elements() {
4652 ElementsKind kind(elements_kind());
4653 return kind >= FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND &&
4654 kind <= LAST_EXTERNAL_ARRAY_ELEMENTS_KIND;
4657 inline bool has_dictionary_elements() {
4658 return elements_kind() == DICTIONARY_ELEMENTS;
4661 inline bool has_slow_elements_kind() {
4662 return elements_kind() == DICTIONARY_ELEMENTS
4663 || elements_kind() == NON_STRICT_ARGUMENTS_ELEMENTS;
4666 static bool IsValidElementsTransition(ElementsKind from_kind,
4667 ElementsKind to_kind);
4669 // Tells whether the map is attached to SharedFunctionInfo
4670 // (for inobject slack tracking).
4671 inline void set_attached_to_shared_function_info(bool value);
4673 inline bool attached_to_shared_function_info();
4675 // Tells whether the map is shared between objects that may have different
4676 // behavior. If true, the map should never be modified, instead a clone
4677 // should be created and modified.
4678 inline void set_is_shared(bool value);
4680 inline bool is_shared();
4682 // Tells whether the instance needs security checks when accessing its
4684 inline void set_is_access_check_needed(bool access_check_needed);
4685 inline bool is_access_check_needed();
4687 // Whether the named interceptor is a fallback interceptor or not
4688 inline void set_named_interceptor_is_fallback(bool value);
4689 inline bool named_interceptor_is_fallback();
4691 // [prototype]: implicit prototype object.
4692 DECL_ACCESSORS(prototype, Object)
4694 // [constructor]: points back to the function responsible for this map.
4695 DECL_ACCESSORS(constructor, Object)
4697 inline JSFunction* unchecked_constructor();
4699 // Should only be called by the code that initializes map to set initial valid
4700 // value of the instance descriptor member.
4701 inline void init_instance_descriptors();
4703 // [instance descriptors]: describes the object.
4704 DECL_ACCESSORS(instance_descriptors, DescriptorArray)
4706 // Sets the instance descriptor array for the map to be an empty descriptor
4708 inline void clear_instance_descriptors();
4710 // [stub cache]: contains stubs compiled for this map.
4711 DECL_ACCESSORS(code_cache, Object)
4713 // [prototype transitions]: cache of prototype transitions.
4714 // Prototype transition is a transition that happens
4715 // when we change object's prototype to a new one.
4717 // 0: finger - index of the first free cell in the cache
4718 // 1 + 2 * i: prototype
4719 // 2 + 2 * i: target map
4720 DECL_ACCESSORS(prototype_transitions, FixedArray)
4722 inline FixedArray* unchecked_prototype_transitions();
4724 static const int kProtoTransitionHeaderSize = 1;
4725 static const int kProtoTransitionNumberOfEntriesOffset = 0;
4726 static const int kProtoTransitionElementsPerEntry = 2;
4727 static const int kProtoTransitionPrototypeOffset = 0;
4728 static const int kProtoTransitionMapOffset = 1;
4730 inline int NumberOfProtoTransitions() {
4731 FixedArray* cache = prototype_transitions();
4732 if (cache->length() == 0) return 0;
4734 Smi::cast(cache->get(kProtoTransitionNumberOfEntriesOffset))->value();
4737 inline void SetNumberOfProtoTransitions(int value) {
4738 FixedArray* cache = prototype_transitions();
4739 ASSERT(cache->length() != 0);
4740 cache->set_unchecked(kProtoTransitionNumberOfEntriesOffset,
4741 Smi::FromInt(value));
4744 // Lookup in the map's instance descriptors and fill out the result
4745 // with the given holder if the name is found. The holder may be
4746 // NULL when this function is used from the compiler.
4747 void LookupInDescriptors(JSObject* holder,
4749 LookupResult* result);
4751 MUST_USE_RESULT MaybeObject* CopyDropDescriptors();
4753 MUST_USE_RESULT MaybeObject* CopyNormalized(PropertyNormalizationMode mode,
4754 NormalizedMapSharingMode sharing);
4756 // Returns a copy of the map, with all transitions dropped from the
4757 // instance descriptors.
4758 MUST_USE_RESULT MaybeObject* CopyDropTransitions();
4760 // Returns the property index for name (only valid for FAST MODE).
4761 int PropertyIndexFor(String* name);
4763 // Returns the next free property index (only valid for FAST MODE).
4764 int NextFreePropertyIndex();
4766 // Returns the number of properties described in instance_descriptors
4767 // filtering out properties with the specified attributes.
4768 int NumberOfDescribedProperties(PropertyAttributes filter = NONE);
4771 static inline Map* cast(Object* obj);
4773 // Locate an accessor in the instance descriptor.
4774 AccessorDescriptor* FindAccessor(String* name);
4776 // Code cache operations.
4778 // Clears the code cache.
4779 inline void ClearCodeCache(Heap* heap);
4781 // Update code cache.
4782 static void UpdateCodeCache(Handle<Map> map,
4783 Handle<String> name,
4785 MUST_USE_RESULT MaybeObject* UpdateCodeCache(String* name, Code* code);
4787 // Returns the found code or undefined if absent.
4788 Object* FindInCodeCache(String* name, Code::Flags flags);
4790 // Returns the non-negative index of the code object if it is in the
4791 // cache and -1 otherwise.
4792 int IndexInCodeCache(Object* name, Code* code);
4794 // Removes a code object from the code cache at the given index.
4795 void RemoveFromCodeCache(String* name, Code* code, int index);
4797 // For every transition in this map, makes the transition's
4798 // target's prototype pointer point back to this map.
4799 // This is undone in MarkCompactCollector::ClearNonLiveTransitions().
4800 void CreateBackPointers();
4802 void CreateOneBackPointer(Object* transition_target);
4804 // Set all map transitions from this map to dead maps to null.
4805 // Also, restore the original prototype on the targets of these
4806 // transitions, so that we do not process this map again while
4807 // following back pointers.
4808 void ClearNonLiveTransitions(Heap* heap, Object* real_prototype);
4810 // Restore a possible back pointer in the prototype field of object.
4811 // Return true in that case and false otherwise. Set *keep_entry to
4812 // true when a live map transition has been found.
4813 bool RestoreOneBackPointer(Object* object,
4814 Object* real_prototype,
4817 // Computes a hash value for this map, to be used in HashTables and such.
4820 // Compares this map to another to see if they describe equivalent objects.
4821 // If |mode| is set to CLEAR_INOBJECT_PROPERTIES, |other| is treated as if
4822 // it had exactly zero inobject properties.
4823 // The "shared" flags of both this map and |other| are ignored.
4824 bool EquivalentToForNormalization(Map* other, PropertyNormalizationMode mode);
4826 // Returns the contents of this map's descriptor array for the given string.
4827 // May return NULL. |safe_to_add_transition| is set to false and NULL
4828 // is returned if adding transitions is not allowed.
4829 Object* GetDescriptorContents(String* sentinel_name,
4830 bool* safe_to_add_transitions);
4832 // Returns the map that this map transitions to if its elements_kind
4833 // is changed to |elements_kind|, or NULL if no such map is cached yet.
4834 // |safe_to_add_transitions| is set to false if adding transitions is not
4836 Map* LookupElementsTransitionMap(ElementsKind elements_kind,
4837 bool* safe_to_add_transition);
4839 // Adds an entry to this map's descriptor array for a transition to
4840 // |transitioned_map| when its elements_kind is changed to |elements_kind|.
4841 MUST_USE_RESULT MaybeObject* AddElementsTransition(
4842 ElementsKind elements_kind, Map* transitioned_map);
4844 // Returns the transitioned map for this map with the most generic
4845 // elements_kind that's found in |candidates|, or null handle if no match is
4847 Handle<Map> FindTransitionedMap(MapHandleList* candidates);
4848 Map* FindTransitionedMap(MapList* candidates);
4851 // Dispatched behavior.
4853 inline void MapPrint() {
4856 void MapPrint(FILE* out);
4860 void SharedMapVerify();
4863 inline int visitor_id();
4864 inline void set_visitor_id(int visitor_id);
4866 typedef void (*TraverseCallback)(Map* map, void* data);
4868 void TraverseTransitionTree(TraverseCallback callback, void* data);
4870 static const int kMaxCachedPrototypeTransitions = 256;
4872 Object* GetPrototypeTransition(Object* prototype);
4874 MUST_USE_RESULT MaybeObject* PutPrototypeTransition(Object* prototype,
4877 static const int kMaxPreAllocatedPropertyFields = 255;
4879 // Layout description.
4880 static const int kInstanceSizesOffset = HeapObject::kHeaderSize;
4881 static const int kInstanceAttributesOffset = kInstanceSizesOffset + kIntSize;
4882 static const int kPrototypeOffset = kInstanceAttributesOffset + kIntSize;
4883 static const int kConstructorOffset = kPrototypeOffset + kPointerSize;
4884 // Storage for instance descriptors is overloaded to also contain additional
4885 // map flags when unused (bit_field3). When the map has instance descriptors,
4886 // the flags are transferred to the instance descriptor array and accessed
4887 // through an extra indirection.
4888 // TODO(1399): It should be possible to make room for bit_field3 in the map
4889 // without overloading the instance descriptors field, but the map is
4890 // currently perfectly aligned to 32 bytes and extending it at all would
4891 // double its size. After the increment GC work lands, this size restriction
4892 // could be loosened and bit_field3 moved directly back in the map.
4893 static const int kInstanceDescriptorsOrBitField3Offset =
4894 kConstructorOffset + kPointerSize;
4895 static const int kCodeCacheOffset =
4896 kInstanceDescriptorsOrBitField3Offset + kPointerSize;
4897 static const int kPrototypeTransitionsOffset =
4898 kCodeCacheOffset + kPointerSize;
4899 static const int kPadStart = kPrototypeTransitionsOffset + kPointerSize;
4900 static const int kSize = MAP_POINTER_ALIGN(kPadStart);
4902 // Layout of pointer fields. Heap iteration code relies on them
4903 // being continuously allocated.
4904 static const int kPointerFieldsBeginOffset = Map::kPrototypeOffset;
4905 static const int kPointerFieldsEndOffset =
4906 Map::kPrototypeTransitionsOffset + kPointerSize;
4908 // Byte offsets within kInstanceSizesOffset.
4909 static const int kInstanceSizeOffset = kInstanceSizesOffset + 0;
4910 static const int kInObjectPropertiesByte = 1;
4911 static const int kInObjectPropertiesOffset =
4912 kInstanceSizesOffset + kInObjectPropertiesByte;
4913 static const int kPreAllocatedPropertyFieldsByte = 2;
4914 static const int kPreAllocatedPropertyFieldsOffset =
4915 kInstanceSizesOffset + kPreAllocatedPropertyFieldsByte;
4916 static const int kVisitorIdByte = 3;
4917 static const int kVisitorIdOffset = kInstanceSizesOffset + kVisitorIdByte;
4919 // Byte offsets within kInstanceAttributesOffset attributes.
4920 static const int kInstanceTypeOffset = kInstanceAttributesOffset + 0;
4921 static const int kUnusedPropertyFieldsOffset = kInstanceAttributesOffset + 1;
4922 static const int kBitFieldOffset = kInstanceAttributesOffset + 2;
4923 static const int kBitField2Offset = kInstanceAttributesOffset + 3;
4925 STATIC_CHECK(kInstanceTypeOffset == Internals::kMapInstanceTypeOffset);
4927 // Bit positions for bit field.
4928 static const int kUnused = 0; // To be used for marking recently used maps.
4929 static const int kHasNonInstancePrototype = 1;
4930 static const int kIsHiddenPrototype = 2;
4931 static const int kHasNamedInterceptor = 3;
4932 static const int kHasIndexedInterceptor = 4;
4933 static const int kIsUndetectable = 5;
4934 static const int kHasInstanceCallHandler = 6;
4935 static const int kIsAccessCheckNeeded = 7;
4937 // Bit positions for bit field 2
4938 static const int kIsExtensible = 0;
4939 static const int kFunctionWithPrototype = 1;
4940 static const int kStringWrapperSafeForDefaultValueOf = 2;
4941 static const int kAttachedToSharedFunctionInfo = 3;
4942 // No bits can be used after kElementsKindFirstBit, they are all reserved for
4943 // storing ElementKind.
4944 static const int kElementsKindShift = 4;
4945 static const int kElementsKindBitCount = 4;
4947 // Derived values from bit field 2
4948 static const int kElementsKindMask = (-1 << kElementsKindShift) &
4949 ((1 << (kElementsKindShift + kElementsKindBitCount)) - 1);
4950 static const int8_t kMaximumBitField2FastElementValue = static_cast<int8_t>(
4951 (FAST_ELEMENTS + 1) << Map::kElementsKindShift) - 1;
4952 static const int8_t kMaximumBitField2FastSmiOnlyElementValue =
4953 static_cast<int8_t>((FAST_SMI_ONLY_ELEMENTS + 1) <<
4954 Map::kElementsKindShift) - 1;
4956 // Bit positions for bit field 3
4957 static const int kIsShared = 0;
4958 static const int kNamedInterceptorIsFallback = 1;
4960 // Layout of the default cache. It holds alternating name and code objects.
4961 static const int kCodeCacheEntrySize = 2;
4962 static const int kCodeCacheEntryNameOffset = 0;
4963 static const int kCodeCacheEntryCodeOffset = 1;
4965 typedef FixedBodyDescriptor<kPointerFieldsBeginOffset,
4966 kPointerFieldsEndOffset,
4967 kSize> BodyDescriptor;
4970 String* elements_transition_sentinel_name();
4971 DISALLOW_IMPLICIT_CONSTRUCTORS(Map);
4975 // An abstract superclass, a marker class really, for simple structure classes.
4976 // It doesn't carry much functionality but allows struct classes to be
4977 // identified in the type system.
4978 class Struct: public HeapObject {
4980 inline void InitializeBody(int object_size);
4981 static inline Struct* cast(Object* that);
4985 // Script describes a script which has been added to the VM.
4986 class Script: public Struct {
4995 // Script compilation types.
4996 enum CompilationType {
4997 COMPILATION_TYPE_HOST = 0,
4998 COMPILATION_TYPE_EVAL = 1
5001 // Script compilation state.
5002 enum CompilationState {
5003 COMPILATION_STATE_INITIAL = 0,
5004 COMPILATION_STATE_COMPILED = 1
5007 // [source]: the script source.
5008 DECL_ACCESSORS(source, Object)
5010 // [name]: the script name.
5011 DECL_ACCESSORS(name, Object)
5013 // [id]: the script id.
5014 DECL_ACCESSORS(id, Object)
5016 // [line_offset]: script line offset in resource from where it was extracted.
5017 DECL_ACCESSORS(line_offset, Smi)
5019 // [column_offset]: script column offset in resource from where it was
5021 DECL_ACCESSORS(column_offset, Smi)
5023 // [data]: additional data associated with this script.
5024 DECL_ACCESSORS(data, Object)
5026 // [context_data]: context data for the context this script was compiled in.
5027 DECL_ACCESSORS(context_data, Object)
5029 // [wrapper]: the wrapper cache.
5030 DECL_ACCESSORS(wrapper, Foreign)
5032 // [type]: the script type.
5033 DECL_ACCESSORS(type, Smi)
5035 // [compilation]: how the the script was compiled.
5036 DECL_ACCESSORS(compilation_type, Smi)
5038 // [is_compiled]: determines whether the script has already been compiled.
5039 DECL_ACCESSORS(compilation_state, Smi)
5041 // [line_ends]: FixedArray of line ends positions.
5042 DECL_ACCESSORS(line_ends, Object)
5044 // [eval_from_shared]: for eval scripts the shared funcion info for the
5045 // function from which eval was called.
5046 DECL_ACCESSORS(eval_from_shared, Object)
5048 // [eval_from_instructions_offset]: the instruction offset in the code for the
5049 // function from which eval was called where eval was called.
5050 DECL_ACCESSORS(eval_from_instructions_offset, Smi)
5052 static inline Script* cast(Object* obj);
5054 // If script source is an external string, check that the underlying
5055 // resource is accessible. Otherwise, always return true.
5056 inline bool HasValidSource();
5059 inline void ScriptPrint() {
5060 ScriptPrint(stdout);
5062 void ScriptPrint(FILE* out);
5065 void ScriptVerify();
5068 static const int kSourceOffset = HeapObject::kHeaderSize;
5069 static const int kNameOffset = kSourceOffset + kPointerSize;
5070 static const int kLineOffsetOffset = kNameOffset + kPointerSize;
5071 static const int kColumnOffsetOffset = kLineOffsetOffset + kPointerSize;
5072 static const int kDataOffset = kColumnOffsetOffset + kPointerSize;
5073 static const int kContextOffset = kDataOffset + kPointerSize;
5074 static const int kWrapperOffset = kContextOffset + kPointerSize;
5075 static const int kTypeOffset = kWrapperOffset + kPointerSize;
5076 static const int kCompilationTypeOffset = kTypeOffset + kPointerSize;
5077 static const int kCompilationStateOffset =
5078 kCompilationTypeOffset + kPointerSize;
5079 static const int kLineEndsOffset = kCompilationStateOffset + kPointerSize;
5080 static const int kIdOffset = kLineEndsOffset + kPointerSize;
5081 static const int kEvalFromSharedOffset = kIdOffset + kPointerSize;
5082 static const int kEvalFrominstructionsOffsetOffset =
5083 kEvalFromSharedOffset + kPointerSize;
5084 static const int kSize = kEvalFrominstructionsOffsetOffset + kPointerSize;
5087 DISALLOW_IMPLICIT_CONSTRUCTORS(Script);
5091 // List of builtin functions we want to identify to improve code
5094 // Each entry has a name of a global object property holding an object
5095 // optionally followed by ".prototype", a name of a builtin function
5096 // on the object (the one the id is set for), and a label.
5098 // Installation of ids for the selected builtin functions is handled
5099 // by the bootstrapper.
5101 // NOTE: Order is important: math functions should be at the end of
5102 // the list and MathFloor should be the first math function.
5103 #define FUNCTIONS_WITH_ID_LIST(V) \
5104 V(Array.prototype, push, ArrayPush) \
5105 V(Array.prototype, pop, ArrayPop) \
5106 V(Function.prototype, apply, FunctionApply) \
5107 V(String.prototype, charCodeAt, StringCharCodeAt) \
5108 V(String.prototype, charAt, StringCharAt) \
5109 V(String, fromCharCode, StringFromCharCode) \
5110 V(Math, floor, MathFloor) \
5111 V(Math, round, MathRound) \
5112 V(Math, ceil, MathCeil) \
5113 V(Math, abs, MathAbs) \
5114 V(Math, log, MathLog) \
5115 V(Math, sin, MathSin) \
5116 V(Math, cos, MathCos) \
5117 V(Math, tan, MathTan) \
5118 V(Math, asin, MathASin) \
5119 V(Math, acos, MathACos) \
5120 V(Math, atan, MathATan) \
5121 V(Math, exp, MathExp) \
5122 V(Math, sqrt, MathSqrt) \
5123 V(Math, pow, MathPow) \
5124 V(Math, random, MathRandom) \
5125 V(Math, max, MathMax) \
5126 V(Math, min, MathMin)
5129 enum BuiltinFunctionId {
5130 #define DECLARE_FUNCTION_ID(ignored1, ignore2, name) \
5132 FUNCTIONS_WITH_ID_LIST(DECLARE_FUNCTION_ID)
5133 #undef DECLARE_FUNCTION_ID
5134 // Fake id for a special case of Math.pow. Note, it continues the
5135 // list of math functions.
5137 kFirstMathFunctionId = kMathFloor
5141 // SharedFunctionInfo describes the JSFunction information that can be
5142 // shared by multiple instances of the function.
5143 class SharedFunctionInfo: public HeapObject {
5145 // [name]: Function name.
5146 DECL_ACCESSORS(name, Object)
5148 // [code]: Function code.
5149 DECL_ACCESSORS(code, Code)
5151 // [scope_info]: Scope info.
5152 DECL_ACCESSORS(scope_info, ScopeInfo)
5154 // [construct stub]: Code stub for constructing instances of this function.
5155 DECL_ACCESSORS(construct_stub, Code)
5157 inline Code* unchecked_code();
5159 // Returns if this function has been compiled to native code yet.
5160 inline bool is_compiled();
5162 // [length]: The function length - usually the number of declared parameters.
5163 // Use up to 2^30 parameters.
5164 inline int length();
5165 inline void set_length(int value);
5167 // [formal parameter count]: The declared number of parameters.
5168 inline int formal_parameter_count();
5169 inline void set_formal_parameter_count(int value);
5171 // Set the formal parameter count so the function code will be
5172 // called without using argument adaptor frames.
5173 inline void DontAdaptArguments();
5175 // [expected_nof_properties]: Expected number of properties for the function.
5176 inline int expected_nof_properties();
5177 inline void set_expected_nof_properties(int value);
5179 // Inobject slack tracking is the way to reclaim unused inobject space.
5181 // The instance size is initially determined by adding some slack to
5182 // expected_nof_properties (to allow for a few extra properties added
5183 // after the constructor). There is no guarantee that the extra space
5184 // will not be wasted.
5186 // Here is the algorithm to reclaim the unused inobject space:
5187 // - Detect the first constructor call for this SharedFunctionInfo.
5188 // When it happens enter the "in progress" state: remember the
5189 // constructor's initial_map and install a special construct stub that
5190 // counts constructor calls.
5191 // - While the tracking is in progress create objects filled with
5192 // one_pointer_filler_map instead of undefined_value. This way they can be
5193 // resized quickly and safely.
5194 // - Once enough (kGenerousAllocationCount) objects have been created
5195 // compute the 'slack' (traverse the map transition tree starting from the
5196 // initial_map and find the lowest value of unused_property_fields).
5197 // - Traverse the transition tree again and decrease the instance size
5198 // of every map. Existing objects will resize automatically (they are
5199 // filled with one_pointer_filler_map). All further allocations will
5200 // use the adjusted instance size.
5201 // - Decrease expected_nof_properties so that an allocations made from
5202 // another context will use the adjusted instance size too.
5203 // - Exit "in progress" state by clearing the reference to the initial_map
5204 // and setting the regular construct stub (generic or inline).
5206 // The above is the main event sequence. Some special cases are possible
5207 // while the tracking is in progress:
5210 // Check if the initial_map is referenced by any live objects (except this
5211 // SharedFunctionInfo). If it is, continue tracking as usual.
5212 // If it is not, clear the reference and reset the tracking state. The
5213 // tracking will be initiated again on the next constructor call.
5215 // - The constructor is called from another context.
5216 // Immediately complete the tracking, perform all the necessary changes
5217 // to maps. This is necessary because there is no efficient way to track
5218 // multiple initial_maps.
5219 // Proceed to create an object in the current context (with the adjusted
5222 // - A different constructor function sharing the same SharedFunctionInfo is
5223 // called in the same context. This could be another closure in the same
5224 // context, or the first function could have been disposed.
5225 // This is handled the same way as the previous case.
5227 // Important: inobject slack tracking is not attempted during the snapshot
5230 static const int kGenerousAllocationCount = 8;
5232 // [construction_count]: Counter for constructor calls made during
5233 // the tracking phase.
5234 inline int construction_count();
5235 inline void set_construction_count(int value);
5237 // [initial_map]: initial map of the first function called as a constructor.
5238 // Saved for the duration of the tracking phase.
5239 // This is a weak link (GC resets it to undefined_value if no other live
5240 // object reference this map).
5241 DECL_ACCESSORS(initial_map, Object)
5243 // True if the initial_map is not undefined and the countdown stub is
5245 inline bool IsInobjectSlackTrackingInProgress();
5247 // Starts the tracking.
5248 // Stores the initial map and installs the countdown stub.
5249 // IsInobjectSlackTrackingInProgress is normally true after this call,
5250 // except when tracking have not been started (e.g. the map has no unused
5251 // properties or the snapshot is being built).
5252 void StartInobjectSlackTracking(Map* map);
5254 // Completes the tracking.
5255 // IsInobjectSlackTrackingInProgress is false after this call.
5256 void CompleteInobjectSlackTracking();
5258 // Clears the initial_map before the GC marking phase to ensure the reference
5259 // is weak. IsInobjectSlackTrackingInProgress is false after this call.
5260 void DetachInitialMap();
5262 // Restores the link to the initial map after the GC marking phase.
5263 // IsInobjectSlackTrackingInProgress is true after this call.
5264 void AttachInitialMap(Map* map);
5266 // False if there are definitely no live objects created from this function.
5267 // True if live objects _may_ exist (existence not guaranteed).
5268 // May go back from true to false after GC.
5269 DECL_BOOLEAN_ACCESSORS(live_objects_may_exist)
5271 // [instance class name]: class name for instances.
5272 DECL_ACCESSORS(instance_class_name, Object)
5274 // [function data]: This field holds some additional data for function.
5275 // Currently it either has FunctionTemplateInfo to make benefit the API
5276 // or Smi identifying a builtin function.
5277 // In the long run we don't want all functions to have this field but
5278 // we can fix that when we have a better model for storing hidden data
5280 DECL_ACCESSORS(function_data, Object)
5282 inline bool IsApiFunction();
5283 inline FunctionTemplateInfo* get_api_func_data();
5284 inline bool HasBuiltinFunctionId();
5285 inline BuiltinFunctionId builtin_function_id();
5287 // [script info]: Script from which the function originates.
5288 DECL_ACCESSORS(script, Object)
5290 // [num_literals]: Number of literals used by this function.
5291 inline int num_literals();
5292 inline void set_num_literals(int value);
5294 // [start_position_and_type]: Field used to store both the source code
5295 // position, whether or not the function is a function expression,
5296 // and whether or not the function is a toplevel function. The two
5297 // least significants bit indicates whether the function is an
5298 // expression and the rest contains the source code position.
5299 inline int start_position_and_type();
5300 inline void set_start_position_and_type(int value);
5302 // [debug info]: Debug information.
5303 DECL_ACCESSORS(debug_info, Object)
5305 // [inferred name]: Name inferred from variable or property
5306 // assignment of this function. Used to facilitate debugging and
5307 // profiling of JavaScript code written in OO style, where almost
5308 // all functions are anonymous but are assigned to object
5310 DECL_ACCESSORS(inferred_name, String)
5312 // The function's name if it is non-empty, otherwise the inferred name.
5313 String* DebugName();
5315 // Position of the 'function' token in the script source.
5316 inline int function_token_position();
5317 inline void set_function_token_position(int function_token_position);
5319 // Position of this function in the script source.
5320 inline int start_position();
5321 inline void set_start_position(int start_position);
5323 // End position of this function in the script source.
5324 inline int end_position();
5325 inline void set_end_position(int end_position);
5327 // Is this function a function expression in the source code.
5328 DECL_BOOLEAN_ACCESSORS(is_expression)
5330 // Is this function a top-level function (scripts, evals).
5331 DECL_BOOLEAN_ACCESSORS(is_toplevel)
5333 // Bit field containing various information collected by the compiler to
5334 // drive optimization.
5335 inline int compiler_hints();
5336 inline void set_compiler_hints(int value);
5338 inline int ast_node_count();
5339 inline void set_ast_node_count(int count);
5341 // A counter used to determine when to stress the deoptimizer with a
5343 inline int deopt_counter();
5344 inline void set_deopt_counter(int counter);
5346 // Inline cache age is used to infer whether the function survived a context
5347 // disposal or not. In the former case we reset the opt_count.
5348 inline int ic_age();
5349 inline void set_ic_age(int age);
5351 // Add information on assignments of the form this.x = ...;
5352 void SetThisPropertyAssignmentsInfo(
5353 bool has_only_simple_this_property_assignments,
5354 FixedArray* this_property_assignments);
5356 // Clear information on assignments of the form this.x = ...;
5357 void ClearThisPropertyAssignmentsInfo();
5359 // Indicate that this function only consists of assignments of the form
5360 // this.x = y; where y is either a constant or refers to an argument.
5361 inline bool has_only_simple_this_property_assignments();
5363 // Indicates if this function can be lazy compiled.
5364 // This is used to determine if we can safely flush code from a function
5365 // when doing GC if we expect that the function will no longer be used.
5366 DECL_BOOLEAN_ACCESSORS(allows_lazy_compilation)
5368 // Indicates how many full GCs this function has survived with assigned
5369 // code object. Used to determine when it is relatively safe to flush
5370 // this code object and replace it with lazy compilation stub.
5371 // Age is reset when GC notices that the code object is referenced
5372 // from the stack or compilation cache.
5373 inline int code_age();
5374 inline void set_code_age(int age);
5376 // Indicates whether optimizations have been disabled for this
5377 // shared function info. If a function is repeatedly optimized or if
5378 // we cannot optimize the function we disable optimization to avoid
5379 // spending time attempting to optimize it again.
5380 DECL_BOOLEAN_ACCESSORS(optimization_disabled)
5382 // Indicates the language mode of the function's code as defined by the
5383 // current harmony drafts for the next ES language standard. Possible
5385 // 1. CLASSIC_MODE - Unrestricted syntax and semantics, same as in ES5.
5386 // 2. STRICT_MODE - Restricted syntax and semantics, same as in ES5.
5387 // 3. EXTENDED_MODE - Only available under the harmony flag, not part of ES5.
5388 inline LanguageMode language_mode();
5389 inline void set_language_mode(LanguageMode language_mode);
5391 // Indicates whether the language mode of this function is CLASSIC_MODE.
5392 inline bool is_classic_mode();
5394 // Indicates whether the language mode of this function is EXTENDED_MODE.
5395 inline bool is_extended_mode();
5397 // False if the function definitely does not allocate an arguments object.
5398 DECL_BOOLEAN_ACCESSORS(uses_arguments)
5400 // True if the function has any duplicated parameter names.
5401 DECL_BOOLEAN_ACCESSORS(has_duplicate_parameters)
5403 // Indicates whether the function is a native function.
5404 // These needs special treatment in .call and .apply since
5405 // null passed as the receiver should not be translated to the
5407 DECL_BOOLEAN_ACCESSORS(native)
5409 // Indicates that the function was created by the Function function.
5410 // Though it's anonymous, toString should treat it as if it had the name
5411 // "anonymous". We don't set the name itself so that the system does not
5412 // see a binding for it.
5413 DECL_BOOLEAN_ACCESSORS(name_should_print_as_anonymous)
5415 // Indicates whether the function is a bound function created using
5416 // the bind function.
5417 DECL_BOOLEAN_ACCESSORS(bound)
5419 // Indicates that the function is anonymous (the name field can be set
5420 // through the API, which does not change this flag).
5421 DECL_BOOLEAN_ACCESSORS(is_anonymous)
5423 // Is this a function or top-level/eval code.
5424 DECL_BOOLEAN_ACCESSORS(is_function)
5426 // Indicates that the function cannot be optimized.
5427 DECL_BOOLEAN_ACCESSORS(dont_optimize)
5429 // Indicates that the function cannot be inlined.
5430 DECL_BOOLEAN_ACCESSORS(dont_inline)
5432 // Indicates whether or not the code in the shared function support
5434 inline bool has_deoptimization_support();
5436 // Enable deoptimization support through recompiled code.
5437 void EnableDeoptimizationSupport(Code* recompiled);
5439 // Disable (further) attempted optimization of all functions sharing this
5440 // shared function info.
5441 void DisableOptimization();
5443 // Lookup the bailout ID and ASSERT that it exists in the non-optimized
5444 // code, returns whether it asserted (i.e., always true if assertions are
5446 bool VerifyBailoutId(int id);
5448 // Check whether a inlined constructor can be generated with the given
5450 bool CanGenerateInlineConstructor(Object* prototype);
5452 // Prevents further attempts to generate inline constructors.
5453 // To be called if generation failed for any reason.
5454 void ForbidInlineConstructor();
5456 // For functions which only contains this property assignments this provides
5457 // access to the names for the properties assigned.
5458 DECL_ACCESSORS(this_property_assignments, Object)
5459 inline int this_property_assignments_count();
5460 inline void set_this_property_assignments_count(int value);
5461 String* GetThisPropertyAssignmentName(int index);
5462 bool IsThisPropertyAssignmentArgument(int index);
5463 int GetThisPropertyAssignmentArgument(int index);
5464 Object* GetThisPropertyAssignmentConstant(int index);
5466 // [source code]: Source code for the function.
5467 bool HasSourceCode();
5468 Handle<Object> GetSourceCode();
5470 inline int opt_count();
5471 inline void set_opt_count(int opt_count);
5473 // Source size of this function.
5476 // Calculate the instance size.
5477 int CalculateInstanceSize();
5479 // Calculate the number of in-object properties.
5480 int CalculateInObjectProperties();
5482 // Dispatched behavior.
5483 // Set max_length to -1 for unlimited length.
5484 void SourceCodePrint(StringStream* accumulator, int max_length);
5486 inline void SharedFunctionInfoPrint() {
5487 SharedFunctionInfoPrint(stdout);
5489 void SharedFunctionInfoPrint(FILE* out);
5492 void SharedFunctionInfoVerify();
5495 void ResetForNewContext(int new_ic_age);
5497 // Helpers to compile the shared code. Returns true on success, false on
5498 // failure (e.g., stack overflow during compilation).
5499 static bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
5500 ClearExceptionFlag flag);
5501 static bool CompileLazy(Handle<SharedFunctionInfo> shared,
5502 ClearExceptionFlag flag);
5504 void SharedFunctionInfoIterateBody(ObjectVisitor* v);
5507 static inline SharedFunctionInfo* cast(Object* obj);
5510 static const int kDontAdaptArgumentsSentinel = -1;
5512 // Layout description.
5514 static const int kNameOffset = HeapObject::kHeaderSize;
5515 static const int kCodeOffset = kNameOffset + kPointerSize;
5516 static const int kScopeInfoOffset = kCodeOffset + kPointerSize;
5517 static const int kConstructStubOffset = kScopeInfoOffset + kPointerSize;
5518 static const int kInstanceClassNameOffset =
5519 kConstructStubOffset + kPointerSize;
5520 static const int kFunctionDataOffset =
5521 kInstanceClassNameOffset + kPointerSize;
5522 static const int kScriptOffset = kFunctionDataOffset + kPointerSize;
5523 static const int kDebugInfoOffset = kScriptOffset + kPointerSize;
5524 static const int kInferredNameOffset = kDebugInfoOffset + kPointerSize;
5525 static const int kInitialMapOffset =
5526 kInferredNameOffset + kPointerSize;
5527 static const int kThisPropertyAssignmentsOffset =
5528 kInitialMapOffset + kPointerSize;
5529 // ic_age is a Smi field. It could be grouped with another Smi field into a
5530 // PSEUDO_SMI_ACCESSORS pair (on x64), if one becomes available.
5531 static const int kICAgeOffset = kThisPropertyAssignmentsOffset + kPointerSize;
5532 #if V8_HOST_ARCH_32_BIT
5534 static const int kLengthOffset =
5535 kICAgeOffset + kPointerSize;
5536 static const int kFormalParameterCountOffset = kLengthOffset + kPointerSize;
5537 static const int kExpectedNofPropertiesOffset =
5538 kFormalParameterCountOffset + kPointerSize;
5539 static const int kNumLiteralsOffset =
5540 kExpectedNofPropertiesOffset + kPointerSize;
5541 static const int kStartPositionAndTypeOffset =
5542 kNumLiteralsOffset + kPointerSize;
5543 static const int kEndPositionOffset =
5544 kStartPositionAndTypeOffset + kPointerSize;
5545 static const int kFunctionTokenPositionOffset =
5546 kEndPositionOffset + kPointerSize;
5547 static const int kCompilerHintsOffset =
5548 kFunctionTokenPositionOffset + kPointerSize;
5549 static const int kThisPropertyAssignmentsCountOffset =
5550 kCompilerHintsOffset + kPointerSize;
5551 static const int kOptCountOffset =
5552 kThisPropertyAssignmentsCountOffset + kPointerSize;
5553 static const int kAstNodeCountOffset = kOptCountOffset + kPointerSize;
5554 static const int kDeoptCounterOffset = kAstNodeCountOffset + kPointerSize;
5558 static const int kSize = kDeoptCounterOffset + kPointerSize;
5560 // The only reason to use smi fields instead of int fields
5561 // is to allow iteration without maps decoding during
5562 // garbage collections.
5563 // To avoid wasting space on 64-bit architectures we use
5564 // the following trick: we group integer fields into pairs
5565 // First integer in each pair is shifted left by 1.
5566 // By doing this we guarantee that LSB of each kPointerSize aligned
5567 // word is not set and thus this word cannot be treated as pointer
5568 // to HeapObject during old space traversal.
5569 static const int kLengthOffset =
5570 kICAgeOffset + kPointerSize;
5571 static const int kFormalParameterCountOffset =
5572 kLengthOffset + kIntSize;
5574 static const int kExpectedNofPropertiesOffset =
5575 kFormalParameterCountOffset + kIntSize;
5576 static const int kNumLiteralsOffset =
5577 kExpectedNofPropertiesOffset + kIntSize;
5579 static const int kEndPositionOffset =
5580 kNumLiteralsOffset + kIntSize;
5581 static const int kStartPositionAndTypeOffset =
5582 kEndPositionOffset + kIntSize;
5584 static const int kFunctionTokenPositionOffset =
5585 kStartPositionAndTypeOffset + kIntSize;
5586 static const int kCompilerHintsOffset =
5587 kFunctionTokenPositionOffset + kIntSize;
5589 static const int kThisPropertyAssignmentsCountOffset =
5590 kCompilerHintsOffset + kIntSize;
5591 static const int kOptCountOffset =
5592 kThisPropertyAssignmentsCountOffset + kIntSize;
5594 static const int kAstNodeCountOffset = kOptCountOffset + kIntSize;
5595 static const int kDeoptCounterOffset = kAstNodeCountOffset + kIntSize;
5598 static const int kSize = kDeoptCounterOffset + kIntSize;
5602 // The construction counter for inobject slack tracking is stored in the
5603 // most significant byte of compiler_hints which is otherwise unused.
5604 // Its offset depends on the endian-ness of the architecture.
5605 #if __BYTE_ORDER == __LITTLE_ENDIAN
5606 static const int kConstructionCountOffset = kCompilerHintsOffset + 3;
5607 #elif __BYTE_ORDER == __BIG_ENDIAN
5608 static const int kConstructionCountOffset = kCompilerHintsOffset + 0;
5610 #error Unknown byte ordering
5613 static const int kAlignedSize = POINTER_SIZE_ALIGN(kSize);
5615 typedef FixedBodyDescriptor<kNameOffset,
5616 kThisPropertyAssignmentsOffset + kPointerSize,
5617 kSize> BodyDescriptor;
5619 // Bit positions in start_position_and_type.
5620 // The source code start position is in the 30 most significant bits of
5621 // the start_position_and_type field.
5622 static const int kIsExpressionBit = 0;
5623 static const int kIsTopLevelBit = 1;
5624 static const int kStartPositionShift = 2;
5625 static const int kStartPositionMask = ~((1 << kStartPositionShift) - 1);
5627 // Bit positions in compiler_hints.
5628 static const int kCodeAgeSize = 3;
5629 static const int kCodeAgeMask = (1 << kCodeAgeSize) - 1;
5631 enum CompilerHints {
5632 kHasOnlySimpleThisPropertyAssignments,
5633 kAllowLazyCompilation,
5634 kLiveObjectsMayExist,
5636 kOptimizationDisabled = kCodeAgeShift + kCodeAgeSize,
5637 kStrictModeFunction,
5638 kExtendedModeFunction,
5640 kHasDuplicateParameters,
5644 kNameShouldPrintAsAnonymous,
5648 kCompilerHintsCount // Pseudo entry
5652 #if V8_HOST_ARCH_32_BIT
5653 // On 32 bit platforms, compiler hints is a smi.
5654 static const int kCompilerHintsSmiTagSize = kSmiTagSize;
5655 static const int kCompilerHintsSize = kPointerSize;
5657 // On 64 bit platforms, compiler hints is not a smi, see comment above.
5658 static const int kCompilerHintsSmiTagSize = 0;
5659 static const int kCompilerHintsSize = kIntSize;
5662 STATIC_ASSERT(SharedFunctionInfo::kCompilerHintsCount <=
5663 SharedFunctionInfo::kCompilerHintsSize * kBitsPerByte);
5666 // Constants for optimizing codegen for strict mode function and
5668 // Allows to use byte-width instructions.
5669 static const int kStrictModeBitWithinByte =
5670 (kStrictModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
5672 static const int kExtendedModeBitWithinByte =
5673 (kExtendedModeFunction + kCompilerHintsSmiTagSize) % kBitsPerByte;
5675 static const int kNativeBitWithinByte =
5676 (kNative + kCompilerHintsSmiTagSize) % kBitsPerByte;
5678 #if __BYTE_ORDER == __LITTLE_ENDIAN
5679 static const int kStrictModeByteOffset = kCompilerHintsOffset +
5680 (kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
5681 static const int kExtendedModeByteOffset = kCompilerHintsOffset +
5682 (kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte;
5683 static const int kNativeByteOffset = kCompilerHintsOffset +
5684 (kNative + kCompilerHintsSmiTagSize) / kBitsPerByte;
5685 #elif __BYTE_ORDER == __BIG_ENDIAN
5686 static const int kStrictModeByteOffset = kCompilerHintsOffset +
5687 (kCompilerHintsSize - 1) -
5688 ((kStrictModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
5689 static const int kExtendedModeByteOffset = kCompilerHintsOffset +
5690 (kCompilerHintsSize - 1) -
5691 ((kExtendedModeFunction + kCompilerHintsSmiTagSize) / kBitsPerByte);
5692 static const int kNativeByteOffset = kCompilerHintsOffset +
5693 (kCompilerHintsSize - 1) -
5694 ((kNative + kCompilerHintsSmiTagSize) / kBitsPerByte);
5696 #error Unknown byte ordering
5700 DISALLOW_IMPLICIT_CONSTRUCTORS(SharedFunctionInfo);
5704 // JSFunction describes JavaScript functions.
5705 class JSFunction: public JSObject {
5707 // [prototype_or_initial_map]:
5708 DECL_ACCESSORS(prototype_or_initial_map, Object)
5710 // [shared]: The information about the function that
5711 // can be shared by instances.
5712 DECL_ACCESSORS(shared, SharedFunctionInfo)
5714 inline SharedFunctionInfo* unchecked_shared();
5716 // [context]: The context for this function.
5717 inline Context* context();
5718 inline Object* unchecked_context();
5719 inline void set_context(Object* context);
5721 // [code]: The generated code object for this function. Executed
5722 // when the function is invoked, e.g. foo() or new foo(). See
5723 // [[Call]] and [[Construct]] description in ECMA-262, section
5725 inline Code* code();
5726 inline void set_code(Code* code);
5727 inline void ReplaceCode(Code* code);
5729 inline Code* unchecked_code();
5731 // Tells whether this function is builtin.
5732 inline bool IsBuiltin();
5734 // Tells whether or not the function needs arguments adaption.
5735 inline bool NeedsArgumentsAdaption();
5737 // Tells whether or not this function has been optimized.
5738 inline bool IsOptimized();
5740 // Tells whether or not this function can be optimized.
5741 inline bool IsOptimizable();
5743 // Mark this function for lazy recompilation. The function will be
5744 // recompiled the next time it is executed.
5745 void MarkForLazyRecompilation();
5747 // Helpers to compile this function. Returns true on success, false on
5748 // failure (e.g., stack overflow during compilation).
5749 static bool CompileLazy(Handle<JSFunction> function,
5750 ClearExceptionFlag flag);
5751 static bool CompileOptimized(Handle<JSFunction> function,
5753 ClearExceptionFlag flag);
5755 // Tells whether or not the function is already marked for lazy
5757 inline bool IsMarkedForLazyRecompilation();
5759 // Check whether or not this function is inlineable.
5760 bool IsInlineable();
5762 // [literals_or_bindings]: Fixed array holding either
5763 // the materialized literals or the bindings of a bound function.
5765 // If the function contains object, regexp or array literals, the
5766 // literals array prefix contains the object, regexp, and array
5767 // function to be used when creating these literals. This is
5768 // necessary so that we do not dynamically lookup the object, regexp
5769 // or array functions. Performing a dynamic lookup, we might end up
5770 // using the functions from a new context that we should not have
5773 // On bound functions, the array is a (copy-on-write) fixed-array containing
5774 // the function that was bound, bound this-value and any bound
5775 // arguments. Bound functions never contain literals.
5776 DECL_ACCESSORS(literals_or_bindings, FixedArray)
5778 inline FixedArray* literals();
5779 inline void set_literals(FixedArray* literals);
5781 inline FixedArray* function_bindings();
5782 inline void set_function_bindings(FixedArray* bindings);
5784 // The initial map for an object created by this constructor.
5785 inline Map* initial_map();
5786 inline void set_initial_map(Map* value);
5787 MUST_USE_RESULT inline MaybeObject* set_initial_map_and_cache_transitions(
5789 inline bool has_initial_map();
5791 // Get and set the prototype property on a JSFunction. If the
5792 // function has an initial map the prototype is set on the initial
5793 // map. Otherwise, the prototype is put in the initial map field
5794 // until an initial map is needed.
5795 inline bool has_prototype();
5796 inline bool has_instance_prototype();
5797 inline Object* prototype();
5798 inline Object* instance_prototype();
5799 MUST_USE_RESULT MaybeObject* SetInstancePrototype(Object* value);
5800 MUST_USE_RESULT MaybeObject* SetPrototype(Object* value);
5802 // After prototype is removed, it will not be created when accessed, and
5803 // [[Construct]] from this function will not be allowed.
5804 Object* RemovePrototype();
5805 inline bool should_have_prototype();
5807 // Accessor for this function's initial map's [[class]]
5808 // property. This is primarily used by ECMA native functions. This
5809 // method sets the class_name field of this function's initial map
5810 // to a given value. It creates an initial map if this function does
5811 // not have one. Note that this method does not copy the initial map
5812 // if it has one already, but simply replaces it with the new value.
5813 // Instances created afterwards will have a map whose [[class]] is
5814 // set to 'value', but there is no guarantees on instances created
5816 Object* SetInstanceClassName(String* name);
5818 // Returns if this function has been compiled to native code yet.
5819 inline bool is_compiled();
5821 // [next_function_link]: Field for linking functions. This list is treated as
5822 // a weak list by the GC.
5823 DECL_ACCESSORS(next_function_link, Object)
5825 // Prints the name of the function using PrintF.
5826 inline void PrintName() {
5829 void PrintName(FILE* out);
5832 static inline JSFunction* cast(Object* obj);
5834 // Iterates the objects, including code objects indirectly referenced
5835 // through pointers to the first instruction in the code object.
5836 void JSFunctionIterateBody(int object_size, ObjectVisitor* v);
5838 // Dispatched behavior.
5840 inline void JSFunctionPrint() {
5841 JSFunctionPrint(stdout);
5843 void JSFunctionPrint(FILE* out);
5846 void JSFunctionVerify();
5849 // Returns the number of allocated literals.
5850 inline int NumberOfLiterals();
5852 // Retrieve the global context from a function's literal array.
5853 static Context* GlobalContextFromLiterals(FixedArray* literals);
5855 // Layout descriptors. The last property (from kNonWeakFieldsEndOffset to
5856 // kSize) is weak and has special handling during garbage collection.
5857 static const int kCodeEntryOffset = JSObject::kHeaderSize;
5858 static const int kPrototypeOrInitialMapOffset =
5859 kCodeEntryOffset + kPointerSize;
5860 static const int kSharedFunctionInfoOffset =
5861 kPrototypeOrInitialMapOffset + kPointerSize;
5862 static const int kContextOffset = kSharedFunctionInfoOffset + kPointerSize;
5863 static const int kLiteralsOffset = kContextOffset + kPointerSize;
5864 static const int kNonWeakFieldsEndOffset = kLiteralsOffset + kPointerSize;
5865 static const int kNextFunctionLinkOffset = kNonWeakFieldsEndOffset;
5866 static const int kSize = kNextFunctionLinkOffset + kPointerSize;
5868 // Layout of the literals array.
5869 static const int kLiteralsPrefixSize = 1;
5870 static const int kLiteralGlobalContextIndex = 0;
5872 // Layout of the bound-function binding array.
5873 static const int kBoundFunctionIndex = 0;
5874 static const int kBoundThisIndex = 1;
5875 static const int kBoundArgumentsStartIndex = 2;
5878 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunction);
5882 // JSGlobalProxy's prototype must be a JSGlobalObject or null,
5883 // and the prototype is hidden. JSGlobalProxy always delegates
5884 // property accesses to its prototype if the prototype is not null.
5886 // A JSGlobalProxy can be reinitialized which will preserve its identity.
5888 // Accessing a JSGlobalProxy requires security check.
5890 class JSGlobalProxy : public JSObject {
5892 // [context]: the owner global context of this global proxy object.
5893 // It is null value if this object is not used by any context.
5894 DECL_ACCESSORS(context, Object)
5897 static inline JSGlobalProxy* cast(Object* obj);
5899 // Dispatched behavior.
5901 inline void JSGlobalProxyPrint() {
5902 JSGlobalProxyPrint(stdout);
5904 void JSGlobalProxyPrint(FILE* out);
5907 void JSGlobalProxyVerify();
5910 // Layout description.
5911 static const int kContextOffset = JSObject::kHeaderSize;
5912 static const int kSize = kContextOffset + kPointerSize;
5915 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalProxy);
5919 // Forward declaration.
5920 class JSBuiltinsObject;
5922 // Common super class for JavaScript global objects and the special
5923 // builtins global objects.
5924 class GlobalObject: public JSObject {
5926 // [builtins]: the object holding the runtime routines written in JS.
5927 DECL_ACCESSORS(builtins, JSBuiltinsObject)
5929 // [global context]: the global context corresponding to this global object.
5930 DECL_ACCESSORS(global_context, Context)
5932 // [global receiver]: the global receiver object of the context
5933 DECL_ACCESSORS(global_receiver, JSObject)
5935 // Retrieve the property cell used to store a property.
5936 JSGlobalPropertyCell* GetPropertyCell(LookupResult* result);
5938 // This is like GetProperty, but is used when you know the lookup won't fail
5939 // by throwing an exception. This is for the debug and builtins global
5940 // objects, where it is known which properties can be expected to be present
5942 Object* GetPropertyNoExceptionThrown(String* key) {
5943 Object* answer = GetProperty(key)->ToObjectUnchecked();
5947 // Ensure that the global object has a cell for the given property name.
5948 static Handle<JSGlobalPropertyCell> EnsurePropertyCell(
5949 Handle<GlobalObject> global,
5950 Handle<String> name);
5951 // TODO(kmillikin): This function can be eliminated once the stub cache is
5952 // full handlified (and the static helper can be written directly).
5953 MUST_USE_RESULT MaybeObject* EnsurePropertyCell(String* name);
5956 static inline GlobalObject* cast(Object* obj);
5958 // Layout description.
5959 static const int kBuiltinsOffset = JSObject::kHeaderSize;
5960 static const int kGlobalContextOffset = kBuiltinsOffset + kPointerSize;
5961 static const int kGlobalReceiverOffset = kGlobalContextOffset + kPointerSize;
5962 static const int kHeaderSize = kGlobalReceiverOffset + kPointerSize;
5965 DISALLOW_IMPLICIT_CONSTRUCTORS(GlobalObject);
5969 // JavaScript global object.
5970 class JSGlobalObject: public GlobalObject {
5973 static inline JSGlobalObject* cast(Object* obj);
5975 // Dispatched behavior.
5977 inline void JSGlobalObjectPrint() {
5978 JSGlobalObjectPrint(stdout);
5980 void JSGlobalObjectPrint(FILE* out);
5983 void JSGlobalObjectVerify();
5986 // Layout description.
5987 static const int kSize = GlobalObject::kHeaderSize;
5990 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalObject);
5994 // Builtins global object which holds the runtime routines written in
5996 class JSBuiltinsObject: public GlobalObject {
5998 // Accessors for the runtime routines written in JavaScript.
5999 inline Object* javascript_builtin(Builtins::JavaScript id);
6000 inline void set_javascript_builtin(Builtins::JavaScript id, Object* value);
6002 // Accessors for code of the runtime routines written in JavaScript.
6003 inline Code* javascript_builtin_code(Builtins::JavaScript id);
6004 inline void set_javascript_builtin_code(Builtins::JavaScript id, Code* value);
6007 static inline JSBuiltinsObject* cast(Object* obj);
6009 // Dispatched behavior.
6011 inline void JSBuiltinsObjectPrint() {
6012 JSBuiltinsObjectPrint(stdout);
6014 void JSBuiltinsObjectPrint(FILE* out);
6017 void JSBuiltinsObjectVerify();
6020 // Layout description. The size of the builtins object includes
6021 // room for two pointers per runtime routine written in javascript
6022 // (function and code object).
6023 static const int kJSBuiltinsCount = Builtins::id_count;
6024 static const int kJSBuiltinsOffset = GlobalObject::kHeaderSize;
6025 static const int kJSBuiltinsCodeOffset =
6026 GlobalObject::kHeaderSize + (kJSBuiltinsCount * kPointerSize);
6027 static const int kSize =
6028 kJSBuiltinsCodeOffset + (kJSBuiltinsCount * kPointerSize);
6030 static int OffsetOfFunctionWithId(Builtins::JavaScript id) {
6031 return kJSBuiltinsOffset + id * kPointerSize;
6034 static int OffsetOfCodeWithId(Builtins::JavaScript id) {
6035 return kJSBuiltinsCodeOffset + id * kPointerSize;
6039 DISALLOW_IMPLICIT_CONSTRUCTORS(JSBuiltinsObject);
6043 // Representation for JS Wrapper objects, String, Number, Boolean, etc.
6044 class JSValue: public JSObject {
6046 // [value]: the object being wrapped.
6047 DECL_ACCESSORS(value, Object)
6050 static inline JSValue* cast(Object* obj);
6052 // Dispatched behavior.
6054 inline void JSValuePrint() {
6055 JSValuePrint(stdout);
6057 void JSValuePrint(FILE* out);
6060 void JSValueVerify();
6063 // Layout description.
6064 static const int kValueOffset = JSObject::kHeaderSize;
6065 static const int kSize = kValueOffset + kPointerSize;
6068 DISALLOW_IMPLICIT_CONSTRUCTORS(JSValue);
6074 // Representation for JS date objects.
6075 class JSDate: public JSObject {
6077 // If one component is NaN, all of them are, indicating a NaN time value.
6078 // [value]: the time value.
6079 DECL_ACCESSORS(value, Object)
6080 // [year]: caches year. Either undefined, smi, or NaN.
6081 DECL_ACCESSORS(year, Object)
6082 // [month]: caches month. Either undefined, smi, or NaN.
6083 DECL_ACCESSORS(month, Object)
6084 // [day]: caches day. Either undefined, smi, or NaN.
6085 DECL_ACCESSORS(day, Object)
6086 // [weekday]: caches day of week. Either undefined, smi, or NaN.
6087 DECL_ACCESSORS(weekday, Object)
6088 // [hour]: caches hours. Either undefined, smi, or NaN.
6089 DECL_ACCESSORS(hour, Object)
6090 // [min]: caches minutes. Either undefined, smi, or NaN.
6091 DECL_ACCESSORS(min, Object)
6092 // [sec]: caches seconds. Either undefined, smi, or NaN.
6093 DECL_ACCESSORS(sec, Object)
6094 // [cache stamp]: sample of the date cache stamp at the
6095 // moment when local fields were cached.
6096 DECL_ACCESSORS(cache_stamp, Object)
6099 static inline JSDate* cast(Object* obj);
6101 // Returns the date field with the specified index.
6102 // See FieldIndex for the list of date fields.
6103 static MaybeObject* GetField(Object* date, Smi* index);
6105 void SetValue(Object* value, bool is_value_nan);
6108 // Dispatched behavior.
6110 inline void JSDatePrint() {
6111 JSDatePrint(stdout);
6113 void JSDatePrint(FILE* out);
6116 void JSDateVerify();
6118 // The order is important. It must be kept in sync with date macros
6129 kFirstUncachedField,
6130 kMillisecond = kFirstUncachedField,
6134 kYearUTC = kFirstUTCField,
6147 // Layout description.
6148 static const int kValueOffset = JSObject::kHeaderSize;
6149 static const int kYearOffset = kValueOffset + kPointerSize;
6150 static const int kMonthOffset = kYearOffset + kPointerSize;
6151 static const int kDayOffset = kMonthOffset + kPointerSize;
6152 static const int kWeekdayOffset = kDayOffset + kPointerSize;
6153 static const int kHourOffset = kWeekdayOffset + kPointerSize;
6154 static const int kMinOffset = kHourOffset + kPointerSize;
6155 static const int kSecOffset = kMinOffset + kPointerSize;
6156 static const int kCacheStampOffset = kSecOffset + kPointerSize;
6157 static const int kSize = kCacheStampOffset + kPointerSize;
6160 inline Object* DoGetField(FieldIndex index);
6162 Object* GetUTCField(FieldIndex index, double value, DateCache* date_cache);
6164 // Computes and caches the cacheable fields of the date.
6165 inline void SetLocalFields(int64_t local_time_ms, DateCache* date_cache);
6168 DISALLOW_IMPLICIT_CONSTRUCTORS(JSDate);
6172 // Representation of message objects used for error reporting through
6173 // the API. The messages are formatted in JavaScript so this object is
6174 // a real JavaScript object. The information used for formatting the
6175 // error messages are not directly accessible from JavaScript to
6176 // prevent leaking information to user code called during error
6178 class JSMessageObject: public JSObject {
6180 // [type]: the type of error message.
6181 DECL_ACCESSORS(type, String)
6183 // [arguments]: the arguments for formatting the error message.
6184 DECL_ACCESSORS(arguments, JSArray)
6186 // [script]: the script from which the error message originated.
6187 DECL_ACCESSORS(script, Object)
6189 // [stack_trace]: the stack trace for this error message.
6190 DECL_ACCESSORS(stack_trace, Object)
6192 // [stack_frames]: an array of stack frames for this error object.
6193 DECL_ACCESSORS(stack_frames, Object)
6195 // [start_position]: the start position in the script for the error message.
6196 inline int start_position();
6197 inline void set_start_position(int value);
6199 // [end_position]: the end position in the script for the error message.
6200 inline int end_position();
6201 inline void set_end_position(int value);
6204 static inline JSMessageObject* cast(Object* obj);
6206 // Dispatched behavior.
6208 inline void JSMessageObjectPrint() {
6209 JSMessageObjectPrint(stdout);
6211 void JSMessageObjectPrint(FILE* out);
6214 void JSMessageObjectVerify();
6217 // Layout description.
6218 static const int kTypeOffset = JSObject::kHeaderSize;
6219 static const int kArgumentsOffset = kTypeOffset + kPointerSize;
6220 static const int kScriptOffset = kArgumentsOffset + kPointerSize;
6221 static const int kStackTraceOffset = kScriptOffset + kPointerSize;
6222 static const int kStackFramesOffset = kStackTraceOffset + kPointerSize;
6223 static const int kStartPositionOffset = kStackFramesOffset + kPointerSize;
6224 static const int kEndPositionOffset = kStartPositionOffset + kPointerSize;
6225 static const int kSize = kEndPositionOffset + kPointerSize;
6227 typedef FixedBodyDescriptor<HeapObject::kMapOffset,
6228 kStackFramesOffset + kPointerSize,
6229 kSize> BodyDescriptor;
6233 // Regular expressions
6234 // The regular expression holds a single reference to a FixedArray in
6235 // the kDataOffset field.
6236 // The FixedArray contains the following data:
6237 // - tag : type of regexp implementation (not compiled yet, atom or irregexp)
6238 // - reference to the original source string
6239 // - reference to the original flag string
6240 // If it is an atom regexp
6241 // - a reference to a literal string to search for
6242 // If it is an irregexp regexp:
6243 // - a reference to code for ASCII inputs (bytecode or compiled), or a smi
6244 // used for tracking the last usage (used for code flushing).
6245 // - a reference to code for UC16 inputs (bytecode or compiled), or a smi
6246 // used for tracking the last usage (used for code flushing)..
6247 // - max number of registers used by irregexp implementations.
6248 // - number of capture registers (output values) of the regexp.
6249 class JSRegExp: public JSObject {
6252 // NOT_COMPILED: Initial value. No data has been stored in the JSRegExp yet.
6253 // ATOM: A simple string to match against using an indexOf operation.
6254 // IRREGEXP: Compiled with Irregexp.
6255 // IRREGEXP_NATIVE: Compiled to native code with Irregexp.
6256 enum Type { NOT_COMPILED, ATOM, IRREGEXP };
6257 enum Flag { NONE = 0, GLOBAL = 1, IGNORE_CASE = 2, MULTILINE = 4 };
6261 explicit Flags(uint32_t value) : value_(value) { }
6262 bool is_global() { return (value_ & GLOBAL) != 0; }
6263 bool is_ignore_case() { return (value_ & IGNORE_CASE) != 0; }
6264 bool is_multiline() { return (value_ & MULTILINE) != 0; }
6265 uint32_t value() { return value_; }
6270 DECL_ACCESSORS(data, Object)
6272 inline Type TypeTag();
6273 inline int CaptureCount();
6274 inline Flags GetFlags();
6275 inline String* Pattern();
6276 inline Object* DataAt(int index);
6277 // Set implementation data after the object has been prepared.
6278 inline void SetDataAt(int index, Object* value);
6280 // Used during GC when flushing code or setting age.
6281 inline Object* DataAtUnchecked(int index);
6282 inline void SetDataAtUnchecked(int index, Object* value, Heap* heap);
6283 inline Type TypeTagUnchecked();
6285 static int code_index(bool is_ascii) {
6287 return kIrregexpASCIICodeIndex;
6289 return kIrregexpUC16CodeIndex;
6293 static int saved_code_index(bool is_ascii) {
6295 return kIrregexpASCIICodeSavedIndex;
6297 return kIrregexpUC16CodeSavedIndex;
6301 static inline JSRegExp* cast(Object* obj);
6303 // Dispatched behavior.
6305 void JSRegExpVerify();
6308 static const int kDataOffset = JSObject::kHeaderSize;
6309 static const int kSize = kDataOffset + kPointerSize;
6311 // Indices in the data array.
6312 static const int kTagIndex = 0;
6313 static const int kSourceIndex = kTagIndex + 1;
6314 static const int kFlagsIndex = kSourceIndex + 1;
6315 static const int kDataIndex = kFlagsIndex + 1;
6316 // The data fields are used in different ways depending on the
6317 // value of the tag.
6318 // Atom regexps (literal strings).
6319 static const int kAtomPatternIndex = kDataIndex;
6321 static const int kAtomDataSize = kAtomPatternIndex + 1;
6323 // Irregexp compiled code or bytecode for ASCII. If compilation
6324 // fails, this fields hold an exception object that should be
6325 // thrown if the regexp is used again.
6326 static const int kIrregexpASCIICodeIndex = kDataIndex;
6327 // Irregexp compiled code or bytecode for UC16. If compilation
6328 // fails, this fields hold an exception object that should be
6329 // thrown if the regexp is used again.
6330 static const int kIrregexpUC16CodeIndex = kDataIndex + 1;
6332 // Saved instance of Irregexp compiled code or bytecode for ASCII that
6333 // is a potential candidate for flushing.
6334 static const int kIrregexpASCIICodeSavedIndex = kDataIndex + 2;
6335 // Saved instance of Irregexp compiled code or bytecode for UC16 that is
6336 // a potential candidate for flushing.
6337 static const int kIrregexpUC16CodeSavedIndex = kDataIndex + 3;
6339 // Maximal number of registers used by either ASCII or UC16.
6340 // Only used to check that there is enough stack space
6341 static const int kIrregexpMaxRegisterCountIndex = kDataIndex + 4;
6342 // Number of captures in the compiled regexp.
6343 static const int kIrregexpCaptureCountIndex = kDataIndex + 5;
6345 static const int kIrregexpDataSize = kIrregexpCaptureCountIndex + 1;
6347 // Offsets directly into the data fixed array.
6348 static const int kDataTagOffset =
6349 FixedArray::kHeaderSize + kTagIndex * kPointerSize;
6350 static const int kDataAsciiCodeOffset =
6351 FixedArray::kHeaderSize + kIrregexpASCIICodeIndex * kPointerSize;
6352 static const int kDataUC16CodeOffset =
6353 FixedArray::kHeaderSize + kIrregexpUC16CodeIndex * kPointerSize;
6354 static const int kIrregexpCaptureCountOffset =
6355 FixedArray::kHeaderSize + kIrregexpCaptureCountIndex * kPointerSize;
6357 // In-object fields.
6358 static const int kSourceFieldIndex = 0;
6359 static const int kGlobalFieldIndex = 1;
6360 static const int kIgnoreCaseFieldIndex = 2;
6361 static const int kMultilineFieldIndex = 3;
6362 static const int kLastIndexFieldIndex = 4;
6363 static const int kInObjectFieldCount = 5;
6365 // The uninitialized value for a regexp code object.
6366 static const int kUninitializedValue = -1;
6368 // The compilation error value for the regexp code object. The real error
6369 // object is in the saved code field.
6370 static const int kCompilationErrorValue = -2;
6372 // When we store the sweep generation at which we moved the code from the
6373 // code index to the saved code index we mask it of to be in the [0:255]
6375 static const int kCodeAgeMask = 0xff;
6379 class CompilationCacheShape : public BaseShape<HashTableKey*> {
6381 static inline bool IsMatch(HashTableKey* key, Object* value) {
6382 return key->IsMatch(value);
6385 static inline uint32_t Hash(HashTableKey* key) {
6389 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
6390 return key->HashForObject(object);
6393 MUST_USE_RESULT static MaybeObject* AsObject(HashTableKey* key) {
6394 return key->AsObject();
6397 static const int kPrefixSize = 0;
6398 static const int kEntrySize = 2;
6402 class CompilationCacheTable: public HashTable<CompilationCacheShape,
6405 // Find cached value for a string key, otherwise return null.
6406 Object* Lookup(String* src);
6407 Object* LookupEval(String* src,
6409 LanguageMode language_mode,
6410 int scope_position);
6411 Object* LookupRegExp(String* source, JSRegExp::Flags flags);
6412 MUST_USE_RESULT MaybeObject* Put(String* src, Object* value);
6413 MUST_USE_RESULT MaybeObject* PutEval(String* src,
6415 SharedFunctionInfo* value,
6416 int scope_position);
6417 MUST_USE_RESULT MaybeObject* PutRegExp(String* src,
6418 JSRegExp::Flags flags,
6421 // Remove given value from cache.
6422 void Remove(Object* value);
6424 static inline CompilationCacheTable* cast(Object* obj);
6427 DISALLOW_IMPLICIT_CONSTRUCTORS(CompilationCacheTable);
6431 class CodeCache: public Struct {
6433 DECL_ACCESSORS(default_cache, FixedArray)
6434 DECL_ACCESSORS(normal_type_cache, Object)
6436 // Add the code object to the cache.
6437 MUST_USE_RESULT MaybeObject* Update(String* name, Code* code);
6439 // Lookup code object in the cache. Returns code object if found and undefined
6441 Object* Lookup(String* name, Code::Flags flags);
6443 // Get the internal index of a code object in the cache. Returns -1 if the
6444 // code object is not in that cache. This index can be used to later call
6445 // RemoveByIndex. The cache cannot be modified between a call to GetIndex and
6447 int GetIndex(Object* name, Code* code);
6449 // Remove an object from the cache with the provided internal index.
6450 void RemoveByIndex(Object* name, Code* code, int index);
6452 static inline CodeCache* cast(Object* obj);
6455 inline void CodeCachePrint() {
6456 CodeCachePrint(stdout);
6458 void CodeCachePrint(FILE* out);
6461 void CodeCacheVerify();
6464 static const int kDefaultCacheOffset = HeapObject::kHeaderSize;
6465 static const int kNormalTypeCacheOffset =
6466 kDefaultCacheOffset + kPointerSize;
6467 static const int kSize = kNormalTypeCacheOffset + kPointerSize;
6470 MUST_USE_RESULT MaybeObject* UpdateDefaultCache(String* name, Code* code);
6471 MUST_USE_RESULT MaybeObject* UpdateNormalTypeCache(String* name, Code* code);
6472 Object* LookupDefaultCache(String* name, Code::Flags flags);
6473 Object* LookupNormalTypeCache(String* name, Code::Flags flags);
6475 // Code cache layout of the default cache. Elements are alternating name and
6476 // code objects for non normal load/store/call IC's.
6477 static const int kCodeCacheEntrySize = 2;
6478 static const int kCodeCacheEntryNameOffset = 0;
6479 static const int kCodeCacheEntryCodeOffset = 1;
6481 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCache);
6485 class CodeCacheHashTableShape : public BaseShape<HashTableKey*> {
6487 static inline bool IsMatch(HashTableKey* key, Object* value) {
6488 return key->IsMatch(value);
6491 static inline uint32_t Hash(HashTableKey* key) {
6495 static inline uint32_t HashForObject(HashTableKey* key, Object* object) {
6496 return key->HashForObject(object);
6499 MUST_USE_RESULT static MaybeObject* AsObject(HashTableKey* key) {
6500 return key->AsObject();
6503 static const int kPrefixSize = 0;
6504 static const int kEntrySize = 2;
6508 class CodeCacheHashTable: public HashTable<CodeCacheHashTableShape,
6511 Object* Lookup(String* name, Code::Flags flags);
6512 MUST_USE_RESULT MaybeObject* Put(String* name, Code* code);
6514 int GetIndex(String* name, Code::Flags flags);
6515 void RemoveByIndex(int index);
6517 static inline CodeCacheHashTable* cast(Object* obj);
6519 // Initial size of the fixed array backing the hash table.
6520 static const int kInitialSize = 64;
6523 DISALLOW_IMPLICIT_CONSTRUCTORS(CodeCacheHashTable);
6527 class PolymorphicCodeCache: public Struct {
6529 DECL_ACCESSORS(cache, Object)
6531 static void Update(Handle<PolymorphicCodeCache> cache,
6532 MapHandleList* maps,
6536 MUST_USE_RESULT MaybeObject* Update(MapHandleList* maps,
6540 // Returns an undefined value if the entry is not found.
6541 Handle<Object> Lookup(MapHandleList* maps, Code::Flags flags);
6543 static inline PolymorphicCodeCache* cast(Object* obj);
6546 inline void PolymorphicCodeCachePrint() {
6547 PolymorphicCodeCachePrint(stdout);
6549 void PolymorphicCodeCachePrint(FILE* out);
6552 void PolymorphicCodeCacheVerify();
6555 static const int kCacheOffset = HeapObject::kHeaderSize;
6556 static const int kSize = kCacheOffset + kPointerSize;
6559 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCache);
6563 class PolymorphicCodeCacheHashTable
6564 : public HashTable<CodeCacheHashTableShape, HashTableKey*> {
6566 Object* Lookup(MapHandleList* maps, int code_kind);
6568 MUST_USE_RESULT MaybeObject* Put(MapHandleList* maps,
6572 static inline PolymorphicCodeCacheHashTable* cast(Object* obj);
6574 static const int kInitialSize = 64;
6576 DISALLOW_IMPLICIT_CONSTRUCTORS(PolymorphicCodeCacheHashTable);
6580 class TypeFeedbackInfo: public Struct {
6582 inline int ic_total_count();
6583 inline void set_ic_total_count(int count);
6585 inline int ic_with_type_info_count();
6586 inline void set_ic_with_type_info_count(int count);
6588 DECL_ACCESSORS(type_feedback_cells, TypeFeedbackCells)
6590 static inline TypeFeedbackInfo* cast(Object* obj);
6593 inline void TypeFeedbackInfoPrint() {
6594 TypeFeedbackInfoPrint(stdout);
6596 void TypeFeedbackInfoPrint(FILE* out);
6599 void TypeFeedbackInfoVerify();
6602 static const int kIcTotalCountOffset = HeapObject::kHeaderSize;
6603 static const int kIcWithTypeinfoCountOffset =
6604 kIcTotalCountOffset + kPointerSize;
6605 static const int kTypeFeedbackCellsOffset =
6606 kIcWithTypeinfoCountOffset + kPointerSize;
6607 static const int kSize = kTypeFeedbackCellsOffset + kPointerSize;
6610 DISALLOW_IMPLICIT_CONSTRUCTORS(TypeFeedbackInfo);
6614 // Representation of a slow alias as part of a non-strict arguments objects.
6615 // For fast aliases (if HasNonStrictArgumentsElements()):
6616 // - the parameter map contains an index into the context
6617 // - all attributes of the element have default values
6618 // For slow aliases (if HasDictionaryArgumentsElements()):
6619 // - the parameter map contains no fast alias mapping (i.e. the hole)
6620 // - this struct (in the slow backing store) contains an index into the context
6621 // - all attributes are available as part if the property details
6622 class AliasedArgumentsEntry: public Struct {
6624 inline int aliased_context_slot();
6625 inline void set_aliased_context_slot(int count);
6627 static inline AliasedArgumentsEntry* cast(Object* obj);
6630 inline void AliasedArgumentsEntryPrint() {
6631 AliasedArgumentsEntryPrint(stdout);
6633 void AliasedArgumentsEntryPrint(FILE* out);
6636 void AliasedArgumentsEntryVerify();
6639 static const int kAliasedContextSlot = HeapObject::kHeaderSize;
6640 static const int kSize = kAliasedContextSlot + kPointerSize;
6643 DISALLOW_IMPLICIT_CONSTRUCTORS(AliasedArgumentsEntry);
6647 enum AllowNullsFlag {ALLOW_NULLS, DISALLOW_NULLS};
6648 enum RobustnessFlag {ROBUST_STRING_TRAVERSAL, FAST_STRING_TRAVERSAL};
6651 class StringHasher {
6653 explicit inline StringHasher(int length, uint32_t seed);
6655 // Returns true if the hash of this string can be computed without
6656 // looking at the contents.
6657 inline bool has_trivial_hash();
6659 // Add a character to the hash and update the array index calculation.
6660 inline void AddCharacter(uint32_t c);
6662 // Adds a character to the hash but does not update the array index
6663 // calculation. This can only be called when it has been verified
6664 // that the input is not an array index.
6665 inline void AddCharacterNoIndex(uint32_t c);
6667 // Add a character above 0xffff as a surrogate pair. These can get into
6668 // the hasher through the routines that take a UTF-8 string and make a symbol.
6669 void AddSurrogatePair(uc32 c);
6670 void AddSurrogatePairNoIndex(uc32 c);
6672 // Returns the value to store in the hash field of a string with
6673 // the given length and contents.
6674 uint32_t GetHashField();
6676 // Returns true if the characters seen so far make up a legal array
6678 bool is_array_index() { return is_array_index_; }
6680 bool is_valid() { return is_valid_; }
6682 void invalidate() { is_valid_ = false; }
6684 // Calculated hash value for a string consisting of 1 to
6685 // String::kMaxArrayIndexSize digits with no leading zeros (except "0").
6686 // value is represented decimal value.
6687 static uint32_t MakeArrayIndexHash(uint32_t value, int length);
6689 // No string is allowed to have a hash of zero. That value is reserved
6690 // for internal properties. If the hash calculation yields zero then we
6692 static const int kZeroHash = 27;
6695 uint32_t array_index() {
6696 ASSERT(is_array_index());
6697 return array_index_;
6700 inline uint32_t GetHash();
6703 uint32_t raw_running_hash_;
6704 uint32_t array_index_;
6705 bool is_array_index_;
6706 bool is_first_char_;
6708 friend class TwoCharHashTableKey;
6712 // Calculates string hash.
6713 template <typename schar>
6714 inline uint32_t HashSequentialString(const schar* chars,
6719 // The characteristics of a string are stored in its map. Retrieving these
6720 // few bits of information is moderately expensive, involving two memory
6721 // loads where the second is dependent on the first. To improve efficiency
6722 // the shape of the string is given its own class so that it can be retrieved
6723 // once and used for several string operations. A StringShape is small enough
6724 // to be passed by value and is immutable, but be aware that flattening a
6725 // string can potentially alter its shape. Also be aware that a GC caused by
6726 // something else can alter the shape of a string due to ConsString
6727 // shortcutting. Keeping these restrictions in mind has proven to be error-
6728 // prone and so we no longer put StringShapes in variables unless there is a
6729 // concrete performance benefit at that particular point in the code.
6730 class StringShape BASE_EMBEDDED {
6732 inline explicit StringShape(String* s);
6733 inline explicit StringShape(Map* s);
6734 inline explicit StringShape(InstanceType t);
6735 inline bool IsSequential();
6736 inline bool IsExternal();
6737 inline bool IsCons();
6738 inline bool IsSliced();
6739 inline bool IsIndirect();
6740 inline bool IsExternalAscii();
6741 inline bool IsExternalTwoByte();
6742 inline bool IsSequentialAscii();
6743 inline bool IsSequentialTwoByte();
6744 inline bool IsSymbol();
6745 inline StringRepresentationTag representation_tag();
6746 inline uint32_t encoding_tag();
6747 inline uint32_t full_representation_tag();
6748 inline uint32_t size_tag();
6750 inline uint32_t type() { return type_; }
6751 inline void invalidate() { valid_ = false; }
6752 inline bool valid() { return valid_; }
6754 inline void invalidate() { }
6760 inline void set_valid() { valid_ = true; }
6763 inline void set_valid() { }
6768 // The String abstract class captures JavaScript string values:
6771 // 4.3.16 String Value
6772 // A string value is a member of the type String and is a finite
6773 // ordered sequence of zero or more 16-bit unsigned integer values.
6775 // All string values have a length field.
6776 class String: public HeapObject {
6778 // Representation of the flat content of a String.
6779 // A non-flat string doesn't have flat content.
6780 // A flat string has content that's encoded as a sequence of either
6781 // ASCII chars or two-byte UC16.
6782 // Returned by String::GetFlatContent().
6785 // Returns true if the string is flat and this structure contains content.
6786 bool IsFlat() { return state_ != NON_FLAT; }
6787 // Returns true if the structure contains ASCII content.
6788 bool IsAscii() { return state_ == ASCII; }
6789 // Returns true if the structure contains two-byte content.
6790 bool IsTwoByte() { return state_ == TWO_BYTE; }
6792 // Return the ASCII content of the string. Only use if IsAscii() returns
6794 Vector<const char> ToAsciiVector() {
6795 ASSERT_EQ(ASCII, state_);
6796 return Vector<const char>::cast(buffer_);
6798 // Return the two-byte content of the string. Only use if IsTwoByte()
6800 Vector<const uc16> ToUC16Vector() {
6801 ASSERT_EQ(TWO_BYTE, state_);
6802 return Vector<const uc16>::cast(buffer_);
6806 enum State { NON_FLAT, ASCII, TWO_BYTE };
6808 // Constructors only used by String::GetFlatContent().
6809 explicit FlatContent(Vector<const char> chars)
6810 : buffer_(Vector<const byte>::cast(chars)),
6812 explicit FlatContent(Vector<const uc16> chars)
6813 : buffer_(Vector<const byte>::cast(chars)),
6814 state_(TWO_BYTE) { }
6815 FlatContent() : buffer_(), state_(NON_FLAT) { }
6817 Vector<const byte> buffer_;
6820 friend class String;
6823 // Get and set the length of the string.
6824 inline int length();
6825 inline void set_length(int value);
6827 // Get and set the hash field of the string.
6828 inline uint32_t hash_field();
6829 inline void set_hash_field(uint32_t value);
6831 // Returns whether this string has only ASCII chars, i.e. all of them can
6832 // be ASCII encoded. This might be the case even if the string is
6833 // two-byte. Such strings may appear when the embedder prefers
6834 // two-byte external representations even for ASCII data.
6835 inline bool IsAsciiRepresentation();
6836 inline bool IsTwoByteRepresentation();
6838 // Cons and slices have an encoding flag that may not represent the actual
6839 // encoding of the underlying string. This is taken into account here.
6840 // Requires: this->IsFlat()
6841 inline bool IsAsciiRepresentationUnderneath();
6842 inline bool IsTwoByteRepresentationUnderneath();
6844 // NOTE: this should be considered only a hint. False negatives are
6846 inline bool HasOnlyAsciiChars();
6848 // Get and set individual two byte chars in the string.
6849 inline void Set(int index, uint16_t value);
6850 // Get individual two byte char in the string. Repeated calls
6851 // to this method are not efficient unless the string is flat.
6852 inline uint16_t Get(int index);
6854 // Try to flatten the string. Checks first inline to see if it is
6855 // necessary. Does nothing if the string is not a cons string.
6856 // Flattening allocates a sequential string with the same data as
6857 // the given string and mutates the cons string to a degenerate
6858 // form, where the first component is the new sequential string and
6859 // the second component is the empty string. If allocation fails,
6860 // this function returns a failure. If flattening succeeds, this
6861 // function returns the sequential string that is now the first
6862 // component of the cons string.
6864 // Degenerate cons strings are handled specially by the garbage
6865 // collector (see IsShortcutCandidate).
6867 // Use FlattenString from Handles.cc to flatten even in case an
6868 // allocation failure happens.
6869 inline MaybeObject* TryFlatten(PretenureFlag pretenure = NOT_TENURED);
6871 // Convenience function. Has exactly the same behavior as
6872 // TryFlatten(), except in the case of failure returns the original
6874 inline String* TryFlattenGetString(PretenureFlag pretenure = NOT_TENURED);
6876 // Tries to return the content of a flat string as a structure holding either
6877 // a flat vector of char or of uc16.
6878 // If the string isn't flat, and therefore doesn't have flat content, the
6879 // returned structure will report so, and can't provide a vector of either
6881 FlatContent GetFlatContent();
6883 // Returns the parent of a sliced string or first part of a flat cons string.
6884 // Requires: StringShape(this).IsIndirect() && this->IsFlat()
6885 inline String* GetUnderlying();
6887 // Mark the string as an undetectable object. It only applies to
6888 // ASCII and two byte string types.
6889 bool MarkAsUndetectable();
6891 // Return a substring.
6892 MUST_USE_RESULT MaybeObject* SubString(int from,
6894 PretenureFlag pretenure = NOT_TENURED);
6896 // String equality operations.
6897 inline bool Equals(String* other);
6898 bool IsEqualTo(Vector<const char> str);
6899 bool IsAsciiEqualTo(Vector<const char> str);
6900 bool IsTwoByteEqualTo(Vector<const uc16> str);
6902 bool SlowEqualsExternal(uc16 *string, int length);
6903 bool SlowEqualsExternal(char *string, int length);
6905 // Return a UTF8 representation of the string. The string is null
6906 // terminated but may optionally contain nulls. Length is returned
6907 // in length_output if length_output is not a null pointer The string
6908 // should be nearly flat, otherwise the performance of this method may
6909 // be very slow (quadratic in the length). Setting robustness_flag to
6910 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
6911 // handles unexpected data without causing assert failures and it does not
6912 // do any heap allocations. This is useful when printing stack traces.
6913 SmartArrayPointer<char> ToCString(AllowNullsFlag allow_nulls,
6914 RobustnessFlag robustness_flag,
6917 int* length_output = 0);
6918 SmartArrayPointer<char> ToCString(
6919 AllowNullsFlag allow_nulls = DISALLOW_NULLS,
6920 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL,
6921 int* length_output = 0);
6923 // Return a 16 bit Unicode representation of the string.
6924 // The string should be nearly flat, otherwise the performance of
6925 // of this method may be very bad. Setting robustness_flag to
6926 // ROBUST_STRING_TRAVERSAL invokes behaviour that is robust This means it
6927 // handles unexpected data without causing assert failures and it does not
6928 // do any heap allocations. This is useful when printing stack traces.
6929 SmartArrayPointer<uc16> ToWideCString(
6930 RobustnessFlag robustness_flag = FAST_STRING_TRAVERSAL);
6932 // Tells whether the hash code has been computed.
6933 inline bool HasHashCode();
6935 // Returns a hash value used for the property table
6936 inline uint32_t Hash();
6938 static uint32_t ComputeHashField(unibrow::CharacterStream* buffer,
6942 static bool ComputeArrayIndex(unibrow::CharacterStream* buffer,
6947 bool MakeExternal(v8::String::ExternalStringResource* resource);
6948 bool MakeExternal(v8::String::ExternalAsciiStringResource* resource);
6951 inline bool AsArrayIndex(uint32_t* index);
6954 static inline String* cast(Object* obj);
6956 void PrintOn(FILE* out);
6958 // For use during stack traces. Performs rudimentary sanity check.
6961 // Dispatched behavior.
6962 void StringShortPrint(StringStream* accumulator);
6964 inline void StringPrint() {
6965 StringPrint(stdout);
6967 void StringPrint(FILE* out);
6969 char* ToAsciiArray();
6972 void StringVerify();
6974 inline bool IsFlat();
6976 // Layout description.
6977 static const int kLengthOffset = HeapObject::kHeaderSize;
6978 static const int kHashFieldOffset = kLengthOffset + kPointerSize;
6979 static const int kSize = kHashFieldOffset + kPointerSize;
6981 // Maximum number of characters to consider when trying to convert a string
6982 // value into an array index.
6983 static const int kMaxArrayIndexSize = 10;
6985 // Max ASCII char code.
6986 static const int kMaxAsciiCharCode = unibrow::Utf8::kMaxOneByteChar;
6987 static const unsigned kMaxAsciiCharCodeU = unibrow::Utf8::kMaxOneByteChar;
6988 static const int kMaxUtf16CodeUnit = 0xffff;
6990 // Mask constant for checking if a string has a computed hash code
6991 // and if it is an array index. The least significant bit indicates
6992 // whether a hash code has been computed. If the hash code has been
6993 // computed the 2nd bit tells whether the string can be used as an
6995 static const int kHashNotComputedMask = 1;
6996 static const int kIsNotArrayIndexMask = 1 << 1;
6997 static const int kNofHashBitFields = 2;
6999 // Shift constant retrieving hash code from hash field.
7000 static const int kHashShift = kNofHashBitFields;
7002 // Only these bits are relevant in the hash, since the top two are shifted
7004 static const uint32_t kHashBitMask = 0xffffffffu >> kHashShift;
7006 // Array index strings this short can keep their index in the hash
7008 static const int kMaxCachedArrayIndexLength = 7;
7010 // For strings which are array indexes the hash value has the string length
7011 // mixed into the hash, mainly to avoid a hash value of zero which would be
7012 // the case for the string '0'. 24 bits are used for the array index value.
7013 static const int kArrayIndexValueBits = 24;
7014 static const int kArrayIndexLengthBits =
7015 kBitsPerInt - kArrayIndexValueBits - kNofHashBitFields;
7017 STATIC_CHECK((kArrayIndexLengthBits > 0));
7018 STATIC_CHECK(kMaxArrayIndexSize < (1 << kArrayIndexLengthBits));
7020 static const int kArrayIndexHashLengthShift =
7021 kArrayIndexValueBits + kNofHashBitFields;
7023 static const int kArrayIndexHashMask = (1 << kArrayIndexHashLengthShift) - 1;
7025 static const int kArrayIndexValueMask =
7026 ((1 << kArrayIndexValueBits) - 1) << kHashShift;
7028 // Check that kMaxCachedArrayIndexLength + 1 is a power of two so we
7029 // could use a mask to test if the length of string is less than or equal to
7030 // kMaxCachedArrayIndexLength.
7031 STATIC_CHECK(IS_POWER_OF_TWO(kMaxCachedArrayIndexLength + 1));
7033 static const int kContainsCachedArrayIndexMask =
7034 (~kMaxCachedArrayIndexLength << kArrayIndexHashLengthShift) |
7035 kIsNotArrayIndexMask;
7037 // Value of empty hash field indicating that the hash is not computed.
7038 static const int kEmptyHashField =
7039 kIsNotArrayIndexMask | kHashNotComputedMask;
7041 // Value of hash field containing computed hash equal to zero.
7042 static const int kZeroHash = kIsNotArrayIndexMask;
7044 // Maximal string length.
7045 static const int kMaxLength = (1 << (32 - 2)) - 1;
7047 // Max length for computing hash. For strings longer than this limit the
7048 // string length is used as the hash value.
7049 static const int kMaxHashCalcLength = 16383;
7051 // Limit for truncation in short printing.
7052 static const int kMaxShortPrintLength = 1024;
7054 // Support for regular expressions.
7055 const uc16* GetTwoByteData();
7056 const uc16* GetTwoByteData(unsigned start);
7058 // Support for StringInputBuffer
7059 static const unibrow::byte* ReadBlock(String* input,
7060 unibrow::byte* util_buffer,
7062 unsigned* remaining,
7064 static const unibrow::byte* ReadBlock(String** input,
7065 unibrow::byte* util_buffer,
7067 unsigned* remaining,
7070 // Helper function for flattening strings.
7071 template <typename sinkchar>
7072 static void WriteToFlat(String* source,
7077 static inline bool IsAscii(const char* chars, int length) {
7078 const char* limit = chars + length;
7079 #ifdef V8_HOST_CAN_READ_UNALIGNED
7080 ASSERT(kMaxAsciiCharCode == 0x7F);
7081 const uintptr_t non_ascii_mask = kUintptrAllBitsSet / 0xFF * 0x80;
7082 while (chars <= limit - sizeof(uintptr_t)) {
7083 if (*reinterpret_cast<const uintptr_t*>(chars) & non_ascii_mask) {
7086 chars += sizeof(uintptr_t);
7089 while (chars < limit) {
7090 if (static_cast<uint8_t>(*chars) > kMaxAsciiCharCodeU) return false;
7096 static inline bool IsAscii(const uc16* chars, int length) {
7097 const uc16* limit = chars + length;
7098 while (chars < limit) {
7099 if (*chars > kMaxAsciiCharCodeU) return false;
7106 class ReadBlockBuffer {
7108 ReadBlockBuffer(unibrow::byte* util_buffer_,
7111 unsigned remaining_) :
7112 util_buffer(util_buffer_),
7114 capacity(capacity_),
7115 remaining(remaining_) {
7117 unibrow::byte* util_buffer;
7123 static inline const unibrow::byte* ReadBlock(String* input,
7124 ReadBlockBuffer* buffer,
7126 unsigned max_chars);
7127 static void ReadBlockIntoBuffer(String* input,
7128 ReadBlockBuffer* buffer,
7129 unsigned* offset_ptr,
7130 unsigned max_chars);
7133 // Try to flatten the top level ConsString that is hiding behind this
7134 // string. This is a no-op unless the string is a ConsString. Flatten
7135 // mutates the ConsString and might return a failure.
7136 MUST_USE_RESULT MaybeObject* SlowTryFlatten(PretenureFlag pretenure);
7138 static inline bool IsHashFieldComputed(uint32_t field);
7140 // Slow case of String::Equals. This implementation works on any strings
7141 // but it is most efficient on strings that are almost flat.
7142 bool SlowEquals(String* other);
7144 // Slow case of AsArrayIndex.
7145 bool SlowAsArrayIndex(uint32_t* index);
7147 // Compute and set the hash code.
7148 uint32_t ComputeAndSetHash();
7150 DISALLOW_IMPLICIT_CONSTRUCTORS(String);
7154 // The SeqString abstract class captures sequential string values.
7155 class SeqString: public String {
7158 static inline SeqString* cast(Object* obj);
7160 // Get and set the symbol id of the string
7161 inline int symbol_id();
7162 inline void set_symbol_id(int value);
7164 // Layout description.
7165 static const int kSymbolIdOffset = String::kSize;
7166 static const int kHeaderSize = kSymbolIdOffset + kPointerSize;
7169 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqString);
7173 // The AsciiString class captures sequential ASCII string objects.
7174 // Each character in the AsciiString is an ASCII character.
7175 class SeqAsciiString: public SeqString {
7177 static const bool kHasAsciiEncoding = true;
7179 // Dispatched behavior.
7180 inline uint16_t SeqAsciiStringGet(int index);
7181 inline void SeqAsciiStringSet(int index, uint16_t value);
7183 // Get the address of the characters in this string.
7184 inline Address GetCharsAddress();
7186 inline char* GetChars();
7189 static inline SeqAsciiString* cast(Object* obj);
7191 // Garbage collection support. This method is called by the
7192 // garbage collector to compute the actual size of an AsciiString
7194 inline int SeqAsciiStringSize(InstanceType instance_type);
7196 // Computes the size for an AsciiString instance of a given length.
7197 static int SizeFor(int length) {
7198 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kCharSize);
7201 // Maximal memory usage for a single sequential ASCII string.
7202 static const int kMaxSize = 512 * MB - 1;
7203 // Maximal length of a single sequential ASCII string.
7204 // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
7205 static const int kMaxLength = (kMaxSize - kHeaderSize);
7207 // Support for StringInputBuffer.
7208 inline void SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7211 inline const unibrow::byte* SeqAsciiStringReadBlock(unsigned* remaining,
7216 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqAsciiString);
7220 // The TwoByteString class captures sequential unicode string objects.
7221 // Each character in the TwoByteString is a two-byte uint16_t.
7222 class SeqTwoByteString: public SeqString {
7224 static const bool kHasAsciiEncoding = false;
7226 // Dispatched behavior.
7227 inline uint16_t SeqTwoByteStringGet(int index);
7228 inline void SeqTwoByteStringSet(int index, uint16_t value);
7230 // Get the address of the characters in this string.
7231 inline Address GetCharsAddress();
7233 inline uc16* GetChars();
7236 const uint16_t* SeqTwoByteStringGetData(unsigned start);
7239 static inline SeqTwoByteString* cast(Object* obj);
7241 // Garbage collection support. This method is called by the
7242 // garbage collector to compute the actual size of a TwoByteString
7244 inline int SeqTwoByteStringSize(InstanceType instance_type);
7246 // Computes the size for a TwoByteString instance of a given length.
7247 static int SizeFor(int length) {
7248 return OBJECT_POINTER_ALIGN(kHeaderSize + length * kShortSize);
7251 // Maximal memory usage for a single sequential two-byte string.
7252 static const int kMaxSize = 512 * MB - 1;
7253 // Maximal length of a single sequential two-byte string.
7254 // Q.v. String::kMaxLength which is the maximal size of concatenated strings.
7255 static const int kMaxLength = (kMaxSize - kHeaderSize) / sizeof(uint16_t);
7257 // Support for StringInputBuffer.
7258 inline void SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7259 unsigned* offset_ptr,
7263 DISALLOW_IMPLICIT_CONSTRUCTORS(SeqTwoByteString);
7267 // The ConsString class describes string values built by using the
7268 // addition operator on strings. A ConsString is a pair where the
7269 // first and second components are pointers to other string values.
7270 // One or both components of a ConsString can be pointers to other
7271 // ConsStrings, creating a binary tree of ConsStrings where the leaves
7272 // are non-ConsString string values. The string value represented by
7273 // a ConsString can be obtained by concatenating the leaf string
7274 // values in a left-to-right depth-first traversal of the tree.
7275 class ConsString: public String {
7277 // First string of the cons cell.
7278 inline String* first();
7279 // Doesn't check that the result is a string, even in debug mode. This is
7280 // useful during GC where the mark bits confuse the checks.
7281 inline Object* unchecked_first();
7282 inline void set_first(String* first,
7283 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
7285 // Second string of the cons cell.
7286 inline String* second();
7287 // Doesn't check that the result is a string, even in debug mode. This is
7288 // useful during GC where the mark bits confuse the checks.
7289 inline Object* unchecked_second();
7290 inline void set_second(String* second,
7291 WriteBarrierMode mode = UPDATE_WRITE_BARRIER);
7293 // Dispatched behavior.
7294 uint16_t ConsStringGet(int index);
7297 static inline ConsString* cast(Object* obj);
7299 // Layout description.
7300 static const int kFirstOffset = POINTER_SIZE_ALIGN(String::kSize);
7301 static const int kSecondOffset = kFirstOffset + kPointerSize;
7302 static const int kSize = kSecondOffset + kPointerSize;
7304 // Support for StringInputBuffer.
7305 inline const unibrow::byte* ConsStringReadBlock(ReadBlockBuffer* buffer,
7306 unsigned* offset_ptr,
7308 inline void ConsStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7309 unsigned* offset_ptr,
7312 // Minimum length for a cons string.
7313 static const int kMinLength = 13;
7315 typedef FixedBodyDescriptor<kFirstOffset, kSecondOffset + kPointerSize, kSize>
7319 void ConsStringVerify();
7323 DISALLOW_IMPLICIT_CONSTRUCTORS(ConsString);
7327 // The Sliced String class describes strings that are substrings of another
7328 // sequential string. The motivation is to save time and memory when creating
7329 // a substring. A Sliced String is described as a pointer to the parent,
7330 // the offset from the start of the parent string and the length. Using
7331 // a Sliced String therefore requires unpacking of the parent string and
7332 // adding the offset to the start address. A substring of a Sliced String
7333 // are not nested since the double indirection is simplified when creating
7334 // such a substring.
7335 // Currently missing features are:
7336 // - handling externalized parent strings
7337 // - external strings as parent
7338 // - truncating sliced string to enable otherwise unneeded parent to be GC'ed.
7339 class SlicedString: public String {
7341 inline String* parent();
7342 inline void set_parent(String* parent);
7343 inline int offset();
7344 inline void set_offset(int offset);
7346 // Dispatched behavior.
7347 uint16_t SlicedStringGet(int index);
7350 static inline SlicedString* cast(Object* obj);
7352 // Layout description.
7353 static const int kParentOffset = POINTER_SIZE_ALIGN(String::kSize);
7354 static const int kOffsetOffset = kParentOffset + kPointerSize;
7355 static const int kSize = kOffsetOffset + kPointerSize;
7357 // Support for StringInputBuffer
7358 inline const unibrow::byte* SlicedStringReadBlock(ReadBlockBuffer* buffer,
7359 unsigned* offset_ptr,
7361 inline void SlicedStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7362 unsigned* offset_ptr,
7364 // Minimum length for a sliced string.
7365 static const int kMinLength = 13;
7367 typedef FixedBodyDescriptor<kParentOffset,
7368 kOffsetOffset + kPointerSize, kSize>
7372 void SlicedStringVerify();
7376 DISALLOW_IMPLICIT_CONSTRUCTORS(SlicedString);
7380 // The ExternalString class describes string values that are backed by
7381 // a string resource that lies outside the V8 heap. ExternalStrings
7382 // consist of the length field common to all strings, a pointer to the
7383 // external resource. It is important to ensure (externally) that the
7384 // resource is not deallocated while the ExternalString is live in the
7387 // The API expects that all ExternalStrings are created through the
7388 // API. Therefore, ExternalStrings should not be used internally.
7389 class ExternalString: public String {
7392 static inline ExternalString* cast(Object* obj);
7394 // Layout description.
7395 static const int kResourceOffset = POINTER_SIZE_ALIGN(String::kSize);
7396 static const int kShortSize = kResourceOffset + kPointerSize;
7397 static const int kResourceDataOffset = kResourceOffset + kPointerSize;
7398 static const int kSize = kResourceDataOffset + kPointerSize;
7400 // Return whether external string is short (data pointer is not cached).
7401 inline bool is_short();
7403 STATIC_CHECK(kResourceOffset == Internals::kStringResourceOffset);
7406 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalString);
7410 // The ExternalAsciiString class is an external string backed by an
7412 class ExternalAsciiString: public ExternalString {
7414 static const bool kHasAsciiEncoding = true;
7416 typedef v8::String::ExternalAsciiStringResource Resource;
7418 // The underlying resource.
7419 inline const Resource* resource();
7420 inline void set_resource(const Resource* buffer);
7422 // Update the pointer cache to the external character array.
7423 // The cached pointer is always valid, as the external character array does =
7424 // not move during lifetime. Deserialization is the only exception, after
7425 // which the pointer cache has to be refreshed.
7426 inline void update_data_cache();
7428 inline const char* GetChars();
7430 // Dispatched behavior.
7431 inline uint16_t ExternalAsciiStringGet(int index);
7434 static inline ExternalAsciiString* cast(Object* obj);
7436 // Garbage collection support.
7437 inline void ExternalAsciiStringIterateBody(ObjectVisitor* v);
7439 template<typename StaticVisitor>
7440 inline void ExternalAsciiStringIterateBody();
7442 // Support for StringInputBuffer.
7443 const unibrow::byte* ExternalAsciiStringReadBlock(unsigned* remaining,
7446 inline void ExternalAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7451 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalAsciiString);
7455 // The ExternalTwoByteString class is an external string backed by a UTF-16
7457 class ExternalTwoByteString: public ExternalString {
7459 static const bool kHasAsciiEncoding = false;
7461 typedef v8::String::ExternalStringResource Resource;
7463 // The underlying string resource.
7464 inline const Resource* resource();
7465 inline void set_resource(const Resource* buffer);
7467 // Update the pointer cache to the external character array.
7468 // The cached pointer is always valid, as the external character array does =
7469 // not move during lifetime. Deserialization is the only exception, after
7470 // which the pointer cache has to be refreshed.
7471 inline void update_data_cache();
7473 inline const uint16_t* GetChars();
7475 // Dispatched behavior.
7476 inline uint16_t ExternalTwoByteStringGet(int index);
7479 inline const uint16_t* ExternalTwoByteStringGetData(unsigned start);
7482 static inline ExternalTwoByteString* cast(Object* obj);
7484 // Garbage collection support.
7485 inline void ExternalTwoByteStringIterateBody(ObjectVisitor* v);
7487 template<typename StaticVisitor>
7488 inline void ExternalTwoByteStringIterateBody();
7491 // Support for StringInputBuffer.
7492 void ExternalTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* buffer,
7493 unsigned* offset_ptr,
7497 DISALLOW_IMPLICIT_CONSTRUCTORS(ExternalTwoByteString);
7501 // Utility superclass for stack-allocated objects that must be updated
7502 // on gc. It provides two ways for the gc to update instances, either
7503 // iterating or updating after gc.
7504 class Relocatable BASE_EMBEDDED {
7506 explicit inline Relocatable(Isolate* isolate);
7507 inline virtual ~Relocatable();
7508 virtual void IterateInstance(ObjectVisitor* v) { }
7509 virtual void PostGarbageCollection() { }
7511 static void PostGarbageCollectionProcessing();
7512 static int ArchiveSpacePerThread();
7513 static char* ArchiveState(Isolate* isolate, char* to);
7514 static char* RestoreState(Isolate* isolate, char* from);
7515 static void Iterate(ObjectVisitor* v);
7516 static void Iterate(ObjectVisitor* v, Relocatable* top);
7517 static char* Iterate(ObjectVisitor* v, char* t);
7524 // A flat string reader provides random access to the contents of a
7525 // string independent of the character width of the string. The handle
7526 // must be valid as long as the reader is being used.
7527 class FlatStringReader : public Relocatable {
7529 FlatStringReader(Isolate* isolate, Handle<String> str);
7530 FlatStringReader(Isolate* isolate, Vector<const char> input);
7531 void PostGarbageCollection();
7532 inline uc32 Get(int index);
7533 int length() { return length_; }
7542 // Note that StringInputBuffers are not valid across a GC! To fix this
7543 // it would have to store a String Handle instead of a String* and
7544 // AsciiStringReadBlock would have to be modified to use memcpy.
7546 // StringInputBuffer is able to traverse any string regardless of how
7547 // deeply nested a sequence of ConsStrings it is made of. However,
7548 // performance will be better if deep strings are flattened before they
7549 // are traversed. Since flattening requires memory allocation this is
7550 // not always desirable, however (esp. in debugging situations).
7551 class StringInputBuffer: public unibrow::InputBuffer<String, String*, 1024> {
7553 virtual void Seek(unsigned pos);
7554 inline StringInputBuffer(): unibrow::InputBuffer<String, String*, 1024>() {}
7555 explicit inline StringInputBuffer(String* backing):
7556 unibrow::InputBuffer<String, String*, 1024>(backing) {}
7560 class SafeStringInputBuffer
7561 : public unibrow::InputBuffer<String, String**, 256> {
7563 virtual void Seek(unsigned pos);
7564 inline SafeStringInputBuffer()
7565 : unibrow::InputBuffer<String, String**, 256>() {}
7566 explicit inline SafeStringInputBuffer(String** backing)
7567 : unibrow::InputBuffer<String, String**, 256>(backing) {}
7571 template <typename T>
7572 class VectorIterator {
7574 VectorIterator(T* d, int l) : data_(Vector<const T>(d, l)), index_(0) { }
7575 explicit VectorIterator(Vector<const T> data) : data_(data), index_(0) { }
7576 T GetNext() { return data_[index_++]; }
7577 bool has_more() { return index_ < data_.length(); }
7579 Vector<const T> data_;
7584 // The Oddball describes objects null, undefined, true, and false.
7585 class Oddball: public HeapObject {
7587 // [to_string]: Cached to_string computed at startup.
7588 DECL_ACCESSORS(to_string, String)
7590 // [to_number]: Cached to_number computed at startup.
7591 DECL_ACCESSORS(to_number, Object)
7594 inline void set_kind(byte kind);
7597 static inline Oddball* cast(Object* obj);
7599 // Dispatched behavior.
7601 void OddballVerify();
7604 // Initialize the fields.
7605 MUST_USE_RESULT MaybeObject* Initialize(const char* to_string,
7609 // Layout description.
7610 static const int kToStringOffset = HeapObject::kHeaderSize;
7611 static const int kToNumberOffset = kToStringOffset + kPointerSize;
7612 static const int kKindOffset = kToNumberOffset + kPointerSize;
7613 static const int kSize = kKindOffset + kPointerSize;
7615 static const byte kFalse = 0;
7616 static const byte kTrue = 1;
7617 static const byte kNotBooleanMask = ~1;
7618 static const byte kTheHole = 2;
7619 static const byte kNull = 3;
7620 static const byte kArgumentMarker = 4;
7621 static const byte kUndefined = 5;
7622 static const byte kOther = 6;
7624 typedef FixedBodyDescriptor<kToStringOffset,
7625 kToNumberOffset + kPointerSize,
7626 kSize> BodyDescriptor;
7629 DISALLOW_IMPLICIT_CONSTRUCTORS(Oddball);
7633 class JSGlobalPropertyCell: public HeapObject {
7635 // [value]: value of the global property.
7636 DECL_ACCESSORS(value, Object)
7639 static inline JSGlobalPropertyCell* cast(Object* obj);
7642 void JSGlobalPropertyCellVerify();
7645 inline void JSGlobalPropertyCellPrint() {
7646 JSGlobalPropertyCellPrint(stdout);
7648 void JSGlobalPropertyCellPrint(FILE* out);
7651 // Layout description.
7652 static const int kValueOffset = HeapObject::kHeaderSize;
7653 static const int kSize = kValueOffset + kPointerSize;
7655 typedef FixedBodyDescriptor<kValueOffset,
7656 kValueOffset + kPointerSize,
7657 kSize> BodyDescriptor;
7660 DISALLOW_IMPLICIT_CONSTRUCTORS(JSGlobalPropertyCell);
7664 // The JSProxy describes EcmaScript Harmony proxies
7665 class JSProxy: public JSReceiver {
7667 // [handler]: The handler property.
7668 DECL_ACCESSORS(handler, Object)
7670 // [hash]: The hash code property (undefined if not initialized yet).
7671 DECL_ACCESSORS(hash, Object)
7674 static inline JSProxy* cast(Object* obj);
7676 bool HasPropertyWithHandler(String* name);
7677 bool HasElementWithHandler(uint32_t index);
7679 MUST_USE_RESULT MaybeObject* GetPropertyWithHandler(
7682 MUST_USE_RESULT MaybeObject* GetElementWithHandler(
7686 MUST_USE_RESULT MaybeObject* SetPropertyWithHandler(
7689 PropertyAttributes attributes,
7690 StrictModeFlag strict_mode);
7691 MUST_USE_RESULT MaybeObject* SetElementWithHandler(
7694 StrictModeFlag strict_mode);
7696 // If the handler defines an accessor property, invoke its setter
7697 // (or throw if only a getter exists) and set *found to true. Otherwise false.
7698 MUST_USE_RESULT MaybeObject* SetPropertyWithHandlerIfDefiningSetter(
7701 PropertyAttributes attributes,
7702 StrictModeFlag strict_mode,
7705 MUST_USE_RESULT MaybeObject* DeletePropertyWithHandler(
7708 MUST_USE_RESULT MaybeObject* DeleteElementWithHandler(
7712 MUST_USE_RESULT PropertyAttributes GetPropertyAttributeWithHandler(
7713 JSReceiver* receiver,
7715 MUST_USE_RESULT PropertyAttributes GetElementAttributeWithHandler(
7716 JSReceiver* receiver,
7719 MUST_USE_RESULT MaybeObject* GetIdentityHash(CreationFlag flag);
7721 // Turn this into an (empty) JSObject.
7724 // Initializes the body after the handler slot.
7725 inline void InitializeBody(int object_size, Object* value);
7727 // Invoke a trap by name. If the trap does not exist on this's handler,
7728 // but derived_trap is non-NULL, invoke that instead. May cause GC.
7729 Handle<Object> CallTrap(const char* name,
7730 Handle<Object> derived_trap,
7732 Handle<Object> args[]);
7734 // Dispatched behavior.
7736 inline void JSProxyPrint() {
7737 JSProxyPrint(stdout);
7739 void JSProxyPrint(FILE* out);
7742 void JSProxyVerify();
7745 // Layout description. We add padding so that a proxy has the same
7746 // size as a virgin JSObject. This is essential for becoming a JSObject
7748 static const int kHandlerOffset = HeapObject::kHeaderSize;
7749 static const int kHashOffset = kHandlerOffset + kPointerSize;
7750 static const int kPaddingOffset = kHashOffset + kPointerSize;
7751 static const int kSize = JSObject::kHeaderSize;
7752 static const int kHeaderSize = kPaddingOffset;
7753 static const int kPaddingSize = kSize - kPaddingOffset;
7755 STATIC_CHECK(kPaddingSize >= 0);
7757 typedef FixedBodyDescriptor<kHandlerOffset,
7759 kSize> BodyDescriptor;
7762 DISALLOW_IMPLICIT_CONSTRUCTORS(JSProxy);
7766 class JSFunctionProxy: public JSProxy {
7768 // [call_trap]: The call trap.
7769 DECL_ACCESSORS(call_trap, Object)
7771 // [construct_trap]: The construct trap.
7772 DECL_ACCESSORS(construct_trap, Object)
7775 static inline JSFunctionProxy* cast(Object* obj);
7777 // Dispatched behavior.
7779 inline void JSFunctionProxyPrint() {
7780 JSFunctionProxyPrint(stdout);
7782 void JSFunctionProxyPrint(FILE* out);
7785 void JSFunctionProxyVerify();
7788 // Layout description.
7789 static const int kCallTrapOffset = JSProxy::kPaddingOffset;
7790 static const int kConstructTrapOffset = kCallTrapOffset + kPointerSize;
7791 static const int kPaddingOffset = kConstructTrapOffset + kPointerSize;
7792 static const int kSize = JSFunction::kSize;
7793 static const int kPaddingSize = kSize - kPaddingOffset;
7795 STATIC_CHECK(kPaddingSize >= 0);
7797 typedef FixedBodyDescriptor<kHandlerOffset,
7798 kConstructTrapOffset + kPointerSize,
7799 kSize> BodyDescriptor;
7802 DISALLOW_IMPLICIT_CONSTRUCTORS(JSFunctionProxy);
7806 // The JSSet describes EcmaScript Harmony sets
7807 class JSSet: public JSObject {
7809 // [set]: the backing hash set containing keys.
7810 DECL_ACCESSORS(table, Object)
7813 static inline JSSet* cast(Object* obj);
7816 inline void JSSetPrint() {
7819 void JSSetPrint(FILE* out);
7825 static const int kTableOffset = JSObject::kHeaderSize;
7826 static const int kSize = kTableOffset + kPointerSize;
7829 DISALLOW_IMPLICIT_CONSTRUCTORS(JSSet);
7833 // The JSMap describes EcmaScript Harmony maps
7834 class JSMap: public JSObject {
7836 // [table]: the backing hash table mapping keys to values.
7837 DECL_ACCESSORS(table, Object)
7840 static inline JSMap* cast(Object* obj);
7843 inline void JSMapPrint() {
7846 void JSMapPrint(FILE* out);
7852 static const int kTableOffset = JSObject::kHeaderSize;
7853 static const int kSize = kTableOffset + kPointerSize;
7856 DISALLOW_IMPLICIT_CONSTRUCTORS(JSMap);
7860 // The JSWeakMap describes EcmaScript Harmony weak maps
7861 class JSWeakMap: public JSObject {
7863 // [table]: the backing hash table mapping keys to values.
7864 DECL_ACCESSORS(table, Object)
7866 // [next]: linked list of encountered weak maps during GC.
7867 DECL_ACCESSORS(next, Object)
7870 static inline JSWeakMap* cast(Object* obj);
7873 inline void JSWeakMapPrint() {
7874 JSWeakMapPrint(stdout);
7876 void JSWeakMapPrint(FILE* out);
7879 void JSWeakMapVerify();
7882 static const int kTableOffset = JSObject::kHeaderSize;
7883 static const int kNextOffset = kTableOffset + kPointerSize;
7884 static const int kSize = kNextOffset + kPointerSize;
7887 DISALLOW_IMPLICIT_CONSTRUCTORS(JSWeakMap);
7891 // Foreign describes objects pointing from JavaScript to C structures.
7892 // Since they cannot contain references to JS HeapObjects they can be
7893 // placed in old_data_space.
7894 class Foreign: public HeapObject {
7896 // [address]: field containing the address.
7897 inline Address foreign_address();
7898 inline void set_foreign_address(Address value);
7901 static inline Foreign* cast(Object* obj);
7903 // Dispatched behavior.
7904 inline void ForeignIterateBody(ObjectVisitor* v);
7906 template<typename StaticVisitor>
7907 inline void ForeignIterateBody();
7910 inline void ForeignPrint() {
7911 ForeignPrint(stdout);
7913 void ForeignPrint(FILE* out);
7916 void ForeignVerify();
7919 // Layout description.
7921 static const int kForeignAddressOffset = HeapObject::kHeaderSize;
7922 static const int kSize = kForeignAddressOffset + kPointerSize;
7924 STATIC_CHECK(kForeignAddressOffset == Internals::kForeignAddressOffset);
7927 DISALLOW_IMPLICIT_CONSTRUCTORS(Foreign);
7931 // The JSArray describes JavaScript Arrays
7932 // Such an array can be in one of two modes:
7933 // - fast, backing storage is a FixedArray and length <= elements.length();
7934 // Please note: push and pop can be used to grow and shrink the array.
7935 // - slow, backing storage is a HashTable with numbers as keys.
7936 class JSArray: public JSObject {
7938 // [length]: The length property.
7939 DECL_ACCESSORS(length, Object)
7941 // Overload the length setter to skip write barrier when the length
7942 // is set to a smi. This matches the set function on FixedArray.
7943 inline void set_length(Smi* length);
7945 MUST_USE_RESULT MaybeObject* JSArrayUpdateLengthFromIndex(uint32_t index,
7948 // Initialize the array with the given capacity. The function may
7949 // fail due to out-of-memory situations, but only if the requested
7950 // capacity is non-zero.
7951 MUST_USE_RESULT MaybeObject* Initialize(int capacity);
7953 // Initializes the array to a certain length.
7954 inline bool AllowsSetElementsLength();
7955 MUST_USE_RESULT MaybeObject* SetElementsLength(Object* length);
7957 // Set the content of the array to the content of storage.
7958 MUST_USE_RESULT inline MaybeObject* SetContent(FixedArrayBase* storage);
7961 static inline JSArray* cast(Object* obj);
7963 // Uses handles. Ensures that the fixed array backing the JSArray has at
7964 // least the stated size.
7965 inline void EnsureSize(int minimum_size_of_backing_fixed_array);
7967 // Dispatched behavior.
7969 inline void JSArrayPrint() {
7970 JSArrayPrint(stdout);
7972 void JSArrayPrint(FILE* out);
7975 void JSArrayVerify();
7978 // Number of element slots to pre-allocate for an empty array.
7979 static const int kPreallocatedArrayElements = 4;
7981 // Layout description.
7982 static const int kLengthOffset = JSObject::kHeaderSize;
7983 static const int kSize = kLengthOffset + kPointerSize;
7986 // Expand the fixed array backing of a fast-case JSArray to at least
7987 // the requested size.
7988 void Expand(int minimum_size_of_backing_fixed_array);
7990 DISALLOW_IMPLICIT_CONSTRUCTORS(JSArray);
7994 // JSRegExpResult is just a JSArray with a specific initial map.
7995 // This initial map adds in-object properties for "index" and "input"
7996 // properties, as assigned by RegExp.prototype.exec, which allows
7997 // faster creation of RegExp exec results.
7998 // This class just holds constants used when creating the result.
7999 // After creation the result must be treated as a JSArray in all regards.
8000 class JSRegExpResult: public JSArray {
8002 // Offsets of object fields.
8003 static const int kIndexOffset = JSArray::kSize;
8004 static const int kInputOffset = kIndexOffset + kPointerSize;
8005 static const int kSize = kInputOffset + kPointerSize;
8006 // Indices of in-object properties.
8007 static const int kIndexIndex = 0;
8008 static const int kInputIndex = 1;
8010 DISALLOW_IMPLICIT_CONSTRUCTORS(JSRegExpResult);
8014 // An accessor must have a getter, but can have no setter.
8016 // When setting a property, V8 searches accessors in prototypes.
8017 // If an accessor was found and it does not have a setter,
8018 // the request is ignored.
8020 // If the accessor in the prototype has the READ_ONLY property attribute, then
8021 // a new value is added to the local object when the property is set.
8022 // This shadows the accessor in the prototype.
8023 class AccessorInfo: public Struct {
8025 DECL_ACCESSORS(getter, Object)
8026 DECL_ACCESSORS(setter, Object)
8027 DECL_ACCESSORS(data, Object)
8028 DECL_ACCESSORS(name, Object)
8029 DECL_ACCESSORS(flag, Smi)
8031 inline bool all_can_read();
8032 inline void set_all_can_read(bool value);
8034 inline bool all_can_write();
8035 inline void set_all_can_write(bool value);
8037 inline bool prohibits_overwriting();
8038 inline void set_prohibits_overwriting(bool value);
8040 inline PropertyAttributes property_attributes();
8041 inline void set_property_attributes(PropertyAttributes attributes);
8043 static inline AccessorInfo* cast(Object* obj);
8046 inline void AccessorInfoPrint() {
8047 AccessorInfoPrint(stdout);
8049 void AccessorInfoPrint(FILE* out);
8052 void AccessorInfoVerify();
8055 static const int kGetterOffset = HeapObject::kHeaderSize;
8056 static const int kSetterOffset = kGetterOffset + kPointerSize;
8057 static const int kDataOffset = kSetterOffset + kPointerSize;
8058 static const int kNameOffset = kDataOffset + kPointerSize;
8059 static const int kFlagOffset = kNameOffset + kPointerSize;
8060 static const int kSize = kFlagOffset + kPointerSize;
8063 // Bit positions in flag.
8064 static const int kAllCanReadBit = 0;
8065 static const int kAllCanWriteBit = 1;
8066 static const int kProhibitsOverwritingBit = 2;
8067 class AttributesField: public BitField<PropertyAttributes, 3, 3> {};
8069 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorInfo);
8073 // Support for JavaScript accessors: A pair of a getter and a setter. Each
8074 // accessor can either be
8075 // * a pointer to a JavaScript function or proxy: a real accessor
8076 // * undefined: considered an accessor by the spec, too, strangely enough
8077 // * the hole: an accessor which has not been set
8078 // * a pointer to a map: a transition used to ensure map sharing
8079 class AccessorPair: public Struct {
8081 DECL_ACCESSORS(getter, Object)
8082 DECL_ACCESSORS(setter, Object)
8084 static inline AccessorPair* cast(Object* obj);
8086 MUST_USE_RESULT MaybeObject* CopyWithoutTransitions();
8088 // Note: Returns undefined instead in case of a hole.
8089 Object* GetComponent(AccessorComponent component);
8091 // Set both components, skipping arguments which are a JavaScript null.
8092 void SetComponents(Object* getter, Object* setter) {
8093 if (!getter->IsNull()) set_getter(getter);
8094 if (!setter->IsNull()) set_setter(setter);
8097 bool ContainsAccessor() {
8098 return IsJSAccessor(getter()) || IsJSAccessor(setter());
8102 void AccessorPairPrint(FILE* out = stdout);
8105 void AccessorPairVerify();
8108 static const int kGetterOffset = HeapObject::kHeaderSize;
8109 static const int kSetterOffset = kGetterOffset + kPointerSize;
8110 static const int kSize = kSetterOffset + kPointerSize;
8113 // Strangely enough, in addition to functions and harmony proxies, the spec
8114 // requires us to consider undefined as a kind of accessor, too:
8116 // Object.defineProperty(obj, "foo", {get: undefined});
8117 // assertTrue("foo" in obj);
8118 bool IsJSAccessor(Object* obj) {
8119 return obj->IsSpecFunction() || obj->IsUndefined();
8122 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessorPair);
8126 class AccessCheckInfo: public Struct {
8128 DECL_ACCESSORS(named_callback, Object)
8129 DECL_ACCESSORS(indexed_callback, Object)
8130 DECL_ACCESSORS(data, Object)
8132 static inline AccessCheckInfo* cast(Object* obj);
8135 inline void AccessCheckInfoPrint() {
8136 AccessCheckInfoPrint(stdout);
8138 void AccessCheckInfoPrint(FILE* out);
8141 void AccessCheckInfoVerify();
8144 static const int kNamedCallbackOffset = HeapObject::kHeaderSize;
8145 static const int kIndexedCallbackOffset = kNamedCallbackOffset + kPointerSize;
8146 static const int kDataOffset = kIndexedCallbackOffset + kPointerSize;
8147 static const int kSize = kDataOffset + kPointerSize;
8150 DISALLOW_IMPLICIT_CONSTRUCTORS(AccessCheckInfo);
8154 class InterceptorInfo: public Struct {
8156 DECL_ACCESSORS(getter, Object)
8157 DECL_ACCESSORS(setter, Object)
8158 DECL_ACCESSORS(query, Object)
8159 DECL_ACCESSORS(deleter, Object)
8160 DECL_ACCESSORS(enumerator, Object)
8161 DECL_ACCESSORS(data, Object)
8162 DECL_ACCESSORS(is_fallback, Smi)
8164 static inline InterceptorInfo* cast(Object* obj);
8167 inline void InterceptorInfoPrint() {
8168 InterceptorInfoPrint(stdout);
8170 void InterceptorInfoPrint(FILE* out);
8173 void InterceptorInfoVerify();
8176 static const int kGetterOffset = HeapObject::kHeaderSize;
8177 static const int kSetterOffset = kGetterOffset + kPointerSize;
8178 static const int kQueryOffset = kSetterOffset + kPointerSize;
8179 static const int kDeleterOffset = kQueryOffset + kPointerSize;
8180 static const int kEnumeratorOffset = kDeleterOffset + kPointerSize;
8181 static const int kDataOffset = kEnumeratorOffset + kPointerSize;
8182 static const int kFallbackOffset = kDataOffset + kPointerSize;
8183 static const int kSize = kFallbackOffset + kPointerSize;
8186 DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptorInfo);
8190 class CallHandlerInfo: public Struct {
8192 DECL_ACCESSORS(callback, Object)
8193 DECL_ACCESSORS(data, Object)
8195 static inline CallHandlerInfo* cast(Object* obj);
8198 inline void CallHandlerInfoPrint() {
8199 CallHandlerInfoPrint(stdout);
8201 void CallHandlerInfoPrint(FILE* out);
8204 void CallHandlerInfoVerify();
8207 static const int kCallbackOffset = HeapObject::kHeaderSize;
8208 static const int kDataOffset = kCallbackOffset + kPointerSize;
8209 static const int kSize = kDataOffset + kPointerSize;
8212 DISALLOW_IMPLICIT_CONSTRUCTORS(CallHandlerInfo);
8216 class TemplateInfo: public Struct {
8218 DECL_ACCESSORS(tag, Object)
8219 DECL_ACCESSORS(property_list, Object)
8222 void TemplateInfoVerify();
8225 static const int kTagOffset = HeapObject::kHeaderSize;
8226 static const int kPropertyListOffset = kTagOffset + kPointerSize;
8227 static const int kHeaderSize = kPropertyListOffset + kPointerSize;
8230 DISALLOW_IMPLICIT_CONSTRUCTORS(TemplateInfo);
8234 class FunctionTemplateInfo: public TemplateInfo {
8236 DECL_ACCESSORS(serial_number, Object)
8237 DECL_ACCESSORS(call_code, Object)
8238 DECL_ACCESSORS(property_accessors, Object)
8239 DECL_ACCESSORS(prototype_template, Object)
8240 DECL_ACCESSORS(parent_template, Object)
8241 DECL_ACCESSORS(named_property_handler, Object)
8242 DECL_ACCESSORS(indexed_property_handler, Object)
8243 DECL_ACCESSORS(instance_template, Object)
8244 DECL_ACCESSORS(class_name, Object)
8245 DECL_ACCESSORS(signature, Object)
8246 DECL_ACCESSORS(instance_call_handler, Object)
8247 DECL_ACCESSORS(access_check_info, Object)
8248 DECL_ACCESSORS(flag, Smi)
8250 // Following properties use flag bits.
8251 DECL_BOOLEAN_ACCESSORS(hidden_prototype)
8252 DECL_BOOLEAN_ACCESSORS(undetectable)
8253 // If the bit is set, object instances created by this function
8254 // requires access check.
8255 DECL_BOOLEAN_ACCESSORS(needs_access_check)
8256 DECL_BOOLEAN_ACCESSORS(read_only_prototype)
8258 static inline FunctionTemplateInfo* cast(Object* obj);
8261 inline void FunctionTemplateInfoPrint() {
8262 FunctionTemplateInfoPrint(stdout);
8264 void FunctionTemplateInfoPrint(FILE* out);
8267 void FunctionTemplateInfoVerify();
8270 static const int kSerialNumberOffset = TemplateInfo::kHeaderSize;
8271 static const int kCallCodeOffset = kSerialNumberOffset + kPointerSize;
8272 static const int kPropertyAccessorsOffset = kCallCodeOffset + kPointerSize;
8273 static const int kPrototypeTemplateOffset =
8274 kPropertyAccessorsOffset + kPointerSize;
8275 static const int kParentTemplateOffset =
8276 kPrototypeTemplateOffset + kPointerSize;
8277 static const int kNamedPropertyHandlerOffset =
8278 kParentTemplateOffset + kPointerSize;
8279 static const int kIndexedPropertyHandlerOffset =
8280 kNamedPropertyHandlerOffset + kPointerSize;
8281 static const int kInstanceTemplateOffset =
8282 kIndexedPropertyHandlerOffset + kPointerSize;
8283 static const int kClassNameOffset = kInstanceTemplateOffset + kPointerSize;
8284 static const int kSignatureOffset = kClassNameOffset + kPointerSize;
8285 static const int kInstanceCallHandlerOffset = kSignatureOffset + kPointerSize;
8286 static const int kAccessCheckInfoOffset =
8287 kInstanceCallHandlerOffset + kPointerSize;
8288 static const int kFlagOffset = kAccessCheckInfoOffset + kPointerSize;
8289 static const int kSize = kFlagOffset + kPointerSize;
8292 // Bit position in the flag, from least significant bit position.
8293 static const int kHiddenPrototypeBit = 0;
8294 static const int kUndetectableBit = 1;
8295 static const int kNeedsAccessCheckBit = 2;
8296 static const int kReadOnlyPrototypeBit = 3;
8298 DISALLOW_IMPLICIT_CONSTRUCTORS(FunctionTemplateInfo);
8302 class ObjectTemplateInfo: public TemplateInfo {
8304 DECL_ACCESSORS(constructor, Object)
8305 DECL_ACCESSORS(internal_field_count, Object)
8307 static inline ObjectTemplateInfo* cast(Object* obj);
8310 inline void ObjectTemplateInfoPrint() {
8311 ObjectTemplateInfoPrint(stdout);
8313 void ObjectTemplateInfoPrint(FILE* out);
8316 void ObjectTemplateInfoVerify();
8319 static const int kConstructorOffset = TemplateInfo::kHeaderSize;
8320 static const int kInternalFieldCountOffset =
8321 kConstructorOffset + kPointerSize;
8322 static const int kSize = kInternalFieldCountOffset + kPointerSize;
8326 class SignatureInfo: public Struct {
8328 DECL_ACCESSORS(receiver, Object)
8329 DECL_ACCESSORS(args, Object)
8331 static inline SignatureInfo* cast(Object* obj);
8334 inline void SignatureInfoPrint() {
8335 SignatureInfoPrint(stdout);
8337 void SignatureInfoPrint(FILE* out);
8340 void SignatureInfoVerify();
8343 static const int kReceiverOffset = Struct::kHeaderSize;
8344 static const int kArgsOffset = kReceiverOffset + kPointerSize;
8345 static const int kSize = kArgsOffset + kPointerSize;
8348 DISALLOW_IMPLICIT_CONSTRUCTORS(SignatureInfo);
8352 class TypeSwitchInfo: public Struct {
8354 DECL_ACCESSORS(types, Object)
8356 static inline TypeSwitchInfo* cast(Object* obj);
8359 inline void TypeSwitchInfoPrint() {
8360 TypeSwitchInfoPrint(stdout);
8362 void TypeSwitchInfoPrint(FILE* out);
8365 void TypeSwitchInfoVerify();
8368 static const int kTypesOffset = Struct::kHeaderSize;
8369 static const int kSize = kTypesOffset + kPointerSize;
8373 #ifdef ENABLE_DEBUGGER_SUPPORT
8374 // The DebugInfo class holds additional information for a function being
8376 class DebugInfo: public Struct {
8378 // The shared function info for the source being debugged.
8379 DECL_ACCESSORS(shared, SharedFunctionInfo)
8380 // Code object for the original code.
8381 DECL_ACCESSORS(original_code, Code)
8382 // Code object for the patched code. This code object is the code object
8383 // currently active for the function.
8384 DECL_ACCESSORS(code, Code)
8385 // Fixed array holding status information for each active break point.
8386 DECL_ACCESSORS(break_points, FixedArray)
8388 // Check if there is a break point at a code position.
8389 bool HasBreakPoint(int code_position);
8390 // Get the break point info object for a code position.
8391 Object* GetBreakPointInfo(int code_position);
8392 // Clear a break point.
8393 static void ClearBreakPoint(Handle<DebugInfo> debug_info,
8395 Handle<Object> break_point_object);
8396 // Set a break point.
8397 static void SetBreakPoint(Handle<DebugInfo> debug_info, int code_position,
8398 int source_position, int statement_position,
8399 Handle<Object> break_point_object);
8400 // Get the break point objects for a code position.
8401 Object* GetBreakPointObjects(int code_position);
8402 // Find the break point info holding this break point object.
8403 static Object* FindBreakPointInfo(Handle<DebugInfo> debug_info,
8404 Handle<Object> break_point_object);
8405 // Get the number of break points for this function.
8406 int GetBreakPointCount();
8408 static inline DebugInfo* cast(Object* obj);
8411 inline void DebugInfoPrint() {
8412 DebugInfoPrint(stdout);
8414 void DebugInfoPrint(FILE* out);
8417 void DebugInfoVerify();
8420 static const int kSharedFunctionInfoIndex = Struct::kHeaderSize;
8421 static const int kOriginalCodeIndex = kSharedFunctionInfoIndex + kPointerSize;
8422 static const int kPatchedCodeIndex = kOriginalCodeIndex + kPointerSize;
8423 static const int kActiveBreakPointsCountIndex =
8424 kPatchedCodeIndex + kPointerSize;
8425 static const int kBreakPointsStateIndex =
8426 kActiveBreakPointsCountIndex + kPointerSize;
8427 static const int kSize = kBreakPointsStateIndex + kPointerSize;
8430 static const int kNoBreakPointInfo = -1;
8432 // Lookup the index in the break_points array for a code position.
8433 int GetBreakPointInfoIndex(int code_position);
8435 DISALLOW_IMPLICIT_CONSTRUCTORS(DebugInfo);
8439 // The BreakPointInfo class holds information for break points set in a
8440 // function. The DebugInfo object holds a BreakPointInfo object for each code
8441 // position with one or more break points.
8442 class BreakPointInfo: public Struct {
8444 // The position in the code for the break point.
8445 DECL_ACCESSORS(code_position, Smi)
8446 // The position in the source for the break position.
8447 DECL_ACCESSORS(source_position, Smi)
8448 // The position in the source for the last statement before this break
8450 DECL_ACCESSORS(statement_position, Smi)
8451 // List of related JavaScript break points.
8452 DECL_ACCESSORS(break_point_objects, Object)
8454 // Removes a break point.
8455 static void ClearBreakPoint(Handle<BreakPointInfo> info,
8456 Handle<Object> break_point_object);
8457 // Set a break point.
8458 static void SetBreakPoint(Handle<BreakPointInfo> info,
8459 Handle<Object> break_point_object);
8460 // Check if break point info has this break point object.
8461 static bool HasBreakPointObject(Handle<BreakPointInfo> info,
8462 Handle<Object> break_point_object);
8463 // Get the number of break points for this code position.
8464 int GetBreakPointCount();
8466 static inline BreakPointInfo* cast(Object* obj);
8469 inline void BreakPointInfoPrint() {
8470 BreakPointInfoPrint(stdout);
8472 void BreakPointInfoPrint(FILE* out);
8475 void BreakPointInfoVerify();
8478 static const int kCodePositionIndex = Struct::kHeaderSize;
8479 static const int kSourcePositionIndex = kCodePositionIndex + kPointerSize;
8480 static const int kStatementPositionIndex =
8481 kSourcePositionIndex + kPointerSize;
8482 static const int kBreakPointObjectsIndex =
8483 kStatementPositionIndex + kPointerSize;
8484 static const int kSize = kBreakPointObjectsIndex + kPointerSize;
8487 DISALLOW_IMPLICIT_CONSTRUCTORS(BreakPointInfo);
8489 #endif // ENABLE_DEBUGGER_SUPPORT
8492 #undef DECL_BOOLEAN_ACCESSORS
8493 #undef DECL_ACCESSORS
8495 #define VISITOR_SYNCHRONIZATION_TAGS_LIST(V) \
8496 V(kSymbolTable, "symbol_table", "(Symbols)") \
8497 V(kExternalStringsTable, "external_strings_table", "(External strings)") \
8498 V(kStrongRootList, "strong_root_list", "(Strong roots)") \
8499 V(kSymbol, "symbol", "(Symbol)") \
8500 V(kBootstrapper, "bootstrapper", "(Bootstrapper)") \
8501 V(kTop, "top", "(Isolate)") \
8502 V(kRelocatable, "relocatable", "(Relocatable)") \
8503 V(kDebug, "debug", "(Debugger)") \
8504 V(kCompilationCache, "compilationcache", "(Compilation cache)") \
8505 V(kHandleScope, "handlescope", "(Handle scope)") \
8506 V(kBuiltins, "builtins", "(Builtins)") \
8507 V(kGlobalHandles, "globalhandles", "(Global handles)") \
8508 V(kThreadManager, "threadmanager", "(Thread manager)") \
8509 V(kExtensions, "Extensions", "(Extensions)")
8511 class VisitorSynchronization : public AllStatic {
8513 #define DECLARE_ENUM(enum_item, ignore1, ignore2) enum_item,
8515 VISITOR_SYNCHRONIZATION_TAGS_LIST(DECLARE_ENUM)
8520 static const char* const kTags[kNumberOfSyncTags];
8521 static const char* const kTagNames[kNumberOfSyncTags];
8524 // Abstract base class for visiting, and optionally modifying, the
8525 // pointers contained in Objects. Used in GC and serialization/deserialization.
8526 class ObjectVisitor BASE_EMBEDDED {
8528 virtual ~ObjectVisitor() {}
8530 // Visits a contiguous arrays of pointers in the half-open range
8531 // [start, end). Any or all of the values may be modified on return.
8532 virtual void VisitPointers(Object** start, Object** end) = 0;
8534 // To allow lazy clearing of inline caches the visitor has
8535 // a rich interface for iterating over Code objects..
8537 // Visits a code target in the instruction stream.
8538 virtual void VisitCodeTarget(RelocInfo* rinfo);
8540 // Visits a code entry in a JS function.
8541 virtual void VisitCodeEntry(Address entry_address);
8543 // Visits a global property cell reference in the instruction stream.
8544 virtual void VisitGlobalPropertyCell(RelocInfo* rinfo);
8546 // Visits a runtime entry in the instruction stream.
8547 virtual void VisitRuntimeEntry(RelocInfo* rinfo) {}
8549 // Visits the resource of an ASCII or two-byte string.
8550 virtual void VisitExternalAsciiString(
8551 v8::String::ExternalAsciiStringResource** resource) {}
8552 virtual void VisitExternalTwoByteString(
8553 v8::String::ExternalStringResource** resource) {}
8555 // Visits a debug call target in the instruction stream.
8556 virtual void VisitDebugTarget(RelocInfo* rinfo);
8558 // Handy shorthand for visiting a single pointer.
8559 virtual void VisitPointer(Object** p) { VisitPointers(p, p + 1); }
8561 // Visit pointer embedded into a code object.
8562 virtual void VisitEmbeddedPointer(RelocInfo* rinfo);
8564 virtual void VisitSharedFunctionInfo(SharedFunctionInfo* shared) {}
8566 // Visits a contiguous arrays of external references (references to the C++
8567 // heap) in the half-open range [start, end). Any or all of the values
8568 // may be modified on return.
8569 virtual void VisitExternalReferences(Address* start, Address* end) {}
8571 virtual void VisitExternalReference(RelocInfo* rinfo);
8573 inline void VisitExternalReference(Address* p) {
8574 VisitExternalReferences(p, p + 1);
8577 // Visits a handle that has an embedder-assigned class ID.
8578 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {}
8580 // Intended for serialization/deserialization checking: insert, or
8581 // check for the presence of, a tag at this position in the stream.
8582 // Also used for marking up GC roots in heap snapshots.
8583 virtual void Synchronize(VisitorSynchronization::SyncTag tag) {}
8587 class StructBodyDescriptor : public
8588 FlexibleBodyDescriptor<HeapObject::kHeaderSize> {
8590 static inline int SizeOf(Map* map, HeapObject* object) {
8591 return map->instance_size();
8596 // BooleanBit is a helper class for setting and getting a bit in an
8598 class BooleanBit : public AllStatic {
8600 static inline bool get(Smi* smi, int bit_position) {
8601 return get(smi->value(), bit_position);
8604 static inline bool get(int value, int bit_position) {
8605 return (value & (1 << bit_position)) != 0;
8608 static inline Smi* set(Smi* smi, int bit_position, bool v) {
8609 return Smi::FromInt(set(smi->value(), bit_position, v));
8612 static inline int set(int value, int bit_position, bool v) {
8614 value |= (1 << bit_position);
8616 value &= ~(1 << bit_position);
8622 } } // namespace v8::internal
8624 #endif // V8_OBJECTS_H_