code-stubs-ia32.cc 54.7 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#if V8_TARGET_ARCH_IA32
6

7
#include "src/api-arguments.h"
8
#include "src/assembler-inl.h"
9
#include "src/base/bits.h"
10
#include "src/bootstrapper.h"
11
#include "src/code-stubs.h"
12 13
#include "src/frame-constants.h"
#include "src/frames.h"
14
#include "src/heap/heap-inl.h"
15
#include "src/ic/handler-compiler.h"
16
#include "src/ic/ic.h"
17
#include "src/ic/stub-cache.h"
18
#include "src/isolate.h"
19 20
#include "src/regexp/jsregexp.h"
#include "src/regexp/regexp-macro-assembler.h"
21
#include "src/runtime/runtime.h"
22

23 24
#include "src/ia32/code-stubs-ia32.h"  // Cannot be the first include.

25 26 27
namespace v8 {
namespace internal {

28
#define __ ACCESS_MASM(masm)
29

30 31 32 33 34 35 36 37
void ArrayNArgumentsConstructorStub::Generate(MacroAssembler* masm) {
  __ pop(ecx);
  __ mov(MemOperand(esp, eax, times_4, 0), edi);
  __ push(edi);
  __ push(ebx);
  __ push(ecx);
  __ add(eax, Immediate(3));
  __ TailCallRuntime(Runtime::kNewArray);
38 39
}

40

41 42 43 44 45
void StoreBufferOverflowStub::Generate(MacroAssembler* masm) {
  // We don't allow a GC during a store buffer overflow so there is no need to
  // store the registers in any particular way, but we do have to store and
  // restore them.
  __ pushad();
46
  if (save_doubles()) {
47 48
    __ sub(esp, Immediate(kDoubleSize * XMMRegister::kNumRegisters));
    for (int i = 0; i < XMMRegister::kNumRegisters; i++) {
49
      XMMRegister reg = XMMRegister::from_code(i);
50
      __ movsd(Operand(esp, i * kDoubleSize), reg);
51 52 53 54 55 56 57
    }
  }
  const int argument_count = 1;

  AllowExternalCallThatCantCauseGC scope(masm);
  __ PrepareCallCFunction(argument_count, ecx);
  __ mov(Operand(esp, 0 * kPointerSize),
58
         Immediate(ExternalReference::isolate_address(isolate())));
59
  __ CallCFunction(
60
      ExternalReference::store_buffer_overflow_function(isolate()),
61
      argument_count);
62
  if (save_doubles()) {
63
    for (int i = 0; i < XMMRegister::kNumRegisters; i++) {
64
      XMMRegister reg = XMMRegister::from_code(i);
65
      __ movsd(reg, Operand(esp, i * kDoubleSize));
66
    }
67
    __ add(esp, Immediate(kDoubleSize * XMMRegister::kNumRegisters));
68 69 70 71 72 73
  }
  __ popad();
  __ ret(0);
}


74 75 76
void DoubleToIStub::Generate(MacroAssembler* masm) {
  Register final_result_reg = this->destination();

77
  Label check_negative, process_64_bits, done;
78

79 80
  // Account for return address and saved regs.
  const int kArgumentOffset = 3 * kPointerSize;
81

82 83 84
  MemOperand mantissa_operand(MemOperand(esp, kArgumentOffset));
  MemOperand exponent_operand(
      MemOperand(esp, kArgumentOffset + kDoubleSize / 2));
85

86
  Register scratch1 = no_reg;
87 88 89 90
  {
    Register scratch_candidates[3] = { ebx, edx, edi };
    for (int i = 0; i < 3; i++) {
      scratch1 = scratch_candidates[i];
91
      if (final_result_reg != scratch1) break;
92 93 94 95
    }
  }
  // Since we must use ecx for shifts below, use some other register (eax)
  // to calculate the result if ecx is the requested return register.
96
  Register result_reg = final_result_reg == ecx ? eax : final_result_reg;
97 98 99
  // Save ecx if it isn't the return register and therefore volatile, or if it
  // is the return register, then save the temp register we use in its stead for
  // the result.
100
  Register save_reg = final_result_reg == ecx ? eax : ecx;
101 102 103 104 105
  __ push(scratch1);
  __ push(save_reg);

  __ mov(scratch1, mantissa_operand);
  if (CpuFeatures::IsSupported(SSE3)) {
106
    CpuFeatureScope scope(masm, SSE3);
107
    // Load x87 register with heap number.
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    __ fld_d(mantissa_operand);
  }
  __ mov(ecx, exponent_operand);

  __ and_(ecx, HeapNumber::kExponentMask);
  __ shr(ecx, HeapNumber::kExponentShift);
  __ lea(result_reg, MemOperand(ecx, -HeapNumber::kExponentBias));
  __ cmp(result_reg, Immediate(HeapNumber::kMantissaBits));
  __ j(below, &process_64_bits);

  // Result is entirely in lower 32-bits of mantissa
  int delta = HeapNumber::kExponentBias + Double::kPhysicalSignificandSize;
  if (CpuFeatures::IsSupported(SSE3)) {
    __ fstp(0);
  }
  __ sub(ecx, Immediate(delta));
  __ xor_(result_reg, result_reg);
  __ cmp(ecx, Immediate(31));
  __ j(above, &done);
  __ shl_cl(scratch1);
  __ jmp(&check_negative);

  __ bind(&process_64_bits);
  if (CpuFeatures::IsSupported(SSE3)) {
    CpuFeatureScope scope(masm, SSE3);
133 134
    // Reserve space for 64 bit answer.
    __ sub(esp, Immediate(kDoubleSize));  // Nolint.
135 136
    // Do conversion, which cannot fail because we checked the exponent.
    __ fisttp_d(Operand(esp, 0));
137 138
    __ mov(result_reg, Operand(esp, 0));  // Load low word of answer as result
    __ add(esp, Immediate(kDoubleSize));
139
    __ jmp(&done);
140
  } else {
141 142 143
    // Result must be extracted from shifted 32-bit mantissa
    __ sub(ecx, Immediate(delta));
    __ neg(ecx);
144
    __ mov(result_reg, exponent_operand);
145 146 147 148
    __ and_(result_reg,
            Immediate(static_cast<uint32_t>(Double::kSignificandMask >> 32)));
    __ add(result_reg,
           Immediate(static_cast<uint32_t>(Double::kHiddenBit >> 32)));
149
    __ shrd_cl(scratch1, result_reg);
150 151
    __ shr_cl(result_reg);
    __ test(ecx, Immediate(32));
152
    __ cmov(not_equal, scratch1, result_reg);
153
  }
154

155 156 157 158
  // If the double was negative, negate the integer result.
  __ bind(&check_negative);
  __ mov(result_reg, scratch1);
  __ neg(result_reg);
159 160
  __ cmp(exponent_operand, Immediate(0));
  __ cmov(greater, result_reg, scratch1);
161 162

  // Restore registers
163
  __ bind(&done);
164 165
  if (final_result_reg != result_reg) {
    DCHECK(final_result_reg == ecx);
166 167 168 169 170
    __ mov(final_result_reg, result_reg);
  }
  __ pop(save_reg);
  __ pop(scratch1);
  __ ret(0);
171 172 173
}


174
void MathPowStub::Generate(MacroAssembler* masm) {
175
  const Register exponent = MathPowTaggedDescriptor::exponent();
176
  DCHECK(exponent == eax);
177 178 179 180 181 182
  const Register scratch = ecx;
  const XMMRegister double_result = xmm3;
  const XMMRegister double_base = xmm2;
  const XMMRegister double_exponent = xmm1;
  const XMMRegister double_scratch = xmm4;

183
  Label call_runtime, done, exponent_not_smi, int_exponent;
184 185 186

  // Save 1 in double_result - we need this several times later on.
  __ mov(scratch, Immediate(1));
187
  __ Cvtsi2sd(double_result, scratch);
188

189
  if (exponent_type() == TAGGED) {
190 191
    __ JumpIfNotSmi(exponent, &exponent_not_smi, Label::kNear);
    __ SmiUntag(exponent);
192 193 194
    __ jmp(&int_exponent);

    __ bind(&exponent_not_smi);
195
    __ movsd(double_exponent,
196
              FieldOperand(exponent, HeapNumber::kValueOffset));
197
  }
198

199
  if (exponent_type() != INTEGER) {
200 201
    Label fast_power, try_arithmetic_simplification;
    __ DoubleToI(exponent, double_exponent, double_scratch,
202 203 204
                 TREAT_MINUS_ZERO_AS_ZERO, &try_arithmetic_simplification,
                 &try_arithmetic_simplification,
                 &try_arithmetic_simplification);
205 206 207
    __ jmp(&int_exponent);

    __ bind(&try_arithmetic_simplification);
208
    // Skip to runtime if possibly NaN (indicated by the indefinite integer).
209
    __ cvttsd2si(exponent, Operand(double_exponent));
210 211
    __ cmp(exponent, Immediate(0x1));
    __ j(overflow, &call_runtime);
212 213 214 215 216 217 218

    // Using FPU instructions to calculate power.
    Label fast_power_failed;
    __ bind(&fast_power);
    __ fnclex();  // Clear flags to catch exceptions later.
    // Transfer (B)ase and (E)xponent onto the FPU register stack.
    __ sub(esp, Immediate(kDoubleSize));
219
    __ movsd(Operand(esp, 0), double_exponent);
220
    __ fld_d(Operand(esp, 0));  // E
221
    __ movsd(Operand(esp, 0), double_base);
222 223 224 225 226 227 228 229 230 231 232 233 234
    __ fld_d(Operand(esp, 0));  // B, E

    // Exponent is in st(1) and base is in st(0)
    // B ^ E = (2^(E * log2(B)) - 1) + 1 = (2^X - 1) + 1 for X = E * log2(B)
    // FYL2X calculates st(1) * log2(st(0))
    __ fyl2x();    // X
    __ fld(0);     // X, X
    __ frndint();  // rnd(X), X
    __ fsub(1);    // rnd(X), X-rnd(X)
    __ fxch(1);    // X - rnd(X), rnd(X)
    // F2XM1 calculates 2^st(0) - 1 for -1 < st(0) < 1
    __ f2xm1();    // 2^(X-rnd(X)) - 1, rnd(X)
    __ fld1();     // 1, 2^(X-rnd(X)) - 1, rnd(X)
235
    __ faddp(1);   // 2^(X-rnd(X)), rnd(X)
236 237
    // FSCALE calculates st(0) * 2^st(1)
    __ fscale();   // 2^X, rnd(X)
238
    __ fstp(1);    // 2^X
239 240
    // Bail out to runtime in case of exceptions in the status word.
    __ fnstsw_ax();
241 242
    __ test_b(eax,
              Immediate(0x5F));  // We check for all but precision exception.
243 244
    __ j(not_zero, &fast_power_failed, Label::kNear);
    __ fstp_d(Operand(esp, 0));
245
    __ movsd(double_result, Operand(esp, 0));
246 247
    __ add(esp, Immediate(kDoubleSize));
    __ jmp(&done);
248

249 250 251
    __ bind(&fast_power_failed);
    __ fninit();
    __ add(esp, Immediate(kDoubleSize));
252
    __ jmp(&call_runtime);
253
  }
254

255 256
  // Calculate power with integer exponent.
  __ bind(&int_exponent);
257
  const XMMRegister double_scratch2 = double_exponent;
258
  __ mov(scratch, exponent);  // Back up exponent.
259 260
  __ movsd(double_scratch, double_base);  // Back up base.
  __ movsd(double_scratch2, double_result);  // Load double_exponent with 1.
261 262

  // Get absolute value of exponent.
263
  Label no_neg, while_true, while_false;
264 265 266 267
  __ test(scratch, scratch);
  __ j(positive, &no_neg, Label::kNear);
  __ neg(scratch);
  __ bind(&no_neg);
268

269
  __ j(zero, &while_false, Label::kNear);
270
  __ shr(scratch, 1);
271 272 273 274 275
  // Above condition means CF==0 && ZF==0.  This means that the
  // bit that has been shifted out is 0 and the result is not 0.
  __ j(above, &while_true, Label::kNear);
  __ movsd(double_result, double_scratch);
  __ j(zero, &while_false, Label::kNear);
276

277 278
  __ bind(&while_true);
  __ shr(scratch, 1);
279
  __ mulsd(double_scratch, double_scratch);
280 281
  __ j(above, &while_true, Label::kNear);
  __ mulsd(double_result, double_scratch);
282 283
  __ j(not_zero, &while_true);

284
  __ bind(&while_false);
285 286
  // scratch has the original value of the exponent - if the exponent is
  // negative, return 1/result.
287
  __ test(exponent, exponent);
288
  __ j(positive, &done);
289 290
  __ divsd(double_scratch2, double_result);
  __ movsd(double_result, double_scratch2);
291 292
  // Test whether result is zero.  Bail out to check for subnormal result.
  // Due to subnormals, x^-y == (1/x)^y does not hold in all cases.
293 294
  __ xorps(double_scratch2, double_scratch2);
  __ ucomisd(double_scratch2, double_result);  // Result cannot be NaN.
295 296 297 298
  // double_exponent aliased as double_scratch2 has already been overwritten
  // and may not have contained the exponent value in the first place when the
  // exponent is a smi.  We reset it with exponent value before bailing out.
  __ j(not_equal, &done);
299
  __ Cvtsi2sd(double_exponent, exponent);
300 301

  // Returning or bailing out.
302 303 304 305 306 307 308 309
  __ bind(&call_runtime);
  {
    AllowExternalCallThatCantCauseGC scope(masm);
    __ PrepareCallCFunction(4, scratch);
    __ movsd(Operand(esp, 0 * kDoubleSize), double_base);
    __ movsd(Operand(esp, 1 * kDoubleSize), double_exponent);
    __ CallCFunction(ExternalReference::power_double_double_function(isolate()),
                     4);
310
  }
311 312 313 314 315 316
  // Return value is in st(0) on ia32.
  // Store it into the (fixed) result register.
  __ sub(esp, Immediate(kDoubleSize));
  __ fstp_d(Operand(esp, 0));
  __ movsd(double_result, Operand(esp, 0));
  __ add(esp, Immediate(kDoubleSize));
317

318 319 320
  __ bind(&done);
  __ ret(0);
}
321

322

323 324 325 326 327
bool CEntryStub::NeedsImmovableCode() {
  return false;
}


328 329 330
void CodeStub::GenerateStubsAheadOfTime(Isolate* isolate) {
  CEntryStub::GenerateAheadOfTime(isolate);
  StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(isolate);
331
  // It is important that the store buffer overflow stubs are generated first.
332
  CommonArrayConstructorStub::GenerateStubsAheadOfTime(isolate);
333
  StoreFastElementStub::GenerateAheadOfTime(isolate);
334 335 336
}


337
void CodeStub::GenerateFPStubs(Isolate* isolate) {
338 339
  // Generate if not already in cache.
  CEntryStub(isolate, 1, kSaveFPRegs).GetCode();
340 341 342
}


343
void CEntryStub::GenerateAheadOfTime(Isolate* isolate) {
344
  CEntryStub stub(isolate, 1, kDontSaveFPRegs);
345
  stub.GetCode();
346 347 348
}


349 350 351 352 353 354 355
void CEntryStub::Generate(MacroAssembler* masm) {
  // eax: number of arguments including receiver
  // ebx: pointer to C function  (C callee-saved)
  // ebp: frame pointer  (restored after C call)
  // esp: stack pointer  (restored after C call)
  // esi: current context (C callee-saved)
  // edi: JS function of the caller (C callee-saved)
356 357 358
  //
  // If argv_in_register():
  // ecx: pointer to the first argument
359 360 361

  ProfileEntryHookStub::MaybeCallEntryHook(masm);

362 363 364 365
  // Reserve space on the stack for the three arguments passed to the call. If
  // result size is greater than can be returned in registers, also reserve
  // space for the hidden argument for the result location, and space for the
  // result itself.
366
  int arg_stack_space = 3;
367

368
  // Enter the exit frame that transitions from JavaScript to C++.
369 370
  if (argv_in_register()) {
    DCHECK(!save_doubles());
371
    DCHECK(!is_builtin_exit());
372
    __ EnterApiExitFrame(arg_stack_space);
373 374 375 376 377

    // Move argc and argv into the correct registers.
    __ mov(esi, ecx);
    __ mov(edi, eax);
  } else {
378 379 380
    __ EnterExitFrame(
        arg_stack_space, save_doubles(),
        is_builtin_exit() ? StackFrame::BUILTIN_EXIT : StackFrame::EXIT);
381
  }
382

383 384 385 386 387 388
  // ebx: pointer to C function  (C callee-saved)
  // ebp: frame pointer  (restored after C call)
  // esp: stack pointer  (restored after C call)
  // edi: number of arguments including receiver  (C callee-saved)
  // esi: pointer to the first argument (C callee-saved)

389
  // Result returned in eax, or eax+edx if result size is 2.
390 391 392 393 394 395

  // Check stack alignment.
  if (FLAG_debug_code) {
    __ CheckStackAlignment();
  }
  // Call C function.
396 397 398 399
  __ mov(Operand(esp, 0 * kPointerSize), edi);  // argc.
  __ mov(Operand(esp, 1 * kPointerSize), esi);  // argv.
  __ mov(Operand(esp, 2 * kPointerSize),
         Immediate(ExternalReference::isolate_address(isolate())));
400
  __ call(ebx);
401

402
  // Result is in eax or edx:eax - do not destroy these registers!
403

404 405
  // Check result for exception sentinel.
  Label exception_returned;
406
  __ cmp(eax, isolate()->factory()->exception());
407
  __ j(equal, &exception_returned);
408

409
  // Check that there is no pending exception, otherwise we
410
  // should have returned the exception sentinel.
411 412
  if (FLAG_debug_code) {
    __ push(edx);
413
    __ mov(edx, Immediate(isolate()->factory()->the_hole_value()));
414
    Label okay;
415
    ExternalReference pending_exception_address(
416
        IsolateAddressId::kPendingExceptionAddress, isolate());
417 418
    __ cmp(edx, Operand::StaticVariable(pending_exception_address));
    // Cannot use check here as it attempts to generate call into runtime.
419
    __ j(equal, &okay, Label::kNear);
420 421 422 423 424
    __ int3();
    __ bind(&okay);
    __ pop(edx);
  }

425
  // Exit the JavaScript to C++ exit frame.
426
  __ LeaveExitFrame(save_doubles(), !argv_in_register());
427 428
  __ ret(0);

429 430
  // Handling of exception.
  __ bind(&exception_returned);
431 432

  ExternalReference pending_handler_context_address(
433
      IsolateAddressId::kPendingHandlerContextAddress, isolate());
434
  ExternalReference pending_handler_code_address(
435
      IsolateAddressId::kPendingHandlerCodeAddress, isolate());
436
  ExternalReference pending_handler_offset_address(
437
      IsolateAddressId::kPendingHandlerOffsetAddress, isolate());
438
  ExternalReference pending_handler_fp_address(
439
      IsolateAddressId::kPendingHandlerFPAddress, isolate());
440
  ExternalReference pending_handler_sp_address(
441
      IsolateAddressId::kPendingHandlerSPAddress, isolate());
442 443 444

  // Ask the runtime for help to determine the handler. This will set eax to
  // contain the current pending exception, don't clobber it.
445 446
  ExternalReference find_handler(Runtime::kUnwindAndFindExceptionHandler,
                                 isolate());
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
  {
    FrameScope scope(masm, StackFrame::MANUAL);
    __ PrepareCallCFunction(3, eax);
    __ mov(Operand(esp, 0 * kPointerSize), Immediate(0));  // argc.
    __ mov(Operand(esp, 1 * kPointerSize), Immediate(0));  // argv.
    __ mov(Operand(esp, 2 * kPointerSize),
           Immediate(ExternalReference::isolate_address(isolate())));
    __ CallCFunction(find_handler, 3);
  }

  // Retrieve the handler context, SP and FP.
  __ mov(esi, Operand::StaticVariable(pending_handler_context_address));
  __ mov(esp, Operand::StaticVariable(pending_handler_sp_address));
  __ mov(ebp, Operand::StaticVariable(pending_handler_fp_address));

462 463
  // If the handler is a JS frame, restore the context to the frame. Note that
  // the context will be set to (esi == 0) for non-JS frames.
464 465 466 467 468 469 470 471 472 473 474
  Label skip;
  __ test(esi, esi);
  __ j(zero, &skip, Label::kNear);
  __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), esi);
  __ bind(&skip);

  // Compute the handler entry address and jump to it.
  __ mov(edi, Operand::StaticVariable(pending_handler_code_address));
  __ mov(edx, Operand::StaticVariable(pending_handler_offset_address));
  __ lea(edi, FieldOperand(edi, edx, times_1, Code::kHeaderSize));
  __ jmp(edi);
475 476 477
}


478
void JSEntryStub::Generate(MacroAssembler* masm) {
479
  Label invoke, handler_entry, exit;
480 481
  Label not_outermost_js, not_outermost_js_2;

482 483
  ProfileEntryHookStub::MaybeCallEntryHook(masm);

484
  // Set up frame.
485
  __ push(ebp);
486
  __ mov(ebp, esp);
487 488

  // Push marker in two places.
489 490
  StackFrame::Type marker = type();
  __ push(Immediate(StackFrame::TypeToMarker(marker)));  // marker
491 492
  ExternalReference context_address(IsolateAddressId::kContextAddress,
                                    isolate());
493
  __ push(Operand::StaticVariable(context_address));  // context
494 495 496 497 498 499
  // Save callee-saved registers (C calling conventions).
  __ push(edi);
  __ push(esi);
  __ push(ebx);

  // Save copies of the top frame descriptor on the stack.
500
  ExternalReference c_entry_fp(IsolateAddressId::kCEntryFPAddress, isolate());
501 502 503
  __ push(Operand::StaticVariable(c_entry_fp));

  // If this is the outermost JS call, set js_entry_sp value.
504
  ExternalReference js_entry_sp(IsolateAddressId::kJSEntrySPAddress, isolate());
505
  __ cmp(Operand::StaticVariable(js_entry_sp), Immediate(0));
506
  __ j(not_equal, &not_outermost_js, Label::kNear);
507
  __ mov(Operand::StaticVariable(js_entry_sp), ebp);
508
  __ push(Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME));
509
  __ jmp(&invoke, Label::kNear);
510
  __ bind(&not_outermost_js);
511
  __ push(Immediate(StackFrame::INNER_JSENTRY_FRAME));
512

513 514 515 516 517 518 519
  // Jump to a faked try block that does the invoke, with a faked catch
  // block that sets the pending exception.
  __ jmp(&invoke);
  __ bind(&handler_entry);
  handler_offset_ = handler_entry.pos();
  // Caught exception: Store result (exception) in the pending exception
  // field in the JSEnv and return a failure sentinel.
520 521
  ExternalReference pending_exception(
      IsolateAddressId::kPendingExceptionAddress, isolate());
522
  __ mov(Operand::StaticVariable(pending_exception), eax);
523
  __ mov(eax, Immediate(isolate()->factory()->exception()));
524 525
  __ jmp(&exit);

526
  // Invoke: Link this frame into the handler chain.
527
  __ bind(&invoke);
528
  __ PushStackHandler();
529

530 531 532 533
  // Invoke the function by calling through JS entry trampoline builtin and
  // pop the faked function when we return. Notice that we cannot store a
  // reference to the trampoline code directly in this stub, because the
  // builtin stubs may not have been generated yet.
534
  if (type() == StackFrame::CONSTRUCT_ENTRY) {
535 536
    __ Call(BUILTIN_CODE(isolate(), JSConstructEntryTrampoline),
            RelocInfo::CODE_TARGET);
537
  } else {
538
    __ Call(BUILTIN_CODE(isolate(), JSEntryTrampoline), RelocInfo::CODE_TARGET);
539 540 541
  }

  // Unlink this frame from the handler chain.
542
  __ PopStackHandler();
543

544 545 546
  __ bind(&exit);
  // Check if the current stack frame is marked as the outermost JS frame.
  __ pop(ebx);
547
  __ cmp(ebx, Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME));
548 549 550 551 552
  __ j(not_equal, &not_outermost_js_2);
  __ mov(Operand::StaticVariable(js_entry_sp), Immediate(0));
  __ bind(&not_outermost_js_2);

  // Restore the top frame descriptor from the stack.
553 554
  __ pop(Operand::StaticVariable(
      ExternalReference(IsolateAddressId::kCEntryFPAddress, isolate())));
555 556 557 558 559

  // Restore callee-saved registers (C calling conventions).
  __ pop(ebx);
  __ pop(esi);
  __ pop(edi);
560
  __ add(esp, Immediate(2 * kPointerSize));  // remove markers
561 562 563 564 565 566

  // Restore frame pointer and return.
  __ pop(ebp);
  __ ret(0);
}

567 568 569 570
// Helper function used to check that the dictionary doesn't contain
// the property. This function may return false negatives, so miss_label
// must always call a backup property check that is complete.
// This function is safe to call if the receiver has fast properties.
571 572 573 574 575 576 577
// Name must be a unique name and receiver must be a heap object.
void NameDictionaryLookupStub::GenerateNegativeLookup(MacroAssembler* masm,
                                                      Label* miss,
                                                      Label* done,
                                                      Register properties,
                                                      Handle<Name> name,
                                                      Register r0) {
578
  DCHECK(name->IsUniqueName());
579 580 581 582 583

  // If names of slots in range from 1 to kProbes - 1 for the hash value are
  // not equal to the name and kProbes-th slot is not used (its name is the
  // undefined value), it guarantees the hash table doesn't contain the
  // property. It's true even if some slots represent deleted properties
584
  // (their names are the hole value).
585 586 587 588 589 590 591 592
  for (int i = 0; i < kInlinedProbes; i++) {
    // Compute the masked index: (hash + i + i * i) & mask.
    Register index = r0;
    // Capacity is smi 2^n.
    __ mov(index, FieldOperand(properties, kCapacityOffset));
    __ dec(index);
    __ and_(index,
            Immediate(Smi::FromInt(name->Hash() +
593
                                   NameDictionary::GetProbeOffset(i))));
594 595

    // Scale the index by multiplying by the entry size.
596
    STATIC_ASSERT(NameDictionary::kEntrySize == 3);
597 598 599
    __ lea(index, Operand(index, index, times_2, 0));  // index *= 3.
    Register entity_name = r0;
    // Having undefined at this place means the name is not contained.
600
    STATIC_ASSERT(kSmiTagSize == 1);
601 602 603 604 605 606
    __ mov(entity_name, Operand(properties, index, times_half_pointer_size,
                                kElementsStartOffset - kHeapObjectTag));
    __ cmp(entity_name, masm->isolate()->factory()->undefined_value());
    __ j(equal, done);

    // Stop if found the property.
607
    __ cmp(entity_name, Handle<Name>(name));
608 609 610
    __ j(equal, miss);
  }

611
  NameDictionaryLookupStub stub(masm->isolate(), properties, r0, r0);
612
  __ push(Immediate(name));
613 614 615 616 617 618 619
  __ push(Immediate(name->Hash()));
  __ CallStub(&stub);
  __ test(r0, r0);
  __ j(not_zero, miss);
  __ jmp(done);
}

620
void NameDictionaryLookupStub::Generate(MacroAssembler* masm) {
621 622
  // This stub overrides SometimesSetsUpAFrame() to return false.  That means
  // we cannot call anything that could cause a GC from this stub.
623 624 625 626 627
  // Stack frame on entry:
  //  esp[0 * kPointerSize]: return address.
  //  esp[1 * kPointerSize]: key's hash.
  //  esp[2 * kPointerSize]: key.
  // Registers:
628
  //  dictionary_: NameDictionary to probe.
629 630 631 632 633 634
  //  result_: used as scratch.
  //  index_: will hold an index of entry if lookup is successful.
  //          might alias with result_.
  // Returns:
  //  result_ is zero if lookup failed, non zero otherwise.

635
  Label in_dictionary, not_in_dictionary;
636

637
  Register scratch = result();
638

639
  __ mov(scratch, FieldOperand(dictionary(), kCapacityOffset));
640 641 642 643 644 645 646 647 648 649 650 651 652
  __ dec(scratch);
  __ SmiUntag(scratch);
  __ push(scratch);

  // If names of slots in range from 1 to kProbes - 1 for the hash value are
  // not equal to the name and kProbes-th slot is not used (its name is the
  // undefined value), it guarantees the hash table doesn't contain the
  // property. It's true even if some slots represent deleted properties
  // (their names are the null value).
  for (int i = kInlinedProbes; i < kTotalProbes; i++) {
    // Compute the masked index: (hash + i + i * i) & mask.
    __ mov(scratch, Operand(esp, 2 * kPointerSize));
    if (i > 0) {
653
      __ add(scratch, Immediate(NameDictionary::GetProbeOffset(i)));
654 655 656 657
    }
    __ and_(scratch, Operand(esp, 0));

    // Scale the index by multiplying by the entry size.
658
    STATIC_ASSERT(NameDictionary::kEntrySize == 3);
659
    __ lea(index(), Operand(scratch, scratch, times_2, 0));  // index *= 3.
660 661

    // Having undefined at this place means the name is not contained.
662
    STATIC_ASSERT(kSmiTagSize == 1);
663
    __ mov(scratch, Operand(dictionary(), index(), times_pointer_size,
664
                            kElementsStartOffset - kHeapObjectTag));
665
    __ cmp(scratch, isolate()->factory()->undefined_value());
666 667 668 669 670 671 672 673
    __ j(equal, &not_in_dictionary);

    // Stop if found the property.
    __ cmp(scratch, Operand(esp, 3 * kPointerSize));
    __ j(equal, &in_dictionary);
  }

  __ bind(&in_dictionary);
674
  __ mov(result(), Immediate(1));
675 676 677 678
  __ Drop(1);
  __ ret(2 * kPointerSize);

  __ bind(&not_in_dictionary);
679
  __ mov(result(), Immediate(0));
680 681 682 683 684
  __ Drop(1);
  __ ret(2 * kPointerSize);
}


685 686
void StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(
    Isolate* isolate) {
687
  StoreBufferOverflowStub stub(isolate, kDontSaveFPRegs);
688
  stub.GetCode();
689 690
  StoreBufferOverflowStub stub2(isolate, kSaveFPRegs);
  stub2.GetCode();
691 692
}

693 694 695 696 697 698 699 700
RecordWriteStub::Mode RecordWriteStub::GetMode(Code* stub) {
  byte first_instruction = stub->instruction_start()[0];
  byte second_instruction = stub->instruction_start()[2];

  if (first_instruction == kTwoByteJumpInstruction) {
    return INCREMENTAL;
  }

701
  DCHECK_EQ(first_instruction, kTwoByteNopInstruction);
702 703 704 705 706

  if (second_instruction == kFiveByteJumpInstruction) {
    return INCREMENTAL_COMPACTION;
  }

707
  DCHECK_EQ(second_instruction, kFiveByteNopInstruction);
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

  return STORE_BUFFER_ONLY;
}

void RecordWriteStub::Patch(Code* stub, Mode mode) {
  switch (mode) {
    case STORE_BUFFER_ONLY:
      DCHECK(GetMode(stub) == INCREMENTAL ||
             GetMode(stub) == INCREMENTAL_COMPACTION);
      stub->instruction_start()[0] = kTwoByteNopInstruction;
      stub->instruction_start()[2] = kFiveByteNopInstruction;
      break;
    case INCREMENTAL:
      DCHECK(GetMode(stub) == STORE_BUFFER_ONLY);
      stub->instruction_start()[0] = kTwoByteJumpInstruction;
      break;
    case INCREMENTAL_COMPACTION:
      DCHECK(GetMode(stub) == STORE_BUFFER_ONLY);
      stub->instruction_start()[0] = kTwoByteNopInstruction;
      stub->instruction_start()[2] = kFiveByteJumpInstruction;
      break;
  }
  DCHECK(GetMode(stub) == mode);
  Assembler::FlushICache(stub->GetIsolate(), stub->instruction_start(), 7);
}
733

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
// Takes the input in 3 registers: address_ value_ and object_.  A pointer to
// the value has just been written into the object, now this stub makes sure
// we keep the GC informed.  The word in the object where the value has been
// written is in the address register.
void RecordWriteStub::Generate(MacroAssembler* masm) {
  Label skip_to_incremental_noncompacting;
  Label skip_to_incremental_compacting;

  // The first two instructions are generated with labels so as to get the
  // offset fixed up correctly by the bind(Label*) call.  We patch it back and
  // forth between a compare instructions (a nop in this position) and the
  // real branch when we start and stop incremental heap marking.
  __ jmp(&skip_to_incremental_noncompacting, Label::kNear);
  __ jmp(&skip_to_incremental_compacting, Label::kFar);

749
  if (remembered_set_action() == EMIT_REMEMBERED_SET) {
750
    __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode());
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
  } else {
    __ ret(0);
  }

  __ bind(&skip_to_incremental_noncompacting);
  GenerateIncremental(masm, INCREMENTAL);

  __ bind(&skip_to_incremental_compacting);
  GenerateIncremental(masm, INCREMENTAL_COMPACTION);

  // Initial mode of the stub is expected to be STORE_BUFFER_ONLY.
  // Will be checked in IncrementalMarking::ActivateGeneratedStub.
  masm->set_byte_at(0, kTwoByteNopInstruction);
  masm->set_byte_at(2, kFiveByteNopInstruction);
}


void RecordWriteStub::GenerateIncremental(MacroAssembler* masm, Mode mode) {
  regs_.Save(masm);

771
  if (remembered_set_action() == EMIT_REMEMBERED_SET) {
772 773 774
    Label dont_need_remembered_set;

    __ mov(regs_.scratch0(), Operand(regs_.address(), 0));
775
    __ JumpIfNotInNewSpace(regs_.scratch0(),  // Value.
776 777 778
                           regs_.scratch0(),
                           &dont_need_remembered_set);

ulan's avatar
ulan committed
779 780
    __ JumpIfInNewSpace(regs_.object(), regs_.scratch0(),
                        &dont_need_remembered_set);
781 782 783 784 785 786 787

    // First notify the incremental marker if necessary, then update the
    // remembered set.
    CheckNeedsToInformIncrementalMarker(
        masm,
        kUpdateRememberedSetOnNoNeedToInformIncrementalMarker,
        mode);
788
    InformIncrementalMarker(masm);
789
    regs_.Restore(masm);
790
    __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode());
791 792 793 794 795 796 797 798

    __ bind(&dont_need_remembered_set);
  }

  CheckNeedsToInformIncrementalMarker(
      masm,
      kReturnOnNoNeedToInformIncrementalMarker,
      mode);
799
  InformIncrementalMarker(masm);
800 801 802 803 804
  regs_.Restore(masm);
  __ ret(0);
}


805
void RecordWriteStub::InformIncrementalMarker(MacroAssembler* masm) {
806
  regs_.SaveCallerSaveRegisters(masm, save_fp_regs_mode());
807 808 809
  int argument_count = 3;
  __ PrepareCallCFunction(argument_count, regs_.scratch0());
  __ mov(Operand(esp, 0 * kPointerSize), regs_.object());
810
  __ mov(Operand(esp, 1 * kPointerSize), regs_.address());  // Slot.
811
  __ mov(Operand(esp, 2 * kPointerSize),
812
         Immediate(ExternalReference::isolate_address(isolate())));
813 814

  AllowExternalCallThatCantCauseGC scope(masm);
815
  __ CallCFunction(
816
      ExternalReference::incremental_marking_record_write_function(isolate()),
817 818
      argument_count);

819
  regs_.RestoreCallerSaveRegisters(masm, save_fp_regs_mode());
820 821
}

822 823 824
void RecordWriteStub::Activate(Code* code) {
  code->GetHeap()->incremental_marking()->ActivateGeneratedStub(code);
}
825 826 827 828 829

void RecordWriteStub::CheckNeedsToInformIncrementalMarker(
    MacroAssembler* masm,
    OnNoNeedToInformIncrementalMarker on_no_need,
    Mode mode) {
830
  Label need_incremental, need_incremental_pop_object;
831

832 833
#ifndef V8_CONCURRENT_MARKING
  Label object_is_black;
834 835 836 837 838 839 840 841 842 843
  // Let's look at the color of the object:  If it is not black we don't have
  // to inform the incremental marker.
  __ JumpIfBlack(regs_.object(),
                 regs_.scratch0(),
                 regs_.scratch1(),
                 &object_is_black,
                 Label::kNear);

  regs_.Restore(masm);
  if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
844
    __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode());
845 846 847 848 849
  } else {
    __ ret(0);
  }

  __ bind(&object_is_black);
850
#endif
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

  // Get the value from the slot.
  __ mov(regs_.scratch0(), Operand(regs_.address(), 0));

  if (mode == INCREMENTAL_COMPACTION) {
    Label ensure_not_white;

    __ CheckPageFlag(regs_.scratch0(),  // Contains value.
                     regs_.scratch1(),  // Scratch.
                     MemoryChunk::kEvacuationCandidateMask,
                     zero,
                     &ensure_not_white,
                     Label::kNear);

    __ CheckPageFlag(regs_.object(),
                     regs_.scratch1(),  // Scratch.
                     MemoryChunk::kSkipEvacuationSlotsRecordingMask,
                     not_zero,
                     &ensure_not_white,
                     Label::kNear);

    __ jmp(&need_incremental);

    __ bind(&ensure_not_white);
  }

  // We need an extra register for this, so we push the object register
  // temporarily.
  __ push(regs_.object());
hpayer's avatar
hpayer committed
880 881 882 883
  __ JumpIfWhite(regs_.scratch0(),  // The value.
                 regs_.scratch1(),  // Scratch.
                 regs_.object(),    // Scratch.
                 &need_incremental_pop_object, Label::kNear);
884 885 886 887
  __ pop(regs_.object());

  regs_.Restore(masm);
  if (on_no_need == kUpdateRememberedSetOnNoNeedToInformIncrementalMarker) {
888
    __ RememberedSetHelper(object(), address(), value(), save_fp_regs_mode());
889 890 891 892 893 894 895 896 897 898 899 900
  } else {
    __ ret(0);
  }

  __ bind(&need_incremental_pop_object);
  __ pop(regs_.object());

  __ bind(&need_incremental);

  // Fall through when we need to inform the incremental marker.
}

901
void ProfileEntryHookStub::MaybeCallEntryHookDelayed(TurboAssembler* tasm,
902
                                                     Zone* zone) {
903
  if (tasm->isolate()->function_entry_hook() != nullptr) {
904
    tasm->CallStubDelayed(new (zone) ProfileEntryHookStub(nullptr));
905 906
  }
}
907

908
void ProfileEntryHookStub::MaybeCallEntryHook(MacroAssembler* masm) {
909
  if (masm->isolate()->function_entry_hook() != nullptr) {
910
    ProfileEntryHookStub stub(masm->isolate());
911 912 913 914 915 916
    masm->CallStub(&stub);
  }
}


void ProfileEntryHookStub::Generate(MacroAssembler* masm) {
917 918 919
  // Save volatile registers.
  const int kNumSavedRegisters = 3;
  __ push(eax);
920
  __ push(ecx);
921
  __ push(edx);
922 923

  // Calculate and push the original stack pointer.
924
  __ lea(eax, Operand(esp, (kNumSavedRegisters + 1) * kPointerSize));
925 926
  __ push(eax);

927 928 929
  // Retrieve our return address and use it to calculate the calling
  // function's address.
  __ mov(eax, Operand(esp, (kNumSavedRegisters + 1) * kPointerSize));
930 931 932 933
  __ sub(eax, Immediate(Assembler::kCallInstructionLength));
  __ push(eax);

  // Call the entry hook.
934
  DCHECK_NOT_NULL(isolate()->function_entry_hook());
935
  __ call(FUNCTION_ADDR(isolate()->function_entry_hook()),
936
          RelocInfo::RUNTIME_ENTRY);
937 938 939
  __ add(esp, Immediate(2 * kPointerSize));

  // Restore ecx.
940
  __ pop(edx);
941
  __ pop(ecx);
942 943
  __ pop(eax);

944 945 946
  __ ret(0);
}

947 948

template<class T>
949 950 951
static void CreateArrayDispatch(MacroAssembler* masm,
                                AllocationSiteOverrideMode mode) {
  if (mode == DISABLE_ALLOCATION_SITES) {
952 953
    T stub(masm->isolate(),
           GetInitialFastElementsKind(),
954
           mode);
955
    __ TailCallStub(&stub);
956
  } else if (mode == DONT_OVERRIDE) {
957 958
    int last_index =
        GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
959 960 961 962 963
    for (int i = 0; i <= last_index; ++i) {
      Label next;
      ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
      __ cmp(edx, kind);
      __ j(not_equal, &next);
964
      T stub(masm->isolate(), kind);
965 966 967
      __ TailCallStub(&stub);
      __ bind(&next);
    }
968

969 970 971 972 973
    // If we reached this point there is a problem.
    __ Abort(kUnexpectedElementsKindInArrayConstructor);
  } else {
    UNREACHABLE();
  }
974 975 976
}


977 978
static void CreateArrayDispatchOneArgument(MacroAssembler* masm,
                                           AllocationSiteOverrideMode mode) {
979
  // ebx - allocation site (if mode != DISABLE_ALLOCATION_SITES)
980
  // edx - kind (if mode != DISABLE_ALLOCATION_SITES)
981 982 983 984
  // eax - number of arguments
  // edi - constructor?
  // esp[0] - return address
  // esp[4] - last argument
985 986 987 988 989 990
  STATIC_ASSERT(PACKED_SMI_ELEMENTS == 0);
  STATIC_ASSERT(HOLEY_SMI_ELEMENTS == 1);
  STATIC_ASSERT(PACKED_ELEMENTS == 2);
  STATIC_ASSERT(HOLEY_ELEMENTS == 3);
  STATIC_ASSERT(PACKED_DOUBLE_ELEMENTS == 4);
  STATIC_ASSERT(HOLEY_DOUBLE_ELEMENTS == 5);
991

992 993 994
  if (mode == DISABLE_ALLOCATION_SITES) {
    ElementsKind initial = GetInitialFastElementsKind();
    ElementsKind holey_initial = GetHoleyElementsKind(initial);
995

996 997
    ArraySingleArgumentConstructorStub stub_holey(masm->isolate(),
                                                  holey_initial,
998 999 1000
                                                  DISABLE_ALLOCATION_SITES);
    __ TailCallStub(&stub_holey);
  } else if (mode == DONT_OVERRIDE) {
1001 1002 1003 1004 1005
    // is the low bit set? If so, we are holey and that is good.
    Label normal_sequence;
    __ test_b(edx, Immediate(1));
    __ j(not_zero, &normal_sequence);

1006 1007 1008
    // We are going to create a holey array, but our kind is non-holey.
    // Fix kind and retry.
    __ inc(edx);
1009

1010
    if (FLAG_debug_code) {
1011 1012
      Handle<Map> allocation_site_map =
          masm->isolate()->factory()->allocation_site_map();
1013 1014
      __ cmp(FieldOperand(ebx, 0), Immediate(allocation_site_map));
      __ Assert(equal, kExpectedAllocationSite);
1015
    }
1016

1017 1018 1019 1020
    // Save the resulting elements kind in type info. We can't just store r3
    // in the AllocationSite::transition_info field because elements kind is
    // restricted to a portion of the field...upper bits need to be left alone.
    STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
1021 1022 1023
    __ add(
        FieldOperand(ebx, AllocationSite::kTransitionInfoOrBoilerplateOffset),
        Immediate(Smi::FromInt(kFastElementsKindPackedToHoley)));
1024 1025

    __ bind(&normal_sequence);
1026 1027
    int last_index =
        GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
1028 1029 1030 1031 1032
    for (int i = 0; i <= last_index; ++i) {
      Label next;
      ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
      __ cmp(edx, kind);
      __ j(not_equal, &next);
1033
      ArraySingleArgumentConstructorStub stub(masm->isolate(), kind);
1034 1035 1036 1037 1038 1039 1040 1041 1042
      __ TailCallStub(&stub);
      __ bind(&next);
    }

    // If we reached this point there is a problem.
    __ Abort(kUnexpectedElementsKindInArrayConstructor);
  } else {
    UNREACHABLE();
  }
1043 1044 1045 1046 1047
}


template<class T>
static void ArrayConstructorStubAheadOfTimeHelper(Isolate* isolate) {
1048 1049
  int to_index =
      GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND);
1050 1051
  for (int i = 0; i <= to_index; ++i) {
    ElementsKind kind = GetFastElementsKindFromSequenceIndex(i);
1052
    T stub(isolate, kind);
1053
    stub.GetCode();
1054
    if (AllocationSite::ShouldTrack(kind)) {
1055
      T stub1(isolate, kind, DISABLE_ALLOCATION_SITES);
1056
      stub1.GetCode();
1057
    }
1058 1059 1060
  }
}

1061
void CommonArrayConstructorStub::GenerateStubsAheadOfTime(Isolate* isolate) {
1062 1063 1064 1065
  ArrayConstructorStubAheadOfTimeHelper<ArrayNoArgumentConstructorStub>(
      isolate);
  ArrayConstructorStubAheadOfTimeHelper<ArraySingleArgumentConstructorStub>(
      isolate);
1066 1067
  ArrayNArgumentsConstructorStub stub(isolate);
  stub.GetCode();
1068

1069
  ElementsKind kinds[2] = {PACKED_ELEMENTS, HOLEY_ELEMENTS};
1070 1071
  for (int i = 0; i < 2; i++) {
    // For internal arrays we only need a few things
1072
    InternalArrayNoArgumentConstructorStub stubh1(isolate, kinds[i]);
1073
    stubh1.GetCode();
1074
    InternalArraySingleArgumentConstructorStub stubh2(isolate, kinds[i]);
1075
    stubh2.GetCode();
1076 1077 1078
  }
}

1079
void ArrayConstructorStub::GenerateDispatchToArrayStub(
1080 1081 1082 1083 1084
    MacroAssembler* masm, AllocationSiteOverrideMode mode) {
  Label not_zero_case, not_one_case;
  __ test(eax, eax);
  __ j(not_zero, &not_zero_case);
  CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode);
1085

1086 1087 1088 1089 1090 1091 1092 1093 1094
  __ bind(&not_zero_case);
  __ cmp(eax, 1);
  __ j(greater, &not_one_case);
  CreateArrayDispatchOneArgument(masm, mode);

  __ bind(&not_one_case);
  ArrayNArgumentsConstructorStub stub(masm->isolate());
  __ TailCallStub(&stub);
}
1095

1096 1097
void ArrayConstructorStub::Generate(MacroAssembler* masm) {
  // ----------- S t a t e -------------
dslomov's avatar
dslomov committed
1098
  //  -- eax : argc (only if argument_count() is ANY or MORE_THAN_ONE)
1099
  //  -- ebx : AllocationSite or undefined
1100
  //  -- edi : constructor
dslomov's avatar
dslomov committed
1101
  //  -- edx : Original constructor
1102 1103 1104 1105 1106 1107 1108 1109 1110
  //  -- esp[0] : return address
  //  -- esp[4] : last argument
  // -----------------------------------
  if (FLAG_debug_code) {
    // The array construct code is only set for the global and natives
    // builtin Array functions which always have maps.

    // Initial map for the builtin Array function should be a map.
    __ mov(ecx, FieldOperand(edi, JSFunction::kPrototypeOrInitialMapOffset));
1111
    // Will both indicate a nullptr and a Smi.
1112
    __ test(ecx, Immediate(kSmiTagMask));
1113
    __ Assert(not_zero, kUnexpectedInitialMapForArrayFunction);
1114
    __ CmpObjectType(ecx, MAP_TYPE, ecx);
1115
    __ Assert(equal, kUnexpectedInitialMapForArrayFunction);
1116

1117 1118
    // We should either have undefined in ebx or a valid AllocationSite
    __ AssertUndefinedOrAllocationSite(ebx);
1119 1120
  }

dslomov's avatar
dslomov committed
1121 1122
  Label subclassing;

1123 1124 1125
  // Enter the context of the Array function.
  __ mov(esi, FieldOperand(edi, JSFunction::kContextOffset));

dslomov's avatar
dslomov committed
1126 1127 1128
  __ cmp(edx, edi);
  __ j(not_equal, &subclassing);

1129
  Label no_info;
1130 1131
  // If the feedback vector is the undefined value call an array constructor
  // that doesn't use AllocationSites.
1132
  __ cmp(ebx, isolate()->factory()->undefined_value());
1133
  __ j(equal, &no_info);
1134

1135
  // Only look at the lower 16 bits of the transition info.
1136 1137
  __ mov(edx,
         FieldOperand(ebx, AllocationSite::kTransitionInfoOrBoilerplateOffset));
1138
  __ SmiUntag(edx);
1139 1140
  STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0);
  __ and_(edx, Immediate(AllocationSite::ElementsKindBits::kMask));
1141
  GenerateDispatchToArrayStub(masm, DONT_OVERRIDE);
1142

1143 1144
  __ bind(&no_info);
  GenerateDispatchToArrayStub(masm, DISABLE_ALLOCATION_SITES);
dslomov's avatar
dslomov committed
1145

dslomov's avatar
dslomov committed
1146
  // Subclassing.
dslomov's avatar
dslomov committed
1147
  __ bind(&subclassing);
1148 1149
  __ mov(Operand(esp, eax, times_pointer_size, kPointerSize), edi);
  __ add(eax, Immediate(3));
1150 1151 1152 1153 1154
  __ PopReturnAddressTo(ecx);
  __ Push(edx);
  __ Push(ebx);
  __ PushReturnAddressFrom(ecx);
  __ JumpToExternalReference(ExternalReference(Runtime::kNewArray, isolate()));
1155 1156 1157
}


1158 1159 1160 1161 1162 1163 1164
void InternalArrayConstructorStub::GenerateCase(
    MacroAssembler* masm, ElementsKind kind) {
  Label not_zero_case, not_one_case;
  Label normal_sequence;

  __ test(eax, eax);
  __ j(not_zero, &not_zero_case);
1165
  InternalArrayNoArgumentConstructorStub stub0(isolate(), kind);
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
  __ TailCallStub(&stub0);

  __ bind(&not_zero_case);
  __ cmp(eax, 1);
  __ j(greater, &not_one_case);

  if (IsFastPackedElementsKind(kind)) {
    // We might need to create a holey array
    // look at the first argument
    __ mov(ecx, Operand(esp, kPointerSize));
    __ test(ecx, ecx);
    __ j(zero, &normal_sequence);

    InternalArraySingleArgumentConstructorStub
1180
        stub1_holey(isolate(), GetHoleyElementsKind(kind));
1181 1182 1183 1184
    __ TailCallStub(&stub1_holey);
  }

  __ bind(&normal_sequence);
1185
  InternalArraySingleArgumentConstructorStub stub1(isolate(), kind);
1186 1187 1188
  __ TailCallStub(&stub1);

  __ bind(&not_one_case);
1189
  ArrayNArgumentsConstructorStub stubN(isolate());
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
  __ TailCallStub(&stubN);
}


void InternalArrayConstructorStub::Generate(MacroAssembler* masm) {
  // ----------- S t a t e -------------
  //  -- eax : argc
  //  -- edi : constructor
  //  -- esp[0] : return address
  //  -- esp[4] : last argument
  // -----------------------------------

  if (FLAG_debug_code) {
    // The array construct code is only set for the global and natives
    // builtin Array functions which always have maps.

    // Initial map for the builtin Array function should be a map.
    __ mov(ecx, FieldOperand(edi, JSFunction::kPrototypeOrInitialMapOffset));
1208
    // Will both indicate a nullptr and a Smi.
1209
    __ test(ecx, Immediate(kSmiTagMask));
1210
    __ Assert(not_zero, kUnexpectedInitialMapForArrayFunction);
1211
    __ CmpObjectType(ecx, MAP_TYPE, ecx);
1212
    __ Assert(equal, kUnexpectedInitialMapForArrayFunction);
1213 1214
  }

1215 1216
  // Figure out the right elements kind
  __ mov(ecx, FieldOperand(edi, JSFunction::kPrototypeOrInitialMapOffset));
1217

1218 1219 1220 1221
  // Load the map's "bit field 2" into |result|. We only need the first byte,
  // but the following masking takes care of that anyway.
  __ mov(ecx, FieldOperand(ecx, Map::kBitField2Offset));
  // Retrieve elements_kind from bit field 2.
1222
  __ DecodeField<Map::ElementsKindBits>(ecx);
1223

1224 1225
  if (FLAG_debug_code) {
    Label done;
1226
    __ cmp(ecx, Immediate(PACKED_ELEMENTS));
1227
    __ j(equal, &done);
1228
    __ cmp(ecx, Immediate(HOLEY_ELEMENTS));
1229
    __ Assert(equal,
1230
              kInvalidElementsKindForInternalArrayOrInternalPackedArray);
1231 1232
    __ bind(&done);
  }
1233

1234
  Label fast_elements_case;
1235
  __ cmp(ecx, Immediate(PACKED_ELEMENTS));
1236
  __ j(equal, &fast_elements_case);
1237
  GenerateCase(masm, HOLEY_ELEMENTS);
1238

1239
  __ bind(&fast_elements_case);
1240
  GenerateCase(masm, PACKED_ELEMENTS);
1241 1242
}

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
// Generates an Operand for saving parameters after PrepareCallApiFunction.
static Operand ApiParameterOperand(int index) {
  return Operand(esp, index * kPointerSize);
}


// Prepares stack to put arguments (aligns and so on). Reserves
// space for return value if needed (assumes the return value is a handle).
// Arguments must be stored in ApiParameterOperand(0), ApiParameterOperand(1)
// etc. Saves context (esi). If space was reserved for return value then
// stores the pointer to the reserved slot into esi.
static void PrepareCallApiFunction(MacroAssembler* masm, int argc) {
  __ EnterApiExitFrame(argc);
  if (__ emit_debug_code()) {
    __ mov(esi, Immediate(bit_cast<int32_t>(kZapValue)));
  }
}


// Calls an API function.  Allocates HandleScope, extracts returned value
// from handle and propagates exceptions.  Clobbers ebx, edi and
// caller-save registers.  Restores context.  On return removes
// stack_space * kPointerSize (GCed).
static void CallApiFunctionAndReturn(MacroAssembler* masm,
                                     Register function_address,
                                     ExternalReference thunk_ref,
                                     Operand thunk_last_arg, int stack_space,
                                     Operand* stack_space_operand,
1271
                                     Operand return_value_operand) {
1272 1273 1274 1275 1276 1277 1278 1279 1280
  Isolate* isolate = masm->isolate();

  ExternalReference next_address =
      ExternalReference::handle_scope_next_address(isolate);
  ExternalReference limit_address =
      ExternalReference::handle_scope_limit_address(isolate);
  ExternalReference level_address =
      ExternalReference::handle_scope_level_address(isolate);

1281
  DCHECK(edx == function_address);
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
  // Allocate HandleScope in callee-save registers.
  __ mov(ebx, Operand::StaticVariable(next_address));
  __ mov(edi, Operand::StaticVariable(limit_address));
  __ add(Operand::StaticVariable(level_address), Immediate(1));

  if (FLAG_log_timer_events) {
    FrameScope frame(masm, StackFrame::MANUAL);
    __ PushSafepointRegisters();
    __ PrepareCallCFunction(1, eax);
    __ mov(Operand(esp, 0),
           Immediate(ExternalReference::isolate_address(isolate)));
    __ CallCFunction(ExternalReference::log_enter_external_function(isolate),
                     1);
    __ PopSafepointRegisters();
  }


  Label profiler_disabled;
  Label end_profiler_check;
  __ mov(eax, Immediate(ExternalReference::is_profiling_address(isolate)));
1302
  __ cmpb(Operand(eax, 0), Immediate(0));
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
  __ j(zero, &profiler_disabled);

  // Additional parameter is the address of the actual getter function.
  __ mov(thunk_last_arg, function_address);
  // Call the api function.
  __ mov(eax, Immediate(thunk_ref));
  __ call(eax);
  __ jmp(&end_profiler_check);

  __ bind(&profiler_disabled);
  // Call the api function.
  __ call(function_address);
  __ bind(&end_profiler_check);

  if (FLAG_log_timer_events) {
    FrameScope frame(masm, StackFrame::MANUAL);
    __ PushSafepointRegisters();
    __ PrepareCallCFunction(1, eax);
    __ mov(Operand(esp, 0),
           Immediate(ExternalReference::isolate_address(isolate)));
    __ CallCFunction(ExternalReference::log_leave_external_function(isolate),
                     1);
    __ PopSafepointRegisters();
  }

  Label prologue;
  // Load the value from ReturnValue
  __ mov(eax, return_value_operand);

  Label promote_scheduled_exception;
  Label delete_allocated_handles;
  Label leave_exit_frame;

  __ bind(&prologue);
  // No more valid handles (the result handle was the last one). Restore
  // previous handle scope.
  __ mov(Operand::StaticVariable(next_address), ebx);
  __ sub(Operand::StaticVariable(level_address), Immediate(1));
  __ Assert(above_equal, kInvalidHandleScopeLevel);
  __ cmp(edi, Operand::StaticVariable(limit_address));
  __ j(not_equal, &delete_allocated_handles);
1344 1345

  // Leave the API exit frame.
1346
  __ bind(&leave_exit_frame);
1347 1348 1349
  if (stack_space_operand != nullptr) {
    __ mov(ebx, *stack_space_operand);
  }
1350
  __ LeaveApiExitFrame();
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370

  // Check if the function scheduled an exception.
  ExternalReference scheduled_exception_address =
      ExternalReference::scheduled_exception_address(isolate);
  __ cmp(Operand::StaticVariable(scheduled_exception_address),
         Immediate(isolate->factory()->the_hole_value()));
  __ j(not_equal, &promote_scheduled_exception);

#if DEBUG
  // Check if the function returned a valid JavaScript value.
  Label ok;
  Register return_value = eax;
  Register map = ecx;

  __ JumpIfSmi(return_value, &ok, Label::kNear);
  __ mov(map, FieldOperand(return_value, HeapObject::kMapOffset));

  __ CmpInstanceType(map, LAST_NAME_TYPE);
  __ j(below_equal, &ok, Label::kNear);

1371
  __ CmpInstanceType(map, FIRST_JS_RECEIVER_TYPE);
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
  __ j(above_equal, &ok, Label::kNear);

  __ cmp(map, isolate->factory()->heap_number_map());
  __ j(equal, &ok, Label::kNear);

  __ cmp(return_value, isolate->factory()->undefined_value());
  __ j(equal, &ok, Label::kNear);

  __ cmp(return_value, isolate->factory()->true_value());
  __ j(equal, &ok, Label::kNear);

  __ cmp(return_value, isolate->factory()->false_value());
  __ j(equal, &ok, Label::kNear);

  __ cmp(return_value, isolate->factory()->null_value());
  __ j(equal, &ok, Label::kNear);

  __ Abort(kAPICallReturnedInvalidObject);

  __ bind(&ok);
#endif

  if (stack_space_operand != nullptr) {
    DCHECK_EQ(0, stack_space);
    __ pop(ecx);
    __ add(esp, ebx);
    __ jmp(ecx);
  } else {
    __ ret(stack_space * kPointerSize);
  }

1403
  // Re-throw by promoting a scheduled exception.
1404
  __ bind(&promote_scheduled_exception);
1405
  __ TailCallRuntime(Runtime::kPromoteScheduledException);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420

  // HandleScope limit has changed. Delete allocated extensions.
  ExternalReference delete_extensions =
      ExternalReference::delete_handle_scope_extensions(isolate);
  __ bind(&delete_allocated_handles);
  __ mov(Operand::StaticVariable(limit_address), edi);
  __ mov(edi, eax);
  __ mov(Operand(esp, 0),
         Immediate(ExternalReference::isolate_address(isolate)));
  __ mov(eax, Immediate(delete_extensions));
  __ call(eax);
  __ mov(eax, edi);
  __ jmp(&leave_exit_frame);
}

vogelheim's avatar
vogelheim committed
1421
void CallApiCallbackStub::Generate(MacroAssembler* masm) {
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
  // ----------- S t a t e -------------
  //  -- ebx                 : call_data
  //  -- ecx                 : holder
  //  -- edx                 : api_function_address
  //  -- esi                 : context
  //  --
  //  -- esp[0]              : return address
  //  -- esp[4]              : last argument
  //  -- ...
  //  -- esp[argc * 4]       : first argument
  //  -- esp[(argc + 1) * 4] : receiver
  // -----------------------------------

  Register call_data = ebx;
  Register holder = ecx;
  Register api_function_address = edx;
1438
  Register return_address = eax;
1439 1440 1441

  typedef FunctionCallbackArguments FCA;

1442 1443
  STATIC_ASSERT(FCA::kArgsLength == 6);
  STATIC_ASSERT(FCA::kNewTargetIndex == 5);
1444 1445 1446 1447 1448 1449
  STATIC_ASSERT(FCA::kDataIndex == 4);
  STATIC_ASSERT(FCA::kReturnValueOffset == 3);
  STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2);
  STATIC_ASSERT(FCA::kIsolateIndex == 1);
  STATIC_ASSERT(FCA::kHolderIndex == 0);

vogelheim's avatar
vogelheim committed
1450
  __ pop(return_address);
1451 1452 1453 1454

  // new target
  __ PushRoot(Heap::kUndefinedValueRootIndex);

1455 1456 1457
  // call data
  __ push(call_data);

1458
  // return value
1459
  __ PushRoot(Heap::kUndefinedValueRootIndex);
1460
  // return value default
1461
  __ PushRoot(Heap::kUndefinedValueRootIndex);
1462
  // isolate
1463
  __ push(Immediate(reinterpret_cast<int>(masm->isolate())));
1464 1465 1466
  // holder
  __ push(holder);

1467
  Register scratch = call_data;
1468

1469 1470
  __ mov(scratch, esp);

1471
  // push return address
1472
  __ push(return_address);
1473

1474 1475 1476 1477 1478 1479 1480 1481
  // API function gets reference to the v8::Arguments. If CPU profiler
  // is enabled wrapper function will be called and we need to pass
  // address of the callback as additional parameter, always allocate
  // space for it.
  const int kApiArgc = 1 + 1;

  // Allocate the v8::Arguments structure in the arguments' space since
  // it's not controlled by GC.
1482
  const int kApiStackSpace = 3;
1483

1484
  PrepareCallApiFunction(masm, kApiArgc + kApiStackSpace);
1485 1486 1487

  // FunctionCallbackInfo::implicit_args_.
  __ mov(ApiParameterOperand(2), scratch);
vogelheim's avatar
vogelheim committed
1488 1489 1490 1491 1492
  __ add(scratch, Immediate((argc() + FCA::kArgsLength - 1) * kPointerSize));
  // FunctionCallbackInfo::values_.
  __ mov(ApiParameterOperand(3), scratch);
  // FunctionCallbackInfo::length_.
  __ Move(ApiParameterOperand(4), Immediate(argc()));
1493 1494 1495 1496 1497

  // v8::InvocationCallback's argument.
  __ lea(scratch, ApiParameterOperand(2));
  __ mov(ApiParameterOperand(0), scratch);

1498
  ExternalReference thunk_ref =
1499
      ExternalReference::invoke_function_callback(masm->isolate());
1500

1501
  // Stores return the first js argument
1502
  int return_value_offset = 0;
vogelheim's avatar
vogelheim committed
1503
  if (is_store()) {
1504 1505 1506 1507
    return_value_offset = 2 + FCA::kArgsLength;
  } else {
    return_value_offset = 2 + FCA::kReturnValueOffset;
  }
1508
  Operand return_value_operand(ebp, return_value_offset * kPointerSize);
1509
  const int stack_space = argc() + FCA::kArgsLength + 1;
1510
  Operand* stack_space_operand = nullptr;
1511 1512
  CallApiFunctionAndReturn(masm, api_function_address, thunk_ref,
                           ApiParameterOperand(1), stack_space,
1513
                           stack_space_operand, return_value_operand);
1514 1515 1516
}


dcarney@chromium.org's avatar
dcarney@chromium.org committed
1517
void CallApiGetterStub::Generate(MacroAssembler* masm) {
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
  // Build v8::PropertyCallbackInfo::args_ array on the stack and push property
  // name below the exit frame to make GC aware of them.
  STATIC_ASSERT(PropertyCallbackArguments::kShouldThrowOnErrorIndex == 0);
  STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 1);
  STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 2);
  STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 3);
  STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 4);
  STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 5);
  STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 6);
  STATIC_ASSERT(PropertyCallbackArguments::kArgsLength == 7);

  Register receiver = ApiGetterDescriptor::ReceiverRegister();
  Register holder = ApiGetterDescriptor::HolderRegister();
  Register callback = ApiGetterDescriptor::CallbackRegister();
  Register scratch = ebx;
  DCHECK(!AreAliased(receiver, holder, callback, scratch));

  __ pop(scratch);  // Pop return address to extend the frame.
  __ push(receiver);
  __ push(FieldOperand(callback, AccessorInfo::kDataOffset));
  __ PushRoot(Heap::kUndefinedValueRootIndex);  // ReturnValue
  // ReturnValue default value
  __ PushRoot(Heap::kUndefinedValueRootIndex);
  __ push(Immediate(ExternalReference::isolate_address(isolate())));
  __ push(holder);
1543
  __ push(Immediate(Smi::kZero));  // should_throw_on_error -> false
1544 1545
  __ push(FieldOperand(callback, AccessorInfo::kNameOffset));
  __ push(scratch);  // Restore return address.
dcarney@chromium.org's avatar
dcarney@chromium.org committed
1546

1547 1548 1549 1550 1551 1552 1553
  // v8::PropertyCallbackInfo::args_ array and name handle.
  const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1;

  // Allocate v8::PropertyCallbackInfo object, arguments for callback and
  // space for optional callback address parameter (in case CPU profiler is
  // active) in non-GCed stack space.
  const int kApiArgc = 3 + 1;
dcarney@chromium.org's avatar
dcarney@chromium.org committed
1554

1555 1556
  // Load address of v8::PropertyAccessorInfo::args_ array.
  __ lea(scratch, Operand(esp, 2 * kPointerSize));
dcarney@chromium.org's avatar
dcarney@chromium.org committed
1557

1558
  PrepareCallApiFunction(masm, kApiArgc);
1559 1560 1561 1562 1563
  // Create v8::PropertyCallbackInfo object on the stack and initialize
  // it's args_ field.
  Operand info_object = ApiParameterOperand(3);
  __ mov(info_object, scratch);

1564
  // Name as handle.
1565
  __ sub(scratch, Immediate(kPointerSize));
1566 1567
  __ mov(ApiParameterOperand(0), scratch);
  // Arguments pointer.
1568
  __ lea(scratch, info_object);
1569
  __ mov(ApiParameterOperand(1), scratch);
1570 1571
  // Reserve space for optional callback address parameter.
  Operand thunk_last_arg = ApiParameterOperand(2);
dcarney@chromium.org's avatar
dcarney@chromium.org committed
1572

1573 1574
  ExternalReference thunk_ref =
      ExternalReference::invoke_accessor_getter_callback(isolate());
dcarney@chromium.org's avatar
dcarney@chromium.org committed
1575

1576 1577 1578 1579
  __ mov(scratch, FieldOperand(callback, AccessorInfo::kJsGetterOffset));
  Register function_address = edx;
  __ mov(function_address,
         FieldOperand(scratch, Foreign::kForeignAddressOffset));
1580 1581 1582
  // +3 is to skip prolog, return address and name handle.
  Operand return_value_operand(
      ebp, (PropertyCallbackArguments::kReturnValueOffset + 3) * kPointerSize);
1583
  CallApiFunctionAndReturn(masm, function_address, thunk_ref, thunk_last_arg,
1584
                           kStackUnwindSpace, nullptr, return_value_operand);
dcarney@chromium.org's avatar
dcarney@chromium.org committed
1585 1586
}

1587 1588
#undef __

1589 1590
}  // namespace internal
}  // namespace v8
1591 1592

#endif  // V8_TARGET_ARCH_IA32