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