Upstream version 7.35.139.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<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   str = FlattenGetString(str);
484
485   int length = end - begin;
486   if (length <= 0) return empty_string();
487   if (length == 1) {
488     return LookupSingleCharacterStringFromCode(isolate(), str->Get(begin));
489   }
490   if (length == 2) {
491     // Optimization for 2-byte strings often used as keys in a decompression
492     // dictionary.  Check whether we already have the string in the string
493     // table to prevent creation of many unnecessary strings.
494     uint16_t c1 = str->Get(begin);
495     uint16_t c2 = str->Get(begin + 1);
496     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
497   }
498
499   if (!FLAG_string_slices || length < SlicedString::kMinLength) {
500     if (str->IsOneByteRepresentation()) {
501       Handle<SeqOneByteString> result = NewRawOneByteString(length);
502       ASSERT(!result.is_null());
503       uint8_t* dest = result->GetChars();
504       DisallowHeapAllocation no_gc;
505       String::WriteToFlat(*str, dest, begin, end);
506       return result;
507     } else {
508       Handle<SeqTwoByteString> result = NewRawTwoByteString(length);
509       ASSERT(!result.is_null());
510       uc16* dest = result->GetChars();
511       DisallowHeapAllocation no_gc;
512       String::WriteToFlat(*str, dest, begin, end);
513       return result;
514     }
515   }
516
517   int offset = begin;
518
519   if (str->IsSlicedString()) {
520     Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
521     str = Handle<String>(slice->parent(), isolate());
522     offset += slice->offset();
523   }
524
525   ASSERT(str->IsSeqString() || str->IsExternalString());
526   Handle<SlicedString> slice = NewRawSlicedString(
527       str->IsOneByteRepresentation() ? String::ONE_BYTE_ENCODING
528                                      : String::TWO_BYTE_ENCODING);
529
530   slice->set_hash_field(String::kEmptyHashField);
531   slice->set_length(length);
532   slice->set_parent(*str);
533   slice->set_offset(offset);
534   return slice;
535 }
536
537
538 Handle<String> Factory::NewExternalStringFromAscii(
539     const ExternalAsciiString::Resource* resource) {
540   CALL_HEAP_FUNCTION(
541       isolate(),
542       isolate()->heap()->AllocateExternalStringFromAscii(resource),
543       String);
544 }
545
546
547 Handle<String> Factory::NewExternalStringFromTwoByte(
548     const ExternalTwoByteString::Resource* resource) {
549   CALL_HEAP_FUNCTION(
550       isolate(),
551       isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
552       String);
553 }
554
555
556 Handle<Symbol> Factory::NewSymbol() {
557   CALL_HEAP_FUNCTION(
558       isolate(),
559       isolate()->heap()->AllocateSymbol(),
560       Symbol);
561 }
562
563
564 Handle<Symbol> Factory::NewPrivateSymbol() {
565   CALL_HEAP_FUNCTION(
566       isolate(),
567       isolate()->heap()->AllocatePrivateSymbol(),
568       Symbol);
569 }
570
571
572 Handle<Context> Factory::NewNativeContext() {
573   CALL_HEAP_FUNCTION(
574       isolate(),
575       isolate()->heap()->AllocateNativeContext(),
576       Context);
577 }
578
579
580 Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
581                                           Handle<ScopeInfo> scope_info) {
582   CALL_HEAP_FUNCTION(
583       isolate(),
584       isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
585       Context);
586 }
587
588
589 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
590   CALL_HEAP_FUNCTION(
591       isolate(),
592       isolate()->heap()->AllocateModuleContext(*scope_info),
593       Context);
594 }
595
596
597 Handle<Context> Factory::NewFunctionContext(int length,
598                                             Handle<JSFunction> function) {
599   CALL_HEAP_FUNCTION(
600       isolate(),
601       isolate()->heap()->AllocateFunctionContext(length, *function),
602       Context);
603 }
604
605
606 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
607                                          Handle<Context> previous,
608                                          Handle<String> name,
609                                          Handle<Object> thrown_object) {
610   CALL_HEAP_FUNCTION(
611       isolate(),
612       isolate()->heap()->AllocateCatchContext(*function,
613                                               *previous,
614                                               *name,
615                                               *thrown_object),
616       Context);
617 }
618
619
620 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
621                                         Handle<Context> previous,
622                                         Handle<JSObject> extension) {
623   CALL_HEAP_FUNCTION(
624       isolate(),
625       isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
626       Context);
627 }
628
629
630 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
631                                          Handle<Context> previous,
632                                          Handle<ScopeInfo> scope_info) {
633   CALL_HEAP_FUNCTION(
634       isolate(),
635       isolate()->heap()->AllocateBlockContext(*function,
636                                               *previous,
637                                               *scope_info),
638       Context);
639 }
640
641
642 Handle<Struct> Factory::NewStruct(InstanceType type) {
643   CALL_HEAP_FUNCTION(
644       isolate(),
645       isolate()->heap()->AllocateStruct(type),
646       Struct);
647 }
648
649
650 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
651     int aliased_context_slot) {
652   Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
653       NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
654   entry->set_aliased_context_slot(aliased_context_slot);
655   return entry;
656 }
657
658
659 Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
660   return Handle<DeclaredAccessorDescriptor>::cast(
661       NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
662 }
663
664
665 Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
666   Handle<DeclaredAccessorInfo> info =
667       Handle<DeclaredAccessorInfo>::cast(
668           NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
669   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
670   return info;
671 }
672
673
674 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
675   Handle<ExecutableAccessorInfo> info =
676       Handle<ExecutableAccessorInfo>::cast(
677           NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
678   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
679   return info;
680 }
681
682
683 Handle<Script> Factory::NewScript(Handle<String> source) {
684   // Generate id for this script.
685   Heap* heap = isolate()->heap();
686   int id = heap->last_script_id()->value() + 1;
687   if (!Smi::IsValid(id) || id < 0) id = 1;
688   heap->set_last_script_id(Smi::FromInt(id));
689
690   // Create and initialize script object.
691   Handle<Foreign> wrapper = NewForeign(0, TENURED);
692   Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
693   script->set_source(*source);
694   script->set_name(heap->undefined_value());
695   script->set_id(Smi::FromInt(id));
696   script->set_line_offset(Smi::FromInt(0));
697   script->set_column_offset(Smi::FromInt(0));
698   script->set_context_data(heap->undefined_value());
699   script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
700   script->set_wrapper(*wrapper);
701   script->set_line_ends(heap->undefined_value());
702   script->set_eval_from_shared(heap->undefined_value());
703   script->set_eval_from_instructions_offset(Smi::FromInt(0));
704   script->set_flags(Smi::FromInt(0));
705
706   return script;
707 }
708
709
710 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
711   CALL_HEAP_FUNCTION(isolate(),
712                      isolate()->heap()->AllocateForeign(addr, pretenure),
713                      Foreign);
714 }
715
716
717 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
718   return NewForeign((Address) desc, TENURED);
719 }
720
721
722 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
723   ASSERT(0 <= length);
724   CALL_HEAP_FUNCTION(
725       isolate(),
726       isolate()->heap()->AllocateByteArray(length, pretenure),
727       ByteArray);
728 }
729
730
731 Handle<ExternalArray> Factory::NewExternalArray(int length,
732                                                 ExternalArrayType array_type,
733                                                 void* external_pointer,
734                                                 PretenureFlag pretenure) {
735   ASSERT(0 <= length && length <= Smi::kMaxValue);
736   CALL_HEAP_FUNCTION(
737       isolate(),
738       isolate()->heap()->AllocateExternalArray(length,
739                                                array_type,
740                                                external_pointer,
741                                                pretenure),
742       ExternalArray);
743 }
744
745
746 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
747     int length,
748     ExternalArrayType array_type,
749     PretenureFlag pretenure) {
750   ASSERT(0 <= length && length <= Smi::kMaxValue);
751   CALL_HEAP_FUNCTION(
752       isolate(),
753       isolate()->heap()->AllocateFixedTypedArray(length,
754                                                  array_type,
755                                                  pretenure),
756       FixedTypedArrayBase);
757 }
758
759
760 Handle<Cell> Factory::NewCell(Handle<Object> value) {
761   AllowDeferredHandleDereference convert_to_cell;
762   CALL_HEAP_FUNCTION(
763       isolate(),
764       isolate()->heap()->AllocateCell(*value),
765       Cell);
766 }
767
768
769 Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
770   CALL_HEAP_FUNCTION(
771       isolate(),
772       isolate()->heap()->AllocatePropertyCell(),
773       PropertyCell);
774 }
775
776
777 Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
778   AllowDeferredHandleDereference convert_to_cell;
779   Handle<PropertyCell> cell = NewPropertyCellWithHole();
780   PropertyCell::SetValueInferType(cell, value);
781   return cell;
782 }
783
784
785 Handle<AllocationSite> Factory::NewAllocationSite() {
786   CALL_HEAP_FUNCTION(
787       isolate(),
788       isolate()->heap()->AllocateAllocationSite(),
789       AllocationSite);
790 }
791
792
793 Handle<Map> Factory::NewMap(InstanceType type,
794                             int instance_size,
795                             ElementsKind elements_kind) {
796   CALL_HEAP_FUNCTION(
797       isolate(),
798       isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
799       Map);
800 }
801
802
803 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
804   // Make sure to use globals from the function's context, since the function
805   // can be from a different context.
806   Handle<Context> native_context(function->context()->native_context());
807   Handle<Map> new_map;
808   if (function->shared()->is_generator()) {
809     // Generator prototypes can share maps since they don't have "constructor"
810     // properties.
811     new_map = handle(native_context->generator_object_prototype_map());
812   } else {
813     // Each function prototype gets a fresh map to avoid unwanted sharing of
814     // maps between prototypes of different constructors.
815     Handle<JSFunction> object_function(native_context->object_function());
816     ASSERT(object_function->has_initial_map());
817     new_map = Map::Copy(handle(object_function->initial_map()));
818   }
819
820   Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
821
822   if (!function->shared()->is_generator()) {
823     JSObject::SetLocalPropertyIgnoreAttributes(prototype,
824                                                constructor_string(),
825                                                function,
826                                                DONT_ENUM);
827   }
828
829   return prototype;
830 }
831
832
833 Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
834   CALL_HEAP_FUNCTION(
835       isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
836 }
837
838
839 Handle<Map> Factory::CopyMap(Handle<Map> src,
840                              int extra_inobject_properties) {
841   Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
842   // Check that we do not overflow the instance size when adding the
843   // extra inobject properties.
844   int instance_size_delta = extra_inobject_properties * kPointerSize;
845   int max_instance_size_delta =
846       JSObject::kMaxInstanceSize - copy->instance_size();
847   int max_extra_properties = max_instance_size_delta >> kPointerSizeLog2;
848   if (extra_inobject_properties > max_extra_properties) {
849     // If the instance size overflows, we allocate as many properties
850     // as we can as inobject properties.
851     instance_size_delta = max_instance_size_delta;
852     extra_inobject_properties = max_extra_properties;
853   }
854   // Adjust the map with the extra inobject properties.
855   int inobject_properties =
856       copy->inobject_properties() + extra_inobject_properties;
857   copy->set_inobject_properties(inobject_properties);
858   copy->set_unused_property_fields(inobject_properties);
859   copy->set_instance_size(copy->instance_size() + instance_size_delta);
860   copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
861   return copy;
862 }
863
864
865 Handle<Map> Factory::CopyMap(Handle<Map> src) {
866   CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
867 }
868
869
870 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
871   CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
872 }
873
874
875 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
876     Handle<FixedArray> array) {
877   ASSERT(isolate()->heap()->InNewSpace(*array));
878   CALL_HEAP_FUNCTION(isolate(),
879                      isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
880                      FixedArray);
881 }
882
883
884 Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
885                                                int new_length,
886                                                PretenureFlag pretenure) {
887   CALL_HEAP_FUNCTION(isolate(),
888                      array->CopySize(new_length, pretenure),
889                      FixedArray);
890 }
891
892
893 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
894     Handle<FixedDoubleArray> array) {
895   CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
896 }
897
898
899 Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
900     Handle<ConstantPoolArray> array) {
901   CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
902 }
903
904
905 Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
906     Handle<SharedFunctionInfo> function_info,
907     Handle<Map> function_map,
908     PretenureFlag pretenure) {
909   CALL_HEAP_FUNCTION(
910       isolate(),
911       isolate()->heap()->AllocateFunction(*function_map,
912                                           *function_info,
913                                           isolate()->heap()->the_hole_value(),
914                                           pretenure),
915                      JSFunction);
916 }
917
918
919 static Handle<Map> MapForNewFunction(Isolate *isolate,
920                                      Handle<SharedFunctionInfo> function_info) {
921   Context *context = isolate->context()->native_context();
922   int map_index = Context::FunctionMapIndex(function_info->strict_mode(),
923                                             function_info->is_generator());
924   return Handle<Map>(Map::cast(context->get(map_index)));
925 }
926
927
928 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
929     Handle<SharedFunctionInfo> function_info,
930     Handle<Context> context,
931     PretenureFlag pretenure) {
932   Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
933       function_info,
934       MapForNewFunction(isolate(), function_info),
935       pretenure);
936
937   if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
938     function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
939   }
940
941   result->set_context(*context);
942
943   int index = function_info->SearchOptimizedCodeMap(context->native_context(),
944                                                     BailoutId::None());
945   if (!function_info->bound() && index < 0) {
946     int number_of_literals = function_info->num_literals();
947     Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
948     if (number_of_literals > 0) {
949       // Store the native context in the literals array prefix. This
950       // context will be used when creating object, regexp and array
951       // literals in this function.
952       literals->set(JSFunction::kLiteralNativeContextIndex,
953                     context->native_context());
954     }
955     result->set_literals(*literals);
956   }
957
958   if (index > 0) {
959     // Caching of optimized code enabled and optimized code found.
960     FixedArray* literals =
961         function_info->GetLiteralsFromOptimizedCodeMap(index);
962     if (literals != NULL) result->set_literals(literals);
963     Code* code = function_info->GetCodeFromOptimizedCodeMap(index);
964     ASSERT(!code->marked_for_deoptimization());
965     result->ReplaceCode(code);
966     return result;
967   }
968
969   if (isolate()->use_crankshaft() &&
970       FLAG_always_opt &&
971       result->is_compiled() &&
972       !function_info->is_toplevel() &&
973       function_info->allows_lazy_compilation() &&
974       !function_info->optimization_disabled() &&
975       !isolate()->DebuggerHasBreakPoints()) {
976     result->MarkForOptimization();
977   }
978   return result;
979 }
980
981
982 Handle<Object> Factory::NewNumber(double value,
983                                   PretenureFlag pretenure) {
984   CALL_HEAP_FUNCTION(
985       isolate(),
986       isolate()->heap()->NumberFromDouble(value, pretenure), Object);
987 }
988
989
990 Handle<Object> Factory::NewNumberFromInt(int32_t value,
991                                          PretenureFlag pretenure) {
992   CALL_HEAP_FUNCTION(
993       isolate(),
994       isolate()->heap()->NumberFromInt32(value, pretenure), Object);
995 }
996
997
998 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
999                                          PretenureFlag pretenure) {
1000   CALL_HEAP_FUNCTION(
1001       isolate(),
1002       isolate()->heap()->NumberFromUint32(value, pretenure), Object);
1003 }
1004
1005
1006 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1007                                           PretenureFlag pretenure) {
1008   CALL_HEAP_FUNCTION(
1009       isolate(),
1010       isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
1011 }
1012
1013
1014 Handle<Float32x4> Factory::NewFloat32x4(float32x4_value_t value,
1015                                         PretenureFlag pretenure) {
1016   CALL_HEAP_FUNCTION(
1017       isolate(),
1018       isolate()->heap()->AllocateFloat32x4(value, pretenure), Float32x4);
1019 }
1020
1021
1022 Handle<Int32x4> Factory::NewInt32x4(int32x4_value_t value,
1023                                       PretenureFlag pretenure) {
1024   CALL_HEAP_FUNCTION(
1025       isolate(),
1026       isolate()->heap()->AllocateInt32x4(value, pretenure), Int32x4);
1027 }
1028
1029
1030 Handle<JSObject> Factory::NewNeanderObject() {
1031   CALL_HEAP_FUNCTION(
1032       isolate(),
1033       isolate()->heap()->AllocateJSObjectFromMap(
1034           isolate()->heap()->neander_map()),
1035       JSObject);
1036 }
1037
1038
1039 Handle<Object> Factory::NewTypeError(const char* message,
1040                                      Vector< Handle<Object> > args) {
1041   return NewError("MakeTypeError", message, args);
1042 }
1043
1044
1045 Handle<Object> Factory::NewTypeError(Handle<String> message) {
1046   return NewError("$TypeError", message);
1047 }
1048
1049
1050 Handle<Object> Factory::NewRangeError(const char* message,
1051                                       Vector< Handle<Object> > args) {
1052   return NewError("MakeRangeError", message, args);
1053 }
1054
1055
1056 Handle<Object> Factory::NewRangeError(Handle<String> message) {
1057   return NewError("$RangeError", message);
1058 }
1059
1060
1061 Handle<Object> Factory::NewSyntaxError(const char* message,
1062                                        Handle<JSArray> args) {
1063   return NewError("MakeSyntaxError", message, args);
1064 }
1065
1066
1067 Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
1068   return NewError("$SyntaxError", message);
1069 }
1070
1071
1072 Handle<Object> Factory::NewReferenceError(const char* message,
1073                                           Vector< Handle<Object> > args) {
1074   return NewError("MakeReferenceError", message, args);
1075 }
1076
1077
1078 Handle<Object> Factory::NewReferenceError(const char* message,
1079                                           Handle<JSArray> args) {
1080   return NewError("MakeReferenceError", message, args);
1081 }
1082
1083
1084 Handle<Object> Factory::NewReferenceError(Handle<String> message) {
1085   return NewError("$ReferenceError", message);
1086 }
1087
1088
1089 Handle<Object> Factory::NewError(const char* maker,
1090                                  const char* message,
1091                                  Vector< Handle<Object> > args) {
1092   // Instantiate a closeable HandleScope for EscapeFrom.
1093   v8::EscapableHandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
1094   Handle<FixedArray> array = NewFixedArray(args.length());
1095   for (int i = 0; i < args.length(); i++) {
1096     array->set(i, *args[i]);
1097   }
1098   Handle<JSArray> object = NewJSArrayWithElements(array);
1099   Handle<Object> result = NewError(maker, message, object);
1100   return result.EscapeFrom(&scope);
1101 }
1102
1103
1104 Handle<Object> Factory::NewEvalError(const char* message,
1105                                      Vector< Handle<Object> > args) {
1106   return NewError("MakeEvalError", message, args);
1107 }
1108
1109
1110 Handle<Object> Factory::NewError(const char* message,
1111                                  Vector< Handle<Object> > args) {
1112   return NewError("MakeError", message, args);
1113 }
1114
1115
1116 Handle<String> Factory::EmergencyNewError(const char* message,
1117                                           Handle<JSArray> args) {
1118   const int kBufferSize = 1000;
1119   char buffer[kBufferSize];
1120   size_t space = kBufferSize;
1121   char* p = &buffer[0];
1122
1123   Vector<char> v(buffer, kBufferSize);
1124   OS::StrNCpy(v, message, space);
1125   space -= Min(space, strlen(message));
1126   p = &buffer[kBufferSize] - space;
1127
1128   for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
1129     if (space > 0) {
1130       *p++ = ' ';
1131       space--;
1132       if (space > 0) {
1133         Handle<String> arg_str = Handle<String>::cast(
1134             Object::GetElementNoExceptionThrown(isolate(), args, i));
1135         SmartArrayPointer<char> arg = arg_str->ToCString();
1136         Vector<char> v2(p, static_cast<int>(space));
1137         OS::StrNCpy(v2, arg.get(), space);
1138         space -= Min(space, strlen(arg.get()));
1139         p = &buffer[kBufferSize] - space;
1140       }
1141     }
1142   }
1143   if (space > 0) {
1144     *p = '\0';
1145   } else {
1146     buffer[kBufferSize - 1] = '\0';
1147   }
1148   Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
1149   return error_string;
1150 }
1151
1152
1153 Handle<Object> Factory::NewError(const char* maker,
1154                                  const char* message,
1155                                  Handle<JSArray> args) {
1156   Handle<String> make_str = InternalizeUtf8String(maker);
1157   Handle<Object> fun_obj(
1158       isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
1159       isolate());
1160   // If the builtins haven't been properly configured yet this error
1161   // constructor may not have been defined.  Bail out.
1162   if (!fun_obj->IsJSFunction()) {
1163     return EmergencyNewError(message, args);
1164   }
1165   Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1166   Handle<Object> message_obj = InternalizeUtf8String(message);
1167   Handle<Object> argv[] = { message_obj, args };
1168
1169   // Invoke the JavaScript factory method. If an exception is thrown while
1170   // running the factory method, use the exception as the result.
1171   bool caught_exception;
1172   Handle<Object> result = Execution::TryCall(fun,
1173                                              isolate()->js_builtins_object(),
1174                                              ARRAY_SIZE(argv),
1175                                              argv,
1176                                              &caught_exception);
1177   return result;
1178 }
1179
1180
1181 Handle<Object> Factory::NewError(Handle<String> message) {
1182   return NewError("$Error", message);
1183 }
1184
1185
1186 Handle<Object> Factory::NewError(const char* constructor,
1187                                  Handle<String> message) {
1188   Handle<String> constr = InternalizeUtf8String(constructor);
1189   Handle<JSFunction> fun = Handle<JSFunction>(
1190       JSFunction::cast(isolate()->js_builtins_object()->
1191                        GetPropertyNoExceptionThrown(*constr)));
1192   Handle<Object> argv[] = { message };
1193
1194   // Invoke the JavaScript factory method. If an exception is thrown while
1195   // running the factory method, use the exception as the result.
1196   bool caught_exception;
1197   Handle<Object> result = Execution::TryCall(fun,
1198                                              isolate()->js_builtins_object(),
1199                                              ARRAY_SIZE(argv),
1200                                              argv,
1201                                              &caught_exception);
1202   return result;
1203 }
1204
1205
1206 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1207                                         InstanceType type,
1208                                         int instance_size,
1209                                         Handle<Code> code,
1210                                         bool force_initial_map) {
1211   // Allocate the function
1212   Handle<JSFunction> function = NewFunction(name, the_hole_value());
1213
1214   // Set up the code pointer in both the shared function info and in
1215   // the function itself.
1216   function->shared()->set_code(*code);
1217   function->set_code(*code);
1218
1219   if (force_initial_map ||
1220       type != JS_OBJECT_TYPE ||
1221       instance_size != JSObject::kHeaderSize) {
1222     Handle<Map> initial_map = NewMap(type, instance_size);
1223     Handle<JSObject> prototype = NewFunctionPrototype(function);
1224     initial_map->set_prototype(*prototype);
1225     function->set_initial_map(*initial_map);
1226     initial_map->set_constructor(*function);
1227   } else {
1228     ASSERT(!function->has_initial_map());
1229     ASSERT(!function->has_prototype());
1230   }
1231
1232   return function;
1233 }
1234
1235
1236 Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
1237                                                      InstanceType type,
1238                                                      int instance_size,
1239                                                      Handle<JSObject> prototype,
1240                                                      Handle<Code> code,
1241                                                      bool force_initial_map) {
1242   // Allocate the function.
1243   Handle<JSFunction> function = NewFunction(name, prototype);
1244
1245   // Set up the code pointer in both the shared function info and in
1246   // the function itself.
1247   function->shared()->set_code(*code);
1248   function->set_code(*code);
1249
1250   if (force_initial_map ||
1251       type != JS_OBJECT_TYPE ||
1252       instance_size != JSObject::kHeaderSize) {
1253     Handle<Map> initial_map = NewMap(type,
1254                                      instance_size,
1255                                      GetInitialFastElementsKind());
1256     function->set_initial_map(*initial_map);
1257     initial_map->set_constructor(*function);
1258   }
1259
1260   JSFunction::SetPrototype(function, prototype);
1261   return function;
1262 }
1263
1264
1265 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1266                                                         Handle<Code> code) {
1267   Handle<JSFunction> function = NewFunctionWithoutPrototype(name, SLOPPY);
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<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1320                                       PretenureFlag pretenure) {
1321   JSFunction::EnsureHasInitialMap(constructor);
1322   CALL_HEAP_FUNCTION(
1323       isolate(),
1324       isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1325 }
1326
1327
1328 Handle<JSObject> Factory::NewJSObjectWithMemento(
1329     Handle<JSFunction> constructor,
1330     Handle<AllocationSite> site) {
1331   JSFunction::EnsureHasInitialMap(constructor);
1332   CALL_HEAP_FUNCTION(
1333       isolate(),
1334       isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1335       JSObject);
1336 }
1337
1338
1339 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1340                                       Handle<ScopeInfo> scope_info) {
1341   CALL_HEAP_FUNCTION(
1342       isolate(),
1343       isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1344 }
1345
1346
1347 // TODO(mstarzinger): Temporary wrapper until handlified.
1348 static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
1349                                                 Handle<Name> name,
1350                                                 Handle<Object> value,
1351                                                 PropertyDetails details) {
1352   CALL_HEAP_FUNCTION(dict->GetIsolate(),
1353                      dict->Add(*name, *value, details),
1354                      NameDictionary);
1355 }
1356
1357
1358 static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
1359                                                    Handle<Map> map) {
1360   CALL_HEAP_FUNCTION(isolate,
1361                      isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1362                      GlobalObject);
1363 }
1364
1365
1366 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1367   ASSERT(constructor->has_initial_map());
1368   Handle<Map> map(constructor->initial_map());
1369   ASSERT(map->is_dictionary_map());
1370
1371   // Make sure no field properties are described in the initial map.
1372   // This guarantees us that normalizing the properties does not
1373   // require us to change property values to PropertyCells.
1374   ASSERT(map->NextFreePropertyIndex() == 0);
1375
1376   // Make sure we don't have a ton of pre-allocated slots in the
1377   // global objects. They will be unused once we normalize the object.
1378   ASSERT(map->unused_property_fields() == 0);
1379   ASSERT(map->inobject_properties() == 0);
1380
1381   // Initial size of the backing store to avoid resize of the storage during
1382   // bootstrapping. The size differs between the JS global object ad the
1383   // builtins object.
1384   int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1385
1386   // Allocate a dictionary object for backing storage.
1387   int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1388   Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);
1389
1390   // The global object might be created from an object template with accessors.
1391   // Fill these accessors into the dictionary.
1392   Handle<DescriptorArray> descs(map->instance_descriptors());
1393   for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1394     PropertyDetails details = descs->GetDetails(i);
1395     ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
1396     PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1397     Handle<Name> name(descs->GetKey(i));
1398     Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1399     Handle<PropertyCell> cell = NewPropertyCell(value);
1400     NameDictionaryAdd(dictionary, name, cell, d);
1401   }
1402
1403   // Allocate the global object and initialize it with the backing store.
1404   Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
1405   isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1406
1407   // Create a new map for the global object.
1408   Handle<Map> new_map = Map::CopyDropDescriptors(map);
1409   new_map->set_dictionary_map(true);
1410
1411   // Set up the global object as a normalized object.
1412   global->set_map(*new_map);
1413   global->set_properties(*dictionary);
1414
1415   // Make sure result is a global object with properties in dictionary.
1416   ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1417   return global;
1418 }
1419
1420
1421 Handle<JSObject> Factory::NewJSObjectFromMap(
1422     Handle<Map> map,
1423     PretenureFlag pretenure,
1424     bool alloc_props,
1425     Handle<AllocationSite> allocation_site) {
1426   CALL_HEAP_FUNCTION(
1427       isolate(),
1428       isolate()->heap()->AllocateJSObjectFromMap(
1429           *map,
1430           pretenure,
1431           alloc_props,
1432           allocation_site.is_null() ? NULL : *allocation_site),
1433       JSObject);
1434 }
1435
1436
1437 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1438                                     int length,
1439                                     int capacity,
1440                                     PretenureFlag pretenure) {
1441   if (capacity != 0) {
1442     elements_kind = GetHoleyElementsKind(elements_kind);
1443   }
1444   CALL_HEAP_FUNCTION(isolate(),
1445                      isolate()->heap()->AllocateJSArrayAndStorage(
1446                          elements_kind,
1447                          length,
1448                          capacity,
1449                          INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
1450                          pretenure),
1451                      JSArray);
1452 }
1453
1454
1455 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1456                                                 ElementsKind elements_kind,
1457                                                 int length,
1458                                                 PretenureFlag pretenure) {
1459   ASSERT(length <= elements->length());
1460   CALL_HEAP_FUNCTION(
1461       isolate(),
1462       isolate()->heap()->AllocateJSArrayWithElements(*elements,
1463                                                      elements_kind,
1464                                                      length,
1465                                                      pretenure),
1466       JSArray);
1467 }
1468
1469
1470 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1471                                      int length,
1472                                      int capacity,
1473                                      ArrayStorageAllocationMode mode) {
1474   CALL_HEAP_FUNCTION_VOID(isolate(),
1475                           isolate()->heap()->AllocateJSArrayStorage(*array,
1476                                                                     length,
1477                                                                     capacity,
1478                                                                     mode));
1479 }
1480
1481
1482 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1483     Handle<JSFunction> function) {
1484   ASSERT(function->shared()->is_generator());
1485   JSFunction::EnsureHasInitialMap(function);
1486   Handle<Map> map(function->initial_map());
1487   ASSERT(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1488   CALL_HEAP_FUNCTION(
1489       isolate(),
1490       isolate()->heap()->AllocateJSObjectFromMap(*map),
1491       JSGeneratorObject);
1492 }
1493
1494
1495 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1496   Handle<JSFunction> array_buffer_fun(
1497       isolate()->context()->native_context()->array_buffer_fun());
1498   CALL_HEAP_FUNCTION(
1499       isolate(),
1500       isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1501       JSArrayBuffer);
1502 }
1503
1504
1505 Handle<JSDataView> Factory::NewJSDataView() {
1506   Handle<JSFunction> data_view_fun(
1507       isolate()->context()->native_context()->data_view_fun());
1508   CALL_HEAP_FUNCTION(
1509       isolate(),
1510       isolate()->heap()->AllocateJSObject(*data_view_fun),
1511       JSDataView);
1512 }
1513
1514
1515 static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1516                                     Isolate* isolate) {
1517   Context* native_context = isolate->context()->native_context();
1518   switch (type) {
1519 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size)                        \
1520     case kExternal##Type##Array:                                              \
1521       return native_context->type##_array_fun();
1522
1523     TYPED_ARRAYS(TYPED_ARRAY_FUN)
1524 #undef TYPED_ARRAY_FUN
1525
1526     default:
1527       UNREACHABLE();
1528       return NULL;
1529   }
1530 }
1531
1532
1533 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1534   Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1535
1536   CALL_HEAP_FUNCTION(
1537       isolate(),
1538       isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1539       JSTypedArray);
1540 }
1541
1542
1543 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1544                                     Handle<Object> prototype) {
1545   CALL_HEAP_FUNCTION(
1546       isolate(),
1547       isolate()->heap()->AllocateJSProxy(*handler, *prototype),
1548       JSProxy);
1549 }
1550
1551
1552 void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1553   CALL_HEAP_FUNCTION_VOID(
1554       isolate(),
1555       isolate()->heap()->ReinitializeJSReceiver(
1556           *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
1557 }
1558
1559
1560 void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1561   CALL_HEAP_FUNCTION_VOID(
1562       isolate(),
1563       isolate()->heap()->ReinitializeJSReceiver(
1564           *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1565 }
1566
1567
1568 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1569     Handle<String> name,
1570     int number_of_literals,
1571     bool is_generator,
1572     Handle<Code> code,
1573     Handle<ScopeInfo> scope_info) {
1574   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
1575   shared->set_code(*code);
1576   shared->set_scope_info(*scope_info);
1577   int literals_array_size = number_of_literals;
1578   // If the function contains object, regexp or array literals,
1579   // allocate extra space for a literals array prefix containing the
1580   // context.
1581   if (number_of_literals > 0) {
1582     literals_array_size += JSFunction::kLiteralsPrefixSize;
1583   }
1584   shared->set_num_literals(literals_array_size);
1585   if (is_generator) {
1586     shared->set_instance_class_name(isolate()->heap()->Generator_string());
1587     shared->DisableOptimization(kGenerator);
1588   }
1589   return shared;
1590 }
1591
1592
1593 Handle<JSMessageObject> Factory::NewJSMessageObject(
1594     Handle<String> type,
1595     Handle<JSArray> arguments,
1596     int start_position,
1597     int end_position,
1598     Handle<Object> script,
1599     Handle<Object> stack_frames) {
1600   CALL_HEAP_FUNCTION(isolate(),
1601                      isolate()->heap()->AllocateJSMessageObject(*type,
1602                          *arguments,
1603                          start_position,
1604                          end_position,
1605                          *script,
1606                          *stack_frames),
1607                      JSMessageObject);
1608 }
1609
1610
1611 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1612   CALL_HEAP_FUNCTION(isolate(),
1613                      isolate()->heap()->AllocateSharedFunctionInfo(*name),
1614                      SharedFunctionInfo);
1615 }
1616
1617
1618 Handle<String> Factory::NumberToString(Handle<Object> number) {
1619   CALL_HEAP_FUNCTION(isolate(),
1620                      isolate()->heap()->NumberToString(*number), String);
1621 }
1622
1623
1624 Handle<String> Factory::Uint32ToString(uint32_t value) {
1625   CALL_HEAP_FUNCTION(isolate(),
1626                      isolate()->heap()->Uint32ToString(value), String);
1627 }
1628
1629
1630 Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
1631     Handle<SeededNumberDictionary> dictionary,
1632     uint32_t key,
1633     Handle<Object> value) {
1634   CALL_HEAP_FUNCTION(isolate(),
1635                      dictionary->AtNumberPut(key, *value),
1636                      SeededNumberDictionary);
1637 }
1638
1639
1640 Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
1641     Handle<UnseededNumberDictionary> dictionary,
1642     uint32_t key,
1643     Handle<Object> value) {
1644   CALL_HEAP_FUNCTION(isolate(),
1645                      dictionary->AtNumberPut(key, *value),
1646                      UnseededNumberDictionary);
1647 }
1648
1649
1650 Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
1651                                               Handle<Object> prototype) {
1652   Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1653   CALL_HEAP_FUNCTION(
1654       isolate(),
1655       isolate()->heap()->AllocateFunction(*isolate()->sloppy_function_map(),
1656                                           *function_share,
1657                                           *prototype),
1658       JSFunction);
1659 }
1660
1661
1662 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1663                                         Handle<Object> prototype) {
1664   Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1665   fun->set_context(isolate()->context()->native_context());
1666   return fun;
1667 }
1668
1669
1670 Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1671     Handle<String> name,
1672     StrictMode strict_mode) {
1673   Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1674   Handle<Map> map = strict_mode == SLOPPY
1675       ? isolate()->sloppy_function_without_prototype_map()
1676       : isolate()->strict_function_without_prototype_map();
1677   CALL_HEAP_FUNCTION(isolate(),
1678                      isolate()->heap()->AllocateFunction(
1679                          *map,
1680                          *function_share,
1681                          *the_hole_value()),
1682                      JSFunction);
1683 }
1684
1685
1686 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
1687     Handle<String> name,
1688     StrictMode strict_mode) {
1689   Handle<JSFunction> fun = NewFunctionWithoutPrototypeHelper(name, strict_mode);
1690   fun->set_context(isolate()->context()->native_context());
1691   return fun;
1692 }
1693
1694
1695 Handle<Object> Factory::ToObject(Handle<Object> object) {
1696   CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
1697 }
1698
1699
1700 Handle<Object> Factory::ToObject(Handle<Object> object,
1701                                  Handle<Context> native_context) {
1702   CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1703 }
1704
1705
1706 #ifdef ENABLE_DEBUGGER_SUPPORT
1707 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
1708   // Get the original code of the function.
1709   Handle<Code> code(shared->code());
1710
1711   // Create a copy of the code before allocating the debug info object to avoid
1712   // allocation while setting up the debug info object.
1713   Handle<Code> original_code(*Factory::CopyCode(code));
1714
1715   // Allocate initial fixed array for active break points before allocating the
1716   // debug info object to avoid allocation while setting up the debug info
1717   // object.
1718   Handle<FixedArray> break_points(
1719       NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1720
1721   // Create and set up the debug info object. Debug info contains function, a
1722   // copy of the original code, the executing code and initial fixed array for
1723   // active break points.
1724   Handle<DebugInfo> debug_info =
1725       Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1726   debug_info->set_shared(*shared);
1727   debug_info->set_original_code(*original_code);
1728   debug_info->set_code(*code);
1729   debug_info->set_break_points(*break_points);
1730
1731   // Link debug info to function.
1732   shared->set_debug_info(*debug_info);
1733
1734   return debug_info;
1735 }
1736 #endif
1737
1738
1739 Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
1740                                              int length) {
1741   CALL_HEAP_FUNCTION(
1742       isolate(),
1743       isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1744 }
1745
1746
1747 Handle<JSFunction> Factory::CreateApiFunction(
1748     Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1749   Handle<Code> code = isolate()->builtins()->HandleApiCall();
1750   Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1751
1752   int internal_field_count = 0;
1753   if (!obj->instance_template()->IsUndefined()) {
1754     Handle<ObjectTemplateInfo> instance_template =
1755         Handle<ObjectTemplateInfo>(
1756             ObjectTemplateInfo::cast(obj->instance_template()));
1757     internal_field_count =
1758         Smi::cast(instance_template->internal_field_count())->value();
1759   }
1760
1761   // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
1762   // JSObject::GetHeaderSize.
1763   int instance_size = kPointerSize * internal_field_count;
1764   InstanceType type;
1765   switch (instance_type) {
1766     case JavaScriptObject:
1767       type = JS_OBJECT_TYPE;
1768       instance_size += JSObject::kHeaderSize;
1769       break;
1770     case InnerGlobalObject:
1771       type = JS_GLOBAL_OBJECT_TYPE;
1772       instance_size += JSGlobalObject::kSize;
1773       break;
1774     case OuterGlobalObject:
1775       type = JS_GLOBAL_PROXY_TYPE;
1776       instance_size += JSGlobalProxy::kSize;
1777       break;
1778     default:
1779       UNREACHABLE();
1780       type = JS_OBJECT_TYPE;  // Keep the compiler happy.
1781       break;
1782   }
1783
1784   Handle<JSFunction> result =
1785       NewFunction(Factory::empty_string(),
1786                   type,
1787                   instance_size,
1788                   code,
1789                   true);
1790
1791   // Set length.
1792   result->shared()->set_length(obj->length());
1793
1794   // Set class name.
1795   Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1796   if (class_name->IsString()) {
1797     result->shared()->set_instance_class_name(*class_name);
1798     result->shared()->set_name(*class_name);
1799   }
1800
1801   Handle<Map> map = Handle<Map>(result->initial_map());
1802
1803   // Mark as undetectable if needed.
1804   if (obj->undetectable()) {
1805     map->set_is_undetectable();
1806   }
1807
1808   // Mark as hidden for the __proto__ accessor if needed.
1809   if (obj->hidden_prototype()) {
1810     map->set_is_hidden_prototype();
1811   }
1812
1813   // Mark as needs_access_check if needed.
1814   if (obj->needs_access_check()) {
1815     map->set_is_access_check_needed(true);
1816   }
1817
1818   // Set interceptor information in the map.
1819   if (!obj->named_property_handler()->IsUndefined()) {
1820     map->set_has_named_interceptor();
1821   }
1822   if (!obj->indexed_property_handler()->IsUndefined()) {
1823     map->set_has_indexed_interceptor();
1824   }
1825
1826   // Set instance call-as-function information in the map.
1827   if (!obj->instance_call_handler()->IsUndefined()) {
1828     map->set_has_instance_call_handler();
1829   }
1830
1831   result->shared()->set_function_data(*obj);
1832   result->shared()->set_construct_stub(*construct_stub);
1833   result->shared()->DontAdaptArguments();
1834
1835   // Recursively copy parent instance templates' accessors,
1836   // 'data' may be modified.
1837   int max_number_of_additional_properties = 0;
1838   int max_number_of_static_properties = 0;
1839   FunctionTemplateInfo* info = *obj;
1840   while (true) {
1841     if (!info->instance_template()->IsUndefined()) {
1842       Object* props =
1843           ObjectTemplateInfo::cast(
1844               info->instance_template())->property_accessors();
1845       if (!props->IsUndefined()) {
1846         Handle<Object> props_handle(props, isolate());
1847         NeanderArray props_array(props_handle);
1848         max_number_of_additional_properties += props_array.length();
1849       }
1850     }
1851     if (!info->property_accessors()->IsUndefined()) {
1852       Object* props = info->property_accessors();
1853       if (!props->IsUndefined()) {
1854         Handle<Object> props_handle(props, isolate());
1855         NeanderArray props_array(props_handle);
1856         max_number_of_static_properties += props_array.length();
1857       }
1858     }
1859     Object* parent = info->parent_template();
1860     if (parent->IsUndefined()) break;
1861     info = FunctionTemplateInfo::cast(parent);
1862   }
1863
1864   Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
1865
1866   // Use a temporary FixedArray to acculumate static accessors
1867   int valid_descriptors = 0;
1868   Handle<FixedArray> array;
1869   if (max_number_of_static_properties > 0) {
1870     array = NewFixedArray(max_number_of_static_properties);
1871   }
1872
1873   while (true) {
1874     // Install instance descriptors
1875     if (!obj->instance_template()->IsUndefined()) {
1876       Handle<ObjectTemplateInfo> instance =
1877           Handle<ObjectTemplateInfo>(
1878               ObjectTemplateInfo::cast(obj->instance_template()), isolate());
1879       Handle<Object> props = Handle<Object>(instance->property_accessors(),
1880                                             isolate());
1881       if (!props->IsUndefined()) {
1882         Map::AppendCallbackDescriptors(map, props);
1883       }
1884     }
1885     // Accumulate static accessors
1886     if (!obj->property_accessors()->IsUndefined()) {
1887       Handle<Object> props = Handle<Object>(obj->property_accessors(),
1888                                             isolate());
1889       valid_descriptors =
1890           AccessorInfo::AppendUnique(props, array, valid_descriptors);
1891     }
1892     // Climb parent chain
1893     Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1894     if (parent->IsUndefined()) break;
1895     obj = Handle<FunctionTemplateInfo>::cast(parent);
1896   }
1897
1898   // Install accumulated static accessors
1899   for (int i = 0; i < valid_descriptors; i++) {
1900     Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
1901     JSObject::SetAccessor(result, accessor);
1902   }
1903
1904   ASSERT(result->shared()->IsApiFunction());
1905   return result;
1906 }
1907
1908
1909 Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1910   CALL_HEAP_FUNCTION(isolate(),
1911                      MapCache::Allocate(isolate()->heap(),
1912                                         at_least_space_for),
1913                      MapCache);
1914 }
1915
1916
1917 MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
1918                                                        FixedArray* keys,
1919                                                        Map* map) {
1920   Object* result;
1921   { MaybeObject* maybe_result =
1922         MapCache::cast(context->map_cache())->Put(keys, map);
1923     if (!maybe_result->ToObject(&result)) return maybe_result;
1924   }
1925   context->set_map_cache(MapCache::cast(result));
1926   return result;
1927 }
1928
1929
1930 Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1931                                         Handle<FixedArray> keys,
1932                                         Handle<Map> map) {
1933   CALL_HEAP_FUNCTION(isolate(),
1934                      UpdateMapCacheWith(*context, *keys, *map), MapCache);
1935 }
1936
1937
1938 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1939                                                Handle<FixedArray> keys) {
1940   if (context->map_cache()->IsUndefined()) {
1941     // Allocate the new map cache for the native context.
1942     Handle<MapCache> new_cache = NewMapCache(24);
1943     context->set_map_cache(*new_cache);
1944   }
1945   // Check to see whether there is a matching element in the cache.
1946   Handle<MapCache> cache =
1947       Handle<MapCache>(MapCache::cast(context->map_cache()));
1948   Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1949   if (result->IsMap()) return Handle<Map>::cast(result);
1950   // Create a new map and add it to the cache.
1951   Handle<Map> map =
1952       CopyMap(Handle<Map>(context->object_function()->initial_map()),
1953               keys->length());
1954   AddToMapCache(context, keys, map);
1955   return Handle<Map>(map);
1956 }
1957
1958
1959 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1960                                 JSRegExp::Type type,
1961                                 Handle<String> source,
1962                                 JSRegExp::Flags flags,
1963                                 Handle<Object> data) {
1964   Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1965
1966   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1967   store->set(JSRegExp::kSourceIndex, *source);
1968   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1969   store->set(JSRegExp::kAtomPatternIndex, *data);
1970   regexp->set_data(*store);
1971 }
1972
1973 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1974                                     JSRegExp::Type type,
1975                                     Handle<String> source,
1976                                     JSRegExp::Flags flags,
1977                                     int capture_count) {
1978   Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1979   Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1980   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1981   store->set(JSRegExp::kSourceIndex, *source);
1982   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1983   store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
1984   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
1985   store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
1986   store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1987   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
1988   store->set(JSRegExp::kIrregexpCaptureCountIndex,
1989              Smi::FromInt(capture_count));
1990   regexp->set_data(*store);
1991 }
1992
1993
1994
1995 void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
1996                                 Handle<JSObject> instance,
1997                                 bool* pending_exception) {
1998   // Configure the instance by adding the properties specified by the
1999   // instance template.
2000   Handle<Object> instance_template(desc->instance_template(), isolate());
2001   if (!instance_template->IsUndefined()) {
2002     Execution::ConfigureInstance(isolate(),
2003                                  instance,
2004                                  instance_template,
2005                                  pending_exception);
2006   } else {
2007     *pending_exception = false;
2008   }
2009 }
2010
2011
2012 Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
2013   Heap* h = isolate()->heap();
2014   if (name->Equals(h->undefined_string())) return undefined_value();
2015   if (name->Equals(h->nan_string())) return nan_value();
2016   if (name->Equals(h->infinity_string())) return infinity_value();
2017   return Handle<Object>::null();
2018 }
2019
2020
2021 Handle<Object> Factory::ToBoolean(bool value) {
2022   return value ? true_value() : false_value();
2023 }
2024
2025
2026 } }  // namespace v8::internal