1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "execution.h"
34 #include "macro-assembler.h"
36 #include "objects-visiting.h"
37 #include "scopeinfo.h"
43 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
47 isolate()->heap()->AllocateFixedArray(size, pretenure),
52 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
53 PretenureFlag pretenure) {
57 isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
62 Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
63 PretenureFlag pretenure) {
67 isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
72 Handle<StringDictionary> Factory::NewStringDictionary(int at_least_space_for) {
73 ASSERT(0 <= at_least_space_for);
74 CALL_HEAP_FUNCTION(isolate(),
75 StringDictionary::Allocate(at_least_space_for),
80 Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
81 int at_least_space_for) {
82 ASSERT(0 <= at_least_space_for);
83 CALL_HEAP_FUNCTION(isolate(),
84 SeededNumberDictionary::Allocate(at_least_space_for),
85 SeededNumberDictionary);
89 Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
90 int at_least_space_for) {
91 ASSERT(0 <= at_least_space_for);
92 CALL_HEAP_FUNCTION(isolate(),
93 UnseededNumberDictionary::Allocate(at_least_space_for),
94 UnseededNumberDictionary);
98 Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
99 ASSERT(0 <= at_least_space_for);
100 CALL_HEAP_FUNCTION(isolate(),
101 ObjectHashSet::Allocate(at_least_space_for),
106 Handle<ObjectHashTable> Factory::NewObjectHashTable(int at_least_space_for) {
107 ASSERT(0 <= at_least_space_for);
108 CALL_HEAP_FUNCTION(isolate(),
109 ObjectHashTable::Allocate(at_least_space_for),
114 Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors) {
115 ASSERT(0 <= number_of_descriptors);
116 CALL_HEAP_FUNCTION(isolate(),
117 DescriptorArray::Allocate(number_of_descriptors),
122 Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
123 int deopt_entry_count,
124 PretenureFlag pretenure) {
125 ASSERT(deopt_entry_count > 0);
126 CALL_HEAP_FUNCTION(isolate(),
127 DeoptimizationInputData::Allocate(deopt_entry_count,
129 DeoptimizationInputData);
133 Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
134 int deopt_entry_count,
135 PretenureFlag pretenure) {
136 ASSERT(deopt_entry_count > 0);
137 CALL_HEAP_FUNCTION(isolate(),
138 DeoptimizationOutputData::Allocate(deopt_entry_count,
140 DeoptimizationOutputData);
144 Handle<AccessorPair> Factory::NewAccessorPair() {
145 CALL_HEAP_FUNCTION(isolate(),
146 isolate()->heap()->AllocateAccessorPair(),
151 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
152 CALL_HEAP_FUNCTION(isolate(),
153 isolate()->heap()->AllocateTypeFeedbackInfo(),
158 // Symbols are created in the old generation (data space).
159 Handle<String> Factory::LookupSymbol(Vector<const char> string) {
160 CALL_HEAP_FUNCTION(isolate(),
161 isolate()->heap()->LookupSymbol(string),
165 // Symbols are created in the old generation (data space).
166 Handle<String> Factory::LookupSymbol(Handle<String> string) {
167 CALL_HEAP_FUNCTION(isolate(),
168 isolate()->heap()->LookupSymbol(*string),
172 Handle<String> Factory::LookupAsciiSymbol(Vector<const char> string) {
173 CALL_HEAP_FUNCTION(isolate(),
174 isolate()->heap()->LookupAsciiSymbol(string),
179 Handle<String> Factory::LookupAsciiSymbol(Handle<SeqAsciiString> string,
182 CALL_HEAP_FUNCTION(isolate(),
183 isolate()->heap()->LookupAsciiSymbol(string,
190 Handle<String> Factory::LookupTwoByteSymbol(Vector<const uc16> string) {
191 CALL_HEAP_FUNCTION(isolate(),
192 isolate()->heap()->LookupTwoByteSymbol(string),
197 Handle<String> Factory::NewStringFromAscii(Vector<const char> string,
198 PretenureFlag pretenure) {
201 isolate()->heap()->AllocateStringFromAscii(string, pretenure),
205 Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
206 PretenureFlag pretenure) {
209 isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
214 Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
215 PretenureFlag pretenure) {
218 isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
223 Handle<SeqAsciiString> Factory::NewRawAsciiString(int length,
224 PretenureFlag pretenure) {
227 isolate()->heap()->AllocateRawAsciiString(length, pretenure),
232 Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
233 PretenureFlag pretenure) {
236 isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
241 Handle<String> Factory::NewConsString(Handle<String> first,
242 Handle<String> second) {
243 CALL_HEAP_FUNCTION(isolate(),
244 isolate()->heap()->AllocateConsString(*first, *second),
249 Handle<String> Factory::NewSubString(Handle<String> str,
252 CALL_HEAP_FUNCTION(isolate(),
253 str->SubString(begin, end),
258 Handle<String> Factory::NewProperSubString(Handle<String> str,
261 ASSERT(begin > 0 || end < str->length());
262 CALL_HEAP_FUNCTION(isolate(),
263 isolate()->heap()->AllocateSubString(*str, begin, end),
268 Handle<String> Factory::NewExternalStringFromAscii(
269 const ExternalAsciiString::Resource* resource) {
272 isolate()->heap()->AllocateExternalStringFromAscii(resource),
277 Handle<String> Factory::NewExternalStringFromTwoByte(
278 const ExternalTwoByteString::Resource* resource) {
281 isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
286 Handle<Context> Factory::NewGlobalContext() {
289 isolate()->heap()->AllocateGlobalContext(),
294 Handle<Context> Factory::NewModuleContext(Handle<Context> previous,
295 Handle<ScopeInfo> scope_info) {
298 isolate()->heap()->AllocateModuleContext(*previous, *scope_info),
303 Handle<Context> Factory::NewFunctionContext(int length,
304 Handle<JSFunction> function) {
307 isolate()->heap()->AllocateFunctionContext(length, *function),
312 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
313 Handle<Context> previous,
315 Handle<Object> thrown_object) {
318 isolate()->heap()->AllocateCatchContext(*function,
326 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
327 Handle<Context> previous,
328 Handle<JSObject> extension) {
331 isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
336 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
337 Handle<Context> previous,
338 Handle<ScopeInfo> scope_info) {
341 isolate()->heap()->AllocateBlockContext(*function,
348 Handle<Struct> Factory::NewStruct(InstanceType type) {
351 isolate()->heap()->AllocateStruct(type),
356 Handle<AccessorInfo> Factory::NewAccessorInfo() {
357 Handle<AccessorInfo> info =
358 Handle<AccessorInfo>::cast(NewStruct(ACCESSOR_INFO_TYPE));
359 info->set_flag(0); // Must clear the flag, it was initialized as undefined.
364 Handle<Script> Factory::NewScript(Handle<String> source) {
365 // Generate id for this script.
367 Heap* heap = isolate()->heap();
368 if (heap->last_script_id()->IsUndefined()) {
369 // Script ids start from one.
372 // Increment id, wrap when positive smi is exhausted.
373 id = Smi::cast(heap->last_script_id())->value();
375 if (!Smi::IsValid(id)) {
379 heap->SetLastScriptId(Smi::FromInt(id));
381 // Create and initialize script object.
382 Handle<Foreign> wrapper = NewForeign(0, TENURED);
383 Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
384 script->set_source(*source);
385 script->set_name(heap->undefined_value());
386 script->set_id(heap->last_script_id());
387 script->set_line_offset(Smi::FromInt(0));
388 script->set_column_offset(Smi::FromInt(0));
389 script->set_data(heap->undefined_value());
390 script->set_context_data(heap->undefined_value());
391 script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
392 script->set_compilation_type(Smi::FromInt(Script::COMPILATION_TYPE_HOST));
393 script->set_compilation_state(
394 Smi::FromInt(Script::COMPILATION_STATE_INITIAL));
395 script->set_wrapper(*wrapper);
396 script->set_line_ends(heap->undefined_value());
397 script->set_eval_from_shared(heap->undefined_value());
398 script->set_eval_from_instructions_offset(Smi::FromInt(0));
404 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
405 CALL_HEAP_FUNCTION(isolate(),
406 isolate()->heap()->AllocateForeign(addr, pretenure),
411 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
412 return NewForeign((Address) desc, TENURED);
416 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
420 isolate()->heap()->AllocateByteArray(length, pretenure),
425 Handle<ExternalArray> Factory::NewExternalArray(int length,
426 ExternalArrayType array_type,
427 void* external_pointer,
428 PretenureFlag pretenure) {
432 isolate()->heap()->AllocateExternalArray(length,
440 Handle<JSGlobalPropertyCell> Factory::NewJSGlobalPropertyCell(
441 Handle<Object> value) {
444 isolate()->heap()->AllocateJSGlobalPropertyCell(*value),
445 JSGlobalPropertyCell);
449 Handle<Map> Factory::NewMap(InstanceType type,
451 ElementsKind elements_kind) {
454 isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
459 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
462 isolate()->heap()->AllocateFunctionPrototype(*function),
467 Handle<Map> Factory::CopyMapDropDescriptors(Handle<Map> src) {
468 CALL_HEAP_FUNCTION(isolate(), src->CopyDropDescriptors(), Map);
472 Handle<Map> Factory::CopyMap(Handle<Map> src,
473 int extra_inobject_properties) {
474 Handle<Map> copy = CopyMapDropDescriptors(src);
475 // Check that we do not overflow the instance size when adding the
476 // extra inobject properties.
477 int instance_size_delta = extra_inobject_properties * kPointerSize;
478 int max_instance_size_delta =
479 JSObject::kMaxInstanceSize - copy->instance_size();
480 if (instance_size_delta > max_instance_size_delta) {
481 // If the instance size overflows, we allocate as many properties
482 // as we can as inobject properties.
483 instance_size_delta = max_instance_size_delta;
484 extra_inobject_properties = max_instance_size_delta >> kPointerSizeLog2;
486 // Adjust the map with the extra inobject properties.
487 int inobject_properties =
488 copy->inobject_properties() + extra_inobject_properties;
489 copy->set_inobject_properties(inobject_properties);
490 copy->set_unused_property_fields(inobject_properties);
491 copy->set_instance_size(copy->instance_size() + instance_size_delta);
492 copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
497 Handle<Map> Factory::CopyMapDropTransitions(Handle<Map> src) {
498 CALL_HEAP_FUNCTION(isolate(), src->CopyDropTransitions(), Map);
502 Handle<Map> Factory::GetElementsTransitionMap(
503 Handle<JSObject> src,
504 ElementsKind elements_kind) {
505 Isolate* i = isolate();
506 CALL_HEAP_FUNCTION(i,
507 src->GetElementsTransitionMap(i, elements_kind),
512 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
513 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
517 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
518 Handle<FixedDoubleArray> array) {
519 CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
523 Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
524 Handle<SharedFunctionInfo> function_info,
525 Handle<Map> function_map,
526 PretenureFlag pretenure) {
529 isolate()->heap()->AllocateFunction(*function_map,
531 isolate()->heap()->the_hole_value(),
537 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
538 Handle<SharedFunctionInfo> function_info,
539 Handle<Context> context,
540 PretenureFlag pretenure) {
541 Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
543 function_info->is_classic_mode()
544 ? isolate()->function_map()
545 : isolate()->strict_mode_function_map(),
548 if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
549 function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
552 result->set_context(*context);
553 if (!function_info->bound()) {
554 int number_of_literals = function_info->num_literals();
555 Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
556 if (number_of_literals > 0) {
557 // Store the object, regexp and array functions in the literals
558 // array prefix. These functions will be used when creating
559 // object, regexp and array literals in this function.
560 literals->set(JSFunction::kLiteralGlobalContextIndex,
561 context->global_context());
563 result->set_literals(*literals);
565 if (V8::UseCrankshaft() &&
567 result->is_compiled() &&
568 !function_info->is_toplevel() &&
569 function_info->allows_lazy_compilation() &&
570 !function_info->optimization_disabled()) {
571 result->MarkForLazyRecompilation();
577 Handle<Object> Factory::NewNumber(double value,
578 PretenureFlag pretenure) {
581 isolate()->heap()->NumberFromDouble(value, pretenure), Object);
585 Handle<Object> Factory::NewNumberFromInt(int32_t value,
586 PretenureFlag pretenure) {
589 isolate()->heap()->NumberFromInt32(value, pretenure), Object);
593 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
594 PretenureFlag pretenure) {
597 isolate()->heap()->NumberFromUint32(value, pretenure), Object);
601 Handle<JSObject> Factory::NewNeanderObject() {
604 isolate()->heap()->AllocateJSObjectFromMap(
605 isolate()->heap()->neander_map()),
610 Handle<Object> Factory::NewTypeError(const char* type,
611 Vector< Handle<Object> > args) {
612 return NewError("MakeTypeError", type, args);
616 Handle<Object> Factory::NewTypeError(Handle<String> message) {
617 return NewError("$TypeError", message);
621 Handle<Object> Factory::NewRangeError(const char* type,
622 Vector< Handle<Object> > args) {
623 return NewError("MakeRangeError", type, args);
627 Handle<Object> Factory::NewRangeError(Handle<String> message) {
628 return NewError("$RangeError", message);
632 Handle<Object> Factory::NewSyntaxError(const char* type, Handle<JSArray> args) {
633 return NewError("MakeSyntaxError", type, args);
637 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
638 return NewError("$SyntaxError", message);
642 Handle<Object> Factory::NewReferenceError(const char* type,
643 Vector< Handle<Object> > args) {
644 return NewError("MakeReferenceError", type, args);
648 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
649 return NewError("$ReferenceError", message);
653 Handle<Object> Factory::NewError(const char* maker, const char* type,
654 Vector< Handle<Object> > args) {
655 v8::HandleScope scope; // Instantiate a closeable HandleScope for EscapeFrom.
656 Handle<FixedArray> array = NewFixedArray(args.length());
657 for (int i = 0; i < args.length(); i++) {
658 array->set(i, *args[i]);
660 Handle<JSArray> object = NewJSArrayWithElements(array);
661 Handle<Object> result = NewError(maker, type, object);
662 return result.EscapeFrom(&scope);
666 Handle<Object> Factory::NewEvalError(const char* type,
667 Vector< Handle<Object> > args) {
668 return NewError("MakeEvalError", type, args);
672 Handle<Object> Factory::NewError(const char* type,
673 Vector< Handle<Object> > args) {
674 return NewError("MakeError", type, args);
678 Handle<Object> Factory::NewError(const char* maker,
680 Handle<JSArray> args) {
681 Handle<String> make_str = LookupAsciiSymbol(maker);
682 Handle<Object> fun_obj(
683 isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str));
684 // If the builtins haven't been properly configured yet this error
685 // constructor may not have been defined. Bail out.
686 if (!fun_obj->IsJSFunction())
687 return undefined_value();
688 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
689 Handle<Object> type_obj = LookupAsciiSymbol(type);
690 Handle<Object> argv[] = { type_obj, args };
692 // Invoke the JavaScript factory method. If an exception is thrown while
693 // running the factory method, use the exception as the result.
694 bool caught_exception;
695 Handle<Object> result = Execution::TryCall(fun,
696 isolate()->js_builtins_object(),
704 Handle<Object> Factory::NewError(Handle<String> message) {
705 return NewError("$Error", message);
709 Handle<Object> Factory::NewError(const char* constructor,
710 Handle<String> message) {
711 Handle<String> constr = LookupAsciiSymbol(constructor);
712 Handle<JSFunction> fun = Handle<JSFunction>(
713 JSFunction::cast(isolate()->js_builtins_object()->
714 GetPropertyNoExceptionThrown(*constr)));
715 Handle<Object> argv[] = { message };
717 // Invoke the JavaScript factory method. If an exception is thrown while
718 // running the factory method, use the exception as the result.
719 bool caught_exception;
720 Handle<Object> result = Execution::TryCall(fun,
721 isolate()->js_builtins_object(),
729 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
733 bool force_initial_map) {
734 // Allocate the function
735 Handle<JSFunction> function = NewFunction(name, the_hole_value());
737 // Set up the code pointer in both the shared function info and in
738 // the function itself.
739 function->shared()->set_code(*code);
740 function->set_code(*code);
742 if (force_initial_map ||
743 type != JS_OBJECT_TYPE ||
744 instance_size != JSObject::kHeaderSize) {
745 Handle<Map> initial_map = NewMap(type, instance_size);
746 Handle<JSObject> prototype = NewFunctionPrototype(function);
747 initial_map->set_prototype(*prototype);
748 function->set_initial_map(*initial_map);
749 initial_map->set_constructor(*function);
751 ASSERT(!function->has_initial_map());
752 ASSERT(!function->has_prototype());
759 Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
762 Handle<JSObject> prototype,
764 bool force_initial_map) {
765 // Allocate the function.
766 Handle<JSFunction> function = NewFunction(name, prototype);
768 // Set up the code pointer in both the shared function info and in
769 // the function itself.
770 function->shared()->set_code(*code);
771 function->set_code(*code);
773 if (force_initial_map ||
774 type != JS_OBJECT_TYPE ||
775 instance_size != JSObject::kHeaderSize) {
776 Handle<Map> initial_map = NewMap(type,
778 FAST_SMI_ONLY_ELEMENTS);
779 function->set_initial_map(*initial_map);
780 initial_map->set_constructor(*function);
783 // Set function.prototype and give the prototype a constructor
784 // property that refers to the function.
785 SetPrototypeProperty(function, prototype);
786 // Currently safe because it is only invoked from Genesis.
787 CHECK_NOT_EMPTY_HANDLE(isolate(),
788 JSObject::SetLocalPropertyIgnoreAttributes(
789 prototype, constructor_symbol(),
790 function, DONT_ENUM));
795 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
797 Handle<JSFunction> function = NewFunctionWithoutPrototype(name,
799 function->shared()->set_code(*code);
800 function->set_code(*code);
801 ASSERT(!function->has_initial_map());
802 ASSERT(!function->has_prototype());
807 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
810 isolate()->heap()->AllocateScopeInfo(length),
815 Handle<Code> Factory::NewCode(const CodeDesc& desc,
817 Handle<Object> self_ref,
819 CALL_HEAP_FUNCTION(isolate(),
820 isolate()->heap()->CreateCode(
821 desc, flags, self_ref, immovable),
826 Handle<Code> Factory::CopyCode(Handle<Code> code) {
827 CALL_HEAP_FUNCTION(isolate(),
828 isolate()->heap()->CopyCode(*code),
833 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
834 CALL_HEAP_FUNCTION(isolate(),
835 isolate()->heap()->CopyCode(*code, reloc_info),
840 MUST_USE_RESULT static inline MaybeObject* DoCopyInsert(
841 DescriptorArray* array,
844 PropertyAttributes attributes) {
845 CallbacksDescriptor desc(key, value, attributes);
846 MaybeObject* obj = array->CopyInsert(&desc, REMOVE_TRANSITIONS);
851 // Allocate the new array.
852 Handle<DescriptorArray> Factory::CopyAppendForeignDescriptor(
853 Handle<DescriptorArray> array,
855 Handle<Object> value,
856 PropertyAttributes attributes) {
857 CALL_HEAP_FUNCTION(isolate(),
858 DoCopyInsert(*array, *key, *value, attributes),
863 Handle<String> Factory::SymbolFromString(Handle<String> value) {
864 CALL_HEAP_FUNCTION(isolate(),
865 isolate()->heap()->LookupSymbol(*value), String);
869 Handle<DescriptorArray> Factory::CopyAppendCallbackDescriptors(
870 Handle<DescriptorArray> array,
871 Handle<Object> descriptors) {
872 v8::NeanderArray callbacks(descriptors);
873 int nof_callbacks = callbacks.length();
874 Handle<DescriptorArray> result =
875 NewDescriptorArray(array->number_of_descriptors() + nof_callbacks);
877 // Number of descriptors added to the result so far.
878 int descriptor_count = 0;
880 // Ensure that marking will not progress and change color of objects.
881 DescriptorArray::WhitenessWitness witness(*result);
883 // Copy the descriptors from the array.
884 for (int i = 0; i < array->number_of_descriptors(); i++) {
885 if (!array->IsNullDescriptor(i)) {
886 DescriptorArray::CopyFrom(result, descriptor_count++, array, i, witness);
890 // Number of duplicates detected.
893 // Fill in new callback descriptors. Process the callbacks from
894 // back to front so that the last callback with a given name takes
895 // precedence over previously added callbacks with that name.
896 for (int i = nof_callbacks - 1; i >= 0; i--) {
897 Handle<AccessorInfo> entry =
898 Handle<AccessorInfo>(AccessorInfo::cast(callbacks.get(i)));
899 // Ensure the key is a symbol before writing into the instance descriptor.
901 SymbolFromString(Handle<String>(String::cast(entry->name())));
902 // Check if a descriptor with this name already exists before writing.
903 if (result->LinearSearch(*key, descriptor_count) ==
904 DescriptorArray::kNotFound) {
905 CallbacksDescriptor desc(*key, *entry, entry->property_attributes());
906 result->Set(descriptor_count, &desc, witness);
913 // If duplicates were detected, allocate a result of the right size
914 // and transfer the elements.
915 if (duplicates > 0) {
916 int number_of_descriptors = result->number_of_descriptors() - duplicates;
917 Handle<DescriptorArray> new_result =
918 NewDescriptorArray(number_of_descriptors);
919 for (int i = 0; i < number_of_descriptors; i++) {
920 DescriptorArray::CopyFrom(new_result, i, result, i, witness);
925 // Sort the result before returning.
926 result->Sort(witness);
931 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
932 PretenureFlag pretenure) {
935 isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
939 Handle<JSModule> Factory::NewJSModule() {
942 isolate()->heap()->AllocateJSModule(), JSModule);
946 Handle<GlobalObject> Factory::NewGlobalObject(
947 Handle<JSFunction> constructor) {
948 CALL_HEAP_FUNCTION(isolate(),
949 isolate()->heap()->AllocateGlobalObject(*constructor),
955 Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map) {
958 isolate()->heap()->AllocateJSObjectFromMap(*map, NOT_TENURED),
963 Handle<JSArray> Factory::NewJSArray(int capacity,
964 ElementsKind elements_kind,
965 PretenureFlag pretenure) {
966 CALL_HEAP_FUNCTION(isolate(),
967 isolate()->heap()->AllocateJSArrayAndStorage(
971 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
977 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
978 ElementsKind elements_kind,
979 PretenureFlag pretenure) {
982 isolate()->heap()->AllocateJSArrayWithElements(*elements,
989 void Factory::SetElementsCapacityAndLength(Handle<JSArray> array,
992 ElementsAccessor* accessor = array->GetElementsAccessor();
993 CALL_HEAP_FUNCTION_VOID(
995 accessor->SetCapacityAndLength(*array, capacity, length));
999 void Factory::SetContent(Handle<JSArray> array,
1000 Handle<FixedArrayBase> elements) {
1001 CALL_HEAP_FUNCTION_VOID(
1003 array->SetContent(*elements));
1007 void Factory::EnsureCanContainHeapObjectElements(Handle<JSArray> array) {
1008 CALL_HEAP_FUNCTION_VOID(
1010 array->EnsureCanContainHeapObjectElements());
1014 void Factory::EnsureCanContainElements(Handle<JSArray> array,
1015 Handle<FixedArrayBase> elements,
1016 EnsureElementsMode mode) {
1017 CALL_HEAP_FUNCTION_VOID(
1019 array->EnsureCanContainElements(*elements, mode));
1023 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1024 Handle<Object> prototype) {
1027 isolate()->heap()->AllocateJSProxy(*handler, *prototype),
1032 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1033 CALL_HEAP_FUNCTION_VOID(
1035 isolate()->heap()->ReinitializeJSReceiver(
1036 *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
1040 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1041 CALL_HEAP_FUNCTION_VOID(
1043 isolate()->heap()->ReinitializeJSReceiver(
1044 *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1048 void Factory::SetIdentityHash(Handle<JSObject> object, Object* hash) {
1049 CALL_HEAP_FUNCTION_VOID(
1051 object->SetIdentityHash(hash, ALLOW_CREATION));
1055 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1056 Handle<String> name,
1057 int number_of_literals,
1059 Handle<ScopeInfo> scope_info) {
1060 Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
1061 shared->set_code(*code);
1062 shared->set_scope_info(*scope_info);
1063 int literals_array_size = number_of_literals;
1064 // If the function contains object, regexp or array literals,
1065 // allocate extra space for a literals array prefix containing the
1067 if (number_of_literals > 0) {
1068 literals_array_size += JSFunction::kLiteralsPrefixSize;
1070 shared->set_num_literals(literals_array_size);
1075 Handle<JSMessageObject> Factory::NewJSMessageObject(
1076 Handle<String> type,
1077 Handle<JSArray> arguments,
1080 Handle<Object> script,
1081 Handle<Object> stack_trace,
1082 Handle<Object> stack_frames) {
1083 CALL_HEAP_FUNCTION(isolate(),
1084 isolate()->heap()->AllocateJSMessageObject(*type,
1094 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1095 CALL_HEAP_FUNCTION(isolate(),
1096 isolate()->heap()->AllocateSharedFunctionInfo(*name),
1097 SharedFunctionInfo);
1101 Handle<String> Factory::NumberToString(Handle<Object> number) {
1102 CALL_HEAP_FUNCTION(isolate(),
1103 isolate()->heap()->NumberToString(*number), String);
1107 Handle<String> Factory::Uint32ToString(uint32_t value) {
1108 CALL_HEAP_FUNCTION(isolate(),
1109 isolate()->heap()->Uint32ToString(value), String);
1113 Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
1114 Handle<SeededNumberDictionary> dictionary,
1116 Handle<Object> value) {
1117 CALL_HEAP_FUNCTION(isolate(),
1118 dictionary->AtNumberPut(key, *value),
1119 SeededNumberDictionary);
1123 Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
1124 Handle<UnseededNumberDictionary> dictionary,
1126 Handle<Object> value) {
1127 CALL_HEAP_FUNCTION(isolate(),
1128 dictionary->AtNumberPut(key, *value),
1129 UnseededNumberDictionary);
1133 Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
1134 Handle<Object> prototype) {
1135 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1138 isolate()->heap()->AllocateFunction(*isolate()->function_map(),
1145 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1146 Handle<Object> prototype) {
1147 Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1148 fun->set_context(isolate()->context()->global_context());
1153 Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1154 Handle<String> name,
1155 LanguageMode language_mode) {
1156 Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1157 Handle<Map> map = (language_mode == CLASSIC_MODE)
1158 ? isolate()->function_without_prototype_map()
1159 : isolate()->strict_mode_function_without_prototype_map();
1160 CALL_HEAP_FUNCTION(isolate(),
1161 isolate()->heap()->AllocateFunction(
1169 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
1170 Handle<String> name,
1171 LanguageMode language_mode) {
1172 Handle<JSFunction> fun =
1173 NewFunctionWithoutPrototypeHelper(name, language_mode);
1174 fun->set_context(isolate()->context()->global_context());
1179 Handle<Object> Factory::ToObject(Handle<Object> object) {
1180 CALL_HEAP_FUNCTION(isolate(), object->ToObject(), Object);
1184 Handle<Object> Factory::ToObject(Handle<Object> object,
1185 Handle<Context> global_context) {
1186 CALL_HEAP_FUNCTION(isolate(), object->ToObject(*global_context), Object);
1190 #ifdef ENABLE_DEBUGGER_SUPPORT
1191 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
1192 // Get the original code of the function.
1193 Handle<Code> code(shared->code());
1195 // Create a copy of the code before allocating the debug info object to avoid
1196 // allocation while setting up the debug info object.
1197 Handle<Code> original_code(*Factory::CopyCode(code));
1199 // Allocate initial fixed array for active break points before allocating the
1200 // debug info object to avoid allocation while setting up the debug info
1202 Handle<FixedArray> break_points(
1203 NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1205 // Create and set up the debug info object. Debug info contains function, a
1206 // copy of the original code, the executing code and initial fixed array for
1207 // active break points.
1208 Handle<DebugInfo> debug_info =
1209 Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1210 debug_info->set_shared(*shared);
1211 debug_info->set_original_code(*original_code);
1212 debug_info->set_code(*code);
1213 debug_info->set_break_points(*break_points);
1215 // Link debug info to function.
1216 shared->set_debug_info(*debug_info);
1223 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
1227 isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1231 Handle<JSFunction> Factory::CreateApiFunction(
1232 Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1233 Handle<Code> code = isolate()->builtins()->HandleApiCall();
1234 Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1236 int internal_field_count = 0;
1237 bool has_external_resource = false;
1239 if (!obj->instance_template()->IsUndefined()) {
1240 Handle<ObjectTemplateInfo> instance_template =
1241 Handle<ObjectTemplateInfo>(
1242 ObjectTemplateInfo::cast(obj->instance_template()));
1243 internal_field_count =
1244 Smi::cast(instance_template->internal_field_count())->value();
1245 has_external_resource =
1246 !instance_template->has_external_resource()->IsUndefined();
1249 int instance_size = kPointerSize * internal_field_count;
1250 if (has_external_resource) instance_size += kPointerSize;
1252 InstanceType type = INVALID_TYPE;
1253 switch (instance_type) {
1254 case JavaScriptObject:
1255 type = JS_OBJECT_TYPE;
1256 instance_size += JSObject::kHeaderSize;
1258 case InnerGlobalObject:
1259 type = JS_GLOBAL_OBJECT_TYPE;
1260 instance_size += JSGlobalObject::kSize;
1262 case OuterGlobalObject:
1263 type = JS_GLOBAL_PROXY_TYPE;
1264 instance_size += JSGlobalProxy::kSize;
1269 ASSERT(type != INVALID_TYPE);
1271 Handle<JSFunction> result =
1272 NewFunction(Factory::empty_symbol(),
1278 Handle<Object> class_name = Handle<Object>(obj->class_name());
1279 if (class_name->IsString()) {
1280 result->shared()->set_instance_class_name(*class_name);
1281 result->shared()->set_name(*class_name);
1284 Handle<Map> map = Handle<Map>(result->initial_map());
1286 // Mark as having external data object if needed
1287 if (has_external_resource) {
1288 map->set_has_external_resource(true);
1291 // Mark as undetectable if needed.
1292 if (obj->undetectable()) {
1293 map->set_is_undetectable();
1296 // Mark as hidden for the __proto__ accessor if needed.
1297 if (obj->hidden_prototype()) {
1298 map->set_is_hidden_prototype();
1301 // Mark as needs_access_check if needed.
1302 if (obj->needs_access_check()) {
1303 map->set_is_access_check_needed(true);
1306 // Set interceptor information in the map.
1307 if (!obj->named_property_handler()->IsUndefined()) {
1308 map->set_has_named_interceptor();
1309 InterceptorInfo *nph = InterceptorInfo::cast(obj->named_property_handler());
1311 nph->is_fallback()->IsUndefined()?false:nph->is_fallback()->value();
1312 map->set_named_interceptor_is_fallback(is_fallback);
1314 if (!obj->indexed_property_handler()->IsUndefined()) {
1315 map->set_has_indexed_interceptor();
1318 // Set instance call-as-function information in the map.
1319 if (!obj->instance_call_handler()->IsUndefined()) {
1320 map->set_has_instance_call_handler();
1323 result->shared()->set_function_data(*obj);
1324 result->shared()->set_construct_stub(*construct_stub);
1325 result->shared()->DontAdaptArguments();
1327 // Recursively copy parent templates' accessors, 'data' may be modified.
1328 Handle<DescriptorArray> array =
1329 Handle<DescriptorArray>(map->instance_descriptors());
1331 Handle<Object> props = Handle<Object>(obj->property_accessors());
1332 if (!props->IsUndefined()) {
1333 array = CopyAppendCallbackDescriptors(array, props);
1335 Handle<Object> parent = Handle<Object>(obj->parent_template());
1336 if (parent->IsUndefined()) break;
1337 obj = Handle<FunctionTemplateInfo>::cast(parent);
1339 if (!array->IsEmpty()) {
1340 map->set_instance_descriptors(*array);
1343 ASSERT(result->shared()->IsApiFunction());
1348 Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1349 CALL_HEAP_FUNCTION(isolate(),
1350 MapCache::Allocate(at_least_space_for), MapCache);
1354 MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
1358 { MaybeObject* maybe_result =
1359 MapCache::cast(context->map_cache())->Put(keys, map);
1360 if (!maybe_result->ToObject(&result)) return maybe_result;
1362 context->set_map_cache(MapCache::cast(result));
1367 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1368 Handle<FixedArray> keys,
1370 CALL_HEAP_FUNCTION(isolate(),
1371 UpdateMapCacheWith(*context, *keys, *map), MapCache);
1375 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1376 Handle<FixedArray> keys) {
1377 if (context->map_cache()->IsUndefined()) {
1378 // Allocate the new map cache for the global context.
1379 Handle<MapCache> new_cache = NewMapCache(24);
1380 context->set_map_cache(*new_cache);
1382 // Check to see whether there is a matching element in the cache.
1383 Handle<MapCache> cache =
1384 Handle<MapCache>(MapCache::cast(context->map_cache()));
1385 Handle<Object> result = Handle<Object>(cache->Lookup(*keys));
1386 if (result->IsMap()) return Handle<Map>::cast(result);
1387 // Create a new map and add it to the cache.
1389 CopyMap(Handle<Map>(context->object_function()->initial_map()),
1391 AddToMapCache(context, keys, map);
1392 return Handle<Map>(map);
1396 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1397 JSRegExp::Type type,
1398 Handle<String> source,
1399 JSRegExp::Flags flags,
1400 Handle<Object> data) {
1401 Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1403 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1404 store->set(JSRegExp::kSourceIndex, *source);
1405 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1406 store->set(JSRegExp::kAtomPatternIndex, *data);
1407 regexp->set_data(*store);
1410 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1411 JSRegExp::Type type,
1412 Handle<String> source,
1413 JSRegExp::Flags flags,
1414 int capture_count) {
1415 Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1416 Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1417 store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1418 store->set(JSRegExp::kSourceIndex, *source);
1419 store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1420 store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
1421 store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
1422 store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
1423 store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1424 store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
1425 store->set(JSRegExp::kIrregexpCaptureCountIndex,
1426 Smi::FromInt(capture_count));
1427 regexp->set_data(*store);
1432 void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
1433 Handle<JSObject> instance,
1434 bool* pending_exception) {
1435 // Configure the instance by adding the properties specified by the
1436 // instance template.
1437 Handle<Object> instance_template = Handle<Object>(desc->instance_template());
1438 if (!instance_template->IsUndefined()) {
1439 Execution::ConfigureInstance(instance,
1443 *pending_exception = false;
1448 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
1449 Heap* h = isolate()->heap();
1450 if (name->Equals(h->undefined_symbol())) return undefined_value();
1451 if (name->Equals(h->nan_symbol())) return nan_value();
1452 if (name->Equals(h->infinity_symbol())) return infinity_value();
1453 return Handle<Object>::null();
1457 Handle<Object> Factory::ToBoolean(bool value) {
1458 return Handle<Object>(value
1459 ? isolate()->heap()->true_value()
1460 : isolate()->heap()->false_value());
1464 } } // namespace v8::internal