e2a5e05693a1202c1f1a41b1ccc7bb47d78580ee
[platform/upstream/v8.git] / src / factory.cc
1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/factory.h"
6
7 #include "src/allocation-site-scopes.h"
8 #include "src/base/bits.h"
9 #include "src/bootstrapper.h"
10 #include "src/conversions.h"
11 #include "src/macro-assembler.h"
12
13 namespace v8 {
14 namespace internal {
15
16
17 template<typename T>
18 Handle<T> Factory::New(Handle<Map> map, AllocationSpace space) {
19   CALL_HEAP_FUNCTION(
20       isolate(),
21       isolate()->heap()->Allocate(*map, space),
22       T);
23 }
24
25
26 template<typename T>
27 Handle<T> Factory::New(Handle<Map> map,
28                        AllocationSpace space,
29                        Handle<AllocationSite> allocation_site) {
30   CALL_HEAP_FUNCTION(
31       isolate(),
32       isolate()->heap()->Allocate(*map, space, *allocation_site),
33       T);
34 }
35
36
37 Handle<HeapObject> Factory::NewFillerObject(int size,
38                                             bool double_align,
39                                             AllocationSpace space) {
40   CALL_HEAP_FUNCTION(
41       isolate(),
42       isolate()->heap()->AllocateFillerObject(size, double_align, space),
43       HeapObject);
44 }
45
46
47 Handle<Box> Factory::NewBox(Handle<Object> value) {
48   Handle<Box> result = Handle<Box>::cast(NewStruct(BOX_TYPE));
49   result->set_value(*value);
50   return result;
51 }
52
53
54 Handle<PrototypeInfo> Factory::NewPrototypeInfo() {
55   Handle<PrototypeInfo> result =
56       Handle<PrototypeInfo>::cast(NewStruct(PROTOTYPE_INFO_TYPE));
57   result->set_prototype_users(WeakFixedArray::Empty());
58   result->set_validity_cell(Smi::FromInt(0));
59   result->set_constructor_name(Smi::FromInt(0));
60   return result;
61 }
62
63
64 Handle<Oddball> Factory::NewOddball(Handle<Map> map,
65                                     const char* to_string,
66                                     Handle<Object> to_number,
67                                     byte kind) {
68   Handle<Oddball> oddball = New<Oddball>(map, OLD_SPACE);
69   Oddball::Initialize(isolate(), oddball, to_string, to_number, kind);
70   return oddball;
71 }
72
73
74 Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
75   DCHECK(0 <= size);
76   CALL_HEAP_FUNCTION(
77       isolate(),
78       isolate()->heap()->AllocateFixedArray(size, pretenure),
79       FixedArray);
80 }
81
82
83 Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
84                                                    PretenureFlag pretenure) {
85   DCHECK(0 <= size);
86   CALL_HEAP_FUNCTION(
87       isolate(),
88       isolate()->heap()->AllocateFixedArrayWithFiller(size,
89                                                       pretenure,
90                                                       *the_hole_value()),
91       FixedArray);
92 }
93
94
95 Handle<FixedArray> Factory::NewUninitializedFixedArray(int size) {
96   CALL_HEAP_FUNCTION(
97       isolate(),
98       isolate()->heap()->AllocateUninitializedFixedArray(size),
99       FixedArray);
100 }
101
102
103 Handle<FixedArrayBase> Factory::NewFixedDoubleArray(int size,
104                                                     PretenureFlag pretenure) {
105   DCHECK(0 <= size);
106   CALL_HEAP_FUNCTION(
107       isolate(),
108       isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
109       FixedArrayBase);
110 }
111
112
113 Handle<FixedArrayBase> Factory::NewFixedDoubleArrayWithHoles(
114     int size,
115     PretenureFlag pretenure) {
116   DCHECK(0 <= size);
117   Handle<FixedArrayBase> array = NewFixedDoubleArray(size, pretenure);
118   if (size > 0) {
119     Handle<FixedDoubleArray> double_array =
120         Handle<FixedDoubleArray>::cast(array);
121     for (int i = 0; i < size; ++i) {
122       double_array->set_the_hole(i);
123     }
124   }
125   return array;
126 }
127
128
129 Handle<OrderedHashSet> Factory::NewOrderedHashSet() {
130   return OrderedHashSet::Allocate(isolate(), OrderedHashSet::kMinCapacity);
131 }
132
133
134 Handle<OrderedHashMap> Factory::NewOrderedHashMap() {
135   return OrderedHashMap::Allocate(isolate(), OrderedHashMap::kMinCapacity);
136 }
137
138
139 Handle<AccessorPair> Factory::NewAccessorPair() {
140   Handle<AccessorPair> accessors =
141       Handle<AccessorPair>::cast(NewStruct(ACCESSOR_PAIR_TYPE));
142   accessors->set_getter(*the_hole_value(), SKIP_WRITE_BARRIER);
143   accessors->set_setter(*the_hole_value(), SKIP_WRITE_BARRIER);
144   return accessors;
145 }
146
147
148 Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
149   Handle<TypeFeedbackInfo> info =
150       Handle<TypeFeedbackInfo>::cast(NewStruct(TYPE_FEEDBACK_INFO_TYPE));
151   info->initialize_storage();
152   return info;
153 }
154
155
156 // Internalized strings are created in the old generation (data space).
157 Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
158   Utf8StringKey key(string, isolate()->heap()->HashSeed());
159   return InternalizeStringWithKey(&key);
160 }
161
162
163 // Internalized strings are created in the old generation (data space).
164 Handle<String> Factory::InternalizeString(Handle<String> string) {
165   if (string->IsInternalizedString()) return string;
166   return StringTable::LookupString(isolate(), string);
167 }
168
169
170 Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
171   OneByteStringKey key(string, isolate()->heap()->HashSeed());
172   return InternalizeStringWithKey(&key);
173 }
174
175
176 Handle<String> Factory::InternalizeOneByteString(
177     Handle<SeqOneByteString> string, int from, int length) {
178   SeqOneByteSubStringKey key(string, from, length);
179   return InternalizeStringWithKey(&key);
180 }
181
182
183 Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
184   TwoByteStringKey key(string, isolate()->heap()->HashSeed());
185   return InternalizeStringWithKey(&key);
186 }
187
188
189 template<class StringTableKey>
190 Handle<String> Factory::InternalizeStringWithKey(StringTableKey* key) {
191   return StringTable::LookupKey(isolate(), key);
192 }
193
194
195 MaybeHandle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
196                                                   PretenureFlag pretenure) {
197   int length = string.length();
198   if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
199   Handle<SeqOneByteString> result;
200   ASSIGN_RETURN_ON_EXCEPTION(
201       isolate(),
202       result,
203       NewRawOneByteString(string.length(), pretenure),
204       String);
205
206   DisallowHeapAllocation no_gc;
207   // Copy the characters into the new object.
208   CopyChars(SeqOneByteString::cast(*result)->GetChars(),
209             string.start(),
210             length);
211   return result;
212 }
213
214 MaybeHandle<String> Factory::NewStringFromUtf8(Vector<const char> string,
215                                                PretenureFlag pretenure) {
216   // Check for ASCII first since this is the common case.
217   const char* start = string.start();
218   int length = string.length();
219   int non_ascii_start = String::NonAsciiStart(start, length);
220   if (non_ascii_start >= length) {
221     // If the string is ASCII, we do not need to convert the characters
222     // since UTF8 is backwards compatible with ASCII.
223     return NewStringFromOneByte(Vector<const uint8_t>::cast(string), pretenure);
224   }
225
226   // Non-ASCII and we need to decode.
227   Access<UnicodeCache::Utf8Decoder>
228       decoder(isolate()->unicode_cache()->utf8_decoder());
229   decoder->Reset(string.start() + non_ascii_start,
230                  length - non_ascii_start);
231   int utf16_length = static_cast<int>(decoder->Utf16Length());
232   DCHECK(utf16_length > 0);
233   // Allocate string.
234   Handle<SeqTwoByteString> result;
235   ASSIGN_RETURN_ON_EXCEPTION(
236       isolate(), result,
237       NewRawTwoByteString(non_ascii_start + utf16_length, pretenure),
238       String);
239   // Copy ASCII portion.
240   uint16_t* data = result->GetChars();
241   const char* ascii_data = string.start();
242   for (int i = 0; i < non_ascii_start; i++) {
243     *data++ = *ascii_data++;
244   }
245   // Now write the remainder.
246   decoder->WriteUtf16(data, utf16_length);
247   return result;
248 }
249
250
251 MaybeHandle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
252                                                   PretenureFlag pretenure) {
253   int length = string.length();
254   const uc16* start = string.start();
255   if (String::IsOneByte(start, length)) {
256     if (length == 1) return LookupSingleCharacterStringFromCode(string[0]);
257     Handle<SeqOneByteString> result;
258     ASSIGN_RETURN_ON_EXCEPTION(
259         isolate(),
260         result,
261         NewRawOneByteString(length, pretenure),
262         String);
263     CopyChars(result->GetChars(), start, length);
264     return result;
265   } else {
266     Handle<SeqTwoByteString> result;
267     ASSIGN_RETURN_ON_EXCEPTION(
268         isolate(),
269         result,
270         NewRawTwoByteString(length, pretenure),
271         String);
272     CopyChars(result->GetChars(), start, length);
273     return result;
274   }
275 }
276
277
278 Handle<String> Factory::NewInternalizedStringFromUtf8(Vector<const char> str,
279                                                       int chars,
280                                                       uint32_t hash_field) {
281   CALL_HEAP_FUNCTION(
282       isolate(),
283       isolate()->heap()->AllocateInternalizedStringFromUtf8(
284           str, chars, hash_field),
285       String);
286 }
287
288
289 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedString(
290       Vector<const uint8_t> str,
291       uint32_t hash_field) {
292   CALL_HEAP_FUNCTION(
293       isolate(),
294       isolate()->heap()->AllocateOneByteInternalizedString(str, hash_field),
295       String);
296 }
297
298
299 MUST_USE_RESULT Handle<String> Factory::NewOneByteInternalizedSubString(
300     Handle<SeqOneByteString> string, int offset, int length,
301     uint32_t hash_field) {
302   CALL_HEAP_FUNCTION(
303       isolate(), isolate()->heap()->AllocateOneByteInternalizedString(
304                      Vector<const uint8_t>(string->GetChars() + offset, length),
305                      hash_field),
306       String);
307 }
308
309
310 MUST_USE_RESULT Handle<String> Factory::NewTwoByteInternalizedString(
311       Vector<const uc16> str,
312       uint32_t hash_field) {
313   CALL_HEAP_FUNCTION(
314       isolate(),
315       isolate()->heap()->AllocateTwoByteInternalizedString(str, hash_field),
316       String);
317 }
318
319
320 Handle<String> Factory::NewInternalizedStringImpl(
321     Handle<String> string, int chars, uint32_t hash_field) {
322   CALL_HEAP_FUNCTION(
323       isolate(),
324       isolate()->heap()->AllocateInternalizedStringImpl(
325           *string, chars, hash_field),
326       String);
327 }
328
329
330 MaybeHandle<Map> Factory::InternalizedStringMapForString(
331     Handle<String> string) {
332   // If the string is in new space it cannot be used as internalized.
333   if (isolate()->heap()->InNewSpace(*string)) return MaybeHandle<Map>();
334
335   // Find the corresponding internalized string map for strings.
336   switch (string->map()->instance_type()) {
337     case STRING_TYPE: return internalized_string_map();
338     case ONE_BYTE_STRING_TYPE:
339       return one_byte_internalized_string_map();
340     case EXTERNAL_STRING_TYPE: return external_internalized_string_map();
341     case EXTERNAL_ONE_BYTE_STRING_TYPE:
342       return external_one_byte_internalized_string_map();
343     case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
344       return external_internalized_string_with_one_byte_data_map();
345     case SHORT_EXTERNAL_STRING_TYPE:
346       return short_external_internalized_string_map();
347     case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
348       return short_external_one_byte_internalized_string_map();
349     case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
350       return short_external_internalized_string_with_one_byte_data_map();
351     default: return MaybeHandle<Map>();  // No match found.
352   }
353 }
354
355
356 MaybeHandle<SeqOneByteString> Factory::NewRawOneByteString(
357     int length, PretenureFlag pretenure) {
358   if (length > String::kMaxLength || length < 0) {
359     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqOneByteString);
360   }
361   CALL_HEAP_FUNCTION(
362       isolate(),
363       isolate()->heap()->AllocateRawOneByteString(length, pretenure),
364       SeqOneByteString);
365 }
366
367
368 MaybeHandle<SeqTwoByteString> Factory::NewRawTwoByteString(
369     int length, PretenureFlag pretenure) {
370   if (length > String::kMaxLength || length < 0) {
371     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), SeqTwoByteString);
372   }
373   CALL_HEAP_FUNCTION(
374       isolate(),
375       isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
376       SeqTwoByteString);
377 }
378
379
380 Handle<String> Factory::LookupSingleCharacterStringFromCode(uint32_t code) {
381   if (code <= String::kMaxOneByteCharCodeU) {
382     {
383       DisallowHeapAllocation no_allocation;
384       Object* value = single_character_string_cache()->get(code);
385       if (value != *undefined_value()) {
386         return handle(String::cast(value), isolate());
387       }
388     }
389     uint8_t buffer[1];
390     buffer[0] = static_cast<uint8_t>(code);
391     Handle<String> result =
392         InternalizeOneByteString(Vector<const uint8_t>(buffer, 1));
393     single_character_string_cache()->set(code, *result);
394     return result;
395   }
396   DCHECK(code <= String::kMaxUtf16CodeUnitU);
397
398   Handle<SeqTwoByteString> result = NewRawTwoByteString(1).ToHandleChecked();
399   result->SeqTwoByteStringSet(0, static_cast<uint16_t>(code));
400   return result;
401 }
402
403
404 // Returns true for a character in a range.  Both limits are inclusive.
405 static inline bool Between(uint32_t character, uint32_t from, uint32_t to) {
406   // This makes uses of the the unsigned wraparound.
407   return character - from <= to - from;
408 }
409
410
411 static inline Handle<String> MakeOrFindTwoCharacterString(Isolate* isolate,
412                                                           uint16_t c1,
413                                                           uint16_t c2) {
414   // Numeric strings have a different hash algorithm not known by
415   // LookupTwoCharsStringIfExists, so we skip this step for such strings.
416   if (!Between(c1, '0', '9') || !Between(c2, '0', '9')) {
417     Handle<String> result;
418     if (StringTable::LookupTwoCharsStringIfExists(isolate, c1, c2).
419         ToHandle(&result)) {
420       return result;
421     }
422   }
423
424   // Now we know the length is 2, we might as well make use of that fact
425   // when building the new string.
426   if (static_cast<unsigned>(c1 | c2) <= String::kMaxOneByteCharCodeU) {
427     // We can do this.
428     DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCodeU +
429                                       1));  // because of this.
430     Handle<SeqOneByteString> str =
431         isolate->factory()->NewRawOneByteString(2).ToHandleChecked();
432     uint8_t* dest = str->GetChars();
433     dest[0] = static_cast<uint8_t>(c1);
434     dest[1] = static_cast<uint8_t>(c2);
435     return str;
436   } else {
437     Handle<SeqTwoByteString> str =
438         isolate->factory()->NewRawTwoByteString(2).ToHandleChecked();
439     uc16* dest = str->GetChars();
440     dest[0] = c1;
441     dest[1] = c2;
442     return str;
443   }
444 }
445
446
447 template<typename SinkChar, typename StringType>
448 Handle<String> ConcatStringContent(Handle<StringType> result,
449                                    Handle<String> first,
450                                    Handle<String> second) {
451   DisallowHeapAllocation pointer_stays_valid;
452   SinkChar* sink = result->GetChars();
453   String::WriteToFlat(*first, sink, 0, first->length());
454   String::WriteToFlat(*second, sink + first->length(), 0, second->length());
455   return result;
456 }
457
458
459 MaybeHandle<String> Factory::NewConsString(Handle<String> left,
460                                            Handle<String> right) {
461   int left_length = left->length();
462   if (left_length == 0) return right;
463   int right_length = right->length();
464   if (right_length == 0) return left;
465
466   int length = left_length + right_length;
467
468   if (length == 2) {
469     uint16_t c1 = left->Get(0);
470     uint16_t c2 = right->Get(0);
471     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
472   }
473
474   // Make sure that an out of memory exception is thrown if the length
475   // of the new cons string is too large.
476   if (length > String::kMaxLength || length < 0) {
477     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
478   }
479
480   bool left_is_one_byte = left->IsOneByteRepresentation();
481   bool right_is_one_byte = right->IsOneByteRepresentation();
482   bool is_one_byte = left_is_one_byte && right_is_one_byte;
483   bool is_one_byte_data_in_two_byte_string = false;
484   if (!is_one_byte) {
485     // At least one of the strings uses two-byte representation so we
486     // can't use the fast case code for short one-byte strings below, but
487     // we can try to save memory if all chars actually fit in one-byte.
488     is_one_byte_data_in_two_byte_string =
489         left->HasOnlyOneByteChars() && right->HasOnlyOneByteChars();
490     if (is_one_byte_data_in_two_byte_string) {
491       isolate()->counters()->string_add_runtime_ext_to_one_byte()->Increment();
492     }
493   }
494
495   // If the resulting string is small make a flat string.
496   if (length < ConsString::kMinLength) {
497     // Note that neither of the two inputs can be a slice because:
498     STATIC_ASSERT(ConsString::kMinLength <= SlicedString::kMinLength);
499     DCHECK(left->IsFlat());
500     DCHECK(right->IsFlat());
501
502     STATIC_ASSERT(ConsString::kMinLength <= String::kMaxLength);
503     if (is_one_byte) {
504       Handle<SeqOneByteString> result =
505           NewRawOneByteString(length).ToHandleChecked();
506       DisallowHeapAllocation no_gc;
507       uint8_t* dest = result->GetChars();
508       // Copy left part.
509       const uint8_t* src =
510           left->IsExternalString()
511               ? Handle<ExternalOneByteString>::cast(left)->GetChars()
512               : Handle<SeqOneByteString>::cast(left)->GetChars();
513       for (int i = 0; i < left_length; i++) *dest++ = src[i];
514       // Copy right part.
515       src = right->IsExternalString()
516                 ? Handle<ExternalOneByteString>::cast(right)->GetChars()
517                 : Handle<SeqOneByteString>::cast(right)->GetChars();
518       for (int i = 0; i < right_length; i++) *dest++ = src[i];
519       return result;
520     }
521
522     return (is_one_byte_data_in_two_byte_string)
523         ? ConcatStringContent<uint8_t>(
524             NewRawOneByteString(length).ToHandleChecked(), left, right)
525         : ConcatStringContent<uc16>(
526             NewRawTwoByteString(length).ToHandleChecked(), left, right);
527   }
528
529   return (is_one_byte || is_one_byte_data_in_two_byte_string)
530              ? NewOneByteConsString(length, left, right)
531              : NewTwoByteConsString(length, left, right);
532 }
533
534
535 MaybeHandle<String> Factory::NewOneByteConsString(int length,
536                                                   Handle<String> left,
537                                                   Handle<String> right) {
538   return NewRawConsString(cons_one_byte_string_map(), length, left, right);
539 }
540
541
542 MaybeHandle<String> Factory::NewTwoByteConsString(int length,
543                                                   Handle<String> left,
544                                                   Handle<String> right) {
545   return NewRawConsString(cons_string_map(), length, left, right);
546 }
547
548
549 MaybeHandle<String> Factory::NewRawConsString(Handle<Map> map, int length,
550                                               Handle<String> left,
551                                               Handle<String> right) {
552   Handle<ConsString> result = New<ConsString>(map, NEW_SPACE);
553
554   DisallowHeapAllocation no_gc;
555   WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
556
557   result->set_hash_field(String::kEmptyHashField);
558   result->set_length(length);
559   result->set_first(*left, mode);
560   result->set_second(*right, mode);
561   return result;
562 }
563
564
565 Handle<String> Factory::NewProperSubString(Handle<String> str,
566                                            int begin,
567                                            int end) {
568 #if VERIFY_HEAP
569   if (FLAG_verify_heap) str->StringVerify();
570 #endif
571   DCHECK(begin > 0 || end < str->length());
572
573   str = String::Flatten(str);
574
575   int length = end - begin;
576   if (length <= 0) return empty_string();
577   if (length == 1) {
578     return LookupSingleCharacterStringFromCode(str->Get(begin));
579   }
580   if (length == 2) {
581     // Optimization for 2-byte strings often used as keys in a decompression
582     // dictionary.  Check whether we already have the string in the string
583     // table to prevent creation of many unnecessary strings.
584     uint16_t c1 = str->Get(begin);
585     uint16_t c2 = str->Get(begin + 1);
586     return MakeOrFindTwoCharacterString(isolate(), c1, c2);
587   }
588
589   if (!FLAG_string_slices || length < SlicedString::kMinLength) {
590     if (str->IsOneByteRepresentation()) {
591       Handle<SeqOneByteString> result =
592           NewRawOneByteString(length).ToHandleChecked();
593       uint8_t* dest = result->GetChars();
594       DisallowHeapAllocation no_gc;
595       String::WriteToFlat(*str, dest, begin, end);
596       return result;
597     } else {
598       Handle<SeqTwoByteString> result =
599           NewRawTwoByteString(length).ToHandleChecked();
600       uc16* dest = result->GetChars();
601       DisallowHeapAllocation no_gc;
602       String::WriteToFlat(*str, dest, begin, end);
603       return result;
604     }
605   }
606
607   int offset = begin;
608
609   if (str->IsSlicedString()) {
610     Handle<SlicedString> slice = Handle<SlicedString>::cast(str);
611     str = Handle<String>(slice->parent(), isolate());
612     offset += slice->offset();
613   }
614
615   DCHECK(str->IsSeqString() || str->IsExternalString());
616   Handle<Map> map = str->IsOneByteRepresentation()
617                         ? sliced_one_byte_string_map()
618                         : sliced_string_map();
619   Handle<SlicedString> slice = New<SlicedString>(map, NEW_SPACE);
620
621   slice->set_hash_field(String::kEmptyHashField);
622   slice->set_length(length);
623   slice->set_parent(*str);
624   slice->set_offset(offset);
625   return slice;
626 }
627
628
629 MaybeHandle<String> Factory::NewExternalStringFromOneByte(
630     const ExternalOneByteString::Resource* resource) {
631   size_t length = resource->length();
632   if (length > static_cast<size_t>(String::kMaxLength)) {
633     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
634   }
635
636   Handle<Map> map = external_one_byte_string_map();
637   Handle<ExternalOneByteString> external_string =
638       New<ExternalOneByteString>(map, NEW_SPACE);
639   external_string->set_length(static_cast<int>(length));
640   external_string->set_hash_field(String::kEmptyHashField);
641   external_string->set_resource(resource);
642
643   return external_string;
644 }
645
646
647 MaybeHandle<String> Factory::NewExternalStringFromTwoByte(
648     const ExternalTwoByteString::Resource* resource) {
649   size_t length = resource->length();
650   if (length > static_cast<size_t>(String::kMaxLength)) {
651     THROW_NEW_ERROR(isolate(), NewInvalidStringLengthError(), String);
652   }
653
654   // For small strings we check whether the resource contains only
655   // one byte characters.  If yes, we use a different string map.
656   static const size_t kOneByteCheckLengthLimit = 32;
657   bool is_one_byte = length <= kOneByteCheckLengthLimit &&
658       String::IsOneByte(resource->data(), static_cast<int>(length));
659   Handle<Map> map = is_one_byte ?
660       external_string_with_one_byte_data_map() : external_string_map();
661   Handle<ExternalTwoByteString> external_string =
662       New<ExternalTwoByteString>(map, NEW_SPACE);
663   external_string->set_length(static_cast<int>(length));
664   external_string->set_hash_field(String::kEmptyHashField);
665   external_string->set_resource(resource);
666
667   return external_string;
668 }
669
670
671 Handle<Symbol> Factory::NewSymbol() {
672   CALL_HEAP_FUNCTION(
673       isolate(),
674       isolate()->heap()->AllocateSymbol(),
675       Symbol);
676 }
677
678
679 Handle<Symbol> Factory::NewPrivateSymbol(Handle<Object> name) {
680   Handle<Symbol> symbol = NewSymbol();
681   symbol->set_is_private(true);
682   if (name->IsString()) {
683     symbol->set_name(*name);
684   } else {
685     DCHECK(name->IsUndefined());
686   }
687   return symbol;
688 }
689
690
691 Handle<Context> Factory::NewNativeContext() {
692   Handle<FixedArray> array =
693       NewFixedArray(Context::NATIVE_CONTEXT_SLOTS, TENURED);
694   array->set_map_no_write_barrier(*native_context_map());
695   Handle<Context> context = Handle<Context>::cast(array);
696   context->set_js_array_maps(*undefined_value());
697   DCHECK(context->IsNativeContext());
698   return context;
699 }
700
701
702 Handle<Context> Factory::NewScriptContext(Handle<JSFunction> function,
703                                           Handle<ScopeInfo> scope_info) {
704   Handle<FixedArray> array =
705       NewFixedArray(scope_info->ContextLength(), TENURED);
706   array->set_map_no_write_barrier(*script_context_map());
707   Handle<Context> context = Handle<Context>::cast(array);
708   context->set_closure(*function);
709   context->set_previous(function->context());
710   context->set_extension(*scope_info);
711   context->set_global_object(function->context()->global_object());
712   DCHECK(context->IsScriptContext());
713   return context;
714 }
715
716
717 Handle<ScriptContextTable> Factory::NewScriptContextTable() {
718   Handle<FixedArray> array = NewFixedArray(1);
719   array->set_map_no_write_barrier(*script_context_table_map());
720   Handle<ScriptContextTable> context_table =
721       Handle<ScriptContextTable>::cast(array);
722   context_table->set_used(0);
723   return context_table;
724 }
725
726
727 Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
728   Handle<FixedArray> array =
729       NewFixedArray(scope_info->ContextLength(), TENURED);
730   array->set_map_no_write_barrier(*module_context_map());
731   // Instance link will be set later.
732   Handle<Context> context = Handle<Context>::cast(array);
733   context->set_extension(Smi::FromInt(0));
734   return context;
735 }
736
737
738 Handle<Context> Factory::NewFunctionContext(int length,
739                                             Handle<JSFunction> function) {
740   DCHECK(length >= Context::MIN_CONTEXT_SLOTS);
741   Handle<FixedArray> array = NewFixedArray(length);
742   array->set_map_no_write_barrier(*function_context_map());
743   Handle<Context> context = Handle<Context>::cast(array);
744   context->set_closure(*function);
745   context->set_previous(function->context());
746   context->set_extension(Smi::FromInt(0));
747   context->set_global_object(function->context()->global_object());
748   return context;
749 }
750
751
752 Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
753                                          Handle<Context> previous,
754                                          Handle<String> name,
755                                          Handle<Object> thrown_object) {
756   STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == Context::THROWN_OBJECT_INDEX);
757   Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS + 1);
758   array->set_map_no_write_barrier(*catch_context_map());
759   Handle<Context> context = Handle<Context>::cast(array);
760   context->set_closure(*function);
761   context->set_previous(*previous);
762   context->set_extension(*name);
763   context->set_global_object(previous->global_object());
764   context->set(Context::THROWN_OBJECT_INDEX, *thrown_object);
765   return context;
766 }
767
768
769 Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
770                                         Handle<Context> previous,
771                                         Handle<JSReceiver> extension) {
772   Handle<FixedArray> array = NewFixedArray(Context::MIN_CONTEXT_SLOTS);
773   array->set_map_no_write_barrier(*with_context_map());
774   Handle<Context> context = Handle<Context>::cast(array);
775   context->set_closure(*function);
776   context->set_previous(*previous);
777   context->set_extension(*extension);
778   context->set_global_object(previous->global_object());
779   return context;
780 }
781
782
783 Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
784                                          Handle<Context> previous,
785                                          Handle<ScopeInfo> scope_info) {
786   Handle<FixedArray> array =
787       NewFixedArrayWithHoles(scope_info->ContextLength());
788   array->set_map_no_write_barrier(*block_context_map());
789   Handle<Context> context = Handle<Context>::cast(array);
790   context->set_closure(*function);
791   context->set_previous(*previous);
792   context->set_extension(*scope_info);
793   context->set_global_object(previous->global_object());
794   return context;
795 }
796
797
798 Handle<Struct> Factory::NewStruct(InstanceType type) {
799   CALL_HEAP_FUNCTION(
800       isolate(),
801       isolate()->heap()->AllocateStruct(type),
802       Struct);
803 }
804
805
806 Handle<CodeCache> Factory::NewCodeCache() {
807   Handle<CodeCache> code_cache =
808       Handle<CodeCache>::cast(NewStruct(CODE_CACHE_TYPE));
809   code_cache->set_default_cache(*empty_fixed_array(), SKIP_WRITE_BARRIER);
810   code_cache->set_normal_type_cache(*undefined_value(), SKIP_WRITE_BARRIER);
811   return code_cache;
812 }
813
814
815 Handle<AliasedArgumentsEntry> Factory::NewAliasedArgumentsEntry(
816     int aliased_context_slot) {
817   Handle<AliasedArgumentsEntry> entry = Handle<AliasedArgumentsEntry>::cast(
818       NewStruct(ALIASED_ARGUMENTS_ENTRY_TYPE));
819   entry->set_aliased_context_slot(aliased_context_slot);
820   return entry;
821 }
822
823
824 Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
825   Handle<ExecutableAccessorInfo> info =
826       Handle<ExecutableAccessorInfo>::cast(
827           NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
828   info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
829   return info;
830 }
831
832
833 Handle<Script> Factory::NewScript(Handle<String> source) {
834   // Create and initialize script object.
835   Heap* heap = isolate()->heap();
836   Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
837   script->set_source(*source);
838   script->set_name(heap->undefined_value());
839   script->set_id(isolate()->heap()->NextScriptId());
840   script->set_line_offset(Smi::FromInt(0));
841   script->set_column_offset(Smi::FromInt(0));
842   script->set_context_data(heap->undefined_value());
843   script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
844   script->set_wrapper(heap->undefined_value());
845   script->set_line_ends(heap->undefined_value());
846   script->set_eval_from_shared(heap->undefined_value());
847   script->set_eval_from_instructions_offset(Smi::FromInt(0));
848   script->set_shared_function_infos(Smi::FromInt(0));
849   script->set_flags(Smi::FromInt(0));
850
851   return script;
852 }
853
854
855 Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
856   CALL_HEAP_FUNCTION(isolate(),
857                      isolate()->heap()->AllocateForeign(addr, pretenure),
858                      Foreign);
859 }
860
861
862 Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
863   return NewForeign((Address) desc, TENURED);
864 }
865
866
867 Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
868   DCHECK(0 <= length);
869   CALL_HEAP_FUNCTION(
870       isolate(),
871       isolate()->heap()->AllocateByteArray(length, pretenure),
872       ByteArray);
873 }
874
875
876 Handle<BytecodeArray> Factory::NewBytecodeArray(int length,
877                                                 const byte* raw_bytecodes,
878                                                 int frame_size) {
879   DCHECK(0 <= length);
880   CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateBytecodeArray(
881                                     length, raw_bytecodes, frame_size),
882                      BytecodeArray);
883 }
884
885
886 Handle<ExternalArray> Factory::NewExternalArray(int length,
887                                                 ExternalArrayType array_type,
888                                                 void* external_pointer,
889                                                 PretenureFlag pretenure) {
890   DCHECK(0 <= length && length <= Smi::kMaxValue);
891   CALL_HEAP_FUNCTION(
892       isolate(),
893       isolate()->heap()->AllocateExternalArray(length,
894                                                array_type,
895                                                external_pointer,
896                                                pretenure),
897       ExternalArray);
898 }
899
900
901 Handle<FixedTypedArrayBase> Factory::NewFixedTypedArray(
902     int length, ExternalArrayType array_type, bool initialize,
903     PretenureFlag pretenure) {
904   DCHECK(0 <= length && length <= Smi::kMaxValue);
905   CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateFixedTypedArray(
906                                     length, array_type, initialize, pretenure),
907                      FixedTypedArrayBase);
908 }
909
910
911 Handle<Cell> Factory::NewCell(Handle<Object> value) {
912   AllowDeferredHandleDereference convert_to_cell;
913   CALL_HEAP_FUNCTION(
914       isolate(),
915       isolate()->heap()->AllocateCell(*value),
916       Cell);
917 }
918
919
920 Handle<PropertyCell> Factory::NewPropertyCell() {
921   CALL_HEAP_FUNCTION(
922       isolate(),
923       isolate()->heap()->AllocatePropertyCell(),
924       PropertyCell);
925 }
926
927
928 Handle<WeakCell> Factory::NewWeakCell(Handle<HeapObject> value) {
929   // It is safe to dereference the value because we are embedding it
930   // in cell and not inspecting its fields.
931   AllowDeferredHandleDereference convert_to_cell;
932   CALL_HEAP_FUNCTION(isolate(), isolate()->heap()->AllocateWeakCell(*value),
933                      WeakCell);
934 }
935
936
937 Handle<AllocationSite> Factory::NewAllocationSite() {
938   Handle<Map> map = allocation_site_map();
939   Handle<AllocationSite> site = New<AllocationSite>(map, OLD_SPACE);
940   site->Initialize();
941
942   // Link the site
943   site->set_weak_next(isolate()->heap()->allocation_sites_list());
944   isolate()->heap()->set_allocation_sites_list(*site);
945   return site;
946 }
947
948
949 Handle<Map> Factory::NewMap(InstanceType type,
950                             int instance_size,
951                             ElementsKind elements_kind) {
952   CALL_HEAP_FUNCTION(
953       isolate(),
954       isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
955       Map);
956 }
957
958
959 Handle<JSObject> Factory::CopyJSObject(Handle<JSObject> object) {
960   CALL_HEAP_FUNCTION(isolate(),
961                      isolate()->heap()->CopyJSObject(*object, NULL),
962                      JSObject);
963 }
964
965
966 Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
967     Handle<JSObject> object,
968     Handle<AllocationSite> site) {
969   CALL_HEAP_FUNCTION(isolate(),
970                      isolate()->heap()->CopyJSObject(
971                          *object,
972                          site.is_null() ? NULL : *site),
973                      JSObject);
974 }
975
976
977 Handle<FixedArray> Factory::CopyFixedArrayWithMap(Handle<FixedArray> array,
978                                                   Handle<Map> map) {
979   CALL_HEAP_FUNCTION(isolate(),
980                      isolate()->heap()->CopyFixedArrayWithMap(*array, *map),
981                      FixedArray);
982 }
983
984
985 Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
986   CALL_HEAP_FUNCTION(isolate(),
987                      isolate()->heap()->CopyFixedArray(*array),
988                      FixedArray);
989 }
990
991
992 Handle<FixedArray> Factory::CopyAndTenureFixedCOWArray(
993     Handle<FixedArray> array) {
994   DCHECK(isolate()->heap()->InNewSpace(*array));
995   CALL_HEAP_FUNCTION(isolate(),
996                      isolate()->heap()->CopyAndTenureFixedCOWArray(*array),
997                      FixedArray);
998 }
999
1000
1001 Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
1002     Handle<FixedDoubleArray> array) {
1003   CALL_HEAP_FUNCTION(isolate(),
1004                      isolate()->heap()->CopyFixedDoubleArray(*array),
1005                      FixedDoubleArray);
1006 }
1007
1008
1009 Handle<Object> Factory::NewNumber(double value,
1010                                   PretenureFlag pretenure) {
1011   // We need to distinguish the minus zero value and this cannot be
1012   // done after conversion to int. Doing this by comparing bit
1013   // patterns is faster than using fpclassify() et al.
1014   if (IsMinusZero(value)) return NewHeapNumber(-0.0, IMMUTABLE, pretenure);
1015
1016   int int_value = FastD2IChecked(value);
1017   if (value == int_value && Smi::IsValid(int_value)) {
1018     return handle(Smi::FromInt(int_value), isolate());
1019   }
1020
1021   // Materialize the value in the heap.
1022   return NewHeapNumber(value, IMMUTABLE, pretenure);
1023 }
1024
1025
1026 Handle<Object> Factory::NewNumberFromInt(int32_t value,
1027                                          PretenureFlag pretenure) {
1028   if (Smi::IsValid(value)) return handle(Smi::FromInt(value), isolate());
1029   // Bypass NewNumber to avoid various redundant checks.
1030   return NewHeapNumber(FastI2D(value), IMMUTABLE, pretenure);
1031 }
1032
1033
1034 Handle<Object> Factory::NewNumberFromUint(uint32_t value,
1035                                           PretenureFlag pretenure) {
1036   int32_t int32v = static_cast<int32_t>(value);
1037   if (int32v >= 0 && Smi::IsValid(int32v)) {
1038     return handle(Smi::FromInt(int32v), isolate());
1039   }
1040   return NewHeapNumber(FastUI2D(value), IMMUTABLE, pretenure);
1041 }
1042
1043
1044 Handle<HeapNumber> Factory::NewHeapNumber(double value,
1045                                           MutableMode mode,
1046                                           PretenureFlag pretenure) {
1047   CALL_HEAP_FUNCTION(
1048       isolate(),
1049       isolate()->heap()->AllocateHeapNumber(value, mode, pretenure),
1050       HeapNumber);
1051 }
1052
1053
1054 Handle<Float32x4> Factory::NewFloat32x4(float w, float x, float y, float z,
1055                                         PretenureFlag pretenure) {
1056   CALL_HEAP_FUNCTION(
1057       isolate(), isolate()->heap()->AllocateFloat32x4(w, x, y, z, pretenure),
1058       Float32x4);
1059 }
1060
1061
1062 Handle<Object> Factory::NewError(const char* maker,
1063                                  MessageTemplate::Template template_index,
1064                                  Handle<Object> arg0, Handle<Object> arg1,
1065                                  Handle<Object> arg2) {
1066   HandleScope scope(isolate());
1067   Handle<String> error_maker = InternalizeUtf8String(maker);
1068   if (isolate()->bootstrapper()->IsActive()) {
1069     // If this exception is being thrown during bootstrapping,
1070     // js_builtins_object is unavailable. We return the error maker
1071     // name's string as the exception since we have nothing better
1072     // to do.
1073     return scope.CloseAndEscape(error_maker);
1074   }
1075   Handle<Object> fun_obj = Object::GetProperty(isolate()->js_builtins_object(),
1076                                                error_maker).ToHandleChecked();
1077
1078   Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1079   Handle<Object> message_type(Smi::FromInt(template_index), isolate());
1080   if (arg0.is_null()) arg0 = undefined_value();
1081   if (arg1.is_null()) arg1 = undefined_value();
1082   if (arg2.is_null()) arg2 = undefined_value();
1083   Handle<Object> argv[] = {message_type, arg0, arg1, arg2};
1084
1085   // Invoke the JavaScript factory method. If an exception is thrown while
1086   // running the factory method, use the exception as the result.
1087   Handle<Object> result;
1088   MaybeHandle<Object> exception;
1089   if (!Execution::TryCall(fun, isolate()->js_builtins_object(), arraysize(argv),
1090                           argv, &exception).ToHandle(&result)) {
1091     Handle<Object> exception_obj;
1092     if (exception.ToHandle(&exception_obj)) {
1093       result = exception_obj;
1094     } else {
1095       result = undefined_value();
1096     }
1097   }
1098   return scope.CloseAndEscape(result);
1099 }
1100
1101
1102 Handle<Object> Factory::NewError(MessageTemplate::Template template_index,
1103                                  Handle<Object> arg0, Handle<Object> arg1,
1104                                  Handle<Object> arg2) {
1105   return NewError("MakeError", template_index, arg0, arg1, arg2);
1106 }
1107
1108
1109 Handle<Object> Factory::NewTypeError(MessageTemplate::Template template_index,
1110                                      Handle<Object> arg0, Handle<Object> arg1,
1111                                      Handle<Object> arg2) {
1112   return NewError("MakeTypeError", template_index, arg0, arg1, arg2);
1113 }
1114
1115
1116 Handle<Object> Factory::NewSyntaxError(MessageTemplate::Template template_index,
1117                                        Handle<Object> arg0, Handle<Object> arg1,
1118                                        Handle<Object> arg2) {
1119   return NewError("MakeSyntaxError", template_index, arg0, arg1, arg2);
1120 }
1121
1122
1123 Handle<Object> Factory::NewReferenceError(
1124     MessageTemplate::Template template_index, Handle<Object> arg0,
1125     Handle<Object> arg1, Handle<Object> arg2) {
1126   return NewError("MakeReferenceError", template_index, arg0, arg1, arg2);
1127 }
1128
1129
1130 Handle<Object> Factory::NewRangeError(MessageTemplate::Template template_index,
1131                                       Handle<Object> arg0, Handle<Object> arg1,
1132                                       Handle<Object> arg2) {
1133   return NewError("MakeRangeError", template_index, arg0, arg1, arg2);
1134 }
1135
1136
1137 Handle<Object> Factory::NewEvalError(MessageTemplate::Template template_index,
1138                                      Handle<Object> arg0, Handle<Object> arg1,
1139                                      Handle<Object> arg2) {
1140   return NewError("MakeEvalError", template_index, arg0, arg1, arg2);
1141 }
1142
1143
1144 Handle<String> Factory::EmergencyNewError(const char* message,
1145                                           Handle<JSArray> args) {
1146   const int kBufferSize = 1000;
1147   char buffer[kBufferSize];
1148   size_t space = kBufferSize;
1149   char* p = &buffer[0];
1150
1151   Vector<char> v(buffer, kBufferSize);
1152   StrNCpy(v, message, space);
1153   space -= Min(space, strlen(message));
1154   p = &buffer[kBufferSize] - space;
1155
1156   for (int i = 0; i < Smi::cast(args->length())->value(); i++) {
1157     if (space > 0) {
1158       *p++ = ' ';
1159       space--;
1160       if (space > 0) {
1161         Handle<String> arg_str = Handle<String>::cast(
1162             Object::GetElement(isolate(), args, i).ToHandleChecked());
1163         base::SmartArrayPointer<char> arg = arg_str->ToCString();
1164         Vector<char> v2(p, static_cast<int>(space));
1165         StrNCpy(v2, arg.get(), space);
1166         space -= Min(space, strlen(arg.get()));
1167         p = &buffer[kBufferSize] - space;
1168       }
1169     }
1170   }
1171   if (space > 0) {
1172     *p = '\0';
1173   } else {
1174     buffer[kBufferSize - 1] = '\0';
1175   }
1176   return NewStringFromUtf8(CStrVector(buffer), TENURED).ToHandleChecked();
1177 }
1178
1179
1180 Handle<Object> Factory::NewError(const char* maker, const char* message,
1181                                  Handle<JSArray> args) {
1182   Handle<String> make_str = InternalizeUtf8String(maker);
1183   Handle<Object> fun_obj = Object::GetProperty(
1184       isolate()->js_builtins_object(), make_str).ToHandleChecked();
1185   // If the builtins haven't been properly configured yet this error
1186   // constructor may not have been defined.  Bail out.
1187   if (!fun_obj->IsJSFunction()) {
1188     return EmergencyNewError(message, args);
1189   }
1190   Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
1191   Handle<Object> message_obj = InternalizeUtf8String(message);
1192   Handle<Object> argv[] = { message_obj, args };
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   Handle<Object> result;
1197   MaybeHandle<Object> exception;
1198   if (!Execution::TryCall(fun,
1199                           isolate()->js_builtins_object(),
1200                           arraysize(argv),
1201                           argv,
1202                           &exception).ToHandle(&result)) {
1203     Handle<Object> exception_obj;
1204     if (exception.ToHandle(&exception_obj)) return exception_obj;
1205     return undefined_value();
1206   }
1207   return result;
1208 }
1209
1210
1211 Handle<Object> Factory::NewError(const char* constructor,
1212                                  Handle<String> message) {
1213   Handle<String> constr = InternalizeUtf8String(constructor);
1214   Handle<JSFunction> fun = Handle<JSFunction>::cast(Object::GetProperty(
1215       isolate()->js_builtins_object(), constr).ToHandleChecked());
1216   Handle<Object> argv[] = { message };
1217
1218   // Invoke the JavaScript factory method. If an exception is thrown while
1219   // running the factory method, use the exception as the result.
1220   Handle<Object> result;
1221   MaybeHandle<Object> exception;
1222   if (!Execution::TryCall(fun,
1223                           isolate()->js_builtins_object(),
1224                           arraysize(argv),
1225                           argv,
1226                           &exception).ToHandle(&result)) {
1227     Handle<Object> exception_obj;
1228     if (exception.ToHandle(&exception_obj)) return exception_obj;
1229     return undefined_value();
1230   }
1231   return result;
1232 }
1233
1234
1235 void Factory::InitializeFunction(Handle<JSFunction> function,
1236                                  Handle<SharedFunctionInfo> info,
1237                                  Handle<Context> context) {
1238   function->initialize_properties();
1239   function->initialize_elements();
1240   function->set_shared(*info);
1241   function->set_code(info->code());
1242   function->set_context(*context);
1243   function->set_prototype_or_initial_map(*the_hole_value());
1244   function->set_literals_or_bindings(*empty_fixed_array());
1245   function->set_next_function_link(*undefined_value(), SKIP_WRITE_BARRIER);
1246 }
1247
1248
1249 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1250                                         Handle<SharedFunctionInfo> info,
1251                                         Handle<Context> context,
1252                                         PretenureFlag pretenure) {
1253   AllocationSpace space = pretenure == TENURED ? OLD_SPACE : NEW_SPACE;
1254   Handle<JSFunction> result = New<JSFunction>(map, space);
1255   InitializeFunction(result, info, context);
1256   return result;
1257 }
1258
1259
1260 Handle<JSFunction> Factory::NewFunction(Handle<Map> map,
1261                                         Handle<String> name,
1262                                         MaybeHandle<Code> code) {
1263   Handle<Context> context(isolate()->native_context());
1264   Handle<SharedFunctionInfo> info = NewSharedFunctionInfo(name, code);
1265   DCHECK(is_sloppy(info->language_mode()) &&
1266          (map.is_identical_to(isolate()->sloppy_function_map()) ||
1267           map.is_identical_to(
1268               isolate()->sloppy_function_without_prototype_map()) ||
1269           map.is_identical_to(
1270               isolate()->sloppy_function_with_readonly_prototype_map()) ||
1271           map.is_identical_to(isolate()->strict_function_map())));
1272   return NewFunction(map, info, context);
1273 }
1274
1275
1276 Handle<JSFunction> Factory::NewFunction(Handle<String> name) {
1277   return NewFunction(
1278       isolate()->sloppy_function_map(), name, MaybeHandle<Code>());
1279 }
1280
1281
1282 Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
1283                                                         Handle<Code> code,
1284                                                         bool is_strict) {
1285   Handle<Map> map = is_strict
1286                         ? isolate()->strict_function_without_prototype_map()
1287                         : isolate()->sloppy_function_without_prototype_map();
1288   return NewFunction(map, name, code);
1289 }
1290
1291
1292 Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1293                                         Handle<Object> prototype,
1294                                         bool read_only_prototype,
1295                                         bool is_strict) {
1296   // In strict mode, readonly strict map is only available during bootstrap
1297   DCHECK(!is_strict || !read_only_prototype ||
1298          isolate()->bootstrapper()->IsActive());
1299   Handle<Map> map =
1300       is_strict ? isolate()->strict_function_map()
1301                 : read_only_prototype
1302                       ? isolate()->sloppy_function_with_readonly_prototype_map()
1303                       : isolate()->sloppy_function_map();
1304   Handle<JSFunction> result = NewFunction(map, name, code);
1305   result->set_prototype_or_initial_map(*prototype);
1306   return result;
1307 }
1308
1309
1310 Handle<JSFunction> Factory::NewFunction(Handle<String> name, Handle<Code> code,
1311                                         Handle<Object> prototype,
1312                                         InstanceType type, int instance_size,
1313                                         bool read_only_prototype,
1314                                         bool install_constructor,
1315                                         bool is_strict) {
1316   // Allocate the function
1317   Handle<JSFunction> function =
1318       NewFunction(name, code, prototype, read_only_prototype, is_strict);
1319
1320   ElementsKind elements_kind =
1321       type == JS_ARRAY_TYPE ? FAST_SMI_ELEMENTS : FAST_HOLEY_SMI_ELEMENTS;
1322   Handle<Map> initial_map = NewMap(type, instance_size, elements_kind);
1323   if (!function->shared()->is_generator()) {
1324     if (prototype->IsTheHole()) {
1325       prototype = NewFunctionPrototype(function);
1326     } else if (install_constructor) {
1327       JSObject::AddProperty(Handle<JSObject>::cast(prototype),
1328                             constructor_string(), function, DONT_ENUM);
1329     }
1330   }
1331
1332   JSFunction::SetInitialMap(function, initial_map,
1333                             Handle<JSReceiver>::cast(prototype));
1334
1335   return function;
1336 }
1337
1338
1339 Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1340                                         Handle<Code> code,
1341                                         InstanceType type,
1342                                         int instance_size) {
1343   return NewFunction(name, code, the_hole_value(), type, instance_size);
1344 }
1345
1346
1347 Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
1348   // Make sure to use globals from the function's context, since the function
1349   // can be from a different context.
1350   Handle<Context> native_context(function->context()->native_context());
1351   Handle<Map> new_map;
1352   if (function->shared()->is_generator()) {
1353     // Generator prototypes can share maps since they don't have "constructor"
1354     // properties.
1355     new_map = handle(native_context->generator_object_prototype_map());
1356   } else {
1357     // Each function prototype gets a fresh map to avoid unwanted sharing of
1358     // maps between prototypes of different constructors.
1359     Handle<JSFunction> object_function(native_context->object_function());
1360     DCHECK(object_function->has_initial_map());
1361     new_map = handle(object_function->initial_map());
1362   }
1363
1364   DCHECK(!new_map->is_prototype_map());
1365   Handle<JSObject> prototype = NewJSObjectFromMap(new_map);
1366
1367   if (!function->shared()->is_generator()) {
1368     JSObject::AddProperty(prototype, constructor_string(), function, DONT_ENUM);
1369   }
1370
1371   return prototype;
1372 }
1373
1374
1375 Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
1376     Handle<SharedFunctionInfo> info,
1377     Handle<Context> context,
1378     PretenureFlag pretenure) {
1379   int map_index =
1380       Context::FunctionMapIndex(info->language_mode(), info->kind());
1381   Handle<Map> map(Map::cast(context->native_context()->get(map_index)));
1382   Handle<JSFunction> result = NewFunction(map, info, context, pretenure);
1383
1384   if (info->ic_age() != isolate()->heap()->global_ic_age()) {
1385     info->ResetForNewContext(isolate()->heap()->global_ic_age());
1386   }
1387
1388   if (FLAG_always_opt && info->allows_lazy_compilation()) {
1389     result->MarkForOptimization();
1390   }
1391
1392   CodeAndLiterals cached = info->SearchOptimizedCodeMap(
1393       context->native_context(), BailoutId::None());
1394   if (cached.code != nullptr) {
1395     // Caching of optimized code enabled and optimized code found.
1396     if (cached.literals != nullptr) result->set_literals(cached.literals);
1397     DCHECK(!cached.code->marked_for_deoptimization());
1398     DCHECK(result->shared()->is_compiled());
1399     result->ReplaceCode(cached.code);
1400   }
1401
1402   if (cached.literals == nullptr && !info->bound()) {
1403     int number_of_literals = info->num_literals();
1404     // TODO(mstarzinger): Consider sharing the newly created literals array.
1405     Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
1406     result->set_literals(*literals);
1407   }
1408
1409   return result;
1410 }
1411
1412
1413 Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1414   Handle<FixedArray> array = NewFixedArray(length, TENURED);
1415   array->set_map_no_write_barrier(*scope_info_map());
1416   Handle<ScopeInfo> scope_info = Handle<ScopeInfo>::cast(array);
1417   return scope_info;
1418 }
1419
1420
1421 Handle<JSObject> Factory::NewExternal(void* value) {
1422   Handle<Foreign> foreign = NewForeign(static_cast<Address>(value));
1423   Handle<JSObject> external = NewJSObjectFromMap(external_map());
1424   external->SetInternalField(0, *foreign);
1425   return external;
1426 }
1427
1428
1429 Handle<Code> Factory::NewCodeRaw(int object_size, bool immovable) {
1430   CALL_HEAP_FUNCTION(isolate(),
1431                      isolate()->heap()->AllocateCode(object_size, immovable),
1432                      Code);
1433 }
1434
1435
1436 Handle<Code> Factory::NewCode(const CodeDesc& desc,
1437                               Code::Flags flags,
1438                               Handle<Object> self_ref,
1439                               bool immovable,
1440                               bool crankshafted,
1441                               int prologue_offset,
1442                               bool is_debug) {
1443   Handle<ByteArray> reloc_info = NewByteArray(desc.reloc_size, TENURED);
1444
1445   // Compute size.
1446   int body_size = RoundUp(desc.instr_size, kObjectAlignment);
1447   int obj_size = Code::SizeFor(body_size);
1448
1449   Handle<Code> code = NewCodeRaw(obj_size, immovable);
1450   DCHECK(isolate()->code_range() == NULL || !isolate()->code_range()->valid() ||
1451          isolate()->code_range()->contains(code->address()) ||
1452          obj_size <= isolate()->heap()->code_space()->AreaSize());
1453
1454   // The code object has not been fully initialized yet.  We rely on the
1455   // fact that no allocation will happen from this point on.
1456   DisallowHeapAllocation no_gc;
1457   code->set_gc_metadata(Smi::FromInt(0));
1458   code->set_ic_age(isolate()->heap()->global_ic_age());
1459   code->set_instruction_size(desc.instr_size);
1460   code->set_relocation_info(*reloc_info);
1461   code->set_flags(flags);
1462   code->set_raw_kind_specific_flags1(0);
1463   code->set_raw_kind_specific_flags2(0);
1464   code->set_is_crankshafted(crankshafted);
1465   code->set_deoptimization_data(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1466   code->set_raw_type_feedback_info(Smi::FromInt(0));
1467   code->set_next_code_link(*undefined_value());
1468   code->set_handler_table(*empty_fixed_array(), SKIP_WRITE_BARRIER);
1469   code->set_prologue_offset(prologue_offset);
1470   if (FLAG_enable_embedded_constant_pool) {
1471     code->set_constant_pool_offset(desc.instr_size - desc.constant_pool_size);
1472   }
1473   if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1474     code->set_marked_for_deoptimization(false);
1475   }
1476
1477   if (is_debug) {
1478     DCHECK(code->kind() == Code::FUNCTION);
1479     code->set_has_debug_break_slots(true);
1480   }
1481
1482   // Allow self references to created code object by patching the handle to
1483   // point to the newly allocated Code object.
1484   if (!self_ref.is_null()) *(self_ref.location()) = *code;
1485
1486   // Migrate generated code.
1487   // The generated code can contain Object** values (typically from handles)
1488   // that are dereferenced during the copy to point directly to the actual heap
1489   // objects. These pointers can include references to the code object itself,
1490   // through the self_reference parameter.
1491   code->CopyFrom(desc);
1492
1493 #ifdef VERIFY_HEAP
1494   if (FLAG_verify_heap) code->ObjectVerify();
1495 #endif
1496   return code;
1497 }
1498
1499
1500 Handle<Code> Factory::CopyCode(Handle<Code> code) {
1501   CALL_HEAP_FUNCTION(isolate(),
1502                      isolate()->heap()->CopyCode(*code),
1503                      Code);
1504 }
1505
1506
1507 Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1508   CALL_HEAP_FUNCTION(isolate(),
1509                      isolate()->heap()->CopyCode(*code, reloc_info),
1510                      Code);
1511 }
1512
1513
1514 Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1515                                       PretenureFlag pretenure) {
1516   JSFunction::EnsureHasInitialMap(constructor);
1517   CALL_HEAP_FUNCTION(
1518       isolate(),
1519       isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1520 }
1521
1522
1523 Handle<JSObject> Factory::NewJSObjectWithMemento(
1524     Handle<JSFunction> constructor,
1525     Handle<AllocationSite> site) {
1526   JSFunction::EnsureHasInitialMap(constructor);
1527   CALL_HEAP_FUNCTION(
1528       isolate(),
1529       isolate()->heap()->AllocateJSObject(*constructor, NOT_TENURED, *site),
1530       JSObject);
1531 }
1532
1533
1534 Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1535                                       Handle<ScopeInfo> scope_info) {
1536   // Allocate a fresh map. Modules do not have a prototype.
1537   Handle<Map> map = NewMap(JS_MODULE_TYPE, JSModule::kSize);
1538   // Allocate the object based on the map.
1539   Handle<JSModule> module =
1540       Handle<JSModule>::cast(NewJSObjectFromMap(map, TENURED));
1541   module->set_context(*context);
1542   module->set_scope_info(*scope_info);
1543   return module;
1544 }
1545
1546
1547 Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1548   DCHECK(constructor->has_initial_map());
1549   Handle<Map> map(constructor->initial_map());
1550   DCHECK(map->is_dictionary_map());
1551
1552   // Make sure no field properties are described in the initial map.
1553   // This guarantees us that normalizing the properties does not
1554   // require us to change property values to PropertyCells.
1555   DCHECK(map->NextFreePropertyIndex() == 0);
1556
1557   // Make sure we don't have a ton of pre-allocated slots in the
1558   // global objects. They will be unused once we normalize the object.
1559   DCHECK(map->unused_property_fields() == 0);
1560   DCHECK(map->inobject_properties() == 0);
1561
1562   // Initial size of the backing store to avoid resize of the storage during
1563   // bootstrapping. The size differs between the JS global object ad the
1564   // builtins object.
1565   int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1566
1567   // Allocate a dictionary object for backing storage.
1568   int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1569   Handle<GlobalDictionary> dictionary =
1570       GlobalDictionary::New(isolate(), at_least_space_for);
1571
1572   // The global object might be created from an object template with accessors.
1573   // Fill these accessors into the dictionary.
1574   Handle<DescriptorArray> descs(map->instance_descriptors());
1575   for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1576     PropertyDetails details = descs->GetDetails(i);
1577     // Only accessors are expected.
1578     DCHECK_EQ(ACCESSOR_CONSTANT, details.type());
1579     PropertyDetails d(details.attributes(), ACCESSOR_CONSTANT, i + 1,
1580                       PropertyCellType::kMutable);
1581     Handle<Name> name(descs->GetKey(i));
1582     Handle<PropertyCell> cell = NewPropertyCell();
1583     cell->set_value(descs->GetCallbacksObject(i));
1584     // |dictionary| already contains enough space for all properties.
1585     USE(GlobalDictionary::Add(dictionary, name, cell, d));
1586   }
1587
1588   // Allocate the global object and initialize it with the backing store.
1589   Handle<GlobalObject> global = New<GlobalObject>(map, OLD_SPACE);
1590   isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1591
1592   // Create a new map for the global object.
1593   Handle<Map> new_map = Map::CopyDropDescriptors(map);
1594   new_map->set_dictionary_map(true);
1595
1596   // Set up the global object as a normalized object.
1597   global->set_map(*new_map);
1598   global->set_properties(*dictionary);
1599
1600   // Make sure result is a global object with properties in dictionary.
1601   DCHECK(global->IsGlobalObject() && !global->HasFastProperties());
1602   return global;
1603 }
1604
1605
1606 Handle<JSObject> Factory::NewJSObjectFromMap(
1607     Handle<Map> map,
1608     PretenureFlag pretenure,
1609     Handle<AllocationSite> allocation_site) {
1610   CALL_HEAP_FUNCTION(
1611       isolate(),
1612       isolate()->heap()->AllocateJSObjectFromMap(
1613           *map,
1614           pretenure,
1615           allocation_site.is_null() ? NULL : *allocation_site),
1616       JSObject);
1617 }
1618
1619
1620 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind,
1621                                     Strength strength,
1622                                     PretenureFlag pretenure) {
1623   Map* map = isolate()->get_initial_js_array_map(elements_kind, strength);
1624   if (map == nullptr) {
1625     DCHECK(strength == Strength::WEAK);
1626     Context* native_context = isolate()->context()->native_context();
1627     JSFunction* array_function = native_context->array_function();
1628     map = array_function->initial_map();
1629   }
1630   return Handle<JSArray>::cast(NewJSObjectFromMap(handle(map), pretenure));
1631 }
1632
1633
1634 Handle<JSArray> Factory::NewJSArray(ElementsKind elements_kind, int length,
1635                                     int capacity, Strength strength,
1636                                     ArrayStorageAllocationMode mode,
1637                                     PretenureFlag pretenure) {
1638   Handle<JSArray> array = NewJSArray(elements_kind, strength, pretenure);
1639   NewJSArrayStorage(array, length, capacity, mode);
1640   return array;
1641 }
1642
1643
1644 Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1645                                                 ElementsKind elements_kind,
1646                                                 int length, Strength strength,
1647                                                 PretenureFlag pretenure) {
1648   DCHECK(length <= elements->length());
1649   Handle<JSArray> array = NewJSArray(elements_kind, strength, pretenure);
1650
1651   array->set_elements(*elements);
1652   array->set_length(Smi::FromInt(length));
1653   JSObject::ValidateElements(array);
1654   return array;
1655 }
1656
1657
1658 void Factory::NewJSArrayStorage(Handle<JSArray> array,
1659                                 int length,
1660                                 int capacity,
1661                                 ArrayStorageAllocationMode mode) {
1662   DCHECK(capacity >= length);
1663
1664   if (capacity == 0) {
1665     array->set_length(Smi::FromInt(0));
1666     array->set_elements(*empty_fixed_array());
1667     return;
1668   }
1669
1670   HandleScope inner_scope(isolate());
1671   Handle<FixedArrayBase> elms;
1672   ElementsKind elements_kind = array->GetElementsKind();
1673   if (IsFastDoubleElementsKind(elements_kind)) {
1674     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1675       elms = NewFixedDoubleArray(capacity);
1676     } else {
1677       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1678       elms = NewFixedDoubleArrayWithHoles(capacity);
1679     }
1680   } else {
1681     DCHECK(IsFastSmiOrObjectElementsKind(elements_kind));
1682     if (mode == DONT_INITIALIZE_ARRAY_ELEMENTS) {
1683       elms = NewUninitializedFixedArray(capacity);
1684     } else {
1685       DCHECK(mode == INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE);
1686       elms = NewFixedArrayWithHoles(capacity);
1687     }
1688   }
1689
1690   array->set_elements(*elms);
1691   array->set_length(Smi::FromInt(length));
1692 }
1693
1694
1695 Handle<JSGeneratorObject> Factory::NewJSGeneratorObject(
1696     Handle<JSFunction> function) {
1697   DCHECK(function->shared()->is_generator());
1698   JSFunction::EnsureHasInitialMap(function);
1699   Handle<Map> map(function->initial_map());
1700   DCHECK(map->instance_type() == JS_GENERATOR_OBJECT_TYPE);
1701   CALL_HEAP_FUNCTION(
1702       isolate(),
1703       isolate()->heap()->AllocateJSObjectFromMap(*map),
1704       JSGeneratorObject);
1705 }
1706
1707
1708 Handle<JSArrayBuffer> Factory::NewJSArrayBuffer(SharedFlag shared) {
1709   Handle<JSFunction> array_buffer_fun(
1710       shared == SharedFlag::kShared
1711           ? isolate()->native_context()->shared_array_buffer_fun()
1712           : isolate()->native_context()->array_buffer_fun());
1713   CALL_HEAP_FUNCTION(
1714       isolate(),
1715       isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1716       JSArrayBuffer);
1717 }
1718
1719
1720 Handle<JSDataView> Factory::NewJSDataView() {
1721   Handle<JSFunction> data_view_fun(
1722       isolate()->native_context()->data_view_fun());
1723   CALL_HEAP_FUNCTION(
1724       isolate(),
1725       isolate()->heap()->AllocateJSObject(*data_view_fun),
1726       JSDataView);
1727 }
1728
1729
1730 Handle<JSMap> Factory::NewJSMap() {
1731   Handle<Map> map(isolate()->native_context()->js_map_map());
1732   Handle<JSMap> js_map = Handle<JSMap>::cast(NewJSObjectFromMap(map));
1733   Runtime::JSMapInitialize(isolate(), js_map);
1734   return js_map;
1735 }
1736
1737
1738 Handle<JSSet> Factory::NewJSSet() {
1739   Handle<Map> map(isolate()->native_context()->js_set_map());
1740   Handle<JSSet> js_set = Handle<JSSet>::cast(NewJSObjectFromMap(map));
1741   Runtime::JSSetInitialize(isolate(), js_set);
1742   return js_set;
1743 }
1744
1745
1746 Handle<JSMapIterator> Factory::NewJSMapIterator() {
1747   Handle<Map> map(isolate()->native_context()->map_iterator_map());
1748   CALL_HEAP_FUNCTION(isolate(),
1749                      isolate()->heap()->AllocateJSObjectFromMap(*map),
1750                      JSMapIterator);
1751 }
1752
1753
1754 Handle<JSSetIterator> Factory::NewJSSetIterator() {
1755   Handle<Map> map(isolate()->native_context()->set_iterator_map());
1756   CALL_HEAP_FUNCTION(isolate(),
1757                      isolate()->heap()->AllocateJSObjectFromMap(*map),
1758                      JSSetIterator);
1759 }
1760
1761
1762 namespace {
1763
1764 ElementsKind GetExternalArrayElementsKind(ExternalArrayType type) {
1765   switch (type) {
1766 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1767   case kExternal##Type##Array:                          \
1768     return EXTERNAL_##TYPE##_ELEMENTS;
1769     TYPED_ARRAYS(TYPED_ARRAY_CASE)
1770   }
1771   UNREACHABLE();
1772   return FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND;
1773 #undef TYPED_ARRAY_CASE
1774 }
1775
1776
1777 size_t GetExternalArrayElementSize(ExternalArrayType type) {
1778   switch (type) {
1779 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1780   case kExternal##Type##Array:                          \
1781     return size;
1782     TYPED_ARRAYS(TYPED_ARRAY_CASE)
1783     default:
1784       UNREACHABLE();
1785       return 0;
1786   }
1787 #undef TYPED_ARRAY_CASE
1788 }
1789
1790
1791 size_t GetFixedTypedArraysElementSize(ElementsKind kind) {
1792   switch (kind) {
1793 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1794   case TYPE##_ELEMENTS:                                 \
1795     return size;
1796     TYPED_ARRAYS(TYPED_ARRAY_CASE)
1797     default:
1798       UNREACHABLE();
1799       return 0;
1800   }
1801 #undef TYPED_ARRAY_CASE
1802 }
1803
1804
1805 ExternalArrayType GetArrayTypeFromElementsKind(ElementsKind kind) {
1806   switch (kind) {
1807 #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
1808   case TYPE##_ELEMENTS:                                 \
1809     return kExternal##Type##Array;
1810     TYPED_ARRAYS(TYPED_ARRAY_CASE)
1811     default:
1812       UNREACHABLE();
1813       return kExternalInt8Array;
1814   }
1815 #undef TYPED_ARRAY_CASE
1816 }
1817
1818
1819 JSFunction* GetTypedArrayFun(ExternalArrayType type, Isolate* isolate) {
1820   Context* native_context = isolate->context()->native_context();
1821   switch (type) {
1822 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size)                        \
1823     case kExternal##Type##Array:                                              \
1824       return native_context->type##_array_fun();
1825
1826     TYPED_ARRAYS(TYPED_ARRAY_FUN)
1827 #undef TYPED_ARRAY_FUN
1828
1829     default:
1830       UNREACHABLE();
1831       return NULL;
1832   }
1833 }
1834
1835
1836 JSFunction* GetTypedArrayFun(ElementsKind elements_kind, Isolate* isolate) {
1837   Context* native_context = isolate->context()->native_context();
1838   switch (elements_kind) {
1839 #define TYPED_ARRAY_FUN(Type, type, TYPE, ctype, size) \
1840   case TYPE##_ELEMENTS:                                \
1841     return native_context->type##_array_fun();
1842
1843     TYPED_ARRAYS(TYPED_ARRAY_FUN)
1844 #undef TYPED_ARRAY_FUN
1845
1846     default:
1847       UNREACHABLE();
1848       return NULL;
1849   }
1850 }
1851
1852
1853 void SetupArrayBufferView(i::Isolate* isolate,
1854                           i::Handle<i::JSArrayBufferView> obj,
1855                           i::Handle<i::JSArrayBuffer> buffer,
1856                           size_t byte_offset, size_t byte_length) {
1857   DCHECK(byte_offset + byte_length <=
1858          static_cast<size_t>(buffer->byte_length()->Number()));
1859
1860   obj->set_buffer(*buffer);
1861
1862   i::Handle<i::Object> byte_offset_object =
1863       isolate->factory()->NewNumberFromSize(byte_offset);
1864   obj->set_byte_offset(*byte_offset_object);
1865
1866   i::Handle<i::Object> byte_length_object =
1867       isolate->factory()->NewNumberFromSize(byte_length);
1868   obj->set_byte_length(*byte_length_object);
1869 }
1870
1871
1872 }  // namespace
1873
1874
1875 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1876   Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1877
1878   CALL_HEAP_FUNCTION(
1879       isolate(),
1880       isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1881       JSTypedArray);
1882 }
1883
1884
1885 Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind) {
1886   Handle<JSFunction> typed_array_fun_handle(
1887       GetTypedArrayFun(elements_kind, isolate()));
1888
1889   CALL_HEAP_FUNCTION(
1890       isolate(), isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1891       JSTypedArray);
1892 }
1893
1894
1895 Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type,
1896                                               Handle<JSArrayBuffer> buffer,
1897                                               size_t byte_offset,
1898                                               size_t length) {
1899   Handle<JSTypedArray> obj = NewJSTypedArray(type);
1900
1901   size_t element_size = GetExternalArrayElementSize(type);
1902   ElementsKind elements_kind = GetExternalArrayElementsKind(type);
1903
1904   CHECK(byte_offset % element_size == 0);
1905
1906   CHECK(length <= (std::numeric_limits<size_t>::max() / element_size));
1907   CHECK(length <= static_cast<size_t>(Smi::kMaxValue));
1908   size_t byte_length = length * element_size;
1909   SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1910
1911   Handle<Object> length_object = NewNumberFromSize(length);
1912   obj->set_length(*length_object);
1913
1914   Handle<ExternalArray> elements = NewExternalArray(
1915       static_cast<int>(length), type,
1916       static_cast<uint8_t*>(buffer->backing_store()) + byte_offset);
1917   Handle<Map> map = JSObject::GetElementsTransitionMap(obj, elements_kind);
1918   JSObject::SetMapAndElements(obj, map, elements);
1919   return obj;
1920 }
1921
1922
1923 Handle<JSTypedArray> Factory::NewJSTypedArray(ElementsKind elements_kind,
1924                                               size_t number_of_elements) {
1925   Handle<JSTypedArray> obj = NewJSTypedArray(elements_kind);
1926
1927   size_t element_size = GetFixedTypedArraysElementSize(elements_kind);
1928   ExternalArrayType array_type = GetArrayTypeFromElementsKind(elements_kind);
1929
1930   CHECK(number_of_elements <=
1931         (std::numeric_limits<size_t>::max() / element_size));
1932   CHECK(number_of_elements <= static_cast<size_t>(Smi::kMaxValue));
1933   size_t byte_length = number_of_elements * element_size;
1934
1935   obj->set_byte_offset(Smi::FromInt(0));
1936   i::Handle<i::Object> byte_length_object =
1937       isolate()->factory()->NewNumberFromSize(byte_length);
1938   obj->set_byte_length(*byte_length_object);
1939   Handle<Object> length_object = NewNumberFromSize(number_of_elements);
1940   obj->set_length(*length_object);
1941
1942   Handle<JSArrayBuffer> buffer = isolate()->factory()->NewJSArrayBuffer();
1943   Runtime::SetupArrayBuffer(isolate(), buffer, true, NULL, byte_length,
1944                             SharedFlag::kNotShared);
1945   obj->set_buffer(*buffer);
1946   Handle<FixedTypedArrayBase> elements =
1947       isolate()->factory()->NewFixedTypedArray(
1948           static_cast<int>(number_of_elements), array_type, true);
1949   obj->set_elements(*elements);
1950   return obj;
1951 }
1952
1953
1954 Handle<JSDataView> Factory::NewJSDataView(Handle<JSArrayBuffer> buffer,
1955                                           size_t byte_offset,
1956                                           size_t byte_length) {
1957   Handle<JSDataView> obj = NewJSDataView();
1958   SetupArrayBufferView(isolate(), obj, buffer, byte_offset, byte_length);
1959   return obj;
1960 }
1961
1962
1963 Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1964                                     Handle<Object> prototype) {
1965   // Allocate map.
1966   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1967   // maps. Will probably depend on the identity of the handler object, too.
1968   Handle<Map> map = NewMap(JS_PROXY_TYPE, JSProxy::kSize);
1969   Map::SetPrototype(map, prototype);
1970
1971   // Allocate the proxy object.
1972   Handle<JSProxy> result = New<JSProxy>(map, NEW_SPACE);
1973   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1974   result->set_handler(*handler);
1975   result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1976   return result;
1977 }
1978
1979
1980 Handle<JSProxy> Factory::NewJSFunctionProxy(Handle<Object> handler,
1981                                             Handle<Object> call_trap,
1982                                             Handle<Object> construct_trap,
1983                                             Handle<Object> prototype) {
1984   // Allocate map.
1985   // TODO(rossberg): Once we optimize proxies, think about a scheme to share
1986   // maps. Will probably depend on the identity of the handler object, too.
1987   Handle<Map> map = NewMap(JS_FUNCTION_PROXY_TYPE, JSFunctionProxy::kSize);
1988   Map::SetPrototype(map, prototype);
1989
1990   // Allocate the proxy object.
1991   Handle<JSFunctionProxy> result = New<JSFunctionProxy>(map, NEW_SPACE);
1992   result->InitializeBody(map->instance_size(), Smi::FromInt(0));
1993   result->set_handler(*handler);
1994   result->set_hash(*undefined_value(), SKIP_WRITE_BARRIER);
1995   result->set_call_trap(*call_trap);
1996   result->set_construct_trap(*construct_trap);
1997   return result;
1998 }
1999
2000
2001 void Factory::ReinitializeJSProxy(Handle<JSProxy> proxy, InstanceType type,
2002                                   int size) {
2003   DCHECK(type == JS_OBJECT_TYPE || type == JS_FUNCTION_TYPE);
2004
2005   Handle<Map> proxy_map(proxy->map());
2006   Handle<Map> map = Map::FixProxy(proxy_map, type, size);
2007
2008   // Check that the receiver has at least the size of the fresh object.
2009   int size_difference = proxy_map->instance_size() - map->instance_size();
2010   DCHECK(size_difference >= 0);
2011
2012   // Allocate the backing storage for the properties.
2013   Handle<FixedArray> properties = empty_fixed_array();
2014
2015   Heap* heap = isolate()->heap();
2016   MaybeHandle<SharedFunctionInfo> shared;
2017   if (type == JS_FUNCTION_TYPE) {
2018     OneByteStringKey key(STATIC_CHAR_VECTOR("<freezing call trap>"),
2019                          heap->HashSeed());
2020     Handle<String> name = InternalizeStringWithKey(&key);
2021     shared = NewSharedFunctionInfo(name, MaybeHandle<Code>());
2022   }
2023
2024   // In order to keep heap in consistent state there must be no allocations
2025   // before object re-initialization is finished and filler object is installed.
2026   DisallowHeapAllocation no_allocation;
2027
2028   // Put in filler if the new object is smaller than the old.
2029   if (size_difference > 0) {
2030     Address address = proxy->address();
2031     heap->CreateFillerObjectAt(address + map->instance_size(), size_difference);
2032     heap->AdjustLiveBytes(address, -size_difference,
2033                           Heap::CONCURRENT_TO_SWEEPER);
2034   }
2035
2036   // Reset the map for the object.
2037   proxy->synchronized_set_map(*map);
2038   Handle<JSObject> jsobj = Handle<JSObject>::cast(proxy);
2039
2040   // Reinitialize the object from the constructor map.
2041   heap->InitializeJSObjectFromMap(*jsobj, *properties, *map);
2042
2043   // The current native context is used to set up certain bits.
2044   // TODO(adamk): Using the current context seems wrong, it should be whatever
2045   // context the JSProxy originated in. But that context isn't stored anywhere.
2046   Handle<Context> context(isolate()->native_context());
2047
2048   // Functions require some minimal initialization.
2049   if (type == JS_FUNCTION_TYPE) {
2050     map->set_function_with_prototype(true);
2051     Handle<JSFunction> js_function = Handle<JSFunction>::cast(proxy);
2052     InitializeFunction(js_function, shared.ToHandleChecked(), context);
2053   } else {
2054     // Provide JSObjects with a constructor.
2055     map->SetConstructor(context->object_function());
2056   }
2057 }
2058
2059
2060 Handle<JSGlobalProxy> Factory::NewUninitializedJSGlobalProxy() {
2061   // Create an empty shell of a JSGlobalProxy that needs to be reinitialized
2062   // via ReinitializeJSGlobalProxy later.
2063   Handle<Map> map = NewMap(JS_GLOBAL_PROXY_TYPE, JSGlobalProxy::kSize);
2064   // Maintain invariant expected from any JSGlobalProxy.
2065   map->set_is_access_check_needed(true);
2066   CALL_HEAP_FUNCTION(
2067       isolate(), isolate()->heap()->AllocateJSObjectFromMap(*map, NOT_TENURED),
2068       JSGlobalProxy);
2069 }
2070
2071
2072 void Factory::ReinitializeJSGlobalProxy(Handle<JSGlobalProxy> object,
2073                                         Handle<JSFunction> constructor) {
2074   DCHECK(constructor->has_initial_map());
2075   Handle<Map> map(constructor->initial_map(), isolate());
2076
2077   // The proxy's hash should be retained across reinitialization.
2078   Handle<Object> hash(object->hash(), isolate());
2079
2080   // Check that the already allocated object has the same size and type as
2081   // objects allocated using the constructor.
2082   DCHECK(map->instance_size() == object->map()->instance_size());
2083   DCHECK(map->instance_type() == object->map()->instance_type());
2084
2085   // Allocate the backing storage for the properties.
2086   Handle<FixedArray> properties = empty_fixed_array();
2087
2088   // In order to keep heap in consistent state there must be no allocations
2089   // before object re-initialization is finished.
2090   DisallowHeapAllocation no_allocation;
2091
2092   // Reset the map for the object.
2093   object->synchronized_set_map(*map);
2094
2095   Heap* heap = isolate()->heap();
2096   // Reinitialize the object from the constructor map.
2097   heap->InitializeJSObjectFromMap(*object, *properties, *map);
2098
2099   // Restore the saved hash.
2100   object->set_hash(*hash);
2101 }
2102
2103
2104 void Factory::BecomeJSObject(Handle<JSProxy> proxy) {
2105   ReinitializeJSProxy(proxy, JS_OBJECT_TYPE, JSObject::kHeaderSize);
2106 }
2107
2108
2109 void Factory::BecomeJSFunction(Handle<JSProxy> proxy) {
2110   ReinitializeJSProxy(proxy, JS_FUNCTION_TYPE, JSFunction::kSize);
2111 }
2112
2113
2114 template Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(
2115     const ZoneFeedbackVectorSpec* spec);
2116 template Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(
2117     const FeedbackVectorSpec* spec);
2118
2119 template <typename Spec>
2120 Handle<TypeFeedbackVector> Factory::NewTypeFeedbackVector(const Spec* spec) {
2121   return TypeFeedbackVector::Allocate<Spec>(isolate(), spec);
2122 }
2123
2124
2125 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2126     Handle<String> name, int number_of_literals, FunctionKind kind,
2127     Handle<Code> code, Handle<ScopeInfo> scope_info,
2128     Handle<TypeFeedbackVector> feedback_vector) {
2129   DCHECK(IsValidFunctionKind(kind));
2130   Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name, code);
2131   shared->set_scope_info(*scope_info);
2132   shared->set_feedback_vector(*feedback_vector);
2133   shared->set_kind(kind);
2134   shared->set_num_literals(number_of_literals);
2135   if (IsGeneratorFunction(kind)) {
2136     shared->set_instance_class_name(isolate()->heap()->Generator_string());
2137     shared->DisableOptimization(kGenerator);
2138   }
2139   return shared;
2140 }
2141
2142
2143 Handle<JSMessageObject> Factory::NewJSMessageObject(
2144     MessageTemplate::Template message, Handle<Object> argument,
2145     int start_position, int end_position, Handle<Object> script,
2146     Handle<Object> stack_frames) {
2147   Handle<Map> map = message_object_map();
2148   Handle<JSMessageObject> message_obj = New<JSMessageObject>(map, NEW_SPACE);
2149   message_obj->set_properties(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2150   message_obj->initialize_elements();
2151   message_obj->set_elements(*empty_fixed_array(), SKIP_WRITE_BARRIER);
2152   message_obj->set_type(message);
2153   message_obj->set_argument(*argument);
2154   message_obj->set_start_position(start_position);
2155   message_obj->set_end_position(end_position);
2156   message_obj->set_script(*script);
2157   message_obj->set_stack_frames(*stack_frames);
2158   return message_obj;
2159 }
2160
2161
2162 Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
2163     Handle<String> name,
2164     MaybeHandle<Code> maybe_code) {
2165   Handle<Map> map = shared_function_info_map();
2166   Handle<SharedFunctionInfo> share = New<SharedFunctionInfo>(map, OLD_SPACE);
2167
2168   // Set pointer fields.
2169   share->set_name(*name);
2170   Handle<Code> code;
2171   if (!maybe_code.ToHandle(&code)) {
2172     code = handle(isolate()->builtins()->builtin(Builtins::kIllegal));
2173   }
2174   share->set_code(*code);
2175   share->set_optimized_code_map(Smi::FromInt(0));
2176   share->set_scope_info(ScopeInfo::Empty(isolate()));
2177   Code* construct_stub =
2178       isolate()->builtins()->builtin(Builtins::kJSConstructStubGeneric);
2179   share->set_construct_stub(construct_stub);
2180   share->set_instance_class_name(*Object_string());
2181   share->set_function_data(*undefined_value(), SKIP_WRITE_BARRIER);
2182   share->set_script(*undefined_value(), SKIP_WRITE_BARRIER);
2183   share->set_debug_info(*undefined_value(), SKIP_WRITE_BARRIER);
2184   share->set_inferred_name(*empty_string(), SKIP_WRITE_BARRIER);
2185   FeedbackVectorSpec empty_spec(0);
2186   Handle<TypeFeedbackVector> feedback_vector =
2187       NewTypeFeedbackVector(&empty_spec);
2188   share->set_feedback_vector(*feedback_vector, SKIP_WRITE_BARRIER);
2189 #if TRACE_MAPS
2190   share->set_unique_id(isolate()->GetNextUniqueSharedFunctionInfoId());
2191 #endif
2192   share->set_profiler_ticks(0);
2193   share->set_ast_node_count(0);
2194   share->set_counters(0);
2195
2196   // Set integer fields (smi or int, depending on the architecture).
2197   share->set_length(0);
2198   share->set_internal_formal_parameter_count(0);
2199   share->set_expected_nof_properties(0);
2200   share->set_num_literals(0);
2201   share->set_start_position_and_type(0);
2202   share->set_end_position(0);
2203   share->set_function_token_position(0);
2204   // All compiler hints default to false or 0.
2205   share->set_compiler_hints(0);
2206   share->set_opt_count_and_bailout_reason(0);
2207
2208   return share;
2209 }
2210
2211
2212 static inline int NumberCacheHash(Handle<FixedArray> cache,
2213                                   Handle<Object> number) {
2214   int mask = (cache->length() >> 1) - 1;
2215   if (number->IsSmi()) {
2216     return Handle<Smi>::cast(number)->value() & mask;
2217   } else {
2218     DoubleRepresentation rep(number->Number());
2219     return
2220         (static_cast<int>(rep.bits) ^ static_cast<int>(rep.bits >> 32)) & mask;
2221   }
2222 }
2223
2224
2225 Handle<Object> Factory::GetNumberStringCache(Handle<Object> number) {
2226   DisallowHeapAllocation no_gc;
2227   int hash = NumberCacheHash(number_string_cache(), number);
2228   Object* key = number_string_cache()->get(hash * 2);
2229   if (key == *number || (key->IsHeapNumber() && number->IsHeapNumber() &&
2230                          key->Number() == number->Number())) {
2231     return Handle<String>(
2232         String::cast(number_string_cache()->get(hash * 2 + 1)), isolate());
2233   }
2234   return undefined_value();
2235 }
2236
2237
2238 void Factory::SetNumberStringCache(Handle<Object> number,
2239                                    Handle<String> string) {
2240   int hash = NumberCacheHash(number_string_cache(), number);
2241   if (number_string_cache()->get(hash * 2) != *undefined_value()) {
2242     int full_size = isolate()->heap()->FullSizeNumberStringCacheLength();
2243     if (number_string_cache()->length() != full_size) {
2244       Handle<FixedArray> new_cache = NewFixedArray(full_size, TENURED);
2245       isolate()->heap()->set_number_string_cache(*new_cache);
2246       return;
2247     }
2248   }
2249   number_string_cache()->set(hash * 2, *number);
2250   number_string_cache()->set(hash * 2 + 1, *string);
2251 }
2252
2253
2254 Handle<String> Factory::NumberToString(Handle<Object> number,
2255                                        bool check_number_string_cache) {
2256   isolate()->counters()->number_to_string_runtime()->Increment();
2257   if (check_number_string_cache) {
2258     Handle<Object> cached = GetNumberStringCache(number);
2259     if (!cached->IsUndefined()) return Handle<String>::cast(cached);
2260   }
2261
2262   char arr[100];
2263   Vector<char> buffer(arr, arraysize(arr));
2264   const char* str;
2265   if (number->IsSmi()) {
2266     int num = Handle<Smi>::cast(number)->value();
2267     str = IntToCString(num, buffer);
2268   } else {
2269     double num = Handle<HeapNumber>::cast(number)->value();
2270     str = DoubleToCString(num, buffer);
2271   }
2272
2273   // We tenure the allocated string since it is referenced from the
2274   // number-string cache which lives in the old space.
2275   Handle<String> js_string = NewStringFromAsciiChecked(str, TENURED);
2276   SetNumberStringCache(number, js_string);
2277   return js_string;
2278 }
2279
2280
2281 Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
2282   // Allocate initial fixed array for active break points before allocating the
2283   // debug info object to avoid allocation while setting up the debug info
2284   // object.
2285   Handle<FixedArray> break_points(
2286       NewFixedArray(DebugInfo::kEstimatedNofBreakPointsInFunction));
2287
2288   // Create and set up the debug info object. Debug info contains function, a
2289   // copy of the original code, the executing code and initial fixed array for
2290   // active break points.
2291   Handle<DebugInfo> debug_info =
2292       Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
2293   debug_info->set_shared(*shared);
2294   debug_info->set_code(shared->code());
2295   debug_info->set_break_points(*break_points);
2296
2297   // Link debug info to function.
2298   shared->set_debug_info(*debug_info);
2299
2300   return debug_info;
2301 }
2302
2303
2304 Handle<JSObject> Factory::NewArgumentsObject(Handle<JSFunction> callee,
2305                                              int length) {
2306   bool strict_mode_callee = is_strict(callee->shared()->language_mode()) ||
2307                             !callee->is_simple_parameter_list();
2308   Handle<Map> map = strict_mode_callee ? isolate()->strict_arguments_map()
2309                                        : isolate()->sloppy_arguments_map();
2310
2311   AllocationSiteUsageContext context(isolate(), Handle<AllocationSite>(),
2312                                      false);
2313   DCHECK(!isolate()->has_pending_exception());
2314   Handle<JSObject> result = NewJSObjectFromMap(map);
2315   Handle<Smi> value(Smi::FromInt(length), isolate());
2316   Object::SetProperty(result, length_string(), value, STRICT).Assert();
2317   if (!strict_mode_callee) {
2318     Object::SetProperty(result, callee_string(), callee, STRICT).Assert();
2319   }
2320   return result;
2321 }
2322
2323
2324 Handle<JSWeakMap> Factory::NewJSWeakMap() {
2325   // TODO(adamk): Currently the map is only created three times per
2326   // isolate. If it's created more often, the map should be moved into the
2327   // strong root list.
2328   Handle<Map> map = NewMap(JS_WEAK_MAP_TYPE, JSWeakMap::kSize);
2329   return Handle<JSWeakMap>::cast(NewJSObjectFromMap(map));
2330 }
2331
2332
2333 Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
2334                                                int number_of_properties,
2335                                                bool is_strong,
2336                                                bool* is_result_from_cache) {
2337   const int kMapCacheSize = 128;
2338
2339   // We do not cache maps for too many properties or when running builtin code.
2340   if (number_of_properties > kMapCacheSize ||
2341       isolate()->bootstrapper()->IsActive()) {
2342     *is_result_from_cache = false;
2343     Handle<Map> map = Map::Create(isolate(), number_of_properties);
2344     if (is_strong) map->set_is_strong();
2345     return map;
2346   }
2347   *is_result_from_cache = true;
2348   if (number_of_properties == 0) {
2349     // Reuse the initial map of the Object function if the literal has no
2350     // predeclared properties, or the strong map if strong.
2351     return handle(is_strong
2352                       ? context->js_object_strong_map()
2353                       : context->object_function()->initial_map(), isolate());
2354   }
2355
2356   int cache_index = number_of_properties - 1;
2357   Handle<Object> maybe_cache(is_strong ? context->strong_map_cache()
2358                                        : context->map_cache(), isolate());
2359   if (maybe_cache->IsUndefined()) {
2360     // Allocate the new map cache for the native context.
2361     maybe_cache = NewFixedArray(kMapCacheSize, TENURED);
2362     if (is_strong) {
2363       context->set_strong_map_cache(*maybe_cache);
2364     } else {
2365       context->set_map_cache(*maybe_cache);
2366     }
2367   } else {
2368     // Check to see whether there is a matching element in the cache.
2369     Handle<FixedArray> cache = Handle<FixedArray>::cast(maybe_cache);
2370     Object* result = cache->get(cache_index);
2371     if (result->IsWeakCell()) {
2372       WeakCell* cell = WeakCell::cast(result);
2373       if (!cell->cleared()) {
2374         return handle(Map::cast(cell->value()), isolate());
2375       }
2376     }
2377   }
2378   // Create a new map and add it to the cache.
2379   Handle<FixedArray> cache = Handle<FixedArray>::cast(maybe_cache);
2380   Handle<Map> map = Map::Create(isolate(), number_of_properties);
2381   if (is_strong) map->set_is_strong();
2382   Handle<WeakCell> cell = NewWeakCell(map);
2383   cache->set(cache_index, *cell);
2384   return map;
2385 }
2386
2387
2388 void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
2389                                 JSRegExp::Type type,
2390                                 Handle<String> source,
2391                                 JSRegExp::Flags flags,
2392                                 Handle<Object> data) {
2393   Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
2394
2395   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2396   store->set(JSRegExp::kSourceIndex, *source);
2397   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2398   store->set(JSRegExp::kAtomPatternIndex, *data);
2399   regexp->set_data(*store);
2400 }
2401
2402
2403 void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
2404                                     JSRegExp::Type type,
2405                                     Handle<String> source,
2406                                     JSRegExp::Flags flags,
2407                                     int capture_count) {
2408   Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
2409   Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
2410   store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
2411   store->set(JSRegExp::kSourceIndex, *source);
2412   store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
2413   store->set(JSRegExp::kIrregexpLatin1CodeIndex, uninitialized);
2414   store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
2415   store->set(JSRegExp::kIrregexpLatin1CodeSavedIndex, uninitialized);
2416   store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
2417   store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
2418   store->set(JSRegExp::kIrregexpCaptureCountIndex,
2419              Smi::FromInt(capture_count));
2420   regexp->set_data(*store);
2421 }
2422
2423
2424 Handle<Object> Factory::GlobalConstantFor(Handle<Name> name) {
2425   if (Name::Equals(name, undefined_string())) return undefined_value();
2426   if (Name::Equals(name, nan_string())) return nan_value();
2427   if (Name::Equals(name, infinity_string())) return infinity_value();
2428   return Handle<Object>::null();
2429 }
2430
2431
2432 Handle<Object> Factory::ToBoolean(bool value) {
2433   return value ? true_value() : false_value();
2434 }
2435
2436
2437 }  // namespace internal
2438 }  // namespace v8