1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "execution.h"
34 #include "isolate-inl.h"
35 #include "macro-assembler.h"
37 #include "objects-visiting.h"
39 #include "scopeinfo.h"
45 Handle<Box> Factory::NewBox(Handle<Object> value, PretenureFlag pretenure) {
48 isolate()->heap()->AllocateBox(*value, pretenure),
53 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
57 isolate()->heap()->AllocateFixedArray(size, pretenure),
62 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
63 PretenureFlag pretenure) {
67 isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
72 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
75 isolate()->heap()->AllocateUninitializedFixedArray(size),
80 Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
81 PretenureFlag pretenure) {
85 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
90 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
91 int number_of_int64_entries,
92 int number_of_code_ptr_entries,
93 int number_of_heap_ptr_entries,
94 int number_of_int32_entries) {
95 ASSERT(number_of_int64_entries > 0 || number_of_code_ptr_entries > 0 ||
96 number_of_heap_ptr_entries > 0 || number_of_int32_entries > 0);
99 isolate()->heap()->AllocateConstantPoolArray(number_of_int64_entries,
100 number_of_code_ptr_entries,
101 number_of_heap_ptr_entries,
102 number_of_int32_entries),
107 Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
108 ASSERT(0 <= at_least_space_for);
109 CALL_HEAP_FUNCTION(isolate(),
110 NameDictionary::Allocate(isolate()->heap(),
116 Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
117 int at_least_space_for) {
118 ASSERT(0 <= at_least_space_for);
119 CALL_HEAP_FUNCTION(isolate(),
120 SeededNumberDictionary::Allocate(isolate()->heap(),
122 SeededNumberDictionary);
126 Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
127 int at_least_space_for) {
128 ASSERT(0 <= at_least_space_for);
129 CALL_HEAP_FUNCTION(isolate(),
130 UnseededNumberDictionary::Allocate(isolate()->heap(),
132 UnseededNumberDictionary);
136 Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
137 ASSERT(0 <= at_least_space_for);
138 CALL_HEAP_FUNCTION(isolate(),
139 ObjectHashSet::Allocate(isolate()->heap(),
145 Handle<ObjectHashTable> Factory::NewObjectHashTable(
146 int at_least_space_for,
147 MinimumCapacity capacity_option) {
148 ASSERT(0 <= at_least_space_for);
149 CALL_HEAP_FUNCTION(isolate(),
150 ObjectHashTable::Allocate(isolate()->heap(),
157 Handle<WeakHashTable> Factory::NewWeakHashTable(int at_least_space_for) {
158 ASSERT(0 <= at_least_space_for);
161 WeakHashTable::Allocate(isolate()->heap(),
163 USE_DEFAULT_MINIMUM_CAPACITY,
169 Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
171 ASSERT(0 <= number_of_descriptors);
172 CALL_HEAP_FUNCTION(isolate(),
173 DescriptorArray::Allocate(
174 isolate(), number_of_descriptors, slack),
179 Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
180 int deopt_entry_count,
181 PretenureFlag pretenure) {
182 ASSERT(deopt_entry_count > 0);
183 CALL_HEAP_FUNCTION(isolate(),
184 DeoptimizationInputData::Allocate(isolate(),
187 DeoptimizationInputData);
191 Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
192 int deopt_entry_count,
193 PretenureFlag pretenure) {
194 ASSERT(deopt_entry_count > 0);
195 CALL_HEAP_FUNCTION(isolate(),
196 DeoptimizationOutputData::Allocate(isolate(),
199 DeoptimizationOutputData);
203 Handle<AccessorPair> Factory::NewAccessorPair() {
204 CALL_HEAP_FUNCTION(isolate(),
205 isolate()->heap()->AllocateAccessorPair(),
210 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
211 CALL_HEAP_FUNCTION(isolate(),
212 isolate()->heap()->AllocateTypeFeedbackInfo(),
217 // Internalized strings are created in the old generation (data space).
218 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
219 Utf8StringKey key(string, isolate()->heap()->HashSeed());
220 return InternalizeStringWithKey(&key);
224 // Internalized strings are created in the old generation (data space).
225 Handle<String> Factory::InternalizeString(Handle<String> string) {
226 CALL_HEAP_FUNCTION(isolate(),
227 isolate()->heap()->InternalizeString(*string),
232 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
233 OneByteStringKey key(string, isolate()->heap()->HashSeed());
234 return InternalizeStringWithKey(&key);
238 Handle<String> Factory::InternalizeOneByteString(
239 Handle<SeqOneByteString> string, int from, int length) {
240 SubStringKey<uint8_t> key(string, from, length);
241 return InternalizeStringWithKey(&key);
245 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
246 TwoByteStringKey key(string, isolate()->heap()->HashSeed());
247 return InternalizeStringWithKey(&key);
251 template<class StringTableKey>
252 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
253 CALL_HEAP_FUNCTION(isolate(),
254 isolate()->heap()->InternalizeStringWithKey(key),
259 template Handle<String> Factory::InternalizeStringWithKey<
260 SubStringKey<uint8_t> > (SubStringKey<uint8_t>* key);
261 template Handle<String> Factory::InternalizeStringWithKey<
262 SubStringKey<uint16_t> > (SubStringKey<uint16_t>* key);
265 Handle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
266 PretenureFlag pretenure) {
269 isolate()->heap()->AllocateStringFromOneByte(string, pretenure),
273 Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
274 PretenureFlag pretenure) {
277 isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
282 Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
283 PretenureFlag pretenure) {
286 isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
291 Handle<SeqOneByteString> Factory::NewRawOneByteString(int length,
292 PretenureFlag pretenure) {
295 isolate()->heap()->AllocateRawOneByteString(length, pretenure),
300 Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
301 PretenureFlag pretenure) {
304 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
309 // Returns true for a character in a range. Both limits are inclusive.
310 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
311 // This makes uses of the the unsigned wraparound.
312 return character - from <= to - from;
316 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
319 // Numeric strings have a different hash algorithm not known by
320 // LookupTwoCharsStringIfExists, so we skip this step for such strings.
321 if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
323 StringTable* table = isolate->heap()->string_table();
324 if (table->LookupTwoCharsStringIfExists(c1, c2, &result)) {
325 return handle(result);
329 // Now we know the length is 2, we might as well make use of that fact
330 // when building the new string.
331 if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
333 ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1)); // because of this.
334 Handle<SeqOneByteString> str = isolate->factory()->NewRawOneByteString(2);
335 uint8_t* dest = str->GetChars();
336 dest[0] = static_cast<uint8_t>(c1);
337 dest[1] = static_cast<uint8_t>(c2);
340 Handle<SeqTwoByteString> str = isolate->factory()->NewRawTwoByteString(2);
341 uc16* dest = str->GetChars();
349 template<typename SinkChar, typename StringType>
350 Handle<String> ConcatStringContent(Handle<StringType> result,
351 Handle<String> first,
352 Handle<String> second) {
353 DisallowHeapAllocation pointer_stays_valid;
354 SinkChar* sink = result->GetChars();
355 String::WriteToFlat(*first, sink, 0, first->length());
356 String::WriteToFlat(*second, sink + first->length(), 0, second->length());
361 Handle<ConsString> Factory::NewRawConsString(String::Encoding encoding) {
362 Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
363 ? cons_ascii_string_map() : cons_string_map();
364 CALL_HEAP_FUNCTION(isolate(),
365 isolate()->heap()->Allocate(*map, NEW_SPACE),
370 Handle<String> Factory::NewConsString(Handle<String> left,
371 Handle<String> right) {
372 int left_length = left->length();
373 if (left_length == 0) return right;
374 int right_length = right->length();
375 if (right_length == 0) return left;
377 int length = left_length + right_length;
380 uint16_t c1 = left->Get(0);
381 uint16_t c2 = right->Get(0);
382 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
385 // Make sure that an out of memory exception is thrown if the length
386 // of the new cons string is too large.
387 if (length > String::kMaxLength || length < 0) {
388 isolate()->ThrowInvalidStringLength();
389 return Handle<String>::null();
392 bool left_is_one_byte = left->IsOneByteRepresentation();
393 bool right_is_one_byte = right->IsOneByteRepresentation();
394 bool is_one_byte = left_is_one_byte && right_is_one_byte;
395 bool is_one_byte_data_in_two_byte_string = false;
397 // At least one of the strings uses two-byte representation so we
398 // can't use the fast case code for short ASCII strings below, but
399 // we can try to save memory if all chars actually fit in ASCII.
400 is_one_byte_data_in_two_byte_string =
401 left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
402 if (is_one_byte_data_in_two_byte_string) {
403 isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
407 // If the resulting string is small make a flat string.
408 if (length < ConsString::kMinLength) {
409 // Note that neither of the two inputs can be a slice because:
410 STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
411 ASSERT(left->IsFlat());
412 ASSERT(right->IsFlat());
414 STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
416 Handle<SeqOneByteString> result = NewRawOneByteString(length);
417 DisallowHeapAllocation no_gc;
418 uint8_t* dest = result->GetChars();
420 const uint8_t* src = left->IsExternalString()
421 ? Handle<ExternalAsciiString>::cast(left)->GetChars()
422 : Handle<SeqOneByteString>::cast(left)->GetChars();
423 for (int i = 0; i < left_length; i++) *dest++ = src[i];
425 src = right->IsExternalString()
426 ? Handle<ExternalAsciiString>::cast(right)->GetChars()
427 : Handle<SeqOneByteString>::cast(right)->GetChars();
428 for (int i = 0; i < right_length; i++) *dest++ = src[i];
432 return (is_one_byte_data_in_two_byte_string)
433 ? ConcatStringContent<uint8_t>(NewRawOneByteString(length), left, right)
434 : ConcatStringContent<uc16>(NewRawTwoByteString(length), left, right);
437 Handle<ConsString> result = NewRawConsString(
438 (is_one_byte || is_one_byte_data_in_two_byte_string)
439 ? String::ONE_BYTE_ENCODING
440 : String::TWO_BYTE_ENCODING);
442 DisallowHeapAllocation no_gc;
443 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
445 result->set_hash_field(String::kEmptyHashField);
446 result->set_length(length);
447 result->set_first(*left, mode);
448 result->set_second(*right, mode);
453 Handle<String> Factory::NewFlatConcatString(Handle<String> first,
454 Handle<String> second) {
455 int total_length = first->length() + second->length();
456 if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
457 return ConcatStringContent<uint8_t>(
458 NewRawOneByteString(total_length), first, second);
460 return ConcatStringContent<uc16>(
461 NewRawTwoByteString(total_length), first, second);
466 Handle<SlicedString> Factory::NewRawSlicedString(String::Encoding encoding) {
467 Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
468 ? sliced_ascii_string_map() : sliced_string_map();
469 CALL_HEAP_FUNCTION(isolate(),
470 isolate()->heap()->Allocate(*map, NEW_SPACE),
475 Handle<String> Factory::NewProperSubString(Handle<String> str,
479 if (FLAG_verify_heap) str->StringVerify();
481 ASSERT(begin > 0 || end < str->length());
483 int length = end - begin;
484 if (length <= 0) return empty_string();
486 return LookupSingleCharacterStringFromCode(isolate(), str->Get(begin));
489 // Optimization for 2-byte strings often used as keys in a decompression
490 // dictionary. Check whether we already have the string in the string
491 // table to prevent creation of many unnecessary strings.
492 uint16_t c1 = str->Get(begin);
493 uint16_t c2 = str->Get(begin + 1);
494 return MakeOrFindTwoCharacterString(isolate(), c1, c2);
497 if (!FLAG_string_slices || length < SlicedString::kMinLength) {
498 if (str->IsOneByteRepresentation()) {
499 Handle<SeqOneByteString> result = NewRawOneByteString(length);
500 ASSERT(!result.is_null());
501 uint8_t* dest = result->GetChars();
502 DisallowHeapAllocation no_gc;
503 String::WriteToFlat(*str, dest, begin, end);
506 Handle<SeqTwoByteString> result = NewRawTwoByteString(length);
507 ASSERT(!result.is_null());
508 uc16* dest = result->GetChars();
509 DisallowHeapAllocation no_gc;
510 String::WriteToFlat(*str, dest, begin, end);
517 while (str->IsConsString()) {
518 Handle<ConsString> cons = Handle<ConsString>::cast(str);
519 int split = cons->first()->length();
520 if (split <= offset) {
521 // Slice is fully contained in the second part.
522 str = Handle<String>(cons->second(), isolate());
523 offset -= split; // Adjust for offset.
525 } else if (offset + length <= split) {
526 // Slice is fully contained in the first part.
527 str = Handle<String>(cons->first(), isolate());
533 if (str->IsSlicedString()) {
534 Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
535 str = Handle<String>(slice->parent(), isolate());
536 offset += slice->offset();
538 str = FlattenGetString(str);
541 ASSERT(str->IsSeqString() || str->IsExternalString());
542 Handle<SlicedString> slice = NewRawSlicedString(
543 str->IsOneByteRepresentation() ? String::ONE_BYTE_ENCODING
544 : String::TWO_BYTE_ENCODING);
546 slice->set_hash_field(String::kEmptyHashField);
547 slice->set_length(length);
548 slice->set_parent(*str);
549 slice->set_offset(offset);
554 Handle<String> Factory::NewExternalStringFromAscii(
555 const ExternalAsciiString::Resource* resource) {
558 isolate()->heap()->AllocateExternalStringFromAscii(resource),
563 Handle<String> Factory::NewExternalStringFromTwoByte(
564 const ExternalTwoByteString::Resource* resource) {
567 isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
572 Handle<Symbol> Factory::NewSymbol() {
575 isolate()->heap()->AllocateSymbol(),
580 Handle<Symbol> Factory::NewPrivateSymbol() {
583 isolate()->heap()->AllocatePrivateSymbol(),
588 Handle<Context> Factory::NewNativeContext() {
591 isolate()->heap()->AllocateNativeContext(),
596 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
597 Handle<ScopeInfo> scope_info) {
600 isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
605 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
608 isolate()->heap()->AllocateModuleContext(*scope_info),
613 Handle<Context> Factory::NewFunctionContext(int length,
614 Handle<JSFunction> function) {
617 isolate()->heap()->AllocateFunctionContext(length, *function),
622 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
623 Handle<Context> previous,
625 Handle<Object> thrown_object) {
628 isolate()->heap()->AllocateCatchContext(*function,
636 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
637 Handle<Context> previous,
638 Handle<JSObject> extension) {
641 isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
646 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
647 Handle<Context> previous,
648 Handle<ScopeInfo> scope_info) {
651 isolate()->heap()->AllocateBlockContext(*function,
658 Handle<Struct> Factory::NewStruct(InstanceType type) {
661 isolate()->heap()->AllocateStruct(type),
666 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
667 int aliased_context_slot) {
668 Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
669 NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
670 entry->set_aliased_context_slot(aliased_context_slot);
675 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
676 return Handle<DeclaredAccessorDescriptor>::cast(
677 NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
681 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
682 Handle<DeclaredAccessorInfo> info =
683 Handle<DeclaredAccessorInfo>::cast(
684 NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
685 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
690 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
691 Handle<ExecutableAccessorInfo> info =
692 Handle<ExecutableAccessorInfo>::cast(
693 NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
694 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
699 Handle<Script> Factory::NewScript(Handle<String> source) {
700 // Generate id for this script.
701 Heap* heap = isolate()->heap();
702 int id = heap->last_script_id()->value() + 1;
703 if (!Smi::IsValid(id) || id < 0) id = 1;
704 heap->set_last_script_id(Smi::FromInt(id));
706 // Create and initialize script object.
707 Handle<Foreign> wrapper = NewForeign(0, TENURED);
708 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
709 script->set_source(*source);
710 script->set_name(heap->undefined_value());
711 script->set_id(Smi::FromInt(id));
712 script->set_line_offset(Smi::FromInt(0));
713 script->set_column_offset(Smi::FromInt(0));
714 script->set_context_data(heap->undefined_value());
715 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
716 script->set_wrapper(*wrapper);
717 script->set_line_ends(heap->undefined_value());
718 script->set_eval_from_shared(heap->undefined_value());
719 script->set_eval_from_instructions_offset(Smi::FromInt(0));
720 script->set_flags(Smi::FromInt(0));
726 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
727 CALL_HEAP_FUNCTION(isolate(),
728 isolate()->heap()->AllocateForeign(addr, pretenure),
733 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
734 return NewForeign((Address) desc, TENURED);
738 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
742 isolate()->heap()->AllocateByteArray(length, pretenure),
747 Handle<ExternalArray> Factory::NewExternalArray(int length,
748 ExternalArrayType array_type,
749 void* external_pointer,
750 PretenureFlag pretenure) {
751 ASSERT(0 <= length && length <= Smi::kMaxValue);
754 isolate()->heap()->AllocateExternalArray(length,
762 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
764 ExternalArrayType array_type,
765 PretenureFlag pretenure) {
766 ASSERT(0 <= length && length <= Smi::kMaxValue);
769 isolate()->heap()->AllocateFixedTypedArray(length,
772 FixedTypedArrayBase);
776 Handle<Cell> Factory::NewCell(Handle<Object> value) {
777 AllowDeferredHandleDereference convert_to_cell;
780 isolate()->heap()->AllocateCell(*value),
785 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
788 isolate()->heap()->AllocatePropertyCell(),
793 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
794 AllowDeferredHandleDereference convert_to_cell;
795 Handle<PropertyCell> cell = NewPropertyCellWithHole();
796 PropertyCell::SetValueInferType(cell, value);
801 Handle<AllocationSite> Factory::NewAllocationSite() {
804 isolate()->heap()->AllocateAllocationSite(),
809 Handle<Map> Factory::NewMap(InstanceType type,
811 ElementsKind elements_kind) {
814 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
819 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
820 // Make sure to use globals from the function's context, since the function
821 // can be from a different context.
822 Handle<Context> native_context(function->context()->native_context());
824 if (function->shared()->is_generator()) {
825 // Generator prototypes can share maps since they don't have "constructor"
827 new_map = handle(native_context->generator_object_prototype_map());
829 // Each function prototype gets a fresh map to avoid unwanted sharing of
830 // maps between prototypes of different constructors.
831 Handle<JSFunction> object_function(native_context->object_function());
832 ASSERT(object_function->has_initial_map());
833 new_map = Map::Copy(handle(object_function->initial_map()));
836 Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
838 if (!function->shared()->is_generator()) {
839 JSObject::SetLocalPropertyIgnoreAttributes(prototype,
840 constructor_string(),
849 Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
851 isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
855 Handle<Map> Factory::CopyMap(Handle<Map> src,
856 int extra_inobject_properties) {
857 Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
858 // Check that we do not overflow the instance size when adding the
859 // extra inobject properties.
860 int instance_size_delta = extra_inobject_properties * kPointerSize;
861 int max_instance_size_delta =
862 JSObject::kMaxInstanceSize - copy->instance_size();
863 int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2;
864 if (extra_inobject_properties > max_extra_properties) {
865 // If the instance size overflows, we allocate as many properties
866 // as we can as inobject properties.
867 instance_size_delta = max_instance_size_delta;
868 extra_inobject_properties = max_extra_properties;
870 // Adjust the map with the extra inobject properties.
871 int inobject_properties =
872 copy->inobject_properties() + extra_inobject_properties;
873 copy->set_inobject_properties(inobject_properties);
874 copy->set_unused_property_fields(inobject_properties);
875 copy->set_instance_size(copy->instance_size() + instance_size_delta);
876 copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
881 Handle<Map> Factory::CopyMap(Handle<Map> src) {
882 CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
886 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
887 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
891 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
892 Handle<FixedArray> array) {
893 ASSERT(isolate()->heap()->InNewSpace(*array));
894 CALL_HEAP_FUNCTION(isolate(),
895 isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
900 Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
902 PretenureFlag pretenure) {
903 CALL_HEAP_FUNCTION(isolate(),
904 array->CopySize(new_length, pretenure),
909 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
910 Handle<FixedDoubleArray> array) {
911 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
915 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
916 Handle<ConstantPoolArray> array) {
917 CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
921 Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
922 Handle<SharedFunctionInfo> function_info,
923 Handle<Map> function_map,
924 PretenureFlag pretenure) {
927 isolate()->heap()->AllocateFunction(*function_map,
929 isolate()->heap()->the_hole_value(),
935 static Handle<Map> MapForNewFunction(Isolate *isolate,
936 Handle<SharedFunctionInfo> function_info) {
937 Context *context = isolate->context()->native_context();
938 int map_index = Context::FunctionMapIndex(function_info->strict_mode(),
939 function_info->is_generator());
940 return Handle<Map>(Map::cast(context->get(map_index)));
944 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
945 Handle<SharedFunctionInfo> function_info,
946 Handle<Context> context,
947 PretenureFlag pretenure) {
948 Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
950 MapForNewFunction(isolate(), function_info),
953 if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
954 function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
957 result->set_context(*context);
959 int index = function_info->SearchOptimizedCodeMap(context->native_context(),
961 if (!function_info->bound() && index < 0) {
962 int number_of_literals = function_info->num_literals();
963 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
964 if (number_of_literals > 0) {
965 // Store the native context in the literals array prefix. This
966 // context will be used when creating object, regexp and array
967 // literals in this function.
968 literals->set(JSFunction::kLiteralNativeContextIndex,
969 context->native_context());
971 result->set_literals(*literals);
975 // Caching of optimized code enabled and optimized code found.
976 FixedArray* literals =
977 function_info->GetLiteralsFromOptimizedCodeMap(index);
978 if (literals != NULL) result->set_literals(literals);
979 Code* code = function_info->GetCodeFromOptimizedCodeMap(index);
980 ASSERT(!code->marked_for_deoptimization());
981 result->ReplaceCode(code);
985 if (isolate()->use_crankshaft() &&
987 result->is_compiled() &&
988 !function_info->is_toplevel() &&
989 function_info->allows_lazy_compilation() &&
990 !function_info->optimization_disabled() &&
991 !isolate()->DebuggerHasBreakPoints()) {
992 result->MarkForOptimization();
998 Handle<Object> Factory::NewNumber(double value,
999 PretenureFlag pretenure) {
1002 isolate()->heap()->NumberFromDouble(value, pretenure), Object);
1006 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1007 PretenureFlag pretenure) {
1010 isolate()->heap()->NumberFromInt32(value, pretenure), Object);
1014 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1015 PretenureFlag pretenure) {
1018 isolate()->heap()->NumberFromUint32(value, pretenure), Object);
1022 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1023 PretenureFlag pretenure) {
1026 isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
1030 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1031 PretenureFlag pretenure) {
1034 isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1038 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1039 PretenureFlag pretenure) {
1042 isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1046 Handle<JSObject> Factory::NewNeanderObject() {
1049 isolate()->heap()->AllocateJSObjectFromMap(
1050 isolate()->heap()->neander_map()),
1055 Handle<Object> Factory::NewTypeError(const char* message,
1056 Vector< Handle<Object> > args) {
1057 return NewError("MakeTypeError", message, args);
1061 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1062 return NewError("$TypeError", message);
1066 Handle<Object> Factory::NewRangeError(const char* message,
1067 Vector< Handle<Object> > args) {
1068 return NewError("MakeRangeError", message, args);
1072 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1073 return NewError("$RangeError", message);
1077 Handle<Object> Factory::NewSyntaxError(const char* message,
1078 Handle<JSArray> args) {
1079 return NewError("MakeSyntaxError", message, args);
1083 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1084 return NewError("$SyntaxError", message);
1088 Handle<Object> Factory::NewReferenceError(const char* message,
1089 Vector< Handle<Object> > args) {
1090 return NewError("MakeReferenceError", message, args);
1094 Handle<Object> Factory::NewReferenceError(const char* message,
1095 Handle<JSArray> args) {
1096 return NewError("MakeReferenceError", message, args);
1100 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1101 return NewError("$ReferenceError", message);
1105 Handle<Object> Factory::NewError(const char* maker,
1106 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 = NewError(maker, message, object);
1116 return result.EscapeFrom(&scope);
1120 Handle<Object> Factory::NewEvalError(const char* message,
1121 Vector< Handle<Object> > args) {
1122 return NewError("MakeEvalError", message, args);
1126 Handle<Object> Factory::NewError(const char* message,
1127 Vector< Handle<Object> > args) {
1128 return NewError("MakeError", message, args);
1132 Handle<String> Factory::EmergencyNewError(const char* message,
1133 Handle<JSArray> args) {
1134 const int kBufferSize = 1000;
1135 char buffer[kBufferSize];
1136 size_t space = kBufferSize;
1137 char* p = &buffer[0];
1139 Vector<char> v(buffer, kBufferSize);
1140 OS::StrNCpy(v, message, space);
1141 space -= Min(space, strlen(message));
1142 p = &buffer[kBufferSize] - space;
1144 for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1149 Handle<String> arg_str = Handle<String>::cast(
1150 Object::GetElementNoExceptionThrown(isolate(), args, i));
1151 SmartArrayPointer<char> arg = arg_str->ToCString();
1152 Vector<char> v2(p, static_cast<int>(space));
1153 OS::StrNCpy(v2, arg.get(), space);
1154 space -= Min(space, strlen(arg.get()));
1155 p = &buffer[kBufferSize] - space;
1162 buffer[kBufferSize - 1] = '\0';
1164 Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
1165 return error_string;
1169 Handle<Object> Factory::NewError(const char* maker,
1170 const char* message,
1171 Handle<JSArray> args) {
1172 Handle<String> make_str = InternalizeUtf8String(maker);
1173 Handle<Object> fun_obj(
1174 isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
1176 // If the builtins haven't been properly configured yet this error
1177 // constructor may not have been defined. Bail out.
1178 if (!fun_obj->IsJSFunction()) {
1179 return EmergencyNewError(message, args);
1181 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1182 Handle<Object> message_obj = InternalizeUtf8String(message);
1183 Handle<Object> argv[] = { message_obj, args };
1185 // Invoke the JavaScript factory method. If an exception is thrown while
1186 // running the factory method, use the exception as the result.
1187 bool caught_exception;
1188 Handle<Object> result = Execution::TryCall(fun,
1189 isolate()->js_builtins_object(),
1197 Handle<Object> Factory::NewError(Handle<String> message) {
1198 return NewError("$Error", message);
1202 Handle<Object> Factory::NewError(const char* constructor,
1203 Handle<String> message) {
1204 Handle<String> constr = InternalizeUtf8String(constructor);
1205 Handle<JSFunction> fun = Handle<JSFunction>(
1206 JSFunction::cast(isolate()->js_builtins_object()->
1207 GetPropertyNoExceptionThrown(*constr)));
1208 Handle<Object> argv[] = { message };
1210 // Invoke the JavaScript factory method. If an exception is thrown while
1211 // running the factory method, use the exception as the result.
1212 bool caught_exception;
1213 Handle<Object> result = Execution::TryCall(fun,
1214 isolate()->js_builtins_object(),
1222 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1226 bool force_initial_map) {
1227 // Allocate the function
1228 Handle<JSFunction> function = NewFunction(name, the_hole_value());
1230 // Set up the code pointer in both the shared function info and in
1231 // the function itself.
1232 function->shared()->set_code(*code);
1233 function->set_code(*code);
1235 if (force_initial_map ||
1236 type != JS_OBJECT_TYPE ||
1237 instance_size != JSObject::kHeaderSize) {
1238 Handle<Map> initial_map = NewMap(type, instance_size);
1239 Handle<JSObject> prototype = NewFunctionPrototype(function);
1240 initial_map->set_prototype(*prototype);
1241 function->set_initial_map(*initial_map);
1242 initial_map->set_constructor(*function);
1244 ASSERT(!function->has_initial_map());
1245 ASSERT(!function->has_prototype());
1252 Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
1255 Handle<JSObject> prototype,
1257 bool force_initial_map) {
1258 // Allocate the function.
1259 Handle<JSFunction> function = NewFunction(name, prototype);
1261 // Set up the code pointer in both the shared function info and in
1262 // the function itself.
1263 function->shared()->set_code(*code);
1264 function->set_code(*code);
1266 if (force_initial_map ||
1267 type != JS_OBJECT_TYPE ||
1268 instance_size != JSObject::kHeaderSize) {
1269 Handle<Map> initial_map = NewMap(type,
1271 GetInitialFastElementsKind());
1272 function->set_initial_map(*initial_map);
1273 initial_map->set_constructor(*function);
1276 JSFunction::SetPrototype(function, prototype);
1281 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1282 Handle<Code> code) {
1283 Handle<JSFunction> function = NewFunctionWithoutPrototype(name, SLOPPY);
1284 function->shared()->set_code(*code);
1285 function->set_code(*code);
1286 ASSERT(!function->has_initial_map());
1287 ASSERT(!function->has_prototype());
1292 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1295 isolate()->heap()->AllocateScopeInfo(length),
1300 Handle<JSObject> Factory::NewExternal(void* value) {
1301 CALL_HEAP_FUNCTION(isolate(),
1302 isolate()->heap()->AllocateExternal(value),
1307 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1309 Handle<Object> self_ref,
1312 int prologue_offset) {
1313 CALL_HEAP_FUNCTION(isolate(),
1314 isolate()->heap()->CreateCode(
1315 desc, flags, self_ref, immovable, crankshafted,
1321 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1322 CALL_HEAP_FUNCTION(isolate(),
1323 isolate()->heap()->CopyCode(*code),
1328 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1329 CALL_HEAP_FUNCTION(isolate(),
1330 isolate()->heap()->CopyCode(*code, reloc_info),
1335 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1336 PretenureFlag pretenure) {
1337 JSFunction::EnsureHasInitialMap(constructor);
1340 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1344 Handle<JSObject> Factory::NewJSObjectWithMemento(
1345 Handle<JSFunction> constructor,
1346 Handle<AllocationSite> site) {
1347 JSFunction::EnsureHasInitialMap(constructor);
1350 isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1355 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1356 Handle<ScopeInfo> scope_info) {
1359 isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1363 // TODO(mstarzinger): Temporary wrapper until handlified.
1364 static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
1366 Handle<Object> value,
1367 PropertyDetails details) {
1368 CALL_HEAP_FUNCTION(dict->GetIsolate(),
1369 dict->Add(*name, *value, details),
1374 static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
1376 CALL_HEAP_FUNCTION(isolate,
1377 isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1382 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1383 ASSERT(constructor->has_initial_map());
1384 Handle<Map> map(constructor->initial_map());
1385 ASSERT(map->is_dictionary_map());
1387 // Make sure no field properties are described in the initial map.
1388 // This guarantees us that normalizing the properties does not
1389 // require us to change property values to PropertyCells.
1390 ASSERT(map->NextFreePropertyIndex() == 0);
1392 // Make sure we don't have a ton of pre-allocated slots in the
1393 // global objects. They will be unused once we normalize the object.
1394 ASSERT(map->unused_property_fields() == 0);
1395 ASSERT(map->inobject_properties() == 0);
1397 // Initial size of the backing store to avoid resize of the storage during
1398 // bootstrapping. The size differs between the JS global object ad the
1400 int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1402 // Allocate a dictionary object for backing storage.
1403 int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1404 Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);
1406 // The global object might be created from an object template with accessors.
1407 // Fill these accessors into the dictionary.
1408 Handle<DescriptorArray> descs(map->instance_descriptors());
1409 for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1410 PropertyDetails details = descs->GetDetails(i);
1411 ASSERT(details.type() == CALLBACKS); // Only accessors are expected.
1412 PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1413 Handle<Name> name(descs->GetKey(i));
1414 Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1415 Handle<PropertyCell> cell = NewPropertyCell(value);
1416 NameDictionaryAdd(dictionary, name, cell, d);
1419 // Allocate the global object and initialize it with the backing store.
1420 Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
1421 isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1423 // Create a new map for the global object.
1424 Handle<Map> new_map = Map::CopyDropDescriptors(map);
1425 new_map->set_dictionary_map(true);
1427 // Set up the global object as a normalized object.
1428 global->set_map(*new_map);
1429 global->set_properties(*dictionary);
1431 // Make sure result is a global object with properties in dictionary.
1432 ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1437 Handle<JSObject> Factory::NewJSObjectFromMap(
1439 PretenureFlag pretenure,
1441 Handle<AllocationSite> allocation_site) {
1444 isolate()->heap()->AllocateJSObjectFromMap(
1448 allocation_site.is_null() ? NULL : *allocation_site),
1453 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1456 PretenureFlag pretenure) {
1457 if (capacity != 0) {
1458 elements_kind = GetHoleyElementsKind(elements_kind);
1460 CALL_HEAP_FUNCTION(isolate(),
1461 isolate()->heap()->AllocateJSArrayAndStorage(
1465 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
1471 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1472 ElementsKind elements_kind,
1474 PretenureFlag pretenure) {
1475 ASSERT(length <= elements->length());
1478 isolate()->heap()->AllocateJSArrayWithElements(*elements,
1486 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1489 ArrayStorageAllocationMode mode) {
1490 CALL_HEAP_FUNCTION_VOID(isolate(),
1491 isolate()->heap()->AllocateJSArrayStorage(*array,
1498 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1499 Handle<JSFunction> function) {
1500 ASSERT(function->shared()->is_generator());
1501 JSFunction::EnsureHasInitialMap(function);
1502 Handle<Map> map(function->initial_map());
1503 ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1506 isolate()->heap()->AllocateJSObjectFromMap(*map),
1511 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1512 Handle<JSFunction> array_buffer_fun(
1513 isolate()->context()->native_context()->array_buffer_fun());
1516 isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1521 Handle<JSDataView> Factory::NewJSDataView() {
1522 Handle<JSFunction> data_view_fun(
1523 isolate()->context()->native_context()->data_view_fun());
1526 isolate()->heap()->AllocateJSObject(*data_view_fun),
1531 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1533 Context* native_context = isolate->context()->native_context();
1535 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1536 case kExternal##Type##Array: \
1537 return native_context->type##_array_fun();
1539 TYPED_ARRAYS(TYPED_ARRAY_FUN)
1540 #undef TYPED_ARRAY_FUN
1549 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1550 Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1554 isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1559 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1560 Handle<Object> prototype) {
1563 isolate()->heap()->AllocateJSProxy(*handler, *prototype),
1568 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1569 CALL_HEAP_FUNCTION_VOID(
1571 isolate()->heap()->ReinitializeJSReceiver(
1572 *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
1576 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1577 CALL_HEAP_FUNCTION_VOID(
1579 isolate()->heap()->ReinitializeJSReceiver(
1580 *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1584 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1585 Handle<String> name,
1586 int number_of_literals,
1589 Handle<ScopeInfo> scope_info) {
1590 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
1591 shared->set_code(*code);
1592 shared->set_scope_info(*scope_info);
1593 int literals_array_size = number_of_literals;
1594 // If the function contains object, regexp or array literals,
1595 // allocate extra space for a literals array prefix containing the
1597 if (number_of_literals > 0) {
1598 literals_array_size += JSFunction::kLiteralsPrefixSize;
1600 shared->set_num_literals(literals_array_size);
1602 shared->set_instance_class_name(isolate()->heap()->Generator_string());
1603 shared->DisableOptimization(kGenerator);
1609 Handle<JSMessageObject> Factory::NewJSMessageObject(
1610 Handle<String> type,
1611 Handle<JSArray> arguments,
1614 Handle<Object> script,
1615 Handle<Object> stack_frames) {
1616 CALL_HEAP_FUNCTION(isolate(),
1617 isolate()->heap()->AllocateJSMessageObject(*type,
1627 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1628 CALL_HEAP_FUNCTION(isolate(),
1629 isolate()->heap()->AllocateSharedFunctionInfo(*name),
1630 SharedFunctionInfo);
1634 Handle<String> Factory::NumberToString(Handle<Object> number) {
1635 CALL_HEAP_FUNCTION(isolate(),
1636 isolate()->heap()->NumberToString(*number), String);
1640 Handle<String> Factory::Uint32ToString(uint32_t value) {
1641 CALL_HEAP_FUNCTION(isolate(),
1642 isolate()->heap()->Uint32ToString(value), String);
1646 Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
1647 Handle<SeededNumberDictionary> dictionary,
1649 Handle<Object> value) {
1650 CALL_HEAP_FUNCTION(isolate(),
1651 dictionary->AtNumberPut(key, *value),
1652 SeededNumberDictionary);
1656 Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
1657 Handle<UnseededNumberDictionary> dictionary,
1659 Handle<Object> value) {
1660 CALL_HEAP_FUNCTION(isolate(),
1661 dictionary->AtNumberPut(key, *value),
1662 UnseededNumberDictionary);
1666 Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
1667 Handle<Object> prototype) {
1668 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1671 isolate()->heap()->AllocateFunction(*isolate()->sloppy_function_map(),
1678 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1679 Handle<Object> prototype) {
1680 Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1681 fun->set_context(isolate()->context()->native_context());
1686 Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1687 Handle<String> name,
1688 StrictMode strict_mode) {
1689 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1690 Handle<Map> map = strict_mode == SLOPPY
1691 ? isolate()->sloppy_function_without_prototype_map()
1692 : isolate()->strict_function_without_prototype_map();
1693 CALL_HEAP_FUNCTION(isolate(),
1694 isolate()->heap()->AllocateFunction(
1702 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
1703 Handle<String> name,
1704 StrictMode strict_mode) {
1705 Handle<JSFunction> fun = NewFunctionWithoutPrototypeHelper(name, strict_mode);
1706 fun->set_context(isolate()->context()->native_context());
1711 Handle<Object> Factory::ToObject(Handle<Object> object) {
1712 CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
1716 Handle<Object> Factory::ToObject(Handle<Object> object,
1717 Handle<Context> native_context) {
1718 CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1722 #ifdef ENABLE_DEBUGGER_SUPPORT
1723 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
1724 // Get the original code of the function.
1725 Handle<Code> code(shared->code());
1727 // Create a copy of the code before allocating the debug info object to avoid
1728 // allocation while setting up the debug info object.
1729 Handle<Code> original_code(*Factory::CopyCode(code));
1731 // Allocate initial fixed array for active break points before allocating the
1732 // debug info object to avoid allocation while setting up the debug info
1734 Handle<FixedArray> break_points(
1735 NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1737 // Create and set up the debug info object. Debug info contains function, a
1738 // copy of the original code, the executing code and initial fixed array for
1739 // active break points.
1740 Handle<DebugInfo> debug_info =
1741 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1742 debug_info->set_shared(*shared);
1743 debug_info->set_original_code(*original_code);
1744 debug_info->set_code(*code);
1745 debug_info->set_break_points(*break_points);
1747 // Link debug info to function.
1748 shared->set_debug_info(*debug_info);
1755 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
1759 isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1763 Handle<JSFunction> Factory::CreateApiFunction(
1764 Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1765 Handle<Code> code = isolate()->builtins()->HandleApiCall();
1766 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1768 int internal_field_count = 0;
1769 if (!obj->instance_template()->IsUndefined()) {
1770 Handle<ObjectTemplateInfo> instance_template =
1771 Handle<ObjectTemplateInfo>(
1772 ObjectTemplateInfo::cast(obj->instance_template()));
1773 internal_field_count =
1774 Smi::cast(instance_template->internal_field_count())->value();
1777 // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
1778 // JSObject::GetHeaderSize.
1779 int instance_size = kPointerSize * internal_field_count;
1781 switch (instance_type) {
1782 case JavaScriptObject:
1783 type = JS_OBJECT_TYPE;
1784 instance_size += JSObject::kHeaderSize;
1786 case InnerGlobalObject:
1787 type = JS_GLOBAL_OBJECT_TYPE;
1788 instance_size += JSGlobalObject::kSize;
1790 case OuterGlobalObject:
1791 type = JS_GLOBAL_PROXY_TYPE;
1792 instance_size += JSGlobalProxy::kSize;
1796 type = JS_OBJECT_TYPE; // Keep the compiler happy.
1800 Handle<JSFunction> result =
1801 NewFunction(Factory::empty_string(),
1808 result->shared()->set_length(obj->length());
1811 Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1812 if (class_name->IsString()) {
1813 result->shared()->set_instance_class_name(*class_name);
1814 result->shared()->set_name(*class_name);
1817 Handle<Map> map = Handle<Map>(result->initial_map());
1819 // Mark as undetectable if needed.
1820 if (obj->undetectable()) {
1821 map->set_is_undetectable();
1824 // Mark as hidden for the __proto__ accessor if needed.
1825 if (obj->hidden_prototype()) {
1826 map->set_is_hidden_prototype();
1829 // Mark as needs_access_check if needed.
1830 if (obj->needs_access_check()) {
1831 map->set_is_access_check_needed(true);
1834 // Set interceptor information in the map.
1835 if (!obj->named_property_handler()->IsUndefined()) {
1836 map->set_has_named_interceptor();
1838 if (!obj->indexed_property_handler()->IsUndefined()) {
1839 map->set_has_indexed_interceptor();
1842 // Set instance call-as-function information in the map.
1843 if (!obj->instance_call_handler()->IsUndefined()) {
1844 map->set_has_instance_call_handler();
1847 result->shared()->set_function_data(*obj);
1848 result->shared()->set_construct_stub(*construct_stub);
1849 result->shared()->DontAdaptArguments();
1851 // Recursively copy parent instance templates' accessors,
1852 // 'data' may be modified.
1853 int max_number_of_additional_properties = 0;
1854 int max_number_of_static_properties = 0;
1855 FunctionTemplateInfo* info = *obj;
1857 if (!info->instance_template()->IsUndefined()) {
1859 ObjectTemplateInfo::cast(
1860 info->instance_template())->property_accessors();
1861 if (!props->IsUndefined()) {
1862 Handle<Object> props_handle(props, isolate());
1863 NeanderArray props_array(props_handle);
1864 max_number_of_additional_properties += props_array.length();
1867 if (!info->property_accessors()->IsUndefined()) {
1868 Object* props = info->property_accessors();
1869 if (!props->IsUndefined()) {
1870 Handle<Object> props_handle(props, isolate());
1871 NeanderArray props_array(props_handle);
1872 max_number_of_static_properties += props_array.length();
1875 Object* parent = info->parent_template();
1876 if (parent->IsUndefined()) break;
1877 info = FunctionTemplateInfo::cast(parent);
1880 Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
1882 // Use a temporary FixedArray to acculumate static accessors
1883 int valid_descriptors = 0;
1884 Handle<FixedArray> array;
1885 if (max_number_of_static_properties > 0) {
1886 array = NewFixedArray(max_number_of_static_properties);
1890 // Install instance descriptors
1891 if (!obj->instance_template()->IsUndefined()) {
1892 Handle<ObjectTemplateInfo> instance =
1893 Handle<ObjectTemplateInfo>(
1894 ObjectTemplateInfo::cast(obj->instance_template()), isolate());
1895 Handle<Object> props = Handle<Object>(instance->property_accessors(),
1897 if (!props->IsUndefined()) {
1898 Map::AppendCallbackDescriptors(map, props);
1901 // Accumulate static accessors
1902 if (!obj->property_accessors()->IsUndefined()) {
1903 Handle<Object> props = Handle<Object>(obj->property_accessors(),
1906 AccessorInfo::AppendUnique(props, array, valid_descriptors);
1908 // Climb parent chain
1909 Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1910 if (parent->IsUndefined()) break;
1911 obj = Handle<FunctionTemplateInfo>::cast(parent);
1914 // Install accumulated static accessors
1915 for (int i = 0; i < valid_descriptors; i++) {
1916 Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
1917 JSObject::SetAccessor(result, accessor);
1920 ASSERT(result->shared()->IsApiFunction());
1925 Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1926 CALL_HEAP_FUNCTION(isolate(),
1927 MapCache::Allocate(isolate()->heap(),
1928 at_least_space_for),
1933 MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
1937 { MaybeObject* maybe_result =
1938 MapCache::cast(context->map_cache())->Put(keys, map);
1939 if (!maybe_result->ToObject(&result)) return maybe_result;
1941 context->set_map_cache(MapCache::cast(result));
1946 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1947 Handle<FixedArray> keys,
1949 CALL_HEAP_FUNCTION(isolate(),
1950 UpdateMapCacheWith(*context, *keys, *map), MapCache);
1954 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1955 Handle<FixedArray> keys) {
1956 if (context->map_cache()->IsUndefined()) {
1957 // Allocate the new map cache for the native context.
1958 Handle<MapCache> new_cache = NewMapCache(24);
1959 context->set_map_cache(*new_cache);
1961 // Check to see whether there is a matching element in the cache.
1962 Handle<MapCache> cache =
1963 Handle<MapCache>(MapCache::cast(context->map_cache()));
1964 Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1965 if (result->IsMap()) return Handle<Map>::cast(result);
1966 // Create a new map and add it to the cache.
1968 CopyMap(Handle<Map>(context->object_function()->initial_map()),
1970 AddToMapCache(context, keys, map);
1971 return Handle<Map>(map);
1975 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1976 JSRegExp::Type type,
1977 Handle<String> source,
1978 JSRegExp::Flags flags,
1979 Handle<Object> data) {
1980 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1982 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1983 store->set(JSRegExp::kSourceIndex, *source);
1984 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1985 store->set(JSRegExp::kAtomPatternIndex, *data);
1986 regexp->set_data(*store);
1989 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1990 JSRegExp::Type type,
1991 Handle<String> source,
1992 JSRegExp::Flags flags,
1993 int capture_count) {
1994 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1995 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1996 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1997 store->set(JSRegExp::kSourceIndex, *source);
1998 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1999 store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
2000 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2001 store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
2002 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2003 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2004 store->set(JSRegExp::kIrregexpCaptureCountIndex,
2005 Smi::FromInt(capture_count));
2006 regexp->set_data(*store);
2011 void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
2012 Handle<JSObject> instance,
2013 bool* pending_exception) {
2014 // Configure the instance by adding the properties specified by the
2015 // instance template.
2016 Handle<Object> instance_template(desc->instance_template(), isolate());
2017 if (!instance_template->IsUndefined()) {
2018 Execution::ConfigureInstance(isolate(),
2023 *pending_exception = false;
2028 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2029 Heap* h = isolate()->heap();
2030 if (name->Equals(h->undefined_string())) return undefined_value();
2031 if (name->Equals(h->nan_string())) return nan_value();
2032 if (name->Equals(h->infinity_string())) return infinity_value();
2033 return Handle<Object>::null();
2037 Handle<Object> Factory::ToBoolean(bool value) {
2038 return value ? true_value() : false_value();
2042 } } // namespace v8::internal