The data contained in this repository can be downloaded to your computer using one of several clients.
Please see the documentation of your version control software client for more information.

Please select the desired protocol below to get the URL.

This URL has Read-Only access.

Statistics
| Branch: | Revision:

main_repo / deps / v8 / src / factory.cc @ f230a1cf

History | View | Annotate | Download (57.8 KB)

1
// Copyright 2013 the V8 project authors. All rights reserved.
2
// Redistribution and use in source and binary forms, with or without
3
// modification, are permitted provided that the following conditions are
4
// met:
5
//
6
//     * Redistributions of source code must retain the above copyright
7
//       notice, this list of conditions and the following disclaimer.
8
//     * Redistributions in binary form must reproduce the above
9
//       copyright notice, this list of conditions and the following
10
//       disclaimer in the documentation and/or other materials provided
11
//       with the distribution.
12
//     * Neither the name of Google Inc. nor the names of its
13
//       contributors may be used to endorse or promote products derived
14
//       from this software without specific prior written permission.
15
//
16
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27

    
28
#include "v8.h"
29

    
30
#include "api.h"
31
#include "debug.h"
32
#include "execution.h"
33
#include "factory.h"
34
#include "isolate-inl.h"
35
#include "macro-assembler.h"
36
#include "objects.h"
37
#include "objects-visiting.h"
38
#include "platform.h"
39
#include "scopeinfo.h"
40

    
41
namespace v8 {
42
namespace internal {
43

    
44

    
45
Handle<Box> Factory::NewBox(Handle<Object> value, PretenureFlag pretenure) {
46
  CALL_HEAP_FUNCTION(
47
      isolate(),
48
      isolate()->heap()->AllocateBox(*value, pretenure),
49
      Box);
50
}
51

    
52

    
53
Handle<FixedArray> Factory::NewFixedArray(int size, PretenureFlag pretenure) {
54
  ASSERT(0 <= size);
55
  CALL_HEAP_FUNCTION(
56
      isolate(),
57
      isolate()->heap()->AllocateFixedArray(size, pretenure),
58
      FixedArray);
59
}
60

    
61

    
62
Handle<FixedArray> Factory::NewFixedArrayWithHoles(int size,
63
                                                   PretenureFlag pretenure) {
64
  ASSERT(0 <= size);
65
  CALL_HEAP_FUNCTION(
66
      isolate(),
67
      isolate()->heap()->AllocateFixedArrayWithHoles(size, pretenure),
68
      FixedArray);
69
}
70

    
71

    
72
Handle<FixedDoubleArray> Factory::NewFixedDoubleArray(int size,
73
                                                      PretenureFlag pretenure) {
74
  ASSERT(0 <= size);
75
  CALL_HEAP_FUNCTION(
76
      isolate(),
77
      isolate()->heap()->AllocateUninitializedFixedDoubleArray(size, pretenure),
78
      FixedDoubleArray);
79
}
80

    
81

    
82
Handle<ConstantPoolArray> Factory::NewConstantPoolArray(
83
    int number_of_int64_entries,
84
    int number_of_ptr_entries,
85
    int number_of_int32_entries) {
86
  ASSERT(number_of_int64_entries > 0 || number_of_ptr_entries > 0 ||
87
         number_of_int32_entries > 0);
88
  CALL_HEAP_FUNCTION(
89
      isolate(),
90
      isolate()->heap()->AllocateConstantPoolArray(number_of_int64_entries,
91
                                                   number_of_ptr_entries,
92
                                                   number_of_int32_entries),
93
      ConstantPoolArray);
94
}
95

    
96

    
97
Handle<NameDictionary> Factory::NewNameDictionary(int at_least_space_for) {
98
  ASSERT(0 <= at_least_space_for);
99
  CALL_HEAP_FUNCTION(isolate(),
100
                     NameDictionary::Allocate(isolate()->heap(),
101
                                              at_least_space_for),
102
                     NameDictionary);
103
}
104

    
105

    
106
Handle<SeededNumberDictionary> Factory::NewSeededNumberDictionary(
107
    int at_least_space_for) {
108
  ASSERT(0 <= at_least_space_for);
109
  CALL_HEAP_FUNCTION(isolate(),
110
                     SeededNumberDictionary::Allocate(isolate()->heap(),
111
                                                      at_least_space_for),
112
                     SeededNumberDictionary);
113
}
114

    
115

    
116
Handle<UnseededNumberDictionary> Factory::NewUnseededNumberDictionary(
117
    int at_least_space_for) {
118
  ASSERT(0 <= at_least_space_for);
119
  CALL_HEAP_FUNCTION(isolate(),
120
                     UnseededNumberDictionary::Allocate(isolate()->heap(),
121
                                                        at_least_space_for),
122
                     UnseededNumberDictionary);
123
}
124

    
125

    
126
Handle<ObjectHashSet> Factory::NewObjectHashSet(int at_least_space_for) {
127
  ASSERT(0 <= at_least_space_for);
128
  CALL_HEAP_FUNCTION(isolate(),
129
                     ObjectHashSet::Allocate(isolate()->heap(),
130
                                             at_least_space_for),
131
                     ObjectHashSet);
132
}
133

    
134

    
135
Handle<ObjectHashTable> Factory::NewObjectHashTable(int at_least_space_for) {
136
  ASSERT(0 <= at_least_space_for);
137
  CALL_HEAP_FUNCTION(isolate(),
138
                     ObjectHashTable::Allocate(isolate()->heap(),
139
                                               at_least_space_for),
140
                     ObjectHashTable);
141
}
142

    
143

    
144
Handle<WeakHashTable> Factory::NewWeakHashTable(int at_least_space_for) {
145
  ASSERT(0 <= at_least_space_for);
146
  CALL_HEAP_FUNCTION(
147
      isolate(),
148
      WeakHashTable::Allocate(isolate()->heap(),
149
                              at_least_space_for,
150
                              WeakHashTable::USE_DEFAULT_MINIMUM_CAPACITY,
151
                              TENURED),
152
      WeakHashTable);
153
}
154

    
155

    
156
Handle<DescriptorArray> Factory::NewDescriptorArray(int number_of_descriptors,
157
                                                    int slack) {
158
  ASSERT(0 <= number_of_descriptors);
159
  CALL_HEAP_FUNCTION(isolate(),
160
                     DescriptorArray::Allocate(
161
                         isolate(), number_of_descriptors, slack),
162
                     DescriptorArray);
163
}
164

    
165

    
166
Handle<DeoptimizationInputData> Factory::NewDeoptimizationInputData(
167
    int deopt_entry_count,
168
    PretenureFlag pretenure) {
169
  ASSERT(deopt_entry_count > 0);
170
  CALL_HEAP_FUNCTION(isolate(),
171
                     DeoptimizationInputData::Allocate(isolate(),
172
                                                       deopt_entry_count,
173
                                                       pretenure),
174
                     DeoptimizationInputData);
175
}
176

    
177

    
178
Handle<DeoptimizationOutputData> Factory::NewDeoptimizationOutputData(
179
    int deopt_entry_count,
180
    PretenureFlag pretenure) {
181
  ASSERT(deopt_entry_count > 0);
182
  CALL_HEAP_FUNCTION(isolate(),
183
                     DeoptimizationOutputData::Allocate(isolate(),
184
                                                        deopt_entry_count,
185
                                                        pretenure),
186
                     DeoptimizationOutputData);
187
}
188

    
189

    
190
Handle<AccessorPair> Factory::NewAccessorPair() {
191
  CALL_HEAP_FUNCTION(isolate(),
192
                     isolate()->heap()->AllocateAccessorPair(),
193
                     AccessorPair);
194
}
195

    
196

    
197
Handle<TypeFeedbackInfo> Factory::NewTypeFeedbackInfo() {
198
  CALL_HEAP_FUNCTION(isolate(),
199
                     isolate()->heap()->AllocateTypeFeedbackInfo(),
200
                     TypeFeedbackInfo);
201
}
202

    
203

    
204
// Internalized strings are created in the old generation (data space).
205
Handle<String> Factory::InternalizeUtf8String(Vector<const char> string) {
206
  CALL_HEAP_FUNCTION(isolate(),
207
                     isolate()->heap()->InternalizeUtf8String(string),
208
                     String);
209
}
210

    
211

    
212
// Internalized strings are created in the old generation (data space).
213
Handle<String> Factory::InternalizeString(Handle<String> string) {
214
  CALL_HEAP_FUNCTION(isolate(),
215
                     isolate()->heap()->InternalizeString(*string),
216
                     String);
217
}
218

    
219

    
220
Handle<String> Factory::InternalizeOneByteString(Vector<const uint8_t> string) {
221
  CALL_HEAP_FUNCTION(isolate(),
222
                     isolate()->heap()->InternalizeOneByteString(string),
223
                     String);
224
}
225

    
226

    
227
Handle<String> Factory::InternalizeOneByteString(
228
    Handle<SeqOneByteString> string, int from, int length) {
229
  CALL_HEAP_FUNCTION(isolate(),
230
                     isolate()->heap()->InternalizeOneByteString(
231
                         string, from, length),
232
                     String);
233
}
234

    
235

    
236
Handle<String> Factory::InternalizeTwoByteString(Vector<const uc16> string) {
237
  CALL_HEAP_FUNCTION(isolate(),
238
                     isolate()->heap()->InternalizeTwoByteString(string),
239
                     String);
240
}
241

    
242

    
243
Handle<String> Factory::NewStringFromOneByte(Vector<const uint8_t> string,
244
                                             PretenureFlag pretenure) {
245
  CALL_HEAP_FUNCTION(
246
      isolate(),
247
      isolate()->heap()->AllocateStringFromOneByte(string, pretenure),
248
      String);
249
}
250

    
251
Handle<String> Factory::NewStringFromUtf8(Vector<const char> string,
252
                                          PretenureFlag pretenure) {
253
  CALL_HEAP_FUNCTION(
254
      isolate(),
255
      isolate()->heap()->AllocateStringFromUtf8(string, pretenure),
256
      String);
257
}
258

    
259

    
260
Handle<String> Factory::NewStringFromTwoByte(Vector<const uc16> string,
261
                                             PretenureFlag pretenure) {
262
  CALL_HEAP_FUNCTION(
263
      isolate(),
264
      isolate()->heap()->AllocateStringFromTwoByte(string, pretenure),
265
      String);
266
}
267

    
268

    
269
Handle<SeqOneByteString> Factory::NewRawOneByteString(int length,
270
                                                  PretenureFlag pretenure) {
271
  CALL_HEAP_FUNCTION(
272
      isolate(),
273
      isolate()->heap()->AllocateRawOneByteString(length, pretenure),
274
      SeqOneByteString);
275
}
276

    
277

    
278
Handle<SeqTwoByteString> Factory::NewRawTwoByteString(int length,
279
                                                      PretenureFlag pretenure) {
280
  CALL_HEAP_FUNCTION(
281
      isolate(),
282
      isolate()->heap()->AllocateRawTwoByteString(length, pretenure),
283
      SeqTwoByteString);
284
}
285

    
286

    
287
Handle<String> Factory::NewConsString(Handle<String> first,
288
                                      Handle<String> second) {
289
  CALL_HEAP_FUNCTION(isolate(),
290
                     isolate()->heap()->AllocateConsString(*first, *second),
291
                     String);
292
}
293

    
294

    
295
template<typename SinkChar, typename StringType>
296
Handle<String> ConcatStringContent(Handle<StringType> result,
297
                                   Handle<String> first,
298
                                   Handle<String> second) {
299
  DisallowHeapAllocation pointer_stays_valid;
300
  SinkChar* sink = result->GetChars();
301
  String::WriteToFlat(*first, sink, 0, first->length());
302
  String::WriteToFlat(*second, sink + first->length(), 0, second->length());
303
  return result;
304
}
305

    
306

    
307
Handle<String> Factory::NewFlatConcatString(Handle<String> first,
308
                                            Handle<String> second) {
309
  int total_length = first->length() + second->length();
310
  if (first->IsOneByteRepresentationUnderneath() &&
311
      second->IsOneByteRepresentationUnderneath()) {
312
    return ConcatStringContent<uint8_t>(
313
        NewRawOneByteString(total_length), first, second);
314
  } else {
315
    return ConcatStringContent<uc16>(
316
        NewRawTwoByteString(total_length), first, second);
317
  }
318
}
319

    
320

    
321
Handle<String> Factory::NewSubString(Handle<String> str,
322
                                     int begin,
323
                                     int end) {
324
  CALL_HEAP_FUNCTION(isolate(),
325
                     str->SubString(begin, end),
326
                     String);
327
}
328

    
329

    
330
Handle<String> Factory::NewProperSubString(Handle<String> str,
331
                                           int begin,
332
                                           int end) {
333
  ASSERT(begin > 0 || end < str->length());
334
  CALL_HEAP_FUNCTION(isolate(),
335
                     isolate()->heap()->AllocateSubString(*str, begin, end),
336
                     String);
337
}
338

    
339

    
340
Handle<String> Factory::NewExternalStringFromAscii(
341
    const ExternalAsciiString::Resource* resource) {
342
  CALL_HEAP_FUNCTION(
343
      isolate(),
344
      isolate()->heap()->AllocateExternalStringFromAscii(resource),
345
      String);
346
}
347

    
348

    
349
Handle<String> Factory::NewExternalStringFromTwoByte(
350
    const ExternalTwoByteString::Resource* resource) {
351
  CALL_HEAP_FUNCTION(
352
      isolate(),
353
      isolate()->heap()->AllocateExternalStringFromTwoByte(resource),
354
      String);
355
}
356

    
357

    
358
Handle<Symbol> Factory::NewSymbol() {
359
  CALL_HEAP_FUNCTION(
360
      isolate(),
361
      isolate()->heap()->AllocateSymbol(),
362
      Symbol);
363
}
364

    
365

    
366
Handle<Context> Factory::NewNativeContext() {
367
  CALL_HEAP_FUNCTION(
368
      isolate(),
369
      isolate()->heap()->AllocateNativeContext(),
370
      Context);
371
}
372

    
373

    
374
Handle<Context> Factory::NewGlobalContext(Handle<JSFunction> function,
375
                                          Handle<ScopeInfo> scope_info) {
376
  CALL_HEAP_FUNCTION(
377
      isolate(),
378
      isolate()->heap()->AllocateGlobalContext(*function, *scope_info),
379
      Context);
380
}
381

    
382

    
383
Handle<Context> Factory::NewModuleContext(Handle<ScopeInfo> scope_info) {
384
  CALL_HEAP_FUNCTION(
385
      isolate(),
386
      isolate()->heap()->AllocateModuleContext(*scope_info),
387
      Context);
388
}
389

    
390

    
391
Handle<Context> Factory::NewFunctionContext(int length,
392
                                            Handle<JSFunction> function) {
393
  CALL_HEAP_FUNCTION(
394
      isolate(),
395
      isolate()->heap()->AllocateFunctionContext(length, *function),
396
      Context);
397
}
398

    
399

    
400
Handle<Context> Factory::NewCatchContext(Handle<JSFunction> function,
401
                                         Handle<Context> previous,
402
                                         Handle<String> name,
403
                                         Handle<Object> thrown_object) {
404
  CALL_HEAP_FUNCTION(
405
      isolate(),
406
      isolate()->heap()->AllocateCatchContext(*function,
407
                                              *previous,
408
                                              *name,
409
                                              *thrown_object),
410
      Context);
411
}
412

    
413

    
414
Handle<Context> Factory::NewWithContext(Handle<JSFunction> function,
415
                                        Handle<Context> previous,
416
                                        Handle<JSObject> extension) {
417
  CALL_HEAP_FUNCTION(
418
      isolate(),
419
      isolate()->heap()->AllocateWithContext(*function, *previous, *extension),
420
      Context);
421
}
422

    
423

    
424
Handle<Context> Factory::NewBlockContext(Handle<JSFunction> function,
425
                                         Handle<Context> previous,
426
                                         Handle<ScopeInfo> scope_info) {
427
  CALL_HEAP_FUNCTION(
428
      isolate(),
429
      isolate()->heap()->AllocateBlockContext(*function,
430
                                              *previous,
431
                                              *scope_info),
432
      Context);
433
}
434

    
435

    
436
Handle<Struct> Factory::NewStruct(InstanceType type) {
437
  CALL_HEAP_FUNCTION(
438
      isolate(),
439
      isolate()->heap()->AllocateStruct(type),
440
      Struct);
441
}
442

    
443

    
444
Handle<DeclaredAccessorDescriptor> Factory::NewDeclaredAccessorDescriptor() {
445
  return Handle<DeclaredAccessorDescriptor>::cast(
446
      NewStruct(DECLARED_ACCESSOR_DESCRIPTOR_TYPE));
447
}
448

    
449

    
450
Handle<DeclaredAccessorInfo> Factory::NewDeclaredAccessorInfo() {
451
  Handle<DeclaredAccessorInfo> info =
452
      Handle<DeclaredAccessorInfo>::cast(
453
          NewStruct(DECLARED_ACCESSOR_INFO_TYPE));
454
  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
455
  return info;
456
}
457

    
458

    
459
Handle<ExecutableAccessorInfo> Factory::NewExecutableAccessorInfo() {
460
  Handle<ExecutableAccessorInfo> info =
461
      Handle<ExecutableAccessorInfo>::cast(
462
          NewStruct(EXECUTABLE_ACCESSOR_INFO_TYPE));
463
  info->set_flag(0);  // Must clear the flag, it was initialized as undefined.
464
  return info;
465
}
466

    
467

    
468
Handle<Script> Factory::NewScript(Handle<String> source) {
469
  // Generate id for this script.
470
  Heap* heap = isolate()->heap();
471
  int id = heap->last_script_id()->value() + 1;
472
  if (!Smi::IsValid(id) || id < 0) id = 1;
473
  heap->set_last_script_id(Smi::FromInt(id));
474

    
475
  // Create and initialize script object.
476
  Handle<Foreign> wrapper = NewForeign(0, TENURED);
477
  Handle<Script> script = Handle<Script>::cast(NewStruct(SCRIPT_TYPE));
478
  script->set_source(*source);
479
  script->set_name(heap->undefined_value());
480
  script->set_id(Smi::FromInt(id));
481
  script->set_line_offset(Smi::FromInt(0));
482
  script->set_column_offset(Smi::FromInt(0));
483
  script->set_data(heap->undefined_value());
484
  script->set_context_data(heap->undefined_value());
485
  script->set_type(Smi::FromInt(Script::TYPE_NORMAL));
486
  script->set_wrapper(*wrapper);
487
  script->set_line_ends(heap->undefined_value());
488
  script->set_eval_from_shared(heap->undefined_value());
489
  script->set_eval_from_instructions_offset(Smi::FromInt(0));
490
  script->set_flags(Smi::FromInt(0));
491

    
492
  return script;
493
}
494

    
495

    
496
Handle<Foreign> Factory::NewForeign(Address addr, PretenureFlag pretenure) {
497
  CALL_HEAP_FUNCTION(isolate(),
498
                     isolate()->heap()->AllocateForeign(addr, pretenure),
499
                     Foreign);
500
}
501

    
502

    
503
Handle<Foreign> Factory::NewForeign(const AccessorDescriptor* desc) {
504
  return NewForeign((Address) desc, TENURED);
505
}
506

    
507

    
508
Handle<ByteArray> Factory::NewByteArray(int length, PretenureFlag pretenure) {
509
  ASSERT(0 <= length);
510
  CALL_HEAP_FUNCTION(
511
      isolate(),
512
      isolate()->heap()->AllocateByteArray(length, pretenure),
513
      ByteArray);
514
}
515

    
516

    
517
Handle<ExternalArray> Factory::NewExternalArray(int length,
518
                                                ExternalArrayType array_type,
519
                                                void* external_pointer,
520
                                                PretenureFlag pretenure) {
521
  ASSERT(0 <= length);
522
  CALL_HEAP_FUNCTION(
523
      isolate(),
524
      isolate()->heap()->AllocateExternalArray(length,
525
                                               array_type,
526
                                               external_pointer,
527
                                               pretenure),
528
      ExternalArray);
529
}
530

    
531

    
532
Handle<Cell> Factory::NewCell(Handle<Object> value) {
533
  AllowDeferredHandleDereference convert_to_cell;
534
  CALL_HEAP_FUNCTION(
535
      isolate(),
536
      isolate()->heap()->AllocateCell(*value),
537
      Cell);
538
}
539

    
540

    
541
Handle<PropertyCell> Factory::NewPropertyCellWithHole() {
542
  CALL_HEAP_FUNCTION(
543
      isolate(),
544
      isolate()->heap()->AllocatePropertyCell(),
545
      PropertyCell);
546
}
547

    
548

    
549
Handle<PropertyCell> Factory::NewPropertyCell(Handle<Object> value) {
550
  AllowDeferredHandleDereference convert_to_cell;
551
  Handle<PropertyCell> cell = NewPropertyCellWithHole();
552
  PropertyCell::SetValueInferType(cell, value);
553
  return cell;
554
}
555

    
556

    
557
Handle<AllocationSite> Factory::NewAllocationSite() {
558
  CALL_HEAP_FUNCTION(
559
      isolate(),
560
      isolate()->heap()->AllocateAllocationSite(),
561
      AllocationSite);
562
}
563

    
564

    
565
Handle<Map> Factory::NewMap(InstanceType type,
566
                            int instance_size,
567
                            ElementsKind elements_kind) {
568
  CALL_HEAP_FUNCTION(
569
      isolate(),
570
      isolate()->heap()->AllocateMap(type, instance_size, elements_kind),
571
      Map);
572
}
573

    
574

    
575
Handle<JSObject> Factory::NewFunctionPrototype(Handle<JSFunction> function) {
576
  CALL_HEAP_FUNCTION(
577
      isolate(),
578
      isolate()->heap()->AllocateFunctionPrototype(*function),
579
      JSObject);
580
}
581

    
582

    
583
Handle<Map> Factory::CopyWithPreallocatedFieldDescriptors(Handle<Map> src) {
584
  CALL_HEAP_FUNCTION(
585
      isolate(), src->CopyWithPreallocatedFieldDescriptors(), Map);
586
}
587

    
588

    
589
Handle<Map> Factory::CopyMap(Handle<Map> src,
590
                             int extra_inobject_properties) {
591
  Handle<Map> copy = CopyWithPreallocatedFieldDescriptors(src);
592
  // Check that we do not overflow the instance size when adding the
593
  // extra inobject properties.
594
  int instance_size_delta = extra_inobject_properties * kPointerSize;
595
  int max_instance_size_delta =
596
      JSObject::kMaxInstanceSize - copy->instance_size();
597
  if (instance_size_delta > max_instance_size_delta) {
598
    // If the instance size overflows, we allocate as many properties
599
    // as we can as inobject properties.
600
    instance_size_delta = max_instance_size_delta;
601
    extra_inobject_properties = max_instance_size_delta >> kPointerSizeLog2;
602
  }
603
  // Adjust the map with the extra inobject properties.
604
  int inobject_properties =
605
      copy->inobject_properties() + extra_inobject_properties;
606
  copy->set_inobject_properties(inobject_properties);
607
  copy->set_unused_property_fields(inobject_properties);
608
  copy->set_instance_size(copy->instance_size() + instance_size_delta);
609
  copy->set_visitor_id(StaticVisitorBase::GetVisitorId(*copy));
610
  return copy;
611
}
612

    
613

    
614
Handle<Map> Factory::CopyMap(Handle<Map> src) {
615
  CALL_HEAP_FUNCTION(isolate(), src->Copy(), Map);
616
}
617

    
618

    
619
Handle<Map> Factory::GetElementsTransitionMap(
620
    Handle<JSObject> src,
621
    ElementsKind elements_kind) {
622
  Isolate* i = isolate();
623
  CALL_HEAP_FUNCTION(i,
624
                     src->GetElementsTransitionMap(i, elements_kind),
625
                     Map);
626
}
627

    
628

    
629
Handle<FixedArray> Factory::CopyFixedArray(Handle<FixedArray> array) {
630
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedArray);
631
}
632

    
633

    
634
Handle<FixedArray> Factory::CopySizeFixedArray(Handle<FixedArray> array,
635
                                               int new_length,
636
                                               PretenureFlag pretenure) {
637
  CALL_HEAP_FUNCTION(isolate(),
638
                     array->CopySize(new_length, pretenure),
639
                     FixedArray);
640
}
641

    
642

    
643
Handle<FixedDoubleArray> Factory::CopyFixedDoubleArray(
644
    Handle<FixedDoubleArray> array) {
645
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), FixedDoubleArray);
646
}
647

    
648

    
649
Handle<ConstantPoolArray> Factory::CopyConstantPoolArray(
650
    Handle<ConstantPoolArray> array) {
651
  CALL_HEAP_FUNCTION(isolate(), array->Copy(), ConstantPoolArray);
652
}
653

    
654

    
655
Handle<JSFunction> Factory::BaseNewFunctionFromSharedFunctionInfo(
656
    Handle<SharedFunctionInfo> function_info,
657
    Handle<Map> function_map,
658
    PretenureFlag pretenure) {
659
  CALL_HEAP_FUNCTION(
660
      isolate(),
661
      isolate()->heap()->AllocateFunction(*function_map,
662
                                          *function_info,
663
                                          isolate()->heap()->the_hole_value(),
664
                                          pretenure),
665
                     JSFunction);
666
}
667

    
668

    
669
static Handle<Map> MapForNewFunction(Isolate *isolate,
670
                                     Handle<SharedFunctionInfo> function_info) {
671
  Context *context = isolate->context()->native_context();
672
  int map_index = Context::FunctionMapIndex(function_info->language_mode(),
673
                                            function_info->is_generator());
674
  return Handle<Map>(Map::cast(context->get(map_index)));
675
}
676

    
677

    
678
Handle<JSFunction> Factory::NewFunctionFromSharedFunctionInfo(
679
    Handle<SharedFunctionInfo> function_info,
680
    Handle<Context> context,
681
    PretenureFlag pretenure) {
682
  Handle<JSFunction> result = BaseNewFunctionFromSharedFunctionInfo(
683
      function_info,
684
      MapForNewFunction(isolate(), function_info),
685
      pretenure);
686

    
687
  if (function_info->ic_age() != isolate()->heap()->global_ic_age()) {
688
    function_info->ResetForNewContext(isolate()->heap()->global_ic_age());
689
  }
690

    
691
  result->set_context(*context);
692

    
693
  int index = function_info->SearchOptimizedCodeMap(context->native_context());
694
  if (!function_info->bound() && index < 0) {
695
    int number_of_literals = function_info->num_literals();
696
    Handle<FixedArray> literals = NewFixedArray(number_of_literals, pretenure);
697
    if (number_of_literals > 0) {
698
      // Store the native context in the literals array prefix. This
699
      // context will be used when creating object, regexp and array
700
      // literals in this function.
701
      literals->set(JSFunction::kLiteralNativeContextIndex,
702
                    context->native_context());
703
    }
704
    result->set_literals(*literals);
705
  }
706

    
707
  if (index > 0) {
708
    // Caching of optimized code enabled and optimized code found.
709
    function_info->InstallFromOptimizedCodeMap(*result, index);
710
    return result;
711
  }
712

    
713
  if (isolate()->use_crankshaft() &&
714
      FLAG_always_opt &&
715
      result->is_compiled() &&
716
      !function_info->is_toplevel() &&
717
      function_info->allows_lazy_compilation() &&
718
      !function_info->optimization_disabled() &&
719
      !isolate()->DebuggerHasBreakPoints()) {
720
    result->MarkForLazyRecompilation();
721
  }
722
  return result;
723
}
724

    
725

    
726
Handle<Object> Factory::NewNumber(double value,
727
                                  PretenureFlag pretenure) {
728
  CALL_HEAP_FUNCTION(
729
      isolate(),
730
      isolate()->heap()->NumberFromDouble(value, pretenure), Object);
731
}
732

    
733

    
734
Handle<Object> Factory::NewNumberFromInt(int32_t value,
735
                                         PretenureFlag pretenure) {
736
  CALL_HEAP_FUNCTION(
737
      isolate(),
738
      isolate()->heap()->NumberFromInt32(value, pretenure), Object);
739
}
740

    
741

    
742
Handle<Object> Factory::NewNumberFromUint(uint32_t value,
743
                                         PretenureFlag pretenure) {
744
  CALL_HEAP_FUNCTION(
745
      isolate(),
746
      isolate()->heap()->NumberFromUint32(value, pretenure), Object);
747
}
748

    
749

    
750
Handle<HeapNumber> Factory::NewHeapNumber(double value,
751
                                          PretenureFlag pretenure) {
752
  CALL_HEAP_FUNCTION(
753
      isolate(),
754
      isolate()->heap()->AllocateHeapNumber(value, pretenure), HeapNumber);
755
}
756

    
757

    
758
Handle<JSObject> Factory::NewNeanderObject() {
759
  CALL_HEAP_FUNCTION(
760
      isolate(),
761
      isolate()->heap()->AllocateJSObjectFromMap(
762
          isolate()->heap()->neander_map()),
763
      JSObject);
764
}
765

    
766

    
767
Handle<Object> Factory::NewTypeError(const char* message,
768
                                     Vector< Handle<Object> > args) {
769
  return NewError("MakeTypeError", message, args);
770
}
771

    
772

    
773
Handle<Object> Factory::NewTypeError(Handle<String> message) {
774
  return NewError("$TypeError", message);
775
}
776

    
777

    
778
Handle<Object> Factory::NewRangeError(const char* message,
779
                                      Vector< Handle<Object> > args) {
780
  return NewError("MakeRangeError", message, args);
781
}
782

    
783

    
784
Handle<Object> Factory::NewRangeError(Handle<String> message) {
785
  return NewError("$RangeError", message);
786
}
787

    
788

    
789
Handle<Object> Factory::NewSyntaxError(const char* message,
790
                                       Handle<JSArray> args) {
791
  return NewError("MakeSyntaxError", message, args);
792
}
793

    
794

    
795
Handle<Object> Factory::NewSyntaxError(Handle<String> message) {
796
  return NewError("$SyntaxError", message);
797
}
798

    
799

    
800
Handle<Object> Factory::NewReferenceError(const char* message,
801
                                          Vector< Handle<Object> > args) {
802
  return NewError("MakeReferenceError", message, args);
803
}
804

    
805

    
806
Handle<Object> Factory::NewReferenceError(Handle<String> message) {
807
  return NewError("$ReferenceError", message);
808
}
809

    
810

    
811
Handle<Object> Factory::NewError(const char* maker,
812
                                 const char* message,
813
                                 Vector< Handle<Object> > args) {
814
  // Instantiate a closeable HandleScope for EscapeFrom.
815
  v8::HandleScope scope(reinterpret_cast<v8::Isolate*>(isolate()));
816
  Handle<FixedArray> array = NewFixedArray(args.length());
817
  for (int i = 0; i < args.length(); i++) {
818
    array->set(i, *args[i]);
819
  }
820
  Handle<JSArray> object = NewJSArrayWithElements(array);
821
  Handle<Object> result = NewError(maker, message, object);
822
  return result.EscapeFrom(&scope);
823
}
824

    
825

    
826
Handle<Object> Factory::NewEvalError(const char* message,
827
                                     Vector< Handle<Object> > args) {
828
  return NewError("MakeEvalError", message, args);
829
}
830

    
831

    
832
Handle<Object> Factory::NewError(const char* message,
833
                                 Vector< Handle<Object> > args) {
834
  return NewError("MakeError", message, args);
835
}
836

    
837

    
838
Handle<String> Factory::EmergencyNewError(const char* message,
839
                                          Handle<JSArray> args) {
840
  const int kBufferSize = 1000;
841
  char buffer[kBufferSize];
842
  size_t space = kBufferSize;
843
  char* p = &buffer[0];
844

    
845
  Vector<char> v(buffer, kBufferSize);
846
  OS::StrNCpy(v, message, space);
847
  space -= Min(space, strlen(message));
848
  p = &buffer[kBufferSize] - space;
849

    
850
  for (unsigned i = 0; i < ARRAY_SIZE(args); i++) {
851
    if (space > 0) {
852
      *p++ = ' ';
853
      space--;
854
      if (space > 0) {
855
        MaybeObject* maybe_arg = args->GetElement(isolate(), i);
856
        Handle<String> arg_str(reinterpret_cast<String*>(maybe_arg));
857
        const char* arg = *arg_str->ToCString();
858
        Vector<char> v2(p, static_cast<int>(space));
859
        OS::StrNCpy(v2, arg, space);
860
        space -= Min(space, strlen(arg));
861
        p = &buffer[kBufferSize] - space;
862
      }
863
    }
864
  }
865
  if (space > 0) {
866
    *p = '\0';
867
  } else {
868
    buffer[kBufferSize - 1] = '\0';
869
  }
870
  Handle<String> error_string = NewStringFromUtf8(CStrVector(buffer), TENURED);
871
  return error_string;
872
}
873

    
874

    
875
Handle<Object> Factory::NewError(const char* maker,
876
                                 const char* message,
877
                                 Handle<JSArray> args) {
878
  Handle<String> make_str = InternalizeUtf8String(maker);
879
  Handle<Object> fun_obj(
880
      isolate()->js_builtins_object()->GetPropertyNoExceptionThrown(*make_str),
881
      isolate());
882
  // If the builtins haven't been properly configured yet this error
883
  // constructor may not have been defined.  Bail out.
884
  if (!fun_obj->IsJSFunction()) {
885
    return EmergencyNewError(message, args);
886
  }
887
  Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
888
  Handle<Object> message_obj = InternalizeUtf8String(message);
889
  Handle<Object> argv[] = { message_obj, args };
890

    
891
  // Invoke the JavaScript factory method. If an exception is thrown while
892
  // running the factory method, use the exception as the result.
893
  bool caught_exception;
894
  Handle<Object> result = Execution::TryCall(fun,
895
                                             isolate()->js_builtins_object(),
896
                                             ARRAY_SIZE(argv),
897
                                             argv,
898
                                             &caught_exception);
899
  return result;
900
}
901

    
902

    
903
Handle<Object> Factory::NewError(Handle<String> message) {
904
  return NewError("$Error", message);
905
}
906

    
907

    
908
Handle<Object> Factory::NewError(const char* constructor,
909
                                 Handle<String> message) {
910
  Handle<String> constr = InternalizeUtf8String(constructor);
911
  Handle<JSFunction> fun = Handle<JSFunction>(
912
      JSFunction::cast(isolate()->js_builtins_object()->
913
                       GetPropertyNoExceptionThrown(*constr)));
914
  Handle<Object> argv[] = { message };
915

    
916
  // Invoke the JavaScript factory method. If an exception is thrown while
917
  // running the factory method, use the exception as the result.
918
  bool caught_exception;
919
  Handle<Object> result = Execution::TryCall(fun,
920
                                             isolate()->js_builtins_object(),
921
                                             ARRAY_SIZE(argv),
922
                                             argv,
923
                                             &caught_exception);
924
  return result;
925
}
926

    
927

    
928
Handle<JSFunction> Factory::NewFunction(Handle<String> name,
929
                                        InstanceType type,
930
                                        int instance_size,
931
                                        Handle<Code> code,
932
                                        bool force_initial_map) {
933
  // Allocate the function
934
  Handle<JSFunction> function = NewFunction(name, the_hole_value());
935

    
936
  // Set up the code pointer in both the shared function info and in
937
  // the function itself.
938
  function->shared()->set_code(*code);
939
  function->set_code(*code);
940

    
941
  if (force_initial_map ||
942
      type != JS_OBJECT_TYPE ||
943
      instance_size != JSObject::kHeaderSize) {
944
    Handle<Map> initial_map = NewMap(type, instance_size);
945
    Handle<JSObject> prototype = NewFunctionPrototype(function);
946
    initial_map->set_prototype(*prototype);
947
    function->set_initial_map(*initial_map);
948
    initial_map->set_constructor(*function);
949
  } else {
950
    ASSERT(!function->has_initial_map());
951
    ASSERT(!function->has_prototype());
952
  }
953

    
954
  return function;
955
}
956

    
957

    
958
Handle<JSFunction> Factory::NewFunctionWithPrototype(Handle<String> name,
959
                                                     InstanceType type,
960
                                                     int instance_size,
961
                                                     Handle<JSObject> prototype,
962
                                                     Handle<Code> code,
963
                                                     bool force_initial_map) {
964
  // Allocate the function.
965
  Handle<JSFunction> function = NewFunction(name, prototype);
966

    
967
  // Set up the code pointer in both the shared function info and in
968
  // the function itself.
969
  function->shared()->set_code(*code);
970
  function->set_code(*code);
971

    
972
  if (force_initial_map ||
973
      type != JS_OBJECT_TYPE ||
974
      instance_size != JSObject::kHeaderSize) {
975
    Handle<Map> initial_map = NewMap(type,
976
                                     instance_size,
977
                                     GetInitialFastElementsKind());
978
    function->set_initial_map(*initial_map);
979
    initial_map->set_constructor(*function);
980
  }
981

    
982
  JSFunction::SetPrototype(function, prototype);
983
  return function;
984
}
985

    
986

    
987
Handle<JSFunction> Factory::NewFunctionWithoutPrototype(Handle<String> name,
988
                                                        Handle<Code> code) {
989
  Handle<JSFunction> function = NewFunctionWithoutPrototype(name,
990
                                                            CLASSIC_MODE);
991
  function->shared()->set_code(*code);
992
  function->set_code(*code);
993
  ASSERT(!function->has_initial_map());
994
  ASSERT(!function->has_prototype());
995
  return function;
996
}
997

    
998

    
999
Handle<ScopeInfo> Factory::NewScopeInfo(int length) {
1000
  CALL_HEAP_FUNCTION(
1001
      isolate(),
1002
      isolate()->heap()->AllocateScopeInfo(length),
1003
      ScopeInfo);
1004
}
1005

    
1006

    
1007
Handle<JSObject> Factory::NewExternal(void* value) {
1008
  CALL_HEAP_FUNCTION(isolate(),
1009
                     isolate()->heap()->AllocateExternal(value),
1010
                     JSObject);
1011
}
1012

    
1013

    
1014
Handle<Code> Factory::NewCode(const CodeDesc& desc,
1015
                              Code::Flags flags,
1016
                              Handle<Object> self_ref,
1017
                              bool immovable,
1018
                              bool crankshafted,
1019
                              int prologue_offset) {
1020
  CALL_HEAP_FUNCTION(isolate(),
1021
                     isolate()->heap()->CreateCode(
1022
                         desc, flags, self_ref, immovable, crankshafted,
1023
                         prologue_offset),
1024
                     Code);
1025
}
1026

    
1027

    
1028
Handle<Code> Factory::CopyCode(Handle<Code> code) {
1029
  CALL_HEAP_FUNCTION(isolate(),
1030
                     isolate()->heap()->CopyCode(*code),
1031
                     Code);
1032
}
1033

    
1034

    
1035
Handle<Code> Factory::CopyCode(Handle<Code> code, Vector<byte> reloc_info) {
1036
  CALL_HEAP_FUNCTION(isolate(),
1037
                     isolate()->heap()->CopyCode(*code, reloc_info),
1038
                     Code);
1039
}
1040

    
1041

    
1042
Handle<String> Factory::InternalizedStringFromString(Handle<String> value) {
1043
  CALL_HEAP_FUNCTION(isolate(),
1044
                     isolate()->heap()->InternalizeString(*value), String);
1045
}
1046

    
1047

    
1048
Handle<JSObject> Factory::NewJSObject(Handle<JSFunction> constructor,
1049
                                      PretenureFlag pretenure) {
1050
  CALL_HEAP_FUNCTION(
1051
      isolate(),
1052
      isolate()->heap()->AllocateJSObject(*constructor, pretenure), JSObject);
1053
}
1054

    
1055

    
1056
Handle<JSModule> Factory::NewJSModule(Handle<Context> context,
1057
                                      Handle<ScopeInfo> scope_info) {
1058
  CALL_HEAP_FUNCTION(
1059
      isolate(),
1060
      isolate()->heap()->AllocateJSModule(*context, *scope_info), JSModule);
1061
}
1062

    
1063

    
1064
// TODO(mstarzinger): Temporary wrapper until handlified.
1065
static Handle<NameDictionary> NameDictionaryAdd(Handle<NameDictionary> dict,
1066
                                                Handle<Name> name,
1067
                                                Handle<Object> value,
1068
                                                PropertyDetails details) {
1069
  CALL_HEAP_FUNCTION(dict->GetIsolate(),
1070
                     dict->Add(*name, *value, details),
1071
                     NameDictionary);
1072
}
1073

    
1074

    
1075
static Handle<GlobalObject> NewGlobalObjectFromMap(Isolate* isolate,
1076
                                                   Handle<Map> map) {
1077
  CALL_HEAP_FUNCTION(isolate,
1078
                     isolate->heap()->Allocate(*map, OLD_POINTER_SPACE),
1079
                     GlobalObject);
1080
}
1081

    
1082

    
1083
Handle<GlobalObject> Factory::NewGlobalObject(Handle<JSFunction> constructor) {
1084
  ASSERT(constructor->has_initial_map());
1085
  Handle<Map> map(constructor->initial_map());
1086
  ASSERT(map->is_dictionary_map());
1087

    
1088
  // Make sure no field properties are described in the initial map.
1089
  // This guarantees us that normalizing the properties does not
1090
  // require us to change property values to PropertyCells.
1091
  ASSERT(map->NextFreePropertyIndex() == 0);
1092

    
1093
  // Make sure we don't have a ton of pre-allocated slots in the
1094
  // global objects. They will be unused once we normalize the object.
1095
  ASSERT(map->unused_property_fields() == 0);
1096
  ASSERT(map->inobject_properties() == 0);
1097

    
1098
  // Initial size of the backing store to avoid resize of the storage during
1099
  // bootstrapping. The size differs between the JS global object ad the
1100
  // builtins object.
1101
  int initial_size = map->instance_type() == JS_GLOBAL_OBJECT_TYPE ? 64 : 512;
1102

    
1103
  // Allocate a dictionary object for backing storage.
1104
  int at_least_space_for = map->NumberOfOwnDescriptors() * 2 + initial_size;
1105
  Handle<NameDictionary> dictionary = NewNameDictionary(at_least_space_for);
1106

    
1107
  // The global object might be created from an object template with accessors.
1108
  // Fill these accessors into the dictionary.
1109
  Handle<DescriptorArray> descs(map->instance_descriptors());
1110
  for (int i = 0; i < map->NumberOfOwnDescriptors(); i++) {
1111
    PropertyDetails details = descs->GetDetails(i);
1112
    ASSERT(details.type() == CALLBACKS);  // Only accessors are expected.
1113
    PropertyDetails d = PropertyDetails(details.attributes(), CALLBACKS, i + 1);
1114
    Handle<Name> name(descs->GetKey(i));
1115
    Handle<Object> value(descs->GetCallbacksObject(i), isolate());
1116
    Handle<PropertyCell> cell = NewPropertyCell(value);
1117
    NameDictionaryAdd(dictionary, name, cell, d);
1118
  }
1119

    
1120
  // Allocate the global object and initialize it with the backing store.
1121
  Handle<GlobalObject> global = NewGlobalObjectFromMap(isolate(), map);
1122
  isolate()->heap()->InitializeJSObjectFromMap(*global, *dictionary, *map);
1123

    
1124
  // Create a new map for the global object.
1125
  Handle<Map> new_map = Map::CopyDropDescriptors(map);
1126
  new_map->set_dictionary_map(true);
1127

    
1128
  // Set up the global object as a normalized object.
1129
  global->set_map(*new_map);
1130
  global->set_properties(*dictionary);
1131

    
1132
  // Make sure result is a global object with properties in dictionary.
1133
  ASSERT(global->IsGlobalObject() && !global->HasFastProperties());
1134
  return global;
1135
}
1136

    
1137

    
1138
Handle<JSObject> Factory::NewJSObjectFromMap(Handle<Map> map,
1139
                                             PretenureFlag pretenure,
1140
                                             bool alloc_props) {
1141
  CALL_HEAP_FUNCTION(
1142
      isolate(),
1143
      isolate()->heap()->AllocateJSObjectFromMap(*map, pretenure, alloc_props),
1144
      JSObject);
1145
}
1146

    
1147

    
1148
Handle<JSArray> Factory::NewJSArray(int capacity,
1149
                                    ElementsKind elements_kind,
1150
                                    PretenureFlag pretenure) {
1151
  if (capacity != 0) {
1152
    elements_kind = GetHoleyElementsKind(elements_kind);
1153
  }
1154
  CALL_HEAP_FUNCTION(isolate(),
1155
                     isolate()->heap()->AllocateJSArrayAndStorage(
1156
                         elements_kind,
1157
                         0,
1158
                         capacity,
1159
                         INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE,
1160
                         pretenure),
1161
                     JSArray);
1162
}
1163

    
1164

    
1165
Handle<JSArray> Factory::NewJSArrayWithElements(Handle<FixedArrayBase> elements,
1166
                                                ElementsKind elements_kind,
1167
                                                PretenureFlag pretenure) {
1168
  CALL_HEAP_FUNCTION(
1169
      isolate(),
1170
      isolate()->heap()->AllocateJSArrayWithElements(*elements,
1171
                                                     elements_kind,
1172
                                                     elements->length(),
1173
                                                     pretenure),
1174
      JSArray);
1175
}
1176

    
1177

    
1178
void Factory::SetElementsCapacityAndLength(Handle<JSArray> array,
1179
                                           int capacity,
1180
                                           int length) {
1181
  ElementsAccessor* accessor = array->GetElementsAccessor();
1182
  CALL_HEAP_FUNCTION_VOID(
1183
      isolate(),
1184
      accessor->SetCapacityAndLength(*array, capacity, length));
1185
}
1186

    
1187

    
1188
void Factory::SetContent(Handle<JSArray> array,
1189
                         Handle<FixedArrayBase> elements) {
1190
  CALL_HEAP_FUNCTION_VOID(
1191
      isolate(),
1192
      array->SetContent(*elements));
1193
}
1194

    
1195

    
1196
Handle<JSArrayBuffer> Factory::NewJSArrayBuffer() {
1197
  Handle<JSFunction> array_buffer_fun(
1198
      isolate()->context()->native_context()->array_buffer_fun());
1199
  CALL_HEAP_FUNCTION(
1200
      isolate(),
1201
      isolate()->heap()->AllocateJSObject(*array_buffer_fun),
1202
      JSArrayBuffer);
1203
}
1204

    
1205

    
1206
Handle<JSDataView> Factory::NewJSDataView() {
1207
  Handle<JSFunction> data_view_fun(
1208
      isolate()->context()->native_context()->data_view_fun());
1209
  CALL_HEAP_FUNCTION(
1210
      isolate(),
1211
      isolate()->heap()->AllocateJSObject(*data_view_fun),
1212
      JSDataView);
1213
}
1214

    
1215

    
1216
static JSFunction* GetTypedArrayFun(ExternalArrayType type,
1217
                                    Isolate* isolate) {
1218
  Context* native_context = isolate->context()->native_context();
1219
  switch (type) {
1220
    case kExternalUnsignedByteArray:
1221
      return native_context->uint8_array_fun();
1222

    
1223
    case kExternalByteArray:
1224
      return native_context->int8_array_fun();
1225

    
1226
    case kExternalUnsignedShortArray:
1227
      return native_context->uint16_array_fun();
1228

    
1229
    case kExternalShortArray:
1230
      return native_context->int16_array_fun();
1231

    
1232
    case kExternalUnsignedIntArray:
1233
      return native_context->uint32_array_fun();
1234

    
1235
    case kExternalIntArray:
1236
      return native_context->int32_array_fun();
1237

    
1238
    case kExternalFloatArray:
1239
      return native_context->float_array_fun();
1240

    
1241
    case kExternalDoubleArray:
1242
      return native_context->double_array_fun();
1243

    
1244
    case kExternalPixelArray:
1245
      return native_context->uint8c_array_fun();
1246

    
1247
    default:
1248
      UNREACHABLE();
1249
      return NULL;
1250
  }
1251
}
1252

    
1253

    
1254
Handle<JSTypedArray> Factory::NewJSTypedArray(ExternalArrayType type) {
1255
  Handle<JSFunction> typed_array_fun_handle(GetTypedArrayFun(type, isolate()));
1256

    
1257
  CALL_HEAP_FUNCTION(
1258
      isolate(),
1259
      isolate()->heap()->AllocateJSObject(*typed_array_fun_handle),
1260
      JSTypedArray);
1261
}
1262

    
1263

    
1264
Handle<JSProxy> Factory::NewJSProxy(Handle<Object> handler,
1265
                                    Handle<Object> prototype) {
1266
  CALL_HEAP_FUNCTION(
1267
      isolate(),
1268
      isolate()->heap()->AllocateJSProxy(*handler, *prototype),
1269
      JSProxy);
1270
}
1271

    
1272

    
1273
void Factory::BecomeJSObject(Handle<JSReceiver> object) {
1274
  CALL_HEAP_FUNCTION_VOID(
1275
      isolate(),
1276
      isolate()->heap()->ReinitializeJSReceiver(
1277
          *object, JS_OBJECT_TYPE, JSObject::kHeaderSize));
1278
}
1279

    
1280

    
1281
void Factory::BecomeJSFunction(Handle<JSReceiver> object) {
1282
  CALL_HEAP_FUNCTION_VOID(
1283
      isolate(),
1284
      isolate()->heap()->ReinitializeJSReceiver(
1285
          *object, JS_FUNCTION_TYPE, JSFunction::kSize));
1286
}
1287

    
1288

    
1289
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(
1290
    Handle<String> name,
1291
    int number_of_literals,
1292
    bool is_generator,
1293
    Handle<Code> code,
1294
    Handle<ScopeInfo> scope_info) {
1295
  Handle<SharedFunctionInfo> shared = NewSharedFunctionInfo(name);
1296
  shared->set_code(*code);
1297
  shared->set_scope_info(*scope_info);
1298
  int literals_array_size = number_of_literals;
1299
  // If the function contains object, regexp or array literals,
1300
  // allocate extra space for a literals array prefix containing the
1301
  // context.
1302
  if (number_of_literals > 0) {
1303
    literals_array_size += JSFunction::kLiteralsPrefixSize;
1304
  }
1305
  shared->set_num_literals(literals_array_size);
1306
  if (is_generator) {
1307
    shared->set_instance_class_name(isolate()->heap()->Generator_string());
1308
    shared->DisableOptimization(kGenerator);
1309
  }
1310
  return shared;
1311
}
1312

    
1313

    
1314
Handle<JSMessageObject> Factory::NewJSMessageObject(
1315
    Handle<String> type,
1316
    Handle<JSArray> arguments,
1317
    int start_position,
1318
    int end_position,
1319
    Handle<Object> script,
1320
    Handle<Object> stack_trace,
1321
    Handle<Object> stack_frames) {
1322
  CALL_HEAP_FUNCTION(isolate(),
1323
                     isolate()->heap()->AllocateJSMessageObject(*type,
1324
                         *arguments,
1325
                         start_position,
1326
                         end_position,
1327
                         *script,
1328
                         *stack_trace,
1329
                         *stack_frames),
1330
                     JSMessageObject);
1331
}
1332

    
1333

    
1334
Handle<SharedFunctionInfo> Factory::NewSharedFunctionInfo(Handle<String> name) {
1335
  CALL_HEAP_FUNCTION(isolate(),
1336
                     isolate()->heap()->AllocateSharedFunctionInfo(*name),
1337
                     SharedFunctionInfo);
1338
}
1339

    
1340

    
1341
Handle<String> Factory::NumberToString(Handle<Object> number) {
1342
  CALL_HEAP_FUNCTION(isolate(),
1343
                     isolate()->heap()->NumberToString(*number), String);
1344
}
1345

    
1346

    
1347
Handle<String> Factory::Uint32ToString(uint32_t value) {
1348
  CALL_HEAP_FUNCTION(isolate(),
1349
                     isolate()->heap()->Uint32ToString(value), String);
1350
}
1351

    
1352

    
1353
Handle<SeededNumberDictionary> Factory::DictionaryAtNumberPut(
1354
    Handle<SeededNumberDictionary> dictionary,
1355
    uint32_t key,
1356
    Handle<Object> value) {
1357
  CALL_HEAP_FUNCTION(isolate(),
1358
                     dictionary->AtNumberPut(key, *value),
1359
                     SeededNumberDictionary);
1360
}
1361

    
1362

    
1363
Handle<UnseededNumberDictionary> Factory::DictionaryAtNumberPut(
1364
    Handle<UnseededNumberDictionary> dictionary,
1365
    uint32_t key,
1366
    Handle<Object> value) {
1367
  CALL_HEAP_FUNCTION(isolate(),
1368
                     dictionary->AtNumberPut(key, *value),
1369
                     UnseededNumberDictionary);
1370
}
1371

    
1372

    
1373
Handle<JSFunction> Factory::NewFunctionHelper(Handle<String> name,
1374
                                              Handle<Object> prototype) {
1375
  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1376
  CALL_HEAP_FUNCTION(
1377
      isolate(),
1378
      isolate()->heap()->AllocateFunction(*isolate()->function_map(),
1379
                                          *function_share,
1380
                                          *prototype),
1381
      JSFunction);
1382
}
1383

    
1384

    
1385
Handle<JSFunction> Factory::NewFunction(Handle<String> name,
1386
                                        Handle<Object> prototype) {
1387
  Handle<JSFunction> fun = NewFunctionHelper(name, prototype);
1388
  fun->set_context(isolate()->context()->native_context());
1389
  return fun;
1390
}
1391

    
1392

    
1393
Handle<JSFunction> Factory::NewFunctionWithoutPrototypeHelper(
1394
    Handle<String> name,
1395
    LanguageMode language_mode) {
1396
  Handle<SharedFunctionInfo> function_share = NewSharedFunctionInfo(name);
1397
  Handle<Map> map = (language_mode == CLASSIC_MODE)
1398
      ? isolate()->function_without_prototype_map()
1399
      : isolate()->strict_mode_function_without_prototype_map();
1400
  CALL_HEAP_FUNCTION(isolate(),
1401
                     isolate()->heap()->AllocateFunction(
1402
                         *map,
1403
                         *function_share,
1404
                         *the_hole_value()),
1405
                     JSFunction);
1406
}
1407

    
1408

    
1409
Handle<JSFunction> Factory::NewFunctionWithoutPrototype(
1410
    Handle<String> name,
1411
    LanguageMode language_mode) {
1412
  Handle<JSFunction> fun =
1413
      NewFunctionWithoutPrototypeHelper(name, language_mode);
1414
  fun->set_context(isolate()->context()->native_context());
1415
  return fun;
1416
}
1417

    
1418

    
1419
Handle<Object> Factory::ToObject(Handle<Object> object) {
1420
  CALL_HEAP_FUNCTION(isolate(), object->ToObject(isolate()), Object);
1421
}
1422

    
1423

    
1424
Handle<Object> Factory::ToObject(Handle<Object> object,
1425
                                 Handle<Context> native_context) {
1426
  CALL_HEAP_FUNCTION(isolate(), object->ToObject(*native_context), Object);
1427
}
1428

    
1429

    
1430
#ifdef ENABLE_DEBUGGER_SUPPORT
1431
Handle<DebugInfo> Factory::NewDebugInfo(Handle<SharedFunctionInfo> shared) {
1432
  // Get the original code of the function.
1433
  Handle<Code> code(shared->code());
1434

    
1435
  // Create a copy of the code before allocating the debug info object to avoid
1436
  // allocation while setting up the debug info object.
1437
  Handle<Code> original_code(*Factory::CopyCode(code));
1438

    
1439
  // Allocate initial fixed array for active break points before allocating the
1440
  // debug info object to avoid allocation while setting up the debug info
1441
  // object.
1442
  Handle<FixedArray> break_points(
1443
      NewFixedArray(Debug::kEstimatedNofBreakPointsInFunction));
1444

    
1445
  // Create and set up the debug info object. Debug info contains function, a
1446
  // copy of the original code, the executing code and initial fixed array for
1447
  // active break points.
1448
  Handle<DebugInfo> debug_info =
1449
      Handle<DebugInfo>::cast(NewStruct(DEBUG_INFO_TYPE));
1450
  debug_info->set_shared(*shared);
1451
  debug_info->set_original_code(*original_code);
1452
  debug_info->set_code(*code);
1453
  debug_info->set_break_points(*break_points);
1454

    
1455
  // Link debug info to function.
1456
  shared->set_debug_info(*debug_info);
1457

    
1458
  return debug_info;
1459
}
1460
#endif
1461

    
1462

    
1463
Handle<JSObject> Factory::NewArgumentsObject(Handle<Object> callee,
1464
                                             int length) {
1465
  CALL_HEAP_FUNCTION(
1466
      isolate(),
1467
      isolate()->heap()->AllocateArgumentsObject(*callee, length), JSObject);
1468
}
1469

    
1470

    
1471
Handle<JSFunction> Factory::CreateApiFunction(
1472
    Handle<FunctionTemplateInfo> obj, ApiInstanceType instance_type) {
1473
  Handle<Code> code = isolate()->builtins()->HandleApiCall();
1474
  Handle<Code> construct_stub = isolate()->builtins()->JSConstructStubApi();
1475

    
1476
  int internal_field_count = 0;
1477
  if (!obj->instance_template()->IsUndefined()) {
1478
    Handle<ObjectTemplateInfo> instance_template =
1479
        Handle<ObjectTemplateInfo>(
1480
            ObjectTemplateInfo::cast(obj->instance_template()));
1481
    internal_field_count =
1482
        Smi::cast(instance_template->internal_field_count())->value();
1483
  }
1484

    
1485
  // TODO(svenpanne) Kill ApiInstanceType and refactor things by generalizing
1486
  // JSObject::GetHeaderSize.
1487
  int instance_size = kPointerSize * internal_field_count;
1488
  InstanceType type;
1489
  switch (instance_type) {
1490
    case JavaScriptObject:
1491
      type = JS_OBJECT_TYPE;
1492
      instance_size += JSObject::kHeaderSize;
1493
      break;
1494
    case InnerGlobalObject:
1495
      type = JS_GLOBAL_OBJECT_TYPE;
1496
      instance_size += JSGlobalObject::kSize;
1497
      break;
1498
    case OuterGlobalObject:
1499
      type = JS_GLOBAL_PROXY_TYPE;
1500
      instance_size += JSGlobalProxy::kSize;
1501
      break;
1502
    default:
1503
      UNREACHABLE();
1504
      type = JS_OBJECT_TYPE;  // Keep the compiler happy.
1505
      break;
1506
  }
1507

    
1508
  Handle<JSFunction> result =
1509
      NewFunction(Factory::empty_string(),
1510
                  type,
1511
                  instance_size,
1512
                  code,
1513
                  true);
1514

    
1515
  // Set length.
1516
  result->shared()->set_length(obj->length());
1517

    
1518
  // Set class name.
1519
  Handle<Object> class_name = Handle<Object>(obj->class_name(), isolate());
1520
  if (class_name->IsString()) {
1521
    result->shared()->set_instance_class_name(*class_name);
1522
    result->shared()->set_name(*class_name);
1523
  }
1524

    
1525
  Handle<Map> map = Handle<Map>(result->initial_map());
1526

    
1527
  // Mark as undetectable if needed.
1528
  if (obj->undetectable()) {
1529
    map->set_is_undetectable();
1530
  }
1531

    
1532
  // Mark as hidden for the __proto__ accessor if needed.
1533
  if (obj->hidden_prototype()) {
1534
    map->set_is_hidden_prototype();
1535
  }
1536

    
1537
  // Mark as needs_access_check if needed.
1538
  if (obj->needs_access_check()) {
1539
    map->set_is_access_check_needed(true);
1540
  }
1541

    
1542
  // Set interceptor information in the map.
1543
  if (!obj->named_property_handler()->IsUndefined()) {
1544
    map->set_has_named_interceptor();
1545
  }
1546
  if (!obj->indexed_property_handler()->IsUndefined()) {
1547
    map->set_has_indexed_interceptor();
1548
  }
1549

    
1550
  // Set instance call-as-function information in the map.
1551
  if (!obj->instance_call_handler()->IsUndefined()) {
1552
    map->set_has_instance_call_handler();
1553
  }
1554

    
1555
  result->shared()->set_function_data(*obj);
1556
  result->shared()->set_construct_stub(*construct_stub);
1557
  result->shared()->DontAdaptArguments();
1558

    
1559
  // Recursively copy parent instance templates' accessors,
1560
  // 'data' may be modified.
1561
  int max_number_of_additional_properties = 0;
1562
  int max_number_of_static_properties = 0;
1563
  FunctionTemplateInfo* info = *obj;
1564
  while (true) {
1565
    if (!info->instance_template()->IsUndefined()) {
1566
      Object* props =
1567
          ObjectTemplateInfo::cast(
1568
              info->instance_template())->property_accessors();
1569
      if (!props->IsUndefined()) {
1570
        Handle<Object> props_handle(props, isolate());
1571
        NeanderArray props_array(props_handle);
1572
        max_number_of_additional_properties += props_array.length();
1573
      }
1574
    }
1575
    if (!info->property_accessors()->IsUndefined()) {
1576
      Object* props = info->property_accessors();
1577
      if (!props->IsUndefined()) {
1578
        Handle<Object> props_handle(props, isolate());
1579
        NeanderArray props_array(props_handle);
1580
        max_number_of_static_properties += props_array.length();
1581
      }
1582
    }
1583
    Object* parent = info->parent_template();
1584
    if (parent->IsUndefined()) break;
1585
    info = FunctionTemplateInfo::cast(parent);
1586
  }
1587

    
1588
  Map::EnsureDescriptorSlack(map, max_number_of_additional_properties);
1589

    
1590
  // Use a temporary FixedArray to acculumate static accessors
1591
  int valid_descriptors = 0;
1592
  Handle<FixedArray> array;
1593
  if (max_number_of_static_properties > 0) {
1594
    array = NewFixedArray(max_number_of_static_properties);
1595
  }
1596

    
1597
  while (true) {
1598
    // Install instance descriptors
1599
    if (!obj->instance_template()->IsUndefined()) {
1600
      Handle<ObjectTemplateInfo> instance =
1601
          Handle<ObjectTemplateInfo>(
1602
              ObjectTemplateInfo::cast(obj->instance_template()), isolate());
1603
      Handle<Object> props = Handle<Object>(instance->property_accessors(),
1604
                                            isolate());
1605
      if (!props->IsUndefined()) {
1606
        Map::AppendCallbackDescriptors(map, props);
1607
      }
1608
    }
1609
    // Accumulate static accessors
1610
    if (!obj->property_accessors()->IsUndefined()) {
1611
      Handle<Object> props = Handle<Object>(obj->property_accessors(),
1612
                                            isolate());
1613
      valid_descriptors =
1614
          AccessorInfo::AppendUnique(props, array, valid_descriptors);
1615
    }
1616
    // Climb parent chain
1617
    Handle<Object> parent = Handle<Object>(obj->parent_template(), isolate());
1618
    if (parent->IsUndefined()) break;
1619
    obj = Handle<FunctionTemplateInfo>::cast(parent);
1620
  }
1621

    
1622
  // Install accumulated static accessors
1623
  for (int i = 0; i < valid_descriptors; i++) {
1624
    Handle<AccessorInfo> accessor(AccessorInfo::cast(array->get(i)));
1625
    JSObject::SetAccessor(result, accessor);
1626
  }
1627

    
1628
  ASSERT(result->shared()->IsApiFunction());
1629
  return result;
1630
}
1631

    
1632

    
1633
Handle<MapCache> Factory::NewMapCache(int at_least_space_for) {
1634
  CALL_HEAP_FUNCTION(isolate(),
1635
                     MapCache::Allocate(isolate()->heap(),
1636
                                        at_least_space_for),
1637
                     MapCache);
1638
}
1639

    
1640

    
1641
MUST_USE_RESULT static MaybeObject* UpdateMapCacheWith(Context* context,
1642
                                                       FixedArray* keys,
1643
                                                       Map* map) {
1644
  Object* result;
1645
  { MaybeObject* maybe_result =
1646
        MapCache::cast(context->map_cache())->Put(keys, map);
1647
    if (!maybe_result->ToObject(&result)) return maybe_result;
1648
  }
1649
  context->set_map_cache(MapCache::cast(result));
1650
  return result;
1651
}
1652

    
1653

    
1654
Handle<MapCache> Factory::AddToMapCache(Handle<Context> context,
1655
                                        Handle<FixedArray> keys,
1656
                                        Handle<Map> map) {
1657
  CALL_HEAP_FUNCTION(isolate(),
1658
                     UpdateMapCacheWith(*context, *keys, *map), MapCache);
1659
}
1660

    
1661

    
1662
Handle<Map> Factory::ObjectLiteralMapFromCache(Handle<Context> context,
1663
                                               Handle<FixedArray> keys) {
1664
  if (context->map_cache()->IsUndefined()) {
1665
    // Allocate the new map cache for the native context.
1666
    Handle<MapCache> new_cache = NewMapCache(24);
1667
    context->set_map_cache(*new_cache);
1668
  }
1669
  // Check to see whether there is a matching element in the cache.
1670
  Handle<MapCache> cache =
1671
      Handle<MapCache>(MapCache::cast(context->map_cache()));
1672
  Handle<Object> result = Handle<Object>(cache->Lookup(*keys), isolate());
1673
  if (result->IsMap()) return Handle<Map>::cast(result);
1674
  // Create a new map and add it to the cache.
1675
  Handle<Map> map =
1676
      CopyMap(Handle<Map>(context->object_function()->initial_map()),
1677
              keys->length());
1678
  AddToMapCache(context, keys, map);
1679
  return Handle<Map>(map);
1680
}
1681

    
1682

    
1683
void Factory::SetRegExpAtomData(Handle<JSRegExp> regexp,
1684
                                JSRegExp::Type type,
1685
                                Handle<String> source,
1686
                                JSRegExp::Flags flags,
1687
                                Handle<Object> data) {
1688
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kAtomDataSize);
1689

    
1690
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1691
  store->set(JSRegExp::kSourceIndex, *source);
1692
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1693
  store->set(JSRegExp::kAtomPatternIndex, *data);
1694
  regexp->set_data(*store);
1695
}
1696

    
1697
void Factory::SetRegExpIrregexpData(Handle<JSRegExp> regexp,
1698
                                    JSRegExp::Type type,
1699
                                    Handle<String> source,
1700
                                    JSRegExp::Flags flags,
1701
                                    int capture_count) {
1702
  Handle<FixedArray> store = NewFixedArray(JSRegExp::kIrregexpDataSize);
1703
  Smi* uninitialized = Smi::FromInt(JSRegExp::kUninitializedValue);
1704
  store->set(JSRegExp::kTagIndex, Smi::FromInt(type));
1705
  store->set(JSRegExp::kSourceIndex, *source);
1706
  store->set(JSRegExp::kFlagsIndex, Smi::FromInt(flags.value()));
1707
  store->set(JSRegExp::kIrregexpASCIICodeIndex, uninitialized);
1708
  store->set(JSRegExp::kIrregexpUC16CodeIndex, uninitialized);
1709
  store->set(JSRegExp::kIrregexpASCIICodeSavedIndex, uninitialized);
1710
  store->set(JSRegExp::kIrregexpUC16CodeSavedIndex, uninitialized);
1711
  store->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(0));
1712
  store->set(JSRegExp::kIrregexpCaptureCountIndex,
1713
             Smi::FromInt(capture_count));
1714
  regexp->set_data(*store);
1715
}
1716

    
1717

    
1718

    
1719
void Factory::ConfigureInstance(Handle<FunctionTemplateInfo> desc,
1720
                                Handle<JSObject> instance,
1721
                                bool* pending_exception) {
1722
  // Configure the instance by adding the properties specified by the
1723
  // instance template.
1724
  Handle<Object> instance_template(desc->instance_template(), isolate());
1725
  if (!instance_template->IsUndefined()) {
1726
    Execution::ConfigureInstance(isolate(),
1727
                                 instance,
1728
                                 instance_template,
1729
                                 pending_exception);
1730
  } else {
1731
    *pending_exception = false;
1732
  }
1733
}
1734

    
1735

    
1736
Handle<Object> Factory::GlobalConstantFor(Handle<String> name) {
1737
  Heap* h = isolate()->heap();
1738
  if (name->Equals(h->undefined_string())) return undefined_value();
1739
  if (name->Equals(h->nan_string())) return nan_value();
1740
  if (name->Equals(h->infinity_string())) return infinity_value();
1741
  return Handle<Object>::null();
1742
}
1743

    
1744

    
1745
Handle<Object> Factory::ToBoolean(bool value) {
1746
  return value ? true_value() : false_value();
1747
}
1748

    
1749

    
1750
} }  // namespace v8::internal