Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / v8 / src / factory.cc
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
4 // met:
5 //
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.
15 //
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.
27
28 #include "v8.h"
29
30 #include "api.h"
31 #include "debug.h"
32 #include "execution.h"
33 #include "factory.h"
34 #include "isolate-inl.h"
35 #include "macro-assembler.h"
36 #include "objects.h"
37 #include "objects-visiting.h"
38 #include "platform.h"
39 #include "scopeinfo.h"
40
41 namespace v8 {
42 namespace internal {
43
44
45 Handle<Box> Factory::NewBox(Handle<Object> value, PretenureFlag pretenure) {
46   CALL_HEAP_FUNCTION(
47       isolate(),
48       isolate()->heap()->AllocateBox(*value, pretenure),
49       Box);
50 }
51
52
53 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
54   ASSERT(0 <= size);
55   CALL_HEAP_FUNCTION(
56       isolate(),
57       isolate()->heap()->AllocateFixedArray(size, pretenure),
58       FixedArray);
59 }
60
61
62 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
63                                                    PretenureFlag pretenure) {
64   ASSERT(0 <= size);
65   CALL_HEAP_FUNCTION(
66       isolate(),
67       isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
68       FixedArray);
69 }
70
71
72 Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
73                                                       PretenureFlag pretenure) {
74   ASSERT(0 <= size);
75   CALL_HEAP_FUNCTION(
76       isolate(),
77       isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
78       FixedDoubleArray);
79 }
80
81
82 Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
83     int number_of_int64_entries,
84     int number_of_ptr_entries,
85     int number_of_int32_entries) {
86   ASSERT(number_of_int64_entries > 0 || number_of_ptr_entries > 0 ||
87          number_of_int32_entries > 0);
88   CALL_HEAP_FUNCTION(
89       isolate(),
90       isolate()->heap()->AllocateConstantPoolArray(number_of_int64_entries,
91                                                    number_of_ptr_entries,
92                                                    number_of_int32_entries),
93       ConstantPoolArray);
94 }
95
96
97 Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
98   ASSERT(0 <= at_least_space_for);
99   CALL_HEAP_FUNCTION(isolate(),
100                      NameDictionary::Allocate(isolate()->heap(),
101                                               at_least_space_for),
102                      NameDictionary);
103 }
104
105
106 Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
107     int at_least_space_for) {
108   ASSERT(0 <= at_least_space_for);
109   CALL_HEAP_FUNCTION(isolate(),
110                      SeededNumberDictionary::Allocate(isolate()->heap(),
111                                                       at_least_space_for),
112                      SeededNumberDictionary);
113 }
114
115
116 Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
117     int at_least_space_for) {
118   ASSERT(0 <= at_least_space_for);
119   CALL_HEAP_FUNCTION(isolate(),
120                      UnseededNumberDictionary::Allocate(isolate()->heap(),
121                                                         at_least_space_for),
122                      UnseededNumberDictionary);
123 }
124
125
126 Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
127   ASSERT(0 <= at_least_space_for);
128   CALL_HEAP_FUNCTION(isolate(),
129                      ObjectHashSet::Allocate(isolate()->heap(),
130                                              at_least_space_for),
131                      ObjectHashSet);
132 }
133
134
135 Handle<ObjectHashTable> Factory::NewObjectHashTable(
136     int at_least_space_for,
137     MinimumCapacity capacity_option) {
138   ASSERT(0 <= at_least_space_for);
139   CALL_HEAP_FUNCTION(isolate(),
140                      ObjectHashTable::Allocate(isolate()->heap(),
141                                                at_least_space_for,
142                                                capacity_option),
143                      ObjectHashTable);
144 }
145
146
147 Handle<WeakHashTable> Factory::NewWeakHashTable(int at_least_space_for) {
148   ASSERT(0 <= at_least_space_for);
149   CALL_HEAP_FUNCTION(
150       isolate(),
151       WeakHashTable::Allocate(isolate()->heap(),
152                               at_least_space_for,
153                               USE_DEFAULT_MINIMUM_CAPACITY,
154                               TENURED),
155       WeakHashTable);
156 }
157
158
159 Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
160                                                     int slack) {
161   ASSERT(0 <= number_of_descriptors);
162   CALL_HEAP_FUNCTION(isolate(),
163                      DescriptorArray::Allocate(
164                          isolate(), number_of_descriptors, slack),
165                      DescriptorArray);
166 }
167
168
169 Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
170     int deopt_entry_count,
171     PretenureFlag pretenure) {
172   ASSERT(deopt_entry_count > 0);
173   CALL_HEAP_FUNCTION(isolate(),
174                      DeoptimizationInputData::Allocate(isolate(),
175                                                        deopt_entry_count,
176                                                        pretenure),
177                      DeoptimizationInputData);
178 }
179
180
181 Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
182     int deopt_entry_count,
183     PretenureFlag pretenure) {
184   ASSERT(deopt_entry_count > 0);
185   CALL_HEAP_FUNCTION(isolate(),
186                      DeoptimizationOutputData::Allocate(isolate(),
187                                                         deopt_entry_count,
188                                                         pretenure),
189                      DeoptimizationOutputData);
190 }
191
192
193 Handle<AccessorPair> Factory::NewAccessorPair() {
194   CALL_HEAP_FUNCTION(isolate(),
195                      isolate()->heap()->AllocateAccessorPair(),
196                      AccessorPair);
197 }
198
199
200 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
201   CALL_HEAP_FUNCTION(isolate(),
202                      isolate()->heap()->AllocateTypeFeedbackInfo(),
203                      TypeFeedbackInfo);
204 }
205
206
207 // Internalized strings are created in the old generation (data space).
208 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
209   Utf8StringKey key(string, isolate()->heap()->HashSeed());
210   return InternalizeStringWithKey(&key);
211 }
212
213
214 // Internalized strings are created in the old generation (data space).
215 Handle<String> Factory::InternalizeString(Handle<String> string) {
216   CALL_HEAP_FUNCTION(isolate(),
217                      isolate()->heap()->InternalizeString(*string),
218                      String);
219 }
220
221
222 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
223   OneByteStringKey key(string, isolate()->heap()->HashSeed());
224   return InternalizeStringWithKey(&key);
225 }
226
227
228 Handle<String> Factory::InternalizeOneByteString(
229     Handle<SeqOneByteString> string, int from, int length) {
230   SubStringKey<uint8_t> key(string, from, length);
231   return InternalizeStringWithKey(&key);
232 }
233
234
235 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
236   TwoByteStringKey key(string, isolate()->heap()->HashSeed());
237   return InternalizeStringWithKey(&key);
238 }
239
240
241 template<class StringTableKey>
242 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
243   CALL_HEAP_FUNCTION(isolate(),
244                      isolate()->heap()->InternalizeStringWithKey(key),
245                      String);
246 }
247
248
249 template Handle<String> Factory::InternalizeStringWithKey<
250     SubStringKey<uint8_t> > (SubStringKey<uint8_t>* key);
251 template Handle<String> Factory::InternalizeStringWithKey<
252     SubStringKey<uint16_t> > (SubStringKey<uint16_t>* key);
253
254
255 Handle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
256                                              PretenureFlag pretenure) {
257   CALL_HEAP_FUNCTION(
258       isolate(),
259       isolate()->heap()->AllocateStringFromOneByte(string, pretenure),
260       String);
261 }
262
263 Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
264                                           PretenureFlag pretenure) {
265   CALL_HEAP_FUNCTION(
266       isolate(),
267       isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
268       String);
269 }
270
271
272 Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
273                                              PretenureFlag pretenure) {
274   CALL_HEAP_FUNCTION(
275       isolate(),
276       isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
277       String);
278 }
279
280
281 Handle<SeqOneByteString> Factory::NewRawOneByteString(int length,
282                                                   PretenureFlag pretenure) {
283   CALL_HEAP_FUNCTION(
284       isolate(),
285       isolate()->heap()->AllocateRawOneByteString(length, pretenure),
286       SeqOneByteString);
287 }
288
289
290 Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
291                                                       PretenureFlag pretenure) {
292   CALL_HEAP_FUNCTION(
293       isolate(),
294       isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
295       SeqTwoByteString);
296 }
297
298
299 // Returns true for a character in a range.  Both limits are inclusive.
300 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
301   // This makes uses of the the unsigned wraparound.
302   return character - from <= to - from;
303 }
304
305
306 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
307                                                           uint16_t c1,
308                                                           uint16_t c2) {
309   // Numeric strings have a different hash algorithm not known by
310   // LookupTwoCharsStringIfExists, so we skip this step for such strings.
311   if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
312     String* result;
313     StringTable* table = isolate->heap()->string_table();
314     if (table->LookupTwoCharsStringIfExists(c1, c2, &result)) {
315       return handle(result);
316     }
317   }
318
319   // Now we know the length is 2, we might as well make use of that fact
320   // when building the new string.
321   if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
322     // We can do this.
323     ASSERT(IsPowerOf2(String::kMaxOneByteCharCodeU + 1));  // because of this.
324     Handle<SeqOneByteString> str = isolate->factory()->NewRawOneByteString(2);
325     uint8_t* dest = str->GetChars();
326     dest[0] = static_cast<uint8_t>(c1);
327     dest[1] = static_cast<uint8_t>(c2);
328     return str;
329   } else {
330     Handle<SeqTwoByteString> str = isolate->factory()->NewRawTwoByteString(2);
331     uc16* dest = str->GetChars();
332     dest[0] = c1;
333     dest[1] = c2;
334     return str;
335   }
336 }
337
338
339 template<typename SinkChar, typename StringType>
340 Handle<String> ConcatStringContent(Handle<StringType> result,
341                                    Handle<String> first,
342                                    Handle<String> second) {
343   DisallowHeapAllocation pointer_stays_valid;
344   SinkChar* sink = result->GetChars();
345   String::WriteToFlat(*first, sink, 0, first->length());
346   String::WriteToFlat(*second, sink + first->length(), 0, second->length());
347   return result;
348 }
349
350
351 Handle<ConsString> Factory::NewRawConsString(String::Encoding encoding) {
352   Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
353       ? cons_ascii_string_map() : cons_string_map();
354   CALL_HEAP_FUNCTION(isolate(),
355                      isolate()->heap()->Allocate(*map, NEW_SPACE),
356                      ConsString);
357 }
358
359
360 Handle<String> Factory::NewConsString(Handle<String> left,
361                                       Handle<String> right) {
362   int left_length = left->length();
363   if (left_length == 0) return right;
364   int right_length = right->length();
365   if (right_length == 0) return left;
366
367   int length = left_length + right_length;
368
369   if (length == 2) {
370     uint16_t c1 = left->Get(0);
371     uint16_t c2 = right->Get(0);
372     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
373   }
374
375   // Make sure that an out of memory exception is thrown if the length
376   // of the new cons string is too large.
377   if (length > String::kMaxLength || length < 0) {
378     isolate()->context()->mark_out_of_memory();
379     V8::FatalProcessOutOfMemory("String concatenation result too large.");
380     UNREACHABLE();
381     return Handle<String>::null();
382   }
383
384   bool left_is_one_byte = left->IsOneByteRepresentation();
385   bool right_is_one_byte = right->IsOneByteRepresentation();
386   bool is_one_byte = left_is_one_byte && right_is_one_byte;
387   bool is_one_byte_data_in_two_byte_string = false;
388   if (!is_one_byte) {
389     // At least one of the strings uses two-byte representation so we
390     // can't use the fast case code for short ASCII strings below, but
391     // we can try to save memory if all chars actually fit in ASCII.
392     is_one_byte_data_in_two_byte_string =
393         left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
394     if (is_one_byte_data_in_two_byte_string) {
395       isolate()->counters()->string_add_runtime_ext_to_ascii()->Increment();
396     }
397   }
398
399   // If the resulting string is small make a flat string.
400   if (length < ConsString::kMinLength) {
401     // Note that neither of the two inputs can be a slice because:
402     STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
403     ASSERT(left->IsFlat());
404     ASSERT(right->IsFlat());
405
406     if (is_one_byte) {
407       Handle<SeqOneByteString> result = NewRawOneByteString(length);
408       DisallowHeapAllocation no_gc;
409       uint8_t* dest = result->GetChars();
410       // Copy left part.
411       const uint8_t* src = left->IsExternalString()
412           ? Handle<ExternalAsciiString>::cast(left)->GetChars()
413           : Handle<SeqOneByteString>::cast(left)->GetChars();
414       for (int i = 0; i < left_length; i++) *dest++ = src[i];
415       // Copy right part.
416       src = right->IsExternalString()
417           ? Handle<ExternalAsciiString>::cast(right)->GetChars()
418           : Handle<SeqOneByteString>::cast(right)->GetChars();
419       for (int i = 0; i < right_length; i++) *dest++ = src[i];
420       return result;
421     }
422
423     return (is_one_byte_data_in_two_byte_string)
424         ? ConcatStringContent<uint8_t>(NewRawOneByteString(length), left, right)
425         : ConcatStringContent<uc16>(NewRawTwoByteString(length), left, right);
426   }
427
428   Handle<ConsString> result = NewRawConsString(
429       (is_one_byte || is_one_byte_data_in_two_byte_string)
430           ? String::ONE_BYTE_ENCODING
431           : String::TWO_BYTE_ENCODING);
432
433   DisallowHeapAllocation no_gc;
434   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
435
436   result->set_hash_field(String::kEmptyHashField);
437   result->set_length(length);
438   result->set_first(*left, mode);
439   result->set_second(*right, mode);
440   return result;
441 }
442
443
444 Handle<String> Factory::NewFlatConcatString(Handle<String> first,
445                                             Handle<String> second) {
446   int total_length = first->length() + second->length();
447   if (first->IsOneByteRepresentation() && second->IsOneByteRepresentation()) {
448     return ConcatStringContent<uint8_t>(
449         NewRawOneByteString(total_length), first, second);
450   } else {
451     return ConcatStringContent<uc16>(
452         NewRawTwoByteString(total_length), first, second);
453   }
454 }
455
456
457 Handle<SlicedString> Factory::NewRawSlicedString(String::Encoding encoding) {
458   Handle<Map> map = (encoding == String::ONE_BYTE_ENCODING)
459       ? sliced_ascii_string_map() : sliced_string_map();
460   CALL_HEAP_FUNCTION(isolate(),
461                      isolate()->heap()->Allocate(*map, NEW_SPACE),
462                      SlicedString);
463 }
464
465
466 Handle<String> Factory::NewProperSubString(Handle<String> str,
467                                            int begin,
468                                            int end) {
469 #if VERIFY_HEAP
470   if (FLAG_verify_heap) str->StringVerify();
471 #endif
472   ASSERT(begin > 0 || end < str->length());
473
474   int length = end - begin;
475   if (length <= 0) return empty_string();
476   if (length == 1) {
477     return LookupSingleCharacterStringFromCode(isolate(), str->Get(begin));
478   }
479   if (length == 2) {
480     // Optimization for 2-byte strings often used as keys in a decompression
481     // dictionary.  Check whether we already have the string in the string
482     // table to prevent creation of many unnecessary strings.
483     uint16_t c1 = str->Get(begin);
484     uint16_t c2 = str->Get(begin + 1);
485     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
486   }
487
488   if (!FLAG_string_slices || length < SlicedString::kMinLength) {
489     if (str->IsOneByteRepresentation()) {
490       Handle<SeqOneByteString> result = NewRawOneByteString(length);
491       uint8_t* dest = result->GetChars();
492       DisallowHeapAllocation no_gc;
493       String::WriteToFlat(*str, dest, begin, end);
494       return result;
495     } else {
496       Handle<SeqTwoByteString> result = NewRawTwoByteString(length);
497       uc16* dest = result->GetChars();
498       DisallowHeapAllocation no_gc;
499       String::WriteToFlat(*str, dest, begin, end);
500       return result;
501     }
502   }
503
504   int offset = begin;
505
506   while (str->IsConsString()) {
507     Handle<ConsString> cons = Handle<ConsString>::cast(str);
508     int split = cons->first()->length();
509     if (split <= offset) {
510       // Slice is fully contained in the second part.
511       str = Handle<String>(cons->second(), isolate());
512       offset -= split;  // Adjust for offset.
513       continue;
514     } else if (offset + length <= split) {
515       // Slice is fully contained in the first part.
516       str = Handle<String>(cons->first(), isolate());
517       continue;
518     }
519     break;
520   }
521
522   if (str->IsSlicedString()) {
523     Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
524     str = Handle<String>(slice->parent(), isolate());
525     offset += slice->offset();
526   } else {
527     str = FlattenGetString(str);
528   }
529
530   ASSERT(str->IsSeqString() || str->IsExternalString());
531   Handle<SlicedString> slice = NewRawSlicedString(
532       str->IsOneByteRepresentation() ? String::ONE_BYTE_ENCODING
533                                      : String::TWO_BYTE_ENCODING);
534
535   slice->set_hash_field(String::kEmptyHashField);
536   slice->set_length(length);
537   slice->set_parent(*str);
538   slice->set_offset(offset);
539   return slice;
540 }
541
542
543 Handle<String> Factory::NewExternalStringFromAscii(
544     const ExternalAsciiString::Resource* resource) {
545   CALL_HEAP_FUNCTION(
546       isolate(),
547       isolate()->heap()->AllocateExternalStringFromAscii(resource),
548       String);
549 }
550
551
552 Handle<String> Factory::NewExternalStringFromTwoByte(
553     const ExternalTwoByteString::Resource* resource) {
554   CALL_HEAP_FUNCTION(
555       isolate(),
556       isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
557       String);
558 }
559
560
561 Handle<Symbol> Factory::NewSymbol() {
562   CALL_HEAP_FUNCTION(
563       isolate(),
564       isolate()->heap()->AllocateSymbol(),
565       Symbol);
566 }
567
568
569 Handle<Symbol> Factory::NewPrivateSymbol() {
570   CALL_HEAP_FUNCTION(
571       isolate(),
572       isolate()->heap()->AllocatePrivateSymbol(),
573       Symbol);
574 }
575
576
577 Handle<Context> Factory::NewNativeContext() {
578   CALL_HEAP_FUNCTION(
579       isolate(),
580       isolate()->heap()->AllocateNativeContext(),
581       Context);
582 }
583
584
585 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
586                                           Handle<ScopeInfo> scope_info) {
587   CALL_HEAP_FUNCTION(
588       isolate(),
589       isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
590       Context);
591 }
592
593
594 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
595   CALL_HEAP_FUNCTION(
596       isolate(),
597       isolate()->heap()->AllocateModuleContext(*scope_info),
598       Context);
599 }
600
601
602 Handle<Context> Factory::NewFunctionContext(int length,
603                                             Handle<JSFunction> function) {
604   CALL_HEAP_FUNCTION(
605       isolate(),
606       isolate()->heap()->AllocateFunctionContext(length, *function),
607       Context);
608 }
609
610
611 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
612                                          Handle<Context> previous,
613                                          Handle<String> name,
614                                          Handle<Object> thrown_object) {
615   CALL_HEAP_FUNCTION(
616       isolate(),
617       isolate()->heap()->AllocateCatchContext(*function,
618                                               *previous,
619                                               *name,
620                                               *thrown_object),
621       Context);
622 }
623
624
625 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
626                                         Handle<Context> previous,
627                                         Handle<JSObject> extension) {
628   CALL_HEAP_FUNCTION(
629       isolate(),
630       isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
631       Context);
632 }
633
634
635 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
636                                          Handle<Context> previous,
637                                          Handle<ScopeInfo> scope_info) {
638   CALL_HEAP_FUNCTION(
639       isolate(),
640       isolate()->heap()->AllocateBlockContext(*function,
641                                               *previous,
642                                               *scope_info),
643       Context);
644 }
645
646
647 Handle<Struct> Factory::NewStruct(InstanceType type) {
648   CALL_HEAP_FUNCTION(
649       isolate(),
650       isolate()->heap()->AllocateStruct(type),
651       Struct);
652 }
653
654
655 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
656     int aliased_context_slot) {
657   Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
658       NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
659   entry->set_aliased_context_slot(aliased_context_slot);
660   return entry;
661 }
662
663
664 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
665   return Handle<DeclaredAccessorDescriptor>::cast(
666       NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
667 }
668
669
670 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
671   Handle<DeclaredAccessorInfo> info =
672       Handle<DeclaredAccessorInfo>::cast(
673           NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
674   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
675   return info;
676 }
677
678
679 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
680   Handle<ExecutableAccessorInfo> info =
681       Handle<ExecutableAccessorInfo>::cast(
682           NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
683   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
684   return info;
685 }
686
687
688 Handle<Script> Factory::NewScript(Handle<String> source) {
689   // Generate id for this script.
690   Heap* heap = isolate()->heap();
691   int id = heap->last_script_id()->value() + 1;
692   if (!Smi::IsValid(id) || id < 0) id = 1;
693   heap->set_last_script_id(Smi::FromInt(id));
694
695   // Create and initialize script object.
696   Handle<Foreign> wrapper = NewForeign(0, TENURED);
697   Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
698   script->set_source(*source);
699   script->set_name(heap->undefined_value());
700   script->set_id(Smi::FromInt(id));
701   script->set_line_offset(Smi::FromInt(0));
702   script->set_column_offset(Smi::FromInt(0));
703   script->set_data(heap->undefined_value());
704   script->set_context_data(heap->undefined_value());
705   script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
706   script->set_wrapper(*wrapper);
707   script->set_line_ends(heap->undefined_value());
708   script->set_eval_from_shared(heap->undefined_value());
709   script->set_eval_from_instructions_offset(Smi::FromInt(0));
710   script->set_flags(Smi::FromInt(0));
711
712   return script;
713 }
714
715
716 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
717   CALL_HEAP_FUNCTION(isolate(),
718                      isolate()->heap()->AllocateForeign(addr, pretenure),
719                      Foreign);
720 }
721
722
723 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
724   return NewForeign((Address) desc, TENURED);
725 }
726
727
728 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
729   ASSERT(0 <= length);
730   CALL_HEAP_FUNCTION(
731       isolate(),
732       isolate()->heap()->AllocateByteArray(length, pretenure),
733       ByteArray);
734 }
735
736
737 Handle<ExternalArray> Factory::NewExternalArray(int length,
738                                                 ExternalArrayType array_type,
739                                                 void* external_pointer,
740                                                 PretenureFlag pretenure) {
741   ASSERT(0 <= length && length <= Smi::kMaxValue);
742   CALL_HEAP_FUNCTION(
743       isolate(),
744       isolate()->heap()->AllocateExternalArray(length,
745                                                array_type,
746                                                external_pointer,
747                                                pretenure),
748       ExternalArray);
749 }
750
751
752 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
753     int length,
754     ExternalArrayType array_type,
755     PretenureFlag pretenure) {
756   ASSERT(0 <= length && length <= Smi::kMaxValue);
757   CALL_HEAP_FUNCTION(
758       isolate(),
759       isolate()->heap()->AllocateFixedTypedArray(length,
760                                                  array_type,
761                                                  pretenure),
762       FixedTypedArrayBase);
763 }
764
765
766 Handle<Cell> Factory::NewCell(Handle<Object> value) {
767   AllowDeferredHandleDereference convert_to_cell;
768   CALL_HEAP_FUNCTION(
769       isolate(),
770       isolate()->heap()->AllocateCell(*value),
771       Cell);
772 }
773
774
775 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
776   CALL_HEAP_FUNCTION(
777       isolate(),
778       isolate()->heap()->AllocatePropertyCell(),
779       PropertyCell);
780 }
781
782
783 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
784   AllowDeferredHandleDereference convert_to_cell;
785   Handle<PropertyCell> cell = NewPropertyCellWithHole();
786   PropertyCell::SetValueInferType(cell, value);
787   return cell;
788 }
789
790
791 Handle<AllocationSite> Factory::NewAllocationSite() {
792   CALL_HEAP_FUNCTION(
793       isolate(),
794       isolate()->heap()->AllocateAllocationSite(),
795       AllocationSite);
796 }
797
798
799 Handle<Map> Factory::NewMap(InstanceType type,
800                             int instance_size,
801                             ElementsKind elements_kind) {
802   CALL_HEAP_FUNCTION(
803       isolate(),
804       isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
805       Map);
806 }
807
808
809 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
810   // Make sure to use globals from the function's context, since the function
811   // can be from a different context.
812   Handle<Context> native_context(function->context()->native_context());
813   Handle<Map> new_map;
814   if (function->shared()->is_generator()) {
815     // Generator prototypes can share maps since they don't have "constructor"
816     // properties.
817     new_map = handle(native_context->generator_object_prototype_map());
818   } else {
819     // Each function prototype gets a fresh map to avoid unwanted sharing of
820     // maps between prototypes of different constructors.
821     Handle<JSFunction> object_function(native_context->object_function());
822     ASSERT(object_function->has_initial_map());
823     new_map = Map::Copy(handle(object_function->initial_map()));
824   }
825
826   Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
827
828   if (!function->shared()->is_generator()) {
829     JSObject::SetLocalPropertyIgnoreAttributes(prototype,
830                                                constructor_string(),
831                                                function,
832                                                DONT_ENUM);
833   }
834
835   return prototype;
836 }
837
838
839 Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
840   CALL_HEAP_FUNCTION(
841       isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
842 }
843
844
845 Handle<Map> Factory::CopyMap(Handle<Map> src,
846                              int extra_inobject_properties) {
847   Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
848   // Check that we do not overflow the instance size when adding the
849   // extra inobject properties.
850   int instance_size_delta = extra_inobject_properties * kPointerSize;
851   int max_instance_size_delta =
852       JSObject::kMaxInstanceSize - copy->instance_size();
853   int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2;
854   if (extra_inobject_properties > max_extra_properties) {
855     // If the instance size overflows, we allocate as many properties
856     // as we can as inobject properties.
857     instance_size_delta = max_instance_size_delta;
858     extra_inobject_properties = max_extra_properties;
859   }
860   // Adjust the map with the extra inobject properties.
861   int inobject_properties =
862       copy->inobject_properties() + extra_inobject_properties;
863   copy->set_inobject_properties(inobject_properties);
864   copy->set_unused_property_fields(inobject_properties);
865   copy->set_instance_size(copy->instance_size() + instance_size_delta);
866   copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
867   return copy;
868 }
869
870
871 Handle<Map> Factory::CopyMap(Handle<Map> src) {
872   CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
873 }
874
875
876 Handle<Map> Factory::GetElementsTransitionMap(
877     Handle<JSObject> src,
878     ElementsKind elements_kind) {
879   Isolate* i = isolate();
880   CALL_HEAP_FUNCTION(i,
881                      src->GetElementsTransitionMap(i, elements_kind),
882                      Map);
883 }
884
885
886 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
887   CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
888 }
889
890
891 Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
892                                                int new_length,
893                                                PretenureFlag pretenure) {
894   CALL_HEAP_FUNCTION(isolate(),
895                      array->CopySize(new_length, pretenure),
896                      FixedArray);
897 }
898
899
900 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
901     Handle<FixedDoubleArray> array) {
902   CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
903 }
904
905
906 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
907     Handle<ConstantPoolArray> array) {
908   CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
909 }
910
911
912 Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
913     Handle<SharedFunctionInfo> function_info,
914     Handle<Map> function_map,
915     PretenureFlag pretenure) {
916   CALL_HEAP_FUNCTION(
917       isolate(),
918       isolate()->heap()->AllocateFunction(*function_map,
919                                           *function_info,
920                                           isolate()->heap()->the_hole_value(),
921                                           pretenure),
922                      JSFunction);
923 }
924
925
926 static Handle<Map> MapForNewFunction(Isolate *isolate,
927                                      Handle<SharedFunctionInfo> function_info) {
928   Context *context = isolate->context()->native_context();
929   int map_index = Context::FunctionMapIndex(function_info->language_mode(),
930                                             function_info->is_generator());
931   return Handle<Map>(Map::cast(context->get(map_index)));
932 }
933
934
935 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
936     Handle<SharedFunctionInfo> function_info,
937     Handle<Context> context,
938     PretenureFlag pretenure) {
939   Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
940       function_info,
941       MapForNewFunction(isolate(), function_info),
942       pretenure);
943
944   if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
945     function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
946   }
947
948   result->set_context(*context);
949
950   int index = function_info->SearchOptimizedCodeMap(context->native_context(),
951                                                     BailoutId::None());
952   if (!function_info->bound() && index < 0) {
953     int number_of_literals = function_info->num_literals();
954     Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
955     if (number_of_literals > 0) {
956       // Store the native context in the literals array prefix. This
957       // context will be used when creating object, regexp and array
958       // literals in this function.
959       literals->set(JSFunction::kLiteralNativeContextIndex,
960                     context->native_context());
961     }
962     result->set_literals(*literals);
963   }
964
965   if (index > 0) {
966     // Caching of optimized code enabled and optimized code found.
967     FixedArray* literals =
968         function_info->GetLiteralsFromOptimizedCodeMap(index);
969     if (literals != NULL) result->set_literals(literals);
970     result->ReplaceCode(function_info->GetCodeFromOptimizedCodeMap(index));
971     return result;
972   }
973
974   if (isolate()->use_crankshaft() &&
975       FLAG_always_opt &&
976       result->is_compiled() &&
977       !function_info->is_toplevel() &&
978       function_info->allows_lazy_compilation() &&
979       !function_info->optimization_disabled() &&
980       !isolate()->DebuggerHasBreakPoints()) {
981     result->MarkForOptimization();
982   }
983   return result;
984 }
985
986
987 Handle<Object> Factory::NewNumber(double value,
988                                   PretenureFlag pretenure) {
989   CALL_HEAP_FUNCTION(
990       isolate(),
991       isolate()->heap()->NumberFromDouble(value, pretenure), Object);
992 }
993
994
995 Handle<Object> Factory::NewNumberFromInt(int32_t value,
996                                          PretenureFlag pretenure) {
997   CALL_HEAP_FUNCTION(
998       isolate(),
999       isolate()->heap()->NumberFromInt32(value, pretenure), Object);
1000 }
1001
1002
1003 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1004                                          PretenureFlag pretenure) {
1005   CALL_HEAP_FUNCTION(
1006       isolate(),
1007       isolate()->heap()->NumberFromUint32(value, pretenure), Object);
1008 }
1009
1010
1011 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1012                                           PretenureFlag pretenure) {
1013   CALL_HEAP_FUNCTION(
1014       isolate(),
1015       isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
1016 }
1017
1018
1019 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1020                                         PretenureFlag pretenure) {
1021   CALL_HEAP_FUNCTION(
1022       isolate(),
1023       isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1024 }
1025
1026
1027 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1028                                       PretenureFlag pretenure) {
1029   CALL_HEAP_FUNCTION(
1030       isolate(),
1031       isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1032 }
1033
1034
1035 Handle<JSObject> Factory::NewNeanderObject() {
1036   CALL_HEAP_FUNCTION(
1037       isolate(),
1038       isolate()->heap()->AllocateJSObjectFromMap(
1039           isolate()->heap()->neander_map()),
1040       JSObject);
1041 }
1042
1043
1044 Handle<Object> Factory::NewTypeError(const char* message,
1045                                      Vector< Handle<Object> > args) {
1046   return NewError("MakeTypeError", message, args);
1047 }
1048
1049
1050 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1051   return NewError("$TypeError", message);
1052 }
1053
1054
1055 Handle<Object> Factory::NewRangeError(const char* message,
1056                                       Vector< Handle<Object> > args) {
1057   return NewError("MakeRangeError", message, args);
1058 }
1059
1060
1061 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1062   return NewError("$RangeError", message);
1063 }
1064
1065
1066 Handle<Object> Factory::NewSyntaxError(const char* message,
1067                                        Handle<JSArray> args) {
1068   return NewError("MakeSyntaxError", message, args);
1069 }
1070
1071
1072 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1073   return NewError("$SyntaxError", message);
1074 }
1075
1076
1077 Handle<Object> Factory::NewReferenceError(const char* message,
1078                                           Vector< Handle<Object> > args) {
1079   return NewError("MakeReferenceError", message, args);
1080 }
1081
1082
1083 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1084   return NewError("$ReferenceError", message);
1085 }
1086
1087
1088 Handle<Object> Factory::NewError(const char* maker,
1089                                  const char* message,
1090                                  Vector< Handle<Object> > args) {
1091   // Instantiate a closeable HandleScope for EscapeFrom.
1092   v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1093   Handle<FixedArray> array = NewFixedArray(args.length());
1094   for (int i = 0; i < args.length(); i++) {
1095     array->set(i, *args[i]);
1096   }
1097   Handle<JSArray> object = NewJSArrayWithElements(array);
1098   Handle<Object> result = NewError(maker, message, object);
1099   return result.EscapeFrom(&scope);
1100 }
1101
1102
1103 Handle<Object> Factory::NewEvalError(const char* message,
1104                                      Vector< Handle<Object> > args) {
1105   return NewError("MakeEvalError", message, args);
1106 }
1107
1108
1109 Handle<Object> Factory::NewError(const char* message,
1110                                  Vector< Handle<Object> > args) {
1111   return NewError("MakeError", message, args);
1112 }
1113
1114
1115 Handle<String> Factory::EmergencyNewError(const char* message,
1116                                           Handle<JSArray> args) {
1117   const int kBufferSize = 1000;
1118   char buffer[kBufferSize];
1119   size_t space = kBufferSize;
1120   char* p = &buffer[0];
1121
1122   Vector<char> v(buffer, kBufferSize);
1123   OS::StrNCpy(v, message, space);
1124   space -= Min(space, strlen(message));
1125   p = &buffer[kBufferSize] - space;
1126
1127   for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1128     if (space > 0) {
1129       *p++ = ' ';
1130       space--;
1131       if (space > 0) {
1132         MaybeObject* maybe_arg = args->GetElement(isolate(), i);
1133         Handle<String> arg_str(reinterpret_cast<String*>(maybe_arg));
1134         SmartArrayPointer<char> arg = arg_str->ToCString();
1135         Vector<char> v2(p, static_cast<int>(space));
1136         OS::StrNCpy(v2, arg.get(), space);
1137         space -= Min(space, strlen(arg.get()));
1138         p = &buffer[kBufferSize] - space;
1139       }
1140     }
1141   }
1142   if (space > 0) {
1143     *p = '\0';
1144   } else {
1145     buffer[kBufferSize - 1] = '\0';
1146   }
1147   Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
1148   return error_string;
1149 }
1150
1151
1152 Handle<Object> Factory::NewError(const char* maker,
1153                                  const char* message,
1154                                  Handle<JSArray> args) {
1155   Handle<String> make_str = InternalizeUtf8String(maker);
1156   Handle<Object> fun_obj(
1157       isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
1158       isolate());
1159   // If the builtins haven't been properly configured yet this error
1160   // constructor may not have been defined.  Bail out.
1161   if (!fun_obj->IsJSFunction()) {
1162     return EmergencyNewError(message, args);
1163   }
1164   Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1165   Handle<Object> message_obj = InternalizeUtf8String(message);
1166   Handle<Object> argv[] = { message_obj, args };
1167
1168   // Invoke the JavaScript factory method. If an exception is thrown while
1169   // running the factory method, use the exception as the result.
1170   bool caught_exception;
1171   Handle<Object> result = Execution::TryCall(fun,
1172                                              isolate()->js_builtins_object(),
1173                                              ARRAY_SIZE(argv),
1174                                              argv,
1175                                              &caught_exception);
1176   return result;
1177 }
1178
1179
1180 Handle<Object> Factory::NewError(Handle<String> message) {
1181   return NewError("$Error", message);
1182 }
1183
1184
1185 Handle<Object> Factory::NewError(const char* constructor,
1186                                  Handle<String> message) {
1187   Handle<String> constr = InternalizeUtf8String(constructor);
1188   Handle<JSFunction> fun = Handle<JSFunction>(
1189       JSFunction::cast(isolate()->js_builtins_object()->
1190                        GetPropertyNoExceptionThrown(*constr)));
1191   Handle<Object> argv[] = { message };
1192
1193   // Invoke the JavaScript factory method. If an exception is thrown while
1194   // running the factory method, use the exception as the result.
1195   bool caught_exception;
1196   Handle<Object> result = Execution::TryCall(fun,
1197                                              isolate()->js_builtins_object(),
1198                                              ARRAY_SIZE(argv),
1199                                              argv,
1200                                              &caught_exception);
1201   return result;
1202 }
1203
1204
1205 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1206                                         InstanceType type,
1207                                         int instance_size,
1208                                         Handle<Code> code,
1209                                         bool force_initial_map) {
1210   // Allocate the function
1211   Handle<JSFunction> function = NewFunction(name, the_hole_value());
1212
1213   // Set up the code pointer in both the shared function info and in
1214   // the function itself.
1215   function->shared()->set_code(*code);
1216   function->set_code(*code);
1217
1218   if (force_initial_map ||
1219       type != JS_OBJECT_TYPE ||
1220       instance_size != JSObject::kHeaderSize) {
1221     Handle<Map> initial_map = NewMap(type, instance_size);
1222     Handle<JSObject> prototype = NewFunctionPrototype(function);
1223     initial_map->set_prototype(*prototype);
1224     function->set_initial_map(*initial_map);
1225     initial_map->set_constructor(*function);
1226   } else {
1227     ASSERT(!function->has_initial_map());
1228     ASSERT(!function->has_prototype());
1229   }
1230
1231   return function;
1232 }
1233
1234
1235 Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
1236                                                      InstanceType type,
1237                                                      int instance_size,
1238                                                      Handle<JSObject> prototype,
1239                                                      Handle<Code> code,
1240                                                      bool force_initial_map) {
1241   // Allocate the function.
1242   Handle<JSFunction> function = NewFunction(name, prototype);
1243
1244   // Set up the code pointer in both the shared function info and in
1245   // the function itself.
1246   function->shared()->set_code(*code);
1247   function->set_code(*code);
1248
1249   if (force_initial_map ||
1250       type != JS_OBJECT_TYPE ||
1251       instance_size != JSObject::kHeaderSize) {
1252     Handle<Map> initial_map = NewMap(type,
1253                                      instance_size,
1254                                      GetInitialFastElementsKind());
1255     function->set_initial_map(*initial_map);
1256     initial_map->set_constructor(*function);
1257   }
1258
1259   JSFunction::SetPrototype(function, prototype);
1260   return function;
1261 }
1262
1263
1264 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1265                                                         Handle<Code> code) {
1266   Handle<JSFunction> function = NewFunctionWithoutPrototype(name,
1267                                                             CLASSIC_MODE);
1268   function->shared()->set_code(*code);
1269   function->set_code(*code);
1270   ASSERT(!function->has_initial_map());
1271   ASSERT(!function->has_prototype());
1272   return function;
1273 }
1274
1275
1276 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1277   CALL_HEAP_FUNCTION(
1278       isolate(),
1279       isolate()->heap()->AllocateScopeInfo(length),
1280       ScopeInfo);
1281 }
1282
1283
1284 Handle<JSObject> Factory::NewExternal(void* value) {
1285   CALL_HEAP_FUNCTION(isolate(),
1286                      isolate()->heap()->AllocateExternal(value),
1287                      JSObject);
1288 }
1289
1290
1291 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1292                               Code::Flags flags,
1293                               Handle<Object> self_ref,
1294                               bool immovable,
1295                               bool crankshafted,
1296                               int prologue_offset) {
1297   CALL_HEAP_FUNCTION(isolate(),
1298                      isolate()->heap()->CreateCode(
1299                          desc, flags, self_ref, immovable, crankshafted,
1300                          prologue_offset),
1301                      Code);
1302 }
1303
1304
1305 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1306   CALL_HEAP_FUNCTION(isolate(),
1307                      isolate()->heap()->CopyCode(*code),
1308                      Code);
1309 }
1310
1311
1312 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1313   CALL_HEAP_FUNCTION(isolate(),
1314                      isolate()->heap()->CopyCode(*code, reloc_info),
1315                      Code);
1316 }
1317
1318
1319 Handle<String> Factory::InternalizedStringFromString(Handle<String> value) {
1320   CALL_HEAP_FUNCTION(isolate(),
1321                      isolate()->heap()->InternalizeString(*value), String);
1322 }
1323
1324
1325 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1326                                       PretenureFlag pretenure) {
1327   JSFunction::EnsureHasInitialMap(constructor);
1328   CALL_HEAP_FUNCTION(
1329       isolate(),
1330       isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1331 }
1332
1333
1334 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1335                                       Handle<ScopeInfo> scope_info) {
1336   CALL_HEAP_FUNCTION(
1337       isolate(),
1338       isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1339 }
1340
1341
1342 // TODO(mstarzinger): Temporary wrapper until handlified.
1343 static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
1344                                                 Handle<Name> name,
1345                                                 Handle<Object> value,
1346                                                 PropertyDetails details) {
1347   CALL_HEAP_FUNCTION(dict->GetIsolate(),
1348                      dict->Add(*name, *value, details),
1349                      NameDictionary);
1350 }
1351
1352
1353 static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
1354                                                    Handle<Map> map) {
1355   CALL_HEAP_FUNCTION(isolate,
1356                      isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1357                      GlobalObject);
1358 }
1359
1360
1361 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1362   ASSERT(constructor->has_initial_map());
1363   Handle<Map> map(constructor->initial_map());
1364   ASSERT(map->is_dictionary_map());
1365
1366   // Make sure no field properties are described in the initial map.
1367   // This guarantees us that normalizing the properties does not
1368   // require us to change property values to PropertyCells.
1369   ASSERT(map->NextFreePropertyIndex() == 0);
1370
1371   // Make sure we don't have a ton of pre-allocated slots in the
1372   // global objects. They will be unused once we normalize the object.
1373   ASSERT(map->unused_property_fields() == 0);
1374   ASSERT(map->inobject_properties() == 0);
1375
1376   // Initial size of the backing store to avoid resize of the storage during
1377   // bootstrapping. The size differs between the JS global object ad the
1378   // builtins object.
1379   int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1380
1381   // Allocate a dictionary object for backing storage.
1382   int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1383   Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);
1384
1385   // The global object might be created from an object template with accessors.
1386   // Fill these accessors into the dictionary.
1387   Handle<DescriptorArray> descs(map->instance_descriptors());
1388   for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1389     PropertyDetails details = descs->GetDetails(i);
1390     ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
1391     PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1392     Handle<Name> name(descs->GetKey(i));
1393     Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1394     Handle<PropertyCell> cell = NewPropertyCell(value);
1395     NameDictionaryAdd(dictionary, name, cell, d);
1396   }
1397
1398   // Allocate the global object and initialize it with the backing store.
1399   Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
1400   isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1401
1402   // Create a new map for the global object.
1403   Handle<Map> new_map = Map::CopyDropDescriptors(map);
1404   new_map->set_dictionary_map(true);
1405
1406   // Set up the global object as a normalized object.
1407   global->set_map(*new_map);
1408   global->set_properties(*dictionary);
1409
1410   // Make sure result is a global object with properties in dictionary.
1411   ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1412   return global;
1413 }
1414
1415
1416 Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map,
1417                                              PretenureFlag pretenure,
1418                                              bool alloc_props) {
1419   CALL_HEAP_FUNCTION(
1420       isolate(),
1421       isolate()->heap()->AllocateJSObjectFromMap(*map, pretenure, alloc_props),
1422       JSObject);
1423 }
1424
1425
1426 Handle<JSArray> Factory::NewJSArray(int capacity,
1427                                     ElementsKind elements_kind,
1428                                     PretenureFlag pretenure) {
1429   if (capacity != 0) {
1430     elements_kind = GetHoleyElementsKind(elements_kind);
1431   }
1432   CALL_HEAP_FUNCTION(isolate(),
1433                      isolate()->heap()->AllocateJSArrayAndStorage(
1434                          elements_kind,
1435                          0,
1436                          capacity,
1437                          INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
1438                          pretenure),
1439                      JSArray);
1440 }
1441
1442
1443 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1444                                                 ElementsKind elements_kind,
1445                                                 PretenureFlag pretenure) {
1446   CALL_HEAP_FUNCTION(
1447       isolate(),
1448       isolate()->heap()->AllocateJSArrayWithElements(*elements,
1449                                                      elements_kind,
1450                                                      elements->length(),
1451                                                      pretenure),
1452       JSArray);
1453 }
1454
1455
1456 void Factory::SetElementsCapacityAndLength(Handle<JSArray> array,
1457                                            int capacity,
1458                                            int length) {
1459   ElementsAccessor* accessor = array->GetElementsAccessor();
1460   CALL_HEAP_FUNCTION_VOID(
1461       isolate(),
1462       accessor->SetCapacityAndLength(*array, capacity, length));
1463 }
1464
1465
1466 void Factory::SetContent(Handle<JSArray> array,
1467                          Handle<FixedArrayBase> elements) {
1468   CALL_HEAP_FUNCTION_VOID(
1469       isolate(),
1470       array->SetContent(*elements));
1471 }
1472
1473
1474 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1475     Handle<JSFunction> function) {
1476   ASSERT(function->shared()->is_generator());
1477   JSFunction::EnsureHasInitialMap(function);
1478   Handle<Map> map(function->initial_map());
1479   ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1480   CALL_HEAP_FUNCTION(
1481       isolate(),
1482       isolate()->heap()->AllocateJSObjectFromMap(*map),
1483       JSGeneratorObject);
1484 }
1485
1486
1487 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1488   Handle<JSFunction> array_buffer_fun(
1489       isolate()->context()->native_context()->array_buffer_fun());
1490   CALL_HEAP_FUNCTION(
1491       isolate(),
1492       isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1493       JSArrayBuffer);
1494 }
1495
1496
1497 Handle<JSDataView> Factory::NewJSDataView() {
1498   Handle<JSFunction> data_view_fun(
1499       isolate()->context()->native_context()->data_view_fun());
1500   CALL_HEAP_FUNCTION(
1501       isolate(),
1502       isolate()->heap()->AllocateJSObject(*data_view_fun),
1503       JSDataView);
1504 }
1505
1506
1507 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1508                                     Isolate* isolate) {
1509   Context* native_context = isolate->context()->native_context();
1510   switch (type) {
1511 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size)                        \
1512     case kExternal##Type##Array:                                              \
1513       return native_context->type##_array_fun();
1514
1515     TYPED_ARRAYS(TYPED_ARRAY_FUN)
1516 #undef TYPED_ARRAY_FUN
1517
1518     default:
1519       UNREACHABLE();
1520       return NULL;
1521   }
1522 }
1523
1524
1525 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1526   Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1527
1528   CALL_HEAP_FUNCTION(
1529       isolate(),
1530       isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1531       JSTypedArray);
1532 }
1533
1534
1535 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1536                                     Handle<Object> prototype) {
1537   CALL_HEAP_FUNCTION(
1538       isolate(),
1539       isolate()->heap()->AllocateJSProxy(*handler, *prototype),
1540       JSProxy);
1541 }
1542
1543
1544 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1545   CALL_HEAP_FUNCTION_VOID(
1546       isolate(),
1547       isolate()->heap()->ReinitializeJSReceiver(
1548           *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
1549 }
1550
1551
1552 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1553   CALL_HEAP_FUNCTION_VOID(
1554       isolate(),
1555       isolate()->heap()->ReinitializeJSReceiver(
1556           *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1557 }
1558
1559
1560 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1561     Handle<String> name,
1562     int number_of_literals,
1563     bool is_generator,
1564     Handle<Code> code,
1565     Handle<ScopeInfo> scope_info) {
1566   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
1567   shared->set_code(*code);
1568   shared->set_scope_info(*scope_info);
1569   int literals_array_size = number_of_literals;
1570   // If the function contains object, regexp or array literals,
1571   // allocate extra space for a literals array prefix containing the
1572   // context.
1573   if (number_of_literals > 0) {
1574     literals_array_size += JSFunction::kLiteralsPrefixSize;
1575   }
1576   shared->set_num_literals(literals_array_size);
1577   if (is_generator) {
1578     shared->set_instance_class_name(isolate()->heap()->Generator_string());
1579     shared->DisableOptimization(kGenerator);
1580   }
1581   return shared;
1582 }
1583
1584
1585 Handle<JSMessageObject> Factory::NewJSMessageObject(
1586     Handle<String> type,
1587     Handle<JSArray> arguments,
1588     int start_position,
1589     int end_position,
1590     Handle<Object> script,
1591     Handle<Object> stack_trace,
1592     Handle<Object> stack_frames) {
1593   CALL_HEAP_FUNCTION(isolate(),
1594                      isolate()->heap()->AllocateJSMessageObject(*type,
1595                          *arguments,
1596                          start_position,
1597                          end_position,
1598                          *script,
1599                          *stack_trace,
1600                          *stack_frames),
1601                      JSMessageObject);
1602 }
1603
1604
1605 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1606   CALL_HEAP_FUNCTION(isolate(),
1607                      isolate()->heap()->AllocateSharedFunctionInfo(*name),
1608                      SharedFunctionInfo);
1609 }
1610
1611
1612 Handle<String> Factory::NumberToString(Handle<Object> number) {
1613   CALL_HEAP_FUNCTION(isolate(),
1614                      isolate()->heap()->NumberToString(*number), String);
1615 }
1616
1617
1618 Handle<String> Factory::Uint32ToString(uint32_t value) {
1619   CALL_HEAP_FUNCTION(isolate(),
1620                      isolate()->heap()->Uint32ToString(value), String);
1621 }
1622
1623
1624 Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
1625     Handle<SeededNumberDictionary> dictionary,
1626     uint32_t key,
1627     Handle<Object> value) {
1628   CALL_HEAP_FUNCTION(isolate(),
1629                      dictionary->AtNumberPut(key, *value),
1630                      SeededNumberDictionary);
1631 }
1632
1633
1634 Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
1635     Handle<UnseededNumberDictionary> dictionary,
1636     uint32_t key,
1637     Handle<Object> value) {
1638   CALL_HEAP_FUNCTION(isolate(),
1639                      dictionary->AtNumberPut(key, *value),
1640                      UnseededNumberDictionary);
1641 }
1642
1643
1644 Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
1645                                               Handle<Object> prototype) {
1646   Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1647   CALL_HEAP_FUNCTION(
1648       isolate(),
1649       isolate()->heap()->AllocateFunction(*isolate()->function_map(),
1650                                           *function_share,
1651                                           *prototype),
1652       JSFunction);
1653 }
1654
1655
1656 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1657                                         Handle<Object> prototype) {
1658   Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1659   fun->set_context(isolate()->context()->native_context());
1660   return fun;
1661 }
1662
1663
1664 Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1665     Handle<String> name,
1666     LanguageMode language_mode) {
1667   Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1668   Handle<Map> map = (language_mode == CLASSIC_MODE)
1669       ? isolate()->function_without_prototype_map()
1670       : isolate()->strict_mode_function_without_prototype_map();
1671   CALL_HEAP_FUNCTION(isolate(),
1672                      isolate()->heap()->AllocateFunction(
1673                          *map,
1674                          *function_share,
1675                          *the_hole_value()),
1676                      JSFunction);
1677 }
1678
1679
1680 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
1681     Handle<String> name,
1682     LanguageMode language_mode) {
1683   Handle<JSFunction> fun =
1684       NewFunctionWithoutPrototypeHelper(name, language_mode);
1685   fun->set_context(isolate()->context()->native_context());
1686   return fun;
1687 }
1688
1689
1690 Handle<Object> Factory::ToObject(Handle<Object> object) {
1691   CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
1692 }
1693
1694
1695 Handle<Object> Factory::ToObject(Handle<Object> object,
1696                                  Handle<Context> native_context) {
1697   CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1698 }
1699
1700
1701 #ifdef ENABLE_DEBUGGER_SUPPORT
1702 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
1703   // Get the original code of the function.
1704   Handle<Code> code(shared->code());
1705
1706   // Create a copy of the code before allocating the debug info object to avoid
1707   // allocation while setting up the debug info object.
1708   Handle<Code> original_code(*Factory::CopyCode(code));
1709
1710   // Allocate initial fixed array for active break points before allocating the
1711   // debug info object to avoid allocation while setting up the debug info
1712   // object.
1713   Handle<FixedArray> break_points(
1714       NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1715
1716   // Create and set up the debug info object. Debug info contains function, a
1717   // copy of the original code, the executing code and initial fixed array for
1718   // active break points.
1719   Handle<DebugInfo> debug_info =
1720       Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1721   debug_info->set_shared(*shared);
1722   debug_info->set_original_code(*original_code);
1723   debug_info->set_code(*code);
1724   debug_info->set_break_points(*break_points);
1725
1726   // Link debug info to function.
1727   shared->set_debug_info(*debug_info);
1728
1729   return debug_info;
1730 }
1731 #endif
1732
1733
1734 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
1735                                              int length) {
1736   CALL_HEAP_FUNCTION(
1737       isolate(),
1738       isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1739 }
1740
1741
1742 Handle<JSFunction> Factory::CreateApiFunction(
1743     Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1744   Handle<Code> code = isolate()->builtins()->HandleApiCall();
1745   Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1746
1747   int internal_field_count = 0;
1748   if (!obj->instance_template()->IsUndefined()) {
1749     Handle<ObjectTemplateInfo> instance_template =
1750         Handle<ObjectTemplateInfo>(
1751             ObjectTemplateInfo::cast(obj->instance_template()));
1752     internal_field_count =
1753         Smi::cast(instance_template->internal_field_count())->value();
1754   }
1755
1756   // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
1757   // JSObject::GetHeaderSize.
1758   int instance_size = kPointerSize * internal_field_count;
1759   InstanceType type;
1760   switch (instance_type) {
1761     case JavaScriptObject:
1762       type = JS_OBJECT_TYPE;
1763       instance_size += JSObject::kHeaderSize;
1764       break;
1765     case InnerGlobalObject:
1766       type = JS_GLOBAL_OBJECT_TYPE;
1767       instance_size += JSGlobalObject::kSize;
1768       break;
1769     case OuterGlobalObject:
1770       type = JS_GLOBAL_PROXY_TYPE;
1771       instance_size += JSGlobalProxy::kSize;
1772       break;
1773     default:
1774       UNREACHABLE();
1775       type = JS_OBJECT_TYPE;  // Keep the compiler happy.
1776       break;
1777   }
1778
1779   Handle<JSFunction> result =
1780       NewFunction(Factory::empty_string(),
1781                   type,
1782                   instance_size,
1783                   code,
1784                   true);
1785
1786   // Set length.
1787   result->shared()->set_length(obj->length());
1788
1789   // Set class name.
1790   Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1791   if (class_name->IsString()) {
1792     result->shared()->set_instance_class_name(*class_name);
1793     result->shared()->set_name(*class_name);
1794   }
1795
1796   Handle<Map> map = Handle<Map>(result->initial_map());
1797
1798   // Mark as undetectable if needed.
1799   if (obj->undetectable()) {
1800     map->set_is_undetectable();
1801   }
1802
1803   // Mark as hidden for the __proto__ accessor if needed.
1804   if (obj->hidden_prototype()) {
1805     map->set_is_hidden_prototype();
1806   }
1807
1808   // Mark as needs_access_check if needed.
1809   if (obj->needs_access_check()) {
1810     map->set_is_access_check_needed(true);
1811   }
1812
1813   // Set interceptor information in the map.
1814   if (!obj->named_property_handler()->IsUndefined()) {
1815     map->set_has_named_interceptor();
1816   }
1817   if (!obj->indexed_property_handler()->IsUndefined()) {
1818     map->set_has_indexed_interceptor();
1819   }
1820
1821   // Set instance call-as-function information in the map.
1822   if (!obj->instance_call_handler()->IsUndefined()) {
1823     map->set_has_instance_call_handler();
1824   }
1825
1826   result->shared()->set_function_data(*obj);
1827   result->shared()->set_construct_stub(*construct_stub);
1828   result->shared()->DontAdaptArguments();
1829
1830   // Recursively copy parent instance templates' accessors,
1831   // 'data' may be modified.
1832   int max_number_of_additional_properties = 0;
1833   int max_number_of_static_properties = 0;
1834   FunctionTemplateInfo* info = *obj;
1835   while (true) {
1836     if (!info->instance_template()->IsUndefined()) {
1837       Object* props =
1838           ObjectTemplateInfo::cast(
1839               info->instance_template())->property_accessors();
1840       if (!props->IsUndefined()) {
1841         Handle<Object> props_handle(props, isolate());
1842         NeanderArray props_array(props_handle);
1843         max_number_of_additional_properties += props_array.length();
1844       }
1845     }
1846     if (!info->property_accessors()->IsUndefined()) {
1847       Object* props = info->property_accessors();
1848       if (!props->IsUndefined()) {
1849         Handle<Object> props_handle(props, isolate());
1850         NeanderArray props_array(props_handle);
1851         max_number_of_static_properties += props_array.length();
1852       }
1853     }
1854     Object* parent = info->parent_template();
1855     if (parent->IsUndefined()) break;
1856     info = FunctionTemplateInfo::cast(parent);
1857   }
1858
1859   Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
1860
1861   // Use a temporary FixedArray to acculumate static accessors
1862   int valid_descriptors = 0;
1863   Handle<FixedArray> array;
1864   if (max_number_of_static_properties > 0) {
1865     array = NewFixedArray(max_number_of_static_properties);
1866   }
1867
1868   while (true) {
1869     // Install instance descriptors
1870     if (!obj->instance_template()->IsUndefined()) {
1871       Handle<ObjectTemplateInfo> instance =
1872           Handle<ObjectTemplateInfo>(
1873               ObjectTemplateInfo::cast(obj->instance_template()), isolate());
1874       Handle<Object> props = Handle<Object>(instance->property_accessors(),
1875                                             isolate());
1876       if (!props->IsUndefined()) {
1877         Map::AppendCallbackDescriptors(map, props);
1878       }
1879     }
1880     // Accumulate static accessors
1881     if (!obj->property_accessors()->IsUndefined()) {
1882       Handle<Object> props = Handle<Object>(obj->property_accessors(),
1883                                             isolate());
1884       valid_descriptors =
1885           AccessorInfo::AppendUnique(props, array, valid_descriptors);
1886     }
1887     // Climb parent chain
1888     Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1889     if (parent->IsUndefined()) break;
1890     obj = Handle<FunctionTemplateInfo>::cast(parent);
1891   }
1892
1893   // Install accumulated static accessors
1894   for (int i = 0; i < valid_descriptors; i++) {
1895     Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
1896     JSObject::SetAccessor(result, accessor);
1897   }
1898
1899   ASSERT(result->shared()->IsApiFunction());
1900   return result;
1901 }
1902
1903
1904 Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1905   CALL_HEAP_FUNCTION(isolate(),
1906                      MapCache::Allocate(isolate()->heap(),
1907                                         at_least_space_for),
1908                      MapCache);
1909 }
1910
1911
1912 MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
1913                                                        FixedArray* keys,
1914                                                        Map* map) {
1915   Object* result;
1916   { MaybeObject* maybe_result =
1917         MapCache::cast(context->map_cache())->Put(keys, map);
1918     if (!maybe_result->ToObject(&result)) return maybe_result;
1919   }
1920   context->set_map_cache(MapCache::cast(result));
1921   return result;
1922 }
1923
1924
1925 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1926                                         Handle<FixedArray> keys,
1927                                         Handle<Map> map) {
1928   CALL_HEAP_FUNCTION(isolate(),
1929                      UpdateMapCacheWith(*context, *keys, *map), MapCache);
1930 }
1931
1932
1933 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1934                                                Handle<FixedArray> keys) {
1935   if (context->map_cache()->IsUndefined()) {
1936     // Allocate the new map cache for the native context.
1937     Handle<MapCache> new_cache = NewMapCache(24);
1938     context->set_map_cache(*new_cache);
1939   }
1940   // Check to see whether there is a matching element in the cache.
1941   Handle<MapCache> cache =
1942       Handle<MapCache>(MapCache::cast(context->map_cache()));
1943   Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1944   if (result->IsMap()) return Handle<Map>::cast(result);
1945   // Create a new map and add it to the cache.
1946   Handle<Map> map =
1947       CopyMap(Handle<Map>(context->object_function()->initial_map()),
1948               keys->length());
1949   AddToMapCache(context, keys, map);
1950   return Handle<Map>(map);
1951 }
1952
1953
1954 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1955                                 JSRegExp::Type type,
1956                                 Handle<String> source,
1957                                 JSRegExp::Flags flags,
1958                                 Handle<Object> data) {
1959   Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1960
1961   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1962   store->set(JSRegExp::kSourceIndex, *source);
1963   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1964   store->set(JSRegExp::kAtomPatternIndex, *data);
1965   regexp->set_data(*store);
1966 }
1967
1968 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1969                                     JSRegExp::Type type,
1970                                     Handle<String> source,
1971                                     JSRegExp::Flags flags,
1972                                     int capture_count) {
1973   Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1974   Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1975   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1976   store->set(JSRegExp::kSourceIndex, *source);
1977   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1978   store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
1979   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
1980   store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
1981   store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1982   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
1983   store->set(JSRegExp::kIrregexpCaptureCountIndex,
1984              Smi::FromInt(capture_count));
1985   regexp->set_data(*store);
1986 }
1987
1988
1989
1990 void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
1991                                 Handle<JSObject> instance,
1992                                 bool* pending_exception) {
1993   // Configure the instance by adding the properties specified by the
1994   // instance template.
1995   Handle<Object> instance_template(desc->instance_template(), isolate());
1996   if (!instance_template->IsUndefined()) {
1997     Execution::ConfigureInstance(isolate(),
1998                                  instance,
1999                                  instance_template,
2000                                  pending_exception);
2001   } else {
2002     *pending_exception = false;
2003   }
2004 }
2005
2006
2007 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2008   Heap* h = isolate()->heap();
2009   if (name->Equals(h->undefined_string())) return undefined_value();
2010   if (name->Equals(h->nan_string())) return nan_value();
2011   if (name->Equals(h->infinity_string())) return infinity_value();
2012   return Handle<Object>::null();
2013 }
2014
2015
2016 Handle<Object> Factory::ToBoolean(bool value) {
2017   return value ? true_value() : false_value();
2018 }
2019
2020
2021 } }  // namespace v8::internal