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 return (is_one_byte || is_one_byte_data_in_two_byte_string)
542 ? NewOneByteConsString(length, left, right)
543 : NewTwoByteConsString(length, left, right);
547 MaybeHandle<String> Factory::NewOneByteConsString(int length,
549 Handle<String> right) {
550 return NewRawConsString(cons_one_byte_string_map(), length, left, right);
554 MaybeHandle<String> Factory::NewTwoByteConsString(int length,
556 Handle<String> right) {
557 return NewRawConsString(cons_string_map(), length, left, right);
561 MaybeHandle<String> Factory::NewRawConsString(Handle<Map> map, int length,
563 Handle<String> right) {
564 Handle<ConsString> result = New<ConsString>(map, NEW_SPACE);
566 DisallowHeapAllocation no_gc;
567 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
569 result->set_hash_field(String::kEmptyHashField);
570 result->set_length(length);
571 result->set_first(*left, mode);
572 result->set_second(*right, mode);
577 Handle<String> Factory::NewProperSubString(Handle<String> str,
581 if (FLAG_verify_heap) str->StringVerify();
583 DCHECK(begin > 0 || end < str->length());
585 str = String::Flatten(str);
587 int length = end - begin;
588 if (length <= 0) return empty_string();
590 return LookupSingleCharacterStringFromCode(str->Get(begin));
593 // Optimization for 2-byte strings often used as keys in a decompression
594 // dictionary. Check whether we already have the string in the string
595 // table to prevent creation of many unnecessary strings.
596 uint16_t c1 = str->Get(begin);
597 uint16_t c2 = str->Get(begin + 1);
598 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
601 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
602 if (str->IsOneByteRepresentation()) {
603 Handle<SeqOneByteString> result =
604 NewRawOneByteString(length).ToHandleChecked();
605 uint8_t* dest = result->GetChars();
606 DisallowHeapAllocation no_gc;
607 String::WriteToFlat(*str, dest, begin, end);
610 Handle<SeqTwoByteString> result =
611 NewRawTwoByteString(length).ToHandleChecked();
612 uc16* dest = result->GetChars();
613 DisallowHeapAllocation no_gc;
614 String::WriteToFlat(*str, dest, begin, end);
621 if (str->IsSlicedString()) {
622 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
623 str = Handle<String>(slice->parent(), isolate());
624 offset += slice->offset();
627 DCHECK(str->IsSeqString() || str->IsExternalString());
628 Handle<Map> map = str->IsOneByteRepresentation()
629 ? sliced_one_byte_string_map()
630 : sliced_string_map();
631 Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
633 slice->set_hash_field(String::kEmptyHashField);
634 slice->set_length(length);
635 slice->set_parent(*str);
636 slice->set_offset(offset);
641 MaybeHandle<String> Factory::NewExternalStringFromOneByte(
642 const ExternalOneByteString::Resource* resource) {
643 size_t length = resource->length();
644 if (length > static_cast<size_t>(String::kMaxLength)) {
645 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
648 Handle<Map> map = external_one_byte_string_map();
649 Handle<ExternalOneByteString> external_string =
650 New<ExternalOneByteString>(map, NEW_SPACE);
651 external_string->set_length(static_cast<int>(length));
652 external_string->set_hash_field(String::kEmptyHashField);
653 external_string->set_resource(resource);
655 return external_string;
659 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
660 const ExternalTwoByteString::Resource* resource) {
661 size_t length = resource->length();
662 if (length > static_cast<size_t>(String::kMaxLength)) {
663 THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
666 // For small strings we check whether the resource contains only
667 // one byte characters. If yes, we use a different string map.
668 static const size_t kOneByteCheckLengthLimit = 32;
669 bool is_one_byte = length <= kOneByteCheckLengthLimit &&
670 String::IsOneByte(resource->data(), static_cast<int>(length));
671 Handle<Map> map = is_one_byte ?
672 external_string_with_one_byte_data_map() : external_string_map();
673 Handle<ExternalTwoByteString> external_string =
674 New<ExternalTwoByteString>(map, NEW_SPACE);
675 external_string->set_length(static_cast<int>(length));
676 external_string->set_hash_field(String::kEmptyHashField);
677 external_string->set_resource(resource);
679 return external_string;
683 Handle<Symbol> Factory::NewSymbol() {
686 isolate()->heap()->AllocateSymbol(),
691 Handle<Symbol> Factory::NewPrivateSymbol() {
692 Handle<Symbol> symbol = NewSymbol();
693 symbol->set_is_private(true);
698 Handle<Symbol> Factory::NewPrivateOwnSymbol() {
699 Handle<Symbol> symbol = NewSymbol();
700 symbol->set_is_private(true);
701 symbol->set_is_own(true);
706 Handle<Context> Factory::NewNativeContext() {
707 Handle<FixedArray> array = NewFixedArray(Context::NATIVE_CONTEXT_SLOTS);
708 array->set_map_no_write_barrier(*native_context_map());
709 Handle<Context> context = Handle<Context>::cast(array);
710 context->set_js_array_maps(*undefined_value());
711 DCHECK(context->IsNativeContext());
716 Handle<Context> Factory::NewScriptContext(Handle<JSFunction> function,
717 Handle<ScopeInfo> scope_info) {
718 Handle<FixedArray> array =
719 NewFixedArray(scope_info->ContextLength(), TENURED);
720 array->set_map_no_write_barrier(*script_context_map());
721 Handle<Context> context = Handle<Context>::cast(array);
722 context->set_closure(*function);
723 context->set_previous(function->context());
724 context->set_extension(*scope_info);
725 context->set_global_object(function->context()->global_object());
726 DCHECK(context->IsScriptContext());
731 Handle<ScriptContextTable> Factory::NewScriptContextTable() {
732 Handle<FixedArray> array = NewFixedArray(1);
733 array->set_map_no_write_barrier(*script_context_table_map());
734 Handle<ScriptContextTable> context_table =
735 Handle<ScriptContextTable>::cast(array);
736 context_table->set_used(0);
737 return context_table;
741 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
742 Handle<FixedArray> array =
743 NewFixedArray(scope_info->ContextLength(), TENURED);
744 array->set_map_no_write_barrier(*module_context_map());
745 // Instance link will be set later.
746 Handle<Context> context = Handle<Context>::cast(array);
747 context->set_extension(Smi::FromInt(0));
752 Handle<Context> Factory::NewFunctionContext(int length,
753 Handle<JSFunction> function) {
754 DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
755 Handle<FixedArray> array = NewFixedArray(length);
756 array->set_map_no_write_barrier(*function_context_map());
757 Handle<Context> context = Handle<Context>::cast(array);
758 context->set_closure(*function);
759 context->set_previous(function->context());
760 context->set_extension(Smi::FromInt(0));
761 context->set_global_object(function->context()->global_object());
766 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
767 Handle<Context> previous,
769 Handle<Object> thrown_object) {
770 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
771 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
772 array->set_map_no_write_barrier(*catch_context_map());
773 Handle<Context> context = Handle<Context>::cast(array);
774 context->set_closure(*function);
775 context->set_previous(*previous);
776 context->set_extension(*name);
777 context->set_global_object(previous->global_object());
778 context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
783 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
784 Handle<Context> previous,
785 Handle<JSReceiver> extension) {
786 Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
787 array->set_map_no_write_barrier(*with_context_map());
788 Handle<Context> context = Handle<Context>::cast(array);
789 context->set_closure(*function);
790 context->set_previous(*previous);
791 context->set_extension(*extension);
792 context->set_global_object(previous->global_object());
797 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
798 Handle<Context> previous,
799 Handle<ScopeInfo> scope_info) {
800 Handle<FixedArray> array =
801 NewFixedArrayWithHoles(scope_info->ContextLength());
802 array->set_map_no_write_barrier(*block_context_map());
803 Handle<Context> context = Handle<Context>::cast(array);
804 context->set_closure(*function);
805 context->set_previous(*previous);
806 context->set_extension(*scope_info);
807 context->set_global_object(previous->global_object());
812 Handle<Struct> Factory::NewStruct(InstanceType type) {
815 isolate()->heap()->AllocateStruct(type),
820 Handle<CodeCache> Factory::NewCodeCache() {
821 Handle<CodeCache> code_cache =
822 Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
823 code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
824 code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
829 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
830 int aliased_context_slot) {
831 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
832 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
833 entry->set_aliased_context_slot(aliased_context_slot);
838 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
839 Handle<ExecutableAccessorInfo> info =
840 Handle<ExecutableAccessorInfo>::cast(
841 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
842 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
847 Handle<Script> Factory::NewScript(Handle<String> source) {
848 // Create and initialize script object.
849 Heap* heap = isolate()->heap();
850 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
851 script->set_source(*source);
852 script->set_name(heap->undefined_value());
853 script->set_id(isolate()->heap()->NextScriptId());
854 script->set_line_offset(Smi::FromInt(0));
855 script->set_column_offset(Smi::FromInt(0));
856 script->set_context_data(heap->undefined_value());
857 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
858 script->set_wrapper(heap->undefined_value());
859 script->set_line_ends(heap->undefined_value());
860 script->set_eval_from_shared(heap->undefined_value());
861 script->set_eval_from_instructions_offset(Smi::FromInt(0));
862 script->set_flags(Smi::FromInt(0));
868 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
869 CALL_HEAP_FUNCTION(isolate(),
870 isolate()->heap()->AllocateForeign(addr, pretenure),
875 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
876 return NewForeign((Address) desc, TENURED);
880 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
884 isolate()->heap()->AllocateByteArray(length, pretenure),
889 Handle<ExternalArray> Factory::NewExternalArray(int length,
890 ExternalArrayType array_type,
891 void* external_pointer,
892 PretenureFlag pretenure) {
893 DCHECK(0 <= length && length <= Smi::kMaxValue);
896 isolate()->heap()->AllocateExternalArray(length,
904 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
906 ExternalArrayType array_type,
907 PretenureFlag pretenure) {
908 DCHECK(0 <= length && length <= Smi::kMaxValue);
911 isolate()->heap()->AllocateFixedTypedArray(length,
914 FixedTypedArrayBase);
918 Handle<Cell> Factory::NewCell(Handle<Object> value) {
919 AllowDeferredHandleDereference convert_to_cell;
922 isolate()->heap()->AllocateCell(*value),
927 Handle<PropertyCell> Factory::NewPropertyCell() {
930 isolate()->heap()->AllocatePropertyCell(),
935 Handle<WeakCell> Factory::NewWeakCell(Handle<HeapObject> value) {
936 AllowDeferredHandleDereference convert_to_cell;
937 CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateWeakCell(*value),
942 Handle<AllocationSite> Factory::NewAllocationSite() {
943 Handle<Map> map = allocation_site_map();
944 Handle<AllocationSite> site = New<AllocationSite>(map, OLD_POINTER_SPACE);
948 site->set_weak_next(isolate()->heap()->allocation_sites_list());
949 isolate()->heap()->set_allocation_sites_list(*site);
954 Handle<Map> Factory::NewMap(InstanceType type,
956 ElementsKind elements_kind) {
959 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
964 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
965 CALL_HEAP_FUNCTION(isolate(),
966 isolate()->heap()->CopyJSObject(*object, NULL),
971 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
972 Handle<JSObject> object,
973 Handle<AllocationSite> site) {
974 CALL_HEAP_FUNCTION(isolate(),
975 isolate()->heap()->CopyJSObject(
977 site.is_null() ? NULL : *site),
982 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
984 CALL_HEAP_FUNCTION(isolate(),
985 isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
990 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
991 CALL_HEAP_FUNCTION(isolate(),
992 isolate()->heap()->CopyFixedArray(*array),
997 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
998 Handle<FixedArray> array) {
999 DCHECK(isolate()->heap()->InNewSpace(*array));
1000 CALL_HEAP_FUNCTION(isolate(),
1001 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
1006 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
1007 Handle<FixedDoubleArray> array) {
1008 CALL_HEAP_FUNCTION(isolate(),
1009 isolate()->heap()->CopyFixedDoubleArray(*array),
1014 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
1015 Handle<ConstantPoolArray> array) {
1016 CALL_HEAP_FUNCTION(isolate(),
1017 isolate()->heap()->CopyConstantPoolArray(*array),
1022 Handle<Object> Factory::NewNumber(double value,
1023 PretenureFlag pretenure) {
1024 // We need to distinguish the minus zero value and this cannot be
1025 // done after conversion to int. Doing this by comparing bit
1026 // patterns is faster than using fpclassify() et al.
1027 if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1029 int int_value = FastD2IChecked(value);
1030 if (value == int_value && Smi::IsValid(int_value)) {
1031 return handle(Smi::FromInt(int_value), isolate());
1034 // Materialize the value in the heap.
1035 return NewHeapNumber(value, IMMUTABLE, pretenure);
1039 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1040 PretenureFlag pretenure) {
1041 if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1042 // Bypass NewNumber to avoid various redundant checks.
1043 return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1047 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1048 PretenureFlag pretenure) {
1049 int32_t int32v = static_cast<int32_t>(value);
1050 if (int32v >= 0 && Smi::IsValid(int32v)) {
1051 return handle(Smi::FromInt(int32v), isolate());
1053 return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1057 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1059 PretenureFlag pretenure) {
1062 isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
1067 Handle<Object> Factory::NewTypeError(const char* message,
1068 Vector<Handle<Object> > args) {
1069 return NewError("MakeTypeError", message, args);
1073 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1074 return NewError("$TypeError", message);
1078 Handle<Object> Factory::NewRangeError(const char* message,
1079 Vector<Handle<Object> > args) {
1080 return NewError("MakeRangeError", message, args);
1084 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1085 return NewError("$RangeError", message);
1089 Handle<Object> Factory::NewSyntaxError(const char* message,
1090 Handle<JSArray> args) {
1091 return NewError("MakeSyntaxError", message, args);
1095 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1096 return NewError("$SyntaxError", message);
1100 Handle<Object> Factory::NewReferenceError(const char* message,
1101 Vector<Handle<Object> > args) {
1102 return NewError("MakeReferenceError", message, args);
1106 Handle<Object> Factory::NewReferenceError(const char* message,
1107 Handle<JSArray> args) {
1108 return NewError("MakeReferenceError", message, args);
1112 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1113 return NewError("$ReferenceError", message);
1117 Handle<Object> Factory::NewError(const char* maker, const char* message,
1118 Vector<Handle<Object> > args) {
1119 // Instantiate a closeable HandleScope for EscapeFrom.
1120 v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1121 Handle<FixedArray> array = NewFixedArray(args.length());
1122 for (int i = 0; i < args.length(); i++) {
1123 array->set(i, *args[i]);
1125 Handle<JSArray> object = NewJSArrayWithElements(array);
1126 Handle<Object> result = NewError(maker, message, object);
1127 return result.EscapeFrom(&scope);
1131 Handle<Object> Factory::NewEvalError(const char* message,
1132 Vector<Handle<Object> > args) {
1133 return NewError("MakeEvalError", message, args);
1137 Handle<Object> Factory::NewError(const char* message,
1138 Vector<Handle<Object> > args) {
1139 return NewError("MakeError", message, args);
1143 Handle<String> Factory::EmergencyNewError(const char* message,
1144 Handle<JSArray> args) {
1145 const int kBufferSize = 1000;
1146 char buffer[kBufferSize];
1147 size_t space = kBufferSize;
1148 char* p = &buffer[0];
1150 Vector<char> v(buffer, kBufferSize);
1151 StrNCpy(v, message, space);
1152 space -= Min(space, strlen(message));
1153 p = &buffer[kBufferSize] - space;
1155 for (int i = 0; i < Smi::cast(args->length())->value(); i++) {
1160 Handle<String> arg_str = Handle<String>::cast(
1161 Object::GetElement(isolate(), args, i).ToHandleChecked());
1162 SmartArrayPointer<char> arg = arg_str->ToCString();
1163 Vector<char> v2(p, static_cast<int>(space));
1164 StrNCpy(v2, arg.get(), space);
1165 space -= Min(space, strlen(arg.get()));
1166 p = &buffer[kBufferSize] - space;
1173 buffer[kBufferSize - 1] = '\0';
1175 return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1179 Handle<Object> Factory::NewError(const char* maker, const char* message,
1180 Handle<JSArray> args) {
1181 Handle<String> make_str = InternalizeUtf8String(maker);
1182 Handle<Object> fun_obj = Object::GetProperty(
1183 isolate()->js_builtins_object(), make_str).ToHandleChecked();
1184 // If the builtins haven't been properly configured yet this error
1185 // constructor may not have been defined. Bail out.
1186 if (!fun_obj->IsJSFunction()) {
1187 return EmergencyNewError(message, args);
1189 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1190 Handle<Object> message_obj = InternalizeUtf8String(message);
1191 Handle<Object> argv[] = { message_obj, args };
1193 // Invoke the JavaScript factory method. If an exception is thrown while
1194 // running the factory method, use the exception as the result.
1195 Handle<Object> result;
1196 MaybeHandle<Object> exception;
1197 if (!Execution::TryCall(fun,
1198 isolate()->js_builtins_object(),
1201 &exception).ToHandle(&result)) {
1202 Handle<Object> exception_obj;
1203 if (exception.ToHandle(&exception_obj)) return exception_obj;
1204 return undefined_value();
1210 Handle<Object> Factory::NewError(Handle<String> message) {
1211 return NewError("$Error", message);
1215 Handle<Object> Factory::NewError(const char* constructor,
1216 Handle<String> message) {
1217 Handle<String> constr = InternalizeUtf8String(constructor);
1218 Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1219 isolate()->js_builtins_object(), constr).ToHandleChecked());
1220 Handle<Object> argv[] = { message };
1222 // Invoke the JavaScript factory method. If an exception is thrown while
1223 // running the factory method, use the exception as the result.
1224 Handle<Object> result;
1225 MaybeHandle<Object> exception;
1226 if (!Execution::TryCall(fun,
1227 isolate()->js_builtins_object(),
1230 &exception).ToHandle(&result)) {
1231 Handle<Object> exception_obj;
1232 if (exception.ToHandle(&exception_obj)) return exception_obj;
1233 return undefined_value();
1239 void Factory::InitializeFunction(Handle<JSFunction> function,
1240 Handle<SharedFunctionInfo> info,
1241 Handle<Context> context) {
1242 function->initialize_properties();
1243 function->initialize_elements();
1244 function->set_shared(*info);
1245 function->set_code(info->code());
1246 function->set_context(*context);
1247 function->set_prototype_or_initial_map(*the_hole_value());
1248 function->set_literals_or_bindings(*empty_fixed_array());
1249 function->set_next_function_link(*undefined_value());
1253 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1254 Handle<SharedFunctionInfo> info,
1255 Handle<Context> context,
1256 PretenureFlag pretenure) {
1257 AllocationSpace space = pretenure == TENURED ? OLD_POINTER_SPACE : NEW_SPACE;
1258 Handle<JSFunction> result = New<JSFunction>(map, space);
1259 InitializeFunction(result, info, context);
1264 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1265 Handle<String> name,
1266 MaybeHandle<Code> code) {
1267 Handle<Context> context(isolate()->native_context());
1268 Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1269 DCHECK(is_sloppy(info->language_mode()) &&
1270 (map.is_identical_to(isolate()->sloppy_function_map()) ||
1271 map.is_identical_to(
1272 isolate()->sloppy_function_without_prototype_map()) ||
1273 map.is_identical_to(
1274 isolate()->sloppy_function_with_readonly_prototype_map())));
1275 return NewFunction(map, info, context);
1279 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1281 isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1285 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1286 Handle<Code> code) {
1288 isolate()->sloppy_function_without_prototype_map(), name, code);
1292 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1294 Handle<Object> prototype,
1295 bool read_only_prototype) {
1296 Handle<Map> map = read_only_prototype
1297 ? isolate()->sloppy_function_with_readonly_prototype_map()
1298 : isolate()->sloppy_function_map();
1299 Handle<JSFunction> result = NewFunction(map, name, code);
1300 result->set_prototype_or_initial_map(*prototype);
1305 Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1306 Handle<Object> prototype,
1307 InstanceType type, int instance_size,
1308 bool read_only_prototype,
1309 bool install_constructor) {
1310 // Allocate the function
1311 Handle<JSFunction> function = NewFunction(
1312 name, code, prototype, read_only_prototype);
1314 ElementsKind elements_kind =
1315 type == JS_ARRAY_TYPE ? FAST_SMI_ELEMENTS : FAST_HOLEY_SMI_ELEMENTS;
1316 Handle<Map> initial_map = NewMap(type, instance_size, elements_kind);
1317 if (!function->shared()->is_generator()) {
1318 if (prototype->IsTheHole()) {
1319 prototype = NewFunctionPrototype(function);
1320 } else if (install_constructor) {
1321 JSObject::AddProperty(Handle<JSObject>::cast(prototype),
1322 constructor_string(), function, DONT_ENUM);
1326 JSFunction::SetInitialMap(function, initial_map,
1327 Handle<JSReceiver>::cast(prototype));
1333 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1336 int instance_size) {
1337 return NewFunction(name, code, the_hole_value(), type, instance_size);
1341 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1342 // Make sure to use globals from the function's context, since the function
1343 // can be from a different context.
1344 Handle<Context> native_context(function->context()->native_context());
1345 Handle<Map> new_map;
1346 if (function->shared()->is_generator()) {
1347 // Generator prototypes can share maps since they don't have "constructor"
1349 new_map = handle(native_context->generator_object_prototype_map());
1351 // Each function prototype gets a fresh map to avoid unwanted sharing of
1352 // maps between prototypes of different constructors.
1353 Handle<JSFunction> object_function(native_context->object_function());
1354 DCHECK(object_function->has_initial_map());
1355 new_map = handle(object_function->initial_map());
1358 DCHECK(!new_map->is_prototype_map());
1359 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1361 if (!function->shared()->is_generator()) {
1362 JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1369 static bool ShouldOptimizeNewClosure(Handle<SharedFunctionInfo> info) {
1370 return !info->is_toplevel() && info->allows_lazy_compilation();
1374 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1375 Handle<SharedFunctionInfo> info,
1376 Handle<Context> context,
1377 PretenureFlag pretenure) {
1379 Context::FunctionMapIndex(info->language_mode(), info->kind());
1380 Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1381 Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1383 if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1384 info->ResetForNewContext(isolate()->heap()->global_ic_age());
1387 int index = info->SearchOptimizedCodeMap(context->native_context(),
1389 if (!info->bound() && index < 0) {
1390 int number_of_literals = info->num_literals();
1391 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1392 result->set_literals(*literals);
1396 // Caching of optimized code enabled and optimized code found.
1397 FixedArray* literals = info->GetLiteralsFromOptimizedCodeMap(index);
1398 if (literals != NULL) result->set_literals(literals);
1399 Code* code = info->GetCodeFromOptimizedCodeMap(index);
1400 DCHECK(!code->marked_for_deoptimization());
1401 result->ReplaceCode(code);
1405 if (FLAG_always_opt && ShouldOptimizeNewClosure(info)) {
1406 result->MarkForOptimization();
1412 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1413 Handle<FixedArray> array = NewFixedArray(length, TENURED);
1414 array->set_map_no_write_barrier(*scope_info_map());
1415 Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1420 Handle<JSObject> Factory::NewExternal(void* value) {
1421 Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1422 Handle<JSObject> external = NewJSObjectFromMap(external_map());
1423 external->SetInternalField(0, *foreign);
1428 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1429 CALL_HEAP_FUNCTION(isolate(),
1430 isolate()->heap()->AllocateCode(object_size, immovable),
1435 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1437 Handle<Object> self_ref,
1440 int prologue_offset,
1442 Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1443 Handle<ConstantPoolArray> constant_pool =
1444 desc.origin->NewConstantPool(isolate());
1447 int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1448 int obj_size = Code::SizeFor(body_size);
1450 Handle<Code> code = NewCodeRaw(obj_size, immovable);
1451 DCHECK(isolate()->code_range() == NULL ||
1452 !isolate()->code_range()->valid() ||
1453 isolate()->code_range()->contains(code->address()));
1455 // The code object has not been fully initialized yet. We rely on the
1456 // fact that no allocation will happen from this point on.
1457 DisallowHeapAllocation no_gc;
1458 code->set_gc_metadata(Smi::FromInt(0));
1459 code->set_ic_age(isolate()->heap()->global_ic_age());
1460 code->set_instruction_size(desc.instr_size);
1461 code->set_relocation_info(*reloc_info);
1462 code->set_flags(flags);
1463 code->set_raw_kind_specific_flags1(0);
1464 code->set_raw_kind_specific_flags2(0);
1465 code->set_is_crankshafted(crankshafted);
1466 code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1467 code->set_raw_type_feedback_info(Smi::FromInt(0));
1468 code->set_next_code_link(*undefined_value());
1469 code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1470 code->set_prologue_offset(prologue_offset);
1471 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1472 code->set_marked_for_deoptimization(false);
1476 DCHECK(code->kind() == Code::FUNCTION);
1477 code->set_has_debug_break_slots(true);
1480 desc.origin->PopulateConstantPool(*constant_pool);
1481 code->set_constant_pool(*constant_pool);
1483 // Allow self references to created code object by patching the handle to
1484 // point to the newly allocated Code object.
1485 if (!self_ref.is_null()) *(self_ref.location()) = *code;
1487 // Migrate generated code.
1488 // The generated code can contain Object** values (typically from handles)
1489 // that are dereferenced during the copy to point directly to the actual heap
1490 // objects. These pointers can include references to the code object itself,
1491 // through the self_reference parameter.
1492 code->CopyFrom(desc);
1495 if (FLAG_verify_heap) code->ObjectVerify();
1501 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1502 CALL_HEAP_FUNCTION(isolate(),
1503 isolate()->heap()->CopyCode(*code),
1508 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1509 CALL_HEAP_FUNCTION(isolate(),
1510 isolate()->heap()->CopyCode(*code, reloc_info),
1515 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1516 PretenureFlag pretenure) {
1517 JSFunction::EnsureHasInitialMap(constructor);
1520 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1524 Handle<JSObject> Factory::NewJSObjectWithMemento(
1525 Handle<JSFunction> constructor,
1526 Handle<AllocationSite> site) {
1527 JSFunction::EnsureHasInitialMap(constructor);
1530 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1535 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1536 Handle<ScopeInfo> scope_info) {
1537 // Allocate a fresh map. Modules do not have a prototype.
1538 Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1539 // Allocate the object based on the map.
1540 Handle<JSModule> module =
1541 Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1542 module->set_context(*context);
1543 module->set_scope_info(*scope_info);
1548 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1549 DCHECK(constructor->has_initial_map());
1550 Handle<Map> map(constructor->initial_map());
1551 DCHECK(map->is_dictionary_map());
1553 // Make sure no field properties are described in the initial map.
1554 // This guarantees us that normalizing the properties does not
1555 // require us to change property values to PropertyCells.
1556 DCHECK(map->NextFreePropertyIndex() == 0);
1558 // Make sure we don't have a ton of pre-allocated slots in the
1559 // global objects. They will be unused once we normalize the object.
1560 DCHECK(map->unused_property_fields() == 0);
1561 DCHECK(map->inobject_properties() == 0);
1563 // Initial size of the backing store to avoid resize of the storage during
1564 // bootstrapping. The size differs between the JS global object ad the
1566 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1568 // Allocate a dictionary object for backing storage.
1569 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1570 Handle<NameDictionary> dictionary =
1571 NameDictionary::New(isolate(), at_least_space_for);
1573 // The global object might be created from an object template with accessors.
1574 // Fill these accessors into the dictionary.
1575 Handle<DescriptorArray> descs(map->instance_descriptors());
1576 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1577 PropertyDetails details = descs->GetDetails(i);
1578 // Only accessors are expected.
1579 DCHECK_EQ(ACCESSOR_CONSTANT, details.type());
1580 PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
1581 PropertyCellType::kMutable);
1582 Handle<Name> name(descs->GetKey(i));
1583 Handle<PropertyCell> cell = NewPropertyCell();
1584 cell->set_value(descs->GetCallbacksObject(i));
1585 // |dictionary| already contains enough space for all properties.
1586 USE(NameDictionary::Add(dictionary, name, cell, d));
1589 // Allocate the global object and initialize it with the backing store.
1590 Handle<GlobalObject> global = New<GlobalObject>(map, OLD_POINTER_SPACE);
1591 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1593 // Create a new map for the global object.
1594 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1595 new_map->set_dictionary_map(true);
1597 // Set up the global object as a normalized object.
1598 global->set_map(*new_map);
1599 global->set_properties(*dictionary);
1601 // Make sure result is a global object with properties in dictionary.
1602 DCHECK(global->IsGlobalObject() && !global->HasFastProperties());
1607 Handle<JSObject> Factory::NewJSObjectFromMap(
1609 PretenureFlag pretenure,
1611 Handle<AllocationSite> allocation_site) {
1614 isolate()->heap()->AllocateJSObjectFromMap(
1618 allocation_site.is_null() ? NULL : *allocation_site),
1623 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1624 PretenureFlag pretenure) {
1625 Context* native_context = isolate()->context()->native_context();
1626 JSFunction* array_function = native_context->array_function();
1627 Map* map = array_function->initial_map();
1628 Map* transition_map = isolate()->get_initial_js_array_map(elements_kind);
1629 if (transition_map != NULL) map = transition_map;
1630 return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1634 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1637 ArrayStorageAllocationMode mode,
1638 PretenureFlag pretenure) {
1639 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1640 NewJSArrayStorage(array, length, capacity, mode);
1645 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1646 ElementsKind elements_kind,
1648 PretenureFlag pretenure) {
1649 DCHECK(length <= elements->length());
1650 Handle<JSArray> array = NewJSArray(elements_kind, pretenure);
1652 array->set_elements(*elements);
1653 array->set_length(Smi::FromInt(length));
1654 JSObject::ValidateElements(array);
1659 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1662 ArrayStorageAllocationMode mode) {
1663 DCHECK(capacity >= length);
1665 if (capacity == 0) {
1666 array->set_length(Smi::FromInt(0));
1667 array->set_elements(*empty_fixed_array());
1671 HandleScope inner_scope(isolate());
1672 Handle<FixedArrayBase> elms;
1673 ElementsKind elements_kind = array->GetElementsKind();
1674 if (IsFastDoubleElementsKind(elements_kind)) {
1675 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1676 elms = NewFixedDoubleArray(capacity);
1678 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1679 elms = NewFixedDoubleArrayWithHoles(capacity);
1682 DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1683 if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1684 elms = NewUninitializedFixedArray(capacity);
1686 DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1687 elms = NewFixedArrayWithHoles(capacity);
1691 array->set_elements(*elms);
1692 array->set_length(Smi::FromInt(length));
1696 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1697 Handle<JSFunction> function) {
1698 DCHECK(function->shared()->is_generator());
1699 JSFunction::EnsureHasInitialMap(function);
1700 Handle<Map> map(function->initial_map());
1701 DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1704 isolate()->heap()->AllocateJSObjectFromMap(*map),
1709 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1710 Handle<JSFunction> array_buffer_fun(
1711 isolate()->native_context()->array_buffer_fun());
1714 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1719 Handle<JSDataView> Factory::NewJSDataView() {
1720 Handle<JSFunction> data_view_fun(
1721 isolate()->native_context()->data_view_fun());
1724 isolate()->heap()->AllocateJSObject(*data_view_fun),
1729 Handle<JSMapIterator> Factory::NewJSMapIterator() {
1730 Handle<Map> map(isolate()->native_context()->map_iterator_map());
1731 CALL_HEAP_FUNCTION(isolate(),
1732 isolate()->heap()->AllocateJSObjectFromMap(*map),
1737 Handle<JSSetIterator> Factory::NewJSSetIterator() {
1738 Handle<Map> map(isolate()->native_context()->set_iterator_map());
1739 CALL_HEAP_FUNCTION(isolate(),
1740 isolate()->heap()->AllocateJSObjectFromMap(*map),
1747 ElementsKind GetExternalArrayElementsKind(ExternalArrayType type) {
1749 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1750 case kExternal##Type##Array: \
1751 return EXTERNAL_##TYPE##_ELEMENTS;
1752 TYPED_ARRAYS(TYPED_ARRAY_CASE)
1755 return FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND;
1756 #undef TYPED_ARRAY_CASE
1760 size_t GetExternalArrayElementSize(ExternalArrayType type) {
1762 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1763 case kExternal##Type##Array: \
1765 TYPED_ARRAYS(TYPED_ARRAY_CASE)
1769 #undef TYPED_ARRAY_CASE
1773 JSFunction* GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
1774 Context* native_context = isolate->context()->native_context();
1776 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1777 case kExternal##Type##Array: \
1778 return native_context->type##_array_fun();
1780 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1781 #undef TYPED_ARRAY_FUN
1790 void SetupArrayBufferView(i::Isolate* isolate,
1791 i::Handle<i::JSArrayBufferView> obj,
1792 i::Handle<i::JSArrayBuffer> buffer,
1793 size_t byte_offset, size_t byte_length) {
1794 DCHECK(byte_offset + byte_length <=
1795 static_cast<size_t>(buffer->byte_length()->Number()));
1797 obj->set_buffer(*buffer);
1799 Heap* heap = isolate->heap();
1800 if (heap->InNewSpace(*obj)) {
1801 obj->set_weak_next(heap->new_array_buffer_views_list());
1802 heap->set_new_array_buffer_views_list(*obj);
1804 obj->set_weak_next(buffer->weak_first_view());
1805 buffer->set_weak_first_view(*obj);
1808 i::Handle<i::Object> byte_offset_object =
1809 isolate->factory()->NewNumberFromSize(byte_offset);
1810 obj->set_byte_offset(*byte_offset_object);
1812 i::Handle<i::Object> byte_length_object =
1813 isolate->factory()->NewNumberFromSize(byte_length);
1814 obj->set_byte_length(*byte_length_object);
1821 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1822 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1826 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1831 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
1832 Handle<JSArrayBuffer> buffer,
1835 Handle<JSTypedArray> obj = NewJSTypedArray(type);
1837 size_t element_size = GetExternalArrayElementSize(type);
1838 ElementsKind elements_kind = GetExternalArrayElementsKind(type);
1840 CHECK(byte_offset % element_size == 0);
1842 CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
1843 CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
1844 size_t byte_length = length * element_size;
1845 SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1847 Handle<Object> length_object = NewNumberFromSize(length);
1848 obj->set_length(*length_object);
1850 Handle<ExternalArray> elements = NewExternalArray(
1851 static_cast<int>(length), type,
1852 static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
1853 Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
1854 JSObject::SetMapAndElements(obj, map, elements);
1859 Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
1861 size_t byte_length) {
1862 Handle<JSDataView> obj = NewJSDataView();
1863 SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1868 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1869 Handle<Object> prototype) {
1871 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1872 // maps. Will probably depend on the identity of the handler object, too.
1873 Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1874 map->SetPrototype(prototype);
1876 // Allocate the proxy object.
1877 Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1878 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1879 result->set_handler(*handler);
1880 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1885 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1886 Handle<Object> call_trap,
1887 Handle<Object> construct_trap,
1888 Handle<Object> prototype) {
1890 // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1891 // maps. Will probably depend on the identity of the handler object, too.
1892 Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1893 map->SetPrototype(prototype);
1895 // Allocate the proxy object.
1896 Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1897 result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1898 result->set_handler(*handler);
1899 result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1900 result->set_call_trap(*call_trap);
1901 result->set_construct_trap(*construct_trap);
1906 void Factory::ReinitializeJSProxy(Handle<JSProxy> proxy, InstanceType type,
1908 DCHECK(type == JS_OBJECT_TYPE || type == JS_FUNCTION_TYPE);
1910 // Allocate fresh map.
1911 // TODO(rossberg): Once we optimize proxies, cache these maps.
1912 Handle<Map> map = NewMap(type, size);
1914 // Check that the receiver has at least the size of the fresh object.
1915 int size_difference = proxy->map()->instance_size() - map->instance_size();
1916 DCHECK(size_difference >= 0);
1918 map->SetPrototype(handle(proxy->map()->prototype(), proxy->GetIsolate()));
1920 // Allocate the backing storage for the properties.
1921 int prop_size = map->InitialPropertiesLength();
1922 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1924 Heap* heap = isolate()->heap();
1925 MaybeHandle<SharedFunctionInfo> shared;
1926 if (type == JS_FUNCTION_TYPE) {
1927 OneByteStringKey key(STATIC_CHAR_VECTOR("<freezing call trap>"),
1929 Handle<String> name = InternalizeStringWithKey(&key);
1930 shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
1933 // In order to keep heap in consistent state there must be no allocations
1934 // before object re-initialization is finished and filler object is installed.
1935 DisallowHeapAllocation no_allocation;
1937 // Put in filler if the new object is smaller than the old.
1938 if (size_difference > 0) {
1939 Address address = proxy->address();
1940 heap->CreateFillerObjectAt(address + map->instance_size(), size_difference);
1941 heap->AdjustLiveBytes(address, -size_difference, Heap::FROM_MUTATOR);
1944 // Reset the map for the object.
1945 proxy->synchronized_set_map(*map);
1946 Handle<JSObject> jsobj = Handle<JSObject>::cast(proxy);
1948 // Reinitialize the object from the constructor map.
1949 heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
1951 // The current native context is used to set up certain bits.
1952 // TODO(adamk): Using the current context seems wrong, it should be whatever
1953 // context the JSProxy originated in. But that context isn't stored anywhere.
1954 Handle<Context> context(isolate()->native_context());
1956 // Functions require some minimal initialization.
1957 if (type == JS_FUNCTION_TYPE) {
1958 map->set_function_with_prototype(true);
1959 Handle<JSFunction> js_function = Handle<JSFunction>::cast(proxy);
1960 InitializeFunction(js_function, shared.ToHandleChecked(), context);
1962 // Provide JSObjects with a constructor.
1963 map->SetConstructor(context->object_function());
1968 Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy() {
1969 // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
1970 // via ReinitializeJSGlobalProxy later.
1971 Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
1972 // Maintain invariant expected from any JSGlobalProxy.
1973 map->set_is_access_check_needed(true);
1974 CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateJSObjectFromMap(
1975 *map, NOT_TENURED, false),
1980 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
1981 Handle<JSFunction> constructor) {
1982 DCHECK(constructor->has_initial_map());
1983 Handle<Map> map(constructor->initial_map(), isolate());
1985 // The proxy's hash should be retained across reinitialization.
1986 Handle<Object> hash(object->hash(), isolate());
1988 // Check that the already allocated object has the same size and type as
1989 // objects allocated using the constructor.
1990 DCHECK(map->instance_size() == object->map()->instance_size());
1991 DCHECK(map->instance_type() == object->map()->instance_type());
1993 // Allocate the backing storage for the properties.
1994 int prop_size = map->InitialPropertiesLength();
1995 Handle<FixedArray> properties = NewFixedArray(prop_size, TENURED);
1997 // In order to keep heap in consistent state there must be no allocations
1998 // before object re-initialization is finished.
1999 DisallowHeapAllocation no_allocation;
2001 // Reset the map for the object.
2002 object->synchronized_set_map(*map);
2004 Heap* heap = isolate()->heap();
2005 // Reinitialize the object from the constructor map.
2006 heap->InitializeJSObjectFromMap(*object, *properties, *map);
2008 // Restore the saved hash.
2009 object->set_hash(*hash);
2013 void Factory::BecomeJSObject(Handle<JSProxy> proxy) {
2014 ReinitializeJSProxy(proxy, JS_OBJECT_TYPE, JSObject::kHeaderSize);
2018 void Factory::BecomeJSFunction(Handle<JSProxy> proxy) {
2019 ReinitializeJSProxy(proxy, JS_FUNCTION_TYPE, JSFunction::kSize);
2023 template Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(
2024 const ZoneFeedbackVectorSpec* spec);
2025 template Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(
2026 const FeedbackVectorSpec* spec);
2028 template <typename Spec>
2029 Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(const Spec* spec) {
2030 return TypeFeedbackVector::Allocate<Spec>(isolate(), spec);
2034 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2035 Handle<String> name, int number_of_literals, FunctionKind kind,
2036 Handle<Code> code, Handle<ScopeInfo> scope_info,
2037 Handle<TypeFeedbackVector> feedback_vector) {
2038 DCHECK(IsValidFunctionKind(kind));
2039 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
2040 shared->set_scope_info(*scope_info);
2041 shared->set_feedback_vector(*feedback_vector);
2042 shared->set_kind(kind);
2043 shared->set_num_literals(number_of_literals);
2044 if (IsGeneratorFunction(kind)) {
2045 shared->set_instance_class_name(isolate()->heap()->Generator_string());
2046 shared->DisableOptimization(kGenerator);
2052 Handle<JSMessageObject> Factory::NewJSMessageObject(
2053 Handle<String> type,
2054 Handle<JSArray> arguments,
2057 Handle<Object> script,
2058 Handle<Object> stack_frames) {
2059 Handle<Map> map = message_object_map();
2060 Handle<JSMessageObject> message = New<JSMessageObject>(map, NEW_SPACE);
2061 message->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2062 message->initialize_elements();
2063 message->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2064 message->set_type(*type);
2065 message->set_arguments(*arguments);
2066 message->set_start_position(start_position);
2067 message->set_end_position(end_position);
2068 message->set_script(*script);
2069 message->set_stack_frames(*stack_frames);
2074 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2075 Handle<String> name,
2076 MaybeHandle<Code> maybe_code) {
2077 Handle<Map> map = shared_function_info_map();
2078 Handle<SharedFunctionInfo> share =
2079 New<SharedFunctionInfo>(map, OLD_POINTER_SPACE);
2081 // Set pointer fields.
2082 share->set_name(*name);
2084 if (!maybe_code.ToHandle(&code)) {
2085 code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
2087 share->set_code(*code);
2088 share->set_optimized_code_map(Smi::FromInt(0));
2089 share->set_scope_info(ScopeInfo::Empty(isolate()));
2090 Code* construct_stub =
2091 isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2092 share->set_construct_stub(construct_stub);
2093 share->set_instance_class_name(*Object_string());
2094 share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
2095 share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
2096 share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
2097 share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
2098 FeedbackVectorSpec empty_spec(0);
2099 Handle<TypeFeedbackVector> feedback_vector =
2100 NewTypeFeedbackVector(&empty_spec);
2101 share->set_feedback_vector(*feedback_vector, SKIP_WRITE_BARRIER);
2103 share->set_unique_id(isolate()->GetNextUniqueSharedFunctionInfoId());
2105 share->set_profiler_ticks(0);
2106 share->set_ast_node_count(0);
2107 share->set_counters(0);
2109 // Set integer fields (smi or int, depending on the architecture).
2110 share->set_length(0);
2111 share->set_internal_formal_parameter_count(0);
2112 share->set_expected_nof_properties(0);
2113 share->set_num_literals(0);
2114 share->set_start_position_and_type(0);
2115 share->set_end_position(0);
2116 share->set_function_token_position(0);
2117 // All compiler hints default to false or 0.
2118 share->set_compiler_hints(0);
2119 share->set_opt_count_and_bailout_reason(0);
2125 static inline int NumberCacheHash(Handle<FixedArray> cache,
2126 Handle<Object> number) {
2127 int mask = (cache->length() >> 1) - 1;
2128 if (number->IsSmi()) {
2129 return Handle<Smi>::cast(number)->value() & mask;
2131 DoubleRepresentation rep(number->Number());
2133 (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2138 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2139 DisallowHeapAllocation no_gc;
2140 int hash = NumberCacheHash(number_string_cache(), number);
2141 Object* key = number_string_cache()->get(hash * 2);
2142 if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2143 key->Number() == number->Number())) {
2144 return Handle<String>(
2145 String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2147 return undefined_value();
2151 void Factory::SetNumberStringCache(Handle<Object> number,
2152 Handle<String> string) {
2153 int hash = NumberCacheHash(number_string_cache(), number);
2154 if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2155 int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2156 if (number_string_cache()->length() != full_size) {
2157 Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2158 isolate()->heap()->set_number_string_cache(*new_cache);
2162 number_string_cache()->set(hash * 2, *number);
2163 number_string_cache()->set(hash * 2 + 1, *string);
2167 Handle<String> Factory::NumberToString(Handle<Object> number,
2168 bool check_number_string_cache) {
2169 isolate()->counters()->number_to_string_runtime()->Increment();
2170 if (check_number_string_cache) {
2171 Handle<Object> cached = GetNumberStringCache(number);
2172 if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2176 Vector<char> buffer(arr, arraysize(arr));
2178 if (number->IsSmi()) {
2179 int num = Handle<Smi>::cast(number)->value();
2180 str = IntToCString(num, buffer);
2182 double num = Handle<HeapNumber>::cast(number)->value();
2183 str = DoubleToCString(num, buffer);
2186 // We tenure the allocated string since it is referenced from the
2187 // number-string cache which lives in the old space.
2188 Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2189 SetNumberStringCache(number, js_string);
2194 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2195 // Get the original code of the function.
2196 Handle<Code> code(shared->code());
2198 // Create a copy of the code before allocating the debug info object to avoid
2199 // allocation while setting up the debug info object.
2200 Handle<Code> original_code(*Factory::CopyCode(code));
2202 // Allocate initial fixed array for active break points before allocating the
2203 // debug info object to avoid allocation while setting up the debug info
2205 Handle<FixedArray> break_points(
2206 NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2208 // Create and set up the debug info object. Debug info contains function, a
2209 // copy of the original code, the executing code and initial fixed array for
2210 // active break points.
2211 Handle<DebugInfo> debug_info =
2212 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2213 debug_info->set_shared(*shared);
2214 debug_info->set_original_code(*original_code);
2215 debug_info->set_code(*code);
2216 debug_info->set_break_points(*break_points);
2218 // Link debug info to function.
2219 shared->set_debug_info(*debug_info);
2225 Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2227 bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
2228 !callee->is_simple_parameter_list();
2229 Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2230 : isolate()->sloppy_arguments_map();
2232 AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2234 DCHECK(!isolate()->has_pending_exception());
2235 Handle<JSObject> result = NewJSObjectFromMap(map);
2236 Handle<Smi> value(Smi::FromInt(length), isolate());
2237 Object::SetProperty(result, length_string(), value, STRICT).Assert();
2238 if (!strict_mode_callee) {
2239 Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2245 Handle<JSWeakMap> Factory::NewJSWeakMap() {
2246 // TODO(adamk): Currently the map is only created three times per
2247 // isolate. If it's created more often, the map should be moved into the
2248 // strong root list.
2249 Handle<Map> map = NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
2250 return Handle<JSWeakMap>::cast(NewJSObjectFromMap(map));
2254 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2255 int number_of_properties,
2256 bool* is_result_from_cache) {
2257 const int kMapCacheSize = 128;
2259 if (number_of_properties > kMapCacheSize) {
2260 *is_result_from_cache = false;
2261 return Map::Create(isolate(), number_of_properties);
2263 *is_result_from_cache = true;
2264 if (number_of_properties == 0) {
2265 // Reuse the initial map of the Object function if the literal has no
2266 // predeclared properties.
2267 return handle(context->object_function()->initial_map(), isolate());
2269 int cache_index = number_of_properties - 1;
2270 if (context->map_cache()->IsUndefined()) {
2271 // Allocate the new map cache for the native context.
2272 Handle<FixedArray> new_cache = NewFixedArray(kMapCacheSize, TENURED);
2273 context->set_map_cache(*new_cache);
2275 // Check to see whether there is a matching element in the cache.
2276 Handle<FixedArray> cache(FixedArray::cast(context->map_cache()));
2278 Object* result = cache->get(cache_index);
2279 if (result->IsWeakCell()) {
2280 WeakCell* cell = WeakCell::cast(result);
2281 if (!cell->cleared()) {
2282 return handle(Map::cast(cell->value()), isolate());
2286 // Create a new map and add it to the cache.
2287 Handle<Map> map = Map::Create(isolate(), number_of_properties);
2288 Handle<WeakCell> cell = NewWeakCell(map);
2289 cache->set(cache_index, *cell);
2294 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2295 JSRegExp::Type type,
2296 Handle<String> source,
2297 JSRegExp::Flags flags,
2298 Handle<Object> data) {
2299 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2301 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2302 store->set(JSRegExp::kSourceIndex, *source);
2303 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2304 store->set(JSRegExp::kAtomPatternIndex, *data);
2305 regexp->set_data(*store);
2309 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2310 JSRegExp::Type type,
2311 Handle<String> source,
2312 JSRegExp::Flags flags,
2313 int capture_count) {
2314 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2315 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2316 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2317 store->set(JSRegExp::kSourceIndex, *source);
2318 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2319 store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
2320 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2321 store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
2322 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2323 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2324 store->set(JSRegExp::kIrregexpCaptureCountIndex,
2325 Smi::FromInt(capture_count));
2326 regexp->set_data(*store);
2330 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2331 if (String::Equals(name, undefined_string())) return undefined_value();
2332 if (String::Equals(name, nan_string())) return nan_value();
2333 if (String::Equals(name, infinity_string())) return infinity_value();
2334 return Handle<Object>::null();
2338 Handle<Object> Factory::ToBoolean(bool value) {
2339 return value ? true_value() : false_value();
2343 } } // namespace v8::internal