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