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