6e686e334689e6f3de1595bd3d5717177bdf76fa
[platform/upstream/v8.git] / src / ppc / code-stubs-ppc.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/v8.h"
6
7 #if V8_TARGET_ARCH_PPC
8
9 #include "src/base/bits.h"
10 #include "src/bootstrapper.h"
11 #include "src/code-stubs.h"
12 #include "src/codegen.h"
13 #include "src/ic/handler-compiler.h"
14 #include "src/ic/ic.h"
15 #include "src/ic/stub-cache.h"
16 #include "src/isolate.h"
17 #include "src/jsregexp.h"
18 #include "src/regexp-macro-assembler.h"
19 #include "src/runtime/runtime.h"
20
21 namespace v8 {
22 namespace internal {
23
24
25 static void InitializeArrayConstructorDescriptor(
26     Isolate* isolate, CodeStubDescriptor* descriptor,
27     int constant_stack_parameter_count) {
28   Address deopt_handler =
29       Runtime::FunctionForId(Runtime::kArrayConstructor)->entry;
30
31   if (constant_stack_parameter_count == 0) {
32     descriptor->Initialize(deopt_handler, constant_stack_parameter_count,
33                            JS_FUNCTION_STUB_MODE);
34   } else {
35     descriptor->Initialize(r3, deopt_handler, constant_stack_parameter_count,
36                            JS_FUNCTION_STUB_MODE, PASS_ARGUMENTS);
37   }
38 }
39
40
41 static void InitializeInternalArrayConstructorDescriptor(
42     Isolate* isolate, CodeStubDescriptor* descriptor,
43     int constant_stack_parameter_count) {
44   Address deopt_handler =
45       Runtime::FunctionForId(Runtime::kInternalArrayConstructor)->entry;
46
47   if (constant_stack_parameter_count == 0) {
48     descriptor->Initialize(deopt_handler, constant_stack_parameter_count,
49                            JS_FUNCTION_STUB_MODE);
50   } else {
51     descriptor->Initialize(r3, deopt_handler, constant_stack_parameter_count,
52                            JS_FUNCTION_STUB_MODE, PASS_ARGUMENTS);
53   }
54 }
55
56
57 void ArrayNoArgumentConstructorStub::InitializeDescriptor(
58     CodeStubDescriptor* descriptor) {
59   InitializeArrayConstructorDescriptor(isolate(), descriptor, 0);
60 }
61
62
63 void ArraySingleArgumentConstructorStub::InitializeDescriptor(
64     CodeStubDescriptor* descriptor) {
65   InitializeArrayConstructorDescriptor(isolate(), descriptor, 1);
66 }
67
68
69 void ArrayNArgumentsConstructorStub::InitializeDescriptor(
70     CodeStubDescriptor* descriptor) {
71   InitializeArrayConstructorDescriptor(isolate(), descriptor, -1);
72 }
73
74
75 void InternalArrayNoArgumentConstructorStub::InitializeDescriptor(
76     CodeStubDescriptor* descriptor) {
77   InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, 0);
78 }
79
80
81 void InternalArraySingleArgumentConstructorStub::InitializeDescriptor(
82     CodeStubDescriptor* descriptor) {
83   InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, 1);
84 }
85
86
87 void InternalArrayNArgumentsConstructorStub::InitializeDescriptor(
88     CodeStubDescriptor* descriptor) {
89   InitializeInternalArrayConstructorDescriptor(isolate(), descriptor, -1);
90 }
91
92
93 #define __ ACCESS_MASM(masm)
94
95
96 static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow,
97                                           Condition cond, bool strong);
98 static void EmitSmiNonsmiComparison(MacroAssembler* masm, Register lhs,
99                                     Register rhs, Label* lhs_not_nan,
100                                     Label* slow, bool strict);
101 static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm, Register lhs,
102                                            Register rhs);
103
104
105 void HydrogenCodeStub::GenerateLightweightMiss(MacroAssembler* masm,
106                                                ExternalReference miss) {
107   // Update the static counter each time a new code stub is generated.
108   isolate()->counters()->code_stubs()->Increment();
109
110   CallInterfaceDescriptor descriptor = GetCallInterfaceDescriptor();
111   int param_count = descriptor.GetEnvironmentParameterCount();
112   {
113     // Call the runtime system in a fresh internal frame.
114     FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
115     DCHECK(param_count == 0 ||
116            r3.is(descriptor.GetEnvironmentParameterRegister(param_count - 1)));
117     // Push arguments
118     for (int i = 0; i < param_count; ++i) {
119       __ push(descriptor.GetEnvironmentParameterRegister(i));
120     }
121     __ CallExternalReference(miss, param_count);
122   }
123
124   __ Ret();
125 }
126
127
128 void DoubleToIStub::Generate(MacroAssembler* masm) {
129   Label out_of_range, only_low, negate, done, fastpath_done;
130   Register input_reg = source();
131   Register result_reg = destination();
132   DCHECK(is_truncating());
133
134   int double_offset = offset();
135
136   // Immediate values for this stub fit in instructions, so it's safe to use ip.
137   Register scratch = GetRegisterThatIsNotOneOf(input_reg, result_reg);
138   Register scratch_low =
139       GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch);
140   Register scratch_high =
141       GetRegisterThatIsNotOneOf(input_reg, result_reg, scratch, scratch_low);
142   DoubleRegister double_scratch = kScratchDoubleReg;
143
144   __ push(scratch);
145   // Account for saved regs if input is sp.
146   if (input_reg.is(sp)) double_offset += kPointerSize;
147
148   if (!skip_fastpath()) {
149     // Load double input.
150     __ lfd(double_scratch, MemOperand(input_reg, double_offset));
151
152     // Do fast-path convert from double to int.
153     __ ConvertDoubleToInt64(double_scratch,
154 #if !V8_TARGET_ARCH_PPC64
155                             scratch,
156 #endif
157                             result_reg, d0);
158
159 // Test for overflow
160 #if V8_TARGET_ARCH_PPC64
161     __ TestIfInt32(result_reg, r0);
162 #else
163     __ TestIfInt32(scratch, result_reg, r0);
164 #endif
165     __ beq(&fastpath_done);
166   }
167
168   __ Push(scratch_high, scratch_low);
169   // Account for saved regs if input is sp.
170   if (input_reg.is(sp)) double_offset += 2 * kPointerSize;
171
172   __ lwz(scratch_high,
173          MemOperand(input_reg, double_offset + Register::kExponentOffset));
174   __ lwz(scratch_low,
175          MemOperand(input_reg, double_offset + Register::kMantissaOffset));
176
177   __ ExtractBitMask(scratch, scratch_high, HeapNumber::kExponentMask);
178   // Load scratch with exponent - 1. This is faster than loading
179   // with exponent because Bias + 1 = 1024 which is a *PPC* immediate value.
180   STATIC_ASSERT(HeapNumber::kExponentBias + 1 == 1024);
181   __ subi(scratch, scratch, Operand(HeapNumber::kExponentBias + 1));
182   // If exponent is greater than or equal to 84, the 32 less significant
183   // bits are 0s (2^84 = 1, 52 significant bits, 32 uncoded bits),
184   // the result is 0.
185   // Compare exponent with 84 (compare exponent - 1 with 83).
186   __ cmpi(scratch, Operand(83));
187   __ bge(&out_of_range);
188
189   // If we reach this code, 31 <= exponent <= 83.
190   // So, we don't have to handle cases where 0 <= exponent <= 20 for
191   // which we would need to shift right the high part of the mantissa.
192   // Scratch contains exponent - 1.
193   // Load scratch with 52 - exponent (load with 51 - (exponent - 1)).
194   __ subfic(scratch, scratch, Operand(51));
195   __ cmpi(scratch, Operand::Zero());
196   __ ble(&only_low);
197   // 21 <= exponent <= 51, shift scratch_low and scratch_high
198   // to generate the result.
199   __ srw(scratch_low, scratch_low, scratch);
200   // Scratch contains: 52 - exponent.
201   // We needs: exponent - 20.
202   // So we use: 32 - scratch = 32 - 52 + exponent = exponent - 20.
203   __ subfic(scratch, scratch, Operand(32));
204   __ ExtractBitMask(result_reg, scratch_high, HeapNumber::kMantissaMask);
205   // Set the implicit 1 before the mantissa part in scratch_high.
206   STATIC_ASSERT(HeapNumber::kMantissaBitsInTopWord >= 16);
207   __ oris(result_reg, result_reg,
208           Operand(1 << ((HeapNumber::kMantissaBitsInTopWord) - 16)));
209   __ slw(r0, result_reg, scratch);
210   __ orx(result_reg, scratch_low, r0);
211   __ b(&negate);
212
213   __ bind(&out_of_range);
214   __ mov(result_reg, Operand::Zero());
215   __ b(&done);
216
217   __ bind(&only_low);
218   // 52 <= exponent <= 83, shift only scratch_low.
219   // On entry, scratch contains: 52 - exponent.
220   __ neg(scratch, scratch);
221   __ slw(result_reg, scratch_low, scratch);
222
223   __ bind(&negate);
224   // If input was positive, scratch_high ASR 31 equals 0 and
225   // scratch_high LSR 31 equals zero.
226   // New result = (result eor 0) + 0 = result.
227   // If the input was negative, we have to negate the result.
228   // Input_high ASR 31 equals 0xffffffff and scratch_high LSR 31 equals 1.
229   // New result = (result eor 0xffffffff) + 1 = 0 - result.
230   __ srawi(r0, scratch_high, 31);
231 #if V8_TARGET_ARCH_PPC64
232   __ srdi(r0, r0, Operand(32));
233 #endif
234   __ xor_(result_reg, result_reg, r0);
235   __ srwi(r0, scratch_high, Operand(31));
236   __ add(result_reg, result_reg, r0);
237
238   __ bind(&done);
239   __ Pop(scratch_high, scratch_low);
240
241   __ bind(&fastpath_done);
242   __ pop(scratch);
243
244   __ Ret();
245 }
246
247
248 // Handle the case where the lhs and rhs are the same object.
249 // Equality is almost reflexive (everything but NaN), so this is a test
250 // for "identity and not NaN".
251 static void EmitIdenticalObjectComparison(MacroAssembler* masm, Label* slow,
252                                           Condition cond, bool strong) {
253   Label not_identical;
254   Label heap_number, return_equal;
255   __ cmp(r3, r4);
256   __ bne(&not_identical);
257
258   // Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
259   // so we do the second best thing - test it ourselves.
260   // They are both equal and they are not both Smis so both of them are not
261   // Smis.  If it's not a heap number, then return equal.
262   if (cond == lt || cond == gt) {
263     // Call runtime on identical JSObjects.
264     __ CompareObjectType(r3, r7, r7, FIRST_SPEC_OBJECT_TYPE);
265     __ bge(slow);
266     // Call runtime on identical symbols since we need to throw a TypeError.
267     __ cmpi(r7, Operand(SYMBOL_TYPE));
268     __ beq(slow);
269     if (strong) {
270       // Call the runtime on anything that is converted in the semantics, since
271       // we need to throw a TypeError. Smis have already been ruled out.
272       __ cmpi(r7, Operand(HEAP_NUMBER_TYPE));
273       __ beq(&return_equal);
274       __ andi(r0, r7, Operand(kIsNotStringMask));
275       __ bne(slow, cr0);
276     }
277   } else {
278     __ CompareObjectType(r3, r7, r7, HEAP_NUMBER_TYPE);
279     __ beq(&heap_number);
280     // Comparing JS objects with <=, >= is complicated.
281     if (cond != eq) {
282       __ cmpi(r7, Operand(FIRST_SPEC_OBJECT_TYPE));
283       __ bge(slow);
284       // Call runtime on identical symbols since we need to throw a TypeError.
285       __ cmpi(r7, Operand(SYMBOL_TYPE));
286       __ beq(slow);
287       if (strong) {
288         // Call the runtime on anything that is converted in the semantics,
289         // since we need to throw a TypeError. Smis and heap numbers have
290         // already been ruled out.
291         __ andi(r0, r7, Operand(kIsNotStringMask));
292         __ bne(slow, cr0);
293       }
294       // Normally here we fall through to return_equal, but undefined is
295       // special: (undefined == undefined) == true, but
296       // (undefined <= undefined) == false!  See ECMAScript 11.8.5.
297       if (cond == le || cond == ge) {
298         __ cmpi(r7, Operand(ODDBALL_TYPE));
299         __ bne(&return_equal);
300         __ LoadRoot(r5, Heap::kUndefinedValueRootIndex);
301         __ cmp(r3, r5);
302         __ bne(&return_equal);
303         if (cond == le) {
304           // undefined <= undefined should fail.
305           __ li(r3, Operand(GREATER));
306         } else {
307           // undefined >= undefined should fail.
308           __ li(r3, Operand(LESS));
309         }
310         __ Ret();
311       }
312     }
313   }
314
315   __ bind(&return_equal);
316   if (cond == lt) {
317     __ li(r3, Operand(GREATER));  // Things aren't less than themselves.
318   } else if (cond == gt) {
319     __ li(r3, Operand(LESS));  // Things aren't greater than themselves.
320   } else {
321     __ li(r3, Operand(EQUAL));  // Things are <=, >=, ==, === themselves.
322   }
323   __ Ret();
324
325   // For less and greater we don't have to check for NaN since the result of
326   // x < x is false regardless.  For the others here is some code to check
327   // for NaN.
328   if (cond != lt && cond != gt) {
329     __ bind(&heap_number);
330     // It is a heap number, so return non-equal if it's NaN and equal if it's
331     // not NaN.
332
333     // The representation of NaN values has all exponent bits (52..62) set,
334     // and not all mantissa bits (0..51) clear.
335     // Read top bits of double representation (second word of value).
336     __ lwz(r5, FieldMemOperand(r3, HeapNumber::kExponentOffset));
337     // Test that exponent bits are all set.
338     STATIC_ASSERT(HeapNumber::kExponentMask == 0x7ff00000u);
339     __ ExtractBitMask(r6, r5, HeapNumber::kExponentMask);
340     __ cmpli(r6, Operand(0x7ff));
341     __ bne(&return_equal);
342
343     // Shift out flag and all exponent bits, retaining only mantissa.
344     __ slwi(r5, r5, Operand(HeapNumber::kNonMantissaBitsInTopWord));
345     // Or with all low-bits of mantissa.
346     __ lwz(r6, FieldMemOperand(r3, HeapNumber::kMantissaOffset));
347     __ orx(r3, r6, r5);
348     __ cmpi(r3, Operand::Zero());
349     // For equal we already have the right value in r3:  Return zero (equal)
350     // if all bits in mantissa are zero (it's an Infinity) and non-zero if
351     // not (it's a NaN).  For <= and >= we need to load r0 with the failing
352     // value if it's a NaN.
353     if (cond != eq) {
354       if (CpuFeatures::IsSupported(ISELECT)) {
355         __ li(r4, Operand((cond == le) ? GREATER : LESS));
356         __ isel(eq, r3, r3, r4);
357       } else {
358         Label not_equal;
359         __ bne(&not_equal);
360         // All-zero means Infinity means equal.
361         __ Ret();
362         __ bind(&not_equal);
363         if (cond == le) {
364           __ li(r3, Operand(GREATER));  // NaN <= NaN should fail.
365         } else {
366           __ li(r3, Operand(LESS));  // NaN >= NaN should fail.
367         }
368       }
369     }
370     __ Ret();
371   }
372   // No fall through here.
373
374   __ bind(&not_identical);
375 }
376
377
378 // See comment at call site.
379 static void EmitSmiNonsmiComparison(MacroAssembler* masm, Register lhs,
380                                     Register rhs, Label* lhs_not_nan,
381                                     Label* slow, bool strict) {
382   DCHECK((lhs.is(r3) && rhs.is(r4)) || (lhs.is(r4) && rhs.is(r3)));
383
384   Label rhs_is_smi;
385   __ JumpIfSmi(rhs, &rhs_is_smi);
386
387   // Lhs is a Smi.  Check whether the rhs is a heap number.
388   __ CompareObjectType(rhs, r6, r7, HEAP_NUMBER_TYPE);
389   if (strict) {
390     // If rhs is not a number and lhs is a Smi then strict equality cannot
391     // succeed.  Return non-equal
392     // If rhs is r3 then there is already a non zero value in it.
393     Label skip;
394     __ beq(&skip);
395     if (!rhs.is(r3)) {
396       __ mov(r3, Operand(NOT_EQUAL));
397     }
398     __ Ret();
399     __ bind(&skip);
400   } else {
401     // Smi compared non-strictly with a non-Smi non-heap-number.  Call
402     // the runtime.
403     __ bne(slow);
404   }
405
406   // Lhs is a smi, rhs is a number.
407   // Convert lhs to a double in d7.
408   __ SmiToDouble(d7, lhs);
409   // Load the double from rhs, tagged HeapNumber r3, to d6.
410   __ lfd(d6, FieldMemOperand(rhs, HeapNumber::kValueOffset));
411
412   // We now have both loaded as doubles but we can skip the lhs nan check
413   // since it's a smi.
414   __ b(lhs_not_nan);
415
416   __ bind(&rhs_is_smi);
417   // Rhs is a smi.  Check whether the non-smi lhs is a heap number.
418   __ CompareObjectType(lhs, r7, r7, HEAP_NUMBER_TYPE);
419   if (strict) {
420     // If lhs is not a number and rhs is a smi then strict equality cannot
421     // succeed.  Return non-equal.
422     // If lhs is r3 then there is already a non zero value in it.
423     Label skip;
424     __ beq(&skip);
425     if (!lhs.is(r3)) {
426       __ mov(r3, Operand(NOT_EQUAL));
427     }
428     __ Ret();
429     __ bind(&skip);
430   } else {
431     // Smi compared non-strictly with a non-smi non-heap-number.  Call
432     // the runtime.
433     __ bne(slow);
434   }
435
436   // Rhs is a smi, lhs is a heap number.
437   // Load the double from lhs, tagged HeapNumber r4, to d7.
438   __ lfd(d7, FieldMemOperand(lhs, HeapNumber::kValueOffset));
439   // Convert rhs to a double in d6.
440   __ SmiToDouble(d6, rhs);
441   // Fall through to both_loaded_as_doubles.
442 }
443
444
445 // See comment at call site.
446 static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm, Register lhs,
447                                            Register rhs) {
448   DCHECK((lhs.is(r3) && rhs.is(r4)) || (lhs.is(r4) && rhs.is(r3)));
449
450   // If either operand is a JS object or an oddball value, then they are
451   // not equal since their pointers are different.
452   // There is no test for undetectability in strict equality.
453   STATIC_ASSERT(LAST_TYPE == LAST_SPEC_OBJECT_TYPE);
454   Label first_non_object;
455   // Get the type of the first operand into r5 and compare it with
456   // FIRST_SPEC_OBJECT_TYPE.
457   __ CompareObjectType(rhs, r5, r5, FIRST_SPEC_OBJECT_TYPE);
458   __ blt(&first_non_object);
459
460   // Return non-zero (r3 is not zero)
461   Label return_not_equal;
462   __ bind(&return_not_equal);
463   __ Ret();
464
465   __ bind(&first_non_object);
466   // Check for oddballs: true, false, null, undefined.
467   __ cmpi(r5, Operand(ODDBALL_TYPE));
468   __ beq(&return_not_equal);
469
470   __ CompareObjectType(lhs, r6, r6, FIRST_SPEC_OBJECT_TYPE);
471   __ bge(&return_not_equal);
472
473   // Check for oddballs: true, false, null, undefined.
474   __ cmpi(r6, Operand(ODDBALL_TYPE));
475   __ beq(&return_not_equal);
476
477   // Now that we have the types we might as well check for
478   // internalized-internalized.
479   STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
480   __ orx(r5, r5, r6);
481   __ andi(r0, r5, Operand(kIsNotStringMask | kIsNotInternalizedMask));
482   __ beq(&return_not_equal, cr0);
483 }
484
485
486 // See comment at call site.
487 static void EmitCheckForTwoHeapNumbers(MacroAssembler* masm, Register lhs,
488                                        Register rhs,
489                                        Label* both_loaded_as_doubles,
490                                        Label* not_heap_numbers, Label* slow) {
491   DCHECK((lhs.is(r3) && rhs.is(r4)) || (lhs.is(r4) && rhs.is(r3)));
492
493   __ CompareObjectType(rhs, r6, r5, HEAP_NUMBER_TYPE);
494   __ bne(not_heap_numbers);
495   __ LoadP(r5, FieldMemOperand(lhs, HeapObject::kMapOffset));
496   __ cmp(r5, r6);
497   __ bne(slow);  // First was a heap number, second wasn't.  Go slow case.
498
499   // Both are heap numbers.  Load them up then jump to the code we have
500   // for that.
501   __ lfd(d6, FieldMemOperand(rhs, HeapNumber::kValueOffset));
502   __ lfd(d7, FieldMemOperand(lhs, HeapNumber::kValueOffset));
503
504   __ b(both_loaded_as_doubles);
505 }
506
507
508 // Fast negative check for internalized-to-internalized equality.
509 static void EmitCheckForInternalizedStringsOrObjects(MacroAssembler* masm,
510                                                      Register lhs, Register rhs,
511                                                      Label* possible_strings,
512                                                      Label* not_both_strings) {
513   DCHECK((lhs.is(r3) && rhs.is(r4)) || (lhs.is(r4) && rhs.is(r3)));
514
515   // r5 is object type of rhs.
516   Label object_test;
517   STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
518   __ andi(r0, r5, Operand(kIsNotStringMask));
519   __ bne(&object_test, cr0);
520   __ andi(r0, r5, Operand(kIsNotInternalizedMask));
521   __ bne(possible_strings, cr0);
522   __ CompareObjectType(lhs, r6, r6, FIRST_NONSTRING_TYPE);
523   __ bge(not_both_strings);
524   __ andi(r0, r6, Operand(kIsNotInternalizedMask));
525   __ bne(possible_strings, cr0);
526
527   // Both are internalized.  We already checked they weren't the same pointer
528   // so they are not equal.
529   __ li(r3, Operand(NOT_EQUAL));
530   __ Ret();
531
532   __ bind(&object_test);
533   __ cmpi(r5, Operand(FIRST_SPEC_OBJECT_TYPE));
534   __ blt(not_both_strings);
535   __ CompareObjectType(lhs, r5, r6, FIRST_SPEC_OBJECT_TYPE);
536   __ blt(not_both_strings);
537   // If both objects are undetectable, they are equal. Otherwise, they
538   // are not equal, since they are different objects and an object is not
539   // equal to undefined.
540   __ LoadP(r6, FieldMemOperand(rhs, HeapObject::kMapOffset));
541   __ lbz(r5, FieldMemOperand(r5, Map::kBitFieldOffset));
542   __ lbz(r6, FieldMemOperand(r6, Map::kBitFieldOffset));
543   __ and_(r3, r5, r6);
544   __ andi(r3, r3, Operand(1 << Map::kIsUndetectable));
545   __ xori(r3, r3, Operand(1 << Map::kIsUndetectable));
546   __ Ret();
547 }
548
549
550 static void CompareICStub_CheckInputType(MacroAssembler* masm, Register input,
551                                          Register scratch,
552                                          CompareICState::State expected,
553                                          Label* fail) {
554   Label ok;
555   if (expected == CompareICState::SMI) {
556     __ JumpIfNotSmi(input, fail);
557   } else if (expected == CompareICState::NUMBER) {
558     __ JumpIfSmi(input, &ok);
559     __ CheckMap(input, scratch, Heap::kHeapNumberMapRootIndex, fail,
560                 DONT_DO_SMI_CHECK);
561   }
562   // We could be strict about internalized/non-internalized here, but as long as
563   // hydrogen doesn't care, the stub doesn't have to care either.
564   __ bind(&ok);
565 }
566
567
568 // On entry r4 and r5 are the values to be compared.
569 // On exit r3 is 0, positive or negative to indicate the result of
570 // the comparison.
571 void CompareICStub::GenerateGeneric(MacroAssembler* masm) {
572   Register lhs = r4;
573   Register rhs = r3;
574   Condition cc = GetCondition();
575
576   Label miss;
577   CompareICStub_CheckInputType(masm, lhs, r5, left(), &miss);
578   CompareICStub_CheckInputType(masm, rhs, r6, right(), &miss);
579
580   Label slow;  // Call builtin.
581   Label not_smis, both_loaded_as_doubles, lhs_not_nan;
582
583   Label not_two_smis, smi_done;
584   __ orx(r5, r4, r3);
585   __ JumpIfNotSmi(r5, &not_two_smis);
586   __ SmiUntag(r4);
587   __ SmiUntag(r3);
588   __ sub(r3, r4, r3);
589   __ Ret();
590   __ bind(&not_two_smis);
591
592   // NOTICE! This code is only reached after a smi-fast-case check, so
593   // it is certain that at least one operand isn't a smi.
594
595   // Handle the case where the objects are identical.  Either returns the answer
596   // or goes to slow.  Only falls through if the objects were not identical.
597   EmitIdenticalObjectComparison(masm, &slow, cc, strong());
598
599   // If either is a Smi (we know that not both are), then they can only
600   // be strictly equal if the other is a HeapNumber.
601   STATIC_ASSERT(kSmiTag == 0);
602   DCHECK_EQ(static_cast<Smi*>(0), Smi::FromInt(0));
603   __ and_(r5, lhs, rhs);
604   __ JumpIfNotSmi(r5, &not_smis);
605   // One operand is a smi.  EmitSmiNonsmiComparison generates code that can:
606   // 1) Return the answer.
607   // 2) Go to slow.
608   // 3) Fall through to both_loaded_as_doubles.
609   // 4) Jump to lhs_not_nan.
610   // In cases 3 and 4 we have found out we were dealing with a number-number
611   // comparison.  The double values of the numbers have been loaded
612   // into d7 and d6.
613   EmitSmiNonsmiComparison(masm, lhs, rhs, &lhs_not_nan, &slow, strict());
614
615   __ bind(&both_loaded_as_doubles);
616   // The arguments have been converted to doubles and stored in d6 and d7
617   __ bind(&lhs_not_nan);
618   Label no_nan;
619   __ fcmpu(d7, d6);
620
621   Label nan, equal, less_than;
622   __ bunordered(&nan);
623   if (CpuFeatures::IsSupported(ISELECT)) {
624     DCHECK(EQUAL == 0);
625     __ li(r4, Operand(GREATER));
626     __ li(r5, Operand(LESS));
627     __ isel(eq, r3, r0, r4);
628     __ isel(lt, r3, r5, r3);
629     __ Ret();
630   } else {
631     __ beq(&equal);
632     __ blt(&less_than);
633     __ li(r3, Operand(GREATER));
634     __ Ret();
635     __ bind(&equal);
636     __ li(r3, Operand(EQUAL));
637     __ Ret();
638     __ bind(&less_than);
639     __ li(r3, Operand(LESS));
640     __ Ret();
641   }
642
643   __ bind(&nan);
644   // If one of the sides was a NaN then the v flag is set.  Load r3 with
645   // whatever it takes to make the comparison fail, since comparisons with NaN
646   // always fail.
647   if (cc == lt || cc == le) {
648     __ li(r3, Operand(GREATER));
649   } else {
650     __ li(r3, Operand(LESS));
651   }
652   __ Ret();
653
654   __ bind(&not_smis);
655   // At this point we know we are dealing with two different objects,
656   // and neither of them is a Smi.  The objects are in rhs_ and lhs_.
657   if (strict()) {
658     // This returns non-equal for some object types, or falls through if it
659     // was not lucky.
660     EmitStrictTwoHeapObjectCompare(masm, lhs, rhs);
661   }
662
663   Label check_for_internalized_strings;
664   Label flat_string_check;
665   // Check for heap-number-heap-number comparison.  Can jump to slow case,
666   // or load both doubles into r3, r4, r5, r6 and jump to the code that handles
667   // that case.  If the inputs are not doubles then jumps to
668   // check_for_internalized_strings.
669   // In this case r5 will contain the type of rhs_.  Never falls through.
670   EmitCheckForTwoHeapNumbers(masm, lhs, rhs, &both_loaded_as_doubles,
671                              &check_for_internalized_strings,
672                              &flat_string_check);
673
674   __ bind(&check_for_internalized_strings);
675   // In the strict case the EmitStrictTwoHeapObjectCompare already took care of
676   // internalized strings.
677   if (cc == eq && !strict()) {
678     // Returns an answer for two internalized strings or two detectable objects.
679     // Otherwise jumps to string case or not both strings case.
680     // Assumes that r5 is the type of rhs_ on entry.
681     EmitCheckForInternalizedStringsOrObjects(masm, lhs, rhs, &flat_string_check,
682                                              &slow);
683   }
684
685   // Check for both being sequential one-byte strings,
686   // and inline if that is the case.
687   __ bind(&flat_string_check);
688
689   __ JumpIfNonSmisNotBothSequentialOneByteStrings(lhs, rhs, r5, r6, &slow);
690
691   __ IncrementCounter(isolate()->counters()->string_compare_native(), 1, r5,
692                       r6);
693   if (cc == eq) {
694     StringHelper::GenerateFlatOneByteStringEquals(masm, lhs, rhs, r5, r6);
695   } else {
696     StringHelper::GenerateCompareFlatOneByteStrings(masm, lhs, rhs, r5, r6, r7);
697   }
698   // Never falls through to here.
699
700   __ bind(&slow);
701
702   __ Push(lhs, rhs);
703   // Figure out which native to call and setup the arguments.
704   Builtins::JavaScript native;
705   if (cc == eq) {
706     native = strict() ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
707   } else {
708     native = strong() ? Builtins::COMPARE_STRONG : Builtins::COMPARE;
709     int ncr;  // NaN compare result
710     if (cc == lt || cc == le) {
711       ncr = GREATER;
712     } else {
713       DCHECK(cc == gt || cc == ge);  // remaining cases
714       ncr = LESS;
715     }
716     __ LoadSmiLiteral(r3, Smi::FromInt(ncr));
717     __ push(r3);
718   }
719
720   // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
721   // tagged as a small integer.
722   __ InvokeBuiltin(native, JUMP_FUNCTION);
723
724   __ bind(&miss);
725   GenerateMiss(masm);
726 }
727
728
729 void StoreBufferOverflowStub::Generate(MacroAssembler* masm) {
730   // We don't allow a GC during a store buffer overflow so there is no need to
731   // store the registers in any particular way, but we do have to store and
732   // restore them.
733   __ mflr(r0);
734   __ MultiPush(kJSCallerSaved | r0.bit());
735   if (save_doubles()) {
736     __ SaveFPRegs(sp, 0, DoubleRegister::kNumVolatileRegisters);
737   }
738   const int argument_count = 1;
739   const int fp_argument_count = 0;
740   const Register scratch = r4;
741
742   AllowExternalCallThatCantCauseGC scope(masm);
743   __ PrepareCallCFunction(argument_count, fp_argument_count, scratch);
744   __ mov(r3, Operand(ExternalReference::isolate_address(isolate())));
745   __ CallCFunction(ExternalReference::store_buffer_overflow_function(isolate()),
746                    argument_count);
747   if (save_doubles()) {
748     __ RestoreFPRegs(sp, 0, DoubleRegister::kNumVolatileRegisters);
749   }
750   __ MultiPop(kJSCallerSaved | r0.bit());
751   __ mtlr(r0);
752   __ Ret();
753 }
754
755
756 void StoreRegistersStateStub::Generate(MacroAssembler* masm) {
757   __ PushSafepointRegisters();
758   __ blr();
759 }
760
761
762 void RestoreRegistersStateStub::Generate(MacroAssembler* masm) {
763   __ PopSafepointRegisters();
764   __ blr();
765 }
766
767
768 void MathPowStub::Generate(MacroAssembler* masm) {
769   const Register base = r4;
770   const Register exponent = MathPowTaggedDescriptor::exponent();
771   DCHECK(exponent.is(r5));
772   const Register heapnumbermap = r8;
773   const Register heapnumber = r3;
774   const DoubleRegister double_base = d1;
775   const DoubleRegister double_exponent = d2;
776   const DoubleRegister double_result = d3;
777   const DoubleRegister double_scratch = d0;
778   const Register scratch = r11;
779   const Register scratch2 = r10;
780
781   Label call_runtime, done, int_exponent;
782   if (exponent_type() == ON_STACK) {
783     Label base_is_smi, unpack_exponent;
784     // The exponent and base are supplied as arguments on the stack.
785     // This can only happen if the stub is called from non-optimized code.
786     // Load input parameters from stack to double registers.
787     __ LoadP(base, MemOperand(sp, 1 * kPointerSize));
788     __ LoadP(exponent, MemOperand(sp, 0 * kPointerSize));
789
790     __ LoadRoot(heapnumbermap, Heap::kHeapNumberMapRootIndex);
791
792     __ UntagAndJumpIfSmi(scratch, base, &base_is_smi);
793     __ LoadP(scratch, FieldMemOperand(base, JSObject::kMapOffset));
794     __ cmp(scratch, heapnumbermap);
795     __ bne(&call_runtime);
796
797     __ lfd(double_base, FieldMemOperand(base, HeapNumber::kValueOffset));
798     __ b(&unpack_exponent);
799
800     __ bind(&base_is_smi);
801     __ ConvertIntToDouble(scratch, double_base);
802     __ bind(&unpack_exponent);
803
804     __ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
805     __ LoadP(scratch, FieldMemOperand(exponent, JSObject::kMapOffset));
806     __ cmp(scratch, heapnumbermap);
807     __ bne(&call_runtime);
808
809     __ lfd(double_exponent,
810            FieldMemOperand(exponent, HeapNumber::kValueOffset));
811   } else if (exponent_type() == TAGGED) {
812     // Base is already in double_base.
813     __ UntagAndJumpIfSmi(scratch, exponent, &int_exponent);
814
815     __ lfd(double_exponent,
816            FieldMemOperand(exponent, HeapNumber::kValueOffset));
817   }
818
819   if (exponent_type() != INTEGER) {
820     // Detect integer exponents stored as double.
821     __ TryDoubleToInt32Exact(scratch, double_exponent, scratch2,
822                              double_scratch);
823     __ beq(&int_exponent);
824
825     if (exponent_type() == ON_STACK) {
826       // Detect square root case.  Crankshaft detects constant +/-0.5 at
827       // compile time and uses DoMathPowHalf instead.  We then skip this check
828       // for non-constant cases of +/-0.5 as these hardly occur.
829       Label not_plus_half, not_minus_inf1, not_minus_inf2;
830
831       // Test for 0.5.
832       __ LoadDoubleLiteral(double_scratch, 0.5, scratch);
833       __ fcmpu(double_exponent, double_scratch);
834       __ bne(&not_plus_half);
835
836       // Calculates square root of base.  Check for the special case of
837       // Math.pow(-Infinity, 0.5) == Infinity (ECMA spec, 15.8.2.13).
838       __ LoadDoubleLiteral(double_scratch, -V8_INFINITY, scratch);
839       __ fcmpu(double_base, double_scratch);
840       __ bne(&not_minus_inf1);
841       __ fneg(double_result, double_scratch);
842       __ b(&done);
843       __ bind(&not_minus_inf1);
844
845       // Add +0 to convert -0 to +0.
846       __ fadd(double_scratch, double_base, kDoubleRegZero);
847       __ fsqrt(double_result, double_scratch);
848       __ b(&done);
849
850       __ bind(&not_plus_half);
851       __ LoadDoubleLiteral(double_scratch, -0.5, scratch);
852       __ fcmpu(double_exponent, double_scratch);
853       __ bne(&call_runtime);
854
855       // Calculates square root of base.  Check for the special case of
856       // Math.pow(-Infinity, -0.5) == 0 (ECMA spec, 15.8.2.13).
857       __ LoadDoubleLiteral(double_scratch, -V8_INFINITY, scratch);
858       __ fcmpu(double_base, double_scratch);
859       __ bne(&not_minus_inf2);
860       __ fmr(double_result, kDoubleRegZero);
861       __ b(&done);
862       __ bind(&not_minus_inf2);
863
864       // Add +0 to convert -0 to +0.
865       __ fadd(double_scratch, double_base, kDoubleRegZero);
866       __ LoadDoubleLiteral(double_result, 1.0, scratch);
867       __ fsqrt(double_scratch, double_scratch);
868       __ fdiv(double_result, double_result, double_scratch);
869       __ b(&done);
870     }
871
872     __ mflr(r0);
873     __ push(r0);
874     {
875       AllowExternalCallThatCantCauseGC scope(masm);
876       __ PrepareCallCFunction(0, 2, scratch);
877       __ MovToFloatParameters(double_base, double_exponent);
878       __ CallCFunction(
879           ExternalReference::power_double_double_function(isolate()), 0, 2);
880     }
881     __ pop(r0);
882     __ mtlr(r0);
883     __ MovFromFloatResult(double_result);
884     __ b(&done);
885   }
886
887   // Calculate power with integer exponent.
888   __ bind(&int_exponent);
889
890   // Get two copies of exponent in the registers scratch and exponent.
891   if (exponent_type() == INTEGER) {
892     __ mr(scratch, exponent);
893   } else {
894     // Exponent has previously been stored into scratch as untagged integer.
895     __ mr(exponent, scratch);
896   }
897   __ fmr(double_scratch, double_base);  // Back up base.
898   __ li(scratch2, Operand(1));
899   __ ConvertIntToDouble(scratch2, double_result);
900
901   // Get absolute value of exponent.
902   __ cmpi(scratch, Operand::Zero());
903   if (CpuFeatures::IsSupported(ISELECT)) {
904     __ neg(scratch2, scratch);
905     __ isel(lt, scratch, scratch2, scratch);
906   } else {
907     Label positive_exponent;
908     __ bge(&positive_exponent);
909     __ neg(scratch, scratch);
910     __ bind(&positive_exponent);
911   }
912
913   Label while_true, no_carry, loop_end;
914   __ bind(&while_true);
915   __ andi(scratch2, scratch, Operand(1));
916   __ beq(&no_carry, cr0);
917   __ fmul(double_result, double_result, double_scratch);
918   __ bind(&no_carry);
919   __ ShiftRightArithImm(scratch, scratch, 1, SetRC);
920   __ beq(&loop_end, cr0);
921   __ fmul(double_scratch, double_scratch, double_scratch);
922   __ b(&while_true);
923   __ bind(&loop_end);
924
925   __ cmpi(exponent, Operand::Zero());
926   __ bge(&done);
927
928   __ li(scratch2, Operand(1));
929   __ ConvertIntToDouble(scratch2, double_scratch);
930   __ fdiv(double_result, double_scratch, double_result);
931   // Test whether result is zero.  Bail out to check for subnormal result.
932   // Due to subnormals, x^-y == (1/x)^y does not hold in all cases.
933   __ fcmpu(double_result, kDoubleRegZero);
934   __ bne(&done);
935   // double_exponent may not containe the exponent value if the input was a
936   // smi.  We set it with exponent value before bailing out.
937   __ ConvertIntToDouble(exponent, double_exponent);
938
939   // Returning or bailing out.
940   Counters* counters = isolate()->counters();
941   if (exponent_type() == ON_STACK) {
942     // The arguments are still on the stack.
943     __ bind(&call_runtime);
944     __ TailCallRuntime(Runtime::kMathPowRT, 2, 1);
945
946     // The stub is called from non-optimized code, which expects the result
947     // as heap number in exponent.
948     __ bind(&done);
949     __ AllocateHeapNumber(heapnumber, scratch, scratch2, heapnumbermap,
950                           &call_runtime);
951     __ stfd(double_result,
952             FieldMemOperand(heapnumber, HeapNumber::kValueOffset));
953     DCHECK(heapnumber.is(r3));
954     __ IncrementCounter(counters->math_pow(), 1, scratch, scratch2);
955     __ Ret(2);
956   } else {
957     __ mflr(r0);
958     __ push(r0);
959     {
960       AllowExternalCallThatCantCauseGC scope(masm);
961       __ PrepareCallCFunction(0, 2, scratch);
962       __ MovToFloatParameters(double_base, double_exponent);
963       __ CallCFunction(
964           ExternalReference::power_double_double_function(isolate()), 0, 2);
965     }
966     __ pop(r0);
967     __ mtlr(r0);
968     __ MovFromFloatResult(double_result);
969
970     __ bind(&done);
971     __ IncrementCounter(counters->math_pow(), 1, scratch, scratch2);
972     __ Ret();
973   }
974 }
975
976
977 bool CEntryStub::NeedsImmovableCode() { return true; }
978
979
980 void CodeStub::GenerateStubsAheadOfTime(Isolate* isolate) {
981   CEntryStub::GenerateAheadOfTime(isolate);
982   StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(isolate);
983   StubFailureTrampolineStub::GenerateAheadOfTime(isolate);
984   ArrayConstructorStubBase::GenerateStubsAheadOfTime(isolate);
985   CreateAllocationSiteStub::GenerateAheadOfTime(isolate);
986   CreateWeakCellStub::GenerateAheadOfTime(isolate);
987   BinaryOpICStub::GenerateAheadOfTime(isolate);
988   StoreRegistersStateStub::GenerateAheadOfTime(isolate);
989   RestoreRegistersStateStub::GenerateAheadOfTime(isolate);
990   BinaryOpICWithAllocationSiteStub::GenerateAheadOfTime(isolate);
991   StoreFastElementStub::GenerateAheadOfTime(isolate);
992   TypeofStub::GenerateAheadOfTime(isolate);
993 }
994
995
996 void StoreRegistersStateStub::GenerateAheadOfTime(Isolate* isolate) {
997   StoreRegistersStateStub stub(isolate);
998   stub.GetCode();
999 }
1000
1001
1002 void RestoreRegistersStateStub::GenerateAheadOfTime(Isolate* isolate) {
1003   RestoreRegistersStateStub stub(isolate);
1004   stub.GetCode();
1005 }
1006
1007
1008 void CodeStub::GenerateFPStubs(Isolate* isolate) {
1009   // Generate if not already in cache.
1010   SaveFPRegsMode mode = kSaveFPRegs;
1011   CEntryStub(isolate, 1, mode).GetCode();
1012   StoreBufferOverflowStub(isolate, mode).GetCode();
1013   isolate->set_fp_stubs_generated(true);
1014 }
1015
1016
1017 void CEntryStub::GenerateAheadOfTime(Isolate* isolate) {
1018   CEntryStub stub(isolate, 1, kDontSaveFPRegs);
1019   stub.GetCode();
1020 }
1021
1022
1023 void CEntryStub::Generate(MacroAssembler* masm) {
1024   // Called from JavaScript; parameters are on stack as if calling JS function.
1025   // r3: number of arguments including receiver
1026   // r4: pointer to builtin function
1027   // fp: frame pointer  (restored after C call)
1028   // sp: stack pointer  (restored as callee's sp after C call)
1029   // cp: current context  (C callee-saved)
1030
1031   ProfileEntryHookStub::MaybeCallEntryHook(masm);
1032
1033   __ mr(r15, r4);
1034
1035   // Compute the argv pointer.
1036   __ ShiftLeftImm(r4, r3, Operand(kPointerSizeLog2));
1037   __ add(r4, r4, sp);
1038   __ subi(r4, r4, Operand(kPointerSize));
1039
1040   // Enter the exit frame that transitions from JavaScript to C++.
1041   FrameScope scope(masm, StackFrame::MANUAL);
1042
1043   // Need at least one extra slot for return address location.
1044   int arg_stack_space = 1;
1045
1046 // PPC LINUX ABI:
1047 #if !ABI_RETURNS_OBJECT_PAIRS_IN_REGS
1048   // Pass buffer for return value on stack if necessary
1049   if (result_size() > 1) {
1050     DCHECK_EQ(2, result_size());
1051     arg_stack_space += 2;
1052   }
1053 #endif
1054
1055   __ EnterExitFrame(save_doubles(), arg_stack_space);
1056
1057   // Store a copy of argc in callee-saved registers for later.
1058   __ mr(r14, r3);
1059
1060   // r3, r14: number of arguments including receiver  (C callee-saved)
1061   // r4: pointer to the first argument
1062   // r15: pointer to builtin function  (C callee-saved)
1063
1064   // Result returned in registers or stack, depending on result size and ABI.
1065
1066   Register isolate_reg = r5;
1067 #if !ABI_RETURNS_OBJECT_PAIRS_IN_REGS
1068   if (result_size() > 1) {
1069     // The return value is 16-byte non-scalar value.
1070     // Use frame storage reserved by calling function to pass return
1071     // buffer as implicit first argument.
1072     __ mr(r5, r4);
1073     __ mr(r4, r3);
1074     __ addi(r3, sp, Operand((kStackFrameExtraParamSlot + 1) * kPointerSize));
1075     isolate_reg = r6;
1076   }
1077 #endif
1078
1079   // Call C built-in.
1080   __ mov(isolate_reg, Operand(ExternalReference::isolate_address(isolate())));
1081
1082 #if ABI_USES_FUNCTION_DESCRIPTORS && !defined(USE_SIMULATOR)
1083   // Native AIX/PPC64 Linux use a function descriptor.
1084   __ LoadP(ToRegister(ABI_TOC_REGISTER), MemOperand(r15, kPointerSize));
1085   __ LoadP(ip, MemOperand(r15, 0));  // Instruction address
1086   Register target = ip;
1087 #elif ABI_TOC_ADDRESSABILITY_VIA_IP
1088   __ Move(ip, r15);
1089   Register target = ip;
1090 #else
1091   Register target = r15;
1092 #endif
1093
1094   // To let the GC traverse the return address of the exit frames, we need to
1095   // know where the return address is. The CEntryStub is unmovable, so
1096   // we can store the address on the stack to be able to find it again and
1097   // we never have to restore it, because it will not change.
1098   Label after_call;
1099   __ mov_label_addr(r0, &after_call);
1100   __ StoreP(r0, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize));
1101   __ Call(target);
1102   __ bind(&after_call);
1103
1104 #if !ABI_RETURNS_OBJECT_PAIRS_IN_REGS
1105   // If return value is on the stack, pop it to registers.
1106   if (result_size() > 1) {
1107     __ LoadP(r4, MemOperand(r3, kPointerSize));
1108     __ LoadP(r3, MemOperand(r3));
1109   }
1110 #endif
1111
1112   // Check result for exception sentinel.
1113   Label exception_returned;
1114   __ CompareRoot(r3, Heap::kExceptionRootIndex);
1115   __ beq(&exception_returned);
1116
1117   // Check that there is no pending exception, otherwise we
1118   // should have returned the exception sentinel.
1119   if (FLAG_debug_code) {
1120     Label okay;
1121     ExternalReference pending_exception_address(
1122         Isolate::kPendingExceptionAddress, isolate());
1123
1124     __ mov(r5, Operand(pending_exception_address));
1125     __ LoadP(r5, MemOperand(r5));
1126     __ CompareRoot(r5, Heap::kTheHoleValueRootIndex);
1127     // Cannot use check here as it attempts to generate call into runtime.
1128     __ beq(&okay);
1129     __ stop("Unexpected pending exception");
1130     __ bind(&okay);
1131   }
1132
1133   // Exit C frame and return.
1134   // r3:r4: result
1135   // sp: stack pointer
1136   // fp: frame pointer
1137   // r14: still holds argc (callee-saved).
1138   __ LeaveExitFrame(save_doubles(), r14, true);
1139   __ blr();
1140
1141   // Handling of exception.
1142   __ bind(&exception_returned);
1143
1144   ExternalReference pending_handler_context_address(
1145       Isolate::kPendingHandlerContextAddress, isolate());
1146   ExternalReference pending_handler_code_address(
1147       Isolate::kPendingHandlerCodeAddress, isolate());
1148   ExternalReference pending_handler_offset_address(
1149       Isolate::kPendingHandlerOffsetAddress, isolate());
1150   ExternalReference pending_handler_fp_address(
1151       Isolate::kPendingHandlerFPAddress, isolate());
1152   ExternalReference pending_handler_sp_address(
1153       Isolate::kPendingHandlerSPAddress, isolate());
1154
1155   // Ask the runtime for help to determine the handler. This will set r3 to
1156   // contain the current pending exception, don't clobber it.
1157   ExternalReference find_handler(Runtime::kUnwindAndFindExceptionHandler,
1158                                  isolate());
1159   {
1160     FrameScope scope(masm, StackFrame::MANUAL);
1161     __ PrepareCallCFunction(3, 0, r3);
1162     __ li(r3, Operand::Zero());
1163     __ li(r4, Operand::Zero());
1164     __ mov(r5, Operand(ExternalReference::isolate_address(isolate())));
1165     __ CallCFunction(find_handler, 3);
1166   }
1167
1168   // Retrieve the handler context, SP and FP.
1169   __ mov(cp, Operand(pending_handler_context_address));
1170   __ LoadP(cp, MemOperand(cp));
1171   __ mov(sp, Operand(pending_handler_sp_address));
1172   __ LoadP(sp, MemOperand(sp));
1173   __ mov(fp, Operand(pending_handler_fp_address));
1174   __ LoadP(fp, MemOperand(fp));
1175
1176   // If the handler is a JS frame, restore the context to the frame. Note that
1177   // the context will be set to (cp == 0) for non-JS frames.
1178   Label skip;
1179   __ cmpi(cp, Operand::Zero());
1180   __ beq(&skip);
1181   __ StoreP(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
1182   __ bind(&skip);
1183
1184   // Compute the handler entry address and jump to it.
1185   ConstantPoolUnavailableScope constant_pool_unavailable(masm);
1186   __ mov(r4, Operand(pending_handler_code_address));
1187   __ LoadP(r4, MemOperand(r4));
1188   __ mov(r5, Operand(pending_handler_offset_address));
1189   __ LoadP(r5, MemOperand(r5));
1190   __ addi(r4, r4, Operand(Code::kHeaderSize - kHeapObjectTag));  // Code start
1191   if (FLAG_enable_embedded_constant_pool) {
1192     __ LoadConstantPoolPointerRegisterFromCodeTargetAddress(r4);
1193   }
1194   __ add(ip, r4, r5);
1195   __ Jump(ip);
1196 }
1197
1198
1199 void JSEntryStub::Generate(MacroAssembler* masm) {
1200   // r3: code entry
1201   // r4: function
1202   // r5: receiver
1203   // r6: argc
1204   // [sp+0]: argv
1205
1206   Label invoke, handler_entry, exit;
1207
1208 // Called from C
1209   __ function_descriptor();
1210
1211   ProfileEntryHookStub::MaybeCallEntryHook(masm);
1212
1213   // PPC LINUX ABI:
1214   // preserve LR in pre-reserved slot in caller's frame
1215   __ mflr(r0);
1216   __ StoreP(r0, MemOperand(sp, kStackFrameLRSlot * kPointerSize));
1217
1218   // Save callee saved registers on the stack.
1219   __ MultiPush(kCalleeSaved);
1220
1221   // Floating point regs FPR0 - FRP13 are volatile
1222   // FPR14-FPR31 are non-volatile, but sub-calls will save them for us
1223
1224   //  int offset_to_argv = kPointerSize * 22; // matches (22*4) above
1225   //  __ lwz(r7, MemOperand(sp, offset_to_argv));
1226
1227   // Push a frame with special values setup to mark it as an entry frame.
1228   // r3: code entry
1229   // r4: function
1230   // r5: receiver
1231   // r6: argc
1232   // r7: argv
1233   __ li(r0, Operand(-1));  // Push a bad frame pointer to fail if it is used.
1234   __ push(r0);
1235   if (FLAG_enable_embedded_constant_pool) {
1236     __ li(kConstantPoolRegister, Operand::Zero());
1237     __ push(kConstantPoolRegister);
1238   }
1239   int marker = type();
1240   __ LoadSmiLiteral(r0, Smi::FromInt(marker));
1241   __ push(r0);
1242   __ push(r0);
1243   // Save copies of the top frame descriptor on the stack.
1244   __ mov(r8, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
1245   __ LoadP(r0, MemOperand(r8));
1246   __ push(r0);
1247
1248   // Set up frame pointer for the frame to be pushed.
1249   __ addi(fp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
1250
1251   // If this is the outermost JS call, set js_entry_sp value.
1252   Label non_outermost_js;
1253   ExternalReference js_entry_sp(Isolate::kJSEntrySPAddress, isolate());
1254   __ mov(r8, Operand(ExternalReference(js_entry_sp)));
1255   __ LoadP(r9, MemOperand(r8));
1256   __ cmpi(r9, Operand::Zero());
1257   __ bne(&non_outermost_js);
1258   __ StoreP(fp, MemOperand(r8));
1259   __ LoadSmiLiteral(ip, Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME));
1260   Label cont;
1261   __ b(&cont);
1262   __ bind(&non_outermost_js);
1263   __ LoadSmiLiteral(ip, Smi::FromInt(StackFrame::INNER_JSENTRY_FRAME));
1264   __ bind(&cont);
1265   __ push(ip);  // frame-type
1266
1267   // Jump to a faked try block that does the invoke, with a faked catch
1268   // block that sets the pending exception.
1269   __ b(&invoke);
1270
1271   __ bind(&handler_entry);
1272   handler_offset_ = handler_entry.pos();
1273   // Caught exception: Store result (exception) in the pending exception
1274   // field in the JSEnv and return a failure sentinel.  Coming in here the
1275   // fp will be invalid because the PushStackHandler below sets it to 0 to
1276   // signal the existence of the JSEntry frame.
1277   __ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
1278                                        isolate())));
1279
1280   __ StoreP(r3, MemOperand(ip));
1281   __ LoadRoot(r3, Heap::kExceptionRootIndex);
1282   __ b(&exit);
1283
1284   // Invoke: Link this frame into the handler chain.
1285   __ bind(&invoke);
1286   // Must preserve r3-r7.
1287   __ PushStackHandler();
1288   // If an exception not caught by another handler occurs, this handler
1289   // returns control to the code after the b(&invoke) above, which
1290   // restores all kCalleeSaved registers (including cp and fp) to their
1291   // saved values before returning a failure to C.
1292
1293   // Clear any pending exceptions.
1294   __ mov(r8, Operand(isolate()->factory()->the_hole_value()));
1295   __ mov(ip, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
1296                                        isolate())));
1297   __ StoreP(r8, MemOperand(ip));
1298
1299   // Invoke the function by calling through JS entry trampoline builtin.
1300   // Notice that we cannot store a reference to the trampoline code directly in
1301   // this stub, because runtime stubs are not traversed when doing GC.
1302
1303   // Expected registers by Builtins::JSEntryTrampoline
1304   // r3: code entry
1305   // r4: function
1306   // r5: receiver
1307   // r6: argc
1308   // r7: argv
1309   if (type() == StackFrame::ENTRY_CONSTRUCT) {
1310     ExternalReference construct_entry(Builtins::kJSConstructEntryTrampoline,
1311                                       isolate());
1312     __ mov(ip, Operand(construct_entry));
1313   } else {
1314     ExternalReference entry(Builtins::kJSEntryTrampoline, isolate());
1315     __ mov(ip, Operand(entry));
1316   }
1317   __ LoadP(ip, MemOperand(ip));  // deref address
1318
1319   // Branch and link to JSEntryTrampoline.
1320   // the address points to the start of the code object, skip the header
1321   __ addi(ip, ip, Operand(Code::kHeaderSize - kHeapObjectTag));
1322   __ mtctr(ip);
1323   __ bctrl();  // make the call
1324
1325   // Unlink this frame from the handler chain.
1326   __ PopStackHandler();
1327
1328   __ bind(&exit);  // r3 holds result
1329   // Check if the current stack frame is marked as the outermost JS frame.
1330   Label non_outermost_js_2;
1331   __ pop(r8);
1332   __ CmpSmiLiteral(r8, Smi::FromInt(StackFrame::OUTERMOST_JSENTRY_FRAME), r0);
1333   __ bne(&non_outermost_js_2);
1334   __ mov(r9, Operand::Zero());
1335   __ mov(r8, Operand(ExternalReference(js_entry_sp)));
1336   __ StoreP(r9, MemOperand(r8));
1337   __ bind(&non_outermost_js_2);
1338
1339   // Restore the top frame descriptors from the stack.
1340   __ pop(r6);
1341   __ mov(ip, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
1342   __ StoreP(r6, MemOperand(ip));
1343
1344   // Reset the stack to the callee saved registers.
1345   __ addi(sp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
1346
1347 // Restore callee-saved registers and return.
1348 #ifdef DEBUG
1349   if (FLAG_debug_code) {
1350     Label here;
1351     __ b(&here, SetLK);
1352     __ bind(&here);
1353   }
1354 #endif
1355
1356   __ MultiPop(kCalleeSaved);
1357
1358   __ LoadP(r0, MemOperand(sp, kStackFrameLRSlot * kPointerSize));
1359   __ mtctr(r0);
1360   __ bctr();
1361 }
1362
1363
1364 // Uses registers r3 to r7.
1365 // Expected input (depending on whether args are in registers or on the stack):
1366 // * object: r3 or at sp + 1 * kPointerSize.
1367 // * function: r4 or at sp.
1368 //
1369 // An inlined call site may have been generated before calling this stub.
1370 // In this case the offset to the inline site to patch is passed in r8.
1371 // (See LCodeGen::DoInstanceOfKnownGlobal)
1372 void InstanceofStub::Generate(MacroAssembler* masm) {
1373   // Call site inlining and patching implies arguments in registers.
1374   DCHECK(HasArgsInRegisters() || !HasCallSiteInlineCheck());
1375
1376   // Fixed register usage throughout the stub:
1377   const Register object = r3;     // Object (lhs).
1378   Register map = r6;              // Map of the object.
1379   const Register function = r4;   // Function (rhs).
1380   const Register prototype = r7;  // Prototype of the function.
1381   const Register inline_site = r9;
1382   const Register scratch = r5;
1383   Register scratch3 = no_reg;
1384
1385   // delta = mov + tagged LoadP + cmp + bne
1386   const int32_t kDeltaToLoadBoolResult =
1387       (Assembler::kMovInstructions + Assembler::kTaggedLoadInstructions + 2) *
1388       Assembler::kInstrSize;
1389
1390   Label slow, loop, is_instance, is_not_instance, not_js_object;
1391
1392   if (!HasArgsInRegisters()) {
1393     __ LoadP(object, MemOperand(sp, 1 * kPointerSize));
1394     __ LoadP(function, MemOperand(sp, 0));
1395   }
1396
1397   // Check that the left hand is a JS object and load map.
1398   __ JumpIfSmi(object, &not_js_object);
1399   __ IsObjectJSObjectType(object, map, scratch, &not_js_object);
1400
1401   // If there is a call site cache don't look in the global cache, but do the
1402   // real lookup and update the call site cache.
1403   if (!HasCallSiteInlineCheck() && !ReturnTrueFalseObject()) {
1404     Label miss;
1405     __ CompareRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
1406     __ bne(&miss);
1407     __ CompareRoot(map, Heap::kInstanceofCacheMapRootIndex);
1408     __ bne(&miss);
1409     __ LoadRoot(r3, Heap::kInstanceofCacheAnswerRootIndex);
1410     __ Ret(HasArgsInRegisters() ? 0 : 2);
1411
1412     __ bind(&miss);
1413   }
1414
1415   // Get the prototype of the function.
1416   __ TryGetFunctionPrototype(function, prototype, scratch, &slow, true);
1417
1418   // Check that the function prototype is a JS object.
1419   __ JumpIfSmi(prototype, &slow);
1420   __ IsObjectJSObjectType(prototype, scratch, scratch, &slow);
1421
1422   // Update the global instanceof or call site inlined cache with the current
1423   // map and function. The cached answer will be set when it is known below.
1424   if (!HasCallSiteInlineCheck()) {
1425     __ StoreRoot(function, Heap::kInstanceofCacheFunctionRootIndex);
1426     __ StoreRoot(map, Heap::kInstanceofCacheMapRootIndex);
1427   } else {
1428     DCHECK(HasArgsInRegisters());
1429     // Patch the (relocated) inlined map check.
1430
1431     // The offset was stored in r8
1432     //   (See LCodeGen::DoDeferredLInstanceOfKnownGlobal).
1433     const Register offset = r8;
1434     __ mflr(inline_site);
1435     __ sub(inline_site, inline_site, offset);
1436     // Get the map location in r8 and patch it.
1437     __ GetRelocatedValue(inline_site, offset, scratch);
1438     __ StoreP(map, FieldMemOperand(offset, Cell::kValueOffset), r0);
1439
1440     __ mr(r10, map);
1441     __ RecordWriteField(offset, Cell::kValueOffset, r10, function,
1442                         kLRHasNotBeenSaved, kDontSaveFPRegs,
1443                         OMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
1444   }
1445
1446   // Register mapping: r6 is object map and r7 is function prototype.
1447   // Get prototype of object into r5.
1448   __ LoadP(scratch, FieldMemOperand(map, Map::kPrototypeOffset));
1449
1450   // We don't need map any more. Use it as a scratch register.
1451   scratch3 = map;
1452   map = no_reg;
1453
1454   // Loop through the prototype chain looking for the function prototype.
1455   __ LoadRoot(scratch3, Heap::kNullValueRootIndex);
1456   __ bind(&loop);
1457   __ cmp(scratch, prototype);
1458   __ beq(&is_instance);
1459   __ cmp(scratch, scratch3);
1460   __ beq(&is_not_instance);
1461   __ LoadP(scratch, FieldMemOperand(scratch, HeapObject::kMapOffset));
1462   __ LoadP(scratch, FieldMemOperand(scratch, Map::kPrototypeOffset));
1463   __ b(&loop);
1464   Factory* factory = isolate()->factory();
1465
1466   __ bind(&is_instance);
1467   if (!HasCallSiteInlineCheck()) {
1468     __ LoadSmiLiteral(r3, Smi::FromInt(0));
1469     __ StoreRoot(r3, Heap::kInstanceofCacheAnswerRootIndex);
1470     if (ReturnTrueFalseObject()) {
1471       __ Move(r3, factory->true_value());
1472     }
1473   } else {
1474     // Patch the call site to return true.
1475     __ LoadRoot(r3, Heap::kTrueValueRootIndex);
1476     __ addi(inline_site, inline_site, Operand(kDeltaToLoadBoolResult));
1477     // Get the boolean result location in scratch and patch it.
1478     __ SetRelocatedValue(inline_site, scratch, r3);
1479
1480     if (!ReturnTrueFalseObject()) {
1481       __ LoadSmiLiteral(r3, Smi::FromInt(0));
1482     }
1483   }
1484   __ Ret(HasArgsInRegisters() ? 0 : 2);
1485
1486   __ bind(&is_not_instance);
1487   if (!HasCallSiteInlineCheck()) {
1488     __ LoadSmiLiteral(r3, Smi::FromInt(1));
1489     __ StoreRoot(r3, Heap::kInstanceofCacheAnswerRootIndex);
1490     if (ReturnTrueFalseObject()) {
1491       __ Move(r3, factory->false_value());
1492     }
1493   } else {
1494     // Patch the call site to return false.
1495     __ LoadRoot(r3, Heap::kFalseValueRootIndex);
1496     __ addi(inline_site, inline_site, Operand(kDeltaToLoadBoolResult));
1497     // Get the boolean result location in scratch and patch it.
1498     __ SetRelocatedValue(inline_site, scratch, r3);
1499
1500     if (!ReturnTrueFalseObject()) {
1501       __ LoadSmiLiteral(r3, Smi::FromInt(1));
1502     }
1503   }
1504   __ Ret(HasArgsInRegisters() ? 0 : 2);
1505
1506   Label object_not_null, object_not_null_or_smi;
1507   __ bind(&not_js_object);
1508   // Before null, smi and string value checks, check that the rhs is a function
1509   // as for a non-function rhs an exception needs to be thrown.
1510   __ JumpIfSmi(function, &slow);
1511   __ CompareObjectType(function, scratch3, scratch, JS_FUNCTION_TYPE);
1512   __ bne(&slow);
1513
1514   // Null is not instance of anything.
1515   __ Cmpi(object, Operand(isolate()->factory()->null_value()), r0);
1516   __ bne(&object_not_null);
1517   if (ReturnTrueFalseObject()) {
1518     __ Move(r3, factory->false_value());
1519   } else {
1520     __ LoadSmiLiteral(r3, Smi::FromInt(1));
1521   }
1522   __ Ret(HasArgsInRegisters() ? 0 : 2);
1523
1524   __ bind(&object_not_null);
1525   // Smi values are not instances of anything.
1526   __ JumpIfNotSmi(object, &object_not_null_or_smi);
1527   if (ReturnTrueFalseObject()) {
1528     __ Move(r3, factory->false_value());
1529   } else {
1530     __ LoadSmiLiteral(r3, Smi::FromInt(1));
1531   }
1532   __ Ret(HasArgsInRegisters() ? 0 : 2);
1533
1534   __ bind(&object_not_null_or_smi);
1535   // String values are not instances of anything.
1536   __ IsObjectJSStringType(object, scratch, &slow);
1537   if (ReturnTrueFalseObject()) {
1538     __ Move(r3, factory->false_value());
1539   } else {
1540     __ LoadSmiLiteral(r3, Smi::FromInt(1));
1541   }
1542   __ Ret(HasArgsInRegisters() ? 0 : 2);
1543
1544   // Slow-case.  Tail call builtin.
1545   __ bind(&slow);
1546   if (!ReturnTrueFalseObject()) {
1547     if (HasArgsInRegisters()) {
1548       __ Push(r3, r4);
1549     }
1550     __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
1551   } else {
1552     {
1553       FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
1554       __ Push(r3, r4);
1555       __ InvokeBuiltin(Builtins::INSTANCE_OF, CALL_FUNCTION);
1556     }
1557     if (CpuFeatures::IsSupported(ISELECT)) {
1558       __ cmpi(r3, Operand::Zero());
1559       __ LoadRoot(r3, Heap::kTrueValueRootIndex);
1560       __ LoadRoot(r4, Heap::kFalseValueRootIndex);
1561       __ isel(eq, r3, r3, r4);
1562     } else {
1563       Label true_value, done;
1564       __ cmpi(r3, Operand::Zero());
1565       __ beq(&true_value);
1566
1567       __ LoadRoot(r3, Heap::kFalseValueRootIndex);
1568       __ b(&done);
1569
1570       __ bind(&true_value);
1571       __ LoadRoot(r3, Heap::kTrueValueRootIndex);
1572
1573       __ bind(&done);
1574     }
1575     __ Ret(HasArgsInRegisters() ? 0 : 2);
1576   }
1577 }
1578
1579
1580 void FunctionPrototypeStub::Generate(MacroAssembler* masm) {
1581   Label miss;
1582   Register receiver = LoadDescriptor::ReceiverRegister();
1583   // Ensure that the vector and slot registers won't be clobbered before
1584   // calling the miss handler.
1585   DCHECK(!AreAliased(r7, r8, LoadWithVectorDescriptor::VectorRegister(),
1586                      LoadWithVectorDescriptor::SlotRegister()));
1587
1588   NamedLoadHandlerCompiler::GenerateLoadFunctionPrototype(masm, receiver, r7,
1589                                                           r8, &miss);
1590   __ bind(&miss);
1591   PropertyAccessCompiler::TailCallBuiltin(
1592       masm, PropertyAccessCompiler::MissBuiltin(Code::LOAD_IC));
1593 }
1594
1595
1596 void LoadIndexedStringStub::Generate(MacroAssembler* masm) {
1597   // Return address is in lr.
1598   Label miss;
1599
1600   Register receiver = LoadDescriptor::ReceiverRegister();
1601   Register index = LoadDescriptor::NameRegister();
1602   Register scratch = r8;
1603   Register result = r3;
1604   DCHECK(!scratch.is(receiver) && !scratch.is(index));
1605   DCHECK(!scratch.is(LoadWithVectorDescriptor::VectorRegister()) &&
1606          result.is(LoadWithVectorDescriptor::SlotRegister()));
1607
1608   // StringCharAtGenerator doesn't use the result register until it's passed
1609   // the different miss possibilities. If it did, we would have a conflict
1610   // when FLAG_vector_ics is true.
1611   StringCharAtGenerator char_at_generator(receiver, index, scratch, result,
1612                                           &miss,  // When not a string.
1613                                           &miss,  // When not a number.
1614                                           &miss,  // When index out of range.
1615                                           STRING_INDEX_IS_ARRAY_INDEX,
1616                                           RECEIVER_IS_STRING);
1617   char_at_generator.GenerateFast(masm);
1618   __ Ret();
1619
1620   StubRuntimeCallHelper call_helper;
1621   char_at_generator.GenerateSlow(masm, PART_OF_IC_HANDLER, call_helper);
1622
1623   __ bind(&miss);
1624   PropertyAccessCompiler::TailCallBuiltin(
1625       masm, PropertyAccessCompiler::MissBuiltin(Code::KEYED_LOAD_IC));
1626 }
1627
1628
1629 void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
1630   CHECK(!has_new_target());
1631   // The displacement is the offset of the last parameter (if any)
1632   // relative to the frame pointer.
1633   const int kDisplacement =
1634       StandardFrameConstants::kCallerSPOffset - kPointerSize;
1635   DCHECK(r4.is(ArgumentsAccessReadDescriptor::index()));
1636   DCHECK(r3.is(ArgumentsAccessReadDescriptor::parameter_count()));
1637
1638   // Check that the key is a smi.
1639   Label slow;
1640   __ JumpIfNotSmi(r4, &slow);
1641
1642   // Check if the calling frame is an arguments adaptor frame.
1643   Label adaptor;
1644   __ LoadP(r5, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1645   __ LoadP(r6, MemOperand(r5, StandardFrameConstants::kContextOffset));
1646   STATIC_ASSERT(StackFrame::ARGUMENTS_ADAPTOR < 0x3fffu);
1647   __ CmpSmiLiteral(r6, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
1648   __ beq(&adaptor);
1649
1650   // Check index against formal parameters count limit passed in
1651   // through register r3. Use unsigned comparison to get negative
1652   // check for free.
1653   __ cmpl(r4, r3);
1654   __ bge(&slow);
1655
1656   // Read the argument from the stack and return it.
1657   __ sub(r6, r3, r4);
1658   __ SmiToPtrArrayOffset(r6, r6);
1659   __ add(r6, fp, r6);
1660   __ LoadP(r3, MemOperand(r6, kDisplacement));
1661   __ blr();
1662
1663   // Arguments adaptor case: Check index against actual arguments
1664   // limit found in the arguments adaptor frame. Use unsigned
1665   // comparison to get negative check for free.
1666   __ bind(&adaptor);
1667   __ LoadP(r3, MemOperand(r5, ArgumentsAdaptorFrameConstants::kLengthOffset));
1668   __ cmpl(r4, r3);
1669   __ bge(&slow);
1670
1671   // Read the argument from the adaptor frame and return it.
1672   __ sub(r6, r3, r4);
1673   __ SmiToPtrArrayOffset(r6, r6);
1674   __ add(r6, r5, r6);
1675   __ LoadP(r3, MemOperand(r6, kDisplacement));
1676   __ blr();
1677
1678   // Slow-case: Handle non-smi or out-of-bounds access to arguments
1679   // by calling the runtime system.
1680   __ bind(&slow);
1681   __ push(r4);
1682   __ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
1683 }
1684
1685
1686 void ArgumentsAccessStub::GenerateNewSloppySlow(MacroAssembler* masm) {
1687   // sp[0] : number of parameters
1688   // sp[1] : receiver displacement
1689   // sp[2] : function
1690
1691   CHECK(!has_new_target());
1692
1693   // Check if the calling frame is an arguments adaptor frame.
1694   Label runtime;
1695   __ LoadP(r6, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1696   __ LoadP(r5, MemOperand(r6, StandardFrameConstants::kContextOffset));
1697   STATIC_ASSERT(StackFrame::ARGUMENTS_ADAPTOR < 0x3fffu);
1698   __ CmpSmiLiteral(r5, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
1699   __ bne(&runtime);
1700
1701   // Patch the arguments.length and the parameters pointer in the current frame.
1702   __ LoadP(r5, MemOperand(r6, ArgumentsAdaptorFrameConstants::kLengthOffset));
1703   __ StoreP(r5, MemOperand(sp, 0 * kPointerSize));
1704   __ SmiToPtrArrayOffset(r5, r5);
1705   __ add(r6, r6, r5);
1706   __ addi(r6, r6, Operand(StandardFrameConstants::kCallerSPOffset));
1707   __ StoreP(r6, MemOperand(sp, 1 * kPointerSize));
1708
1709   __ bind(&runtime);
1710   __ TailCallRuntime(Runtime::kNewSloppyArguments, 3, 1);
1711 }
1712
1713
1714 void ArgumentsAccessStub::GenerateNewSloppyFast(MacroAssembler* masm) {
1715   // Stack layout:
1716   //  sp[0] : number of parameters (tagged)
1717   //  sp[1] : address of receiver argument
1718   //  sp[2] : function
1719   // Registers used over whole function:
1720   //  r9 : allocated object (tagged)
1721   //  r11 : mapped parameter count (tagged)
1722
1723   CHECK(!has_new_target());
1724
1725   __ LoadP(r4, MemOperand(sp, 0 * kPointerSize));
1726   // r4 = parameter count (tagged)
1727
1728   // Check if the calling frame is an arguments adaptor frame.
1729   Label runtime;
1730   Label adaptor_frame, try_allocate;
1731   __ LoadP(r6, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1732   __ LoadP(r5, MemOperand(r6, StandardFrameConstants::kContextOffset));
1733   STATIC_ASSERT(StackFrame::ARGUMENTS_ADAPTOR < 0x3fffu);
1734   __ CmpSmiLiteral(r5, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
1735   __ beq(&adaptor_frame);
1736
1737   // No adaptor, parameter count = argument count.
1738   __ mr(r5, r4);
1739   __ b(&try_allocate);
1740
1741   // We have an adaptor frame. Patch the parameters pointer.
1742   __ bind(&adaptor_frame);
1743   __ LoadP(r5, MemOperand(r6, ArgumentsAdaptorFrameConstants::kLengthOffset));
1744   __ SmiToPtrArrayOffset(r7, r5);
1745   __ add(r6, r6, r7);
1746   __ addi(r6, r6, Operand(StandardFrameConstants::kCallerSPOffset));
1747   __ StoreP(r6, MemOperand(sp, 1 * kPointerSize));
1748
1749   // r4 = parameter count (tagged)
1750   // r5 = argument count (tagged)
1751   // Compute the mapped parameter count = min(r4, r5) in r4.
1752   __ cmp(r4, r5);
1753   if (CpuFeatures::IsSupported(ISELECT)) {
1754     __ isel(lt, r4, r4, r5);
1755   } else {
1756     Label skip;
1757     __ blt(&skip);
1758     __ mr(r4, r5);
1759     __ bind(&skip);
1760   }
1761
1762   __ bind(&try_allocate);
1763
1764   // Compute the sizes of backing store, parameter map, and arguments object.
1765   // 1. Parameter map, has 2 extra words containing context and backing store.
1766   const int kParameterMapHeaderSize =
1767       FixedArray::kHeaderSize + 2 * kPointerSize;
1768   // If there are no mapped parameters, we do not need the parameter_map.
1769   __ CmpSmiLiteral(r4, Smi::FromInt(0), r0);
1770   if (CpuFeatures::IsSupported(ISELECT)) {
1771     __ SmiToPtrArrayOffset(r11, r4);
1772     __ addi(r11, r11, Operand(kParameterMapHeaderSize));
1773     __ isel(eq, r11, r0, r11);
1774   } else {
1775     Label skip2, skip3;
1776     __ bne(&skip2);
1777     __ li(r11, Operand::Zero());
1778     __ b(&skip3);
1779     __ bind(&skip2);
1780     __ SmiToPtrArrayOffset(r11, r4);
1781     __ addi(r11, r11, Operand(kParameterMapHeaderSize));
1782     __ bind(&skip3);
1783   }
1784
1785   // 2. Backing store.
1786   __ SmiToPtrArrayOffset(r7, r5);
1787   __ add(r11, r11, r7);
1788   __ addi(r11, r11, Operand(FixedArray::kHeaderSize));
1789
1790   // 3. Arguments object.
1791   __ addi(r11, r11, Operand(Heap::kSloppyArgumentsObjectSize));
1792
1793   // Do the allocation of all three objects in one go.
1794   __ Allocate(r11, r3, r6, r7, &runtime, TAG_OBJECT);
1795
1796   // r3 = address of new object(s) (tagged)
1797   // r5 = argument count (smi-tagged)
1798   // Get the arguments boilerplate from the current native context into r4.
1799   const int kNormalOffset =
1800       Context::SlotOffset(Context::SLOPPY_ARGUMENTS_MAP_INDEX);
1801   const int kAliasedOffset =
1802       Context::SlotOffset(Context::ALIASED_ARGUMENTS_MAP_INDEX);
1803
1804   __ LoadP(r7,
1805            MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
1806   __ LoadP(r7, FieldMemOperand(r7, GlobalObject::kNativeContextOffset));
1807   __ cmpi(r4, Operand::Zero());
1808   if (CpuFeatures::IsSupported(ISELECT)) {
1809     __ LoadP(r11, MemOperand(r7, kNormalOffset));
1810     __ LoadP(r7, MemOperand(r7, kAliasedOffset));
1811     __ isel(eq, r7, r11, r7);
1812   } else {
1813     Label skip4, skip5;
1814     __ bne(&skip4);
1815     __ LoadP(r7, MemOperand(r7, kNormalOffset));
1816     __ b(&skip5);
1817     __ bind(&skip4);
1818     __ LoadP(r7, MemOperand(r7, kAliasedOffset));
1819     __ bind(&skip5);
1820   }
1821
1822   // r3 = address of new object (tagged)
1823   // r4 = mapped parameter count (tagged)
1824   // r5 = argument count (smi-tagged)
1825   // r7 = address of arguments map (tagged)
1826   __ StoreP(r7, FieldMemOperand(r3, JSObject::kMapOffset), r0);
1827   __ LoadRoot(r6, Heap::kEmptyFixedArrayRootIndex);
1828   __ StoreP(r6, FieldMemOperand(r3, JSObject::kPropertiesOffset), r0);
1829   __ StoreP(r6, FieldMemOperand(r3, JSObject::kElementsOffset), r0);
1830
1831   // Set up the callee in-object property.
1832   STATIC_ASSERT(Heap::kArgumentsCalleeIndex == 1);
1833   __ LoadP(r6, MemOperand(sp, 2 * kPointerSize));
1834   __ AssertNotSmi(r6);
1835   const int kCalleeOffset =
1836       JSObject::kHeaderSize + Heap::kArgumentsCalleeIndex * kPointerSize;
1837   __ StoreP(r6, FieldMemOperand(r3, kCalleeOffset), r0);
1838
1839   // Use the length (smi tagged) and set that as an in-object property too.
1840   __ AssertSmi(r5);
1841   STATIC_ASSERT(Heap::kArgumentsLengthIndex == 0);
1842   const int kLengthOffset =
1843       JSObject::kHeaderSize + Heap::kArgumentsLengthIndex * kPointerSize;
1844   __ StoreP(r5, FieldMemOperand(r3, kLengthOffset), r0);
1845
1846   // Set up the elements pointer in the allocated arguments object.
1847   // If we allocated a parameter map, r7 will point there, otherwise
1848   // it will point to the backing store.
1849   __ addi(r7, r3, Operand(Heap::kSloppyArgumentsObjectSize));
1850   __ StoreP(r7, FieldMemOperand(r3, JSObject::kElementsOffset), r0);
1851
1852   // r3 = address of new object (tagged)
1853   // r4 = mapped parameter count (tagged)
1854   // r5 = argument count (tagged)
1855   // r7 = address of parameter map or backing store (tagged)
1856   // Initialize parameter map. If there are no mapped arguments, we're done.
1857   Label skip_parameter_map;
1858   __ CmpSmiLiteral(r4, Smi::FromInt(0), r0);
1859   if (CpuFeatures::IsSupported(ISELECT)) {
1860     __ isel(eq, r6, r7, r6);
1861     __ beq(&skip_parameter_map);
1862   } else {
1863     Label skip6;
1864     __ bne(&skip6);
1865     // Move backing store address to r6, because it is
1866     // expected there when filling in the unmapped arguments.
1867     __ mr(r6, r7);
1868     __ b(&skip_parameter_map);
1869     __ bind(&skip6);
1870   }
1871
1872   __ LoadRoot(r9, Heap::kSloppyArgumentsElementsMapRootIndex);
1873   __ StoreP(r9, FieldMemOperand(r7, FixedArray::kMapOffset), r0);
1874   __ AddSmiLiteral(r9, r4, Smi::FromInt(2), r0);
1875   __ StoreP(r9, FieldMemOperand(r7, FixedArray::kLengthOffset), r0);
1876   __ StoreP(cp, FieldMemOperand(r7, FixedArray::kHeaderSize + 0 * kPointerSize),
1877             r0);
1878   __ SmiToPtrArrayOffset(r9, r4);
1879   __ add(r9, r7, r9);
1880   __ addi(r9, r9, Operand(kParameterMapHeaderSize));
1881   __ StoreP(r9, FieldMemOperand(r7, FixedArray::kHeaderSize + 1 * kPointerSize),
1882             r0);
1883
1884   // Copy the parameter slots and the holes in the arguments.
1885   // We need to fill in mapped_parameter_count slots. They index the context,
1886   // where parameters are stored in reverse order, at
1887   //   MIN_CONTEXT_SLOTS .. MIN_CONTEXT_SLOTS+parameter_count-1
1888   // The mapped parameter thus need to get indices
1889   //   MIN_CONTEXT_SLOTS+parameter_count-1 ..
1890   //       MIN_CONTEXT_SLOTS+parameter_count-mapped_parameter_count
1891   // We loop from right to left.
1892   Label parameters_loop, parameters_test;
1893   __ mr(r9, r4);
1894   __ LoadP(r11, MemOperand(sp, 0 * kPointerSize));
1895   __ AddSmiLiteral(r11, r11, Smi::FromInt(Context::MIN_CONTEXT_SLOTS), r0);
1896   __ sub(r11, r11, r4);
1897   __ LoadRoot(r10, Heap::kTheHoleValueRootIndex);
1898   __ SmiToPtrArrayOffset(r6, r9);
1899   __ add(r6, r7, r6);
1900   __ addi(r6, r6, Operand(kParameterMapHeaderSize));
1901
1902   // r9 = loop variable (tagged)
1903   // r4 = mapping index (tagged)
1904   // r6 = address of backing store (tagged)
1905   // r7 = address of parameter map (tagged)
1906   // r8 = temporary scratch (a.o., for address calculation)
1907   // r10 = the hole value
1908   __ b(&parameters_test);
1909
1910   __ bind(&parameters_loop);
1911   __ SubSmiLiteral(r9, r9, Smi::FromInt(1), r0);
1912   __ SmiToPtrArrayOffset(r8, r9);
1913   __ addi(r8, r8, Operand(kParameterMapHeaderSize - kHeapObjectTag));
1914   __ StorePX(r11, MemOperand(r8, r7));
1915   __ subi(r8, r8, Operand(kParameterMapHeaderSize - FixedArray::kHeaderSize));
1916   __ StorePX(r10, MemOperand(r8, r6));
1917   __ AddSmiLiteral(r11, r11, Smi::FromInt(1), r0);
1918   __ bind(&parameters_test);
1919   __ CmpSmiLiteral(r9, Smi::FromInt(0), r0);
1920   __ bne(&parameters_loop);
1921
1922   __ bind(&skip_parameter_map);
1923   // r5 = argument count (tagged)
1924   // r6 = address of backing store (tagged)
1925   // r8 = scratch
1926   // Copy arguments header and remaining slots (if there are any).
1927   __ LoadRoot(r8, Heap::kFixedArrayMapRootIndex);
1928   __ StoreP(r8, FieldMemOperand(r6, FixedArray::kMapOffset), r0);
1929   __ StoreP(r5, FieldMemOperand(r6, FixedArray::kLengthOffset), r0);
1930
1931   Label arguments_loop, arguments_test;
1932   __ mr(r11, r4);
1933   __ LoadP(r7, MemOperand(sp, 1 * kPointerSize));
1934   __ SmiToPtrArrayOffset(r8, r11);
1935   __ sub(r7, r7, r8);
1936   __ b(&arguments_test);
1937
1938   __ bind(&arguments_loop);
1939   __ subi(r7, r7, Operand(kPointerSize));
1940   __ LoadP(r9, MemOperand(r7, 0));
1941   __ SmiToPtrArrayOffset(r8, r11);
1942   __ add(r8, r6, r8);
1943   __ StoreP(r9, FieldMemOperand(r8, FixedArray::kHeaderSize), r0);
1944   __ AddSmiLiteral(r11, r11, Smi::FromInt(1), r0);
1945
1946   __ bind(&arguments_test);
1947   __ cmp(r11, r5);
1948   __ blt(&arguments_loop);
1949
1950   // Return and remove the on-stack parameters.
1951   __ addi(sp, sp, Operand(3 * kPointerSize));
1952   __ Ret();
1953
1954   // Do the runtime call to allocate the arguments object.
1955   // r5 = argument count (tagged)
1956   __ bind(&runtime);
1957   __ StoreP(r5, MemOperand(sp, 0 * kPointerSize));  // Patch argument count.
1958   __ TailCallRuntime(Runtime::kNewSloppyArguments, 3, 1);
1959 }
1960
1961
1962 void LoadIndexedInterceptorStub::Generate(MacroAssembler* masm) {
1963   // Return address is in lr.
1964   Label slow;
1965
1966   Register receiver = LoadDescriptor::ReceiverRegister();
1967   Register key = LoadDescriptor::NameRegister();
1968
1969   // Check that the key is an array index, that is Uint32.
1970   __ TestIfPositiveSmi(key, r0);
1971   __ bne(&slow, cr0);
1972
1973   // Everything is fine, call runtime.
1974   __ Push(receiver, key);  // Receiver, key.
1975
1976   // Perform tail call to the entry.
1977   __ TailCallExternalReference(
1978       ExternalReference(IC_Utility(IC::kLoadElementWithInterceptor),
1979                         masm->isolate()),
1980       2, 1);
1981
1982   __ bind(&slow);
1983   PropertyAccessCompiler::TailCallBuiltin(
1984       masm, PropertyAccessCompiler::MissBuiltin(Code::KEYED_LOAD_IC));
1985 }
1986
1987
1988 void ArgumentsAccessStub::GenerateNewStrict(MacroAssembler* masm) {
1989   // sp[0] : number of parameters
1990   // sp[4] : receiver displacement
1991   // sp[8] : function
1992   // Check if the calling frame is an arguments adaptor frame.
1993   Label adaptor_frame, try_allocate, runtime;
1994   __ LoadP(r5, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1995   __ LoadP(r6, MemOperand(r5, StandardFrameConstants::kContextOffset));
1996   STATIC_ASSERT(StackFrame::ARGUMENTS_ADAPTOR < 0x3fffu);
1997   __ CmpSmiLiteral(r6, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
1998   __ beq(&adaptor_frame);
1999
2000   // Get the length from the frame.
2001   __ LoadP(r4, MemOperand(sp, 0));
2002   __ b(&try_allocate);
2003
2004   // Patch the arguments.length and the parameters pointer.
2005   __ bind(&adaptor_frame);
2006   __ LoadP(r4, MemOperand(r5, ArgumentsAdaptorFrameConstants::kLengthOffset));
2007   if (has_new_target()) {
2008     __ CmpSmiLiteral(r4, Smi::FromInt(0), r0);
2009     Label skip_decrement;
2010     __ beq(&skip_decrement);
2011     // Subtract 1 from smi-tagged arguments count.
2012     __ SubSmiLiteral(r4, r4, Smi::FromInt(1), r0);
2013     __ bind(&skip_decrement);
2014   }
2015   __ StoreP(r4, MemOperand(sp, 0));
2016   __ SmiToPtrArrayOffset(r6, r4);
2017   __ add(r6, r5, r6);
2018   __ addi(r6, r6, Operand(StandardFrameConstants::kCallerSPOffset));
2019   __ StoreP(r6, MemOperand(sp, 1 * kPointerSize));
2020
2021   // Try the new space allocation. Start out with computing the size
2022   // of the arguments object and the elements array in words.
2023   Label add_arguments_object;
2024   __ bind(&try_allocate);
2025   __ cmpi(r4, Operand::Zero());
2026   __ beq(&add_arguments_object);
2027   __ SmiUntag(r4);
2028   __ addi(r4, r4, Operand(FixedArray::kHeaderSize / kPointerSize));
2029   __ bind(&add_arguments_object);
2030   __ addi(r4, r4, Operand(Heap::kStrictArgumentsObjectSize / kPointerSize));
2031
2032   // Do the allocation of both objects in one go.
2033   __ Allocate(r4, r3, r5, r6, &runtime,
2034               static_cast<AllocationFlags>(TAG_OBJECT | SIZE_IN_WORDS));
2035
2036   // Get the arguments boilerplate from the current native context.
2037   __ LoadP(r7,
2038            MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
2039   __ LoadP(r7, FieldMemOperand(r7, GlobalObject::kNativeContextOffset));
2040   __ LoadP(
2041       r7,
2042       MemOperand(r7, Context::SlotOffset(Context::STRICT_ARGUMENTS_MAP_INDEX)));
2043
2044   __ StoreP(r7, FieldMemOperand(r3, JSObject::kMapOffset), r0);
2045   __ LoadRoot(r6, Heap::kEmptyFixedArrayRootIndex);
2046   __ StoreP(r6, FieldMemOperand(r3, JSObject::kPropertiesOffset), r0);
2047   __ StoreP(r6, FieldMemOperand(r3, JSObject::kElementsOffset), r0);
2048
2049   // Get the length (smi tagged) and set that as an in-object property too.
2050   STATIC_ASSERT(Heap::kArgumentsLengthIndex == 0);
2051   __ LoadP(r4, MemOperand(sp, 0 * kPointerSize));
2052   __ AssertSmi(r4);
2053   __ StoreP(r4,
2054             FieldMemOperand(r3, JSObject::kHeaderSize +
2055                                     Heap::kArgumentsLengthIndex * kPointerSize),
2056             r0);
2057
2058   // If there are no actual arguments, we're done.
2059   Label done;
2060   __ cmpi(r4, Operand::Zero());
2061   __ beq(&done);
2062
2063   // Get the parameters pointer from the stack.
2064   __ LoadP(r5, MemOperand(sp, 1 * kPointerSize));
2065
2066   // Set up the elements pointer in the allocated arguments object and
2067   // initialize the header in the elements fixed array.
2068   __ addi(r7, r3, Operand(Heap::kStrictArgumentsObjectSize));
2069   __ StoreP(r7, FieldMemOperand(r3, JSObject::kElementsOffset), r0);
2070   __ LoadRoot(r6, Heap::kFixedArrayMapRootIndex);
2071   __ StoreP(r6, FieldMemOperand(r7, FixedArray::kMapOffset), r0);
2072   __ StoreP(r4, FieldMemOperand(r7, FixedArray::kLengthOffset), r0);
2073   // Untag the length for the loop.
2074   __ SmiUntag(r4);
2075
2076   // Copy the fixed array slots.
2077   Label loop;
2078   // Set up r7 to point just prior to the first array slot.
2079   __ addi(r7, r7,
2080           Operand(FixedArray::kHeaderSize - kHeapObjectTag - kPointerSize));
2081   __ mtctr(r4);
2082   __ bind(&loop);
2083   // Pre-decrement r5 with kPointerSize on each iteration.
2084   // Pre-decrement in order to skip receiver.
2085   __ LoadPU(r6, MemOperand(r5, -kPointerSize));
2086   // Pre-increment r7 with kPointerSize on each iteration.
2087   __ StorePU(r6, MemOperand(r7, kPointerSize));
2088   __ bdnz(&loop);
2089
2090   // Return and remove the on-stack parameters.
2091   __ bind(&done);
2092   __ addi(sp, sp, Operand(3 * kPointerSize));
2093   __ Ret();
2094
2095   // Do the runtime call to allocate the arguments object.
2096   __ bind(&runtime);
2097   __ TailCallRuntime(Runtime::kNewStrictArguments, 3, 1);
2098 }
2099
2100
2101 void RestParamAccessStub::GenerateNew(MacroAssembler* masm) {
2102   // Stack layout on entry.
2103   //  sp[0] : language mode
2104   //  sp[4] : index of rest parameter
2105   //  sp[8] : number of parameters
2106   //  sp[12] : receiver displacement
2107
2108   Label runtime;
2109   __ LoadP(r5, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
2110   __ LoadP(r6, MemOperand(r5, StandardFrameConstants::kContextOffset));
2111   __ CmpSmiLiteral(r6, Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR), r0);
2112   __ bne(&runtime);
2113
2114   // Patch the arguments.length and the parameters pointer.
2115   __ LoadP(r4, MemOperand(r5, ArgumentsAdaptorFrameConstants::kLengthOffset));
2116   __ StoreP(r4, MemOperand(sp, 2 * kPointerSize));
2117   __ SmiToPtrArrayOffset(r6, r4);
2118   __ add(r6, r5, r6);
2119   __ addi(r6, r6, Operand(StandardFrameConstants::kCallerSPOffset));
2120   __ StoreP(r6, MemOperand(sp, 3 * kPointerSize));
2121
2122   __ bind(&runtime);
2123   __ TailCallRuntime(Runtime::kNewRestParam, 4, 1);
2124 }
2125
2126
2127 void RegExpExecStub::Generate(MacroAssembler* masm) {
2128 // Just jump directly to runtime if native RegExp is not selected at compile
2129 // time or if regexp entry in generated code is turned off runtime switch or
2130 // at compilation.
2131 #ifdef V8_INTERPRETED_REGEXP
2132   __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
2133 #else  // V8_INTERPRETED_REGEXP
2134
2135   // Stack frame on entry.
2136   //  sp[0]: last_match_info (expected JSArray)
2137   //  sp[4]: previous index
2138   //  sp[8]: subject string
2139   //  sp[12]: JSRegExp object
2140
2141   const int kLastMatchInfoOffset = 0 * kPointerSize;
2142   const int kPreviousIndexOffset = 1 * kPointerSize;
2143   const int kSubjectOffset = 2 * kPointerSize;
2144   const int kJSRegExpOffset = 3 * kPointerSize;
2145
2146   Label runtime, br_over, encoding_type_UC16;
2147
2148   // Allocation of registers for this function. These are in callee save
2149   // registers and will be preserved by the call to the native RegExp code, as
2150   // this code is called using the normal C calling convention. When calling
2151   // directly from generated code the native RegExp code will not do a GC and
2152   // therefore the content of these registers are safe to use after the call.
2153   Register subject = r14;
2154   Register regexp_data = r15;
2155   Register last_match_info_elements = r16;
2156   Register code = r17;
2157
2158   // Ensure register assigments are consistent with callee save masks
2159   DCHECK(subject.bit() & kCalleeSaved);
2160   DCHECK(regexp_data.bit() & kCalleeSaved);
2161   DCHECK(last_match_info_elements.bit() & kCalleeSaved);
2162   DCHECK(code.bit() & kCalleeSaved);
2163
2164   // Ensure that a RegExp stack is allocated.
2165   ExternalReference address_of_regexp_stack_memory_address =
2166       ExternalReference::address_of_regexp_stack_memory_address(isolate());
2167   ExternalReference address_of_regexp_stack_memory_size =
2168       ExternalReference::address_of_regexp_stack_memory_size(isolate());
2169   __ mov(r3, Operand(address_of_regexp_stack_memory_size));
2170   __ LoadP(r3, MemOperand(r3, 0));
2171   __ cmpi(r3, Operand::Zero());
2172   __ beq(&runtime);
2173
2174   // Check that the first argument is a JSRegExp object.
2175   __ LoadP(r3, MemOperand(sp, kJSRegExpOffset));
2176   __ JumpIfSmi(r3, &runtime);
2177   __ CompareObjectType(r3, r4, r4, JS_REGEXP_TYPE);
2178   __ bne(&runtime);
2179
2180   // Check that the RegExp has been compiled (data contains a fixed array).
2181   __ LoadP(regexp_data, FieldMemOperand(r3, JSRegExp::kDataOffset));
2182   if (FLAG_debug_code) {
2183     __ TestIfSmi(regexp_data, r0);
2184     __ Check(ne, kUnexpectedTypeForRegExpDataFixedArrayExpected, cr0);
2185     __ CompareObjectType(regexp_data, r3, r3, FIXED_ARRAY_TYPE);
2186     __ Check(eq, kUnexpectedTypeForRegExpDataFixedArrayExpected);
2187   }
2188
2189   // regexp_data: RegExp data (FixedArray)
2190   // Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
2191   __ LoadP(r3, FieldMemOperand(regexp_data, JSRegExp::kDataTagOffset));
2192   // DCHECK(Smi::FromInt(JSRegExp::IRREGEXP) < (char *)0xffffu);
2193   __ CmpSmiLiteral(r3, Smi::FromInt(JSRegExp::IRREGEXP), r0);
2194   __ bne(&runtime);
2195
2196   // regexp_data: RegExp data (FixedArray)
2197   // Check that the number of captures fit in the static offsets vector buffer.
2198   __ LoadP(r5,
2199            FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
2200   // Check (number_of_captures + 1) * 2 <= offsets vector size
2201   // Or          number_of_captures * 2 <= offsets vector size - 2
2202   // SmiToShortArrayOffset accomplishes the multiplication by 2 and
2203   // SmiUntag (which is a nop for 32-bit).
2204   __ SmiToShortArrayOffset(r5, r5);
2205   STATIC_ASSERT(Isolate::kJSRegexpStaticOffsetsVectorSize >= 2);
2206   __ cmpli(r5, Operand(Isolate::kJSRegexpStaticOffsetsVectorSize - 2));
2207   __ bgt(&runtime);
2208
2209   // Reset offset for possibly sliced string.
2210   __ li(r11, Operand::Zero());
2211   __ LoadP(subject, MemOperand(sp, kSubjectOffset));
2212   __ JumpIfSmi(subject, &runtime);
2213   __ mr(r6, subject);  // Make a copy of the original subject string.
2214   __ LoadP(r3, FieldMemOperand(subject, HeapObject::kMapOffset));
2215   __ lbz(r3, FieldMemOperand(r3, Map::kInstanceTypeOffset));
2216   // subject: subject string
2217   // r6: subject string
2218   // r3: subject string instance type
2219   // regexp_data: RegExp data (FixedArray)
2220   // Handle subject string according to its encoding and representation:
2221   // (1) Sequential string?  If yes, go to (5).
2222   // (2) Anything but sequential or cons?  If yes, go to (6).
2223   // (3) Cons string.  If the string is flat, replace subject with first string.
2224   //     Otherwise bailout.
2225   // (4) Is subject external?  If yes, go to (7).
2226   // (5) Sequential string.  Load regexp code according to encoding.
2227   // (E) Carry on.
2228   /// [...]
2229
2230   // Deferred code at the end of the stub:
2231   // (6) Not a long external string?  If yes, go to (8).
2232   // (7) External string.  Make it, offset-wise, look like a sequential string.
2233   //     Go to (5).
2234   // (8) Short external string or not a string?  If yes, bail out to runtime.
2235   // (9) Sliced string.  Replace subject with parent.  Go to (4).
2236
2237   Label seq_string /* 5 */, external_string /* 7 */, check_underlying /* 4 */,
2238       not_seq_nor_cons /* 6 */, not_long_external /* 8 */;
2239
2240   // (1) Sequential string?  If yes, go to (5).
2241   STATIC_ASSERT((kIsNotStringMask | kStringRepresentationMask |
2242                  kShortExternalStringMask) == 0x93);
2243   __ andi(r4, r3, Operand(kIsNotStringMask | kStringRepresentationMask |
2244                           kShortExternalStringMask));
2245   STATIC_ASSERT((kStringTag | kSeqStringTag) == 0);
2246   __ beq(&seq_string, cr0);  // Go to (5).
2247
2248   // (2) Anything but sequential or cons?  If yes, go to (6).
2249   STATIC_ASSERT(kConsStringTag < kExternalStringTag);
2250   STATIC_ASSERT(kSlicedStringTag > kExternalStringTag);
2251   STATIC_ASSERT(kIsNotStringMask > kExternalStringTag);
2252   STATIC_ASSERT(kShortExternalStringTag > kExternalStringTag);
2253   STATIC_ASSERT(kExternalStringTag < 0xffffu);
2254   __ cmpi(r4, Operand(kExternalStringTag));
2255   __ bge(&not_seq_nor_cons);  // Go to (6).
2256
2257   // (3) Cons string.  Check that it's flat.
2258   // Replace subject with first string and reload instance type.
2259   __ LoadP(r3, FieldMemOperand(subject, ConsString::kSecondOffset));
2260   __ CompareRoot(r3, Heap::kempty_stringRootIndex);
2261   __ bne(&runtime);
2262   __ LoadP(subject, FieldMemOperand(subject, ConsString::kFirstOffset));
2263
2264   // (4) Is subject external?  If yes, go to (7).
2265   __ bind(&check_underlying);
2266   __ LoadP(r3, FieldMemOperand(subject, HeapObject::kMapOffset));
2267   __ lbz(r3, FieldMemOperand(r3, Map::kInstanceTypeOffset));
2268   STATIC_ASSERT(kSeqStringTag == 0);
2269   STATIC_ASSERT(kStringRepresentationMask == 3);
2270   __ andi(r0, r3, Operand(kStringRepresentationMask));
2271   // The underlying external string is never a short external string.
2272   STATIC_ASSERT(ExternalString::kMaxShortLength < ConsString::kMinLength);
2273   STATIC_ASSERT(ExternalString::kMaxShortLength < SlicedString::kMinLength);
2274   __ bne(&external_string, cr0);  // Go to (7).
2275
2276   // (5) Sequential string.  Load regexp code according to encoding.
2277   __ bind(&seq_string);
2278   // subject: sequential subject string (or look-alike, external string)
2279   // r6: original subject string
2280   // Load previous index and check range before r6 is overwritten.  We have to
2281   // use r6 instead of subject here because subject might have been only made
2282   // to look like a sequential string when it actually is an external string.
2283   __ LoadP(r4, MemOperand(sp, kPreviousIndexOffset));
2284   __ JumpIfNotSmi(r4, &runtime);
2285   __ LoadP(r6, FieldMemOperand(r6, String::kLengthOffset));
2286   __ cmpl(r6, r4);
2287   __ ble(&runtime);
2288   __ SmiUntag(r4);
2289
2290   STATIC_ASSERT(4 == kOneByteStringTag);
2291   STATIC_ASSERT(kTwoByteStringTag == 0);
2292   STATIC_ASSERT(kStringEncodingMask == 4);
2293   __ ExtractBitMask(r6, r3, kStringEncodingMask, SetRC);
2294   __ beq(&encoding_type_UC16, cr0);
2295   __ LoadP(code,
2296            FieldMemOperand(regexp_data, JSRegExp::kDataOneByteCodeOffset));
2297   __ b(&br_over);
2298   __ bind(&encoding_type_UC16);
2299   __ LoadP(code, FieldMemOperand(regexp_data, JSRegExp::kDataUC16CodeOffset));
2300   __ bind(&br_over);
2301
2302   // (E) Carry on.  String handling is done.
2303   // code: irregexp code
2304   // Check that the irregexp code has been generated for the actual string
2305   // encoding. If it has, the field contains a code object otherwise it contains
2306   // a smi (code flushing support).
2307   __ JumpIfSmi(code, &runtime);
2308
2309   // r4: previous index
2310   // r6: encoding of subject string (1 if one_byte, 0 if two_byte);
2311   // code: Address of generated regexp code
2312   // subject: Subject string
2313   // regexp_data: RegExp data (FixedArray)
2314   // All checks done. Now push arguments for native regexp code.
2315   __ IncrementCounter(isolate()->counters()->regexp_entry_native(), 1, r3, r5);
2316
2317   // Isolates: note we add an additional parameter here (isolate pointer).
2318   const int kRegExpExecuteArguments = 10;
2319   const int kParameterRegisters = 8;
2320   __ EnterExitFrame(false, kRegExpExecuteArguments - kParameterRegisters);
2321
2322   // Stack pointer now points to cell where return address is to be written.
2323   // Arguments are before that on the stack or in registers.
2324
2325   // Argument 10 (in stack parameter area): Pass current isolate address.
2326   __ mov(r3, Operand(ExternalReference::isolate_address(isolate())));
2327   __ StoreP(r3, MemOperand(sp, (kStackFrameExtraParamSlot + 1) * kPointerSize));
2328
2329   // Argument 9 is a dummy that reserves the space used for
2330   // the return address added by the ExitFrame in native calls.
2331
2332   // Argument 8 (r10): Indicate that this is a direct call from JavaScript.
2333   __ li(r10, Operand(1));
2334
2335   // Argument 7 (r9): Start (high end) of backtracking stack memory area.
2336   __ mov(r3, Operand(address_of_regexp_stack_memory_address));
2337   __ LoadP(r3, MemOperand(r3, 0));
2338   __ mov(r5, Operand(address_of_regexp_stack_memory_size));
2339   __ LoadP(r5, MemOperand(r5, 0));
2340   __ add(r9, r3, r5);
2341
2342   // Argument 6 (r8): Set the number of capture registers to zero to force
2343   // global egexps to behave as non-global.  This does not affect non-global
2344   // regexps.
2345   __ li(r8, Operand::Zero());
2346
2347   // Argument 5 (r7): static offsets vector buffer.
2348   __ mov(
2349       r7,
2350       Operand(ExternalReference::address_of_static_offsets_vector(isolate())));
2351
2352   // For arguments 4 (r6) and 3 (r5) get string length, calculate start of data
2353   // and calculate the shift of the index (0 for one-byte and 1 for two-byte).
2354   __ addi(r18, subject, Operand(SeqString::kHeaderSize - kHeapObjectTag));
2355   __ xori(r6, r6, Operand(1));
2356   // Load the length from the original subject string from the previous stack
2357   // frame. Therefore we have to use fp, which points exactly to two pointer
2358   // sizes below the previous sp. (Because creating a new stack frame pushes
2359   // the previous fp onto the stack and moves up sp by 2 * kPointerSize.)
2360   __ LoadP(subject, MemOperand(fp, kSubjectOffset + 2 * kPointerSize));
2361   // If slice offset is not 0, load the length from the original sliced string.
2362   // Argument 4, r6: End of string data
2363   // Argument 3, r5: Start of string data
2364   // Prepare start and end index of the input.
2365   __ ShiftLeft_(r11, r11, r6);
2366   __ add(r11, r18, r11);
2367   __ ShiftLeft_(r5, r4, r6);
2368   __ add(r5, r11, r5);
2369
2370   __ LoadP(r18, FieldMemOperand(subject, String::kLengthOffset));
2371   __ SmiUntag(r18);
2372   __ ShiftLeft_(r6, r18, r6);
2373   __ add(r6, r11, r6);
2374
2375   // Argument 2 (r4): Previous index.
2376   // Already there
2377
2378   // Argument 1 (r3): Subject string.
2379   __ mr(r3, subject);
2380
2381   // Locate the code entry and call it.
2382   __ addi(code, code, Operand(Code::kHeaderSize - kHeapObjectTag));
2383
2384
2385 #if ABI_USES_FUNCTION_DESCRIPTORS && defined(USE_SIMULATOR)
2386   // Even Simulated AIX/PPC64 Linux uses a function descriptor for the
2387   // RegExp routine.  Extract the instruction address here since
2388   // DirectCEntryStub::GenerateCall will not do it for calls out to
2389   // what it thinks is C code compiled for the simulator/host
2390   // platform.
2391   __ LoadP(code, MemOperand(code, 0));  // Instruction address
2392 #endif
2393
2394   DirectCEntryStub stub(isolate());
2395   stub.GenerateCall(masm, code);
2396
2397   __ LeaveExitFrame(false, no_reg, true);
2398
2399   // r3: result (int32)
2400   // subject: subject string (callee saved)
2401   // regexp_data: RegExp data (callee saved)
2402   // last_match_info_elements: Last match info elements (callee saved)
2403   // Check the result.
2404   Label success;
2405   __ cmpwi(r3, Operand(1));
2406   // We expect exactly one result since we force the called regexp to behave
2407   // as non-global.
2408   __ beq(&success);
2409   Label failure;
2410   __ cmpwi(r3, Operand(NativeRegExpMacroAssembler::FAILURE));
2411   __ beq(&failure);
2412   __ cmpwi(r3, Operand(NativeRegExpMacroAssembler::EXCEPTION));
2413   // If not exception it can only be retry. Handle that in the runtime system.
2414   __ bne(&runtime);
2415   // Result must now be exception. If there is no pending exception already a
2416   // stack overflow (on the backtrack stack) was detected in RegExp code but
2417   // haven't created the exception yet. Handle that in the runtime system.
2418   // TODO(592): Rerunning the RegExp to get the stack overflow exception.
2419   __ mov(r4, Operand(isolate()->factory()->the_hole_value()));
2420   __ mov(r5, Operand(ExternalReference(Isolate::kPendingExceptionAddress,
2421                                        isolate())));
2422   __ LoadP(r3, MemOperand(r5, 0));
2423   __ cmp(r3, r4);
2424   __ beq(&runtime);
2425
2426   // For exception, throw the exception again.
2427   __ TailCallRuntime(Runtime::kRegExpExecReThrow, 4, 1);
2428
2429   __ bind(&failure);
2430   // For failure and exception return null.
2431   __ mov(r3, Operand(isolate()->factory()->null_value()));
2432   __ addi(sp, sp, Operand(4 * kPointerSize));
2433   __ Ret();
2434
2435   // Process the result from the native regexp code.
2436   __ bind(&success);
2437   __ LoadP(r4,
2438            FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
2439   // Calculate number of capture registers (number_of_captures + 1) * 2.
2440   // SmiToShortArrayOffset accomplishes the multiplication by 2 and
2441   // SmiUntag (which is a nop for 32-bit).
2442   __ SmiToShortArrayOffset(r4, r4);
2443   __ addi(r4, r4, Operand(2));
2444
2445   __ LoadP(r3, MemOperand(sp, kLastMatchInfoOffset));
2446   __ JumpIfSmi(r3, &runtime);
2447   __ CompareObjectType(r3, r5, r5, JS_ARRAY_TYPE);
2448   __ bne(&runtime);
2449   // Check that the JSArray is in fast case.
2450   __ LoadP(last_match_info_elements,
2451            FieldMemOperand(r3, JSArray::kElementsOffset));
2452   __ LoadP(r3,
2453            FieldMemOperand(last_match_info_elements, HeapObject::kMapOffset));
2454   __ CompareRoot(r3, Heap::kFixedArrayMapRootIndex);
2455   __ bne(&runtime);
2456   // Check that the last match info has space for the capture registers and the
2457   // additional information.
2458   __ LoadP(
2459       r3, FieldMemOperand(last_match_info_elements, FixedArray::kLengthOffset));
2460   __ addi(r5, r4, Operand(RegExpImpl::kLastMatchOverhead));
2461   __ SmiUntag(r0, r3);
2462   __ cmp(r5, r0);
2463   __ bgt(&runtime);
2464
2465   // r4: number of capture registers
2466   // subject: subject string
2467   // Store the capture count.
2468   __ SmiTag(r5, r4);
2469   __ StoreP(r5, FieldMemOperand(last_match_info_elements,
2470                                 RegExpImpl::kLastCaptureCountOffset),
2471             r0);
2472   // Store last subject and last input.
2473   __ StoreP(subject, FieldMemOperand(last_match_info_elements,
2474                                      RegExpImpl::kLastSubjectOffset),
2475             r0);
2476   __ mr(r5, subject);
2477   __ RecordWriteField(last_match_info_elements, RegExpImpl::kLastSubjectOffset,
2478                       subject, r10, kLRHasNotBeenSaved, kDontSaveFPRegs);
2479   __ mr(subject, r5);
2480   __ StoreP(subject, FieldMemOperand(last_match_info_elements,
2481                                      RegExpImpl::kLastInputOffset),
2482             r0);
2483   __ RecordWriteField(last_match_info_elements, RegExpImpl::kLastInputOffset,
2484                       subject, r10, kLRHasNotBeenSaved, kDontSaveFPRegs);
2485
2486   // Get the static offsets vector filled by the native regexp code.
2487   ExternalReference address_of_static_offsets_vector =
2488       ExternalReference::address_of_static_offsets_vector(isolate());
2489   __ mov(r5, Operand(address_of_static_offsets_vector));
2490
2491   // r4: number of capture registers
2492   // r5: offsets vector
2493   Label next_capture;
2494   // Capture register counter starts from number of capture registers and
2495   // counts down until wraping after zero.
2496   __ addi(
2497       r3, last_match_info_elements,
2498       Operand(RegExpImpl::kFirstCaptureOffset - kHeapObjectTag - kPointerSize));
2499   __ addi(r5, r5, Operand(-kIntSize));  // bias down for lwzu
2500   __ mtctr(r4);
2501   __ bind(&next_capture);
2502   // Read the value from the static offsets vector buffer.
2503   __ lwzu(r6, MemOperand(r5, kIntSize));
2504   // Store the smi value in the last match info.
2505   __ SmiTag(r6);
2506   __ StorePU(r6, MemOperand(r3, kPointerSize));
2507   __ bdnz(&next_capture);
2508
2509   // Return last match info.
2510   __ LoadP(r3, MemOperand(sp, kLastMatchInfoOffset));
2511   __ addi(sp, sp, Operand(4 * kPointerSize));
2512   __ Ret();
2513
2514   // Do the runtime call to execute the regexp.
2515   __ bind(&runtime);
2516   __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
2517
2518   // Deferred code for string handling.
2519   // (6) Not a long external string?  If yes, go to (8).
2520   __ bind(&not_seq_nor_cons);
2521   // Compare flags are still set.
2522   __ bgt(&not_long_external);  // Go to (8).
2523
2524   // (7) External string.  Make it, offset-wise, look like a sequential string.
2525   __ bind(&external_string);
2526   __ LoadP(r3, FieldMemOperand(subject, HeapObject::kMapOffset));
2527   __ lbz(r3, FieldMemOperand(r3, Map::kInstanceTypeOffset));
2528   if (FLAG_debug_code) {
2529     // Assert that we do not have a cons or slice (indirect strings) here.
2530     // Sequential strings have already been ruled out.
2531     STATIC_ASSERT(kIsIndirectStringMask == 1);
2532     __ andi(r0, r3, Operand(kIsIndirectStringMask));
2533     __ Assert(eq, kExternalStringExpectedButNotFound, cr0);
2534   }
2535   __ LoadP(subject,
2536            FieldMemOperand(subject, ExternalString::kResourceDataOffset));
2537   // Move the pointer so that offset-wise, it looks like a sequential string.
2538   STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
2539   __ subi(subject, subject,
2540           Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
2541   __ b(&seq_string);  // Go to (5).
2542
2543   // (8) Short external string or not a string?  If yes, bail out to runtime.
2544   __ bind(&not_long_external);
2545   STATIC_ASSERT(kNotStringTag != 0 && kShortExternalStringTag != 0);
2546   __ andi(r0, r4, Operand(kIsNotStringMask | kShortExternalStringMask));
2547   __ bne(&runtime, cr0);
2548
2549   // (9) Sliced string.  Replace subject with parent.  Go to (4).
2550   // Load offset into r11 and replace subject string with parent.
2551   __ LoadP(r11, FieldMemOperand(subject, SlicedString::kOffsetOffset));
2552   __ SmiUntag(r11);
2553   __ LoadP(subject, FieldMemOperand(subject, SlicedString::kParentOffset));
2554   __ b(&check_underlying);  // Go to (4).
2555 #endif  // V8_INTERPRETED_REGEXP
2556 }
2557
2558
2559 static void CallStubInRecordCallTarget(MacroAssembler* masm, CodeStub* stub) {
2560   // r3 : number of arguments to the construct function
2561   // r5 : Feedback vector
2562   // r6 : slot in feedback vector (Smi)
2563   // r4 : the function to call
2564   FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
2565
2566   // Number-of-arguments register must be smi-tagged to call out.
2567   __ SmiTag(r3);
2568   __ Push(r6, r5, r4, r3);
2569
2570   __ CallStub(stub);
2571
2572   __ Pop(r6, r5, r4, r3);
2573   __ SmiUntag(r3);
2574 }
2575
2576
2577 static void GenerateRecordCallTarget(MacroAssembler* masm) {
2578   // Cache the called function in a feedback vector slot.  Cache states
2579   // are uninitialized, monomorphic (indicated by a JSFunction), and
2580   // megamorphic.
2581   // r3 : number of arguments to the construct function
2582   // r4 : the function to call
2583   // r5 : Feedback vector
2584   // r6 : slot in feedback vector (Smi)
2585   Label initialize, done, miss, megamorphic, not_array_function;
2586
2587   DCHECK_EQ(*TypeFeedbackVector::MegamorphicSentinel(masm->isolate()),
2588             masm->isolate()->heap()->megamorphic_symbol());
2589   DCHECK_EQ(*TypeFeedbackVector::UninitializedSentinel(masm->isolate()),
2590             masm->isolate()->heap()->uninitialized_symbol());
2591
2592   // Load the cache state into r7.
2593   __ SmiToPtrArrayOffset(r7, r6);
2594   __ add(r7, r5, r7);
2595   __ LoadP(r7, FieldMemOperand(r7, FixedArray::kHeaderSize));
2596
2597   // A monomorphic cache hit or an already megamorphic state: invoke the
2598   // function without changing the state.
2599   // We don't know if r7 is a WeakCell or a Symbol, but it's harmless to read at
2600   // this position in a symbol (see static asserts in type-feedback-vector.h).
2601   Label check_allocation_site;
2602   Register feedback_map = r8;
2603   Register weak_value = r9;
2604   __ LoadP(weak_value, FieldMemOperand(r7, WeakCell::kValueOffset));
2605   __ cmp(r4, weak_value);
2606   __ beq(&done);
2607   __ CompareRoot(r7, Heap::kmegamorphic_symbolRootIndex);
2608   __ beq(&done);
2609   __ LoadP(feedback_map, FieldMemOperand(r7, HeapObject::kMapOffset));
2610   __ CompareRoot(feedback_map, Heap::kWeakCellMapRootIndex);
2611   __ bne(FLAG_pretenuring_call_new ? &miss : &check_allocation_site);
2612
2613   // If the weak cell is cleared, we have a new chance to become monomorphic.
2614   __ JumpIfSmi(weak_value, &initialize);
2615   __ b(&megamorphic);
2616
2617   if (!FLAG_pretenuring_call_new) {
2618     __ bind(&check_allocation_site);
2619     // If we came here, we need to see if we are the array function.
2620     // If we didn't have a matching function, and we didn't find the megamorph
2621     // sentinel, then we have in the slot either some other function or an
2622     // AllocationSite.
2623     __ CompareRoot(feedback_map, Heap::kAllocationSiteMapRootIndex);
2624     __ bne(&miss);
2625
2626     // Make sure the function is the Array() function
2627     __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r7);
2628     __ cmp(r4, r7);
2629     __ bne(&megamorphic);
2630     __ b(&done);
2631   }
2632
2633   __ bind(&miss);
2634
2635   // A monomorphic miss (i.e, here the cache is not uninitialized) goes
2636   // megamorphic.
2637   __ CompareRoot(r7, Heap::kuninitialized_symbolRootIndex);
2638   __ beq(&initialize);
2639   // MegamorphicSentinel is an immortal immovable object (undefined) so no
2640   // write-barrier is needed.
2641   __ bind(&megamorphic);
2642   __ SmiToPtrArrayOffset(r7, r6);
2643   __ add(r7, r5, r7);
2644   __ LoadRoot(ip, Heap::kmegamorphic_symbolRootIndex);
2645   __ StoreP(ip, FieldMemOperand(r7, FixedArray::kHeaderSize), r0);
2646   __ jmp(&done);
2647
2648   // An uninitialized cache is patched with the function
2649   __ bind(&initialize);
2650
2651   if (!FLAG_pretenuring_call_new) {
2652     // Make sure the function is the Array() function.
2653     __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r7);
2654     __ cmp(r4, r7);
2655     __ bne(&not_array_function);
2656
2657     // The target function is the Array constructor,
2658     // Create an AllocationSite if we don't already have it, store it in the
2659     // slot.
2660     CreateAllocationSiteStub create_stub(masm->isolate());
2661     CallStubInRecordCallTarget(masm, &create_stub);
2662     __ b(&done);
2663
2664     __ bind(&not_array_function);
2665   }
2666
2667   CreateWeakCellStub create_stub(masm->isolate());
2668   CallStubInRecordCallTarget(masm, &create_stub);
2669   __ bind(&done);
2670 }
2671
2672
2673 static void EmitContinueIfStrictOrNative(MacroAssembler* masm, Label* cont) {
2674   // Do not transform the receiver for strict mode functions and natives.
2675   __ LoadP(r6, FieldMemOperand(r4, JSFunction::kSharedFunctionInfoOffset));
2676   __ lwz(r7, FieldMemOperand(r6, SharedFunctionInfo::kCompilerHintsOffset));
2677   __ TestBit(r7,
2678 #if V8_TARGET_ARCH_PPC64
2679              SharedFunctionInfo::kStrictModeFunction,
2680 #else
2681              SharedFunctionInfo::kStrictModeFunction + kSmiTagSize,
2682 #endif
2683              r0);
2684   __ bne(cont, cr0);
2685
2686   // Do not transform the receiver for native.
2687   __ TestBit(r7,
2688 #if V8_TARGET_ARCH_PPC64
2689              SharedFunctionInfo::kNative,
2690 #else
2691              SharedFunctionInfo::kNative + kSmiTagSize,
2692 #endif
2693              r0);
2694   __ bne(cont, cr0);
2695 }
2696
2697
2698 static void EmitSlowCase(MacroAssembler* masm, int argc, Label* non_function) {
2699   // Check for function proxy.
2700   STATIC_ASSERT(JS_FUNCTION_PROXY_TYPE < 0xffffu);
2701   __ cmpi(r7, Operand(JS_FUNCTION_PROXY_TYPE));
2702   __ bne(non_function);
2703   __ push(r4);  // put proxy as additional argument
2704   __ li(r3, Operand(argc + 1));
2705   __ li(r5, Operand::Zero());
2706   __ GetBuiltinFunction(r4, Builtins::CALL_FUNCTION_PROXY);
2707   {
2708     Handle<Code> adaptor =
2709         masm->isolate()->builtins()->ArgumentsAdaptorTrampoline();
2710     __ Jump(adaptor, RelocInfo::CODE_TARGET);
2711   }
2712
2713   // CALL_NON_FUNCTION expects the non-function callee as receiver (instead
2714   // of the original receiver from the call site).
2715   __ bind(non_function);
2716   __ StoreP(r4, MemOperand(sp, argc * kPointerSize), r0);
2717   __ li(r3, Operand(argc));  // Set up the number of arguments.
2718   __ li(r5, Operand::Zero());
2719   __ GetBuiltinFunction(r4, Builtins::CALL_NON_FUNCTION);
2720   __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
2721           RelocInfo::CODE_TARGET);
2722 }
2723
2724
2725 static void EmitWrapCase(MacroAssembler* masm, int argc, Label* cont) {
2726   // Wrap the receiver and patch it back onto the stack.
2727   {
2728     FrameAndConstantPoolScope frame_scope(masm, StackFrame::INTERNAL);
2729     __ Push(r4, r6);
2730     __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
2731     __ pop(r4);
2732   }
2733   __ StoreP(r3, MemOperand(sp, argc * kPointerSize), r0);
2734   __ b(cont);
2735 }
2736
2737
2738 static void CallFunctionNoFeedback(MacroAssembler* masm, int argc,
2739                                    bool needs_checks, bool call_as_method) {
2740   // r4 : the function to call
2741   Label slow, non_function, wrap, cont;
2742
2743   if (needs_checks) {
2744     // Check that the function is really a JavaScript function.
2745     // r4: pushed function (to be verified)
2746     __ JumpIfSmi(r4, &non_function);
2747
2748     // Goto slow case if we do not have a function.
2749     __ CompareObjectType(r4, r7, r7, JS_FUNCTION_TYPE);
2750     __ bne(&slow);
2751   }
2752
2753   // Fast-case: Invoke the function now.
2754   // r4: pushed function
2755   ParameterCount actual(argc);
2756
2757   if (call_as_method) {
2758     if (needs_checks) {
2759       EmitContinueIfStrictOrNative(masm, &cont);
2760     }
2761
2762     // Compute the receiver in sloppy mode.
2763     __ LoadP(r6, MemOperand(sp, argc * kPointerSize), r0);
2764
2765     if (needs_checks) {
2766       __ JumpIfSmi(r6, &wrap);
2767       __ CompareObjectType(r6, r7, r7, FIRST_SPEC_OBJECT_TYPE);
2768       __ blt(&wrap);
2769     } else {
2770       __ b(&wrap);
2771     }
2772
2773     __ bind(&cont);
2774   }
2775
2776   __ InvokeFunction(r4, actual, JUMP_FUNCTION, NullCallWrapper());
2777
2778   if (needs_checks) {
2779     // Slow-case: Non-function called.
2780     __ bind(&slow);
2781     EmitSlowCase(masm, argc, &non_function);
2782   }
2783
2784   if (call_as_method) {
2785     __ bind(&wrap);
2786     EmitWrapCase(masm, argc, &cont);
2787   }
2788 }
2789
2790
2791 void CallFunctionStub::Generate(MacroAssembler* masm) {
2792   CallFunctionNoFeedback(masm, argc(), NeedsChecks(), CallAsMethod());
2793 }
2794
2795
2796 void CallConstructStub::Generate(MacroAssembler* masm) {
2797   // r3 : number of arguments
2798   // r4 : the function to call
2799   // r5 : feedback vector
2800   // r6 : (only if r5 is not the megamorphic symbol) slot in feedback
2801   //      vector (Smi)
2802   Label slow, non_function_call;
2803
2804   // Check that the function is not a smi.
2805   __ JumpIfSmi(r4, &non_function_call);
2806   // Check that the function is a JSFunction.
2807   __ CompareObjectType(r4, r7, r7, JS_FUNCTION_TYPE);
2808   __ bne(&slow);
2809
2810   if (RecordCallTarget()) {
2811     GenerateRecordCallTarget(masm);
2812
2813     __ SmiToPtrArrayOffset(r8, r6);
2814     __ add(r8, r5, r8);
2815     if (FLAG_pretenuring_call_new) {
2816       // Put the AllocationSite from the feedback vector into r5.
2817       // By adding kPointerSize we encode that we know the AllocationSite
2818       // entry is at the feedback vector slot given by r6 + 1.
2819       __ LoadP(r5, FieldMemOperand(r8, FixedArray::kHeaderSize + kPointerSize));
2820     } else {
2821       // Put the AllocationSite from the feedback vector into r5, or undefined.
2822       __ LoadP(r5, FieldMemOperand(r8, FixedArray::kHeaderSize));
2823       __ LoadP(r8, FieldMemOperand(r5, AllocationSite::kMapOffset));
2824       __ CompareRoot(r8, Heap::kAllocationSiteMapRootIndex);
2825       if (CpuFeatures::IsSupported(ISELECT)) {
2826         __ LoadRoot(r8, Heap::kUndefinedValueRootIndex);
2827         __ isel(eq, r5, r5, r8);
2828       } else {
2829         Label feedback_register_initialized;
2830         __ beq(&feedback_register_initialized);
2831         __ LoadRoot(r5, Heap::kUndefinedValueRootIndex);
2832         __ bind(&feedback_register_initialized);
2833       }
2834     }
2835
2836     __ AssertUndefinedOrAllocationSite(r5, r8);
2837   }
2838
2839   // Pass function as original constructor.
2840   if (IsSuperConstructorCall()) {
2841     __ ShiftLeftImm(r7, r3, Operand(kPointerSizeLog2));
2842     __ addi(r7, r7, Operand(kPointerSize));
2843     __ LoadPX(r6, MemOperand(sp, r7));
2844   } else {
2845     __ mr(r6, r4);
2846   }
2847
2848   // Jump to the function-specific construct stub.
2849   Register jmp_reg = r7;
2850   __ LoadP(jmp_reg, FieldMemOperand(r4, JSFunction::kSharedFunctionInfoOffset));
2851   __ LoadP(jmp_reg,
2852            FieldMemOperand(jmp_reg, SharedFunctionInfo::kConstructStubOffset));
2853   __ addi(ip, jmp_reg, Operand(Code::kHeaderSize - kHeapObjectTag));
2854   __ JumpToJSEntry(ip);
2855
2856   // r3: number of arguments
2857   // r4: called object
2858   // r7: object type
2859   Label do_call;
2860   __ bind(&slow);
2861   STATIC_ASSERT(JS_FUNCTION_PROXY_TYPE < 0xffffu);
2862   __ cmpi(r7, Operand(JS_FUNCTION_PROXY_TYPE));
2863   __ bne(&non_function_call);
2864   __ GetBuiltinFunction(r4, Builtins::CALL_FUNCTION_PROXY_AS_CONSTRUCTOR);
2865   __ b(&do_call);
2866
2867   __ bind(&non_function_call);
2868   __ GetBuiltinFunction(r4, Builtins::CALL_NON_FUNCTION_AS_CONSTRUCTOR);
2869   __ bind(&do_call);
2870   // Set expected number of arguments to zero (not changing r3).
2871   __ li(r5, Operand::Zero());
2872   __ Jump(masm->isolate()->builtins()->ArgumentsAdaptorTrampoline(),
2873           RelocInfo::CODE_TARGET);
2874 }
2875
2876
2877 static void EmitLoadTypeFeedbackVector(MacroAssembler* masm, Register vector) {
2878   __ LoadP(vector, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
2879   __ LoadP(vector,
2880            FieldMemOperand(vector, JSFunction::kSharedFunctionInfoOffset));
2881   __ LoadP(vector,
2882            FieldMemOperand(vector, SharedFunctionInfo::kFeedbackVectorOffset));
2883 }
2884
2885
2886 void CallIC_ArrayStub::Generate(MacroAssembler* masm) {
2887   // r4 - function
2888   // r6 - slot id
2889   // r5 - vector
2890   Label miss;
2891   int argc = arg_count();
2892   ParameterCount actual(argc);
2893
2894   __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r7);
2895   __ cmp(r4, r7);
2896   __ bne(&miss);
2897
2898   __ mov(r3, Operand(arg_count()));
2899   __ SmiToPtrArrayOffset(r7, r6);
2900   __ add(r7, r5, r7);
2901   __ LoadP(r7, FieldMemOperand(r7, FixedArray::kHeaderSize));
2902
2903   // Verify that r7 contains an AllocationSite
2904   __ LoadP(r8, FieldMemOperand(r7, HeapObject::kMapOffset));
2905   __ CompareRoot(r8, Heap::kAllocationSiteMapRootIndex);
2906   __ bne(&miss);
2907
2908   __ mr(r5, r7);
2909   __ mr(r6, r4);
2910   ArrayConstructorStub stub(masm->isolate(), arg_count());
2911   __ TailCallStub(&stub);
2912
2913   __ bind(&miss);
2914   GenerateMiss(masm);
2915
2916   // The slow case, we need this no matter what to complete a call after a miss.
2917   CallFunctionNoFeedback(masm, arg_count(), true, CallAsMethod());
2918
2919   // Unreachable.
2920   __ stop("Unexpected code address");
2921 }
2922
2923
2924 void CallICStub::Generate(MacroAssembler* masm) {
2925   // r4 - function
2926   // r6 - slot id (Smi)
2927   // r5 - vector
2928   const int with_types_offset =
2929       FixedArray::OffsetOfElementAt(TypeFeedbackVector::kWithTypesIndex);
2930   const int generic_offset =
2931       FixedArray::OffsetOfElementAt(TypeFeedbackVector::kGenericCountIndex);
2932   Label extra_checks_or_miss, slow_start;
2933   Label slow, non_function, wrap, cont;
2934   Label have_js_function;
2935   int argc = arg_count();
2936   ParameterCount actual(argc);
2937
2938   // The checks. First, does r4 match the recorded monomorphic target?
2939   __ SmiToPtrArrayOffset(r7, r6);
2940   __ add(r7, r5, r7);
2941   __ LoadP(r7, FieldMemOperand(r7, FixedArray::kHeaderSize));
2942
2943   // We don't know that we have a weak cell. We might have a private symbol
2944   // or an AllocationSite, but the memory is safe to examine.
2945   // AllocationSite::kTransitionInfoOffset - contains a Smi or pointer to
2946   // FixedArray.
2947   // WeakCell::kValueOffset - contains a JSFunction or Smi(0)
2948   // Symbol::kHashFieldSlot - if the low bit is 1, then the hash is not
2949   // computed, meaning that it can't appear to be a pointer. If the low bit is
2950   // 0, then hash is computed, but the 0 bit prevents the field from appearing
2951   // to be a pointer.
2952   STATIC_ASSERT(WeakCell::kSize >= kPointerSize);
2953   STATIC_ASSERT(AllocationSite::kTransitionInfoOffset ==
2954                     WeakCell::kValueOffset &&
2955                 WeakCell::kValueOffset == Symbol::kHashFieldSlot);
2956
2957   __ LoadP(r8, FieldMemOperand(r7, WeakCell::kValueOffset));
2958   __ cmp(r4, r8);
2959   __ bne(&extra_checks_or_miss);
2960
2961   // The compare above could have been a SMI/SMI comparison. Guard against this
2962   // convincing us that we have a monomorphic JSFunction.
2963   __ JumpIfSmi(r4, &extra_checks_or_miss);
2964
2965   __ bind(&have_js_function);
2966   if (CallAsMethod()) {
2967     EmitContinueIfStrictOrNative(masm, &cont);
2968     // Compute the receiver in sloppy mode.
2969     __ LoadP(r6, MemOperand(sp, argc * kPointerSize), r0);
2970
2971     __ JumpIfSmi(r6, &wrap);
2972     __ CompareObjectType(r6, r7, r7, FIRST_SPEC_OBJECT_TYPE);
2973     __ blt(&wrap);
2974
2975     __ bind(&cont);
2976   }
2977
2978   __ InvokeFunction(r4, actual, JUMP_FUNCTION, NullCallWrapper());
2979
2980   __ bind(&slow);
2981   EmitSlowCase(masm, argc, &non_function);
2982
2983   if (CallAsMethod()) {
2984     __ bind(&wrap);
2985     EmitWrapCase(masm, argc, &cont);
2986   }
2987
2988   __ bind(&extra_checks_or_miss);
2989   Label uninitialized, miss;
2990
2991   __ CompareRoot(r7, Heap::kmegamorphic_symbolRootIndex);
2992   __ beq(&slow_start);
2993
2994   // The following cases attempt to handle MISS cases without going to the
2995   // runtime.
2996   if (FLAG_trace_ic) {
2997     __ b(&miss);
2998   }
2999
3000   __ CompareRoot(r7, Heap::kuninitialized_symbolRootIndex);
3001   __ beq(&uninitialized);
3002
3003   // We are going megamorphic. If the feedback is a JSFunction, it is fine
3004   // to handle it here. More complex cases are dealt with in the runtime.
3005   __ AssertNotSmi(r7);
3006   __ CompareObjectType(r7, r8, r8, JS_FUNCTION_TYPE);
3007   __ bne(&miss);
3008   __ SmiToPtrArrayOffset(r7, r6);
3009   __ add(r7, r5, r7);
3010   __ LoadRoot(ip, Heap::kmegamorphic_symbolRootIndex);
3011   __ StoreP(ip, FieldMemOperand(r7, FixedArray::kHeaderSize), r0);
3012   // We have to update statistics for runtime profiling.
3013   __ LoadP(r7, FieldMemOperand(r5, with_types_offset));
3014   __ SubSmiLiteral(r7, r7, Smi::FromInt(1), r0);
3015   __ StoreP(r7, FieldMemOperand(r5, with_types_offset), r0);
3016   __ LoadP(r7, FieldMemOperand(r5, generic_offset));
3017   __ AddSmiLiteral(r7, r7, Smi::FromInt(1), r0);
3018   __ StoreP(r7, FieldMemOperand(r5, generic_offset), r0);
3019   __ b(&slow_start);
3020
3021   __ bind(&uninitialized);
3022
3023   // We are going monomorphic, provided we actually have a JSFunction.
3024   __ JumpIfSmi(r4, &miss);
3025
3026   // Goto miss case if we do not have a function.
3027   __ CompareObjectType(r4, r7, r7, JS_FUNCTION_TYPE);
3028   __ bne(&miss);
3029
3030   // Make sure the function is not the Array() function, which requires special
3031   // behavior on MISS.
3032   __ LoadGlobalFunction(Context::ARRAY_FUNCTION_INDEX, r7);
3033   __ cmp(r4, r7);
3034   __ beq(&miss);
3035
3036   // Update stats.
3037   __ LoadP(r7, FieldMemOperand(r5, with_types_offset));
3038   __ AddSmiLiteral(r7, r7, Smi::FromInt(1), r0);
3039   __ StoreP(r7, FieldMemOperand(r5, with_types_offset), r0);
3040
3041   // Store the function. Use a stub since we need a frame for allocation.
3042   // r5 - vector
3043   // r6 - slot
3044   // r4 - function
3045   {
3046     FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
3047     CreateWeakCellStub create_stub(masm->isolate());
3048     __ Push(r4);
3049     __ CallStub(&create_stub);
3050     __ Pop(r4);
3051   }
3052
3053   __ b(&have_js_function);
3054
3055   // We are here because tracing is on or we encountered a MISS case we can't
3056   // handle here.
3057   __ bind(&miss);
3058   GenerateMiss(masm);
3059
3060   // the slow case
3061   __ bind(&slow_start);
3062   // Check that the function is really a JavaScript function.
3063   // r4: pushed function (to be verified)
3064   __ JumpIfSmi(r4, &non_function);
3065
3066   // Goto slow case if we do not have a function.
3067   __ CompareObjectType(r4, r7, r7, JS_FUNCTION_TYPE);
3068   __ bne(&slow);
3069   __ b(&have_js_function);
3070 }
3071
3072
3073 void CallICStub::GenerateMiss(MacroAssembler* masm) {
3074   FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
3075
3076   // Push the function and feedback info.
3077   __ Push(r4, r5, r6);
3078
3079   // Call the entry.
3080   IC::UtilityId id = GetICState() == DEFAULT ? IC::kCallIC_Miss
3081                                              : IC::kCallIC_Customization_Miss;
3082
3083   ExternalReference miss = ExternalReference(IC_Utility(id), masm->isolate());
3084   __ CallExternalReference(miss, 3);
3085
3086   // Move result to r4 and exit the internal frame.
3087   __ mr(r4, r3);
3088 }
3089
3090
3091 // StringCharCodeAtGenerator
3092 void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
3093   // If the receiver is a smi trigger the non-string case.
3094   if (check_mode_ == RECEIVER_IS_UNKNOWN) {
3095     __ JumpIfSmi(object_, receiver_not_string_);
3096
3097     // Fetch the instance type of the receiver into result register.
3098     __ LoadP(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
3099     __ lbz(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset));
3100     // If the receiver is not a string trigger the non-string case.
3101     __ andi(r0, result_, Operand(kIsNotStringMask));
3102     __ bne(receiver_not_string_, cr0);
3103   }
3104
3105   // If the index is non-smi trigger the non-smi case.
3106   __ JumpIfNotSmi(index_, &index_not_smi_);
3107   __ bind(&got_smi_index_);
3108
3109   // Check for index out of range.
3110   __ LoadP(ip, FieldMemOperand(object_, String::kLengthOffset));
3111   __ cmpl(ip, index_);
3112   __ ble(index_out_of_range_);
3113
3114   __ SmiUntag(index_);
3115
3116   StringCharLoadGenerator::Generate(masm, object_, index_, result_,
3117                                     &call_runtime_);
3118
3119   __ SmiTag(result_);
3120   __ bind(&exit_);
3121 }
3122
3123
3124 void StringCharCodeAtGenerator::GenerateSlow(
3125     MacroAssembler* masm, EmbedMode embed_mode,
3126     const RuntimeCallHelper& call_helper) {
3127   __ Abort(kUnexpectedFallthroughToCharCodeAtSlowCase);
3128
3129   // Index is not a smi.
3130   __ bind(&index_not_smi_);
3131   // If index is a heap number, try converting it to an integer.
3132   __ CheckMap(index_, result_, Heap::kHeapNumberMapRootIndex, index_not_number_,
3133               DONT_DO_SMI_CHECK);
3134   call_helper.BeforeCall(masm);
3135   if (embed_mode == PART_OF_IC_HANDLER) {
3136     __ Push(LoadWithVectorDescriptor::VectorRegister(),
3137             LoadWithVectorDescriptor::SlotRegister(), object_, index_);
3138   } else {
3139     // index_ is consumed by runtime conversion function.
3140     __ Push(object_, index_);
3141   }
3142   if (index_flags_ == STRING_INDEX_IS_NUMBER) {
3143     __ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
3144   } else {
3145     DCHECK(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
3146     // NumberToSmi discards numbers that are not exact integers.
3147     __ CallRuntime(Runtime::kNumberToSmi, 1);
3148   }
3149   // Save the conversion result before the pop instructions below
3150   // have a chance to overwrite it.
3151   __ Move(index_, r3);
3152   if (embed_mode == PART_OF_IC_HANDLER) {
3153     __ Pop(LoadWithVectorDescriptor::VectorRegister(),
3154            LoadWithVectorDescriptor::SlotRegister(), object_);
3155   } else {
3156     __ pop(object_);
3157   }
3158   // Reload the instance type.
3159   __ LoadP(result_, FieldMemOperand(object_, HeapObject::kMapOffset));
3160   __ lbz(result_, FieldMemOperand(result_, Map::kInstanceTypeOffset));
3161   call_helper.AfterCall(masm);
3162   // If index is still not a smi, it must be out of range.
3163   __ JumpIfNotSmi(index_, index_out_of_range_);
3164   // Otherwise, return to the fast path.
3165   __ b(&got_smi_index_);
3166
3167   // Call runtime. We get here when the receiver is a string and the
3168   // index is a number, but the code of getting the actual character
3169   // is too complex (e.g., when the string needs to be flattened).
3170   __ bind(&call_runtime_);
3171   call_helper.BeforeCall(masm);
3172   __ SmiTag(index_);
3173   __ Push(object_, index_);
3174   __ CallRuntime(Runtime::kStringCharCodeAtRT, 2);
3175   __ Move(result_, r3);
3176   call_helper.AfterCall(masm);
3177   __ b(&exit_);
3178
3179   __ Abort(kUnexpectedFallthroughFromCharCodeAtSlowCase);
3180 }
3181
3182
3183 // -------------------------------------------------------------------------
3184 // StringCharFromCodeGenerator
3185
3186 void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
3187   // Fast case of Heap::LookupSingleCharacterStringFromCode.
3188   DCHECK(base::bits::IsPowerOfTwo32(String::kMaxOneByteCharCode + 1));
3189   __ LoadSmiLiteral(r0, Smi::FromInt(~String::kMaxOneByteCharCode));
3190   __ ori(r0, r0, Operand(kSmiTagMask));
3191   __ and_(r0, code_, r0);
3192   __ cmpi(r0, Operand::Zero());
3193   __ bne(&slow_case_);
3194
3195   __ LoadRoot(result_, Heap::kSingleCharacterStringCacheRootIndex);
3196   // At this point code register contains smi tagged one-byte char code.
3197   __ mr(r0, code_);
3198   __ SmiToPtrArrayOffset(code_, code_);
3199   __ add(result_, result_, code_);
3200   __ mr(code_, r0);
3201   __ LoadP(result_, FieldMemOperand(result_, FixedArray::kHeaderSize));
3202   __ CompareRoot(result_, Heap::kUndefinedValueRootIndex);
3203   __ beq(&slow_case_);
3204   __ bind(&exit_);
3205 }
3206
3207
3208 void StringCharFromCodeGenerator::GenerateSlow(
3209     MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
3210   __ Abort(kUnexpectedFallthroughToCharFromCodeSlowCase);
3211
3212   __ bind(&slow_case_);
3213   call_helper.BeforeCall(masm);
3214   __ push(code_);
3215   __ CallRuntime(Runtime::kCharFromCode, 1);
3216   __ Move(result_, r3);
3217   call_helper.AfterCall(masm);
3218   __ b(&exit_);
3219
3220   __ Abort(kUnexpectedFallthroughFromCharFromCodeSlowCase);
3221 }
3222
3223
3224 enum CopyCharactersFlags { COPY_ONE_BYTE = 1, DEST_ALWAYS_ALIGNED = 2 };
3225
3226
3227 void StringHelper::GenerateCopyCharacters(MacroAssembler* masm, Register dest,
3228                                           Register src, Register count,
3229                                           Register scratch,
3230                                           String::Encoding encoding) {
3231   if (FLAG_debug_code) {
3232     // Check that destination is word aligned.
3233     __ andi(r0, dest, Operand(kPointerAlignmentMask));
3234     __ Check(eq, kDestinationOfCopyNotAligned, cr0);
3235   }
3236
3237   // Nothing to do for zero characters.
3238   Label done;
3239   if (encoding == String::TWO_BYTE_ENCODING) {
3240     // double the length
3241     __ add(count, count, count, LeaveOE, SetRC);
3242     __ beq(&done, cr0);
3243   } else {
3244     __ cmpi(count, Operand::Zero());
3245     __ beq(&done);
3246   }
3247
3248   // Copy count bytes from src to dst.
3249   Label byte_loop;
3250   __ mtctr(count);
3251   __ bind(&byte_loop);
3252   __ lbz(scratch, MemOperand(src));
3253   __ addi(src, src, Operand(1));
3254   __ stb(scratch, MemOperand(dest));
3255   __ addi(dest, dest, Operand(1));
3256   __ bdnz(&byte_loop);
3257
3258   __ bind(&done);
3259 }
3260
3261
3262 void SubStringStub::Generate(MacroAssembler* masm) {
3263   Label runtime;
3264
3265   // Stack frame on entry.
3266   //  lr: return address
3267   //  sp[0]: to
3268   //  sp[4]: from
3269   //  sp[8]: string
3270
3271   // This stub is called from the native-call %_SubString(...), so
3272   // nothing can be assumed about the arguments. It is tested that:
3273   //  "string" is a sequential string,
3274   //  both "from" and "to" are smis, and
3275   //  0 <= from <= to <= string.length.
3276   // If any of these assumptions fail, we call the runtime system.
3277
3278   const int kToOffset = 0 * kPointerSize;
3279   const int kFromOffset = 1 * kPointerSize;
3280   const int kStringOffset = 2 * kPointerSize;
3281
3282   __ LoadP(r5, MemOperand(sp, kToOffset));
3283   __ LoadP(r6, MemOperand(sp, kFromOffset));
3284
3285   // If either to or from had the smi tag bit set, then fail to generic runtime
3286   __ JumpIfNotSmi(r5, &runtime);
3287   __ JumpIfNotSmi(r6, &runtime);
3288   __ SmiUntag(r5);
3289   __ SmiUntag(r6, SetRC);
3290   // Both r5 and r6 are untagged integers.
3291
3292   // We want to bailout to runtime here if From is negative.
3293   __ blt(&runtime, cr0);  // From < 0.
3294
3295   __ cmpl(r6, r5);
3296   __ bgt(&runtime);  // Fail if from > to.
3297   __ sub(r5, r5, r6);
3298
3299   // Make sure first argument is a string.
3300   __ LoadP(r3, MemOperand(sp, kStringOffset));
3301   __ JumpIfSmi(r3, &runtime);
3302   Condition is_string = masm->IsObjectStringType(r3, r4);
3303   __ b(NegateCondition(is_string), &runtime, cr0);
3304
3305   Label single_char;
3306   __ cmpi(r5, Operand(1));
3307   __ b(eq, &single_char);
3308
3309   // Short-cut for the case of trivial substring.
3310   Label return_r3;
3311   // r3: original string
3312   // r5: result string length
3313   __ LoadP(r7, FieldMemOperand(r3, String::kLengthOffset));
3314   __ SmiUntag(r0, r7);
3315   __ cmpl(r5, r0);
3316   // Return original string.
3317   __ beq(&return_r3);
3318   // Longer than original string's length or negative: unsafe arguments.
3319   __ bgt(&runtime);
3320   // Shorter than original string's length: an actual substring.
3321
3322   // Deal with different string types: update the index if necessary
3323   // and put the underlying string into r8.
3324   // r3: original string
3325   // r4: instance type
3326   // r5: length
3327   // r6: from index (untagged)
3328   Label underlying_unpacked, sliced_string, seq_or_external_string;
3329   // If the string is not indirect, it can only be sequential or external.
3330   STATIC_ASSERT(kIsIndirectStringMask == (kSlicedStringTag & kConsStringTag));
3331   STATIC_ASSERT(kIsIndirectStringMask != 0);
3332   __ andi(r0, r4, Operand(kIsIndirectStringMask));
3333   __ beq(&seq_or_external_string, cr0);
3334
3335   __ andi(r0, r4, Operand(kSlicedNotConsMask));
3336   __ bne(&sliced_string, cr0);
3337   // Cons string.  Check whether it is flat, then fetch first part.
3338   __ LoadP(r8, FieldMemOperand(r3, ConsString::kSecondOffset));
3339   __ CompareRoot(r8, Heap::kempty_stringRootIndex);
3340   __ bne(&runtime);
3341   __ LoadP(r8, FieldMemOperand(r3, ConsString::kFirstOffset));
3342   // Update instance type.
3343   __ LoadP(r4, FieldMemOperand(r8, HeapObject::kMapOffset));
3344   __ lbz(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
3345   __ b(&underlying_unpacked);
3346
3347   __ bind(&sliced_string);
3348   // Sliced string.  Fetch parent and correct start index by offset.
3349   __ LoadP(r8, FieldMemOperand(r3, SlicedString::kParentOffset));
3350   __ LoadP(r7, FieldMemOperand(r3, SlicedString::kOffsetOffset));
3351   __ SmiUntag(r4, r7);
3352   __ add(r6, r6, r4);  // Add offset to index.
3353   // Update instance type.
3354   __ LoadP(r4, FieldMemOperand(r8, HeapObject::kMapOffset));
3355   __ lbz(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
3356   __ b(&underlying_unpacked);
3357
3358   __ bind(&seq_or_external_string);
3359   // Sequential or external string.  Just move string to the expected register.
3360   __ mr(r8, r3);
3361
3362   __ bind(&underlying_unpacked);
3363
3364   if (FLAG_string_slices) {
3365     Label copy_routine;
3366     // r8: underlying subject string
3367     // r4: instance type of underlying subject string
3368     // r5: length
3369     // r6: adjusted start index (untagged)
3370     __ cmpi(r5, Operand(SlicedString::kMinLength));
3371     // Short slice.  Copy instead of slicing.
3372     __ blt(&copy_routine);
3373     // Allocate new sliced string.  At this point we do not reload the instance
3374     // type including the string encoding because we simply rely on the info
3375     // provided by the original string.  It does not matter if the original
3376     // string's encoding is wrong because we always have to recheck encoding of
3377     // the newly created string's parent anyways due to externalized strings.
3378     Label two_byte_slice, set_slice_header;
3379     STATIC_ASSERT((kStringEncodingMask & kOneByteStringTag) != 0);
3380     STATIC_ASSERT((kStringEncodingMask & kTwoByteStringTag) == 0);
3381     __ andi(r0, r4, Operand(kStringEncodingMask));
3382     __ beq(&two_byte_slice, cr0);
3383     __ AllocateOneByteSlicedString(r3, r5, r9, r10, &runtime);
3384     __ b(&set_slice_header);
3385     __ bind(&two_byte_slice);
3386     __ AllocateTwoByteSlicedString(r3, r5, r9, r10, &runtime);
3387     __ bind(&set_slice_header);
3388     __ SmiTag(r6);
3389     __ StoreP(r8, FieldMemOperand(r3, SlicedString::kParentOffset), r0);
3390     __ StoreP(r6, FieldMemOperand(r3, SlicedString::kOffsetOffset), r0);
3391     __ b(&return_r3);
3392
3393     __ bind(&copy_routine);
3394   }
3395
3396   // r8: underlying subject string
3397   // r4: instance type of underlying subject string
3398   // r5: length
3399   // r6: adjusted start index (untagged)
3400   Label two_byte_sequential, sequential_string, allocate_result;
3401   STATIC_ASSERT(kExternalStringTag != 0);
3402   STATIC_ASSERT(kSeqStringTag == 0);
3403   __ andi(r0, r4, Operand(kExternalStringTag));
3404   __ beq(&sequential_string, cr0);
3405
3406   // Handle external string.
3407   // Rule out short external strings.
3408   STATIC_ASSERT(kShortExternalStringTag != 0);
3409   __ andi(r0, r4, Operand(kShortExternalStringTag));
3410   __ bne(&runtime, cr0);
3411   __ LoadP(r8, FieldMemOperand(r8, ExternalString::kResourceDataOffset));
3412   // r8 already points to the first character of underlying string.
3413   __ b(&allocate_result);
3414
3415   __ bind(&sequential_string);
3416   // Locate first character of underlying subject string.
3417   STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqOneByteString::kHeaderSize);
3418   __ addi(r8, r8, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
3419
3420   __ bind(&allocate_result);
3421   // Sequential acii string.  Allocate the result.
3422   STATIC_ASSERT((kOneByteStringTag & kStringEncodingMask) != 0);
3423   __ andi(r0, r4, Operand(kStringEncodingMask));
3424   __ beq(&two_byte_sequential, cr0);
3425
3426   // Allocate and copy the resulting one-byte string.
3427   __ AllocateOneByteString(r3, r5, r7, r9, r10, &runtime);
3428
3429   // Locate first character of substring to copy.
3430   __ add(r8, r8, r6);
3431   // Locate first character of result.
3432   __ addi(r4, r3, Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
3433
3434   // r3: result string
3435   // r4: first character of result string
3436   // r5: result string length
3437   // r8: first character of substring to copy
3438   STATIC_ASSERT((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
3439   StringHelper::GenerateCopyCharacters(masm, r4, r8, r5, r6,
3440                                        String::ONE_BYTE_ENCODING);
3441   __ b(&return_r3);
3442
3443   // Allocate and copy the resulting two-byte string.
3444   __ bind(&two_byte_sequential);
3445   __ AllocateTwoByteString(r3, r5, r7, r9, r10, &runtime);
3446
3447   // Locate first character of substring to copy.
3448   __ ShiftLeftImm(r4, r6, Operand(1));
3449   __ add(r8, r8, r4);
3450   // Locate first character of result.
3451   __ addi(r4, r3, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3452
3453   // r3: result string.
3454   // r4: first character of result.
3455   // r5: result length.
3456   // r8: first character of substring to copy.
3457   STATIC_ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
3458   StringHelper::GenerateCopyCharacters(masm, r4, r8, r5, r6,
3459                                        String::TWO_BYTE_ENCODING);
3460
3461   __ bind(&return_r3);
3462   Counters* counters = isolate()->counters();
3463   __ IncrementCounter(counters->sub_string_native(), 1, r6, r7);
3464   __ Drop(3);
3465   __ Ret();
3466
3467   // Just jump to runtime to create the sub string.
3468   __ bind(&runtime);
3469   __ TailCallRuntime(Runtime::kSubStringRT, 3, 1);
3470
3471   __ bind(&single_char);
3472   // r3: original string
3473   // r4: instance type
3474   // r5: length
3475   // r6: from index (untagged)
3476   __ SmiTag(r6, r6);
3477   StringCharAtGenerator generator(r3, r6, r5, r3, &runtime, &runtime, &runtime,
3478                                   STRING_INDEX_IS_NUMBER, RECEIVER_IS_STRING);
3479   generator.GenerateFast(masm);
3480   __ Drop(3);
3481   __ Ret();
3482   generator.SkipSlow(masm, &runtime);
3483 }
3484
3485
3486 void ToNumberStub::Generate(MacroAssembler* masm) {
3487   // The ToNumber stub takes one argument in r3.
3488   Label not_smi;
3489   __ JumpIfNotSmi(r3, &not_smi);
3490   __ blr();
3491   __ bind(&not_smi);
3492
3493   Label not_heap_number;
3494   __ LoadP(r4, FieldMemOperand(r3, HeapObject::kMapOffset));
3495   __ lbz(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
3496   // r3: object
3497   // r4: instance type.
3498   __ cmpi(r4, Operand(HEAP_NUMBER_TYPE));
3499   __ bne(&not_heap_number);
3500   __ blr();
3501   __ bind(&not_heap_number);
3502
3503   Label not_string, slow_string;
3504   __ cmpli(r4, Operand(FIRST_NONSTRING_TYPE));
3505   __ bge(&not_string);
3506   // Check if string has a cached array index.
3507   __ lwz(r5, FieldMemOperand(r3, String::kHashFieldOffset));
3508   __ And(r0, r5, Operand(String::kContainsCachedArrayIndexMask), SetRC);
3509   __ bne(&slow_string, cr0);
3510   __ IndexFromHash(r5, r3);
3511   __ blr();
3512   __ bind(&slow_string);
3513   __ push(r3);  // Push argument.
3514   __ TailCallRuntime(Runtime::kStringToNumber, 1, 1);
3515   __ bind(&not_string);
3516
3517   Label not_oddball;
3518   __ cmpi(r4, Operand(ODDBALL_TYPE));
3519   __ bne(&not_oddball);
3520   __ LoadP(r3, FieldMemOperand(r3, Oddball::kToNumberOffset));
3521   __ blr();
3522   __ bind(&not_oddball);
3523
3524   __ push(r3);  // Push argument.
3525   __ InvokeBuiltin(Builtins::TO_NUMBER, JUMP_FUNCTION);
3526 }
3527
3528
3529 void StringHelper::GenerateFlatOneByteStringEquals(MacroAssembler* masm,
3530                                                    Register left,
3531                                                    Register right,
3532                                                    Register scratch1,
3533                                                    Register scratch2) {
3534   Register length = scratch1;
3535
3536   // Compare lengths.
3537   Label strings_not_equal, check_zero_length;
3538   __ LoadP(length, FieldMemOperand(left, String::kLengthOffset));
3539   __ LoadP(scratch2, FieldMemOperand(right, String::kLengthOffset));
3540   __ cmp(length, scratch2);
3541   __ beq(&check_zero_length);
3542   __ bind(&strings_not_equal);
3543   __ LoadSmiLiteral(r3, Smi::FromInt(NOT_EQUAL));
3544   __ Ret();
3545
3546   // Check if the length is zero.
3547   Label compare_chars;
3548   __ bind(&check_zero_length);
3549   STATIC_ASSERT(kSmiTag == 0);
3550   __ cmpi(length, Operand::Zero());
3551   __ bne(&compare_chars);
3552   __ LoadSmiLiteral(r3, Smi::FromInt(EQUAL));
3553   __ Ret();
3554
3555   // Compare characters.
3556   __ bind(&compare_chars);
3557   GenerateOneByteCharsCompareLoop(masm, left, right, length, scratch2,
3558                                   &strings_not_equal);
3559
3560   // Characters are equal.
3561   __ LoadSmiLiteral(r3, Smi::FromInt(EQUAL));
3562   __ Ret();
3563 }
3564
3565
3566 void StringHelper::GenerateCompareFlatOneByteStrings(
3567     MacroAssembler* masm, Register left, Register right, Register scratch1,
3568     Register scratch2, Register scratch3) {
3569   Label result_not_equal, compare_lengths;
3570   // Find minimum length and length difference.
3571   __ LoadP(scratch1, FieldMemOperand(left, String::kLengthOffset));
3572   __ LoadP(scratch2, FieldMemOperand(right, String::kLengthOffset));
3573   __ sub(scratch3, scratch1, scratch2, LeaveOE, SetRC);
3574   Register length_delta = scratch3;
3575   if (CpuFeatures::IsSupported(ISELECT)) {
3576     __ isel(gt, scratch1, scratch2, scratch1, cr0);
3577   } else {
3578     Label skip;
3579     __ ble(&skip, cr0);
3580     __ mr(scratch1, scratch2);
3581     __ bind(&skip);
3582   }
3583   Register min_length = scratch1;
3584   STATIC_ASSERT(kSmiTag == 0);
3585   __ cmpi(min_length, Operand::Zero());
3586   __ beq(&compare_lengths);
3587
3588   // Compare loop.
3589   GenerateOneByteCharsCompareLoop(masm, left, right, min_length, scratch2,
3590                                   &result_not_equal);
3591
3592   // Compare lengths - strings up to min-length are equal.
3593   __ bind(&compare_lengths);
3594   DCHECK(Smi::FromInt(EQUAL) == static_cast<Smi*>(0));
3595   // Use length_delta as result if it's zero.
3596   __ mr(r3, length_delta);
3597   __ cmpi(r3, Operand::Zero());
3598   __ bind(&result_not_equal);
3599   // Conditionally update the result based either on length_delta or
3600   // the last comparion performed in the loop above.
3601   if (CpuFeatures::IsSupported(ISELECT)) {
3602     __ LoadSmiLiteral(r4, Smi::FromInt(GREATER));
3603     __ LoadSmiLiteral(r5, Smi::FromInt(LESS));
3604     __ isel(eq, r3, r0, r4);
3605     __ isel(lt, r3, r5, r3);
3606     __ Ret();
3607   } else {
3608     Label less_equal, equal;
3609     __ ble(&less_equal);
3610     __ LoadSmiLiteral(r3, Smi::FromInt(GREATER));
3611     __ Ret();
3612     __ bind(&less_equal);
3613     __ beq(&equal);
3614     __ LoadSmiLiteral(r3, Smi::FromInt(LESS));
3615     __ bind(&equal);
3616     __ Ret();
3617   }
3618 }
3619
3620
3621 void StringHelper::GenerateOneByteCharsCompareLoop(
3622     MacroAssembler* masm, Register left, Register right, Register length,
3623     Register scratch1, Label* chars_not_equal) {
3624   // Change index to run from -length to -1 by adding length to string
3625   // start. This means that loop ends when index reaches zero, which
3626   // doesn't need an additional compare.
3627   __ SmiUntag(length);
3628   __ addi(scratch1, length,
3629           Operand(SeqOneByteString::kHeaderSize - kHeapObjectTag));
3630   __ add(left, left, scratch1);
3631   __ add(right, right, scratch1);
3632   __ subfic(length, length, Operand::Zero());
3633   Register index = length;  // index = -length;
3634
3635   // Compare loop.
3636   Label loop;
3637   __ bind(&loop);
3638   __ lbzx(scratch1, MemOperand(left, index));
3639   __ lbzx(r0, MemOperand(right, index));
3640   __ cmp(scratch1, r0);
3641   __ bne(chars_not_equal);
3642   __ addi(index, index, Operand(1));
3643   __ cmpi(index, Operand::Zero());
3644   __ bne(&loop);
3645 }
3646
3647
3648 void StringCompareStub::Generate(MacroAssembler* masm) {
3649   Label runtime;
3650
3651   Counters* counters = isolate()->counters();
3652
3653   // Stack frame on entry.
3654   //  sp[0]: right string
3655   //  sp[4]: left string
3656   __ LoadP(r3, MemOperand(sp));  // Load right in r3, left in r4.
3657   __ LoadP(r4, MemOperand(sp, kPointerSize));
3658
3659   Label not_same;
3660   __ cmp(r3, r4);
3661   __ bne(&not_same);
3662   STATIC_ASSERT(EQUAL == 0);
3663   STATIC_ASSERT(kSmiTag == 0);
3664   __ LoadSmiLiteral(r3, Smi::FromInt(EQUAL));
3665   __ IncrementCounter(counters->string_compare_native(), 1, r4, r5);
3666   __ addi(sp, sp, Operand(2 * kPointerSize));
3667   __ Ret();
3668
3669   __ bind(&not_same);
3670
3671   // Check that both objects are sequential one-byte strings.
3672   __ JumpIfNotBothSequentialOneByteStrings(r4, r3, r5, r6, &runtime);
3673
3674   // Compare flat one-byte strings natively. Remove arguments from stack first.
3675   __ IncrementCounter(counters->string_compare_native(), 1, r5, r6);
3676   __ addi(sp, sp, Operand(2 * kPointerSize));
3677   StringHelper::GenerateCompareFlatOneByteStrings(masm, r4, r3, r5, r6, r7);
3678
3679   // Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
3680   // tagged as a small integer.
3681   __ bind(&runtime);
3682   __ TailCallRuntime(Runtime::kStringCompareRT, 2, 1);
3683 }
3684
3685
3686 void BinaryOpICWithAllocationSiteStub::Generate(MacroAssembler* masm) {
3687   // ----------- S t a t e -------------
3688   //  -- r4    : left
3689   //  -- r3    : right
3690   //  -- lr    : return address
3691   // -----------------------------------
3692
3693   // Load r5 with the allocation site.  We stick an undefined dummy value here
3694   // and replace it with the real allocation site later when we instantiate this
3695   // stub in BinaryOpICWithAllocationSiteStub::GetCodeCopyFromTemplate().
3696   __ Move(r5, handle(isolate()->heap()->undefined_value()));
3697
3698   // Make sure that we actually patched the allocation site.
3699   if (FLAG_debug_code) {
3700     __ TestIfSmi(r5, r0);
3701     __ Assert(ne, kExpectedAllocationSite, cr0);
3702     __ push(r5);
3703     __ LoadP(r5, FieldMemOperand(r5, HeapObject::kMapOffset));
3704     __ LoadRoot(ip, Heap::kAllocationSiteMapRootIndex);
3705     __ cmp(r5, ip);
3706     __ pop(r5);
3707     __ Assert(eq, kExpectedAllocationSite);
3708   }
3709
3710   // Tail call into the stub that handles binary operations with allocation
3711   // sites.
3712   BinaryOpWithAllocationSiteStub stub(isolate(), state());
3713   __ TailCallStub(&stub);
3714 }
3715
3716
3717 void CompareICStub::GenerateSmis(MacroAssembler* masm) {
3718   DCHECK(state() == CompareICState::SMI);
3719   Label miss;
3720   __ orx(r5, r4, r3);
3721   __ JumpIfNotSmi(r5, &miss);
3722
3723   if (GetCondition() == eq) {
3724     // For equality we do not care about the sign of the result.
3725     // __ sub(r3, r3, r4, SetCC);
3726     __ sub(r3, r3, r4);
3727   } else {
3728     // Untag before subtracting to avoid handling overflow.
3729     __ SmiUntag(r4);
3730     __ SmiUntag(r3);
3731     __ sub(r3, r4, r3);
3732   }
3733   __ Ret();
3734
3735   __ bind(&miss);
3736   GenerateMiss(masm);
3737 }
3738
3739
3740 void CompareICStub::GenerateNumbers(MacroAssembler* masm) {
3741   DCHECK(state() == CompareICState::NUMBER);
3742
3743   Label generic_stub;
3744   Label unordered, maybe_undefined1, maybe_undefined2;
3745   Label miss;
3746   Label equal, less_than;
3747
3748   if (left() == CompareICState::SMI) {
3749     __ JumpIfNotSmi(r4, &miss);
3750   }
3751   if (right() == CompareICState::SMI) {
3752     __ JumpIfNotSmi(r3, &miss);
3753   }
3754
3755   // Inlining the double comparison and falling back to the general compare
3756   // stub if NaN is involved.
3757   // Load left and right operand.
3758   Label done, left, left_smi, right_smi;
3759   __ JumpIfSmi(r3, &right_smi);
3760   __ CheckMap(r3, r5, Heap::kHeapNumberMapRootIndex, &maybe_undefined1,
3761               DONT_DO_SMI_CHECK);
3762   __ lfd(d1, FieldMemOperand(r3, HeapNumber::kValueOffset));
3763   __ b(&left);
3764   __ bind(&right_smi);
3765   __ SmiToDouble(d1, r3);
3766
3767   __ bind(&left);
3768   __ JumpIfSmi(r4, &left_smi);
3769   __ CheckMap(r4, r5, Heap::kHeapNumberMapRootIndex, &maybe_undefined2,
3770               DONT_DO_SMI_CHECK);
3771   __ lfd(d0, FieldMemOperand(r4, HeapNumber::kValueOffset));
3772   __ b(&done);
3773   __ bind(&left_smi);
3774   __ SmiToDouble(d0, r4);
3775
3776   __ bind(&done);
3777
3778   // Compare operands
3779   __ fcmpu(d0, d1);
3780
3781   // Don't base result on status bits when a NaN is involved.
3782   __ bunordered(&unordered);
3783
3784   // Return a result of -1, 0, or 1, based on status bits.
3785   if (CpuFeatures::IsSupported(ISELECT)) {
3786     DCHECK(EQUAL == 0);
3787     __ li(r4, Operand(GREATER));
3788     __ li(r5, Operand(LESS));
3789     __ isel(eq, r3, r0, r4);
3790     __ isel(lt, r3, r5, r3);
3791     __ Ret();
3792   } else {
3793     __ beq(&equal);
3794     __ blt(&less_than);
3795     //  assume greater than
3796     __ li(r3, Operand(GREATER));
3797     __ Ret();
3798     __ bind(&equal);
3799     __ li(r3, Operand(EQUAL));
3800     __ Ret();
3801     __ bind(&less_than);
3802     __ li(r3, Operand(LESS));
3803     __ Ret();
3804   }
3805
3806   __ bind(&unordered);
3807   __ bind(&generic_stub);
3808   CompareICStub stub(isolate(), op(), strong(), CompareICState::GENERIC,
3809                      CompareICState::GENERIC, CompareICState::GENERIC);
3810   __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
3811
3812   __ bind(&maybe_undefined1);
3813   if (Token::IsOrderedRelationalCompareOp(op())) {
3814     __ CompareRoot(r3, Heap::kUndefinedValueRootIndex);
3815     __ bne(&miss);
3816     __ JumpIfSmi(r4, &unordered);
3817     __ CompareObjectType(r4, r5, r5, HEAP_NUMBER_TYPE);
3818     __ bne(&maybe_undefined2);
3819     __ b(&unordered);
3820   }
3821
3822   __ bind(&maybe_undefined2);
3823   if (Token::IsOrderedRelationalCompareOp(op())) {
3824     __ CompareRoot(r4, Heap::kUndefinedValueRootIndex);
3825     __ beq(&unordered);
3826   }
3827
3828   __ bind(&miss);
3829   GenerateMiss(masm);
3830 }
3831
3832
3833 void CompareICStub::GenerateInternalizedStrings(MacroAssembler* masm) {
3834   DCHECK(state() == CompareICState::INTERNALIZED_STRING);
3835   Label miss, not_equal;
3836
3837   // Registers containing left and right operands respectively.
3838   Register left = r4;
3839   Register right = r3;
3840   Register tmp1 = r5;
3841   Register tmp2 = r6;
3842
3843   // Check that both operands are heap objects.
3844   __ JumpIfEitherSmi(left, right, &miss);
3845
3846   // Check that both operands are symbols.
3847   __ LoadP(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
3848   __ LoadP(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
3849   __ lbz(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
3850   __ lbz(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
3851   STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
3852   __ orx(tmp1, tmp1, tmp2);
3853   __ andi(r0, tmp1, Operand(kIsNotStringMask | kIsNotInternalizedMask));
3854   __ bne(&miss, cr0);
3855
3856   // Internalized strings are compared by identity.
3857   __ cmp(left, right);
3858   __ bne(&not_equal);
3859   // Make sure r3 is non-zero. At this point input operands are
3860   // guaranteed to be non-zero.
3861   DCHECK(right.is(r3));
3862   STATIC_ASSERT(EQUAL == 0);
3863   STATIC_ASSERT(kSmiTag == 0);
3864   __ LoadSmiLiteral(r3, Smi::FromInt(EQUAL));
3865   __ bind(&not_equal);
3866   __ Ret();
3867
3868   __ bind(&miss);
3869   GenerateMiss(masm);
3870 }
3871
3872
3873 void CompareICStub::GenerateUniqueNames(MacroAssembler* masm) {
3874   DCHECK(state() == CompareICState::UNIQUE_NAME);
3875   DCHECK(GetCondition() == eq);
3876   Label miss;
3877
3878   // Registers containing left and right operands respectively.
3879   Register left = r4;
3880   Register right = r3;
3881   Register tmp1 = r5;
3882   Register tmp2 = r6;
3883
3884   // Check that both operands are heap objects.
3885   __ JumpIfEitherSmi(left, right, &miss);
3886
3887   // Check that both operands are unique names. This leaves the instance
3888   // types loaded in tmp1 and tmp2.
3889   __ LoadP(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
3890   __ LoadP(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
3891   __ lbz(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
3892   __ lbz(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
3893
3894   __ JumpIfNotUniqueNameInstanceType(tmp1, &miss);
3895   __ JumpIfNotUniqueNameInstanceType(tmp2, &miss);
3896
3897   // Unique names are compared by identity.
3898   __ cmp(left, right);
3899   __ bne(&miss);
3900   // Make sure r3 is non-zero. At this point input operands are
3901   // guaranteed to be non-zero.
3902   DCHECK(right.is(r3));
3903   STATIC_ASSERT(EQUAL == 0);
3904   STATIC_ASSERT(kSmiTag == 0);
3905   __ LoadSmiLiteral(r3, Smi::FromInt(EQUAL));
3906   __ Ret();
3907
3908   __ bind(&miss);
3909   GenerateMiss(masm);
3910 }
3911
3912
3913 void CompareICStub::GenerateStrings(MacroAssembler* masm) {
3914   DCHECK(state() == CompareICState::STRING);
3915   Label miss, not_identical, is_symbol;
3916
3917   bool equality = Token::IsEqualityOp(op());
3918
3919   // Registers containing left and right operands respectively.
3920   Register left = r4;
3921   Register right = r3;
3922   Register tmp1 = r5;
3923   Register tmp2 = r6;
3924   Register tmp3 = r7;
3925   Register tmp4 = r8;
3926
3927   // Check that both operands are heap objects.
3928   __ JumpIfEitherSmi(left, right, &miss);
3929
3930   // Check that both operands are strings. This leaves the instance
3931   // types loaded in tmp1 and tmp2.
3932   __ LoadP(tmp1, FieldMemOperand(left, HeapObject::kMapOffset));
3933   __ LoadP(tmp2, FieldMemOperand(right, HeapObject::kMapOffset));
3934   __ lbz(tmp1, FieldMemOperand(tmp1, Map::kInstanceTypeOffset));
3935   __ lbz(tmp2, FieldMemOperand(tmp2, Map::kInstanceTypeOffset));
3936   STATIC_ASSERT(kNotStringTag != 0);
3937   __ orx(tmp3, tmp1, tmp2);
3938   __ andi(r0, tmp3, Operand(kIsNotStringMask));
3939   __ bne(&miss, cr0);
3940
3941   // Fast check for identical strings.
3942   __ cmp(left, right);
3943   STATIC_ASSERT(EQUAL == 0);
3944   STATIC_ASSERT(kSmiTag == 0);
3945   __ bne(&not_identical);
3946   __ LoadSmiLiteral(r3, Smi::FromInt(EQUAL));
3947   __ Ret();
3948   __ bind(&not_identical);
3949
3950   // Handle not identical strings.
3951
3952   // Check that both strings are internalized strings. If they are, we're done
3953   // because we already know they are not identical. We know they are both
3954   // strings.
3955   if (equality) {
3956     DCHECK(GetCondition() == eq);
3957     STATIC_ASSERT(kInternalizedTag == 0);
3958     __ orx(tmp3, tmp1, tmp2);
3959     __ andi(r0, tmp3, Operand(kIsNotInternalizedMask));
3960     __ bne(&is_symbol, cr0);
3961     // Make sure r3 is non-zero. At this point input operands are
3962     // guaranteed to be non-zero.
3963     DCHECK(right.is(r3));
3964     __ Ret();
3965     __ bind(&is_symbol);
3966   }
3967
3968   // Check that both strings are sequential one-byte.
3969   Label runtime;
3970   __ JumpIfBothInstanceTypesAreNotSequentialOneByte(tmp1, tmp2, tmp3, tmp4,
3971                                                     &runtime);
3972
3973   // Compare flat one-byte strings. Returns when done.
3974   if (equality) {
3975     StringHelper::GenerateFlatOneByteStringEquals(masm, left, right, tmp1,
3976                                                   tmp2);
3977   } else {
3978     StringHelper::GenerateCompareFlatOneByteStrings(masm, left, right, tmp1,
3979                                                     tmp2, tmp3);
3980   }
3981
3982   // Handle more complex cases in runtime.
3983   __ bind(&runtime);
3984   __ Push(left, right);
3985   if (equality) {
3986     __ TailCallRuntime(Runtime::kStringEquals, 2, 1);
3987   } else {
3988     __ TailCallRuntime(Runtime::kStringCompareRT, 2, 1);
3989   }
3990
3991   __ bind(&miss);
3992   GenerateMiss(masm);
3993 }
3994
3995
3996 void CompareICStub::GenerateObjects(MacroAssembler* masm) {
3997   DCHECK(state() == CompareICState::OBJECT);
3998   Label miss;
3999   __ and_(r5, r4, r3);
4000   __ JumpIfSmi(r5, &miss);
4001
4002   __ CompareObjectType(r3, r5, r5, JS_OBJECT_TYPE);
4003   __ bne(&miss);
4004   __ CompareObjectType(r4, r5, r5, JS_OBJECT_TYPE);
4005   __ bne(&miss);
4006
4007   DCHECK(GetCondition() == eq);
4008   __ sub(r3, r3, r4);
4009   __ Ret();
4010
4011   __ bind(&miss);
4012   GenerateMiss(masm);
4013 }
4014
4015
4016 void CompareICStub::GenerateKnownObjects(MacroAssembler* masm) {
4017   Label miss;
4018   Handle<WeakCell> cell = Map::WeakCellForMap(known_map_);
4019   __ and_(r5, r4, r3);
4020   __ JumpIfSmi(r5, &miss);
4021   __ GetWeakValue(r7, cell);
4022   __ LoadP(r5, FieldMemOperand(r3, HeapObject::kMapOffset));
4023   __ LoadP(r6, FieldMemOperand(r4, HeapObject::kMapOffset));
4024   __ cmp(r5, r7);
4025   __ bne(&miss);
4026   __ cmp(r6, r7);
4027   __ bne(&miss);
4028
4029   __ sub(r3, r3, r4);
4030   __ Ret();
4031
4032   __ bind(&miss);
4033   GenerateMiss(masm);
4034 }
4035
4036
4037 void CompareICStub::GenerateMiss(MacroAssembler* masm) {
4038   {
4039     // Call the runtime system in a fresh internal frame.
4040     ExternalReference miss =
4041         ExternalReference(IC_Utility(IC::kCompareIC_Miss), isolate());
4042
4043     FrameAndConstantPoolScope scope(masm, StackFrame::INTERNAL);
4044     __ Push(r4, r3);
4045     __ Push(r4, r3);
4046     __ LoadSmiLiteral(r0, Smi::FromInt(op()));
4047     __ push(r0);
4048     __ CallExternalReference(miss, 3);
4049     // Compute the entry point of the rewritten stub.
4050     __ addi(r5, r3, Operand(Code::kHeaderSize - kHeapObjectTag));
4051     // Restore registers.
4052     __ Pop(r4, r3);
4053   }
4054
4055   __ JumpToJSEntry(r5);
4056 }
4057
4058
4059 // This stub is paired with DirectCEntryStub::GenerateCall
4060 void DirectCEntryStub::Generate(MacroAssembler* masm) {
4061   // Place the return address on the stack, making the call
4062   // GC safe. The RegExp backend also relies on this.
4063   __ mflr(r0);
4064   __ StoreP(r0, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize));
4065   __ Call(ip);  // Call the C++ function.
4066   __ LoadP(r0, MemOperand(sp, kStackFrameExtraParamSlot * kPointerSize));
4067   __ mtlr(r0);
4068   __ blr();
4069 }
4070
4071
4072 void DirectCEntryStub::GenerateCall(MacroAssembler* masm, Register target) {
4073 #if ABI_USES_FUNCTION_DESCRIPTORS && !defined(USE_SIMULATOR)
4074   // Native AIX/PPC64 Linux use a function descriptor.
4075   __ LoadP(ToRegister(ABI_TOC_REGISTER), MemOperand(target, kPointerSize));
4076   __ LoadP(ip, MemOperand(target, 0));  // Instruction address
4077 #else
4078   // ip needs to be set for DirectCEentryStub::Generate, and also
4079   // for ABI_TOC_ADDRESSABILITY_VIA_IP.
4080   __ Move(ip, target);
4081 #endif
4082
4083   intptr_t code = reinterpret_cast<intptr_t>(GetCode().location());
4084   __ mov(r0, Operand(code, RelocInfo::CODE_TARGET));
4085   __ Call(r0);  // Call the stub.
4086 }
4087
4088
4089 void NameDictionaryLookupStub::GenerateNegativeLookup(
4090     MacroAssembler* masm, Label* miss, Label* done, Register receiver,
4091     Register properties, Handle<Name> name, Register scratch0) {
4092   DCHECK(name->IsUniqueName());
4093   // If names of slots in range from 1 to kProbes - 1 for the hash value are
4094   // not equal to the name and kProbes-th slot is not used (its name is the
4095   // undefined value), it guarantees the hash table doesn't contain the
4096   // property. It's true even if some slots represent deleted properties
4097   // (their names are the hole value).
4098   for (int i = 0; i < kInlinedProbes; i++) {
4099     // scratch0 points to properties hash.
4100     // Compute the masked index: (hash + i + i * i) & mask.
4101     Register index = scratch0;
4102     // Capacity is smi 2^n.
4103     __ LoadP(index, FieldMemOperand(properties, kCapacityOffset));
4104     __ subi(index, index, Operand(1));
4105     __ LoadSmiLiteral(
4106         ip, Smi::FromInt(name->Hash() + NameDictionary::GetProbeOffset(i)));
4107     __ and_(index, index, ip);
4108
4109     // Scale the index by multiplying by the entry size.
4110     STATIC_ASSERT(NameDictionary::kEntrySize == 3);
4111     __ ShiftLeftImm(ip, index, Operand(1));
4112     __ add(index, index, ip);  // index *= 3.
4113
4114     Register entity_name = scratch0;
4115     // Having undefined at this place means the name is not contained.
4116     Register tmp = properties;
4117     __ SmiToPtrArrayOffset(ip, index);
4118     __ add(tmp, properties, ip);
4119     __ LoadP(entity_name, FieldMemOperand(tmp, kElementsStartOffset));
4120
4121     DCHECK(!tmp.is(entity_name));
4122     __ LoadRoot(tmp, Heap::kUndefinedValueRootIndex);
4123     __ cmp(entity_name, tmp);
4124     __ beq(done);
4125
4126     // Load the hole ready for use below:
4127     __ LoadRoot(tmp, Heap::kTheHoleValueRootIndex);
4128
4129     // Stop if found the property.
4130     __ Cmpi(entity_name, Operand(Handle<Name>(name)), r0);
4131     __ beq(miss);
4132
4133     Label good;
4134     __ cmp(entity_name, tmp);
4135     __ beq(&good);
4136
4137     // Check if the entry name is not a unique name.
4138     __ LoadP(entity_name, FieldMemOperand(entity_name, HeapObject::kMapOffset));
4139     __ lbz(entity_name, FieldMemOperand(entity_name, Map::kInstanceTypeOffset));
4140     __ JumpIfNotUniqueNameInstanceType(entity_name, miss);
4141     __ bind(&good);
4142
4143     // Restore the properties.
4144     __ LoadP(properties,
4145              FieldMemOperand(receiver, JSObject::kPropertiesOffset));
4146   }
4147
4148   const int spill_mask = (r0.bit() | r9.bit() | r8.bit() | r7.bit() | r6.bit() |
4149                           r5.bit() | r4.bit() | r3.bit());
4150
4151   __ mflr(r0);
4152   __ MultiPush(spill_mask);
4153
4154   __ LoadP(r3, FieldMemOperand(receiver, JSObject::kPropertiesOffset));
4155   __ mov(r4, Operand(Handle<Name>(name)));
4156   NameDictionaryLookupStub stub(masm->isolate(), NEGATIVE_LOOKUP);
4157   __ CallStub(&stub);
4158   __ cmpi(r3, Operand::Zero());
4159
4160   __ MultiPop(spill_mask);  // MultiPop does not touch condition flags
4161   __ mtlr(r0);
4162
4163   __ beq(done);
4164   __ bne(miss);
4165 }
4166
4167
4168 // Probe the name dictionary in the |elements| register. Jump to the
4169 // |done| label if a property with the given name is found. Jump to
4170 // the |miss| label otherwise.
4171 // If lookup was successful |scratch2| will be equal to elements + 4 * index.
4172 void NameDictionaryLookupStub::GeneratePositiveLookup(
4173     MacroAssembler* masm, Label* miss, Label* done, Register elements,
4174     Register name, Register scratch1, Register scratch2) {
4175   DCHECK(!elements.is(scratch1));
4176   DCHECK(!elements.is(scratch2));
4177   DCHECK(!name.is(scratch1));
4178   DCHECK(!name.is(scratch2));
4179
4180   __ AssertName(name);
4181
4182   // Compute the capacity mask.
4183   __ LoadP(scratch1, FieldMemOperand(elements, kCapacityOffset));
4184   __ SmiUntag(scratch1);  // convert smi to int
4185   __ subi(scratch1, scratch1, Operand(1));
4186
4187   // Generate an unrolled loop that performs a few probes before
4188   // giving up. Measurements done on Gmail indicate that 2 probes
4189   // cover ~93% of loads from dictionaries.
4190   for (int i = 0; i < kInlinedProbes; i++) {
4191     // Compute the masked index: (hash + i + i * i) & mask.
4192     __ lwz(scratch2, FieldMemOperand(name, Name::kHashFieldOffset));
4193     if (i > 0) {
4194       // Add the probe offset (i + i * i) left shifted to avoid right shifting
4195       // the hash in a separate instruction. The value hash + i + i * i is right
4196       // shifted in the following and instruction.
4197       DCHECK(NameDictionary::GetProbeOffset(i) <
4198              1 << (32 - Name::kHashFieldOffset));
4199       __ addi(scratch2, scratch2,
4200               Operand(NameDictionary::GetProbeOffset(i) << Name::kHashShift));
4201     }
4202     __ srwi(scratch2, scratch2, Operand(Name::kHashShift));
4203     __ and_(scratch2, scratch1, scratch2);
4204
4205     // Scale the index by multiplying by the element size.
4206     DCHECK(NameDictionary::kEntrySize == 3);
4207     // scratch2 = scratch2 * 3.
4208     __ ShiftLeftImm(ip, scratch2, Operand(1));
4209     __ add(scratch2, scratch2, ip);
4210
4211     // Check if the key is identical to the name.
4212     __ ShiftLeftImm(ip, scratch2, Operand(kPointerSizeLog2));
4213     __ add(scratch2, elements, ip);
4214     __ LoadP(ip, FieldMemOperand(scratch2, kElementsStartOffset));
4215     __ cmp(name, ip);
4216     __ beq(done);
4217   }
4218
4219   const int spill_mask = (r0.bit() | r9.bit() | r8.bit() | r7.bit() | r6.bit() |
4220                           r5.bit() | r4.bit() | r3.bit()) &
4221                          ~(scratch1.bit() | scratch2.bit());
4222
4223   __ mflr(r0);
4224   __ MultiPush(spill_mask);
4225   if (name.is(r3)) {
4226     DCHECK(!elements.is(r4));
4227     __ mr(r4, name);
4228     __ mr(r3, elements);
4229   } else {
4230     __ mr(r3, elements);
4231     __ mr(r4, name);
4232   }
4233   NameDictionaryLookupStub stub(masm->isolate(), POSITIVE_LOOKUP);
4234   __ CallStub(&stub);
4235   __ cmpi(r3, Operand::Zero());
4236   __ mr(scratch2, r5);
4237   __ MultiPop(spill_mask);
4238   __ mtlr(r0);
4239
4240   __ bne(done);
4241   __ beq(miss);
4242 }
4243
4244
4245 void NameDictionaryLookupStub::Generate(MacroAssembler* masm) {
4246   // This stub overrides SometimesSetsUpAFrame() to return false.  That means
4247   // we cannot call anything that could cause a GC from this stub.
4248   // Registers:
4249   //  result: NameDictionary to probe
4250   //  r4: key
4251   //  dictionary: NameDictionary to probe.
4252   //  index: will hold an index of entry if lookup is successful.
4253   //         might alias with result_.
4254   // Returns:
4255   //  result_ is zero if lookup failed, non zero otherwise.
4256
4257   Register result = r3;
4258   Register dictionary = r3;
4259   Register key = r4;
4260   Register index = r5;
4261   Register mask = r6;
4262   Register hash = r7;
4263   Register undefined = r8;
4264   Register entry_key = r9;
4265   Register scratch = r9;
4266
4267   Label in_dictionary, maybe_in_dictionary, not_in_dictionary;
4268
4269   __ LoadP(mask, FieldMemOperand(dictionary, kCapacityOffset));
4270   __ SmiUntag(mask);
4271   __ subi(mask, mask, Operand(1));
4272
4273   __ lwz(hash, FieldMemOperand(key, Name::kHashFieldOffset));
4274
4275   __ LoadRoot(undefined, Heap::kUndefinedValueRootIndex);
4276
4277   for (int i = kInlinedProbes; i < kTotalProbes; i++) {
4278     // Compute the masked index: (hash + i + i * i) & mask.
4279     // Capacity is smi 2^n.
4280     if (i > 0) {
4281       // Add the probe offset (i + i * i) left shifted to avoid right shifting
4282       // the hash in a separate instruction. The value hash + i + i * i is right
4283       // shifted in the following and instruction.
4284       DCHECK(NameDictionary::GetProbeOffset(i) <
4285              1 << (32 - Name::kHashFieldOffset));
4286       __ addi(index, hash,
4287               Operand(NameDictionary::GetProbeOffset(i) << Name::kHashShift));
4288     } else {
4289       __ mr(index, hash);
4290     }
4291     __ srwi(r0, index, Operand(Name::kHashShift));
4292     __ and_(index, mask, r0);
4293
4294     // Scale the index by multiplying by the entry size.
4295     DCHECK(NameDictionary::kEntrySize == 3);
4296     __ ShiftLeftImm(scratch, index, Operand(1));
4297     __ add(index, index, scratch);  // index *= 3.
4298
4299     __ ShiftLeftImm(scratch, index, Operand(kPointerSizeLog2));
4300     __ add(index, dictionary, scratch);
4301     __ LoadP(entry_key, FieldMemOperand(index, kElementsStartOffset));
4302
4303     // Having undefined at this place means the name is not contained.
4304     __ cmp(entry_key, undefined);
4305     __ beq(&not_in_dictionary);
4306
4307     // Stop if found the property.
4308     __ cmp(entry_key, key);
4309     __ beq(&in_dictionary);
4310
4311     if (i != kTotalProbes - 1 && mode() == NEGATIVE_LOOKUP) {
4312       // Check if the entry name is not a unique name.
4313       __ LoadP(entry_key, FieldMemOperand(entry_key, HeapObject::kMapOffset));
4314       __ lbz(entry_key, FieldMemOperand(entry_key, Map::kInstanceTypeOffset));
4315       __ JumpIfNotUniqueNameInstanceType(entry_key, &maybe_in_dictionary);
4316     }
4317   }
4318
4319   __ bind(&maybe_in_dictionary);
4320   // If we are doing negative lookup then probing failure should be
4321   // treated as a lookup success. For positive lookup probing failure
4322   // should be treated as lookup failure.
4323   if (mode() == POSITIVE_LOOKUP) {
4324     __ li(result, Operand::Zero());
4325     __ Ret();
4326   }
4327
4328   __ bind(&in_dictionary);
4329   __ li(result, Operand(1));
4330   __ Ret();
4331
4332   __ bind(&not_in_dictionary);
4333   __ li(result, Operand::Zero());
4334   __ Ret();
4335 }
4336
4337
4338 void StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(
4339     Isolate* isolate) {
4340   StoreBufferOverflowStub stub1(isolate, kDontSaveFPRegs);
4341   stub1.GetCode();
4342   // Hydrogen code stubs need stub2 at snapshot time.
4343   StoreBufferOverflowStub stub2(isolate, kSaveFPRegs);
4344   stub2.GetCode();
4345 }
4346
4347
4348 // Takes the input in 3 registers: address_ value_ and object_.  A pointer to
4349 // the value has just been written into the object, now this stub makes sure
4350 // we keep the GC informed.  The word in the object where the value has been
4351 // written is in the address register.
4352 void RecordWriteStub::Generate(MacroAssembler* masm) {
4353   Label skip_to_incremental_noncompacting;
4354   Label skip_to_incremental_compacting;
4355
4356   // The first two branch instructions are generated with labels so as to
4357   // get the offset fixed up correctly by the bind(Label*) call.  We patch
4358   // it back and forth between branch condition True and False
4359   // when we start and stop incremental heap marking.
4360   // See RecordWriteStub::Patch for details.
4361
4362   // Clear the bit, branch on True for NOP action initially
4363   __ crclr(Assembler::encode_crbit(cr2, CR_LT));
4364   __ blt(&skip_to_incremental_noncompacting, cr2);
4365   __ blt(&skip_to_incremental_compacting, cr2);
4366
4367   if (remembered_set_action() == EMIT_REMEMBERED_SET) {
4368     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4369                            MacroAssembler::kReturnAtEnd);
4370   }
4371   __ Ret();
4372
4373   __ bind(&skip_to_incremental_noncompacting);
4374   GenerateIncremental(masm, INCREMENTAL);
4375
4376   __ bind(&skip_to_incremental_compacting);
4377   GenerateIncremental(masm, INCREMENTAL_COMPACTION);
4378
4379   // Initial mode of the stub is expected to be STORE_BUFFER_ONLY.
4380   // Will be checked in IncrementalMarking::ActivateGeneratedStub.
4381   // patching not required on PPC as the initial path is effectively NOP
4382 }
4383
4384
4385 void RecordWriteStub::GenerateIncremental(MacroAssembler* masm, Mode mode) {
4386   regs_.Save(masm);
4387
4388   if (remembered_set_action() == EMIT_REMEMBERED_SET) {
4389     Label dont_need_remembered_set;
4390
4391     __ LoadP(regs_.scratch0(), MemOperand(regs_.address(), 0));
4392     __ JumpIfNotInNewSpace(regs_.scratch0(),  // Value.
4393                            regs_.scratch0(), &dont_need_remembered_set);
4394
4395     __ CheckPageFlag(regs_.object(), regs_.scratch0(),
4396                      1 << MemoryChunk::SCAN_ON_SCAVENGE, ne,
4397                      &dont_need_remembered_set);
4398
4399     // First notify the incremental marker if necessary, then update the
4400     // remembered set.
4401     CheckNeedsToInformIncrementalMarker(
4402         masm, kUpdateRememberedSetOnNoNeedToInformIncrementalMarker, mode);
4403     InformIncrementalMarker(masm);
4404     regs_.Restore(masm);
4405     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4406                            MacroAssembler::kReturnAtEnd);
4407
4408     __ bind(&dont_need_remembered_set);
4409   }
4410
4411   CheckNeedsToInformIncrementalMarker(
4412       masm, kReturnOnNoNeedToInformIncrementalMarker, mode);
4413   InformIncrementalMarker(masm);
4414   regs_.Restore(masm);
4415   __ Ret();
4416 }
4417
4418
4419 void RecordWriteStub::InformIncrementalMarker(MacroAssembler* masm) {
4420   regs_.SaveCallerSaveRegisters(masm, save_fp_regs_mode());
4421   int argument_count = 3;
4422   __ PrepareCallCFunction(argument_count, regs_.scratch0());
4423   Register address =
4424       r3.is(regs_.address()) ? regs_.scratch0() : regs_.address();
4425   DCHECK(!address.is(regs_.object()));
4426   DCHECK(!address.is(r3));
4427   __ mr(address, regs_.address());
4428   __ mr(r3, regs_.object());
4429   __ mr(r4, address);
4430   __ mov(r5, Operand(ExternalReference::isolate_address(isolate())));
4431
4432   AllowExternalCallThatCantCauseGC scope(masm);
4433   __ CallCFunction(
4434       ExternalReference::incremental_marking_record_write_function(isolate()),
4435       argument_count);
4436   regs_.RestoreCallerSaveRegisters(masm, save_fp_regs_mode());
4437 }
4438
4439
4440 void RecordWriteStub::CheckNeedsToInformIncrementalMarker(
4441     MacroAssembler* masm, OnNoNeedToInformIncrementalMarker on_no_need,
4442     Mode mode) {
4443   Label on_black;
4444   Label need_incremental;
4445   Label need_incremental_pop_scratch;
4446
4447   DCHECK((~Page::kPageAlignmentMask & 0xffff) == 0);
4448   __ lis(r0, Operand((~Page::kPageAlignmentMask >> 16)));
4449   __ and_(regs_.scratch0(), regs_.object(), r0);
4450   __ LoadP(
4451       regs_.scratch1(),
4452       MemOperand(regs_.scratch0(), MemoryChunk::kWriteBarrierCounterOffset));
4453   __ subi(regs_.scratch1(), regs_.scratch1(), Operand(1));
4454   __ StoreP(
4455       regs_.scratch1(),
4456       MemOperand(regs_.scratch0(), MemoryChunk::kWriteBarrierCounterOffset));
4457   __ cmpi(regs_.scratch1(), Operand::Zero());  // PPC, we could do better here
4458   __ blt(&need_incremental);
4459
4460   // Let's look at the color of the object:  If it is not black we don't have
4461   // to inform the incremental marker.
4462   __ JumpIfBlack(regs_.object(), regs_.scratch0(), regs_.scratch1(), &on_black);
4463
4464   regs_.Restore(masm);
4465   if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
4466     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4467                            MacroAssembler::kReturnAtEnd);
4468   } else {
4469     __ Ret();
4470   }
4471
4472   __ bind(&on_black);
4473
4474   // Get the value from the slot.
4475   __ LoadP(regs_.scratch0(), MemOperand(regs_.address(), 0));
4476
4477   if (mode == INCREMENTAL_COMPACTION) {
4478     Label ensure_not_white;
4479
4480     __ CheckPageFlag(regs_.scratch0(),  // Contains value.
4481                      regs_.scratch1(),  // Scratch.
4482                      MemoryChunk::kEvacuationCandidateMask, eq,
4483                      &ensure_not_white);
4484
4485     __ CheckPageFlag(regs_.object(),
4486                      regs_.scratch1(),  // Scratch.
4487                      MemoryChunk::kSkipEvacuationSlotsRecordingMask, eq,
4488                      &need_incremental);
4489
4490     __ bind(&ensure_not_white);
4491   }
4492
4493   // We need extra registers for this, so we push the object and the address
4494   // register temporarily.
4495   __ Push(regs_.object(), regs_.address());
4496   __ EnsureNotWhite(regs_.scratch0(),  // The value.
4497                     regs_.scratch1(),  // Scratch.
4498                     regs_.object(),    // Scratch.
4499                     regs_.address(),   // Scratch.
4500                     &need_incremental_pop_scratch);
4501   __ Pop(regs_.object(), regs_.address());
4502
4503   regs_.Restore(masm);
4504   if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
4505     __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode(),
4506                            MacroAssembler::kReturnAtEnd);
4507   } else {
4508     __ Ret();
4509   }
4510
4511   __ bind(&need_incremental_pop_scratch);
4512   __ Pop(regs_.object(), regs_.address());
4513
4514   __ bind(&need_incremental);
4515
4516   // Fall through when we need to inform the incremental marker.
4517 }
4518
4519
4520 void StoreArrayLiteralElementStub::Generate(MacroAssembler* masm) {
4521   // ----------- S t a t e -------------
4522   //  -- r3    : element value to store
4523   //  -- r6    : element index as smi
4524   //  -- sp[0] : array literal index in function as smi
4525   //  -- sp[4] : array literal
4526   // clobbers r3, r5, r7
4527   // -----------------------------------
4528
4529   Label element_done;
4530   Label double_elements;
4531   Label smi_element;
4532   Label slow_elements;
4533   Label fast_elements;
4534
4535   // Get array literal index, array literal and its map.
4536   __ LoadP(r7, MemOperand(sp, 0 * kPointerSize));
4537   __ LoadP(r4, MemOperand(sp, 1 * kPointerSize));
4538   __ LoadP(r5, FieldMemOperand(r4, JSObject::kMapOffset));
4539
4540   __ CheckFastElements(r5, r8, &double_elements);
4541   // FAST_*_SMI_ELEMENTS or FAST_*_ELEMENTS
4542   __ JumpIfSmi(r3, &smi_element);
4543   __ CheckFastSmiElements(r5, r8, &fast_elements);
4544
4545   // Store into the array literal requires a elements transition. Call into
4546   // the runtime.
4547   __ bind(&slow_elements);
4548   // call.
4549   __ Push(r4, r6, r3);
4550   __ LoadP(r8, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
4551   __ LoadP(r8, FieldMemOperand(r8, JSFunction::kLiteralsOffset));
4552   __ Push(r8, r7);
4553   __ TailCallRuntime(Runtime::kStoreArrayLiteralElement, 5, 1);
4554
4555   // Array literal has ElementsKind of FAST_*_ELEMENTS and value is an object.
4556   __ bind(&fast_elements);
4557   __ LoadP(r8, FieldMemOperand(r4, JSObject::kElementsOffset));
4558   __ SmiToPtrArrayOffset(r9, r6);
4559   __ add(r9, r8, r9);
4560 #if V8_TARGET_ARCH_PPC64
4561   // add due to offset alignment requirements of StorePU
4562   __ addi(r9, r9, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
4563   __ StoreP(r3, MemOperand(r9));
4564 #else
4565   __ StorePU(r3, MemOperand(r9, FixedArray::kHeaderSize - kHeapObjectTag));
4566 #endif
4567   // Update the write barrier for the array store.
4568   __ RecordWrite(r8, r9, r3, kLRHasNotBeenSaved, kDontSaveFPRegs,
4569                  EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
4570   __ Ret();
4571
4572   // Array literal has ElementsKind of FAST_*_SMI_ELEMENTS or FAST_*_ELEMENTS,
4573   // and value is Smi.
4574   __ bind(&smi_element);
4575   __ LoadP(r8, FieldMemOperand(r4, JSObject::kElementsOffset));
4576   __ SmiToPtrArrayOffset(r9, r6);
4577   __ add(r9, r8, r9);
4578   __ StoreP(r3, FieldMemOperand(r9, FixedArray::kHeaderSize), r0);
4579   __ Ret();
4580
4581   // Array literal has ElementsKind of FAST_DOUBLE_ELEMENTS.
4582   __ bind(&double_elements);
4583   __ LoadP(r8, FieldMemOperand(r4, JSObject::kElementsOffset));
4584   __ StoreNumberToDoubleElements(r3, r6, r8, r9, d0, &slow_elements);
4585   __ Ret();
4586 }
4587
4588
4589 void StubFailureTrampolineStub::Generate(MacroAssembler* masm) {
4590   CEntryStub ces(isolate(), 1, kSaveFPRegs);
4591   __ Call(ces.GetCode(), RelocInfo::CODE_TARGET);
4592   int parameter_count_offset =
4593       StubFailureTrampolineFrame::kCallerStackParameterCountFrameOffset;
4594   __ LoadP(r4, MemOperand(fp, parameter_count_offset));
4595   if (function_mode() == JS_FUNCTION_STUB_MODE) {
4596     __ addi(r4, r4, Operand(1));
4597   }
4598   masm->LeaveFrame(StackFrame::STUB_FAILURE_TRAMPOLINE);
4599   __ slwi(r4, r4, Operand(kPointerSizeLog2));
4600   __ add(sp, sp, r4);
4601   __ Ret();
4602 }
4603
4604
4605 void LoadICTrampolineStub::Generate(MacroAssembler* masm) {
4606   EmitLoadTypeFeedbackVector(masm, LoadWithVectorDescriptor::VectorRegister());
4607   LoadICStub stub(isolate(), state());
4608   stub.GenerateForTrampoline(masm);
4609 }
4610
4611
4612 void KeyedLoadICTrampolineStub::Generate(MacroAssembler* masm) {
4613   EmitLoadTypeFeedbackVector(masm, LoadWithVectorDescriptor::VectorRegister());
4614   KeyedLoadICStub stub(isolate());
4615   stub.GenerateForTrampoline(masm);
4616 }
4617
4618
4619 void CallICTrampolineStub::Generate(MacroAssembler* masm) {
4620   EmitLoadTypeFeedbackVector(masm, r5);
4621   CallICStub stub(isolate(), state());
4622   __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
4623 }
4624
4625
4626 void CallIC_ArrayTrampolineStub::Generate(MacroAssembler* masm) {
4627   EmitLoadTypeFeedbackVector(masm, r5);
4628   CallIC_ArrayStub stub(isolate(), state());
4629   __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
4630 }
4631
4632
4633 void LoadICStub::Generate(MacroAssembler* masm) { GenerateImpl(masm, false); }
4634
4635
4636 void LoadICStub::GenerateForTrampoline(MacroAssembler* masm) {
4637   GenerateImpl(masm, true);
4638 }
4639
4640
4641 static void HandleArrayCases(MacroAssembler* masm, Register receiver,
4642                              Register key, Register vector, Register slot,
4643                              Register feedback, Register receiver_map,
4644                              Register scratch1, Register scratch2,
4645                              bool is_polymorphic, Label* miss) {
4646   // feedback initially contains the feedback array
4647   Label next_loop, prepare_next;
4648   Label start_polymorphic;
4649
4650   Register cached_map = scratch1;
4651
4652   __ LoadP(cached_map,
4653            FieldMemOperand(feedback, FixedArray::OffsetOfElementAt(0)));
4654   __ LoadP(cached_map, FieldMemOperand(cached_map, WeakCell::kValueOffset));
4655   __ cmp(receiver_map, cached_map);
4656   __ bne(&start_polymorphic);
4657   // found, now call handler.
4658   Register handler = feedback;
4659   __ LoadP(handler,
4660            FieldMemOperand(feedback, FixedArray::OffsetOfElementAt(1)));
4661   __ addi(ip, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
4662   __ Jump(ip);
4663
4664
4665   Register length = scratch2;
4666   __ bind(&start_polymorphic);
4667   __ LoadP(length, FieldMemOperand(feedback, FixedArray::kLengthOffset));
4668   if (!is_polymorphic) {
4669     // If the IC could be monomorphic we have to make sure we don't go past the
4670     // end of the feedback array.
4671     __ CmpSmiLiteral(length, Smi::FromInt(2), r0);
4672     __ beq(miss);
4673   }
4674
4675   Register too_far = length;
4676   Register pointer_reg = feedback;
4677
4678   // +-----+------+------+-----+-----+ ... ----+
4679   // | map | len  | wm0  | h0  | wm1 |      hN |
4680   // +-----+------+------+-----+-----+ ... ----+
4681   //                 0      1     2        len-1
4682   //                              ^              ^
4683   //                              |              |
4684   //                         pointer_reg      too_far
4685   //                         aka feedback     scratch2
4686   // also need receiver_map
4687   // use cached_map (scratch1) to look in the weak map values.
4688   __ SmiToPtrArrayOffset(r0, length);
4689   __ add(too_far, feedback, r0);
4690   __ addi(too_far, too_far, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
4691   __ addi(pointer_reg, feedback,
4692           Operand(FixedArray::OffsetOfElementAt(2) - kHeapObjectTag));
4693
4694   __ bind(&next_loop);
4695   __ LoadP(cached_map, MemOperand(pointer_reg));
4696   __ LoadP(cached_map, FieldMemOperand(cached_map, WeakCell::kValueOffset));
4697   __ cmp(receiver_map, cached_map);
4698   __ bne(&prepare_next);
4699   __ LoadP(handler, MemOperand(pointer_reg, kPointerSize));
4700   __ addi(ip, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
4701   __ Jump(ip);
4702
4703   __ bind(&prepare_next);
4704   __ addi(pointer_reg, pointer_reg, Operand(kPointerSize * 2));
4705   __ cmp(pointer_reg, too_far);
4706   __ blt(&next_loop);
4707
4708   // We exhausted our array of map handler pairs.
4709   __ b(miss);
4710 }
4711
4712
4713 static void HandleMonomorphicCase(MacroAssembler* masm, Register receiver,
4714                                   Register receiver_map, Register feedback,
4715                                   Register vector, Register slot,
4716                                   Register scratch, Label* compare_map,
4717                                   Label* load_smi_map, Label* try_array) {
4718   __ JumpIfSmi(receiver, load_smi_map);
4719   __ LoadP(receiver_map, FieldMemOperand(receiver, HeapObject::kMapOffset));
4720   __ bind(compare_map);
4721   Register cached_map = scratch;
4722   // Move the weak map into the weak_cell register.
4723   __ LoadP(cached_map, FieldMemOperand(feedback, WeakCell::kValueOffset));
4724   __ cmp(cached_map, receiver_map);
4725   __ bne(try_array);
4726   Register handler = feedback;
4727   __ SmiToPtrArrayOffset(r0, slot);
4728   __ add(handler, vector, r0);
4729   __ LoadP(handler,
4730            FieldMemOperand(handler, FixedArray::kHeaderSize + kPointerSize));
4731   __ addi(ip, handler, Operand(Code::kHeaderSize - kHeapObjectTag));
4732   __ Jump(ip);
4733 }
4734
4735
4736 void LoadICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4737   Register receiver = LoadWithVectorDescriptor::ReceiverRegister();  // r4
4738   Register name = LoadWithVectorDescriptor::NameRegister();          // r5
4739   Register vector = LoadWithVectorDescriptor::VectorRegister();      // r6
4740   Register slot = LoadWithVectorDescriptor::SlotRegister();          // r3
4741   Register feedback = r7;
4742   Register receiver_map = r8;
4743   Register scratch1 = r9;
4744
4745   __ SmiToPtrArrayOffset(r0, slot);
4746   __ add(feedback, vector, r0);
4747   __ LoadP(feedback, FieldMemOperand(feedback, FixedArray::kHeaderSize));
4748
4749   // Try to quickly handle the monomorphic case without knowing for sure
4750   // if we have a weak cell in feedback. We do know it's safe to look
4751   // at WeakCell::kValueOffset.
4752   Label try_array, load_smi_map, compare_map;
4753   Label not_array, miss;
4754   HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
4755                         scratch1, &compare_map, &load_smi_map, &try_array);
4756
4757   // Is it a fixed array?
4758   __ bind(&try_array);
4759   __ LoadP(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
4760   __ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
4761   __ bne(&not_array);
4762   HandleArrayCases(masm, receiver, name, vector, slot, feedback, receiver_map,
4763                    scratch1, r10, true, &miss);
4764
4765   __ bind(&not_array);
4766   __ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
4767   __ bne(&miss);
4768   Code::Flags code_flags = Code::RemoveTypeAndHolderFromFlags(
4769       Code::ComputeHandlerFlags(Code::LOAD_IC));
4770   masm->isolate()->stub_cache()->GenerateProbe(masm, Code::LOAD_IC, code_flags,
4771                                                false, receiver, name, feedback,
4772                                                receiver_map, scratch1, r10);
4773
4774   __ bind(&miss);
4775   LoadIC::GenerateMiss(masm);
4776
4777   __ bind(&load_smi_map);
4778   __ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
4779   __ b(&compare_map);
4780 }
4781
4782
4783 void KeyedLoadICStub::Generate(MacroAssembler* masm) {
4784   GenerateImpl(masm, false);
4785 }
4786
4787
4788 void KeyedLoadICStub::GenerateForTrampoline(MacroAssembler* masm) {
4789   GenerateImpl(masm, true);
4790 }
4791
4792
4793 void KeyedLoadICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4794   Register receiver = LoadWithVectorDescriptor::ReceiverRegister();  // r4
4795   Register key = LoadWithVectorDescriptor::NameRegister();           // r5
4796   Register vector = LoadWithVectorDescriptor::VectorRegister();      // r6
4797   Register slot = LoadWithVectorDescriptor::SlotRegister();          // r3
4798   Register feedback = r7;
4799   Register receiver_map = r8;
4800   Register scratch1 = r9;
4801
4802   __ SmiToPtrArrayOffset(r0, slot);
4803   __ add(feedback, vector, r0);
4804   __ LoadP(feedback, FieldMemOperand(feedback, FixedArray::kHeaderSize));
4805
4806   // Try to quickly handle the monomorphic case without knowing for sure
4807   // if we have a weak cell in feedback. We do know it's safe to look
4808   // at WeakCell::kValueOffset.
4809   Label try_array, load_smi_map, compare_map;
4810   Label not_array, miss;
4811   HandleMonomorphicCase(masm, receiver, receiver_map, feedback, vector, slot,
4812                         scratch1, &compare_map, &load_smi_map, &try_array);
4813
4814   __ bind(&try_array);
4815   // Is it a fixed array?
4816   __ LoadP(scratch1, FieldMemOperand(feedback, HeapObject::kMapOffset));
4817   __ CompareRoot(scratch1, Heap::kFixedArrayMapRootIndex);
4818   __ bne(&not_array);
4819
4820   // We have a polymorphic element handler.
4821   Label polymorphic, try_poly_name;
4822   __ bind(&polymorphic);
4823   HandleArrayCases(masm, receiver, key, vector, slot, feedback, receiver_map,
4824                    scratch1, r10, true, &miss);
4825
4826   __ bind(&not_array);
4827   // Is it generic?
4828   __ CompareRoot(feedback, Heap::kmegamorphic_symbolRootIndex);
4829   __ bne(&try_poly_name);
4830   Handle<Code> megamorphic_stub =
4831       KeyedLoadIC::ChooseMegamorphicStub(masm->isolate());
4832   __ Jump(megamorphic_stub, RelocInfo::CODE_TARGET);
4833
4834   __ bind(&try_poly_name);
4835   // We might have a name in feedback, and a fixed array in the next slot.
4836   __ cmp(key, feedback);
4837   __ bne(&miss);
4838   // If the name comparison succeeded, we know we have a fixed array with
4839   // at least one map/handler pair.
4840   __ SmiToPtrArrayOffset(r0, slot);
4841   __ add(feedback, vector, r0);
4842   __ LoadP(feedback,
4843            FieldMemOperand(feedback, FixedArray::kHeaderSize + kPointerSize));
4844   HandleArrayCases(masm, receiver, key, vector, slot, feedback, receiver_map,
4845                    scratch1, r10, false, &miss);
4846
4847   __ bind(&miss);
4848   KeyedLoadIC::GenerateMiss(masm);
4849
4850   __ bind(&load_smi_map);
4851   __ LoadRoot(receiver_map, Heap::kHeapNumberMapRootIndex);
4852   __ b(&compare_map);
4853 }
4854
4855
4856 void VectorStoreICTrampolineStub::Generate(MacroAssembler* masm) {
4857   EmitLoadTypeFeedbackVector(masm, VectorStoreICDescriptor::VectorRegister());
4858   VectorStoreICStub stub(isolate(), state());
4859   stub.GenerateForTrampoline(masm);
4860 }
4861
4862
4863 void VectorKeyedStoreICTrampolineStub::Generate(MacroAssembler* masm) {
4864   EmitLoadTypeFeedbackVector(masm, VectorStoreICDescriptor::VectorRegister());
4865   VectorKeyedStoreICStub stub(isolate(), state());
4866   stub.GenerateForTrampoline(masm);
4867 }
4868
4869
4870 void VectorStoreICStub::Generate(MacroAssembler* masm) {
4871   GenerateImpl(masm, false);
4872 }
4873
4874
4875 void VectorStoreICStub::GenerateForTrampoline(MacroAssembler* masm) {
4876   GenerateImpl(masm, true);
4877 }
4878
4879
4880 void VectorStoreICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4881   Label miss;
4882
4883   // TODO(mvstanton): Implement.
4884   __ bind(&miss);
4885   StoreIC::GenerateMiss(masm);
4886 }
4887
4888
4889 void VectorKeyedStoreICStub::Generate(MacroAssembler* masm) {
4890   GenerateImpl(masm, false);
4891 }
4892
4893
4894 void VectorKeyedStoreICStub::GenerateForTrampoline(MacroAssembler* masm) {
4895   GenerateImpl(masm, true);
4896 }
4897
4898
4899 void VectorKeyedStoreICStub::GenerateImpl(MacroAssembler* masm, bool in_frame) {
4900   Label miss;
4901
4902   // TODO(mvstanton): Implement.
4903   __ bind(&miss);
4904   KeyedStoreIC::GenerateMiss(masm);
4905 }
4906
4907
4908 void ProfileEntryHookStub::MaybeCallEntryHook(MacroAssembler* masm) {
4909   if (masm->isolate()->function_entry_hook() != NULL) {
4910     PredictableCodeSizeScope predictable(masm,
4911 #if V8_TARGET_ARCH_PPC64
4912                                          14 * Assembler::kInstrSize);
4913 #else
4914                                          11 * Assembler::kInstrSize);
4915 #endif
4916     ProfileEntryHookStub stub(masm->isolate());
4917     __ mflr(r0);
4918     __ Push(r0, ip);
4919     __ CallStub(&stub);
4920     __ Pop(r0, ip);
4921     __ mtlr(r0);
4922   }
4923 }
4924
4925
4926 void ProfileEntryHookStub::Generate(MacroAssembler* masm) {
4927   // The entry hook is a "push lr, ip" instruction, followed by a call.
4928   const int32_t kReturnAddressDistanceFromFunctionStart =
4929       Assembler::kCallTargetAddressOffset + 3 * Assembler::kInstrSize;
4930
4931   // This should contain all kJSCallerSaved registers.
4932   const RegList kSavedRegs = kJSCallerSaved |  // Caller saved registers.
4933                              r15.bit();        // Saved stack pointer.
4934
4935   // We also save lr, so the count here is one higher than the mask indicates.
4936   const int32_t kNumSavedRegs = kNumJSCallerSaved + 2;
4937
4938   // Save all caller-save registers as this may be called from anywhere.
4939   __ mflr(ip);
4940   __ MultiPush(kSavedRegs | ip.bit());
4941
4942   // Compute the function's address for the first argument.
4943   __ subi(r3, ip, Operand(kReturnAddressDistanceFromFunctionStart));
4944
4945   // The caller's return address is two slots above the saved temporaries.
4946   // Grab that for the second argument to the hook.
4947   __ addi(r4, sp, Operand((kNumSavedRegs + 1) * kPointerSize));
4948
4949   // Align the stack if necessary.
4950   int frame_alignment = masm->ActivationFrameAlignment();
4951   if (frame_alignment > kPointerSize) {
4952     __ mr(r15, sp);
4953     DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
4954     __ ClearRightImm(sp, sp, Operand(WhichPowerOf2(frame_alignment)));
4955   }
4956
4957 #if !defined(USE_SIMULATOR)
4958   uintptr_t entry_hook =
4959       reinterpret_cast<uintptr_t>(isolate()->function_entry_hook());
4960   __ mov(ip, Operand(entry_hook));
4961
4962 #if ABI_USES_FUNCTION_DESCRIPTORS
4963   // Function descriptor
4964   __ LoadP(ToRegister(ABI_TOC_REGISTER), MemOperand(ip, kPointerSize));
4965   __ LoadP(ip, MemOperand(ip, 0));
4966 #elif ABI_TOC_ADDRESSABILITY_VIA_IP
4967 // ip set above, so nothing to do.
4968 #endif
4969
4970   // PPC LINUX ABI:
4971   __ li(r0, Operand::Zero());
4972   __ StorePU(r0, MemOperand(sp, -kNumRequiredStackFrameSlots * kPointerSize));
4973 #else
4974   // Under the simulator we need to indirect the entry hook through a
4975   // trampoline function at a known address.
4976   // It additionally takes an isolate as a third parameter
4977   __ mov(r5, Operand(ExternalReference::isolate_address(isolate())));
4978
4979   ApiFunction dispatcher(FUNCTION_ADDR(EntryHookTrampoline));
4980   __ mov(ip, Operand(ExternalReference(
4981                  &dispatcher, ExternalReference::BUILTIN_CALL, isolate())));
4982 #endif
4983   __ Call(ip);
4984
4985 #if !defined(USE_SIMULATOR)
4986   __ addi(sp, sp, Operand(kNumRequiredStackFrameSlots * kPointerSize));
4987 #endif
4988
4989   // Restore the stack pointer if needed.
4990   if (frame_alignment > kPointerSize) {
4991     __ mr(sp, r15);
4992   }
4993
4994   // Also pop lr to get Ret(0).
4995   __ MultiPop(kSavedRegs | ip.bit());
4996   __ mtlr(ip);
4997   __ Ret();
4998 }
4999
5000
5001 template <class T>
5002 static void CreateArrayDispatch(MacroAssembler* masm,
5003                                 AllocationSiteOverrideMode mode) {
5004   if (mode == DISABLE_ALLOCATION_SITES) {
5005     T stub(masm->isolate(), GetInitialFastElementsKind(), mode);
5006     __ TailCallStub(&stub);
5007   } else if (mode == DONT_OVERRIDE) {
5008     int last_index =
5009         GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
5010     for (int i = 0; i <= last_index; ++i) {
5011       ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
5012       __ Cmpi(r6, Operand(kind), r0);
5013       T stub(masm->isolate(), kind);
5014       __ TailCallStub(&stub, eq);
5015     }
5016
5017     // If we reached this point there is a problem.
5018     __ Abort(kUnexpectedElementsKindInArrayConstructor);
5019   } else {
5020     UNREACHABLE();
5021   }
5022 }
5023
5024
5025 static void CreateArrayDispatchOneArgument(MacroAssembler* masm,
5026                                            AllocationSiteOverrideMode mode) {
5027   // r5 - allocation site (if mode != DISABLE_ALLOCATION_SITES)
5028   // r6 - kind (if mode != DISABLE_ALLOCATION_SITES)
5029   // r3 - number of arguments
5030   // r4 - constructor?
5031   // sp[0] - last argument
5032   Label normal_sequence;
5033   if (mode == DONT_OVERRIDE) {
5034     DCHECK(FAST_SMI_ELEMENTS == 0);
5035     DCHECK(FAST_HOLEY_SMI_ELEMENTS == 1);
5036     DCHECK(FAST_ELEMENTS == 2);
5037     DCHECK(FAST_HOLEY_ELEMENTS == 3);
5038     DCHECK(FAST_DOUBLE_ELEMENTS == 4);
5039     DCHECK(FAST_HOLEY_DOUBLE_ELEMENTS == 5);
5040
5041     // is the low bit set? If so, we are holey and that is good.
5042     __ andi(r0, r6, Operand(1));
5043     __ bne(&normal_sequence, cr0);
5044   }
5045
5046   // look at the first argument
5047   __ LoadP(r8, MemOperand(sp, 0));
5048   __ cmpi(r8, Operand::Zero());
5049   __ beq(&normal_sequence);
5050
5051   if (mode == DISABLE_ALLOCATION_SITES) {
5052     ElementsKind initial = GetInitialFastElementsKind();
5053     ElementsKind holey_initial = GetHoleyElementsKind(initial);
5054
5055     ArraySingleArgumentConstructorStub stub_holey(
5056         masm->isolate(), holey_initial, DISABLE_ALLOCATION_SITES);
5057     __ TailCallStub(&stub_holey);
5058
5059     __ bind(&normal_sequence);
5060     ArraySingleArgumentConstructorStub stub(masm->isolate(), initial,
5061                                             DISABLE_ALLOCATION_SITES);
5062     __ TailCallStub(&stub);
5063   } else if (mode == DONT_OVERRIDE) {
5064     // We are going to create a holey array, but our kind is non-holey.
5065     // Fix kind and retry (only if we have an allocation site in the slot).
5066     __ addi(r6, r6, Operand(1));
5067
5068     if (FLAG_debug_code) {
5069       __ LoadP(r8, FieldMemOperand(r5, 0));
5070       __ CompareRoot(r8, Heap::kAllocationSiteMapRootIndex);
5071       __ Assert(eq, kExpectedAllocationSite);
5072     }
5073
5074     // Save the resulting elements kind in type info. We can't just store r6
5075     // in the AllocationSite::transition_info field because elements kind is
5076     // restricted to a portion of the field...upper bits need to be left alone.
5077     STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
5078     __ LoadP(r7, FieldMemOperand(r5, AllocationSite::kTransitionInfoOffset));
5079     __ AddSmiLiteral(r7, r7, Smi::FromInt(kFastElementsKindPackedToHoley), r0);
5080     __ StoreP(r7, FieldMemOperand(r5, AllocationSite::kTransitionInfoOffset),
5081               r0);
5082
5083     __ bind(&normal_sequence);
5084     int last_index =
5085         GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
5086     for (int i = 0; i <= last_index; ++i) {
5087       ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
5088       __ mov(r0, Operand(kind));
5089       __ cmp(r6, r0);
5090       ArraySingleArgumentConstructorStub stub(masm->isolate(), kind);
5091       __ TailCallStub(&stub, eq);
5092     }
5093
5094     // If we reached this point there is a problem.
5095     __ Abort(kUnexpectedElementsKindInArrayConstructor);
5096   } else {
5097     UNREACHABLE();
5098   }
5099 }
5100
5101
5102 template <class T>
5103 static void ArrayConstructorStubAheadOfTimeHelper(Isolate* isolate) {
5104   int to_index =
5105       GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
5106   for (int i = 0; i <= to_index; ++i) {
5107     ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
5108     T stub(isolate, kind);
5109     stub.GetCode();
5110     if (AllocationSite::GetMode(kind) != DONT_TRACK_ALLOCATION_SITE) {
5111       T stub1(isolate, kind, DISABLE_ALLOCATION_SITES);
5112       stub1.GetCode();
5113     }
5114   }
5115 }
5116
5117
5118 void ArrayConstructorStubBase::GenerateStubsAheadOfTime(Isolate* isolate) {
5119   ArrayConstructorStubAheadOfTimeHelper<ArrayNoArgumentConstructorStub>(
5120       isolate);
5121   ArrayConstructorStubAheadOfTimeHelper<ArraySingleArgumentConstructorStub>(
5122       isolate);
5123   ArrayConstructorStubAheadOfTimeHelper<ArrayNArgumentsConstructorStub>(
5124       isolate);
5125 }
5126
5127
5128 void InternalArrayConstructorStubBase::GenerateStubsAheadOfTime(
5129     Isolate* isolate) {
5130   ElementsKind kinds[2] = {FAST_ELEMENTS, FAST_HOLEY_ELEMENTS};
5131   for (int i = 0; i < 2; i++) {
5132     // For internal arrays we only need a few things
5133     InternalArrayNoArgumentConstructorStub stubh1(isolate, kinds[i]);
5134     stubh1.GetCode();
5135     InternalArraySingleArgumentConstructorStub stubh2(isolate, kinds[i]);
5136     stubh2.GetCode();
5137     InternalArrayNArgumentsConstructorStub stubh3(isolate, kinds[i]);
5138     stubh3.GetCode();
5139   }
5140 }
5141
5142
5143 void ArrayConstructorStub::GenerateDispatchToArrayStub(
5144     MacroAssembler* masm, AllocationSiteOverrideMode mode) {
5145   if (argument_count() == ANY) {
5146     Label not_zero_case, not_one_case;
5147     __ cmpi(r3, Operand::Zero());
5148     __ bne(&not_zero_case);
5149     CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
5150
5151     __ bind(&not_zero_case);
5152     __ cmpi(r3, Operand(1));
5153     __ bgt(&not_one_case);
5154     CreateArrayDispatchOneArgument(masm, mode);
5155
5156     __ bind(&not_one_case);
5157     CreateArrayDispatch<ArrayNArgumentsConstructorStub>(masm, mode);
5158   } else if (argument_count() == NONE) {
5159     CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
5160   } else if (argument_count() == ONE) {
5161     CreateArrayDispatchOneArgument(masm, mode);
5162   } else if (argument_count() == MORE_THAN_ONE) {
5163     CreateArrayDispatch<ArrayNArgumentsConstructorStub>(masm, mode);
5164   } else {
5165     UNREACHABLE();
5166   }
5167 }
5168
5169
5170 void ArrayConstructorStub::Generate(MacroAssembler* masm) {
5171   // ----------- S t a t e -------------
5172   //  -- r3 : argc (only if argument_count() == ANY)
5173   //  -- r4 : constructor
5174   //  -- r5 : AllocationSite or undefined
5175   //  -- r6 : original constructor
5176   //  -- sp[0] : return address
5177   //  -- sp[4] : last argument
5178   // -----------------------------------
5179
5180   if (FLAG_debug_code) {
5181     // The array construct code is only set for the global and natives
5182     // builtin Array functions which always have maps.
5183
5184     // Initial map for the builtin Array function should be a map.
5185     __ LoadP(r7, FieldMemOperand(r4, JSFunction::kPrototypeOrInitialMapOffset));
5186     // Will both indicate a NULL and a Smi.
5187     __ TestIfSmi(r7, r0);
5188     __ Assert(ne, kUnexpectedInitialMapForArrayFunction, cr0);
5189     __ CompareObjectType(r7, r7, r8, MAP_TYPE);
5190     __ Assert(eq, kUnexpectedInitialMapForArrayFunction);
5191
5192     // We should either have undefined in r5 or a valid AllocationSite
5193     __ AssertUndefinedOrAllocationSite(r5, r7);
5194   }
5195
5196   Label subclassing;
5197   __ cmp(r6, r4);
5198   __ bne(&subclassing);
5199
5200   Label no_info;
5201   // Get the elements kind and case on that.
5202   __ CompareRoot(r5, Heap::kUndefinedValueRootIndex);
5203   __ beq(&no_info);
5204
5205   __ LoadP(r6, FieldMemOperand(r5, AllocationSite::kTransitionInfoOffset));
5206   __ SmiUntag(r6);
5207   STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
5208   __ And(r6, r6, Operand(AllocationSite::ElementsKindBits::kMask));
5209   GenerateDispatchToArrayStub(masm, DONT_OVERRIDE);
5210
5211   __ bind(&no_info);
5212   GenerateDispatchToArrayStub(masm, DISABLE_ALLOCATION_SITES);
5213
5214   __ bind(&subclassing);
5215   __ push(r4);
5216   __ push(r6);
5217
5218   // Adjust argc.
5219   switch (argument_count()) {
5220     case ANY:
5221     case MORE_THAN_ONE:
5222       __ addi(r3, r3, Operand(2));
5223       break;
5224     case NONE:
5225       __ li(r3, Operand(2));
5226       break;
5227     case ONE:
5228       __ li(r3, Operand(3));
5229       break;
5230   }
5231
5232   __ JumpToExternalReference(
5233       ExternalReference(Runtime::kArrayConstructorWithSubclassing, isolate()));
5234 }
5235
5236
5237 void InternalArrayConstructorStub::GenerateCase(MacroAssembler* masm,
5238                                                 ElementsKind kind) {
5239   __ cmpli(r3, Operand(1));
5240
5241   InternalArrayNoArgumentConstructorStub stub0(isolate(), kind);
5242   __ TailCallStub(&stub0, lt);
5243
5244   InternalArrayNArgumentsConstructorStub stubN(isolate(), kind);
5245   __ TailCallStub(&stubN, gt);
5246
5247   if (IsFastPackedElementsKind(kind)) {
5248     // We might need to create a holey array
5249     // look at the first argument
5250     __ LoadP(r6, MemOperand(sp, 0));
5251     __ cmpi(r6, Operand::Zero());
5252
5253     InternalArraySingleArgumentConstructorStub stub1_holey(
5254         isolate(), GetHoleyElementsKind(kind));
5255     __ TailCallStub(&stub1_holey, ne);
5256   }
5257
5258   InternalArraySingleArgumentConstructorStub stub1(isolate(), kind);
5259   __ TailCallStub(&stub1);
5260 }
5261
5262
5263 void InternalArrayConstructorStub::Generate(MacroAssembler* masm) {
5264   // ----------- S t a t e -------------
5265   //  -- r3 : argc
5266   //  -- r4 : constructor
5267   //  -- sp[0] : return address
5268   //  -- sp[4] : last argument
5269   // -----------------------------------
5270
5271   if (FLAG_debug_code) {
5272     // The array construct code is only set for the global and natives
5273     // builtin Array functions which always have maps.
5274
5275     // Initial map for the builtin Array function should be a map.
5276     __ LoadP(r6, FieldMemOperand(r4, JSFunction::kPrototypeOrInitialMapOffset));
5277     // Will both indicate a NULL and a Smi.
5278     __ TestIfSmi(r6, r0);
5279     __ Assert(ne, kUnexpectedInitialMapForArrayFunction, cr0);
5280     __ CompareObjectType(r6, r6, r7, MAP_TYPE);
5281     __ Assert(eq, kUnexpectedInitialMapForArrayFunction);
5282   }
5283
5284   // Figure out the right elements kind
5285   __ LoadP(r6, FieldMemOperand(r4, JSFunction::kPrototypeOrInitialMapOffset));
5286   // Load the map's "bit field 2" into |result|.
5287   __ lbz(r6, FieldMemOperand(r6, Map::kBitField2Offset));
5288   // Retrieve elements_kind from bit field 2.
5289   __ DecodeField<Map::ElementsKindBits>(r6);
5290
5291   if (FLAG_debug_code) {
5292     Label done;
5293     __ cmpi(r6, Operand(FAST_ELEMENTS));
5294     __ beq(&done);
5295     __ cmpi(r6, Operand(FAST_HOLEY_ELEMENTS));
5296     __ Assert(eq, kInvalidElementsKindForInternalArrayOrInternalPackedArray);
5297     __ bind(&done);
5298   }
5299
5300   Label fast_elements_case;
5301   __ cmpi(r6, Operand(FAST_ELEMENTS));
5302   __ beq(&fast_elements_case);
5303   GenerateCase(masm, FAST_HOLEY_ELEMENTS);
5304
5305   __ bind(&fast_elements_case);
5306   GenerateCase(masm, FAST_ELEMENTS);
5307 }
5308
5309
5310 static int AddressOffset(ExternalReference ref0, ExternalReference ref1) {
5311   return ref0.address() - ref1.address();
5312 }
5313
5314
5315 // Calls an API function.  Allocates HandleScope, extracts returned value
5316 // from handle and propagates exceptions.  Restores context.  stack_space
5317 // - space to be unwound on exit (includes the call JS arguments space and
5318 // the additional space allocated for the fast call).
5319 static void CallApiFunctionAndReturn(MacroAssembler* masm,
5320                                      Register function_address,
5321                                      ExternalReference thunk_ref,
5322                                      int stack_space,
5323                                      MemOperand* stack_space_operand,
5324                                      MemOperand return_value_operand,
5325                                      MemOperand* context_restore_operand) {
5326   Isolate* isolate = masm->isolate();
5327   ExternalReference next_address =
5328       ExternalReference::handle_scope_next_address(isolate);
5329   const int kNextOffset = 0;
5330   const int kLimitOffset = AddressOffset(
5331       ExternalReference::handle_scope_limit_address(isolate), next_address);
5332   const int kLevelOffset = AddressOffset(
5333       ExternalReference::handle_scope_level_address(isolate), next_address);
5334
5335   // Additional parameter is the address of the actual callback.
5336   DCHECK(function_address.is(r4) || function_address.is(r5));
5337   Register scratch = r6;
5338
5339   __ mov(scratch, Operand(ExternalReference::is_profiling_address(isolate)));
5340   __ lbz(scratch, MemOperand(scratch, 0));
5341   __ cmpi(scratch, Operand::Zero());
5342
5343   if (CpuFeatures::IsSupported(ISELECT)) {
5344     __ mov(scratch, Operand(thunk_ref));
5345     __ isel(eq, scratch, function_address, scratch);
5346   } else {
5347     Label profiler_disabled;
5348     Label end_profiler_check;
5349     __ beq(&profiler_disabled);
5350     __ mov(scratch, Operand(thunk_ref));
5351     __ b(&end_profiler_check);
5352     __ bind(&profiler_disabled);
5353     __ mr(scratch, function_address);
5354     __ bind(&end_profiler_check);
5355   }
5356
5357   // Allocate HandleScope in callee-save registers.
5358   // r17 - next_address
5359   // r14 - next_address->kNextOffset
5360   // r15 - next_address->kLimitOffset
5361   // r16 - next_address->kLevelOffset
5362   __ mov(r17, Operand(next_address));
5363   __ LoadP(r14, MemOperand(r17, kNextOffset));
5364   __ LoadP(r15, MemOperand(r17, kLimitOffset));
5365   __ lwz(r16, MemOperand(r17, kLevelOffset));
5366   __ addi(r16, r16, Operand(1));
5367   __ stw(r16, MemOperand(r17, kLevelOffset));
5368
5369   if (FLAG_log_timer_events) {
5370     FrameScope frame(masm, StackFrame::MANUAL);
5371     __ PushSafepointRegisters();
5372     __ PrepareCallCFunction(1, r3);
5373     __ mov(r3, Operand(ExternalReference::isolate_address(isolate)));
5374     __ CallCFunction(ExternalReference::log_enter_external_function(isolate),
5375                      1);
5376     __ PopSafepointRegisters();
5377   }
5378
5379   // Native call returns to the DirectCEntry stub which redirects to the
5380   // return address pushed on stack (could have moved after GC).
5381   // DirectCEntry stub itself is generated early and never moves.
5382   DirectCEntryStub stub(isolate);
5383   stub.GenerateCall(masm, scratch);
5384
5385   if (FLAG_log_timer_events) {
5386     FrameScope frame(masm, StackFrame::MANUAL);
5387     __ PushSafepointRegisters();
5388     __ PrepareCallCFunction(1, r3);
5389     __ mov(r3, Operand(ExternalReference::isolate_address(isolate)));
5390     __ CallCFunction(ExternalReference::log_leave_external_function(isolate),
5391                      1);
5392     __ PopSafepointRegisters();
5393   }
5394
5395   Label promote_scheduled_exception;
5396   Label delete_allocated_handles;
5397   Label leave_exit_frame;
5398   Label return_value_loaded;
5399
5400   // load value from ReturnValue
5401   __ LoadP(r3, return_value_operand);
5402   __ bind(&return_value_loaded);
5403   // No more valid handles (the result handle was the last one). Restore
5404   // previous handle scope.
5405   __ StoreP(r14, MemOperand(r17, kNextOffset));
5406   if (__ emit_debug_code()) {
5407     __ lwz(r4, MemOperand(r17, kLevelOffset));
5408     __ cmp(r4, r16);
5409     __ Check(eq, kUnexpectedLevelAfterReturnFromApiCall);
5410   }
5411   __ subi(r16, r16, Operand(1));
5412   __ stw(r16, MemOperand(r17, kLevelOffset));
5413   __ LoadP(r0, MemOperand(r17, kLimitOffset));
5414   __ cmp(r15, r0);
5415   __ bne(&delete_allocated_handles);
5416
5417   // Leave the API exit frame.
5418   __ bind(&leave_exit_frame);
5419   bool restore_context = context_restore_operand != NULL;
5420   if (restore_context) {
5421     __ LoadP(cp, *context_restore_operand);
5422   }
5423   // LeaveExitFrame expects unwind space to be in a register.
5424   if (stack_space_operand != NULL) {
5425     __ lwz(r14, *stack_space_operand);
5426   } else {
5427     __ mov(r14, Operand(stack_space));
5428   }
5429   __ LeaveExitFrame(false, r14, !restore_context, stack_space_operand != NULL);
5430
5431   // Check if the function scheduled an exception.
5432   __ LoadRoot(r14, Heap::kTheHoleValueRootIndex);
5433   __ mov(r15, Operand(ExternalReference::scheduled_exception_address(isolate)));
5434   __ LoadP(r15, MemOperand(r15));
5435   __ cmp(r14, r15);
5436   __ bne(&promote_scheduled_exception);
5437
5438   __ blr();
5439
5440   // Re-throw by promoting a scheduled exception.
5441   __ bind(&promote_scheduled_exception);
5442   __ TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
5443
5444   // HandleScope limit has changed. Delete allocated extensions.
5445   __ bind(&delete_allocated_handles);
5446   __ StoreP(r15, MemOperand(r17, kLimitOffset));
5447   __ mr(r14, r3);
5448   __ PrepareCallCFunction(1, r15);
5449   __ mov(r3, Operand(ExternalReference::isolate_address(isolate)));
5450   __ CallCFunction(ExternalReference::delete_handle_scope_extensions(isolate),
5451                    1);
5452   __ mr(r3, r14);
5453   __ b(&leave_exit_frame);
5454 }
5455
5456
5457 static void CallApiFunctionStubHelper(MacroAssembler* masm,
5458                                       const ParameterCount& argc,
5459                                       bool return_first_arg,
5460                                       bool call_data_undefined) {
5461   // ----------- S t a t e -------------
5462   //  -- r3                  : callee
5463   //  -- r7                  : call_data
5464   //  -- r5                  : holder
5465   //  -- r4                  : api_function_address
5466   //  -- r6                  : number of arguments if argc is a register
5467   //  -- cp                  : context
5468   //  --
5469   //  -- sp[0]               : last argument
5470   //  -- ...
5471   //  -- sp[(argc - 1)* 4]   : first argument
5472   //  -- sp[argc * 4]        : receiver
5473   // -----------------------------------
5474
5475   Register callee = r3;
5476   Register call_data = r7;
5477   Register holder = r5;
5478   Register api_function_address = r4;
5479   Register context = cp;
5480
5481   typedef FunctionCallbackArguments FCA;
5482
5483   STATIC_ASSERT(FCA::kContextSaveIndex == 6);
5484   STATIC_ASSERT(FCA::kCalleeIndex == 5);
5485   STATIC_ASSERT(FCA::kDataIndex == 4);
5486   STATIC_ASSERT(FCA::kReturnValueOffset == 3);
5487   STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2);
5488   STATIC_ASSERT(FCA::kIsolateIndex == 1);
5489   STATIC_ASSERT(FCA::kHolderIndex == 0);
5490   STATIC_ASSERT(FCA::kArgsLength == 7);
5491
5492   DCHECK(argc.is_immediate() || r3.is(argc.reg()));
5493
5494   // context save
5495   __ push(context);
5496   // load context from callee
5497   __ LoadP(context, FieldMemOperand(callee, JSFunction::kContextOffset));
5498
5499   // callee
5500   __ push(callee);
5501
5502   // call data
5503   __ push(call_data);
5504
5505   Register scratch = call_data;
5506   if (!call_data_undefined) {
5507     __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
5508   }
5509   // return value
5510   __ push(scratch);
5511   // return value default
5512   __ push(scratch);
5513   // isolate
5514   __ mov(scratch, Operand(ExternalReference::isolate_address(masm->isolate())));
5515   __ push(scratch);
5516   // holder
5517   __ push(holder);
5518
5519   // Prepare arguments.
5520   __ mr(scratch, sp);
5521
5522   // Allocate the v8::Arguments structure in the arguments' space since
5523   // it's not controlled by GC.
5524   // PPC LINUX ABI:
5525   //
5526   // Create 5 extra slots on stack:
5527   //    [0] space for DirectCEntryStub's LR save
5528   //    [1-4] FunctionCallbackInfo
5529   const int kApiStackSpace = 5;
5530   const int kFunctionCallbackInfoOffset =
5531       (kStackFrameExtraParamSlot + 1) * kPointerSize;
5532
5533   FrameScope frame_scope(masm, StackFrame::MANUAL);
5534   __ EnterExitFrame(false, kApiStackSpace);
5535
5536   DCHECK(!api_function_address.is(r3) && !scratch.is(r3));
5537   // r3 = FunctionCallbackInfo&
5538   // Arguments is after the return address.
5539   __ addi(r3, sp, Operand(kFunctionCallbackInfoOffset));
5540   // FunctionCallbackInfo::implicit_args_
5541   __ StoreP(scratch, MemOperand(r3, 0 * kPointerSize));
5542   if (argc.is_immediate()) {
5543     // FunctionCallbackInfo::values_
5544     __ addi(ip, scratch,
5545             Operand((FCA::kArgsLength - 1 + argc.immediate()) * kPointerSize));
5546     __ StoreP(ip, MemOperand(r3, 1 * kPointerSize));
5547     // FunctionCallbackInfo::length_ = argc
5548     __ li(ip, Operand(argc.immediate()));
5549     __ stw(ip, MemOperand(r3, 2 * kPointerSize));
5550     // FunctionCallbackInfo::is_construct_call_ = 0
5551     __ li(ip, Operand::Zero());
5552     __ stw(ip, MemOperand(r3, 2 * kPointerSize + kIntSize));
5553   } else {
5554     __ ShiftLeftImm(ip, argc.reg(), Operand(kPointerSizeLog2));
5555     __ addi(ip, ip, Operand((FCA::kArgsLength - 1) * kPointerSize));
5556     // FunctionCallbackInfo::values_
5557     __ add(r0, scratch, ip);
5558     __ StoreP(r0, MemOperand(r3, 1 * kPointerSize));
5559     // FunctionCallbackInfo::length_ = argc
5560     __ stw(argc.reg(), MemOperand(r3, 2 * kPointerSize));
5561     // FunctionCallbackInfo::is_construct_call_
5562     __ stw(ip, MemOperand(r3, 2 * kPointerSize + kIntSize));
5563   }
5564
5565   ExternalReference thunk_ref =
5566       ExternalReference::invoke_function_callback(masm->isolate());
5567
5568   AllowExternalCallThatCantCauseGC scope(masm);
5569   MemOperand context_restore_operand(
5570       fp, (2 + FCA::kContextSaveIndex) * kPointerSize);
5571   // Stores return the first js argument
5572   int return_value_offset = 0;
5573   if (return_first_arg) {
5574     return_value_offset = 2 + FCA::kArgsLength;
5575   } else {
5576     return_value_offset = 2 + FCA::kReturnValueOffset;
5577   }
5578   MemOperand return_value_operand(fp, return_value_offset * kPointerSize);
5579   int stack_space = 0;
5580   MemOperand is_construct_call_operand =
5581       MemOperand(sp, kFunctionCallbackInfoOffset + 2 * kPointerSize + kIntSize);
5582   MemOperand* stack_space_operand = &is_construct_call_operand;
5583   if (argc.is_immediate()) {
5584     stack_space = argc.immediate() + FCA::kArgsLength + 1;
5585     stack_space_operand = NULL;
5586   }
5587   CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, stack_space,
5588                            stack_space_operand, return_value_operand,
5589                            &context_restore_operand);
5590 }
5591
5592
5593 void CallApiFunctionStub::Generate(MacroAssembler* masm) {
5594   bool call_data_undefined = this->call_data_undefined();
5595   CallApiFunctionStubHelper(masm, ParameterCount(r6), false,
5596                             call_data_undefined);
5597 }
5598
5599
5600 void CallApiAccessorStub::Generate(MacroAssembler* masm) {
5601   bool is_store = this->is_store();
5602   int argc = this->argc();
5603   bool call_data_undefined = this->call_data_undefined();
5604   CallApiFunctionStubHelper(masm, ParameterCount(argc), is_store,
5605                             call_data_undefined);
5606 }
5607
5608
5609 void CallApiGetterStub::Generate(MacroAssembler* masm) {
5610   // ----------- S t a t e -------------
5611   //  -- sp[0]                  : name
5612   //  -- sp[4 - kArgsLength*4]  : PropertyCallbackArguments object
5613   //  -- ...
5614   //  -- r5                     : api_function_address
5615   // -----------------------------------
5616
5617   Register api_function_address = ApiGetterDescriptor::function_address();
5618   DCHECK(api_function_address.is(r5));
5619
5620   __ mr(r3, sp);                               // r0 = Handle<Name>
5621   __ addi(r4, r3, Operand(1 * kPointerSize));  // r4 = PCA
5622
5623 // If ABI passes Handles (pointer-sized struct) in a register:
5624 //
5625 // Create 2 extra slots on stack:
5626 //    [0] space for DirectCEntryStub's LR save
5627 //    [1] AccessorInfo&
5628 //
5629 // Otherwise:
5630 //
5631 // Create 3 extra slots on stack:
5632 //    [0] space for DirectCEntryStub's LR save
5633 //    [1] copy of Handle (first arg)
5634 //    [2] AccessorInfo&
5635 #if ABI_PASSES_HANDLES_IN_REGS
5636   const int kAccessorInfoSlot = kStackFrameExtraParamSlot + 1;
5637   const int kApiStackSpace = 2;
5638 #else
5639   const int kArg0Slot = kStackFrameExtraParamSlot + 1;
5640   const int kAccessorInfoSlot = kArg0Slot + 1;
5641   const int kApiStackSpace = 3;
5642 #endif
5643
5644   FrameScope frame_scope(masm, StackFrame::MANUAL);
5645   __ EnterExitFrame(false, kApiStackSpace);
5646
5647 #if !ABI_PASSES_HANDLES_IN_REGS
5648   // pass 1st arg by reference
5649   __ StoreP(r3, MemOperand(sp, kArg0Slot * kPointerSize));
5650   __ addi(r3, sp, Operand(kArg0Slot * kPointerSize));
5651 #endif
5652
5653   // Create PropertyAccessorInfo instance on the stack above the exit frame with
5654   // r4 (internal::Object** args_) as the data.
5655   __ StoreP(r4, MemOperand(sp, kAccessorInfoSlot * kPointerSize));
5656   // r4 = AccessorInfo&
5657   __ addi(r4, sp, Operand(kAccessorInfoSlot * kPointerSize));
5658
5659   const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1;
5660
5661   ExternalReference thunk_ref =
5662       ExternalReference::invoke_accessor_getter_callback(isolate());
5663   CallApiFunctionAndReturn(masm, api_function_address, thunk_ref,
5664                            kStackUnwindSpace, NULL,
5665                            MemOperand(fp, 6 * kPointerSize), NULL);
5666 }
5667
5668
5669 #undef __
5670 }  // namespace internal
5671 }  // namespace v8
5672
5673 #endif  // V8_TARGET_ARCH_PPC