macro-assembler-x87.cc 81.5 KB
Newer Older
danno@chromium.org's avatar
danno@chromium.org committed
1 2 3 4 5 6
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if V8_TARGET_ARCH_X87

7
#include "src/base/bits.h"
8
#include "src/base/division-by-constant.h"
9 10
#include "src/bootstrapper.h"
#include "src/codegen.h"
11
#include "src/debug/debug.h"
12
#include "src/runtime/runtime.h"
13
#include "src/x87/frames-x87.h"
14
#include "src/x87/macro-assembler-x87.h"
danno@chromium.org's avatar
danno@chromium.org committed
15 16 17 18 19 20 21

namespace v8 {
namespace internal {

// -------------------------------------------------------------------------
// MacroAssembler implementation.

22
MacroAssembler::MacroAssembler(Isolate* isolate, void* buffer, int size,
23
                               CodeObjectRequired create_code_object)
danno@chromium.org's avatar
danno@chromium.org committed
24 25
    : Assembler(arg_isolate, buffer, size),
      generating_stub_(false),
26 27
      has_frame_(false),
      isolate_(isolate) {
28
  if (create_code_object == CodeObjectRequired::kYes) {
29
    code_object_ =
30
        Handle<Object>::New(isolate_->heap()->undefined_value(), isolate_);
danno@chromium.org's avatar
danno@chromium.org committed
31 32 33 34 35
  }
}


void MacroAssembler::Load(Register dst, const Operand& src, Representation r) {
36
  DCHECK(!r.IsDouble());
danno@chromium.org's avatar
danno@chromium.org committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
  if (r.IsInteger8()) {
    movsx_b(dst, src);
  } else if (r.IsUInteger8()) {
    movzx_b(dst, src);
  } else if (r.IsInteger16()) {
    movsx_w(dst, src);
  } else if (r.IsUInteger16()) {
    movzx_w(dst, src);
  } else {
    mov(dst, src);
  }
}


void MacroAssembler::Store(Register src, const Operand& dst, Representation r) {
52
  DCHECK(!r.IsDouble());
danno@chromium.org's avatar
danno@chromium.org committed
53 54 55 56 57
  if (r.IsInteger8() || r.IsUInteger8()) {
    mov_b(dst, src);
  } else if (r.IsInteger16() || r.IsUInteger16()) {
    mov_w(dst, src);
  } else {
58 59 60 61 62
    if (r.IsHeapObject()) {
      AssertNotSmi(src);
    } else if (r.IsSmi()) {
      AssertSmi(src);
    }
danno@chromium.org's avatar
danno@chromium.org committed
63 64 65 66 67 68 69
    mov(dst, src);
  }
}


void MacroAssembler::LoadRoot(Register destination, Heap::RootListIndex index) {
  if (isolate()->heap()->RootCanBeTreatedAsConstant(index)) {
70
    mov(destination, isolate()->heap()->root_handle(index));
danno@chromium.org's avatar
danno@chromium.org committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84
    return;
  }
  ExternalReference roots_array_start =
      ExternalReference::roots_array_start(isolate());
  mov(destination, Immediate(index));
  mov(destination, Operand::StaticArray(destination,
                                        times_pointer_size,
                                        roots_array_start));
}


void MacroAssembler::StoreRoot(Register source,
                               Register scratch,
                               Heap::RootListIndex index) {
85
  DCHECK(Heap::RootCanBeWrittenAfterInitialization(index));
danno@chromium.org's avatar
danno@chromium.org committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  ExternalReference roots_array_start =
      ExternalReference::roots_array_start(isolate());
  mov(scratch, Immediate(index));
  mov(Operand::StaticArray(scratch, times_pointer_size, roots_array_start),
      source);
}


void MacroAssembler::CompareRoot(Register with,
                                 Register scratch,
                                 Heap::RootListIndex index) {
  ExternalReference roots_array_start =
      ExternalReference::roots_array_start(isolate());
  mov(scratch, Immediate(index));
  cmp(with, Operand::StaticArray(scratch,
                                times_pointer_size,
                                roots_array_start));
}


void MacroAssembler::CompareRoot(Register with, Heap::RootListIndex index) {
107
  DCHECK(isolate()->heap()->RootCanBeTreatedAsConstant(index));
108
  cmp(with, isolate()->heap()->root_handle(index));
danno@chromium.org's avatar
danno@chromium.org committed
109 110 111 112 113
}


void MacroAssembler::CompareRoot(const Operand& with,
                                 Heap::RootListIndex index) {
114
  DCHECK(isolate()->heap()->RootCanBeTreatedAsConstant(index));
115
  cmp(with, isolate()->heap()->root_handle(index));
danno@chromium.org's avatar
danno@chromium.org committed
116 117 118
}


119 120 121 122 123
void MacroAssembler::PushRoot(Heap::RootListIndex index) {
  DCHECK(isolate()->heap()->RootCanBeTreatedAsConstant(index));
  Push(isolate()->heap()->root_handle(index));
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
#define REG(Name) \
  { Register::kCode_##Name }

static const Register saved_regs[] = {REG(eax), REG(ecx), REG(edx)};

#undef REG

static const int kNumberOfSavedRegs = sizeof(saved_regs) / sizeof(Register);

void MacroAssembler::PushCallerSaved(SaveFPRegsMode fp_mode,
                                     Register exclusion1, Register exclusion2,
                                     Register exclusion3) {
  // 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.
  for (int i = 0; i < kNumberOfSavedRegs; i++) {
    Register reg = saved_regs[i];
    if (!reg.is(exclusion1) && !reg.is(exclusion2) && !reg.is(exclusion3)) {
      push(reg);
    }
  }
  if (fp_mode == kSaveFPRegs) {
    // Save FPU state in m108byte.
    sub(esp, Immediate(108));
    fnsave(Operand(esp, 0));
  }
}

void MacroAssembler::PopCallerSaved(SaveFPRegsMode fp_mode, Register exclusion1,
                                    Register exclusion2, Register exclusion3) {
  if (fp_mode == kSaveFPRegs) {
    // Restore FPU state in m108byte.
    frstor(Operand(esp, 0));
    add(esp, Immediate(108));
  }

  for (int i = kNumberOfSavedRegs - 1; i >= 0; i--) {
    Register reg = saved_regs[i];
    if (!reg.is(exclusion1) && !reg.is(exclusion2) && !reg.is(exclusion3)) {
      pop(reg);
    }
  }
}
167

168 169 170
void MacroAssembler::InNewSpace(Register object, Register scratch, Condition cc,
                                Label* condition_met,
                                Label::Distance distance) {
mlippautz's avatar
mlippautz committed
171 172
  CheckPageFlag(object, scratch, MemoryChunk::kIsInNewSpaceMask, cc,
                condition_met, distance);
danno@chromium.org's avatar
danno@chromium.org committed
173 174 175 176 177
}


void MacroAssembler::RememberedSetHelper(
    Register object,  // Only used for debug checks.
178
    Register addr, Register scratch, SaveFPRegsMode save_fp,
danno@chromium.org's avatar
danno@chromium.org committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    MacroAssembler::RememberedSetFinalAction and_then) {
  Label done;
  if (emit_debug_code()) {
    Label ok;
    JumpIfNotInNewSpace(object, scratch, &ok, Label::kNear);
    int3();
    bind(&ok);
  }
  // Load store buffer top.
  ExternalReference store_buffer =
      ExternalReference::store_buffer_top(isolate());
  mov(scratch, Operand::StaticVariable(store_buffer));
  // Store pointer to buffer.
  mov(Operand(scratch, 0), addr);
  // Increment buffer top.
  add(scratch, Immediate(kPointerSize));
  // Write back new top of buffer.
  mov(Operand::StaticVariable(store_buffer), scratch);
  // Call stub on end of buffer.
  // Check for end of buffer.
199
  test(scratch, Immediate(StoreBuffer::kStoreBufferMask));
danno@chromium.org's avatar
danno@chromium.org committed
200 201
  if (and_then == kReturnAtEnd) {
    Label buffer_overflowed;
202
    j(equal, &buffer_overflowed, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
203 204 205
    ret(0);
    bind(&buffer_overflowed);
  } else {
206
    DCHECK(and_then == kFallThroughAtEnd);
207
    j(not_equal, &done, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
208
  }
209
  StoreBufferOverflowStub store_buffer_overflow(isolate(), save_fp);
danno@chromium.org's avatar
danno@chromium.org committed
210 211 212 213
  CallStub(&store_buffer_overflow);
  if (and_then == kReturnAtEnd) {
    ret(0);
  } else {
214
    DCHECK(and_then == kFallThroughAtEnd);
danno@chromium.org's avatar
danno@chromium.org committed
215 216 217 218 219
    bind(&done);
  }
}


220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
void MacroAssembler::ClampTOSToUint8(Register result_reg) {
  Label done, conv_failure;
  sub(esp, Immediate(kPointerSize));
  fnclex();
  fist_s(Operand(esp, 0));
  pop(result_reg);
  X87CheckIA();
  j(equal, &conv_failure, Label::kNear);
  test(result_reg, Immediate(0xFFFFFF00));
  j(zero, &done, Label::kNear);
  setcc(sign, result_reg);
  sub(result_reg, Immediate(1));
  and_(result_reg, Immediate(255));
  jmp(&done, Label::kNear);
  bind(&conv_failure);
  fnclex();
  fldz();
  fld(1);
  FCmp();
  setcc(below, result_reg);  // 1 if negative, 0 if positive.
  dec_b(result_reg);         // 0 if negative, 255 if positive.
  bind(&done);
}


danno@chromium.org's avatar
danno@chromium.org committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
void MacroAssembler::ClampUint8(Register reg) {
  Label done;
  test(reg, Immediate(0xFFFFFF00));
  j(zero, &done, Label::kNear);
  setcc(negative, reg);  // 1 if negative, 0 if positive.
  dec_b(reg);  // 0 if negative, 255 if positive.
  bind(&done);
}


void MacroAssembler::SlowTruncateToI(Register result_reg,
                                     Register input_reg,
                                     int offset) {
  DoubleToIStub stub(isolate(), input_reg, result_reg, offset, true);
  call(stub.GetCode(), RelocInfo::CODE_TARGET);
}


void MacroAssembler::TruncateX87TOSToI(Register result_reg) {
  sub(esp, Immediate(kDoubleSize));
  fst_d(MemOperand(esp, 0));
  SlowTruncateToI(result_reg, esp, 0);
  add(esp, Immediate(kDoubleSize));
}


void MacroAssembler::X87TOSToI(Register result_reg,
                               MinusZeroMode minus_zero_mode,
273 274
                               Label* lost_precision, Label* is_nan,
                               Label* minus_zero, Label::Distance dst) {
danno@chromium.org's avatar
danno@chromium.org committed
275 276 277 278 279 280 281
  Label done;
  sub(esp, Immediate(kPointerSize));
  fld(0);
  fist_s(MemOperand(esp, 0));
  fild_s(MemOperand(esp, 0));
  pop(result_reg);
  FCmp();
282 283
  j(not_equal, lost_precision, dst);
  j(parity_even, is_nan, dst);
danno@chromium.org's avatar
danno@chromium.org committed
284 285 286 287 288 289 290 291 292
  if (minus_zero_mode == FAIL_ON_MINUS_ZERO) {
    test(result_reg, Operand(result_reg));
    j(not_zero, &done, Label::kNear);
    // To check for minus zero, we load the value again as float, and check
    // if that is still 0.
    sub(esp, Immediate(kPointerSize));
    fst_s(MemOperand(esp, 0));
    pop(result_reg);
    test(result_reg, Operand(result_reg));
293
    j(not_zero, minus_zero, dst);
danno@chromium.org's avatar
danno@chromium.org committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307
  }
  bind(&done);
}


void MacroAssembler::TruncateHeapNumberToI(Register result_reg,
                                           Register input_reg) {
  Label done, slow_case;

  SlowTruncateToI(result_reg, input_reg);
  bind(&done);
}


308
void MacroAssembler::LoadUint32NoSSE2(const Operand& src) {
danno@chromium.org's avatar
danno@chromium.org committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
  Label done;
  push(src);
  fild_s(Operand(esp, 0));
  cmp(src, Immediate(0));
  j(not_sign, &done, Label::kNear);
  ExternalReference uint32_bias =
        ExternalReference::address_of_uint32_bias();
  fld_d(Operand::StaticVariable(uint32_bias));
  faddp(1);
  bind(&done);
  add(esp, Immediate(kPointerSize));
}


void MacroAssembler::RecordWriteField(
324 325 326
    Register object, int offset, Register value, Register dst,
    SaveFPRegsMode save_fp, RememberedSetAction remembered_set_action,
    SmiCheck smi_check, PointersToHereCheck pointers_to_here_check_for_value) {
danno@chromium.org's avatar
danno@chromium.org committed
327 328 329 330 331 332 333 334 335 336 337
  // First, check if a write barrier is even needed. The tests below
  // catch stores of Smis.
  Label done;

  // Skip barrier if writing a smi.
  if (smi_check == INLINE_SMI_CHECK) {
    JumpIfSmi(value, &done, Label::kNear);
  }

  // Although the object register is tagged, the offset is relative to the start
  // of the object, so so offset must be a multiple of kPointerSize.
338
  DCHECK(IsAligned(offset, kPointerSize));
danno@chromium.org's avatar
danno@chromium.org committed
339 340 341 342

  lea(dst, FieldOperand(object, offset));
  if (emit_debug_code()) {
    Label ok;
343
    test_b(dst, Immediate((1 << kPointerSizeLog2) - 1));
danno@chromium.org's avatar
danno@chromium.org committed
344 345 346 347 348
    j(zero, &ok, Label::kNear);
    int3();
    bind(&ok);
  }

349 350
  RecordWrite(object, dst, value, save_fp, remembered_set_action,
              OMIT_SMI_CHECK, pointers_to_here_check_for_value);
danno@chromium.org's avatar
danno@chromium.org committed
351 352 353 354 355 356

  bind(&done);

  // Clobber clobbered input registers when running with the debug-code flag
  // turned on to provoke errors.
  if (emit_debug_code()) {
357 358
    mov(value, Immediate(bit_cast<int32_t>(kZapValue)));
    mov(dst, Immediate(bit_cast<int32_t>(kZapValue)));
danno@chromium.org's avatar
danno@chromium.org committed
359 360 361 362
  }
}


363 364 365
void MacroAssembler::RecordWriteForMap(Register object, Handle<Map> map,
                                       Register scratch1, Register scratch2,
                                       SaveFPRegsMode save_fp) {
danno@chromium.org's avatar
danno@chromium.org committed
366 367 368 369 370 371 372
  Label done;

  Register address = scratch1;
  Register value = scratch2;
  if (emit_debug_code()) {
    Label ok;
    lea(address, FieldOperand(object, HeapObject::kMapOffset));
373
    test_b(address, Immediate((1 << kPointerSizeLog2) - 1));
danno@chromium.org's avatar
danno@chromium.org committed
374 375 376 377 378
    j(zero, &ok, Label::kNear);
    int3();
    bind(&ok);
  }

379 380 381
  DCHECK(!object.is(value));
  DCHECK(!object.is(address));
  DCHECK(!value.is(address));
danno@chromium.org's avatar
danno@chromium.org committed
382 383 384 385 386 387
  AssertNotSmi(object);

  if (!FLAG_incremental_marking) {
    return;
  }

388 389 390
  // Compute the address.
  lea(address, FieldOperand(object, HeapObject::kMapOffset));

danno@chromium.org's avatar
danno@chromium.org committed
391 392 393 394
  // A single check of the map's pages interesting flag suffices, since it is
  // only set during incremental collection, and then it's also guaranteed that
  // the from object's page's interesting flag is also set.  This optimization
  // relies on the fact that maps can never be in new space.
395
  DCHECK(!isolate()->heap()->InNewSpace(*map));
danno@chromium.org's avatar
danno@chromium.org committed
396 397 398 399 400 401
  CheckPageFlagForMap(map,
                      MemoryChunk::kPointersToHereAreInterestingMask,
                      zero,
                      &done,
                      Label::kNear);

402 403
  RecordWriteStub stub(isolate(), object, value, address, OMIT_REMEMBERED_SET,
                       save_fp);
danno@chromium.org's avatar
danno@chromium.org committed
404 405 406 407
  CallStub(&stub);

  bind(&done);

408 409 410 411
  // Count number of write barriers in generated code.
  isolate()->counters()->write_barriers_static()->Increment();
  IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1);

danno@chromium.org's avatar
danno@chromium.org committed
412 413 414
  // Clobber clobbered input registers when running with the debug-code flag
  // turned on to provoke errors.
  if (emit_debug_code()) {
415 416 417
    mov(value, Immediate(bit_cast<int32_t>(kZapValue)));
    mov(scratch1, Immediate(bit_cast<int32_t>(kZapValue)));
    mov(scratch2, Immediate(bit_cast<int32_t>(kZapValue)));
danno@chromium.org's avatar
danno@chromium.org committed
418 419 420 421
  }
}


422
void MacroAssembler::RecordWrite(
423 424
    Register object, Register address, Register value, SaveFPRegsMode fp_mode,
    RememberedSetAction remembered_set_action, SmiCheck smi_check,
425
    PointersToHereCheck pointers_to_here_check_for_value) {
426 427 428
  DCHECK(!object.is(value));
  DCHECK(!object.is(address));
  DCHECK(!value.is(address));
danno@chromium.org's avatar
danno@chromium.org committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  AssertNotSmi(object);

  if (remembered_set_action == OMIT_REMEMBERED_SET &&
      !FLAG_incremental_marking) {
    return;
  }

  if (emit_debug_code()) {
    Label ok;
    cmp(value, Operand(address, 0));
    j(equal, &ok, Label::kNear);
    int3();
    bind(&ok);
  }

  // First, check if a write barrier is even needed. The tests below
  // catch stores of Smis and stores into young gen.
  Label done;

  if (smi_check == INLINE_SMI_CHECK) {
    // Skip barrier if writing a smi.
    JumpIfSmi(value, &done, Label::kNear);
  }

453 454 455 456 457 458 459 460
  if (pointers_to_here_check_for_value != kPointersToHereAreAlwaysInteresting) {
    CheckPageFlag(value,
                  value,  // Used as scratch.
                  MemoryChunk::kPointersToHereAreInterestingMask,
                  zero,
                  &done,
                  Label::kNear);
  }
danno@chromium.org's avatar
danno@chromium.org committed
461 462 463 464 465 466 467
  CheckPageFlag(object,
                value,  // Used as scratch.
                MemoryChunk::kPointersFromHereAreInterestingMask,
                zero,
                &done,
                Label::kNear);

468 469
  RecordWriteStub stub(isolate(), object, value, address, remembered_set_action,
                       fp_mode);
danno@chromium.org's avatar
danno@chromium.org committed
470 471 472 473
  CallStub(&stub);

  bind(&done);

474 475 476 477
  // Count number of write barriers in generated code.
  isolate()->counters()->write_barriers_static()->Increment();
  IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1);

danno@chromium.org's avatar
danno@chromium.org committed
478 479 480
  // Clobber clobbered registers when running with the debug-code flag
  // turned on to provoke errors.
  if (emit_debug_code()) {
481 482
    mov(address, Immediate(bit_cast<int32_t>(kZapValue)));
    mov(value, Immediate(bit_cast<int32_t>(kZapValue)));
danno@chromium.org's avatar
danno@chromium.org committed
483 484 485
  }
}

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
void MacroAssembler::RecordWriteCodeEntryField(Register js_function,
                                               Register code_entry,
                                               Register scratch) {
  const int offset = JSFunction::kCodeEntryOffset;

  // Since a code entry (value) is always in old space, we don't need to update
  // remembered set. If incremental marking is off, there is nothing for us to
  // do.
  if (!FLAG_incremental_marking) return;

  DCHECK(!js_function.is(code_entry));
  DCHECK(!js_function.is(scratch));
  DCHECK(!code_entry.is(scratch));
  AssertNotSmi(js_function);

  if (emit_debug_code()) {
    Label ok;
    lea(scratch, FieldOperand(js_function, offset));
    cmp(code_entry, Operand(scratch, 0));
    j(equal, &ok, Label::kNear);
    int3();
    bind(&ok);
  }

  // First, check if a write barrier is even needed. The tests below
  // catch stores of Smis and stores into young gen.
  Label done;

  CheckPageFlag(code_entry, scratch,
                MemoryChunk::kPointersToHereAreInterestingMask, zero, &done,
                Label::kNear);
  CheckPageFlag(js_function, scratch,
                MemoryChunk::kPointersFromHereAreInterestingMask, zero, &done,
                Label::kNear);

  // Save input registers.
  push(js_function);
  push(code_entry);

  const Register dst = scratch;
  lea(dst, FieldOperand(js_function, offset));

  // Save caller-saved registers.
  PushCallerSaved(kDontSaveFPRegs, js_function, code_entry);

  int argument_count = 3;
  PrepareCallCFunction(argument_count, code_entry);
  mov(Operand(esp, 0 * kPointerSize), js_function);
  mov(Operand(esp, 1 * kPointerSize), dst);  // Slot.
  mov(Operand(esp, 2 * kPointerSize),
      Immediate(ExternalReference::isolate_address(isolate())));

  {
    AllowExternalCallThatCantCauseGC scope(this);
    CallCFunction(
        ExternalReference::incremental_marking_record_write_code_entry_function(
            isolate()),
        argument_count);
  }

  // Restore caller-saved registers.
  PopCallerSaved(kDontSaveFPRegs, js_function, code_entry);

  // Restore input registers.
  pop(code_entry);
  pop(js_function);

  bind(&done);
}
danno@chromium.org's avatar
danno@chromium.org committed
555 556 557

void MacroAssembler::DebugBreak() {
  Move(eax, Immediate(0));
558 559
  mov(ebx, Immediate(ExternalReference(Runtime::kHandleDebuggerStatement,
                                       isolate())));
danno@chromium.org's avatar
danno@chromium.org committed
560
  CEntryStub ces(isolate(), 1);
561
  call(ces.GetCode(), RelocInfo::DEBUGGER_STATEMENT);
danno@chromium.org's avatar
danno@chromium.org committed
562 563
}

564
void MacroAssembler::ShlPair(Register high, Register low, uint8_t shift) {
565 566 567 568 569 570 571 572 573 574
  if (shift >= 32) {
    mov(high, low);
    shl(high, shift - 32);
    xor_(low, low);
  } else {
    shld(high, low, shift);
    shl(low, shift);
  }
}

575
void MacroAssembler::ShlPair_cl(Register high, Register low) {
576 577 578 579 580 581 582 583 584
  shld_cl(high, low);
  shl_cl(low);
  Label done;
  test(ecx, Immediate(0x20));
  j(equal, &done, Label::kNear);
  mov(high, low);
  xor_(low, low);
  bind(&done);
}
danno@chromium.org's avatar
danno@chromium.org committed
585

586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
void MacroAssembler::ShrPair(Register high, Register low, uint8_t shift) {
  if (shift >= 32) {
    mov(low, high);
    shr(low, shift - 32);
    xor_(high, high);
  } else {
    shrd(high, low, shift);
    shr(high, shift);
  }
}

void MacroAssembler::ShrPair_cl(Register high, Register low) {
  shrd_cl(low, high);
  shr_cl(high);
  Label done;
  test(ecx, Immediate(0x20));
  j(equal, &done, Label::kNear);
  mov(low, high);
  xor_(high, high);
  bind(&done);
}

void MacroAssembler::SarPair(Register high, Register low, uint8_t shift) {
  if (shift >= 32) {
    mov(low, high);
    sar(low, shift - 32);
    sar(high, 31);
  } else {
    shrd(high, low, shift);
    sar(high, shift);
  }
}

void MacroAssembler::SarPair_cl(Register high, Register low) {
  shrd_cl(low, high);
  sar_cl(high);
  Label done;
  test(ecx, Immediate(0x20));
  j(equal, &done, Label::kNear);
  mov(low, high);
  sar(high, 31);
  bind(&done);
}

danno@chromium.org's avatar
danno@chromium.org committed
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
bool MacroAssembler::IsUnsafeImmediate(const Immediate& x) {
  static const int kMaxImmediateBits = 17;
  if (!RelocInfo::IsNone(x.rmode_)) return false;
  return !is_intn(x.x_, kMaxImmediateBits);
}


void MacroAssembler::SafeMove(Register dst, const Immediate& x) {
  if (IsUnsafeImmediate(x) && jit_cookie() != 0) {
    Move(dst, Immediate(x.x_ ^ jit_cookie()));
    xor_(dst, jit_cookie());
  } else {
    Move(dst, x);
  }
}


void MacroAssembler::SafePush(const Immediate& x) {
  if (IsUnsafeImmediate(x) && jit_cookie() != 0) {
    push(Immediate(x.x_ ^ jit_cookie()));
    xor_(Operand(esp, 0), Immediate(jit_cookie()));
  } else {
    push(x);
  }
}


void MacroAssembler::CmpObjectType(Register heap_object,
                                   InstanceType type,
                                   Register map) {
  mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
  CmpInstanceType(map, type);
}


void MacroAssembler::CmpInstanceType(Register map, InstanceType type) {
666
  cmpb(FieldOperand(map, Map::kInstanceTypeOffset), Immediate(type));
danno@chromium.org's avatar
danno@chromium.org committed
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
}

void MacroAssembler::CompareMap(Register obj, Handle<Map> map) {
  cmp(FieldOperand(obj, HeapObject::kMapOffset), map);
}


void MacroAssembler::CheckMap(Register obj,
                              Handle<Map> map,
                              Label* fail,
                              SmiCheckType smi_check_type) {
  if (smi_check_type == DO_SMI_CHECK) {
    JumpIfSmi(obj, fail);
  }

  CompareMap(obj, map);
  j(not_equal, fail);
}


Condition MacroAssembler::IsObjectStringType(Register heap_object,
                                             Register map,
                                             Register instance_type) {
  mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
  movzx_b(instance_type, FieldOperand(map, Map::kInstanceTypeOffset));
  STATIC_ASSERT(kNotStringTag != 0);
  test(instance_type, Immediate(kIsNotStringMask));
  return zero;
}


void MacroAssembler::FCmp() {
  fucompp();
  push(eax);
  fnstsw_ax();
  sahf();
  pop(eax);
}


707 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 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
void MacroAssembler::FXamMinusZero() {
  fxam();
  push(eax);
  fnstsw_ax();
  and_(eax, Immediate(0x4700));
  // For minus zero, C3 == 1 && C1 == 1.
  cmp(eax, Immediate(0x4200));
  pop(eax);
  fstp(0);
}


void MacroAssembler::FXamSign() {
  fxam();
  push(eax);
  fnstsw_ax();
  // For negative value (including -0.0), C1 == 1.
  and_(eax, Immediate(0x0200));
  pop(eax);
  fstp(0);
}


void MacroAssembler::X87CheckIA() {
  push(eax);
  fnstsw_ax();
  // For #IA, IE == 1 && SF == 0.
  and_(eax, Immediate(0x0041));
  cmp(eax, Immediate(0x0001));
  pop(eax);
}


// rc=00B, round to nearest.
// rc=01B, round down.
// rc=10B, round up.
// rc=11B, round toward zero.
void MacroAssembler::X87SetRC(int rc) {
  sub(esp, Immediate(kPointerSize));
  fnstcw(MemOperand(esp, 0));
  and_(MemOperand(esp, 0), Immediate(0xF3FF));
  or_(MemOperand(esp, 0), Immediate(rc));
  fldcw(MemOperand(esp, 0));
  add(esp, Immediate(kPointerSize));
}


754
void MacroAssembler::X87SetFPUCW(int cw) {
755
  RecordComment("-- X87SetFPUCW start --");
756 757 758
  push(Immediate(cw));
  fldcw(MemOperand(esp, 0));
  add(esp, Immediate(kPointerSize));
759
  RecordComment("-- X87SetFPUCW end--");
760 761 762
}


danno@chromium.org's avatar
danno@chromium.org committed
763 764 765 766 767 768 769 770
void MacroAssembler::AssertSmi(Register object) {
  if (emit_debug_code()) {
    test(object, Immediate(kSmiTagMask));
    Check(equal, kOperandIsNotASmi);
  }
}


771 772 773 774 775 776 777 778
void MacroAssembler::AssertFunction(Register object) {
  if (emit_debug_code()) {
    test(object, Immediate(kSmiTagMask));
    Check(not_equal, kOperandIsASmiAndNotAFunction);
    Push(object);
    CmpObjectType(object, JS_FUNCTION_TYPE, object);
    Pop(object);
    Check(equal, kOperandIsNotAFunction);
779 780 781 782 783 784 785 786 787 788 789 790
  }
}


void MacroAssembler::AssertBoundFunction(Register object) {
  if (emit_debug_code()) {
    test(object, Immediate(kSmiTagMask));
    Check(not_equal, kOperandIsASmiAndNotABoundFunction);
    Push(object);
    CmpObjectType(object, JS_BOUND_FUNCTION_TYPE, object);
    Pop(object);
    Check(equal, kOperandIsNotABoundFunction);
791 792 793
  }
}

794 795 796 797 798 799 800 801 802 803 804
void MacroAssembler::AssertGeneratorObject(Register object) {
  if (emit_debug_code()) {
    test(object, Immediate(kSmiTagMask));
    Check(not_equal, kOperandIsASmiAndNotAGeneratorObject);
    Push(object);
    CmpObjectType(object, JS_GENERATOR_OBJECT_TYPE, object);
    Pop(object);
    Check(equal, kOperandIsNotAGeneratorObject);
  }
}

danno@chromium.org's avatar
danno@chromium.org committed
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
void MacroAssembler::AssertUndefinedOrAllocationSite(Register object) {
  if (emit_debug_code()) {
    Label done_checking;
    AssertNotSmi(object);
    cmp(object, isolate()->factory()->undefined_value());
    j(equal, &done_checking);
    cmp(FieldOperand(object, 0),
        Immediate(isolate()->factory()->allocation_site_map()));
    Assert(equal, kExpectedUndefinedOrCell);
    bind(&done_checking);
  }
}


void MacroAssembler::AssertNotSmi(Register object) {
  if (emit_debug_code()) {
    test(object, Immediate(kSmiTagMask));
    Check(not_equal, kOperandIsASmi);
  }
}

826
void MacroAssembler::StubPrologue(StackFrame::Type type) {
danno@chromium.org's avatar
danno@chromium.org committed
827 828
  push(ebp);  // Caller's frame pointer.
  mov(ebp, esp);
829
  push(Immediate(Smi::FromInt(type)));
danno@chromium.org's avatar
danno@chromium.org committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
}


void MacroAssembler::Prologue(bool code_pre_aging) {
  PredictableCodeSizeScope predictible_code_size_scope(this,
      kNoCodeAgeSequenceLength);
  if (code_pre_aging) {
      // Pre-age the code.
    call(isolate()->builtins()->MarkCodeAsExecutedOnce(),
        RelocInfo::CODE_AGE_SEQUENCE);
    Nop(kNoCodeAgeSequenceLength - Assembler::kCallInstructionLength);
  } else {
    push(ebp);  // Caller's frame pointer.
    mov(ebp, esp);
    push(esi);  // Callee's context.
    push(edi);  // Callee's JS function.
  }
}

849
void MacroAssembler::EmitLoadFeedbackVector(Register vector) {
850
  mov(vector, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
851 852
  mov(vector, FieldOperand(vector, JSFunction::kFeedbackVectorOffset));
  mov(vector, FieldOperand(vector, Cell::kValueOffset));
853 854 855
}


856 857 858 859 860 861 862
void MacroAssembler::EnterFrame(StackFrame::Type type,
                                bool load_constant_pool_pointer_reg) {
  // Out-of-line constant pool not implemented on x87.
  UNREACHABLE();
}


danno@chromium.org's avatar
danno@chromium.org committed
863 864 865 866
void MacroAssembler::EnterFrame(StackFrame::Type type) {
  push(ebp);
  mov(ebp, esp);
  push(Immediate(Smi::FromInt(type)));
867 868 869
  if (type == StackFrame::INTERNAL) {
    push(Immediate(CodeObject()));
  }
danno@chromium.org's avatar
danno@chromium.org committed
870 871 872 873 874 875 876 877 878
  if (emit_debug_code()) {
    cmp(Operand(esp, 0), Immediate(isolate()->factory()->undefined_value()));
    Check(not_equal, kCodeObjectNotProperlyPatched);
  }
}


void MacroAssembler::LeaveFrame(StackFrame::Type type) {
  if (emit_debug_code()) {
879
    cmp(Operand(ebp, CommonFrameConstants::kContextOrFrameTypeOffset),
danno@chromium.org's avatar
danno@chromium.org committed
880 881 882 883 884 885
        Immediate(Smi::FromInt(type)));
    Check(equal, kStackFrameTypesMustMatch);
  }
  leave();
}

886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
void MacroAssembler::EnterBuiltinFrame(Register context, Register target,
                                       Register argc) {
  Push(ebp);
  Move(ebp, esp);
  Push(context);
  Push(target);
  Push(argc);
}

void MacroAssembler::LeaveBuiltinFrame(Register context, Register target,
                                       Register argc) {
  Pop(argc);
  Pop(target);
  Pop(context);
  leave();
}

903 904 905
void MacroAssembler::EnterExitFramePrologue(StackFrame::Type frame_type) {
  DCHECK(frame_type == StackFrame::EXIT ||
         frame_type == StackFrame::BUILTIN_EXIT);
danno@chromium.org's avatar
danno@chromium.org committed
906 907

  // Set up the frame structure on the stack.
908 909 910
  DCHECK_EQ(+2 * kPointerSize, ExitFrameConstants::kCallerSPDisplacement);
  DCHECK_EQ(+1 * kPointerSize, ExitFrameConstants::kCallerPCOffset);
  DCHECK_EQ(0 * kPointerSize, ExitFrameConstants::kCallerFPOffset);
danno@chromium.org's avatar
danno@chromium.org committed
911 912 913 914
  push(ebp);
  mov(ebp, esp);

  // Reserve room for entry stack pointer and push the code object.
915
  push(Immediate(Smi::FromInt(frame_type)));
916
  DCHECK_EQ(-2 * kPointerSize, ExitFrameConstants::kSPOffset);
danno@chromium.org's avatar
danno@chromium.org committed
917
  push(Immediate(0));  // Saved entry sp, patched before call.
918
  DCHECK_EQ(-3 * kPointerSize, ExitFrameConstants::kCodeOffset);
danno@chromium.org's avatar
danno@chromium.org committed
919 920 921 922 923
  push(Immediate(CodeObject()));  // Accessed from ExitFrame::code_slot.

  // Save the frame pointer and the context in top.
  ExternalReference c_entry_fp_address(Isolate::kCEntryFPAddress, isolate());
  ExternalReference context_address(Isolate::kContextAddress, isolate());
924
  ExternalReference c_function_address(Isolate::kCFunctionAddress, isolate());
danno@chromium.org's avatar
danno@chromium.org committed
925 926
  mov(Operand::StaticVariable(c_entry_fp_address), ebp);
  mov(Operand::StaticVariable(context_address), esi);
927
  mov(Operand::StaticVariable(c_function_address), ebx);
danno@chromium.org's avatar
danno@chromium.org committed
928 929 930
}


931 932 933 934 935 936
void MacroAssembler::EnterExitFrameEpilogue(int argc, bool save_doubles) {
  // Optionally save FPU state.
  if (save_doubles) {
    // Store FPU state to m108byte.
    int space = 108 + argc * kPointerSize;
    sub(esp, Immediate(space));
937
    const int offset = -ExitFrameConstants::kFixedFrameSizeFromFp;
938 939 940 941
    fnsave(MemOperand(ebp, offset - 108));
  } else {
    sub(esp, Immediate(argc * kPointerSize));
  }
danno@chromium.org's avatar
danno@chromium.org committed
942 943

  // Get the required frame alignment for the OS.
944
  const int kFrameAlignment = base::OS::ActivationFrameAlignment();
danno@chromium.org's avatar
danno@chromium.org committed
945
  if (kFrameAlignment > 0) {
946
    DCHECK(base::bits::IsPowerOfTwo32(kFrameAlignment));
danno@chromium.org's avatar
danno@chromium.org committed
947 948 949 950 951 952 953
    and_(esp, -kFrameAlignment);
  }

  // Patch the saved entry sp.
  mov(Operand(ebp, ExitFrameConstants::kSPOffset), esp);
}

954 955 956
void MacroAssembler::EnterExitFrame(int argc, bool save_doubles,
                                    StackFrame::Type frame_type) {
  EnterExitFramePrologue(frame_type);
danno@chromium.org's avatar
danno@chromium.org committed
957 958 959 960 961 962 963

  // Set up argc and argv in callee-saved registers.
  int offset = StandardFrameConstants::kCallerSPOffset - kPointerSize;
  mov(edi, eax);
  lea(esi, Operand(ebp, eax, times_4, offset));

  // Reserve space for argc, argv and isolate.
964
  EnterExitFrameEpilogue(argc, save_doubles);
danno@chromium.org's avatar
danno@chromium.org committed
965 966 967 968
}


void MacroAssembler::EnterApiExitFrame(int argc) {
969
  EnterExitFramePrologue(StackFrame::EXIT);
970
  EnterExitFrameEpilogue(argc, false);
danno@chromium.org's avatar
danno@chromium.org committed
971 972 973
}


974
void MacroAssembler::LeaveExitFrame(bool save_doubles, bool pop_arguments) {
975 976
  // Optionally restore FPU state.
  if (save_doubles) {
977
    const int offset = -ExitFrameConstants::kFixedFrameSizeFromFp;
978 979 980
    frstor(MemOperand(ebp, offset - 108));
  }

981 982 983 984
  if (pop_arguments) {
    // Get the return address from the stack and restore the frame pointer.
    mov(ecx, Operand(ebp, 1 * kPointerSize));
    mov(ebp, Operand(ebp, 0 * kPointerSize));
danno@chromium.org's avatar
danno@chromium.org committed
985

986 987
    // Pop the arguments and the receiver from the caller stack.
    lea(esp, Operand(esi, 1 * kPointerSize));
danno@chromium.org's avatar
danno@chromium.org committed
988

989 990 991 992 993 994
    // Push the return address to get ready to return.
    push(ecx);
  } else {
    // Otherwise just leave the exit frame.
    leave();
  }
danno@chromium.org's avatar
danno@chromium.org committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024

  LeaveExitFrameEpilogue(true);
}


void MacroAssembler::LeaveExitFrameEpilogue(bool restore_context) {
  // Restore current context from top and clear it in debug mode.
  ExternalReference context_address(Isolate::kContextAddress, isolate());
  if (restore_context) {
    mov(esi, Operand::StaticVariable(context_address));
  }
#ifdef DEBUG
  mov(Operand::StaticVariable(context_address), Immediate(0));
#endif

  // Clear the top frame.
  ExternalReference c_entry_fp_address(Isolate::kCEntryFPAddress,
                                       isolate());
  mov(Operand::StaticVariable(c_entry_fp_address), Immediate(0));
}


void MacroAssembler::LeaveApiExitFrame(bool restore_context) {
  mov(esp, ebp);
  pop(ebp);

  LeaveExitFrameEpilogue(restore_context);
}


1025
void MacroAssembler::PushStackHandler() {
danno@chromium.org's avatar
danno@chromium.org committed
1026
  // Adjust this code if not the case.
1027
  STATIC_ASSERT(StackHandlerConstants::kSize == 1 * kPointerSize);
danno@chromium.org's avatar
danno@chromium.org committed
1028 1029 1030 1031 1032
  STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);

  // Link the current handler as the next handler.
  ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
  push(Operand::StaticVariable(handler_address));
1033

danno@chromium.org's avatar
danno@chromium.org committed
1034 1035 1036 1037 1038
  // Set this new handler as the current one.
  mov(Operand::StaticVariable(handler_address), esp);
}


1039
void MacroAssembler::PopStackHandler() {
danno@chromium.org's avatar
danno@chromium.org committed
1040 1041 1042 1043 1044 1045 1046 1047
  STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
  ExternalReference handler_address(Isolate::kHandlerAddress, isolate());
  pop(Operand::StaticVariable(handler_address));
  add(esp, Immediate(StackHandlerConstants::kSize - kPointerSize));
}


// Compute the hash code from the untagged key.  This must be kept in sync with
1048
// ComputeIntegerHash in utils.h and KeyedLoadGenericStub in
danno@chromium.org's avatar
danno@chromium.org committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
// code-stub-hydrogen.cc
//
// Note: r0 will contain hash code
void MacroAssembler::GetNumberHash(Register r0, Register scratch) {
  // Xor original key with a seed.
  if (serializer_enabled()) {
    ExternalReference roots_array_start =
        ExternalReference::roots_array_start(isolate());
    mov(scratch, Immediate(Heap::kHashSeedRootIndex));
    mov(scratch,
        Operand::StaticArray(scratch, times_pointer_size, roots_array_start));
    SmiUntag(scratch);
    xor_(r0, scratch);
  } else {
    int32_t seed = isolate()->heap()->HashSeed();
    xor_(r0, Immediate(seed));
  }

  // hash = ~hash + (hash << 15);
  mov(scratch, r0);
  not_(r0);
  shl(scratch, 15);
  add(r0, scratch);
  // hash = hash ^ (hash >> 12);
  mov(scratch, r0);
  shr(scratch, 12);
  xor_(r0, scratch);
  // hash = hash + (hash << 2);
  lea(r0, Operand(r0, r0, times_4, 0));
  // hash = hash ^ (hash >> 4);
  mov(scratch, r0);
  shr(scratch, 4);
  xor_(r0, scratch);
  // hash = hash * 2057;
  imul(r0, r0, 2057);
  // hash = hash ^ (hash >> 16);
  mov(scratch, r0);
  shr(scratch, 16);
  xor_(r0, scratch);
1088
  and_(r0, 0x3fffffff);
danno@chromium.org's avatar
danno@chromium.org committed
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
}

void MacroAssembler::LoadAllocationTopHelper(Register result,
                                             Register scratch,
                                             AllocationFlags flags) {
  ExternalReference allocation_top =
      AllocationUtils::GetAllocationTopReference(isolate(), flags);

  // Just return if allocation top is already known.
  if ((flags & RESULT_CONTAINS_TOP) != 0) {
    // No use of scratch if allocation top is provided.
1100
    DCHECK(scratch.is(no_reg));
danno@chromium.org's avatar
danno@chromium.org committed
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
#ifdef DEBUG
    // Assert that result actually contains top on entry.
    cmp(result, Operand::StaticVariable(allocation_top));
    Check(equal, kUnexpectedAllocationTop);
#endif
    return;
  }

  // Move address of new object to result. Use scratch register if available.
  if (scratch.is(no_reg)) {
    mov(result, Operand::StaticVariable(allocation_top));
  } else {
    mov(scratch, Immediate(allocation_top));
    mov(result, Operand(scratch, 0));
  }
}


void MacroAssembler::UpdateAllocationTopHelper(Register result_end,
                                               Register scratch,
                                               AllocationFlags flags) {
  if (emit_debug_code()) {
    test(result_end, Immediate(kObjectAlignmentMask));
    Check(zero, kUnalignedAllocationInNewSpace);
  }

  ExternalReference allocation_top =
      AllocationUtils::GetAllocationTopReference(isolate(), flags);

  // Update new top. Use scratch if available.
  if (scratch.is(no_reg)) {
    mov(Operand::StaticVariable(allocation_top), result_end);
  } else {
    mov(Operand(scratch, 0), result_end);
  }
}


void MacroAssembler::Allocate(int object_size,
                              Register result,
                              Register result_end,
                              Register scratch,
                              Label* gc_required,
                              AllocationFlags flags) {
1145
  DCHECK((flags & (RESULT_CONTAINS_TOP | SIZE_IN_WORDS)) == 0);
1146
  DCHECK(object_size <= kMaxRegularHeapObjectSize);
1147
  DCHECK((flags & ALLOCATION_FOLDED) == 0);
danno@chromium.org's avatar
danno@chromium.org committed
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
  if (!FLAG_inline_new) {
    if (emit_debug_code()) {
      // Trash the registers to simulate an allocation failure.
      mov(result, Immediate(0x7091));
      if (result_end.is_valid()) {
        mov(result_end, Immediate(0x7191));
      }
      if (scratch.is_valid()) {
        mov(scratch, Immediate(0x7291));
      }
    }
    jmp(gc_required);
    return;
  }
1162
  DCHECK(!result.is(result_end));
danno@chromium.org's avatar
danno@chromium.org committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

  // Load address of new object into result.
  LoadAllocationTopHelper(result, scratch, flags);

  ExternalReference allocation_limit =
      AllocationUtils::GetAllocationLimitReference(isolate(), flags);

  // Align the next allocation. Storing the filler map without checking top is
  // safe in new-space because the limit of the heap is aligned there.
  if ((flags & DOUBLE_ALIGNMENT) != 0) {
1173
    DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
danno@chromium.org's avatar
danno@chromium.org committed
1174 1175 1176
    Label aligned;
    test(result, Immediate(kDoubleAlignmentMask));
    j(zero, &aligned, Label::kNear);
1177
    if ((flags & PRETENURE) != 0) {
danno@chromium.org's avatar
danno@chromium.org committed
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
      cmp(result, Operand::StaticVariable(allocation_limit));
      j(above_equal, gc_required);
    }
    mov(Operand(result, 0),
        Immediate(isolate()->factory()->one_pointer_filler_map()));
    add(result, Immediate(kDoubleSize / 2));
    bind(&aligned);
  }

  // Calculate new top and bail out if space is exhausted.
  Register top_reg = result_end.is_valid() ? result_end : result;
1189

danno@chromium.org's avatar
danno@chromium.org committed
1190 1191 1192 1193 1194 1195 1196
  if (!top_reg.is(result)) {
    mov(top_reg, result);
  }
  add(top_reg, Immediate(object_size));
  cmp(top_reg, Operand::StaticVariable(allocation_limit));
  j(above, gc_required);

1197 1198 1199 1200
  if ((flags & ALLOCATION_FOLDING_DOMINATOR) == 0) {
    // The top pointer is not updated for allocation folding dominators.
    UpdateAllocationTopHelper(top_reg, scratch, flags);
  }
danno@chromium.org's avatar
danno@chromium.org committed
1201 1202

  if (top_reg.is(result)) {
1203 1204
    sub(result, Immediate(object_size - kHeapObjectTag));
  } else {
1205
    // Tag the result.
1206
    DCHECK(kHeapObjectTag == 1);
danno@chromium.org's avatar
danno@chromium.org committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    inc(result);
  }
}


void MacroAssembler::Allocate(int header_size,
                              ScaleFactor element_size,
                              Register element_count,
                              RegisterValueType element_count_type,
                              Register result,
                              Register result_end,
                              Register scratch,
                              Label* gc_required,
                              AllocationFlags flags) {
1221
  DCHECK((flags & SIZE_IN_WORDS) == 0);
1222 1223
  DCHECK((flags & ALLOCATION_FOLDING_DOMINATOR) == 0);
  DCHECK((flags & ALLOCATION_FOLDED) == 0);
danno@chromium.org's avatar
danno@chromium.org committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
  if (!FLAG_inline_new) {
    if (emit_debug_code()) {
      // Trash the registers to simulate an allocation failure.
      mov(result, Immediate(0x7091));
      mov(result_end, Immediate(0x7191));
      if (scratch.is_valid()) {
        mov(scratch, Immediate(0x7291));
      }
      // Register element_count is not modified by the function.
    }
    jmp(gc_required);
    return;
  }
1237
  DCHECK(!result.is(result_end));
danno@chromium.org's avatar
danno@chromium.org committed
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247

  // Load address of new object into result.
  LoadAllocationTopHelper(result, scratch, flags);

  ExternalReference allocation_limit =
      AllocationUtils::GetAllocationLimitReference(isolate(), flags);

  // Align the next allocation. Storing the filler map without checking top is
  // safe in new-space because the limit of the heap is aligned there.
  if ((flags & DOUBLE_ALIGNMENT) != 0) {
1248
    DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
danno@chromium.org's avatar
danno@chromium.org committed
1249 1250 1251
    Label aligned;
    test(result, Immediate(kDoubleAlignmentMask));
    j(zero, &aligned, Label::kNear);
1252
    if ((flags & PRETENURE) != 0) {
danno@chromium.org's avatar
danno@chromium.org committed
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
      cmp(result, Operand::StaticVariable(allocation_limit));
      j(above_equal, gc_required);
    }
    mov(Operand(result, 0),
        Immediate(isolate()->factory()->one_pointer_filler_map()));
    add(result, Immediate(kDoubleSize / 2));
    bind(&aligned);
  }

  // Calculate new top and bail out if space is exhausted.
  // We assume that element_count*element_size + header_size does not
  // overflow.
  if (element_count_type == REGISTER_VALUE_IS_SMI) {
    STATIC_ASSERT(static_cast<ScaleFactor>(times_2 - 1) == times_1);
    STATIC_ASSERT(static_cast<ScaleFactor>(times_4 - 1) == times_2);
    STATIC_ASSERT(static_cast<ScaleFactor>(times_8 - 1) == times_4);
1269 1270
    DCHECK(element_size >= times_2);
    DCHECK(kSmiTagSize == 1);
danno@chromium.org's avatar
danno@chromium.org committed
1271 1272
    element_size = static_cast<ScaleFactor>(element_size - 1);
  } else {
1273
    DCHECK(element_count_type == REGISTER_VALUE_IS_INT32);
danno@chromium.org's avatar
danno@chromium.org committed
1274 1275 1276 1277 1278 1279 1280
  }
  lea(result_end, Operand(element_count, element_size, header_size));
  add(result_end, result);
  j(carry, gc_required);
  cmp(result_end, Operand::StaticVariable(allocation_limit));
  j(above, gc_required);

1281
  // Tag result.
1282 1283
  DCHECK(kHeapObjectTag == 1);
  inc(result);
danno@chromium.org's avatar
danno@chromium.org committed
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

  // Update allocation top.
  UpdateAllocationTopHelper(result_end, scratch, flags);
}

void MacroAssembler::Allocate(Register object_size,
                              Register result,
                              Register result_end,
                              Register scratch,
                              Label* gc_required,
                              AllocationFlags flags) {
1295
  DCHECK((flags & (RESULT_CONTAINS_TOP | SIZE_IN_WORDS)) == 0);
1296
  DCHECK((flags & ALLOCATION_FOLDED) == 0);
danno@chromium.org's avatar
danno@chromium.org committed
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
  if (!FLAG_inline_new) {
    if (emit_debug_code()) {
      // Trash the registers to simulate an allocation failure.
      mov(result, Immediate(0x7091));
      mov(result_end, Immediate(0x7191));
      if (scratch.is_valid()) {
        mov(scratch, Immediate(0x7291));
      }
      // object_size is left unchanged by this function.
    }
    jmp(gc_required);
    return;
  }
1310
  DCHECK(!result.is(result_end));
danno@chromium.org's avatar
danno@chromium.org committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

  // Load address of new object into result.
  LoadAllocationTopHelper(result, scratch, flags);

  ExternalReference allocation_limit =
      AllocationUtils::GetAllocationLimitReference(isolate(), flags);

  // Align the next allocation. Storing the filler map without checking top is
  // safe in new-space because the limit of the heap is aligned there.
  if ((flags & DOUBLE_ALIGNMENT) != 0) {
1321
    DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
danno@chromium.org's avatar
danno@chromium.org committed
1322 1323 1324
    Label aligned;
    test(result, Immediate(kDoubleAlignmentMask));
    j(zero, &aligned, Label::kNear);
1325
    if ((flags & PRETENURE) != 0) {
danno@chromium.org's avatar
danno@chromium.org committed
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
      cmp(result, Operand::StaticVariable(allocation_limit));
      j(above_equal, gc_required);
    }
    mov(Operand(result, 0),
        Immediate(isolate()->factory()->one_pointer_filler_map()));
    add(result, Immediate(kDoubleSize / 2));
    bind(&aligned);
  }

  // Calculate new top and bail out if space is exhausted.
  if (!object_size.is(result_end)) {
    mov(result_end, object_size);
  }
  add(result_end, result);
  cmp(result_end, Operand::StaticVariable(allocation_limit));
  j(above, gc_required);

1343 1344 1345
  // Tag result.
  DCHECK(kHeapObjectTag == 1);
  inc(result);
danno@chromium.org's avatar
danno@chromium.org committed
1346

1347 1348 1349 1350
  if ((flags & ALLOCATION_FOLDING_DOMINATOR) == 0) {
    // The top pointer is not updated for allocation folding dominators.
    UpdateAllocationTopHelper(result_end, scratch, flags);
  }
danno@chromium.org's avatar
danno@chromium.org committed
1351 1352
}

1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 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
void MacroAssembler::FastAllocate(int object_size, Register result,
                                  Register result_end, AllocationFlags flags) {
  DCHECK(!result.is(result_end));
  // Load address of new object into result.
  LoadAllocationTopHelper(result, no_reg, flags);

  if ((flags & DOUBLE_ALIGNMENT) != 0) {
    DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
    Label aligned;
    test(result, Immediate(kDoubleAlignmentMask));
    j(zero, &aligned, Label::kNear);
    mov(Operand(result, 0),
        Immediate(isolate()->factory()->one_pointer_filler_map()));
    add(result, Immediate(kDoubleSize / 2));
    bind(&aligned);
  }

  lea(result_end, Operand(result, object_size));
  UpdateAllocationTopHelper(result_end, no_reg, flags);

  DCHECK(kHeapObjectTag == 1);
  inc(result);
}

void MacroAssembler::FastAllocate(Register object_size, Register result,
                                  Register result_end, AllocationFlags flags) {
  DCHECK(!result.is(result_end));
  // Load address of new object into result.
  LoadAllocationTopHelper(result, no_reg, flags);

  if ((flags & DOUBLE_ALIGNMENT) != 0) {
    DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
    Label aligned;
    test(result, Immediate(kDoubleAlignmentMask));
    j(zero, &aligned, Label::kNear);
    mov(Operand(result, 0),
        Immediate(isolate()->factory()->one_pointer_filler_map()));
    add(result, Immediate(kDoubleSize / 2));
    bind(&aligned);
  }

  lea(result_end, Operand(result, object_size, times_1, 0));
  UpdateAllocationTopHelper(result_end, no_reg, flags);

  DCHECK(kHeapObjectTag == 1);
  inc(result);
}
danno@chromium.org's avatar
danno@chromium.org committed
1400 1401 1402 1403

void MacroAssembler::AllocateHeapNumber(Register result,
                                        Register scratch1,
                                        Register scratch2,
1404 1405
                                        Label* gc_required,
                                        MutableMode mode) {
danno@chromium.org's avatar
danno@chromium.org committed
1406 1407
  // Allocate heap number in new space.
  Allocate(HeapNumber::kSize, result, scratch1, scratch2, gc_required,
1408
           NO_ALLOCATION_FLAGS);
danno@chromium.org's avatar
danno@chromium.org committed
1409

1410 1411 1412 1413
  Handle<Map> map = mode == MUTABLE
      ? isolate()->factory()->mutable_heap_number_map()
      : isolate()->factory()->heap_number_map();

danno@chromium.org's avatar
danno@chromium.org committed
1414
  // Set the map.
1415
  mov(FieldOperand(result, HeapObject::kMapOffset), Immediate(map));
danno@chromium.org's avatar
danno@chromium.org committed
1416 1417
}

1418 1419 1420 1421 1422 1423 1424 1425
void MacroAssembler::AllocateJSValue(Register result, Register constructor,
                                     Register value, Register scratch,
                                     Label* gc_required) {
  DCHECK(!result.is(constructor));
  DCHECK(!result.is(scratch));
  DCHECK(!result.is(value));

  // Allocate JSValue in new space.
1426 1427
  Allocate(JSValue::kSize, result, scratch, no_reg, gc_required,
           NO_ALLOCATION_FLAGS);
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438

  // Initialize the JSValue.
  LoadGlobalFunctionInitialMap(constructor, scratch);
  mov(FieldOperand(result, HeapObject::kMapOffset), scratch);
  LoadRoot(scratch, Heap::kEmptyFixedArrayRootIndex);
  mov(FieldOperand(result, JSObject::kPropertiesOffset), scratch);
  mov(FieldOperand(result, JSObject::kElementsOffset), scratch);
  mov(FieldOperand(result, JSValue::kValueOffset), value);
  STATIC_ASSERT(JSValue::kSize == 4 * kPointerSize);
}

1439 1440
void MacroAssembler::InitializeFieldsWithFiller(Register current_address,
                                                Register end_address,
danno@chromium.org's avatar
danno@chromium.org committed
1441 1442
                                                Register filler) {
  Label loop, entry;
1443
  jmp(&entry, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
1444
  bind(&loop);
1445 1446
  mov(Operand(current_address, 0), filler);
  add(current_address, Immediate(kPointerSize));
danno@chromium.org's avatar
danno@chromium.org committed
1447
  bind(&entry);
1448
  cmp(current_address, end_address);
1449
  j(below, &loop, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
1450 1451 1452 1453 1454 1455 1456
}


void MacroAssembler::BooleanBitTest(Register object,
                                    int field_offset,
                                    int bit_index) {
  bit_index += kSmiTagSize + kSmiShiftSize;
1457
  DCHECK(base::bits::IsPowerOfTwo32(kBitsPerByte));
danno@chromium.org's avatar
danno@chromium.org committed
1458 1459 1460
  int byte_index = bit_index / kBitsPerByte;
  int byte_bit_index = bit_index & (kBitsPerByte - 1);
  test_b(FieldOperand(object, field_offset + byte_index),
1461
         Immediate(1 << byte_bit_index));
danno@chromium.org's avatar
danno@chromium.org committed
1462 1463
}

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
void MacroAssembler::GetMapConstructor(Register result, Register map,
                                       Register temp) {
  Label done, loop;
  mov(result, FieldOperand(map, Map::kConstructorOrBackPointerOffset));
  bind(&loop);
  JumpIfSmi(result, &done, Label::kNear);
  CmpObjectType(result, MAP_TYPE, temp);
  j(not_equal, &done, Label::kNear);
  mov(result, FieldOperand(result, Map::kConstructorOrBackPointerOffset));
  jmp(&loop);
  bind(&done);
}
danno@chromium.org's avatar
danno@chromium.org committed
1476 1477

void MacroAssembler::CallStub(CodeStub* stub, TypeFeedbackId ast_id) {
1478
  DCHECK(AllowThisStubCall(stub));  // Calls are not allowed in some stubs.
danno@chromium.org's avatar
danno@chromium.org committed
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  call(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id);
}


void MacroAssembler::TailCallStub(CodeStub* stub) {
  jmp(stub->GetCode(), RelocInfo::CODE_TARGET);
}



bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
  return has_frame_ || !stub->SometimesSetsUpAFrame();
}

1493 1494
void MacroAssembler::CallRuntime(const Runtime::Function* f, int num_arguments,
                                 SaveFPRegsMode save_doubles) {
danno@chromium.org's avatar
danno@chromium.org committed
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
  // If the expected number of arguments of the runtime function is
  // constant, we check that the actual number of arguments match the
  // expectation.
  CHECK(f->nargs < 0 || f->nargs == num_arguments);

  // TODO(1236192): Most runtime routines don't need the number of
  // arguments passed in because it is constant. At some point we
  // should remove this need and make the runtime routine entry code
  // smarter.
  Move(eax, Immediate(num_arguments));
  mov(ebx, Immediate(ExternalReference(f, isolate())));
1506
  CEntryStub ces(isolate(), 1, save_doubles);
danno@chromium.org's avatar
danno@chromium.org committed
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
  CallStub(&ces);
}


void MacroAssembler::CallExternalReference(ExternalReference ref,
                                           int num_arguments) {
  mov(eax, Immediate(num_arguments));
  mov(ebx, Immediate(ref));

  CEntryStub stub(isolate(), 1);
  CallStub(&stub);
}


1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid) {
  // ----------- S t a t e -------------
  //  -- esp[0]                 : return address
  //  -- esp[8]                 : argument num_arguments - 1
  //  ...
  //  -- esp[8 * num_arguments] : argument 0 (receiver)
  //
  //  For runtime functions with variable arguments:
  //  -- eax                    : number of  arguments
  // -----------------------------------

  const Runtime::Function* function = Runtime::FunctionForId(fid);
  DCHECK_EQ(1, function->result_size);
  if (function->nargs >= 0) {
    // TODO(1236192): Most runtime routines don't need the number of
    // arguments passed in because it is constant. At some point we
    // should remove this need and make the runtime routine entry code
    // smarter.
    mov(eax, Immediate(function->nargs));
  }
  JumpToExternalReference(ExternalReference(fid, isolate()));
danno@chromium.org's avatar
danno@chromium.org committed
1542 1543
}

1544 1545
void MacroAssembler::JumpToExternalReference(const ExternalReference& ext,
                                             bool builtin_exit_frame) {
danno@chromium.org's avatar
danno@chromium.org committed
1546 1547
  // Set the entry point and jump to the C entry runtime stub.
  mov(ebx, Immediate(ext));
1548 1549
  CEntryStub ces(isolate(), 1, kDontSaveFPRegs, kArgvOnStack,
                 builtin_exit_frame);
danno@chromium.org's avatar
danno@chromium.org committed
1550 1551 1552
  jmp(ces.GetCode(), RelocInfo::CODE_TARGET);
}

1553 1554 1555 1556
void MacroAssembler::PrepareForTailCall(
    const ParameterCount& callee_args_count, Register caller_args_count_reg,
    Register scratch0, Register scratch1, ReturnAddressState ra_state,
    int number_of_temp_values_after_return_address) {
1557 1558 1559 1560 1561 1562 1563
#if DEBUG
  if (callee_args_count.is_reg()) {
    DCHECK(!AreAliased(callee_args_count.reg(), caller_args_count_reg, scratch0,
                       scratch1));
  } else {
    DCHECK(!AreAliased(caller_args_count_reg, scratch0, scratch1));
  }
1564 1565
  DCHECK(ra_state != ReturnAddressState::kNotOnStack ||
         number_of_temp_values_after_return_address == 0);
1566 1567 1568 1569 1570 1571 1572
#endif

  // Calculate the destination address where we will put the return address
  // after we drop current frame.
  Register new_sp_reg = scratch0;
  if (callee_args_count.is_reg()) {
    sub(caller_args_count_reg, callee_args_count.reg());
1573 1574 1575 1576
    lea(new_sp_reg,
        Operand(ebp, caller_args_count_reg, times_pointer_size,
                StandardFrameConstants::kCallerPCOffset -
                    number_of_temp_values_after_return_address * kPointerSize));
1577 1578 1579
  } else {
    lea(new_sp_reg, Operand(ebp, caller_args_count_reg, times_pointer_size,
                            StandardFrameConstants::kCallerPCOffset -
1580 1581 1582
                                (callee_args_count.immediate() +
                                 number_of_temp_values_after_return_address) *
                                    kPointerSize));
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
  }

  if (FLAG_debug_code) {
    cmp(esp, new_sp_reg);
    Check(below, kStackAccessBelowStackPointer);
  }

  // Copy return address from caller's frame to current frame's return address
  // to avoid its trashing and let the following loop copy it to the right
  // place.
  Register tmp_reg = scratch1;
  if (ra_state == ReturnAddressState::kOnStack) {
    mov(tmp_reg, Operand(ebp, StandardFrameConstants::kCallerPCOffset));
1596 1597
    mov(Operand(esp, number_of_temp_values_after_return_address * kPointerSize),
        tmp_reg);
1598 1599
  } else {
    DCHECK(ReturnAddressState::kNotOnStack == ra_state);
1600
    DCHECK_EQ(0, number_of_temp_values_after_return_address);
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
    Push(Operand(ebp, StandardFrameConstants::kCallerPCOffset));
  }

  // Restore caller's frame pointer now as it could be overwritten by
  // the copying loop.
  mov(ebp, Operand(ebp, StandardFrameConstants::kCallerFPOffset));

  // +2 here is to copy both receiver and return address.
  Register count_reg = caller_args_count_reg;
  if (callee_args_count.is_reg()) {
1611 1612
    lea(count_reg, Operand(callee_args_count.reg(),
                           2 + number_of_temp_values_after_return_address));
1613
  } else {
1614 1615
    mov(count_reg, Immediate(callee_args_count.immediate() + 2 +
                             number_of_temp_values_after_return_address));
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
    // TODO(ishell): Unroll copying loop for small immediate values.
  }

  // Now copy callee arguments to the caller frame going backwards to avoid
  // callee arguments corruption (source and destination areas could overlap).
  Label loop, entry;
  jmp(&entry, Label::kNear);
  bind(&loop);
  dec(count_reg);
  mov(tmp_reg, Operand(esp, count_reg, times_pointer_size, 0));
  mov(Operand(new_sp_reg, count_reg, times_pointer_size, 0), tmp_reg);
  bind(&entry);
  cmp(count_reg, Immediate(0));
  j(not_equal, &loop, Label::kNear);

  // Leave current frame.
  mov(esp, new_sp_reg);
}
danno@chromium.org's avatar
danno@chromium.org committed
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645

void MacroAssembler::InvokePrologue(const ParameterCount& expected,
                                    const ParameterCount& actual,
                                    Label* done,
                                    bool* definitely_mismatches,
                                    InvokeFlag flag,
                                    Label::Distance done_near,
                                    const CallWrapper& call_wrapper) {
  bool definitely_matches = false;
  *definitely_mismatches = false;
  Label invoke;
  if (expected.is_immediate()) {
1646
    DCHECK(actual.is_immediate());
1647
    mov(eax, actual.immediate());
danno@chromium.org's avatar
danno@chromium.org committed
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
    if (expected.immediate() == actual.immediate()) {
      definitely_matches = true;
    } else {
      const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
      if (expected.immediate() == sentinel) {
        // Don't worry about adapting arguments for builtins that
        // don't want that done. Skip adaption code by making it look
        // like we have a match between expected and actual number of
        // arguments.
        definitely_matches = true;
      } else {
        *definitely_mismatches = true;
        mov(ebx, expected.immediate());
      }
    }
  } else {
    if (actual.is_immediate()) {
      // Expected is in register, actual is immediate. This is the
      // case when we invoke function values without going through the
      // IC mechanism.
1668
      mov(eax, actual.immediate());
danno@chromium.org's avatar
danno@chromium.org committed
1669 1670
      cmp(expected.reg(), actual.immediate());
      j(equal, &invoke);
1671
      DCHECK(expected.reg().is(ebx));
danno@chromium.org's avatar
danno@chromium.org committed
1672 1673 1674 1675 1676
    } else if (!expected.reg().is(actual.reg())) {
      // Both expected and actual are in (different) registers. This
      // is the case when we invoke functions using call and apply.
      cmp(expected.reg(), actual.reg());
      j(equal, &invoke);
1677 1678
      DCHECK(actual.reg().is(eax));
      DCHECK(expected.reg().is(ebx));
1679 1680
    } else {
      Move(eax, actual.reg());
danno@chromium.org's avatar
danno@chromium.org committed
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
    }
  }

  if (!definitely_matches) {
    Handle<Code> adaptor =
        isolate()->builtins()->ArgumentsAdaptorTrampoline();
    if (flag == CALL_FUNCTION) {
      call_wrapper.BeforeCall(CallSize(adaptor, RelocInfo::CODE_TARGET));
      call(adaptor, RelocInfo::CODE_TARGET);
      call_wrapper.AfterCall();
      if (!*definitely_mismatches) {
        jmp(done, done_near);
      }
    } else {
      jmp(adaptor, RelocInfo::CODE_TARGET);
    }
    bind(&invoke);
  }
}

1701 1702 1703 1704 1705 1706 1707 1708
void MacroAssembler::CheckDebugHook(Register fun, Register new_target,
                                    const ParameterCount& expected,
                                    const ParameterCount& actual) {
  Label skip_hook;
  ExternalReference debug_hook_active =
      ExternalReference::debug_hook_on_function_call_address(isolate());
  cmpb(Operand::StaticVariable(debug_hook_active), Immediate(0));
  j(equal, &skip_hook);
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
  {
    FrameScope frame(this,
                     has_frame() ? StackFrame::NONE : StackFrame::INTERNAL);
    if (expected.is_reg()) {
      SmiTag(expected.reg());
      Push(expected.reg());
    }
    if (actual.is_reg()) {
      SmiTag(actual.reg());
      Push(actual.reg());
    }
    if (new_target.is_valid()) {
      Push(new_target);
    }
    Push(fun);
    Push(fun);
1725
    CallRuntime(Runtime::kDebugOnFunctionCall);
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
    Pop(fun);
    if (new_target.is_valid()) {
      Pop(new_target);
    }
    if (actual.is_reg()) {
      Pop(actual.reg());
      SmiUntag(actual.reg());
    }
    if (expected.is_reg()) {
      Pop(expected.reg());
      SmiUntag(expected.reg());
    }
  }
1739
  bind(&skip_hook);
1740 1741 1742 1743 1744 1745 1746 1747
}


void MacroAssembler::InvokeFunctionCode(Register function, Register new_target,
                                        const ParameterCount& expected,
                                        const ParameterCount& actual,
                                        InvokeFlag flag,
                                        const CallWrapper& call_wrapper) {
danno@chromium.org's avatar
danno@chromium.org committed
1748
  // You can't call a function without a valid frame.
1749
  DCHECK(flag == JUMP_FUNCTION || has_frame());
1750
  DCHECK(function.is(edi));
1751
  DCHECK_IMPLIES(new_target.is_valid(), new_target.is(edx));
1752

1753 1754
  if (call_wrapper.NeedsDebugHookCheck()) {
    CheckDebugHook(function, new_target, expected, actual);
1755 1756 1757
  }

  // Clear the new.target register if not given.
1758 1759 1760 1761
  if (!new_target.is_valid()) {
    mov(edx, isolate()->factory()->undefined_value());
  }

danno@chromium.org's avatar
danno@chromium.org committed
1762 1763
  Label done;
  bool definitely_mismatches = false;
1764 1765
  InvokePrologue(expected, actual, &done, &definitely_mismatches, flag,
                 Label::kNear, call_wrapper);
danno@chromium.org's avatar
danno@chromium.org committed
1766
  if (!definitely_mismatches) {
1767 1768 1769 1770
    // We call indirectly through the code field in the function to
    // allow recompilation to take effect without changing any of the
    // call sites.
    Operand code = FieldOperand(function, JSFunction::kCodeEntryOffset);
danno@chromium.org's avatar
danno@chromium.org committed
1771 1772 1773 1774 1775
    if (flag == CALL_FUNCTION) {
      call_wrapper.BeforeCall(CallSize(code));
      call(code);
      call_wrapper.AfterCall();
    } else {
1776
      DCHECK(flag == JUMP_FUNCTION);
danno@chromium.org's avatar
danno@chromium.org committed
1777 1778 1779 1780 1781 1782 1783
      jmp(code);
    }
    bind(&done);
  }
}


1784
void MacroAssembler::InvokeFunction(Register fun, Register new_target,
danno@chromium.org's avatar
danno@chromium.org committed
1785 1786 1787 1788
                                    const ParameterCount& actual,
                                    InvokeFlag flag,
                                    const CallWrapper& call_wrapper) {
  // You can't call a function without a valid frame.
1789
  DCHECK(flag == JUMP_FUNCTION || has_frame());
danno@chromium.org's avatar
danno@chromium.org committed
1790

1791
  DCHECK(fun.is(edi));
1792
  mov(ebx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
danno@chromium.org's avatar
danno@chromium.org committed
1793
  mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
1794
  mov(ebx, FieldOperand(ebx, SharedFunctionInfo::kFormalParameterCountOffset));
danno@chromium.org's avatar
danno@chromium.org committed
1795 1796 1797
  SmiUntag(ebx);

  ParameterCount expected(ebx);
1798
  InvokeFunctionCode(edi, new_target, expected, actual, flag, call_wrapper);
danno@chromium.org's avatar
danno@chromium.org committed
1799 1800 1801 1802 1803 1804 1805 1806 1807
}


void MacroAssembler::InvokeFunction(Register fun,
                                    const ParameterCount& expected,
                                    const ParameterCount& actual,
                                    InvokeFlag flag,
                                    const CallWrapper& call_wrapper) {
  // You can't call a function without a valid frame.
1808
  DCHECK(flag == JUMP_FUNCTION || has_frame());
danno@chromium.org's avatar
danno@chromium.org committed
1809

1810
  DCHECK(fun.is(edi));
danno@chromium.org's avatar
danno@chromium.org committed
1811 1812
  mov(esi, FieldOperand(edi, JSFunction::kContextOffset));

1813
  InvokeFunctionCode(edi, no_reg, expected, actual, flag, call_wrapper);
danno@chromium.org's avatar
danno@chromium.org committed
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
}


void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
                                    const ParameterCount& expected,
                                    const ParameterCount& actual,
                                    InvokeFlag flag,
                                    const CallWrapper& call_wrapper) {
  LoadHeapObject(edi, function);
  InvokeFunction(edi, expected, actual, flag, call_wrapper);
}


void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
  if (context_chain_length > 0) {
    // Move up the chain of contexts to the context containing the slot.
    mov(dst, Operand(esi, Context::SlotOffset(Context::PREVIOUS_INDEX)));
    for (int i = 1; i < context_chain_length; i++) {
      mov(dst, Operand(dst, Context::SlotOffset(Context::PREVIOUS_INDEX)));
    }
  } else {
    // Slot is in the current function context.  Move it into the
    // destination register in case we store into it (the write barrier
    // cannot be allowed to destroy the context in esi).
    mov(dst, esi);
  }

  // We should not have found a with context by walking the context chain
  // (i.e., the static scope chain and runtime context chain do not agree).
  // A variable occurring in such a scope should have slot type LOOKUP and
  // not CONTEXT.
  if (emit_debug_code()) {
    cmp(FieldOperand(dst, HeapObject::kMapOffset),
        isolate()->factory()->with_context_map());
    Check(not_equal, kVariableResolvedToWithContext);
  }
}


1853
void MacroAssembler::LoadGlobalProxy(Register dst) {
1854 1855
  mov(dst, NativeContextOperand());
  mov(dst, ContextOperand(dst, Context::GLOBAL_PROXY_INDEX));
1856 1857
}

danno@chromium.org's avatar
danno@chromium.org committed
1858
void MacroAssembler::LoadGlobalFunction(int index, Register function) {
1859 1860
  // Load the native context from the current context.
  mov(function, NativeContextOperand());
danno@chromium.org's avatar
danno@chromium.org committed
1861
  // Load the function from the native context.
1862
  mov(function, ContextOperand(function, index));
danno@chromium.org's avatar
danno@chromium.org committed
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
}


void MacroAssembler::LoadGlobalFunctionInitialMap(Register function,
                                                  Register map) {
  // Load the initial map.  The global functions all have initial maps.
  mov(map, FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
  if (emit_debug_code()) {
    Label ok, fail;
    CheckMap(map, isolate()->factory()->meta_map(), &fail, DO_SMI_CHECK);
    jmp(&ok);
    bind(&fail);
    Abort(kGlobalFunctionsMustHaveInitialMap);
    bind(&ok);
  }
}


// Store the value in register src in the safepoint register stack
// slot for register dst.
void MacroAssembler::StoreToSafepointRegisterSlot(Register dst, Register src) {
  mov(SafepointRegisterSlot(dst), src);
}


void MacroAssembler::StoreToSafepointRegisterSlot(Register dst, Immediate src) {
  mov(SafepointRegisterSlot(dst), src);
}


void MacroAssembler::LoadFromSafepointRegisterSlot(Register dst, Register src) {
  mov(dst, SafepointRegisterSlot(src));
}


Operand MacroAssembler::SafepointRegisterSlot(Register reg) {
  return Operand(esp, SafepointRegisterStackIndex(reg.code()) * kPointerSize);
}


int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
  // The registers are pushed starting with the lowest encoding,
  // which means that lowest encodings are furthest away from
  // the stack pointer.
1907
  DCHECK(reg_code >= 0 && reg_code < kNumSafepointRegisters);
danno@chromium.org's avatar
danno@chromium.org committed
1908 1909 1910 1911 1912 1913
  return kNumSafepointRegisters - reg_code - 1;
}


void MacroAssembler::LoadHeapObject(Register result,
                                    Handle<HeapObject> object) {
1914
  mov(result, object);
danno@chromium.org's avatar
danno@chromium.org committed
1915 1916 1917 1918
}


void MacroAssembler::CmpHeapObject(Register reg, Handle<HeapObject> object) {
1919
  cmp(reg, object);
danno@chromium.org's avatar
danno@chromium.org committed
1920 1921
}

1922
void MacroAssembler::PushHeapObject(Handle<HeapObject> object) { Push(object); }
danno@chromium.org's avatar
danno@chromium.org committed
1923

1924
void MacroAssembler::GetWeakValue(Register value, Handle<WeakCell> cell) {
1925 1926
  mov(value, cell);
  mov(value, FieldOperand(value, WeakCell::kValueOffset));
1927 1928 1929 1930 1931 1932
}


void MacroAssembler::LoadWeakValue(Register value, Handle<WeakCell> cell,
                                   Label* miss) {
  GetWeakValue(value, cell);
1933 1934 1935 1936
  JumpIfSmi(value, miss);
}


danno@chromium.org's avatar
danno@chromium.org committed
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
void MacroAssembler::Ret() {
  ret(0);
}


void MacroAssembler::Ret(int bytes_dropped, Register scratch) {
  if (is_uint16(bytes_dropped)) {
    ret(bytes_dropped);
  } else {
    pop(scratch);
    add(esp, Immediate(bytes_dropped));
    push(scratch);
    ret(0);
  }
}


void MacroAssembler::VerifyX87StackDepth(uint32_t depth) {
1955 1956 1957
  // Turn off the stack depth check when serializer is enabled to reduce the
  // code size.
  if (serializer_enabled()) return;
danno@chromium.org's avatar
danno@chromium.org committed
1958
  // Make sure the floating point stack is either empty or has depth items.
1959
  DCHECK(depth <= 7);
danno@chromium.org's avatar
danno@chromium.org committed
1960
  // This is very expensive.
1961
  DCHECK(FLAG_debug_code && FLAG_enable_slow_asserts);
danno@chromium.org's avatar
danno@chromium.org committed
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992

  // The top-of-stack (tos) is 7 if there is one item pushed.
  int tos = (8 - depth) % 8;
  const int kTopMask = 0x3800;
  push(eax);
  fwait();
  fnstsw_ax();
  and_(eax, kTopMask);
  shr(eax, 11);
  cmp(eax, Immediate(tos));
  Check(equal, kUnexpectedFPUStackDepthAfterInstruction);
  fnclex();
  pop(eax);
}


void MacroAssembler::Drop(int stack_elements) {
  if (stack_elements > 0) {
    add(esp, Immediate(stack_elements * kPointerSize));
  }
}


void MacroAssembler::Move(Register dst, Register src) {
  if (!dst.is(src)) {
    mov(dst, src);
  }
}


void MacroAssembler::Move(Register dst, const Immediate& x) {
1993
  if (x.is_zero() && RelocInfo::IsNone(x.rmode_)) {
danno@chromium.org's avatar
danno@chromium.org committed
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    xor_(dst, dst);  // Shorter than mov of 32-bit immediate 0.
  } else {
    mov(dst, x);
  }
}


void MacroAssembler::Move(const Operand& dst, const Immediate& x) {
  mov(dst, x);
}


2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
void MacroAssembler::Lzcnt(Register dst, const Operand& src) {
  // TODO(intel): Add support for LZCNT (with ABM/BMI1).
  Label not_zero_src;
  bsr(dst, src);
  j(not_zero, &not_zero_src, Label::kNear);
  Move(dst, Immediate(63));  // 63^31 == 32
  bind(&not_zero_src);
  xor_(dst, Immediate(31));  // for x in [0..31], 31^x == 31-x.
}


2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
void MacroAssembler::Tzcnt(Register dst, const Operand& src) {
  // TODO(intel): Add support for TZCNT (with ABM/BMI1).
  Label not_zero_src;
  bsf(dst, src);
  j(not_zero, &not_zero_src, Label::kNear);
  Move(dst, Immediate(32));  // The result of tzcnt is 32 if src = 0.
  bind(&not_zero_src);
}


2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
void MacroAssembler::Popcnt(Register dst, const Operand& src) {
  // TODO(intel): Add support for POPCNT (with POPCNT)
  // if (CpuFeatures::IsSupported(POPCNT)) {
  //   CpuFeatureScope scope(this, POPCNT);
  //   popcnt(dst, src);
  //   return;
  // }
  UNREACHABLE();
}


danno@chromium.org's avatar
danno@chromium.org committed
2038 2039 2040 2041 2042 2043 2044 2045
void MacroAssembler::SetCounter(StatsCounter* counter, int value) {
  if (FLAG_native_code_counters && counter->Enabled()) {
    mov(Operand::StaticVariable(ExternalReference(counter)), Immediate(value));
  }
}


void MacroAssembler::IncrementCounter(StatsCounter* counter, int value) {
2046
  DCHECK(value > 0);
danno@chromium.org's avatar
danno@chromium.org committed
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
  if (FLAG_native_code_counters && counter->Enabled()) {
    Operand operand = Operand::StaticVariable(ExternalReference(counter));
    if (value == 1) {
      inc(operand);
    } else {
      add(operand, Immediate(value));
    }
  }
}


void MacroAssembler::DecrementCounter(StatsCounter* counter, int value) {
2059
  DCHECK(value > 0);
danno@chromium.org's avatar
danno@chromium.org committed
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
  if (FLAG_native_code_counters && counter->Enabled()) {
    Operand operand = Operand::StaticVariable(ExternalReference(counter));
    if (value == 1) {
      dec(operand);
    } else {
      sub(operand, Immediate(value));
    }
  }
}


void MacroAssembler::IncrementCounter(Condition cc,
                                      StatsCounter* counter,
                                      int value) {
2074
  DCHECK(value > 0);
danno@chromium.org's avatar
danno@chromium.org committed
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
  if (FLAG_native_code_counters && counter->Enabled()) {
    Label skip;
    j(NegateCondition(cc), &skip);
    pushfd();
    IncrementCounter(counter, value);
    popfd();
    bind(&skip);
  }
}


void MacroAssembler::DecrementCounter(Condition cc,
                                      StatsCounter* counter,
                                      int value) {
2089
  DCHECK(value > 0);
danno@chromium.org's avatar
danno@chromium.org committed
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
  if (FLAG_native_code_counters && counter->Enabled()) {
    Label skip;
    j(NegateCondition(cc), &skip);
    pushfd();
    DecrementCounter(counter, value);
    popfd();
    bind(&skip);
  }
}


void MacroAssembler::Assert(Condition cc, BailoutReason reason) {
  if (emit_debug_code()) Check(cc, reason);
}



void MacroAssembler::Check(Condition cc, BailoutReason reason) {
  Label L;
  j(cc, &L);
  Abort(reason);
  // will not return here
  bind(&L);
}


void MacroAssembler::CheckStackAlignment() {
2117
  int frame_alignment = base::OS::ActivationFrameAlignment();
danno@chromium.org's avatar
danno@chromium.org committed
2118 2119
  int frame_alignment_mask = frame_alignment - 1;
  if (frame_alignment > kPointerSize) {
2120
    DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
danno@chromium.org's avatar
danno@chromium.org committed
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
    Label alignment_as_expected;
    test(esp, Immediate(frame_alignment_mask));
    j(zero, &alignment_as_expected);
    // Abort if stack is not aligned.
    int3();
    bind(&alignment_as_expected);
  }
}


void MacroAssembler::Abort(BailoutReason reason) {
#ifdef DEBUG
  const char* msg = GetBailoutReason(reason);
  if (msg != NULL) {
    RecordComment("Abort message: ");
    RecordComment(msg);
  }

  if (FLAG_trap_on_abort) {
    int3();
    return;
  }
#endif

2145 2146 2147 2148 2149
  // Check if Abort() has already been initialized.
  DCHECK(isolate()->builtins()->Abort()->IsHeapObject());

  Move(edx, Smi::FromInt(static_cast<int>(reason)));

danno@chromium.org's avatar
danno@chromium.org committed
2150 2151 2152 2153 2154
  // Disable stub call restrictions to always allow calls to abort.
  if (!has_frame_) {
    // We don't actually want to generate a pile of code for this, so just
    // claim there is a stack frame, without generating one.
    FrameScope scope(this, StackFrame::NONE);
2155
    Call(isolate()->builtins()->Abort(), RelocInfo::CODE_TARGET);
danno@chromium.org's avatar
danno@chromium.org committed
2156
  } else {
2157
    Call(isolate()->builtins()->Abort(), RelocInfo::CODE_TARGET);
danno@chromium.org's avatar
danno@chromium.org committed
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
  }
  // will not return here
  int3();
}


void MacroAssembler::LoadInstanceDescriptors(Register map,
                                             Register descriptors) {
  mov(descriptors, FieldOperand(map, Map::kDescriptorsOffset));
}


void MacroAssembler::NumberOfOwnDescriptors(Register dst, Register map) {
  mov(dst, FieldOperand(map, Map::kBitField3Offset));
  DecodeField<Map::NumberOfOwnDescriptorsBits>(dst);
}


2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
void MacroAssembler::LoadAccessor(Register dst, Register holder,
                                  int accessor_index,
                                  AccessorComponent accessor) {
  mov(dst, FieldOperand(holder, HeapObject::kMapOffset));
  LoadInstanceDescriptors(dst, dst);
  mov(dst, FieldOperand(dst, DescriptorArray::GetValueOffset(accessor_index)));
  int offset = accessor == ACCESSOR_GETTER ? AccessorPair::kGetterOffset
                                           : AccessorPair::kSetterOffset;
  mov(dst, FieldOperand(dst, offset));
}

2187 2188 2189 2190 2191
void MacroAssembler::JumpIfNotBothSequentialOneByteStrings(Register object1,
                                                           Register object2,
                                                           Register scratch1,
                                                           Register scratch2,
                                                           Label* failure) {
danno@chromium.org's avatar
danno@chromium.org committed
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
  // Check that both objects are not smis.
  STATIC_ASSERT(kSmiTag == 0);
  mov(scratch1, object1);
  and_(scratch1, object2);
  JumpIfSmi(scratch1, failure);

  // Load instance type for both strings.
  mov(scratch1, FieldOperand(object1, HeapObject::kMapOffset));
  mov(scratch2, FieldOperand(object2, HeapObject::kMapOffset));
  movzx_b(scratch1, FieldOperand(scratch1, Map::kInstanceTypeOffset));
  movzx_b(scratch2, FieldOperand(scratch2, Map::kInstanceTypeOffset));

2204 2205
  // Check that both are flat one-byte strings.
  const int kFlatOneByteStringMask =
danno@chromium.org's avatar
danno@chromium.org committed
2206
      kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask;
2207
  const int kFlatOneByteStringTag =
danno@chromium.org's avatar
danno@chromium.org committed
2208 2209
      kStringTag | kOneByteStringTag | kSeqStringTag;
  // Interleave bits from both instance types and compare them in one check.
2210 2211
  const int kShift = 8;
  DCHECK_EQ(0, kFlatOneByteStringMask & (kFlatOneByteStringMask << kShift));
2212 2213
  and_(scratch1, kFlatOneByteStringMask);
  and_(scratch2, kFlatOneByteStringMask);
2214 2215 2216
  shl(scratch2, kShift);
  or_(scratch1, scratch2);
  cmp(scratch1, kFlatOneByteStringTag | (kFlatOneByteStringTag << kShift));
danno@chromium.org's avatar
danno@chromium.org committed
2217 2218 2219 2220
  j(not_equal, failure);
}


2221 2222 2223
void MacroAssembler::JumpIfNotUniqueNameInstanceType(Operand operand,
                                                     Label* not_unique_name,
                                                     Label::Distance distance) {
danno@chromium.org's avatar
danno@chromium.org committed
2224 2225 2226 2227
  STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
  Label succeed;
  test(operand, Immediate(kIsNotStringMask | kIsNotInternalizedMask));
  j(zero, &succeed);
2228
  cmpb(operand, Immediate(SYMBOL_TYPE));
danno@chromium.org's avatar
danno@chromium.org committed
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
  j(not_equal, not_unique_name, distance);

  bind(&succeed);
}


void MacroAssembler::EmitSeqStringSetCharCheck(Register string,
                                               Register index,
                                               Register value,
                                               uint32_t encoding_mask) {
  Label is_object;
  JumpIfNotSmi(string, &is_object, Label::kNear);
  Abort(kNonObject);
  bind(&is_object);

  push(value);
  mov(value, FieldOperand(string, HeapObject::kMapOffset));
  movzx_b(value, FieldOperand(value, Map::kInstanceTypeOffset));

  and_(value, Immediate(kStringRepresentationMask | kStringEncodingMask));
  cmp(value, Immediate(encoding_mask));
  pop(value);
  Check(equal, kUnexpectedStringType);

  // The index is assumed to be untagged coming in, tag it to compare with the
  // string length without using a temp register, it is restored at the end of
  // this function.
  SmiTag(index);
  Check(no_overflow, kIndexIsTooLarge);

  cmp(index, FieldOperand(string, String::kLengthOffset));
  Check(less, kIndexIsTooLarge);

2262
  cmp(index, Immediate(Smi::kZero));
danno@chromium.org's avatar
danno@chromium.org committed
2263 2264 2265 2266 2267 2268 2269 2270
  Check(greater_equal, kIndexIsNegative);

  // Restore the index
  SmiUntag(index);
}


void MacroAssembler::PrepareCallCFunction(int num_arguments, Register scratch) {
2271
  int frame_alignment = base::OS::ActivationFrameAlignment();
danno@chromium.org's avatar
danno@chromium.org committed
2272 2273 2274 2275 2276
  if (frame_alignment != 0) {
    // Make stack end at alignment and make room for num_arguments words
    // and the original value of esp.
    mov(scratch, esp);
    sub(esp, Immediate((num_arguments + 1) * kPointerSize));
2277
    DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
danno@chromium.org's avatar
danno@chromium.org committed
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
    and_(esp, -frame_alignment);
    mov(Operand(esp, num_arguments * kPointerSize), scratch);
  } else {
    sub(esp, Immediate(num_arguments * kPointerSize));
  }
}


void MacroAssembler::CallCFunction(ExternalReference function,
                                   int num_arguments) {
  // Trashing eax is ok as it will be the return value.
  mov(eax, Immediate(function));
  CallCFunction(eax, num_arguments);
}


void MacroAssembler::CallCFunction(Register function,
                                   int num_arguments) {
2296
  DCHECK(has_frame());
danno@chromium.org's avatar
danno@chromium.org committed
2297 2298 2299 2300 2301 2302
  // Check stack alignment.
  if (emit_debug_code()) {
    CheckStackAlignment();
  }

  call(function);
2303
  if (base::OS::ActivationFrameAlignment() != 0) {
danno@chromium.org's avatar
danno@chromium.org committed
2304 2305 2306 2307 2308 2309 2310
    mov(esp, Operand(esp, num_arguments * kPointerSize));
  } else {
    add(esp, Immediate(num_arguments * kPointerSize));
  }
}


2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
#ifdef DEBUG
bool AreAliased(Register reg1,
                Register reg2,
                Register reg3,
                Register reg4,
                Register reg5,
                Register reg6,
                Register reg7,
                Register reg8) {
  int n_of_valid_regs = reg1.is_valid() + reg2.is_valid() +
      reg3.is_valid() + reg4.is_valid() + reg5.is_valid() + reg6.is_valid() +
      reg7.is_valid() + reg8.is_valid();

  RegList regs = 0;
  if (reg1.is_valid()) regs |= reg1.bit();
  if (reg2.is_valid()) regs |= reg2.bit();
  if (reg3.is_valid()) regs |= reg3.bit();
  if (reg4.is_valid()) regs |= reg4.bit();
  if (reg5.is_valid()) regs |= reg5.bit();
  if (reg6.is_valid()) regs |= reg6.bit();
  if (reg7.is_valid()) regs |= reg7.bit();
  if (reg8.is_valid()) regs |= reg8.bit();
  int n_of_non_aliasing_regs = NumRegs(regs);

  return n_of_valid_regs != n_of_non_aliasing_regs;
danno@chromium.org's avatar
danno@chromium.org committed
2336
}
2337
#endif
danno@chromium.org's avatar
danno@chromium.org committed
2338 2339


2340
CodePatcher::CodePatcher(Isolate* isolate, byte* address, int size)
danno@chromium.org's avatar
danno@chromium.org committed
2341 2342
    : address_(address),
      size_(size),
2343
      masm_(isolate, address, size + Assembler::kGap, CodeObjectRequired::kNo) {
danno@chromium.org's avatar
danno@chromium.org committed
2344 2345 2346
  // Create a new macro assembler pointing to the address of the code to patch.
  // The size is adjusted with kGap on order for the assembler to generate size
  // bytes of instructions without failing with buffer size constraints.
2347
  DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
danno@chromium.org's avatar
danno@chromium.org committed
2348 2349 2350 2351 2352
}


CodePatcher::~CodePatcher() {
  // Indicate that code has changed.
2353
  Assembler::FlushICache(masm_.isolate(), address_, size_);
danno@chromium.org's avatar
danno@chromium.org committed
2354 2355

  // Check that the code was patched as expected.
2356 2357
  DCHECK(masm_.pc_ == address_ + size_);
  DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
danno@chromium.org's avatar
danno@chromium.org committed
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
}


void MacroAssembler::CheckPageFlag(
    Register object,
    Register scratch,
    int mask,
    Condition cc,
    Label* condition_met,
    Label::Distance condition_met_distance) {
2368
  DCHECK(cc == zero || cc == not_zero);
danno@chromium.org's avatar
danno@chromium.org committed
2369 2370 2371 2372 2373 2374 2375
  if (scratch.is(object)) {
    and_(scratch, Immediate(~Page::kPageAlignmentMask));
  } else {
    mov(scratch, Immediate(~Page::kPageAlignmentMask));
    and_(scratch, object);
  }
  if (mask < (1 << kBitsPerByte)) {
2376
    test_b(Operand(scratch, MemoryChunk::kFlagsOffset), Immediate(mask));
danno@chromium.org's avatar
danno@chromium.org committed
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
  } else {
    test(Operand(scratch, MemoryChunk::kFlagsOffset), Immediate(mask));
  }
  j(cc, condition_met, condition_met_distance);
}


void MacroAssembler::CheckPageFlagForMap(
    Handle<Map> map,
    int mask,
    Condition cc,
    Label* condition_met,
    Label::Distance condition_met_distance) {
2390
  DCHECK(cc == zero || cc == not_zero);
danno@chromium.org's avatar
danno@chromium.org committed
2391
  Page* page = Page::FromAddress(map->address());
2392
  DCHECK(!serializer_enabled());  // Serializer cannot match page_flags.
danno@chromium.org's avatar
danno@chromium.org committed
2393 2394 2395
  ExternalReference reference(ExternalReference::page_flags(page));
  // The inlined static address check of the page's flags relies
  // on maps never being compacted.
2396
  DCHECK(!isolate()->heap()->mark_compact_collector()->
danno@chromium.org's avatar
danno@chromium.org committed
2397 2398
         IsOnEvacuationCandidate(*map));
  if (mask < (1 << kBitsPerByte)) {
2399
    test_b(Operand::StaticVariable(reference), Immediate(mask));
danno@chromium.org's avatar
danno@chromium.org committed
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
  } else {
    test(Operand::StaticVariable(reference), Immediate(mask));
  }
  j(cc, condition_met, condition_met_distance);
}


void MacroAssembler::JumpIfBlack(Register object,
                                 Register scratch0,
                                 Register scratch1,
                                 Label* on_black,
                                 Label::Distance on_black_near) {
2412 2413 2414
  HasColor(object, scratch0, scratch1, on_black, on_black_near, 1,
           1);  // kBlackBitPattern.
  DCHECK(strcmp(Marking::kBlackBitPattern, "11") == 0);
danno@chromium.org's avatar
danno@chromium.org committed
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
}


void MacroAssembler::HasColor(Register object,
                              Register bitmap_scratch,
                              Register mask_scratch,
                              Label* has_color,
                              Label::Distance has_color_distance,
                              int first_bit,
                              int second_bit) {
2425
  DCHECK(!AreAliased(object, bitmap_scratch, mask_scratch, ecx));
danno@chromium.org's avatar
danno@chromium.org committed
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438

  GetMarkBits(object, bitmap_scratch, mask_scratch);

  Label other_color, word_boundary;
  test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
  j(first_bit == 1 ? zero : not_zero, &other_color, Label::kNear);
  add(mask_scratch, mask_scratch);  // Shift left 1 by adding.
  j(zero, &word_boundary, Label::kNear);
  test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
  j(second_bit == 1 ? not_zero : zero, has_color, has_color_distance);
  jmp(&other_color, Label::kNear);

  bind(&word_boundary);
2439 2440
  test_b(Operand(bitmap_scratch, MemoryChunk::kHeaderSize + kPointerSize),
         Immediate(1));
danno@chromium.org's avatar
danno@chromium.org committed
2441 2442 2443 2444 2445 2446 2447 2448 2449

  j(second_bit == 1 ? not_zero : zero, has_color, has_color_distance);
  bind(&other_color);
}


void MacroAssembler::GetMarkBits(Register addr_reg,
                                 Register bitmap_reg,
                                 Register mask_reg) {
2450
  DCHECK(!AreAliased(addr_reg, mask_reg, bitmap_reg, ecx));
danno@chromium.org's avatar
danno@chromium.org committed
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
  mov(bitmap_reg, Immediate(~Page::kPageAlignmentMask));
  and_(bitmap_reg, addr_reg);
  mov(ecx, addr_reg);
  int shift =
      Bitmap::kBitsPerCellLog2 + kPointerSizeLog2 - Bitmap::kBytesPerCellLog2;
  shr(ecx, shift);
  and_(ecx,
       (Page::kPageAlignmentMask >> shift) & ~(Bitmap::kBytesPerCell - 1));

  add(bitmap_reg, ecx);
  mov(ecx, addr_reg);
  shr(ecx, kPointerSizeLog2);
  and_(ecx, (1 << Bitmap::kBitsPerCellLog2) - 1);
  mov(mask_reg, Immediate(1));
  shl_cl(mask_reg);
}


hpayer's avatar
hpayer committed
2469 2470 2471
void MacroAssembler::JumpIfWhite(Register value, Register bitmap_scratch,
                                 Register mask_scratch, Label* value_is_white,
                                 Label::Distance distance) {
2472
  DCHECK(!AreAliased(value, bitmap_scratch, mask_scratch, ecx));
danno@chromium.org's avatar
danno@chromium.org committed
2473 2474 2475
  GetMarkBits(value, bitmap_scratch, mask_scratch);

  // If the value is black or grey we don't need to do anything.
2476
  DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
2477 2478
  DCHECK(strcmp(Marking::kBlackBitPattern, "11") == 0);
  DCHECK(strcmp(Marking::kGreyBitPattern, "10") == 0);
2479
  DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
danno@chromium.org's avatar
danno@chromium.org committed
2480 2481 2482 2483

  // Since both black and grey have a 1 in the first position and white does
  // not have a 1 there we only need to check one bit.
  test(mask_scratch, Operand(bitmap_scratch, MemoryChunk::kHeaderSize));
2484
  j(zero, value_is_white, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
}


void MacroAssembler::EnumLength(Register dst, Register map) {
  STATIC_ASSERT(Map::EnumLengthBits::kShift == 0);
  mov(dst, FieldOperand(map, Map::kBitField3Offset));
  and_(dst, Immediate(Map::EnumLengthBits::kMask));
  SmiTag(dst);
}


void MacroAssembler::CheckEnumCache(Label* call_runtime) {
  Label next, start;
  mov(ecx, eax);

  // Check if the enum length field is properly initialized, indicating that
  // there is an enum cache.
  mov(ebx, FieldOperand(ecx, HeapObject::kMapOffset));

  EnumLength(edx, ebx);
  cmp(edx, Immediate(Smi::FromInt(kInvalidEnumCacheSentinel)));
  j(equal, call_runtime);

  jmp(&start);

  bind(&next);
  mov(ebx, FieldOperand(ecx, HeapObject::kMapOffset));

  // For all objects but the receiver, check that the cache is empty.
  EnumLength(edx, ebx);
2515
  cmp(edx, Immediate(Smi::kZero));
danno@chromium.org's avatar
danno@chromium.org committed
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
  j(not_equal, call_runtime);

  bind(&start);

  // Check that there are no elements. Register rcx contains the current JS
  // object we've reached through the prototype chain.
  Label no_elements;
  mov(ecx, FieldOperand(ecx, JSObject::kElementsOffset));
  cmp(ecx, isolate()->factory()->empty_fixed_array());
  j(equal, &no_elements);

  // Second chance, the object may be using the empty slow element dictionary.
  cmp(ecx, isolate()->factory()->empty_slow_element_dictionary());
  j(not_equal, call_runtime);

  bind(&no_elements);
  mov(ecx, FieldOperand(ebx, Map::kPrototypeOffset));
  cmp(ecx, isolate()->factory()->null_value());
  j(not_equal, &next);
}


void MacroAssembler::TestJSArrayForAllocationMemento(
    Register receiver_reg,
    Register scratch_reg,
    Label* no_memento_found) {
2542 2543
  Label map_check;
  Label top_check;
danno@chromium.org's avatar
danno@chromium.org committed
2544 2545
  ExternalReference new_space_allocation_top =
      ExternalReference::new_space_allocation_top_address(isolate());
2546
  const int kMementoMapOffset = JSArray::kSize - kHeapObjectTag;
2547 2548
  const int kMementoLastWordOffset =
      kMementoMapOffset + AllocationMemento::kSize - kPointerSize;
2549 2550 2551 2552 2553

  // Bail out if the object is not in new space.
  JumpIfNotInNewSpace(receiver_reg, scratch_reg, no_memento_found);
  // If the object is in new space, we need to check whether it is on the same
  // page as the current top.
2554
  lea(scratch_reg, Operand(receiver_reg, kMementoLastWordOffset));
2555 2556 2557 2558 2559 2560
  xor_(scratch_reg, Operand::StaticVariable(new_space_allocation_top));
  test(scratch_reg, Immediate(~Page::kPageAlignmentMask));
  j(zero, &top_check);
  // The object is on a different page than allocation top. Bail out if the
  // object sits on the page boundary as no memento can follow and we cannot
  // touch the memory following it.
2561
  lea(scratch_reg, Operand(receiver_reg, kMementoLastWordOffset));
2562 2563 2564 2565 2566 2567 2568 2569
  xor_(scratch_reg, receiver_reg);
  test(scratch_reg, Immediate(~Page::kPageAlignmentMask));
  j(not_zero, no_memento_found);
  // Continue with the actual map check.
  jmp(&map_check);
  // If top is on the same page as the current object, we need to check whether
  // we are below top.
  bind(&top_check);
2570
  lea(scratch_reg, Operand(receiver_reg, kMementoLastWordOffset));
danno@chromium.org's avatar
danno@chromium.org committed
2571
  cmp(scratch_reg, Operand::StaticVariable(new_space_allocation_top));
2572
  j(greater_equal, no_memento_found);
2573 2574 2575 2576
  // Memento map check.
  bind(&map_check);
  mov(scratch_reg, Operand(receiver_reg, kMementoMapOffset));
  cmp(scratch_reg, Immediate(isolate()->factory()->allocation_memento_map()));
danno@chromium.org's avatar
danno@chromium.org committed
2577 2578 2579
}

void MacroAssembler::TruncatingDiv(Register dividend, int32_t divisor) {
2580 2581
  DCHECK(!dividend.is(eax));
  DCHECK(!dividend.is(edx));
2582 2583 2584
  base::MagicNumbersForDivision<uint32_t> mag =
      base::SignedDivisionByConstant(static_cast<uint32_t>(divisor));
  mov(eax, Immediate(mag.multiplier));
danno@chromium.org's avatar
danno@chromium.org committed
2585
  imul(dividend);
2586 2587 2588 2589
  bool neg = (mag.multiplier & (static_cast<uint32_t>(1) << 31)) != 0;
  if (divisor > 0 && neg) add(edx, dividend);
  if (divisor < 0 && !neg && mag.multiplier > 0) sub(edx, dividend);
  if (mag.shift > 0) sar(edx, mag.shift);
danno@chromium.org's avatar
danno@chromium.org committed
2590 2591 2592 2593 2594 2595
  mov(eax, dividend);
  shr(eax, 31);
  add(edx, eax);
}


2596 2597
}  // namespace internal
}  // namespace v8
danno@chromium.org's avatar
danno@chromium.org committed
2598 2599

#endif  // V8_TARGET_ARCH_X87