1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "src/factory.h"
7 #include "src/allocation-site-scopes.h"
8 #include "src/base/bits.h"
9 #include "src/conversions.h"
10 #include "src/isolate-inl.h"
11 #include "src/macro-assembler.h"
18 Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
21 isolate()->heap()->Allocate(*map, space),
27 Handle<T> Factory::New(Handle<Map> map,
28 AllocationSpace space,
29 Handle<AllocationSite> allocation_site) {
32 isolate()->heap()->Allocate(*map, space, *allocation_site),
37 Handle<HeapObject> Factory::NewFillerObject(int size,
39 AllocationSpace space) {
42 isolate()->heap()->AllocateFillerObject(size, double_align, space),
47 Handle<Box> Factory::NewBox(Handle<Object> value) {
48 Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
49 result->set_value(*value);
54 Handle<Oddball> Factory::NewOddball(Handle<Map> map,
55 const char* to_string,
56 Handle<Object> to_number,
58 Handle<Oddball> oddball = New<Oddball>(map, OLD_POINTER_SPACE);
59 Oddball::Initialize(isolate(), oddball, to_string, to_number, kind);
64 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
68 isolate()->heap()->AllocateFixedArray(size, pretenure),
73 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
74 PretenureFlag pretenure) {
78 isolate()->heap()->AllocateFixedArrayWithFiller(size,
85 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
88 isolate()->heap()->AllocateUninitializedFixedArray(size),
93 Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
94 PretenureFlag pretenure) {
98 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
103 Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
105 PretenureFlag pretenure) {
107 Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
109 Handle<FixedDoubleArray> double_array =
110 Handle<FixedDoubleArray>::cast(array);
111 for (int i = 0; i < size; ++i) {
112 double_array->set_the_hole(i);
119 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
120 const ConstantPoolArray::NumberOfEntries& small) {
121 DCHECK(small.total_count() > 0);
124 isolate()->heap()->AllocateConstantPoolArray(small),
129 Handle<ConstantPoolArray> Factory::NewExtendedConstantPoolArray(
130 const ConstantPoolArray::NumberOfEntries& small,
131 const ConstantPoolArray::NumberOfEntries& extended) {
132 DCHECK(small.total_count() > 0);
133 DCHECK(extended.total_count() > 0);
136 isolate()->heap()->AllocateExtendedConstantPoolArray(small, extended),
141 Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
142 return OrderedHashSet::Allocate(isolate(), 4);
146 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
147 return OrderedHashMap::Allocate(isolate(), 4);
151 Handle<AccessorPair> Factory::NewAccessorPair() {
152 Handle<AccessorPair> accessors =
153 Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
154 accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
155 accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
160 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
161 Handle<TypeFeedbackInfo> info =
162 Handle<TypeFeedbackInfo>::cast(NewStruct(TYPE_FEEDBACK_INFO_TYPE));
163 info->initialize_storage();
168 // Internalized strings are created in the old generation (data space).
169 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
170 Utf8StringKey key(string, isolate()->heap()->HashSeed());
171 return InternalizeStringWithKey(&key);
175 // Internalized strings are created in the old generation (data space).
176 Handle<String> Factory::InternalizeString(Handle<String> string) {
177 if (string->IsInternalizedString()) return string;
178 return StringTable::LookupString(isolate(), string);
182 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
183 OneByteStringKey key(string, isolate()->heap()->HashSeed());
184 return InternalizeStringWithKey(&key);
188 Handle<String> Factory::InternalizeOneByteString(
189 Handle<SeqOneByteString> string, int from, int length) {
190 SeqOneByteSubStringKey key(string, from, length);
191 return InternalizeStringWithKey(&key);
195 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
196 TwoByteStringKey key(string, isolate()->heap()->HashSeed());
197 return InternalizeStringWithKey(&key);
201 template<class StringTableKey>
202 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
203 return StringTable::LookupKey(isolate(), key);
207 MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
208 PretenureFlag pretenure) {
209 int length = string.length();
210 if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
211 Handle<SeqOneByteString> result;
212 ASSIGN_RETURN_ON_EXCEPTION(
215 NewRawOneByteString(string.length(), pretenure),
218 DisallowHeapAllocation no_gc;
219 // Copy the characters into the new object.
220 CopyChars(SeqOneByteString::cast(*result)->GetChars(),
226 MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
227 PretenureFlag pretenure) {
228 // Check for ASCII first since this is the common case.
229 const char* start = string.start();
230 int length = string.length();
231 int non_ascii_start = String::NonAsciiStart(start, length);
232 if (non_ascii_start >= length) {
233 // If the string is ASCII, we do not need to convert the characters
234 // since UTF8 is backwards compatible with ASCII.
235 return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
238 // Non-ASCII and we need to decode.
239 Access<UnicodeCache::Utf8Decoder>
240 decoder(isolate()->unicode_cache()->utf8_decoder());
241 decoder->Reset(string.start() + non_ascii_start,
242 length - non_ascii_start);
243 int utf16_length = decoder->Utf16Length();
244 DCHECK(utf16_length > 0);
246 Handle<SeqTwoByteString> result;
247 ASSIGN_RETURN_ON_EXCEPTION(
249 NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
251 // Copy ASCII portion.
252 uint16_t* data = result->GetChars();
253 const char* ascii_data = string.start();
254 for (int i = 0; i < non_ascii_start; i++) {
255 *data++ = *ascii_data++;
257 // Now write the remainder.
258 decoder->WriteUtf16(data, utf16_length);
263 MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
264 PretenureFlag pretenure) {
265 int length = string.length();
266 const uc16* start = string.start();
267 if (String::IsOneByte(start, length)) {
268 if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
269 Handle<SeqOneByteString> result;
270 ASSIGN_RETURN_ON_EXCEPTION(
273 NewRawOneByteString(length, pretenure),
275 CopyChars(result->GetChars(), start, length);
278 Handle<SeqTwoByteString> result;
279 ASSIGN_RETURN_ON_EXCEPTION(
282 NewRawTwoByteString(length, pretenure),
284 CopyChars(result->GetChars(), start, length);
290 Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
292 uint32_t hash_field) {
295 isolate()->heap()->AllocateInternalizedStringFromUtf8(
296 str, chars, hash_field),
301 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
302 Vector<const uint8_t> str,
303 uint32_t hash_field) {
306 isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
311 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedSubString(
312 Handle<SeqOneByteString> string, int offset, int length,
313 uint32_t hash_field) {
315 isolate(), isolate()->heap()->AllocateOneByteInternalizedString(
316 Vector<const uint8_t>(string->GetChars() + offset, length),
322 MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
323 Vector<const uc16> str,
324 uint32_t hash_field) {
327 isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
332 Handle<String> Factory::NewInternalizedStringImpl(
333 Handle<String> string, int chars, uint32_t hash_field) {
336 isolate()->heap()->AllocateInternalizedStringImpl(
337 *string, chars, hash_field),
342 MaybeHandle<Map> Factory::InternalizedStringMapForString(
343 Handle<String> string) {
344 // If the string is in new space it cannot be used as internalized.
345 if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
347 // Find the corresponding internalized string map for strings.
348 switch (string->map()->instance_type()) {
349 case STRING_TYPE: return internalized_string_map();
350 case ONE_BYTE_STRING_TYPE:
351 return one_byte_internalized_string_map();
352 case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
353 case EXTERNAL_ONE_BYTE_STRING_TYPE:
354 return external_one_byte_internalized_string_map();
355 case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
356 return external_internalized_string_with_one_byte_data_map();
357 case SHORT_EXTERNAL_STRING_TYPE:
358 return short_external_internalized_string_map();
359 case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
360 return short_external_one_byte_internalized_string_map();
361 case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
362 return short_external_internalized_string_with_one_byte_data_map();
363 default: return MaybeHandle<Map>(); // No match found.
368 MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
369 int length, PretenureFlag pretenure) {
370 if (length > String::kMaxLength || length < 0) {
371 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
375 isolate()->heap()->AllocateRawOneByteString(length, pretenure),
380 MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
381 int length, PretenureFlag pretenure) {
382 if (length > String::kMaxLength || length < 0) {
383 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
387 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
392 Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
393 if (code <= String::kMaxOneByteCharCodeU) {
395 DisallowHeapAllocation no_allocation;
396 Object* value = single_character_string_cache()->get(code);
397 if (value != *undefined_value()) {
398 return handle(String::cast(value), isolate());
402 buffer[0] = static_cast<uint8_t>(code);
403 Handle<String> result =
404 InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
405 single_character_string_cache()->set(code, *result);
408 DCHECK(code <= String::kMaxUtf16CodeUnitU);
410 Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
411 result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
416 // Returns true for a character in a range. Both limits are inclusive.
417 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
418 // This makes uses of the the unsigned wraparound.
419 return character - from <= to - from;
423 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
426 // Numeric strings have a different hash algorithm not known by
427 // LookupTwoCharsStringIfExists, so we skip this step for such strings.
428 if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
429 Handle<String> result;
430 if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
436 // Now we know the length is 2, we might as well make use of that fact
437 // when building the new string.
438 if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
440 DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCodeU +
441 1)); // because of this.
442 Handle<SeqOneByteString> str =
443 isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
444 uint8_t* dest = str->GetChars();
445 dest[0] = static_cast<uint8_t>(c1);
446 dest[1] = static_cast<uint8_t>(c2);
449 Handle<SeqTwoByteString> str =
450 isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
451 uc16* dest = str->GetChars();
459 template<typename SinkChar, typename StringType>
460 Handle<String> ConcatStringContent(Handle<StringType> result,
461 Handle<String> first,
462 Handle<String> second) {
463 DisallowHeapAllocation pointer_stays_valid;
464 SinkChar* sink = result->GetChars();
465 String::WriteToFlat(*first, sink, 0, first->length());
466 String::WriteToFlat(*second, sink + first->length(), 0, second->length());
471 MaybeHandle<String> Factory::NewConsString(Handle<String> left,
472 Handle<String> right) {
473 int left_length = left->length();
474 if (left_length == 0) return right;
475 int right_length = right->length();
476 if (right_length == 0) return left;
478 int length = left_length + right_length;
481 uint16_t c1 = left->Get(0);
482 uint16_t c2 = right->Get(0);
483 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
486 // Make sure that an out of memory exception is thrown if the length
487 // of the new cons string is too large.
488 if (length > String::kMaxLength || length < 0) {
489 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
492 bool left_is_one_byte = left->IsOneByteRepresentation();
493 bool right_is_one_byte = right->IsOneByteRepresentation();
494 bool is_one_byte = left_is_one_byte && right_is_one_byte;
495 bool is_one_byte_data_in_two_byte_string = false;
497 // At least one of the strings uses two-byte representation so we
498 // can't use the fast case code for short one-byte strings below, but
499 // we can try to save memory if all chars actually fit in one-byte.
500 is_one_byte_data_in_two_byte_string =
501 left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
502 if (is_one_byte_data_in_two_byte_string) {
503 isolate()->counters()->string_add_runtime_ext_to_one_byte()->Increment();
507 // If the resulting string is small make a flat string.
508 if (length < ConsString::kMinLength) {
509 // Note that neither of the two inputs can be a slice because:
510 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
511 DCHECK(left->IsFlat());
512 DCHECK(right->IsFlat());
514 STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
516 Handle<SeqOneByteString> result =
517 NewRawOneByteString(length).ToHandleChecked();
518 DisallowHeapAllocation no_gc;
519 uint8_t* dest = result->GetChars();
522 left->IsExternalString()
523 ? Handle<ExternalOneByteString>::cast(left)->GetChars()
524 : Handle<SeqOneByteString>::cast(left)->GetChars();
525 for (int i = 0; i < left_length; i++) *dest++ = src[i];
527 src = right->IsExternalString()
528 ? Handle<ExternalOneByteString>::cast(right)->GetChars()
529 : Handle<SeqOneByteString>::cast(right)->GetChars();
530 for (int i = 0; i < right_length; i++) *dest++ = src[i];
534 return (is_one_byte_data_in_two_byte_string)
535 ? ConcatStringContent<uint8_t>(
536 NewRawOneByteString(length).ToHandleChecked(), left, right)
537 : ConcatStringContent<uc16>(
538 NewRawTwoByteString(length).ToHandleChecked(), left, right);
541 Handle<Map> map = (is_one_byte || is_one_byte_data_in_two_byte_string)
542 ? cons_one_byte_string_map()
544 Handle<ConsString> result = New<ConsString>(map, NEW_SPACE);
546 DisallowHeapAllocation no_gc;
547 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
549 result->set_hash_field(String::kEmptyHashField);
550 result->set_length(length);
551 result->set_first(*left, mode);
552 result->set_second(*right, mode);
557 Handle<String> Factory::NewProperSubString(Handle<String> str,
561 if (FLAG_verify_heap) str->StringVerify();
563 DCHECK(begin > 0 || end < str->length());
565 str = String::Flatten(str);
567 int length = end - begin;
568 if (length <= 0) return empty_string();
570 return LookupSingleCharacterStringFromCode(str->Get(begin));
573 // Optimization for 2-byte strings often used as keys in a decompression
574 // dictionary. Check whether we already have the string in the string
575 // table to prevent creation of many unnecessary strings.
576 uint16_t c1 = str->Get(begin);
577 uint16_t c2 = str->Get(begin + 1);
578 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
581 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
582 if (str->IsOneByteRepresentation()) {
583 Handle<SeqOneByteString> result =
584 NewRawOneByteString(length).ToHandleChecked();
585 uint8_t* dest = result->GetChars();
586 DisallowHeapAllocation no_gc;
587 String::WriteToFlat(*str, dest, begin, end);
590 Handle<SeqTwoByteString> result =
591 NewRawTwoByteString(length).ToHandleChecked();
592 uc16* dest = result->GetChars();
593 DisallowHeapAllocation no_gc;
594 String::WriteToFlat(*str, dest, begin, end);
601 if (str->IsSlicedString()) {
602 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
603 str = Handle<String>(slice->parent(), isolate());
604 offset += slice->offset();
607 DCHECK(str->IsSeqString() || str->IsExternalString());
608 Handle<Map> map = str->IsOneByteRepresentation()
609 ? sliced_one_byte_string_map()
610 : sliced_string_map();
611 Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
613 slice->set_hash_field(String::kEmptyHashField);
614 slice->set_length(length);
615 slice->set_parent(*str);
616 slice->set_offset(offset);
621 MaybeHandle<String> Factory::NewExternalStringFromOneByte(
622 const ExternalOneByteString::Resource* resource) {
623 size_t length = resource->length();
624 if (length > static_cast<size_t>(String::kMaxLength)) {
625 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
628 Handle<Map> map = external_one_byte_string_map();
629 Handle<ExternalOneByteString> external_string =
630 New<ExternalOneByteString>(map, NEW_SPACE);
631 external_string->set_length(static_cast<int>(length));
632 external_string->set_hash_field(String::kEmptyHashField);
633 external_string->set_resource(resource);
635 return external_string;
639 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
640 const ExternalTwoByteString::Resource* resource) {
641 size_t length = resource->length();
642 if (length > static_cast<size_t>(String::kMaxLength)) {
643 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
646 // For small strings we check whether the resource contains only
647 // one byte characters. If yes, we use a different string map.
648 static const size_t kOneByteCheckLengthLimit = 32;
649 bool is_one_byte = length <= kOneByteCheckLengthLimit &&
650 String::IsOneByte(resource->data(), static_cast<int>(length));
651 Handle<Map> map = is_one_byte ?
652 external_string_with_one_byte_data_map() : external_string_map();
653 Handle<ExternalTwoByteString> external_string =
654 New<ExternalTwoByteString>(map, NEW_SPACE);
655 external_string->set_length(static_cast<int>(length));
656 external_string->set_hash_field(String::kEmptyHashField);
657 external_string->set_resource(resource);
659 return external_string;
663 Handle<Symbol> Factory::NewSymbol() {
666 isolate()->heap()->AllocateSymbol(),
671 Handle<Symbol> Factory::NewPrivateSymbol() {
672 Handle<Symbol> symbol = NewSymbol();
673 symbol->set_is_private(true);
678 Handle<Symbol> Factory::NewPrivateOwnSymbol() {
679 Handle<Symbol> symbol = NewSymbol();
680 symbol->set_is_private(true);
681 symbol->set_is_own(true);
686 Handle<Context> Factory::NewNativeContext() {
687 Handle<FixedArray> array = NewFixedArray(Context::NATIVE_CONTEXT_SLOTS);
688 array->set_map_no_write_barrier(*native_context_map());
689 Handle<Context> context = Handle<Context>::cast(array);
690 context->set_js_array_maps(*undefined_value());
691 DCHECK(context->IsNativeContext());
696 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
697 Handle<ScopeInfo> scope_info) {
698 Handle<FixedArray> array =
699 NewFixedArray(scope_info->ContextLength(), TENURED);
700 array->set_map_no_write_barrier(*global_context_map());
701 Handle<Context> context = Handle<Context>::cast(array);
702 context->set_closure(*function);
703 context->set_previous(function->context());
704 context->set_extension(*scope_info);
705 context->set_global_object(function->context()->global_object());
706 DCHECK(context->IsGlobalContext());
711 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
712 Handle<FixedArray> array =
713 NewFixedArray(scope_info->ContextLength(), TENURED);
714 array->set_map_no_write_barrier(*module_context_map());
715 // Instance link will be set later.
716 Handle<Context> context = Handle<Context>::cast(array);
717 context->set_extension(Smi::FromInt(0));
722 Handle<Context> Factory::NewFunctionContext(int length,
723 Handle<JSFunction> function) {
724 DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
725 Handle<FixedArray> array = NewFixedArray(length);
726 array->set_map_no_write_barrier(*function_context_map());
727 Handle<Context> context = Handle<Context>::cast(array);
728 context->set_closure(*function);
729 context->set_previous(function->context());
730 context->set_extension(Smi::FromInt(0));
731 context->set_global_object(function->context()->global_object());
736 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
737 Handle<Context> previous,
739 Handle<Object> thrown_object) {
740 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
741 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
742 array->set_map_no_write_barrier(*catch_context_map());
743 Handle<Context> context = Handle<Context>::cast(array);
744 context->set_closure(*function);
745 context->set_previous(*previous);
746 context->set_extension(*name);
747 context->set_global_object(previous->global_object());
748 context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
753 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
754 Handle<Context> previous,
755 Handle<JSReceiver> extension) {
756 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
757 array->set_map_no_write_barrier(*with_context_map());
758 Handle<Context> context = Handle<Context>::cast(array);
759 context->set_closure(*function);
760 context->set_previous(*previous);
761 context->set_extension(*extension);
762 context->set_global_object(previous->global_object());
767 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
768 Handle<Context> previous,
769 Handle<ScopeInfo> scope_info) {
770 Handle<FixedArray> array =
771 NewFixedArrayWithHoles(scope_info->ContextLength());
772 array->set_map_no_write_barrier(*block_context_map());
773 Handle<Context> context = Handle<Context>::cast(array);
774 context->set_closure(*function);
775 context->set_previous(*previous);
776 context->set_extension(*scope_info);
777 context->set_global_object(previous->global_object());
782 Handle<Struct> Factory::NewStruct(InstanceType type) {
785 isolate()->heap()->AllocateStruct(type),
790 Handle<CodeCache> Factory::NewCodeCache() {
791 Handle<CodeCache> code_cache =
792 Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
793 code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
794 code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
799 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
800 int aliased_context_slot) {
801 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
802 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
803 entry->set_aliased_context_slot(aliased_context_slot);
808 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
809 return Handle<DeclaredAccessorDescriptor>::cast(
810 NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
814 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
815 Handle<DeclaredAccessorInfo> info =
816 Handle<DeclaredAccessorInfo>::cast(
817 NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
818 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
823 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
824 Handle<ExecutableAccessorInfo> info =
825 Handle<ExecutableAccessorInfo>::cast(
826 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
827 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
832 Handle<Script> Factory::NewScript(Handle<String> source) {
833 // Generate id for this script.
834 Heap* heap = isolate()->heap();
835 int id = heap->last_script_id()->value() + 1;
836 if (!Smi::IsValid(id) || id < 0) id = 1;
837 heap->set_last_script_id(Smi::FromInt(id));
839 // Create and initialize script object.
840 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
841 script->set_source(*source);
842 script->set_name(heap->undefined_value());
843 script->set_id(Smi::FromInt(id));
844 script->set_line_offset(Smi::FromInt(0));
845 script->set_column_offset(Smi::FromInt(0));
846 script->set_context_data(heap->undefined_value());
847 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
848 script->set_wrapper(heap->undefined_value());
849 script->set_line_ends(heap->undefined_value());
850 script->set_eval_from_shared(heap->undefined_value());
851 script->set_eval_from_instructions_offset(Smi::FromInt(0));
852 script->set_flags(Smi::FromInt(0));
858 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
859 CALL_HEAP_FUNCTION(isolate(),
860 isolate()->heap()->AllocateForeign(addr, pretenure),
865 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
866 return NewForeign((Address) desc, TENURED);
870 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
874 isolate()->heap()->AllocateByteArray(length, pretenure),
879 Handle<ExternalArray> Factory::NewExternalArray(int length,
880 ExternalArrayType array_type,
881 void* external_pointer,
882 PretenureFlag pretenure) {
883 DCHECK(0 <= length && length <= Smi::kMaxValue);
886 isolate()->heap()->AllocateExternalArray(length,
894 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
896 ExternalArrayType array_type,
897 PretenureFlag pretenure) {
898 DCHECK(0 <= length && length <= Smi::kMaxValue);
901 isolate()->heap()->AllocateFixedTypedArray(length,
904 FixedTypedArrayBase);
908 Handle<Cell> Factory::NewCell(Handle<Object> value) {
909 AllowDeferredHandleDereference convert_to_cell;
912 isolate()->heap()->AllocateCell(*value),
917 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
920 isolate()->heap()->AllocatePropertyCell(),
925 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
926 AllowDeferredHandleDereference convert_to_cell;
927 Handle<PropertyCell> cell = NewPropertyCellWithHole();
928 PropertyCell::SetValueInferType(cell, value);
933 Handle<WeakCell> Factory::NewWeakCell(Handle<HeapObject> value) {
934 AllowDeferredHandleDereference convert_to_cell;
935 CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateWeakCell(*value),
940 Handle<AllocationSite> Factory::NewAllocationSite() {
941 Handle<Map> map = allocation_site_map();
942 Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
946 site->set_weak_next(isolate()->heap()->allocation_sites_list());
947 isolate()->heap()->set_allocation_sites_list(*site);
952 Handle<Map> Factory::NewMap(InstanceType type,
954 ElementsKind elements_kind) {
957 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
962 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
963 CALL_HEAP_FUNCTION(isolate(),
964 isolate()->heap()->CopyJSObject(*object, NULL),
969 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
970 Handle<JSObject> object,
971 Handle<AllocationSite> site) {
972 CALL_HEAP_FUNCTION(isolate(),
973 isolate()->heap()->CopyJSObject(
975 site.is_null() ? NULL : *site),
980 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
982 CALL_HEAP_FUNCTION(isolate(),
983 isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
988 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
989 CALL_HEAP_FUNCTION(isolate(),
990 isolate()->heap()->CopyFixedArray(*array),
995 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
996 Handle<FixedArray> array) {
997 DCHECK(isolate()->heap()->InNewSpace(*array));
998 CALL_HEAP_FUNCTION(isolate(),
999 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
1004 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
1005 Handle<FixedDoubleArray> array) {
1006 CALL_HEAP_FUNCTION(isolate(),
1007 isolate()->heap()->CopyFixedDoubleArray(*array),
1012 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
1013 Handle<ConstantPoolArray> array) {
1014 CALL_HEAP_FUNCTION(isolate(),
1015 isolate()->heap()->CopyConstantPoolArray(*array),
1020 Handle<Object> Factory::NewNumber(double value,
1021 PretenureFlag pretenure) {
1022 // We need to distinguish the minus zero value and this cannot be
1023 // done after conversion to int. Doing this by comparing bit
1024 // patterns is faster than using fpclassify() et al.
1025 if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1027 int int_value = FastD2I(value);
1028 if (value == int_value && Smi::IsValid(int_value)) {
1029 return handle(Smi::FromInt(int_value), isolate());
1032 // Materialize the value in the heap.
1033 return NewHeapNumber(value, IMMUTABLE, pretenure);
1037 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1038 PretenureFlag pretenure) {
1039 if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1040 // Bypass NewNumber to avoid various redundant checks.
1041 return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1045 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1046 PretenureFlag pretenure) {
1047 int32_t int32v = static_cast<int32_t>(value);
1048 if (int32v >= 0 && Smi::IsValid(int32v)) {
1049 return handle(Smi::FromInt(int32v), isolate());
1051 return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1055 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1057 PretenureFlag pretenure) {
1060 isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
1065 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1066 PretenureFlag pretenure) {
1069 isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1073 Handle<Float64x2> Factory::NewFloat64x2(float64x2_value_t value,
1074 PretenureFlag pretenure) {
1077 isolate()->heap()->AllocateFloat64x2(value, pretenure), Float64x2);
1081 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1082 PretenureFlag pretenure) {
1085 isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1089 MaybeHandle<Object> Factory::NewTypeError(const char* message,
1090 Vector<Handle<Object> > args) {
1091 return NewError("MakeTypeError", message, args);
1095 MaybeHandle<Object> Factory::NewTypeError(Handle<String> message) {
1096 return NewError("$TypeError", message);
1100 MaybeHandle<Object> Factory::NewRangeError(const char* message,
1101 Vector<Handle<Object> > args) {
1102 return NewError("MakeRangeError", message, args);
1106 MaybeHandle<Object> Factory::NewRangeError(Handle<String> message) {
1107 return NewError("$RangeError", message);
1111 MaybeHandle<Object> Factory::NewSyntaxError(const char* message,
1112 Handle<JSArray> args) {
1113 return NewError("MakeSyntaxError", message, args);
1117 MaybeHandle<Object> Factory::NewSyntaxError(Handle<String> message) {
1118 return NewError("$SyntaxError", message);
1122 MaybeHandle<Object> Factory::NewReferenceError(const char* message,
1123 Vector<Handle<Object> > args) {
1124 return NewError("MakeReferenceError", message, args);
1128 MaybeHandle<Object> Factory::NewReferenceError(const char* message,
1129 Handle<JSArray> args) {
1130 return NewError("MakeReferenceError", message, args);
1134 MaybeHandle<Object> Factory::NewReferenceError(Handle<String> message) {
1135 return NewError("$ReferenceError", message);
1139 MaybeHandle<Object> Factory::NewError(const char* maker, const char* message,
1140 Vector<Handle<Object> > args) {
1141 // Instantiate a closeable HandleScope for EscapeFrom.
1142 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1143 Handle<FixedArray> array = NewFixedArray(args.length());
1144 for (int i = 0; i < args.length(); i++) {
1145 array->set(i, *args[i]);
1147 Handle<JSArray> object = NewJSArrayWithElements(array);
1148 Handle<Object> result;
1149 ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
1150 NewError(maker, message, object), Object);
1151 return result.EscapeFrom(&scope);
1155 MaybeHandle<Object> Factory::NewEvalError(const char* message,
1156 Vector<Handle<Object> > args) {
1157 return NewError("MakeEvalError", message, args);
1161 MaybeHandle<Object> Factory::NewError(const char* message,
1162 Vector<Handle<Object> > args) {
1163 return NewError("MakeError", message, args);
1167 Handle<String> Factory::EmergencyNewError(const char* message,
1168 Handle<JSArray> args) {
1169 const int kBufferSize = 1000;
1170 char buffer[kBufferSize];
1171 size_t space = kBufferSize;
1172 char* p = &buffer[0];
1174 Vector<char> v(buffer, kBufferSize);
1175 StrNCpy(v, message, space);
1176 space -= Min(space, strlen(message));
1177 p = &buffer[kBufferSize] - space;
1179 for (int i = 0; i < Smi::cast(args->length())->value(); i++) {
1184 Handle<String> arg_str = Handle<String>::cast(
1185 Object::GetElement(isolate(), args, i).ToHandleChecked());
1186 SmartArrayPointer<char> arg = arg_str->ToCString();
1187 Vector<char> v2(p, static_cast<int>(space));
1188 StrNCpy(v2, arg.get(), space);
1189 space -= Min(space, strlen(arg.get()));
1190 p = &buffer[kBufferSize] - space;
1197 buffer[kBufferSize - 1] = '\0';
1199 return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1203 MaybeHandle<Object> Factory::NewError(const char* maker, const char* message,
1204 Handle<JSArray> args) {
1205 Handle<String> make_str = InternalizeUtf8String(maker);
1206 Handle<Object> fun_obj = Object::GetProperty(
1207 isolate()->js_builtins_object(), make_str).ToHandleChecked();
1208 // If the builtins haven't been properly configured yet this error
1209 // constructor may not have been defined. Bail out.
1210 if (!fun_obj->IsJSFunction()) {
1211 return EmergencyNewError(message, args);
1213 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1214 Handle<Object> message_obj = InternalizeUtf8String(message);
1215 Handle<Object> argv[] = { message_obj, args };
1217 // Invoke the JavaScript factory method. If an exception is thrown while
1218 // running the factory method, use the exception as the result.
1219 Handle<Object> result;
1220 MaybeHandle<Object> exception;
1221 if (!Execution::TryCall(fun,
1222 isolate()->js_builtins_object(),
1225 &exception).ToHandle(&result)) {
1232 MaybeHandle<Object> Factory::NewError(Handle<String> message) {
1233 return NewError("$Error", message);
1237 MaybeHandle<Object> Factory::NewError(const char* constructor,
1238 Handle<String> message) {
1239 Handle<String> constr = InternalizeUtf8String(constructor);
1240 Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1241 isolate()->js_builtins_object(), constr).ToHandleChecked());
1242 Handle<Object> argv[] = { message };
1244 // Invoke the JavaScript factory method. If an exception is thrown while
1245 // running the factory method, use the exception as the result.
1246 Handle<Object> result;
1247 MaybeHandle<Object> exception;
1248 if (!Execution::TryCall(fun,
1249 isolate()->js_builtins_object(),
1252 &exception).ToHandle(&result)) {
1259 void Factory::InitializeFunction(Handle<JSFunction> function,
1260 Handle<SharedFunctionInfo> info,
1261 Handle<Context> context) {
1262 function->initialize_properties();
1263 function->initialize_elements();
1264 function->set_shared(*info);
1265 function->set_code(info->code());
1266 function->set_context(*context);
1267 function->set_prototype_or_initial_map(*the_hole_value());
1268 function->set_literals_or_bindings(*empty_fixed_array());
1269 function->set_next_function_link(*undefined_value());
1273 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1274 Handle<SharedFunctionInfo> info,
1275 Handle<Context> context,
1276 PretenureFlag pretenure) {
1277 AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1278 Handle<JSFunction> result = New<JSFunction>(map, space);
1279 InitializeFunction(result, info, context);
1284 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1285 Handle<String> name,
1286 MaybeHandle<Code> code) {
1287 Handle<Context> context(isolate()->native_context());
1288 Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1289 DCHECK((info->strict_mode() == SLOPPY) &&
1290 (map.is_identical_to(isolate()->sloppy_function_map()) ||
1291 map.is_identical_to(
1292 isolate()->sloppy_function_without_prototype_map()) ||
1293 map.is_identical_to(
1294 isolate()->sloppy_function_with_readonly_prototype_map())));
1295 return NewFunction(map, info, context);
1299 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1301 isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1305 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1306 Handle<Code> code) {
1308 isolate()->sloppy_function_without_prototype_map(), name, code);
1312 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1314 Handle<Object> prototype,
1315 bool read_only_prototype) {
1316 Handle<Map> map = read_only_prototype
1317 ? isolate()->sloppy_function_with_readonly_prototype_map()
1318 : isolate()->sloppy_function_map();
1319 Handle<JSFunction> result = NewFunction(map, name, code);
1320 result->set_prototype_or_initial_map(*prototype);
1325 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1327 Handle<Object> prototype,
1330 bool read_only_prototype) {
1331 // Allocate the function
1332 Handle<JSFunction> function = NewFunction(
1333 name, code, prototype, read_only_prototype);
1335 ElementsKind elements_kind =
1336 type == JS_ARRAY_TYPE ? FAST_SMI_ELEMENTS : FAST_HOLEY_SMI_ELEMENTS;
1337 Handle<Map> initial_map = NewMap(type, instance_size, elements_kind);
1338 if (prototype->IsTheHole() && !function->shared()->is_generator()) {
1339 prototype = NewFunctionPrototype(function);
1342 JSFunction::SetInitialMap(function, initial_map,
1343 Handle<JSReceiver>::cast(prototype));
1349 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1352 int instance_size) {
1353 return NewFunction(name, code, the_hole_value(), type, instance_size);
1357 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1358 // Make sure to use globals from the function's context, since the function
1359 // can be from a different context.
1360 Handle<Context> native_context(function->context()->native_context());
1361 Handle<Map> new_map;
1362 if (function->shared()->is_generator()) {
1363 // Generator prototypes can share maps since they don't have "constructor"
1365 new_map = handle(native_context->generator_object_prototype_map());
1367 // Each function prototype gets a fresh map to avoid unwanted sharing of
1368 // maps between prototypes of different constructors.
1369 Handle<JSFunction> object_function(native_context->object_function());
1370 DCHECK(object_function->has_initial_map());
1371 new_map = handle(object_function->initial_map());
1374 DCHECK(!new_map->is_prototype_map());
1375 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1377 if (!function->shared()->is_generator()) {
1378 JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1385 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1386 Handle<SharedFunctionInfo> info,
1387 Handle<Context> context,
1388 PretenureFlag pretenure) {
1389 int map_index = Context::FunctionMapIndex(info->strict_mode(), info->kind());
1390 Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1391 Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1393 if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1394 info->ResetForNewContext(isolate()->heap()->global_ic_age());
1397 int index = info->SearchOptimizedCodeMap(context->native_context(),
1399 if (!info->bound() && index < 0) {
1400 int number_of_literals = info->num_literals();
1401 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1402 if (number_of_literals > 0) {
1403 // Store the native context in the literals array prefix. This
1404 // context will be used when creating object, regexp and array
1405 // literals in this function.
1406 literals->set(JSFunction::kLiteralNativeContextIndex,
1407 context->native_context());
1409 result->set_literals(*literals);
1413 // Caching of optimized code enabled and optimized code found.
1414 FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1415 if (literals != NULL) result->set_literals(literals);
1416 Code* code = info->GetCodeFromOptimizedCodeMap(index);
1417 DCHECK(!code->marked_for_deoptimization());
1418 result->ReplaceCode(code);
1422 if (isolate()->use_crankshaft() &&
1424 result->is_compiled() &&
1425 !info->is_toplevel() &&
1426 info->allows_lazy_compilation() &&
1427 !info->optimization_disabled() &&
1428 !isolate()->DebuggerHasBreakPoints()) {
1429 result->MarkForOptimization();
1435 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1436 Handle<FixedArray> array = NewFixedArray(length, TENURED);
1437 array->set_map_no_write_barrier(*scope_info_map());
1438 Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1443 Handle<JSObject> Factory::NewExternal(void* value) {
1444 Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1445 Handle<JSObject> external = NewJSObjectFromMap(external_map());
1446 external->SetInternalField(0, *foreign);
1451 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1452 CALL_HEAP_FUNCTION(isolate(),
1453 isolate()->heap()->AllocateCode(object_size, immovable),
1458 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1460 Handle<Object> self_ref,
1463 int prologue_offset,
1465 Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1466 Handle<ConstantPoolArray> constant_pool =
1467 desc.origin->NewConstantPool(isolate());
1470 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1471 int obj_size = Code::SizeFor(body_size);
1473 Handle<Code> code = NewCodeRaw(obj_size, immovable);
1474 DCHECK(isolate()->code_range() == NULL ||
1475 !isolate()->code_range()->valid() ||
1476 isolate()->code_range()->contains(code->address()));
1478 // The code object has not been fully initialized yet. We rely on the
1479 // fact that no allocation will happen from this point on.
1480 DisallowHeapAllocation no_gc;
1481 code->set_gc_metadata(Smi::FromInt(0));
1482 code->set_ic_age(isolate()->heap()->global_ic_age());
1483 code->set_instruction_size(desc.instr_size);
1484 code->set_relocation_info(*reloc_info);
1485 code->set_flags(flags);
1486 code->set_raw_kind_specific_flags1(0);
1487 code->set_raw_kind_specific_flags2(0);
1488 code->set_is_crankshafted(crankshafted);
1489 code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1490 code->set_raw_type_feedback_info(Smi::FromInt(0));
1491 code->set_next_code_link(*undefined_value());
1492 code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1493 code->set_prologue_offset(prologue_offset);
1494 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1495 code->set_marked_for_deoptimization(false);
1499 DCHECK(code->kind() == Code::FUNCTION);
1500 code->set_has_debug_break_slots(true);
1503 desc.origin->PopulateConstantPool(*constant_pool);
1504 code->set_constant_pool(*constant_pool);
1506 // Allow self references to created code object by patching the handle to
1507 // point to the newly allocated Code object.
1508 if (!self_ref.is_null()) *(self_ref.location()) = *code;
1510 // Migrate generated code.
1511 // The generated code can contain Object** values (typically from handles)
1512 // that are dereferenced during the copy to point directly to the actual heap
1513 // objects. These pointers can include references to the code object itself,
1514 // through the self_reference parameter.
1515 code->CopyFrom(desc);
1518 if (FLAG_verify_heap) code->ObjectVerify();
1524 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1525 CALL_HEAP_FUNCTION(isolate(),
1526 isolate()->heap()->CopyCode(*code),
1531 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1532 CALL_HEAP_FUNCTION(isolate(),
1533 isolate()->heap()->CopyCode(*code, reloc_info),
1538 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1539 PretenureFlag pretenure) {
1540 JSFunction::EnsureHasInitialMap(constructor);
1543 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1547 Handle<JSObject> Factory::NewJSObjectWithMemento(
1548 Handle<JSFunction> constructor,
1549 Handle<AllocationSite> site) {
1550 JSFunction::EnsureHasInitialMap(constructor);
1553 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1558 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1559 Handle<ScopeInfo> scope_info) {
1560 // Allocate a fresh map. Modules do not have a prototype.
1561 Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1562 // Allocate the object based on the map.
1563 Handle<JSModule> module =
1564 Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1565 module->set_context(*context);
1566 module->set_scope_info(*scope_info);
1571 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1572 DCHECK(constructor->has_initial_map());
1573 Handle<Map> map(constructor->initial_map());
1574 DCHECK(map->is_dictionary_map());
1576 // Make sure no field properties are described in the initial map.
1577 // This guarantees us that normalizing the properties does not
1578 // require us to change property values to PropertyCells.
1579 DCHECK(map->NextFreePropertyIndex() == 0);
1581 // Make sure we don't have a ton of pre-allocated slots in the
1582 // global objects. They will be unused once we normalize the object.
1583 DCHECK(map->unused_property_fields() == 0);
1584 DCHECK(map->inobject_properties() == 0);
1586 // Initial size of the backing store to avoid resize of the storage during
1587 // bootstrapping. The size differs between the JS global object ad the
1589 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1591 // Allocate a dictionary object for backing storage.
1592 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1593 Handle<NameDictionary> dictionary =
1594 NameDictionary::New(isolate(), at_least_space_for);
1596 // The global object might be created from an object template with accessors.
1597 // Fill these accessors into the dictionary.
1598 Handle<DescriptorArray> descs(map->instance_descriptors());
1599 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1600 PropertyDetails details = descs->GetDetails(i);
1601 DCHECK(details.type() == CALLBACKS); // Only accessors are expected.
1602 PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1603 Handle<Name> name(descs->GetKey(i));
1604 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1605 Handle<PropertyCell> cell = NewPropertyCell(value);
1606 // |dictionary| already contains enough space for all properties.
1607 USE(NameDictionary::Add(dictionary, name, cell, d));
1610 // Allocate the global object and initialize it with the backing store.
1611 Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1612 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1614 // Create a new map for the global object.
1615 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1616 new_map->set_dictionary_map(true);
1618 // Set up the global object as a normalized object.
1619 global->set_map(*new_map);
1620 global->set_properties(*dictionary);
1622 // Make sure result is a global object with properties in dictionary.
1623 DCHECK(global->IsGlobalObject() && !global->HasFastProperties());
1628 Handle<JSObject> Factory::NewJSObjectFromMap(
1630 PretenureFlag pretenure,
1632 Handle<AllocationSite> allocation_site) {
1635 isolate()->heap()->AllocateJSObjectFromMap(
1639 allocation_site.is_null() ? NULL : *allocation_site),
1644 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1645 PretenureFlag pretenure) {
1646 Context* native_context = isolate()->context()->native_context();
1647 JSFunction* array_function = native_context->array_function();
1648 Map* map = array_function->initial_map();
1649 Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1650 if (transition_map != NULL) map = transition_map;
1651 return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1655 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1658 ArrayStorageAllocationMode mode,
1659 PretenureFlag pretenure) {
1660 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1661 NewJSArrayStorage(array, length, capacity, mode);
1666 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1667 ElementsKind elements_kind,
1669 PretenureFlag pretenure) {
1670 DCHECK(length <= elements->length());
1671 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1673 array->set_elements(*elements);
1674 array->set_length(Smi::FromInt(length));
1675 JSObject::ValidateElements(array);
1680 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1683 ArrayStorageAllocationMode mode) {
1684 DCHECK(capacity >= length);
1686 if (capacity == 0) {
1687 array->set_length(Smi::FromInt(0));
1688 array->set_elements(*empty_fixed_array());
1692 Handle<FixedArrayBase> elms;
1693 ElementsKind elements_kind = array->GetElementsKind();
1694 if (IsFastDoubleElementsKind(elements_kind)) {
1695 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1696 elms = NewFixedDoubleArray(capacity);
1698 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1699 elms = NewFixedDoubleArrayWithHoles(capacity);
1702 DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1703 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1704 elms = NewUninitializedFixedArray(capacity);
1706 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1707 elms = NewFixedArrayWithHoles(capacity);
1711 array->set_elements(*elms);
1712 array->set_length(Smi::FromInt(length));
1716 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1717 Handle<JSFunction> function) {
1718 DCHECK(function->shared()->is_generator());
1719 JSFunction::EnsureHasInitialMap(function);
1720 Handle<Map> map(function->initial_map());
1721 DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1724 isolate()->heap()->AllocateJSObjectFromMap(*map),
1729 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1730 Handle<JSFunction> array_buffer_fun(
1731 isolate()->native_context()->array_buffer_fun());
1734 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1739 Handle<JSDataView> Factory::NewJSDataView() {
1740 Handle<JSFunction> data_view_fun(
1741 isolate()->native_context()->data_view_fun());
1744 isolate()->heap()->AllocateJSObject(*data_view_fun),
1749 Handle<JSMapIterator> Factory::NewJSMapIterator() {
1750 Handle<Map> map(isolate()->native_context()->map_iterator_map());
1751 CALL_HEAP_FUNCTION(isolate(),
1752 isolate()->heap()->AllocateJSObjectFromMap(*map),
1757 Handle<JSSetIterator> Factory::NewJSSetIterator() {
1758 Handle<Map> map(isolate()->native_context()->set_iterator_map());
1759 CALL_HEAP_FUNCTION(isolate(),
1760 isolate()->heap()->AllocateJSObjectFromMap(*map),
1767 ElementsKind GetExternalArrayElementsKind(ExternalArrayType type) {
1769 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1770 case kExternal##Type##Array: \
1771 return EXTERNAL_##TYPE##_ELEMENTS;
1772 TYPED_ARRAYS(TYPED_ARRAY_CASE)
1775 return FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND;
1776 #undef TYPED_ARRAY_CASE
1780 size_t GetExternalArrayElementSize(ExternalArrayType type) {
1782 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1783 case kExternal##Type##Array: \
1785 TYPED_ARRAYS(TYPED_ARRAY_CASE)
1789 #undef TYPED_ARRAY_CASE
1793 JSFunction* GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
1794 Context* native_context = isolate->context()->native_context();
1796 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1797 case kExternal##Type##Array: \
1798 return native_context->type##_array_fun();
1800 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1801 #undef TYPED_ARRAY_FUN
1810 void SetupArrayBufferView(i::Isolate* isolate,
1811 i::Handle<i::JSArrayBufferView> obj,
1812 i::Handle<i::JSArrayBuffer> buffer,
1813 size_t byte_offset, size_t byte_length) {
1814 DCHECK(byte_offset + byte_length <=
1815 static_cast<size_t>(buffer->byte_length()->Number()));
1817 obj->set_buffer(*buffer);
1819 obj->set_weak_next(buffer->weak_first_view());
1820 buffer->set_weak_first_view(*obj);
1822 i::Handle<i::Object> byte_offset_object =
1823 isolate->factory()->NewNumberFromSize(byte_offset);
1824 obj->set_byte_offset(*byte_offset_object);
1826 i::Handle<i::Object> byte_length_object =
1827 isolate->factory()->NewNumberFromSize(byte_length);
1828 obj->set_byte_length(*byte_length_object);
1835 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1836 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1840 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1845 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
1846 Handle<JSArrayBuffer> buffer,
1849 Handle<JSTypedArray> obj = NewJSTypedArray(type);
1851 size_t element_size = GetExternalArrayElementSize(type);
1852 ElementsKind elements_kind = GetExternalArrayElementsKind(type);
1854 CHECK(byte_offset % element_size == 0);
1856 CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
1857 CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
1858 size_t byte_length = length * element_size;
1859 SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1861 Handle<Object> length_object = NewNumberFromSize(length);
1862 obj->set_length(*length_object);
1864 Handle<ExternalArray> elements = NewExternalArray(
1865 static_cast<int>(length), type,
1866 static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
1867 Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
1868 JSObject::SetMapAndElements(obj, map, elements);
1873 Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
1875 size_t byte_length) {
1876 Handle<JSDataView> obj = NewJSDataView();
1877 SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1882 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1883 Handle<Object> prototype) {
1885 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1886 // maps. Will probably depend on the identity of the handler object, too.
1887 Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1888 map->set_prototype(*prototype);
1890 // Allocate the proxy object.
1891 Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1892 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1893 result->set_handler(*handler);
1894 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1899 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1900 Handle<Object> call_trap,
1901 Handle<Object> construct_trap,
1902 Handle<Object> prototype) {
1904 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1905 // maps. Will probably depend on the identity of the handler object, too.
1906 Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1907 map->set_prototype(*prototype);
1909 // Allocate the proxy object.
1910 Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1911 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1912 result->set_handler(*handler);
1913 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1914 result->set_call_trap(*call_trap);
1915 result->set_construct_trap(*construct_trap);
1920 void Factory::ReinitializeJSProxy(Handle<JSProxy> proxy, InstanceType type,
1922 DCHECK(type == JS_OBJECT_TYPE || type == JS_FUNCTION_TYPE);
1924 // Allocate fresh map.
1925 // TODO(rossberg): Once we optimize proxies, cache these maps.
1926 Handle<Map> map = NewMap(type, size);
1928 // Check that the receiver has at least the size of the fresh object.
1929 int size_difference = proxy->map()->instance_size() - map->instance_size();
1930 DCHECK(size_difference >= 0);
1932 map->set_prototype(proxy->map()->prototype());
1934 // Allocate the backing storage for the properties.
1935 int prop_size = map->InitialPropertiesLength();
1936 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1938 Heap* heap = isolate()->heap();
1939 MaybeHandle<SharedFunctionInfo> shared;
1940 if (type == JS_FUNCTION_TYPE) {
1941 OneByteStringKey key(STATIC_CHAR_VECTOR("<freezing call trap>"),
1943 Handle<String> name = InternalizeStringWithKey(&key);
1944 shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1947 // In order to keep heap in consistent state there must be no allocations
1948 // before object re-initialization is finished and filler object is installed.
1949 DisallowHeapAllocation no_allocation;
1951 // Put in filler if the new object is smaller than the old.
1952 if (size_difference > 0) {
1953 Address address = proxy->address();
1954 heap->CreateFillerObjectAt(address + map->instance_size(), size_difference);
1955 heap->AdjustLiveBytes(address, -size_difference, Heap::FROM_MUTATOR);
1958 // Reset the map for the object.
1959 proxy->synchronized_set_map(*map);
1960 Handle<JSObject> jsobj = Handle<JSObject>::cast(proxy);
1962 // Reinitialize the object from the constructor map.
1963 heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1965 // The current native context is used to set up certain bits.
1966 // TODO(adamk): Using the current context seems wrong, it should be whatever
1967 // context the JSProxy originated in. But that context isn't stored anywhere.
1968 Handle<Context> context(isolate()->native_context());
1970 // Functions require some minimal initialization.
1971 if (type == JS_FUNCTION_TYPE) {
1972 map->set_function_with_prototype(true);
1973 Handle<JSFunction> js_function = Handle<JSFunction>::cast(proxy);
1974 InitializeFunction(js_function, shared.ToHandleChecked(), context);
1976 // Provide JSObjects with a constructor.
1977 map->set_constructor(context->object_function());
1982 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1983 Handle<JSFunction> constructor) {
1984 DCHECK(constructor->has_initial_map());
1985 Handle<Map> map(constructor->initial_map(), isolate());
1987 // The proxy's hash should be retained across reinitialization.
1988 Handle<Object> hash(object->hash(), isolate());
1990 // Check that the already allocated object has the same size and type as
1991 // objects allocated using the constructor.
1992 DCHECK(map->instance_size() == object->map()->instance_size());
1993 DCHECK(map->instance_type() == object->map()->instance_type());
1995 // Allocate the backing storage for the properties.
1996 int prop_size = map->InitialPropertiesLength();
1997 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1999 // In order to keep heap in consistent state there must be no allocations
2000 // before object re-initialization is finished.
2001 DisallowHeapAllocation no_allocation;
2003 // Reset the map for the object.
2004 object->synchronized_set_map(*map);
2006 Heap* heap = isolate()->heap();
2007 // Reinitialize the object from the constructor map.
2008 heap->InitializeJSObjectFromMap(*object, *properties, *map);
2010 // Restore the saved hash.
2011 object->set_hash(*hash);
2015 void Factory::BecomeJSObject(Handle<JSProxy> proxy) {
2016 ReinitializeJSProxy(proxy, JS_OBJECT_TYPE, JSObject::kHeaderSize);
2020 void Factory::BecomeJSFunction(Handle<JSProxy> proxy) {
2021 ReinitializeJSProxy(proxy, JS_FUNCTION_TYPE, JSFunction::kSize);
2025 Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(int slot_count,
2026 int ic_slot_count) {
2027 return TypeFeedbackVector::Allocate(isolate(), slot_count, ic_slot_count);
2031 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2032 Handle<String> name, int number_of_literals, FunctionKind kind,
2033 Handle<Code> code, Handle<ScopeInfo> scope_info,
2034 Handle<TypeFeedbackVector> feedback_vector) {
2035 DCHECK(IsValidFunctionKind(kind));
2036 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
2037 shared->set_scope_info(*scope_info);
2038 shared->set_feedback_vector(*feedback_vector);
2039 shared->set_kind(kind);
2040 int literals_array_size = number_of_literals;
2041 // If the function contains object, regexp or array literals,
2042 // allocate extra space for a literals array prefix containing the
2044 if (number_of_literals > 0) {
2045 literals_array_size += JSFunction::kLiteralsPrefixSize;
2047 shared->set_num_literals(literals_array_size);
2048 if (IsGeneratorFunction(kind)) {
2049 shared->set_instance_class_name(isolate()->heap()->Generator_string());
2050 shared->DisableOptimization(kGenerator);
2056 Handle<JSMessageObject> Factory::NewJSMessageObject(
2057 Handle<String> type,
2058 Handle<JSArray> arguments,
2061 Handle<Object> script,
2062 Handle<Object> stack_frames) {
2063 Handle<Map> map = message_object_map();
2064 Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
2065 message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2066 message->initialize_elements();
2067 message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2068 message->set_type(*type);
2069 message->set_arguments(*arguments);
2070 message->set_start_position(start_position);
2071 message->set_end_position(end_position);
2072 message->set_script(*script);
2073 message->set_stack_frames(*stack_frames);
2078 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2079 Handle<String> name,
2080 MaybeHandle<Code> maybe_code) {
2081 Handle<Map> map = shared_function_info_map();
2082 Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map,
2085 // Set pointer fields.
2086 share->set_name(*name);
2088 if (!maybe_code.ToHandle(&code)) {
2089 code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
2091 share->set_code(*code);
2092 share->set_optimized_code_map(Smi::FromInt(0));
2093 share->set_scope_info(ScopeInfo::Empty(isolate()));
2094 Code* construct_stub =
2095 isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2096 share->set_construct_stub(construct_stub);
2097 share->set_instance_class_name(*Object_string());
2098 share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
2099 share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
2100 share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
2101 share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
2102 Handle<TypeFeedbackVector> feedback_vector = NewTypeFeedbackVector(0, 0);
2103 share->set_feedback_vector(*feedback_vector, SKIP_WRITE_BARRIER);
2104 share->set_profiler_ticks(0);
2105 share->set_ast_node_count(0);
2106 share->set_counters(0);
2108 // Set integer fields (smi or int, depending on the architecture).
2109 share->set_length(0);
2110 share->set_formal_parameter_count(0);
2111 share->set_expected_nof_properties(0);
2112 share->set_num_literals(0);
2113 share->set_start_position_and_type(0);
2114 share->set_end_position(0);
2115 share->set_function_token_position(0);
2116 // All compiler hints default to false or 0.
2117 share->set_compiler_hints(0);
2118 share->set_opt_count_and_bailout_reason(0);
2124 static inline int NumberCacheHash(Handle<FixedArray> cache,
2125 Handle<Object> number) {
2126 int mask = (cache->length() >> 1) - 1;
2127 if (number->IsSmi()) {
2128 return Handle<Smi>::cast(number)->value() & mask;
2130 DoubleRepresentation rep(number->Number());
2132 (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2137 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2138 DisallowHeapAllocation no_gc;
2139 int hash = NumberCacheHash(number_string_cache(), number);
2140 Object* key = number_string_cache()->get(hash * 2);
2141 if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2142 key->Number() == number->Number())) {
2143 return Handle<String>(
2144 String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2146 return undefined_value();
2150 void Factory::SetNumberStringCache(Handle<Object> number,
2151 Handle<String> string) {
2152 int hash = NumberCacheHash(number_string_cache(), number);
2153 if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2154 int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2155 if (number_string_cache()->length() != full_size) {
2156 // The first time we have a hash collision, we move to the full sized
2157 // number string cache. The idea is to have a small number string
2158 // cache in the snapshot to keep boot-time memory usage down.
2159 // If we expand the number string cache already while creating
2160 // the snapshot then that didn't work out.
2161 DCHECK(!isolate()->serializer_enabled() || FLAG_extra_code != NULL);
2162 Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2163 isolate()->heap()->set_number_string_cache(*new_cache);
2167 number_string_cache()->set(hash * 2, *number);
2168 number_string_cache()->set(hash * 2 + 1, *string);
2172 Handle<String> Factory::NumberToString(Handle<Object> number,
2173 bool check_number_string_cache) {
2174 isolate()->counters()->number_to_string_runtime()->Increment();
2175 if (check_number_string_cache) {
2176 Handle<Object> cached = GetNumberStringCache(number);
2177 if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2181 Vector<char> buffer(arr, arraysize(arr));
2183 if (number->IsSmi()) {
2184 int num = Handle<Smi>::cast(number)->value();
2185 str = IntToCString(num, buffer);
2187 double num = Handle<HeapNumber>::cast(number)->value();
2188 str = DoubleToCString(num, buffer);
2191 // We tenure the allocated string since it is referenced from the
2192 // number-string cache which lives in the old space.
2193 Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2194 SetNumberStringCache(number, js_string);
2199 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2200 // Get the original code of the function.
2201 Handle<Code> code(shared->code());
2203 // Create a copy of the code before allocating the debug info object to avoid
2204 // allocation while setting up the debug info object.
2205 Handle<Code> original_code(*Factory::CopyCode(code));
2207 // Allocate initial fixed array for active break points before allocating the
2208 // debug info object to avoid allocation while setting up the debug info
2210 Handle<FixedArray> break_points(
2211 NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2213 // Create and set up the debug info object. Debug info contains function, a
2214 // copy of the original code, the executing code and initial fixed array for
2215 // active break points.
2216 Handle<DebugInfo> debug_info =
2217 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2218 debug_info->set_shared(*shared);
2219 debug_info->set_original_code(*original_code);
2220 debug_info->set_code(*code);
2221 debug_info->set_break_points(*break_points);
2223 // Link debug info to function.
2224 shared->set_debug_info(*debug_info);
2230 Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2232 bool strict_mode_callee = callee->shared()->strict_mode() == STRICT;
2233 Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2234 : isolate()->sloppy_arguments_map();
2236 AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2238 DCHECK(!isolate()->has_pending_exception());
2239 Handle<JSObject> result = NewJSObjectFromMap(map);
2240 Handle<Smi> value(Smi::FromInt(length), isolate());
2241 Object::SetProperty(result, length_string(), value, STRICT).Assert();
2242 if (!strict_mode_callee) {
2243 Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2249 Handle<JSFunction> Factory::CreateApiFunction(
2250 Handle<FunctionTemplateInfo> obj,
2251 Handle<Object> prototype,
2252 ApiInstanceType instance_type) {
2253 Handle<Code> code = isolate()->builtins()->HandleApiCall();
2254 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
2256 Handle<JSFunction> result;
2257 if (obj->remove_prototype()) {
2258 result = NewFunctionWithoutPrototype(empty_string(), code);
2260 int internal_field_count = 0;
2261 if (!obj->instance_template()->IsUndefined()) {
2262 Handle<ObjectTemplateInfo> instance_template =
2263 Handle<ObjectTemplateInfo>(
2264 ObjectTemplateInfo::cast(obj->instance_template()));
2265 internal_field_count =
2266 Smi::cast(instance_template->internal_field_count())->value();
2269 // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
2270 // JSObject::GetHeaderSize.
2271 int instance_size = kPointerSize * internal_field_count;
2273 switch (instance_type) {
2274 case JavaScriptObjectType:
2275 type = JS_OBJECT_TYPE;
2276 instance_size += JSObject::kHeaderSize;
2278 case GlobalObjectType:
2279 type = JS_GLOBAL_OBJECT_TYPE;
2280 instance_size += JSGlobalObject::kSize;
2282 case GlobalProxyType:
2283 type = JS_GLOBAL_PROXY_TYPE;
2284 instance_size += JSGlobalProxy::kSize;
2288 type = JS_OBJECT_TYPE; // Keep the compiler happy.
2292 result = NewFunction(empty_string(), code, prototype, type,
2293 instance_size, obj->read_only_prototype());
2296 result->shared()->set_length(obj->length());
2297 Handle<Object> class_name(obj->class_name(), isolate());
2298 if (class_name->IsString()) {
2299 result->shared()->set_instance_class_name(*class_name);
2300 result->shared()->set_name(*class_name);
2302 result->shared()->set_function_data(*obj);
2303 result->shared()->set_construct_stub(*construct_stub);
2304 result->shared()->DontAdaptArguments();
2306 if (obj->remove_prototype()) {
2307 DCHECK(result->shared()->IsApiFunction());
2308 DCHECK(!result->has_initial_map());
2309 DCHECK(!result->has_prototype());
2313 if (prototype->IsTheHole()) {
2315 LookupIterator it(handle(JSObject::cast(result->prototype())),
2316 constructor_string(),
2317 LookupIterator::OWN_SKIP_INTERCEPTOR);
2318 MaybeHandle<Object> maybe_prop = Object::GetProperty(&it);
2319 DCHECK(it.IsFound());
2320 DCHECK(maybe_prop.ToHandleChecked().is_identical_to(result));
2323 JSObject::AddProperty(handle(JSObject::cast(result->prototype())),
2324 constructor_string(), result, DONT_ENUM);
2327 // Down from here is only valid for API functions that can be used as a
2328 // constructor (don't set the "remove prototype" flag).
2330 Handle<Map> map(result->initial_map());
2332 // Mark as undetectable if needed.
2333 if (obj->undetectable()) {
2334 map->set_is_undetectable();
2337 // Mark as hidden for the __proto__ accessor if needed.
2338 if (obj->hidden_prototype()) {
2339 map->set_is_hidden_prototype();
2342 // Mark as needs_access_check if needed.
2343 if (obj->needs_access_check()) {
2344 map->set_is_access_check_needed(true);
2347 // Set interceptor information in the map.
2348 if (!obj->named_property_handler()->IsUndefined()) {
2349 map->set_has_named_interceptor();
2351 if (!obj->indexed_property_handler()->IsUndefined()) {
2352 map->set_has_indexed_interceptor();
2355 // Set instance call-as-function information in the map.
2356 if (!obj->instance_call_handler()->IsUndefined()) {
2357 map->set_has_instance_call_handler();
2360 // Recursively copy parent instance templates' accessors,
2361 // 'data' may be modified.
2362 int max_number_of_additional_properties = 0;
2363 int max_number_of_static_properties = 0;
2364 FunctionTemplateInfo* info = *obj;
2366 if (!info->instance_template()->IsUndefined()) {
2368 ObjectTemplateInfo::cast(
2369 info->instance_template())->property_accessors();
2370 if (!props->IsUndefined()) {
2371 Handle<Object> props_handle(props, isolate());
2372 NeanderArray props_array(props_handle);
2373 max_number_of_additional_properties += props_array.length();
2376 if (!info->property_accessors()->IsUndefined()) {
2377 Object* props = info->property_accessors();
2378 if (!props->IsUndefined()) {
2379 Handle<Object> props_handle(props, isolate());
2380 NeanderArray props_array(props_handle);
2381 max_number_of_static_properties += props_array.length();
2384 Object* parent = info->parent_template();
2385 if (parent->IsUndefined()) break;
2386 info = FunctionTemplateInfo::cast(parent);
2389 Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
2391 // Use a temporary FixedArray to acculumate static accessors
2392 int valid_descriptors = 0;
2393 Handle<FixedArray> array;
2394 if (max_number_of_static_properties > 0) {
2395 array = NewFixedArray(max_number_of_static_properties);
2399 // Install instance descriptors
2400 if (!obj->instance_template()->IsUndefined()) {
2401 Handle<ObjectTemplateInfo> instance =
2402 Handle<ObjectTemplateInfo>(
2403 ObjectTemplateInfo::cast(obj->instance_template()), isolate());
2404 Handle<Object> props = Handle<Object>(instance->property_accessors(),
2406 if (!props->IsUndefined()) {
2407 Map::AppendCallbackDescriptors(map, props);
2410 // Accumulate static accessors
2411 if (!obj->property_accessors()->IsUndefined()) {
2412 Handle<Object> props = Handle<Object>(obj->property_accessors(),
2415 AccessorInfo::AppendUnique(props, array, valid_descriptors);
2417 // Climb parent chain
2418 Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
2419 if (parent->IsUndefined()) break;
2420 obj = Handle<FunctionTemplateInfo>::cast(parent);
2423 // Install accumulated static accessors
2424 for (int i = 0; i < valid_descriptors; i++) {
2425 Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
2426 JSObject::SetAccessor(result, accessor).Assert();
2429 DCHECK(result->shared()->IsApiFunction());
2434 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
2435 Handle<FixedArray> keys,
2437 Handle<MapCache> map_cache = handle(MapCache::cast(context->map_cache()));
2438 Handle<MapCache> result = MapCache::Put(map_cache, keys, map);
2439 context->set_map_cache(*result);
2444 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2445 Handle<FixedArray> keys) {
2446 if (context->map_cache()->IsUndefined()) {
2447 // Allocate the new map cache for the native context.
2448 Handle<MapCache> new_cache = MapCache::New(isolate(), 24);
2449 context->set_map_cache(*new_cache);
2451 // Check to see whether there is a matching element in the cache.
2452 Handle<MapCache> cache =
2453 Handle<MapCache>(MapCache::cast(context->map_cache()));
2454 Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
2455 if (result->IsMap()) return Handle<Map>::cast(result);
2456 int length = keys->length();
2457 // Create a new map and add it to the cache. Reuse the initial map of the
2458 // Object function if the literal has no predeclared properties.
2459 Handle<Map> map = length == 0
2460 ? handle(context->object_function()->initial_map())
2461 : Map::Create(isolate(), length);
2462 AddToMapCache(context, keys, map);
2467 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2468 JSRegExp::Type type,
2469 Handle<String> source,
2470 JSRegExp::Flags flags,
2471 Handle<Object> data) {
2472 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2474 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2475 store->set(JSRegExp::kSourceIndex, *source);
2476 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2477 store->set(JSRegExp::kAtomPatternIndex, *data);
2478 regexp->set_data(*store);
2481 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2482 JSRegExp::Type type,
2483 Handle<String> source,
2484 JSRegExp::Flags flags,
2485 int capture_count) {
2486 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2487 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2488 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2489 store->set(JSRegExp::kSourceIndex, *source);
2490 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2491 store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
2492 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2493 store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
2494 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2495 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2496 store->set(JSRegExp::kIrregexpCaptureCountIndex,
2497 Smi::FromInt(capture_count));
2498 regexp->set_data(*store);
2503 MaybeHandle<FunctionTemplateInfo> Factory::ConfigureInstance(
2504 Handle<FunctionTemplateInfo> desc, Handle<JSObject> instance) {
2505 // Configure the instance by adding the properties specified by the
2506 // instance template.
2507 Handle<Object> instance_template(desc->instance_template(), isolate());
2508 if (!instance_template->IsUndefined()) {
2509 RETURN_ON_EXCEPTION(
2511 Execution::ConfigureInstance(isolate(), instance, instance_template),
2512 FunctionTemplateInfo);
2518 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2519 if (String::Equals(name, undefined_string())) return undefined_value();
2520 if (String::Equals(name, nan_string())) return nan_value();
2521 if (String::Equals(name, infinity_string())) return infinity_value();
2522 return Handle<Object>::null();
2526 Handle<Object> Factory::ToBoolean(bool value) {
2527 return value ? true_value() : false_value();
2531 } } // namespace v8::internal