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(), OrderedHashSet::kMinCapacity);
146 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
147 return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kMinCapacity);
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 = static_cast<int>(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::NewScriptContext(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(*script_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->IsScriptContext());
711 Handle<ScriptContextTable> Factory::NewScriptContextTable() {
712 Handle<FixedArray> array = NewFixedArray(1);
713 array->set_map_no_write_barrier(*script_context_table_map());
714 Handle<ScriptContextTable> context_table =
715 Handle<ScriptContextTable>::cast(array);
716 context_table->set_used(0);
717 return context_table;
721 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
722 Handle<FixedArray> array =
723 NewFixedArray(scope_info->ContextLength(), TENURED);
724 array->set_map_no_write_barrier(*module_context_map());
725 // Instance link will be set later.
726 Handle<Context> context = Handle<Context>::cast(array);
727 context->set_extension(Smi::FromInt(0));
732 Handle<Context> Factory::NewFunctionContext(int length,
733 Handle<JSFunction> function) {
734 DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
735 Handle<FixedArray> array = NewFixedArray(length);
736 array->set_map_no_write_barrier(*function_context_map());
737 Handle<Context> context = Handle<Context>::cast(array);
738 context->set_closure(*function);
739 context->set_previous(function->context());
740 context->set_extension(Smi::FromInt(0));
741 context->set_global_object(function->context()->global_object());
746 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
747 Handle<Context> previous,
749 Handle<Object> thrown_object) {
750 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
751 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
752 array->set_map_no_write_barrier(*catch_context_map());
753 Handle<Context> context = Handle<Context>::cast(array);
754 context->set_closure(*function);
755 context->set_previous(*previous);
756 context->set_extension(*name);
757 context->set_global_object(previous->global_object());
758 context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
763 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
764 Handle<Context> previous,
765 Handle<JSReceiver> extension) {
766 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
767 array->set_map_no_write_barrier(*with_context_map());
768 Handle<Context> context = Handle<Context>::cast(array);
769 context->set_closure(*function);
770 context->set_previous(*previous);
771 context->set_extension(*extension);
772 context->set_global_object(previous->global_object());
777 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
778 Handle<Context> previous,
779 Handle<ScopeInfo> scope_info) {
780 Handle<FixedArray> array =
781 NewFixedArrayWithHoles(scope_info->ContextLength());
782 array->set_map_no_write_barrier(*block_context_map());
783 Handle<Context> context = Handle<Context>::cast(array);
784 context->set_closure(*function);
785 context->set_previous(*previous);
786 context->set_extension(*scope_info);
787 context->set_global_object(previous->global_object());
792 Handle<Struct> Factory::NewStruct(InstanceType type) {
795 isolate()->heap()->AllocateStruct(type),
800 Handle<CodeCache> Factory::NewCodeCache() {
801 Handle<CodeCache> code_cache =
802 Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
803 code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
804 code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
805 code_cache->set_weak_cell_cache(*undefined_value(), SKIP_WRITE_BARRIER);
810 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
811 int aliased_context_slot) {
812 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
813 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
814 entry->set_aliased_context_slot(aliased_context_slot);
819 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
820 Handle<ExecutableAccessorInfo> info =
821 Handle<ExecutableAccessorInfo>::cast(
822 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
823 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
828 Handle<Script> Factory::NewScript(Handle<String> source) {
829 // Create and initialize script object.
830 Heap* heap = isolate()->heap();
831 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
832 script->set_source(*source);
833 script->set_name(heap->undefined_value());
834 script->set_id(isolate()->heap()->NextScriptId());
835 script->set_line_offset(Smi::FromInt(0));
836 script->set_column_offset(Smi::FromInt(0));
837 script->set_context_data(heap->undefined_value());
838 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
839 script->set_wrapper(heap->undefined_value());
840 script->set_line_ends(heap->undefined_value());
841 script->set_eval_from_shared(heap->undefined_value());
842 script->set_eval_from_instructions_offset(Smi::FromInt(0));
843 script->set_flags(Smi::FromInt(0));
849 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
850 CALL_HEAP_FUNCTION(isolate(),
851 isolate()->heap()->AllocateForeign(addr, pretenure),
856 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
857 return NewForeign((Address) desc, TENURED);
861 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
865 isolate()->heap()->AllocateByteArray(length, pretenure),
870 Handle<ExternalArray> Factory::NewExternalArray(int length,
871 ExternalArrayType array_type,
872 void* external_pointer,
873 PretenureFlag pretenure) {
874 DCHECK(0 <= length && length <= Smi::kMaxValue);
877 isolate()->heap()->AllocateExternalArray(length,
885 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
887 ExternalArrayType array_type,
888 PretenureFlag pretenure) {
889 DCHECK(0 <= length && length <= Smi::kMaxValue);
892 isolate()->heap()->AllocateFixedTypedArray(length,
895 FixedTypedArrayBase);
899 Handle<Cell> Factory::NewCell(Handle<Object> value) {
900 AllowDeferredHandleDereference convert_to_cell;
903 isolate()->heap()->AllocateCell(*value),
908 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
911 isolate()->heap()->AllocatePropertyCell(),
916 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
917 AllowDeferredHandleDereference convert_to_cell;
918 Handle<PropertyCell> cell = NewPropertyCellWithHole();
919 PropertyCell::SetValueInferType(cell, value);
924 Handle<WeakCell> Factory::NewWeakCell(Handle<HeapObject> value) {
925 AllowDeferredHandleDereference convert_to_cell;
926 CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateWeakCell(*value),
931 Handle<AllocationSite> Factory::NewAllocationSite() {
932 Handle<Map> map = allocation_site_map();
933 Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
937 site->set_weak_next(isolate()->heap()->allocation_sites_list());
938 isolate()->heap()->set_allocation_sites_list(*site);
943 Handle<Map> Factory::NewMap(InstanceType type,
945 ElementsKind elements_kind) {
948 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
953 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
954 CALL_HEAP_FUNCTION(isolate(),
955 isolate()->heap()->CopyJSObject(*object, NULL),
960 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
961 Handle<JSObject> object,
962 Handle<AllocationSite> site) {
963 CALL_HEAP_FUNCTION(isolate(),
964 isolate()->heap()->CopyJSObject(
966 site.is_null() ? NULL : *site),
971 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
973 CALL_HEAP_FUNCTION(isolate(),
974 isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
979 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
980 CALL_HEAP_FUNCTION(isolate(),
981 isolate()->heap()->CopyFixedArray(*array),
986 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
987 Handle<FixedArray> array) {
988 DCHECK(isolate()->heap()->InNewSpace(*array));
989 CALL_HEAP_FUNCTION(isolate(),
990 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
995 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
996 Handle<FixedDoubleArray> array) {
997 CALL_HEAP_FUNCTION(isolate(),
998 isolate()->heap()->CopyFixedDoubleArray(*array),
1003 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
1004 Handle<ConstantPoolArray> array) {
1005 CALL_HEAP_FUNCTION(isolate(),
1006 isolate()->heap()->CopyConstantPoolArray(*array),
1011 Handle<Object> Factory::NewNumber(double value,
1012 PretenureFlag pretenure) {
1013 // We need to distinguish the minus zero value and this cannot be
1014 // done after conversion to int. Doing this by comparing bit
1015 // patterns is faster than using fpclassify() et al.
1016 if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1018 int int_value = FastD2IChecked(value);
1019 if (value == int_value && Smi::IsValid(int_value)) {
1020 return handle(Smi::FromInt(int_value), isolate());
1023 // Materialize the value in the heap.
1024 return NewHeapNumber(value, IMMUTABLE, pretenure);
1028 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1029 PretenureFlag pretenure) {
1030 if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1031 // Bypass NewNumber to avoid various redundant checks.
1032 return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1036 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1037 PretenureFlag pretenure) {
1038 int32_t int32v = static_cast<int32_t>(value);
1039 if (int32v >= 0 && Smi::IsValid(int32v)) {
1040 return handle(Smi::FromInt(int32v), isolate());
1042 return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1046 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1048 PretenureFlag pretenure) {
1051 isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
1056 MaybeHandle<Object> Factory::NewTypeError(const char* message,
1057 Vector<Handle<Object> > args) {
1058 return NewError("MakeTypeError", message, args);
1062 MaybeHandle<Object> Factory::NewTypeError(Handle<String> message) {
1063 return NewError("$TypeError", message);
1067 MaybeHandle<Object> Factory::NewRangeError(const char* message,
1068 Vector<Handle<Object> > args) {
1069 return NewError("MakeRangeError", message, args);
1073 MaybeHandle<Object> Factory::NewRangeError(Handle<String> message) {
1074 return NewError("$RangeError", message);
1078 MaybeHandle<Object> Factory::NewSyntaxError(const char* message,
1079 Handle<JSArray> args) {
1080 return NewError("MakeSyntaxError", message, args);
1084 MaybeHandle<Object> Factory::NewSyntaxError(Handle<String> message) {
1085 return NewError("$SyntaxError", message);
1089 MaybeHandle<Object> Factory::NewReferenceError(const char* message,
1090 Vector<Handle<Object> > args) {
1091 return NewError("MakeReferenceError", message, args);
1095 MaybeHandle<Object> Factory::NewReferenceError(const char* message,
1096 Handle<JSArray> args) {
1097 return NewError("MakeReferenceError", message, args);
1101 MaybeHandle<Object> Factory::NewReferenceError(Handle<String> message) {
1102 return NewError("$ReferenceError", message);
1106 MaybeHandle<Object> Factory::NewError(const char* maker, const char* message,
1107 Vector<Handle<Object> > args) {
1108 // Instantiate a closeable HandleScope for EscapeFrom.
1109 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1110 Handle<FixedArray> array = NewFixedArray(args.length());
1111 for (int i = 0; i < args.length(); i++) {
1112 array->set(i, *args[i]);
1114 Handle<JSArray> object = NewJSArrayWithElements(array);
1115 Handle<Object> result;
1116 ASSIGN_RETURN_ON_EXCEPTION(isolate(), result,
1117 NewError(maker, message, object), Object);
1118 return result.EscapeFrom(&scope);
1122 MaybeHandle<Object> Factory::NewEvalError(const char* message,
1123 Vector<Handle<Object> > args) {
1124 return NewError("MakeEvalError", message, args);
1128 MaybeHandle<Object> Factory::NewError(const char* message,
1129 Vector<Handle<Object> > args) {
1130 return NewError("MakeError", message, args);
1134 Handle<String> Factory::EmergencyNewError(const char* message,
1135 Handle<JSArray> args) {
1136 const int kBufferSize = 1000;
1137 char buffer[kBufferSize];
1138 size_t space = kBufferSize;
1139 char* p = &buffer[0];
1141 Vector<char> v(buffer, kBufferSize);
1142 StrNCpy(v, message, space);
1143 space -= Min(space, strlen(message));
1144 p = &buffer[kBufferSize] - space;
1146 for (int i = 0; i < Smi::cast(args->length())->value(); i++) {
1151 Handle<String> arg_str = Handle<String>::cast(
1152 Object::GetElement(isolate(), args, i).ToHandleChecked());
1153 SmartArrayPointer<char> arg = arg_str->ToCString();
1154 Vector<char> v2(p, static_cast<int>(space));
1155 StrNCpy(v2, arg.get(), space);
1156 space -= Min(space, strlen(arg.get()));
1157 p = &buffer[kBufferSize] - space;
1164 buffer[kBufferSize - 1] = '\0';
1166 return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1170 MaybeHandle<Object> Factory::NewError(const char* maker, const char* message,
1171 Handle<JSArray> args) {
1172 Handle<String> make_str = InternalizeUtf8String(maker);
1173 Handle<Object> fun_obj = Object::GetProperty(
1174 isolate()->js_builtins_object(), make_str).ToHandleChecked();
1175 // If the builtins haven't been properly configured yet this error
1176 // constructor may not have been defined. Bail out.
1177 if (!fun_obj->IsJSFunction()) {
1178 return EmergencyNewError(message, args);
1180 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1181 Handle<Object> message_obj = InternalizeUtf8String(message);
1182 Handle<Object> argv[] = { message_obj, args };
1184 // Invoke the JavaScript factory method. If an exception is thrown while
1185 // running the factory method, use the exception as the result.
1186 Handle<Object> result;
1187 MaybeHandle<Object> exception;
1188 if (!Execution::TryCall(fun,
1189 isolate()->js_builtins_object(),
1192 &exception).ToHandle(&result)) {
1199 MaybeHandle<Object> Factory::NewError(Handle<String> message) {
1200 return NewError("$Error", message);
1204 MaybeHandle<Object> Factory::NewError(const char* constructor,
1205 Handle<String> message) {
1206 Handle<String> constr = InternalizeUtf8String(constructor);
1207 Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1208 isolate()->js_builtins_object(), constr).ToHandleChecked());
1209 Handle<Object> argv[] = { message };
1211 // Invoke the JavaScript factory method. If an exception is thrown while
1212 // running the factory method, use the exception as the result.
1213 Handle<Object> result;
1214 MaybeHandle<Object> exception;
1215 if (!Execution::TryCall(fun,
1216 isolate()->js_builtins_object(),
1219 &exception).ToHandle(&result)) {
1226 void Factory::InitializeFunction(Handle<JSFunction> function,
1227 Handle<SharedFunctionInfo> info,
1228 Handle<Context> context) {
1229 function->initialize_properties();
1230 function->initialize_elements();
1231 function->set_shared(*info);
1232 function->set_code(info->code());
1233 function->set_context(*context);
1234 function->set_prototype_or_initial_map(*the_hole_value());
1235 function->set_literals_or_bindings(*empty_fixed_array());
1236 function->set_next_function_link(*undefined_value());
1240 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1241 Handle<SharedFunctionInfo> info,
1242 Handle<Context> context,
1243 PretenureFlag pretenure) {
1244 AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1245 Handle<JSFunction> result = New<JSFunction>(map, space);
1246 InitializeFunction(result, info, context);
1251 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1252 Handle<String> name,
1253 MaybeHandle<Code> code) {
1254 Handle<Context> context(isolate()->native_context());
1255 Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1256 DCHECK(is_sloppy(info->language_mode()) &&
1257 (map.is_identical_to(isolate()->sloppy_function_map()) ||
1258 map.is_identical_to(
1259 isolate()->sloppy_function_without_prototype_map()) ||
1260 map.is_identical_to(
1261 isolate()->sloppy_function_with_readonly_prototype_map())));
1262 return NewFunction(map, info, context);
1266 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1268 isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1272 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1273 Handle<Code> code) {
1275 isolate()->sloppy_function_without_prototype_map(), name, code);
1279 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1281 Handle<Object> prototype,
1282 bool read_only_prototype) {
1283 Handle<Map> map = read_only_prototype
1284 ? isolate()->sloppy_function_with_readonly_prototype_map()
1285 : isolate()->sloppy_function_map();
1286 Handle<JSFunction> result = NewFunction(map, name, code);
1287 result->set_prototype_or_initial_map(*prototype);
1292 Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1293 Handle<Object> prototype,
1294 InstanceType type, int instance_size,
1295 bool read_only_prototype,
1296 bool install_constructor) {
1297 // Allocate the function
1298 Handle<JSFunction> function = NewFunction(
1299 name, code, prototype, read_only_prototype);
1301 ElementsKind elements_kind =
1302 type == JS_ARRAY_TYPE ? FAST_SMI_ELEMENTS : FAST_HOLEY_SMI_ELEMENTS;
1303 Handle<Map> initial_map = NewMap(type, instance_size, elements_kind);
1304 if (!function->shared()->is_generator()) {
1305 if (prototype->IsTheHole()) {
1306 prototype = NewFunctionPrototype(function);
1307 } else if (install_constructor) {
1308 JSObject::AddProperty(Handle<JSObject>::cast(prototype),
1309 constructor_string(), function, DONT_ENUM);
1313 JSFunction::SetInitialMap(function, initial_map,
1314 Handle<JSReceiver>::cast(prototype));
1320 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1323 int instance_size) {
1324 return NewFunction(name, code, the_hole_value(), type, instance_size);
1328 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1329 // Make sure to use globals from the function's context, since the function
1330 // can be from a different context.
1331 Handle<Context> native_context(function->context()->native_context());
1332 Handle<Map> new_map;
1333 if (function->shared()->is_generator()) {
1334 // Generator prototypes can share maps since they don't have "constructor"
1336 new_map = handle(native_context->generator_object_prototype_map());
1338 // Each function prototype gets a fresh map to avoid unwanted sharing of
1339 // maps between prototypes of different constructors.
1340 Handle<JSFunction> object_function(native_context->object_function());
1341 DCHECK(object_function->has_initial_map());
1342 new_map = handle(object_function->initial_map());
1345 DCHECK(!new_map->is_prototype_map());
1346 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1348 if (!function->shared()->is_generator()) {
1349 JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1356 static bool ShouldOptimizeNewClosure(Isolate* isolate,
1357 Handle<SharedFunctionInfo> info) {
1358 return isolate->use_crankshaft() && !info->is_toplevel() &&
1359 info->is_compiled() && info->allows_lazy_compilation();
1363 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1364 Handle<SharedFunctionInfo> info,
1365 Handle<Context> context,
1366 PretenureFlag pretenure) {
1368 Context::FunctionMapIndex(info->language_mode(), info->kind());
1369 Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1370 Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1372 if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1373 info->ResetForNewContext(isolate()->heap()->global_ic_age());
1376 int index = info->SearchOptimizedCodeMap(context->native_context(),
1378 if (!info->bound() && index < 0) {
1379 int number_of_literals = info->num_literals();
1380 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1381 if (number_of_literals > 0) {
1382 // Store the native context in the literals array prefix. This
1383 // context will be used when creating object, regexp and array
1384 // literals in this function.
1385 literals->set(JSFunction::kLiteralNativeContextIndex,
1386 context->native_context());
1388 result->set_literals(*literals);
1392 // Caching of optimized code enabled and optimized code found.
1393 FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1394 if (literals != NULL) result->set_literals(literals);
1395 Code* code = info->GetCodeFromOptimizedCodeMap(index);
1396 DCHECK(!code->marked_for_deoptimization());
1397 result->ReplaceCode(code);
1401 if (FLAG_always_opt && ShouldOptimizeNewClosure(isolate(), info)) {
1402 result->MarkForOptimization();
1408 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1409 Handle<FixedArray> array = NewFixedArray(length, TENURED);
1410 array->set_map_no_write_barrier(*scope_info_map());
1411 Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1416 Handle<JSObject> Factory::NewExternal(void* value) {
1417 Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1418 Handle<JSObject> external = NewJSObjectFromMap(external_map());
1419 external->SetInternalField(0, *foreign);
1424 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1425 CALL_HEAP_FUNCTION(isolate(),
1426 isolate()->heap()->AllocateCode(object_size, immovable),
1431 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1433 Handle<Object> self_ref,
1436 int prologue_offset,
1438 Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1439 Handle<ConstantPoolArray> constant_pool =
1440 desc.origin->NewConstantPool(isolate());
1443 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1444 int obj_size = Code::SizeFor(body_size);
1446 Handle<Code> code = NewCodeRaw(obj_size, immovable);
1447 DCHECK(isolate()->code_range() == NULL ||
1448 !isolate()->code_range()->valid() ||
1449 isolate()->code_range()->contains(code->address()));
1451 // The code object has not been fully initialized yet. We rely on the
1452 // fact that no allocation will happen from this point on.
1453 DisallowHeapAllocation no_gc;
1454 code->set_gc_metadata(Smi::FromInt(0));
1455 code->set_ic_age(isolate()->heap()->global_ic_age());
1456 code->set_instruction_size(desc.instr_size);
1457 code->set_relocation_info(*reloc_info);
1458 code->set_flags(flags);
1459 code->set_raw_kind_specific_flags1(0);
1460 code->set_raw_kind_specific_flags2(0);
1461 code->set_is_crankshafted(crankshafted);
1462 code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1463 code->set_raw_type_feedback_info(Smi::FromInt(0));
1464 code->set_next_code_link(*undefined_value());
1465 code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1466 code->set_prologue_offset(prologue_offset);
1467 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1468 code->set_marked_for_deoptimization(false);
1472 DCHECK(code->kind() == Code::FUNCTION);
1473 code->set_has_debug_break_slots(true);
1476 desc.origin->PopulateConstantPool(*constant_pool);
1477 code->set_constant_pool(*constant_pool);
1479 // Allow self references to created code object by patching the handle to
1480 // point to the newly allocated Code object.
1481 if (!self_ref.is_null()) *(self_ref.location()) = *code;
1483 // Migrate generated code.
1484 // The generated code can contain Object** values (typically from handles)
1485 // that are dereferenced during the copy to point directly to the actual heap
1486 // objects. These pointers can include references to the code object itself,
1487 // through the self_reference parameter.
1488 code->CopyFrom(desc);
1491 if (FLAG_verify_heap) code->ObjectVerify();
1497 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1498 CALL_HEAP_FUNCTION(isolate(),
1499 isolate()->heap()->CopyCode(*code),
1504 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1505 CALL_HEAP_FUNCTION(isolate(),
1506 isolate()->heap()->CopyCode(*code, reloc_info),
1511 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1512 PretenureFlag pretenure) {
1513 JSFunction::EnsureHasInitialMap(constructor);
1516 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1520 Handle<JSObject> Factory::NewJSObjectWithMemento(
1521 Handle<JSFunction> constructor,
1522 Handle<AllocationSite> site) {
1523 JSFunction::EnsureHasInitialMap(constructor);
1526 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1531 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1532 Handle<ScopeInfo> scope_info) {
1533 // Allocate a fresh map. Modules do not have a prototype.
1534 Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1535 // Allocate the object based on the map.
1536 Handle<JSModule> module =
1537 Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1538 module->set_context(*context);
1539 module->set_scope_info(*scope_info);
1544 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1545 DCHECK(constructor->has_initial_map());
1546 Handle<Map> map(constructor->initial_map());
1547 DCHECK(map->is_dictionary_map());
1549 // Make sure no field properties are described in the initial map.
1550 // This guarantees us that normalizing the properties does not
1551 // require us to change property values to PropertyCells.
1552 DCHECK(map->NextFreePropertyIndex() == 0);
1554 // Make sure we don't have a ton of pre-allocated slots in the
1555 // global objects. They will be unused once we normalize the object.
1556 DCHECK(map->unused_property_fields() == 0);
1557 DCHECK(map->inobject_properties() == 0);
1559 // Initial size of the backing store to avoid resize of the storage during
1560 // bootstrapping. The size differs between the JS global object ad the
1562 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1564 // Allocate a dictionary object for backing storage.
1565 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1566 Handle<NameDictionary> dictionary =
1567 NameDictionary::New(isolate(), at_least_space_for);
1569 // The global object might be created from an object template with accessors.
1570 // Fill these accessors into the dictionary.
1571 Handle<DescriptorArray> descs(map->instance_descriptors());
1572 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1573 PropertyDetails details = descs->GetDetails(i);
1574 // Only accessors are expected.
1575 DCHECK_EQ(ACCESSOR_CONSTANT, details.type());
1576 PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1);
1577 Handle<Name> name(descs->GetKey(i));
1578 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1579 Handle<PropertyCell> cell = NewPropertyCell(value);
1580 // |dictionary| already contains enough space for all properties.
1581 USE(NameDictionary::Add(dictionary, name, cell, d));
1584 // Allocate the global object and initialize it with the backing store.
1585 Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1586 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1588 // Create a new map for the global object.
1589 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1590 new_map->set_dictionary_map(true);
1592 // Set up the global object as a normalized object.
1593 global->set_map(*new_map);
1594 global->set_properties(*dictionary);
1596 // Make sure result is a global object with properties in dictionary.
1597 DCHECK(global->IsGlobalObject() && !global->HasFastProperties());
1602 Handle<JSObject> Factory::NewJSObjectFromMap(
1604 PretenureFlag pretenure,
1606 Handle<AllocationSite> allocation_site) {
1609 isolate()->heap()->AllocateJSObjectFromMap(
1613 allocation_site.is_null() ? NULL : *allocation_site),
1618 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1619 PretenureFlag pretenure) {
1620 Context* native_context = isolate()->context()->native_context();
1621 JSFunction* array_function = native_context->array_function();
1622 Map* map = array_function->initial_map();
1623 Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1624 if (transition_map != NULL) map = transition_map;
1625 return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1629 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1632 ArrayStorageAllocationMode mode,
1633 PretenureFlag pretenure) {
1634 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1635 NewJSArrayStorage(array, length, capacity, mode);
1640 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1641 ElementsKind elements_kind,
1643 PretenureFlag pretenure) {
1644 DCHECK(length <= elements->length());
1645 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1647 array->set_elements(*elements);
1648 array->set_length(Smi::FromInt(length));
1649 JSObject::ValidateElements(array);
1654 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1657 ArrayStorageAllocationMode mode) {
1658 DCHECK(capacity >= length);
1660 if (capacity == 0) {
1661 array->set_length(Smi::FromInt(0));
1662 array->set_elements(*empty_fixed_array());
1666 HandleScope inner_scope(isolate());
1667 Handle<FixedArrayBase> elms;
1668 ElementsKind elements_kind = array->GetElementsKind();
1669 if (IsFastDoubleElementsKind(elements_kind)) {
1670 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1671 elms = NewFixedDoubleArray(capacity);
1673 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1674 elms = NewFixedDoubleArrayWithHoles(capacity);
1677 DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1678 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1679 elms = NewUninitializedFixedArray(capacity);
1681 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1682 elms = NewFixedArrayWithHoles(capacity);
1686 array->set_elements(*elms);
1687 array->set_length(Smi::FromInt(length));
1691 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1692 Handle<JSFunction> function) {
1693 DCHECK(function->shared()->is_generator());
1694 JSFunction::EnsureHasInitialMap(function);
1695 Handle<Map> map(function->initial_map());
1696 DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1699 isolate()->heap()->AllocateJSObjectFromMap(*map),
1704 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1705 Handle<JSFunction> array_buffer_fun(
1706 isolate()->native_context()->array_buffer_fun());
1709 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1714 Handle<JSDataView> Factory::NewJSDataView() {
1715 Handle<JSFunction> data_view_fun(
1716 isolate()->native_context()->data_view_fun());
1719 isolate()->heap()->AllocateJSObject(*data_view_fun),
1724 Handle<JSMapIterator> Factory::NewJSMapIterator() {
1725 Handle<Map> map(isolate()->native_context()->map_iterator_map());
1726 CALL_HEAP_FUNCTION(isolate(),
1727 isolate()->heap()->AllocateJSObjectFromMap(*map),
1732 Handle<JSSetIterator> Factory::NewJSSetIterator() {
1733 Handle<Map> map(isolate()->native_context()->set_iterator_map());
1734 CALL_HEAP_FUNCTION(isolate(),
1735 isolate()->heap()->AllocateJSObjectFromMap(*map),
1742 ElementsKind GetExternalArrayElementsKind(ExternalArrayType type) {
1744 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1745 case kExternal##Type##Array: \
1746 return EXTERNAL_##TYPE##_ELEMENTS;
1747 TYPED_ARRAYS(TYPED_ARRAY_CASE)
1750 return FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND;
1751 #undef TYPED_ARRAY_CASE
1755 size_t GetExternalArrayElementSize(ExternalArrayType type) {
1757 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1758 case kExternal##Type##Array: \
1760 TYPED_ARRAYS(TYPED_ARRAY_CASE)
1764 #undef TYPED_ARRAY_CASE
1768 JSFunction* GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
1769 Context* native_context = isolate->context()->native_context();
1771 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1772 case kExternal##Type##Array: \
1773 return native_context->type##_array_fun();
1775 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1776 #undef TYPED_ARRAY_FUN
1785 void SetupArrayBufferView(i::Isolate* isolate,
1786 i::Handle<i::JSArrayBufferView> obj,
1787 i::Handle<i::JSArrayBuffer> buffer,
1788 size_t byte_offset, size_t byte_length) {
1789 DCHECK(byte_offset + byte_length <=
1790 static_cast<size_t>(buffer->byte_length()->Number()));
1792 obj->set_buffer(*buffer);
1794 obj->set_weak_next(buffer->weak_first_view());
1795 buffer->set_weak_first_view(*obj);
1797 i::Handle<i::Object> byte_offset_object =
1798 isolate->factory()->NewNumberFromSize(byte_offset);
1799 obj->set_byte_offset(*byte_offset_object);
1801 i::Handle<i::Object> byte_length_object =
1802 isolate->factory()->NewNumberFromSize(byte_length);
1803 obj->set_byte_length(*byte_length_object);
1810 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1811 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1815 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1820 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
1821 Handle<JSArrayBuffer> buffer,
1824 Handle<JSTypedArray> obj = NewJSTypedArray(type);
1826 size_t element_size = GetExternalArrayElementSize(type);
1827 ElementsKind elements_kind = GetExternalArrayElementsKind(type);
1829 CHECK(byte_offset % element_size == 0);
1831 CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
1832 CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
1833 size_t byte_length = length * element_size;
1834 SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1836 Handle<Object> length_object = NewNumberFromSize(length);
1837 obj->set_length(*length_object);
1839 Handle<ExternalArray> elements = NewExternalArray(
1840 static_cast<int>(length), type,
1841 static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
1842 Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
1843 JSObject::SetMapAndElements(obj, map, elements);
1848 Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
1850 size_t byte_length) {
1851 Handle<JSDataView> obj = NewJSDataView();
1852 SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1857 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1858 Handle<Object> prototype) {
1860 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1861 // maps. Will probably depend on the identity of the handler object, too.
1862 Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1863 map->SetPrototype(prototype);
1865 // Allocate the proxy object.
1866 Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1867 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1868 result->set_handler(*handler);
1869 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1874 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1875 Handle<Object> call_trap,
1876 Handle<Object> construct_trap,
1877 Handle<Object> prototype) {
1879 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1880 // maps. Will probably depend on the identity of the handler object, too.
1881 Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1882 map->SetPrototype(prototype);
1884 // Allocate the proxy object.
1885 Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1886 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1887 result->set_handler(*handler);
1888 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1889 result->set_call_trap(*call_trap);
1890 result->set_construct_trap(*construct_trap);
1895 void Factory::ReinitializeJSProxy(Handle<JSProxy> proxy, InstanceType type,
1897 DCHECK(type == JS_OBJECT_TYPE || type == JS_FUNCTION_TYPE);
1899 // Allocate fresh map.
1900 // TODO(rossberg): Once we optimize proxies, cache these maps.
1901 Handle<Map> map = NewMap(type, size);
1903 // Check that the receiver has at least the size of the fresh object.
1904 int size_difference = proxy->map()->instance_size() - map->instance_size();
1905 DCHECK(size_difference >= 0);
1907 map->SetPrototype(handle(proxy->map()->prototype(), proxy->GetIsolate()));
1909 // Allocate the backing storage for the properties.
1910 int prop_size = map->InitialPropertiesLength();
1911 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1913 Heap* heap = isolate()->heap();
1914 MaybeHandle<SharedFunctionInfo> shared;
1915 if (type == JS_FUNCTION_TYPE) {
1916 OneByteStringKey key(STATIC_CHAR_VECTOR("<freezing call trap>"),
1918 Handle<String> name = InternalizeStringWithKey(&key);
1919 shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1922 // In order to keep heap in consistent state there must be no allocations
1923 // before object re-initialization is finished and filler object is installed.
1924 DisallowHeapAllocation no_allocation;
1926 // Put in filler if the new object is smaller than the old.
1927 if (size_difference > 0) {
1928 Address address = proxy->address();
1929 heap->CreateFillerObjectAt(address + map->instance_size(), size_difference);
1930 heap->AdjustLiveBytes(address, -size_difference, Heap::FROM_MUTATOR);
1933 // Reset the map for the object.
1934 proxy->synchronized_set_map(*map);
1935 Handle<JSObject> jsobj = Handle<JSObject>::cast(proxy);
1937 // Reinitialize the object from the constructor map.
1938 heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1940 // The current native context is used to set up certain bits.
1941 // TODO(adamk): Using the current context seems wrong, it should be whatever
1942 // context the JSProxy originated in. But that context isn't stored anywhere.
1943 Handle<Context> context(isolate()->native_context());
1945 // Functions require some minimal initialization.
1946 if (type == JS_FUNCTION_TYPE) {
1947 map->set_function_with_prototype(true);
1948 Handle<JSFunction> js_function = Handle<JSFunction>::cast(proxy);
1949 InitializeFunction(js_function, shared.ToHandleChecked(), context);
1951 // Provide JSObjects with a constructor.
1952 map->set_constructor(context->object_function());
1957 Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy() {
1958 // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
1959 // via ReinitializeJSGlobalProxy later.
1960 Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
1961 // Maintain invariant expected from any JSGlobalProxy.
1962 map->set_is_access_check_needed(true);
1963 CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObjectFromMap(
1964 *map, NOT_TENURED, false),
1969 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1970 Handle<JSFunction> constructor) {
1971 DCHECK(constructor->has_initial_map());
1972 Handle<Map> map(constructor->initial_map(), isolate());
1974 // The proxy's hash should be retained across reinitialization.
1975 Handle<Object> hash(object->hash(), isolate());
1977 // Check that the already allocated object has the same size and type as
1978 // objects allocated using the constructor.
1979 DCHECK(map->instance_size() == object->map()->instance_size());
1980 DCHECK(map->instance_type() == object->map()->instance_type());
1982 // Allocate the backing storage for the properties.
1983 int prop_size = map->InitialPropertiesLength();
1984 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1986 // In order to keep heap in consistent state there must be no allocations
1987 // before object re-initialization is finished.
1988 DisallowHeapAllocation no_allocation;
1990 // Reset the map for the object.
1991 object->synchronized_set_map(*map);
1993 Heap* heap = isolate()->heap();
1994 // Reinitialize the object from the constructor map.
1995 heap->InitializeJSObjectFromMap(*object, *properties, *map);
1997 // Restore the saved hash.
1998 object->set_hash(*hash);
2002 void Factory::BecomeJSObject(Handle<JSProxy> proxy) {
2003 ReinitializeJSProxy(proxy, JS_OBJECT_TYPE, JSObject::kHeaderSize);
2007 void Factory::BecomeJSFunction(Handle<JSProxy> proxy) {
2008 ReinitializeJSProxy(proxy, JS_FUNCTION_TYPE, JSFunction::kSize);
2012 Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(
2013 const FeedbackVectorSpec& spec) {
2014 return TypeFeedbackVector::Allocate(isolate(), spec);
2018 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2019 Handle<String> name, int number_of_literals, FunctionKind kind,
2020 Handle<Code> code, Handle<ScopeInfo> scope_info,
2021 Handle<TypeFeedbackVector> feedback_vector) {
2022 DCHECK(IsValidFunctionKind(kind));
2023 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
2024 shared->set_scope_info(*scope_info);
2025 shared->set_feedback_vector(*feedback_vector);
2026 shared->set_kind(kind);
2027 int literals_array_size = number_of_literals;
2028 // If the function contains object, regexp or array literals,
2029 // allocate extra space for a literals array prefix containing the
2031 if (number_of_literals > 0) {
2032 literals_array_size += JSFunction::kLiteralsPrefixSize;
2034 shared->set_num_literals(literals_array_size);
2035 if (IsGeneratorFunction(kind)) {
2036 shared->set_instance_class_name(isolate()->heap()->Generator_string());
2037 shared->DisableOptimization(kGenerator);
2043 Handle<JSMessageObject> Factory::NewJSMessageObject(
2044 Handle<String> type,
2045 Handle<JSArray> arguments,
2048 Handle<Object> script,
2049 Handle<Object> stack_frames) {
2050 Handle<Map> map = message_object_map();
2051 Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
2052 message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2053 message->initialize_elements();
2054 message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2055 message->set_type(*type);
2056 message->set_arguments(*arguments);
2057 message->set_start_position(start_position);
2058 message->set_end_position(end_position);
2059 message->set_script(*script);
2060 message->set_stack_frames(*stack_frames);
2065 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2066 Handle<String> name,
2067 MaybeHandle<Code> maybe_code) {
2068 Handle<Map> map = shared_function_info_map();
2069 Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map,
2072 // Set pointer fields.
2073 share->set_name(*name);
2075 if (!maybe_code.ToHandle(&code)) {
2076 code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
2078 share->set_code(*code);
2079 share->set_optimized_code_map(Smi::FromInt(0));
2080 share->set_scope_info(ScopeInfo::Empty(isolate()));
2081 Code* construct_stub =
2082 isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2083 share->set_construct_stub(construct_stub);
2084 share->set_instance_class_name(*Object_string());
2085 share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
2086 share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
2087 share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
2088 share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
2089 FeedbackVectorSpec empty_spec;
2090 Handle<TypeFeedbackVector> feedback_vector =
2091 NewTypeFeedbackVector(empty_spec);
2092 share->set_feedback_vector(*feedback_vector, SKIP_WRITE_BARRIER);
2094 share->set_unique_id(isolate()->GetNextUniqueSharedFunctionInfoId());
2096 share->set_profiler_ticks(0);
2097 share->set_ast_node_count(0);
2098 share->set_counters(0);
2100 // Set integer fields (smi or int, depending on the architecture).
2101 share->set_length(0);
2102 share->set_internal_formal_parameter_count(0);
2103 share->set_expected_nof_properties(0);
2104 share->set_num_literals(0);
2105 share->set_start_position_and_type(0);
2106 share->set_end_position(0);
2107 share->set_function_token_position(0);
2108 // All compiler hints default to false or 0.
2109 share->set_compiler_hints(0);
2110 share->set_opt_count_and_bailout_reason(0);
2116 static inline int NumberCacheHash(Handle<FixedArray> cache,
2117 Handle<Object> number) {
2118 int mask = (cache->length() >> 1) - 1;
2119 if (number->IsSmi()) {
2120 return Handle<Smi>::cast(number)->value() & mask;
2122 DoubleRepresentation rep(number->Number());
2124 (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2129 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2130 DisallowHeapAllocation no_gc;
2131 int hash = NumberCacheHash(number_string_cache(), number);
2132 Object* key = number_string_cache()->get(hash * 2);
2133 if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2134 key->Number() == number->Number())) {
2135 return Handle<String>(
2136 String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2138 return undefined_value();
2142 void Factory::SetNumberStringCache(Handle<Object> number,
2143 Handle<String> string) {
2144 int hash = NumberCacheHash(number_string_cache(), number);
2145 if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2146 int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2147 if (number_string_cache()->length() != full_size) {
2148 Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2149 isolate()->heap()->set_number_string_cache(*new_cache);
2153 number_string_cache()->set(hash * 2, *number);
2154 number_string_cache()->set(hash * 2 + 1, *string);
2158 Handle<String> Factory::NumberToString(Handle<Object> number,
2159 bool check_number_string_cache) {
2160 isolate()->counters()->number_to_string_runtime()->Increment();
2161 if (check_number_string_cache) {
2162 Handle<Object> cached = GetNumberStringCache(number);
2163 if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2167 Vector<char> buffer(arr, arraysize(arr));
2169 if (number->IsSmi()) {
2170 int num = Handle<Smi>::cast(number)->value();
2171 str = IntToCString(num, buffer);
2173 double num = Handle<HeapNumber>::cast(number)->value();
2174 str = DoubleToCString(num, buffer);
2177 // We tenure the allocated string since it is referenced from the
2178 // number-string cache which lives in the old space.
2179 Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2180 SetNumberStringCache(number, js_string);
2185 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2186 // Get the original code of the function.
2187 Handle<Code> code(shared->code());
2189 // Create a copy of the code before allocating the debug info object to avoid
2190 // allocation while setting up the debug info object.
2191 Handle<Code> original_code(*Factory::CopyCode(code));
2193 // Allocate initial fixed array for active break points before allocating the
2194 // debug info object to avoid allocation while setting up the debug info
2196 Handle<FixedArray> break_points(
2197 NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2199 // Create and set up the debug info object. Debug info contains function, a
2200 // copy of the original code, the executing code and initial fixed array for
2201 // active break points.
2202 Handle<DebugInfo> debug_info =
2203 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2204 debug_info->set_shared(*shared);
2205 debug_info->set_original_code(*original_code);
2206 debug_info->set_code(*code);
2207 debug_info->set_break_points(*break_points);
2209 // Link debug info to function.
2210 shared->set_debug_info(*debug_info);
2216 Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2218 bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
2219 !callee->is_simple_parameter_list();
2220 Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2221 : isolate()->sloppy_arguments_map();
2223 AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2225 DCHECK(!isolate()->has_pending_exception());
2226 Handle<JSObject> result = NewJSObjectFromMap(map);
2227 Handle<Smi> value(Smi::FromInt(length), isolate());
2228 Object::SetProperty(result, length_string(), value, STRICT).Assert();
2229 if (!strict_mode_callee) {
2230 Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2236 Handle<JSWeakMap> Factory::NewJSWeakMap() {
2237 // TODO(adamk): Currently the map is only created three times per
2238 // isolate. If it's created more often, the map should be moved into the
2239 // strong root list.
2240 Handle<Map> map = NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
2241 return Handle<JSWeakMap>::cast(NewJSObjectFromMap(map));
2245 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2246 int number_of_properties,
2247 bool* is_result_from_cache) {
2248 const int kMapCacheSize = 128;
2250 if (number_of_properties > kMapCacheSize) {
2251 *is_result_from_cache = false;
2252 return Map::Create(isolate(), number_of_properties);
2254 *is_result_from_cache = true;
2255 if (number_of_properties == 0) {
2256 // Reuse the initial map of the Object function if the literal has no
2257 // predeclared properties.
2258 return handle(context->object_function()->initial_map(), isolate());
2260 int cache_index = number_of_properties - 1;
2261 if (context->map_cache()->IsUndefined()) {
2262 // Allocate the new map cache for the native context.
2263 Handle<FixedArray> new_cache = NewFixedArray(kMapCacheSize, TENURED);
2264 context->set_map_cache(*new_cache);
2266 // Check to see whether there is a matching element in the cache.
2267 Handle<FixedArray> cache(FixedArray::cast(context->map_cache()));
2269 Object* result = cache->get(cache_index);
2270 if (result->IsWeakCell()) {
2271 WeakCell* cell = WeakCell::cast(result);
2272 if (!cell->cleared()) {
2273 return handle(Map::cast(cell->value()), isolate());
2277 // Create a new map and add it to the cache.
2278 Handle<Map> map = Map::Create(isolate(), number_of_properties);
2279 Handle<WeakCell> cell = NewWeakCell(map);
2280 cache->set(cache_index, *cell);
2285 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2286 JSRegExp::Type type,
2287 Handle<String> source,
2288 JSRegExp::Flags flags,
2289 Handle<Object> data) {
2290 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2292 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2293 store->set(JSRegExp::kSourceIndex, *source);
2294 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2295 store->set(JSRegExp::kAtomPatternIndex, *data);
2296 regexp->set_data(*store);
2300 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2301 JSRegExp::Type type,
2302 Handle<String> source,
2303 JSRegExp::Flags flags,
2304 int capture_count) {
2305 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2306 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2307 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2308 store->set(JSRegExp::kSourceIndex, *source);
2309 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2310 store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
2311 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2312 store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
2313 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2314 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2315 store->set(JSRegExp::kIrregexpCaptureCountIndex,
2316 Smi::FromInt(capture_count));
2317 regexp->set_data(*store);
2321 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2322 if (String::Equals(name, undefined_string())) return undefined_value();
2323 if (String::Equals(name, nan_string())) return nan_value();
2324 if (String::Equals(name, infinity_string())) return infinity_value();
2325 return Handle<Object>::null();
2329 Handle<Object> Factory::ToBoolean(bool value) {
2330 return value ? true_value() : false_value();
2334 } } // namespace v8::internal