1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "utilities/macros.hpp"
  43 #if INCLUDE_ALL_GCS
  44 #include "gc/g1/g1CollectedHeap.inline.hpp"
  45 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  46 #include "gc/g1/heapRegion.hpp"
  47 #endif // INCLUDE_ALL_GCS
  48 
  49 #ifdef PRODUCT
  50 #define BLOCK_COMMENT(str) /* nothing */
  51 #define STOP(error) stop(error)
  52 #else
  53 #define BLOCK_COMMENT(str) block_comment(str)
  54 #define STOP(error) block_comment(error); stop(error)
  55 #endif
  56 
  57 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  58 
  59 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  60 
  61 #ifdef ASSERT
  62 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  63 #endif
  64 
  65 static Assembler::Condition reverse[] = {
  66     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  67     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  68     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  69     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  70     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  71     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  72     Assembler::above          /* belowEqual    = 0x6 */ ,
  73     Assembler::belowEqual     /* above         = 0x7 */ ,
  74     Assembler::positive       /* negative      = 0x8 */ ,
  75     Assembler::negative       /* positive      = 0x9 */ ,
  76     Assembler::noParity       /* parity        = 0xa */ ,
  77     Assembler::parity         /* noParity      = 0xb */ ,
  78     Assembler::greaterEqual   /* less          = 0xc */ ,
  79     Assembler::less           /* greaterEqual  = 0xd */ ,
  80     Assembler::greater        /* lessEqual     = 0xe */ ,
  81     Assembler::lessEqual      /* greater       = 0xf, */
  82 
  83 };
  84 
  85 
  86 // Implementation of MacroAssembler
  87 
  88 // First all the versions that have distinct versions depending on 32/64 bit
  89 // Unless the difference is trivial (1 line or so).
  90 
  91 #ifndef _LP64
  92 
  93 // 32bit versions
  94 
  95 Address MacroAssembler::as_Address(AddressLiteral adr) {
  96   return Address(adr.target(), adr.rspec());
  97 }
  98 
  99 Address MacroAssembler::as_Address(ArrayAddress adr) {
 100   return Address::make_array(adr);
 101 }
 102 
 103 void MacroAssembler::call_VM_leaf_base(address entry_point,
 104                                        int number_of_arguments) {
 105   call(RuntimeAddress(entry_point));
 106   increment(rsp, number_of_arguments * wordSize);
 107 }
 108 
 109 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 110   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 111 }
 112 
 113 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 114   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 115 }
 116 
 117 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 118   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 122   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::extend_sign(Register hi, Register lo) {
 126   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 127   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 128     cdql();
 129   } else {
 130     movl(hi, lo);
 131     sarl(hi, 31);
 132   }
 133 }
 134 
 135 void MacroAssembler::jC2(Register tmp, Label& L) {
 136   // set parity bit if FPU flag C2 is set (via rax)
 137   save_rax(tmp);
 138   fwait(); fnstsw_ax();
 139   sahf();
 140   restore_rax(tmp);
 141   // branch
 142   jcc(Assembler::parity, L);
 143 }
 144 
 145 void MacroAssembler::jnC2(Register tmp, Label& L) {
 146   // set parity bit if FPU flag C2 is set (via rax)
 147   save_rax(tmp);
 148   fwait(); fnstsw_ax();
 149   sahf();
 150   restore_rax(tmp);
 151   // branch
 152   jcc(Assembler::noParity, L);
 153 }
 154 
 155 // 32bit can do a case table jump in one instruction but we no longer allow the base
 156 // to be installed in the Address class
 157 void MacroAssembler::jump(ArrayAddress entry) {
 158   jmp(as_Address(entry));
 159 }
 160 
 161 // Note: y_lo will be destroyed
 162 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 163   // Long compare for Java (semantics as described in JVM spec.)
 164   Label high, low, done;
 165 
 166   cmpl(x_hi, y_hi);
 167   jcc(Assembler::less, low);
 168   jcc(Assembler::greater, high);
 169   // x_hi is the return register
 170   xorl(x_hi, x_hi);
 171   cmpl(x_lo, y_lo);
 172   jcc(Assembler::below, low);
 173   jcc(Assembler::equal, done);
 174 
 175   bind(high);
 176   xorl(x_hi, x_hi);
 177   increment(x_hi);
 178   jmp(done);
 179 
 180   bind(low);
 181   xorl(x_hi, x_hi);
 182   decrementl(x_hi);
 183 
 184   bind(done);
 185 }
 186 
 187 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 188     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 189 }
 190 
 191 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 192   // leal(dst, as_Address(adr));
 193   // see note in movl as to why we must use a move
 194   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 195 }
 196 
 197 void MacroAssembler::leave() {
 198   mov(rsp, rbp);
 199   pop(rbp);
 200 }
 201 
 202 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 203   // Multiplication of two Java long values stored on the stack
 204   // as illustrated below. Result is in rdx:rax.
 205   //
 206   // rsp ---> [  ??  ] \               \
 207   //            ....    | y_rsp_offset  |
 208   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 209   //          [ y_hi ]                  | (in bytes)
 210   //            ....                    |
 211   //          [ x_lo ]                 /
 212   //          [ x_hi ]
 213   //            ....
 214   //
 215   // Basic idea: lo(result) = lo(x_lo * y_lo)
 216   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 217   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 218   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 219   Label quick;
 220   // load x_hi, y_hi and check if quick
 221   // multiplication is possible
 222   movl(rbx, x_hi);
 223   movl(rcx, y_hi);
 224   movl(rax, rbx);
 225   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 226   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 227   // do full multiplication
 228   // 1st step
 229   mull(y_lo);                                    // x_hi * y_lo
 230   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 231   // 2nd step
 232   movl(rax, x_lo);
 233   mull(rcx);                                     // x_lo * y_hi
 234   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 235   // 3rd step
 236   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 237   movl(rax, x_lo);
 238   mull(y_lo);                                    // x_lo * y_lo
 239   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 240 }
 241 
 242 void MacroAssembler::lneg(Register hi, Register lo) {
 243   negl(lo);
 244   adcl(hi, 0);
 245   negl(hi);
 246 }
 247 
 248 void MacroAssembler::lshl(Register hi, Register lo) {
 249   // Java shift left long support (semantics as described in JVM spec., p.305)
 250   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 251   // shift value is in rcx !
 252   assert(hi != rcx, "must not use rcx");
 253   assert(lo != rcx, "must not use rcx");
 254   const Register s = rcx;                        // shift count
 255   const int      n = BitsPerWord;
 256   Label L;
 257   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 258   cmpl(s, n);                                    // if (s < n)
 259   jcc(Assembler::less, L);                       // else (s >= n)
 260   movl(hi, lo);                                  // x := x << n
 261   xorl(lo, lo);
 262   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 263   bind(L);                                       // s (mod n) < n
 264   shldl(hi, lo);                                 // x := x << s
 265   shll(lo);
 266 }
 267 
 268 
 269 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 270   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 271   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 272   assert(hi != rcx, "must not use rcx");
 273   assert(lo != rcx, "must not use rcx");
 274   const Register s = rcx;                        // shift count
 275   const int      n = BitsPerWord;
 276   Label L;
 277   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 278   cmpl(s, n);                                    // if (s < n)
 279   jcc(Assembler::less, L);                       // else (s >= n)
 280   movl(lo, hi);                                  // x := x >> n
 281   if (sign_extension) sarl(hi, 31);
 282   else                xorl(hi, hi);
 283   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 284   bind(L);                                       // s (mod n) < n
 285   shrdl(lo, hi);                                 // x := x >> s
 286   if (sign_extension) sarl(hi);
 287   else                shrl(hi);
 288 }
 289 
 290 void MacroAssembler::movoop(Register dst, jobject obj) {
 291   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 292 }
 293 
 294 void MacroAssembler::movoop(Address dst, jobject obj) {
 295   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 296 }
 297 
 298 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 299   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 300 }
 301 
 302 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 303   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 304 }
 305 
 306 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 307   // scratch register is not used,
 308   // it is defined to match parameters of 64-bit version of this method.
 309   if (src.is_lval()) {
 310     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 311   } else {
 312     movl(dst, as_Address(src));
 313   }
 314 }
 315 
 316 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 317   movl(as_Address(dst), src);
 318 }
 319 
 320 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 321   movl(dst, as_Address(src));
 322 }
 323 
 324 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 325 void MacroAssembler::movptr(Address dst, intptr_t src) {
 326   movl(dst, src);
 327 }
 328 
 329 
 330 void MacroAssembler::pop_callee_saved_registers() {
 331   pop(rcx);
 332   pop(rdx);
 333   pop(rdi);
 334   pop(rsi);
 335 }
 336 
 337 void MacroAssembler::pop_fTOS() {
 338   fld_d(Address(rsp, 0));
 339   addl(rsp, 2 * wordSize);
 340 }
 341 
 342 void MacroAssembler::push_callee_saved_registers() {
 343   push(rsi);
 344   push(rdi);
 345   push(rdx);
 346   push(rcx);
 347 }
 348 
 349 void MacroAssembler::push_fTOS() {
 350   subl(rsp, 2 * wordSize);
 351   fstp_d(Address(rsp, 0));
 352 }
 353 
 354 
 355 void MacroAssembler::pushoop(jobject obj) {
 356   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 357 }
 358 
 359 void MacroAssembler::pushklass(Metadata* obj) {
 360   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 361 }
 362 
 363 void MacroAssembler::pushptr(AddressLiteral src) {
 364   if (src.is_lval()) {
 365     push_literal32((int32_t)src.target(), src.rspec());
 366   } else {
 367     pushl(as_Address(src));
 368   }
 369 }
 370 
 371 void MacroAssembler::set_word_if_not_zero(Register dst) {
 372   xorl(dst, dst);
 373   set_byte_if_not_zero(dst);
 374 }
 375 
 376 static void pass_arg0(MacroAssembler* masm, Register arg) {
 377   masm->push(arg);
 378 }
 379 
 380 static void pass_arg1(MacroAssembler* masm, Register arg) {
 381   masm->push(arg);
 382 }
 383 
 384 static void pass_arg2(MacroAssembler* masm, Register arg) {
 385   masm->push(arg);
 386 }
 387 
 388 static void pass_arg3(MacroAssembler* masm, Register arg) {
 389   masm->push(arg);
 390 }
 391 
 392 #ifndef PRODUCT
 393 extern "C" void findpc(intptr_t x);
 394 #endif
 395 
 396 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 397   // In order to get locks to work, we need to fake a in_VM state
 398   JavaThread* thread = JavaThread::current();
 399   JavaThreadState saved_state = thread->thread_state();
 400   thread->set_thread_state(_thread_in_vm);
 401   if (ShowMessageBoxOnError) {
 402     JavaThread* thread = JavaThread::current();
 403     JavaThreadState saved_state = thread->thread_state();
 404     thread->set_thread_state(_thread_in_vm);
 405     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 406       ttyLocker ttyl;
 407       BytecodeCounter::print();
 408     }
 409     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 410     // This is the value of eip which points to where verify_oop will return.
 411     if (os::message_box(msg, "Execution stopped, print registers?")) {
 412       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 413       BREAKPOINT;
 414     }
 415   } else {
 416     ttyLocker ttyl;
 417     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 418   }
 419   // Don't assert holding the ttyLock
 420     assert(false, err_msg("DEBUG MESSAGE: %s", msg));
 421   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 422 }
 423 
 424 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 425   ttyLocker ttyl;
 426   FlagSetting fs(Debugging, true);
 427   tty->print_cr("eip = 0x%08x", eip);
 428 #ifndef PRODUCT
 429   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 430     tty->cr();
 431     findpc(eip);
 432     tty->cr();
 433   }
 434 #endif
 435 #define PRINT_REG(rax) \
 436   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 437   PRINT_REG(rax);
 438   PRINT_REG(rbx);
 439   PRINT_REG(rcx);
 440   PRINT_REG(rdx);
 441   PRINT_REG(rdi);
 442   PRINT_REG(rsi);
 443   PRINT_REG(rbp);
 444   PRINT_REG(rsp);
 445 #undef PRINT_REG
 446   // Print some words near top of staack.
 447   int* dump_sp = (int*) rsp;
 448   for (int col1 = 0; col1 < 8; col1++) {
 449     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 450     os::print_location(tty, *dump_sp++);
 451   }
 452   for (int row = 0; row < 16; row++) {
 453     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 454     for (int col = 0; col < 8; col++) {
 455       tty->print(" 0x%08x", *dump_sp++);
 456     }
 457     tty->cr();
 458   }
 459   // Print some instructions around pc:
 460   Disassembler::decode((address)eip-64, (address)eip);
 461   tty->print_cr("--------");
 462   Disassembler::decode((address)eip, (address)eip+32);
 463 }
 464 
 465 void MacroAssembler::stop(const char* msg) {
 466   ExternalAddress message((address)msg);
 467   // push address of message
 468   pushptr(message.addr());
 469   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 470   pusha();                                            // push registers
 471   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 472   hlt();
 473 }
 474 
 475 void MacroAssembler::warn(const char* msg) {
 476   push_CPU_state();
 477 
 478   ExternalAddress message((address) msg);
 479   // push address of message
 480   pushptr(message.addr());
 481 
 482   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 483   addl(rsp, wordSize);       // discard argument
 484   pop_CPU_state();
 485 }
 486 
 487 void MacroAssembler::print_state() {
 488   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 489   pusha();                                            // push registers
 490 
 491   push_CPU_state();
 492   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 493   pop_CPU_state();
 494 
 495   popa();
 496   addl(rsp, wordSize);
 497 }
 498 
 499 #else // _LP64
 500 
 501 // 64 bit versions
 502 
 503 Address MacroAssembler::as_Address(AddressLiteral adr) {
 504   // amd64 always does this as a pc-rel
 505   // we can be absolute or disp based on the instruction type
 506   // jmp/call are displacements others are absolute
 507   assert(!adr.is_lval(), "must be rval");
 508   assert(reachable(adr), "must be");
 509   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 510 
 511 }
 512 
 513 Address MacroAssembler::as_Address(ArrayAddress adr) {
 514   AddressLiteral base = adr.base();
 515   lea(rscratch1, base);
 516   Address index = adr.index();
 517   assert(index._disp == 0, "must not have disp"); // maybe it can?
 518   Address array(rscratch1, index._index, index._scale, index._disp);
 519   return array;
 520 }
 521 
 522 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 523   Label L, E;
 524 
 525 #ifdef _WIN64
 526   // Windows always allocates space for it's register args
 527   assert(num_args <= 4, "only register arguments supported");
 528   subq(rsp,  frame::arg_reg_save_area_bytes);
 529 #endif
 530 
 531   // Align stack if necessary
 532   testl(rsp, 15);
 533   jcc(Assembler::zero, L);
 534 
 535   subq(rsp, 8);
 536   {
 537     call(RuntimeAddress(entry_point));
 538   }
 539   addq(rsp, 8);
 540   jmp(E);
 541 
 542   bind(L);
 543   {
 544     call(RuntimeAddress(entry_point));
 545   }
 546 
 547   bind(E);
 548 
 549 #ifdef _WIN64
 550   // restore stack pointer
 551   addq(rsp, frame::arg_reg_save_area_bytes);
 552 #endif
 553 
 554 }
 555 
 556 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 557   assert(!src2.is_lval(), "should use cmpptr");
 558 
 559   if (reachable(src2)) {
 560     cmpq(src1, as_Address(src2));
 561   } else {
 562     lea(rscratch1, src2);
 563     Assembler::cmpq(src1, Address(rscratch1, 0));
 564   }
 565 }
 566 
 567 int MacroAssembler::corrected_idivq(Register reg) {
 568   // Full implementation of Java ldiv and lrem; checks for special
 569   // case as described in JVM spec., p.243 & p.271.  The function
 570   // returns the (pc) offset of the idivl instruction - may be needed
 571   // for implicit exceptions.
 572   //
 573   //         normal case                           special case
 574   //
 575   // input : rax: dividend                         min_long
 576   //         reg: divisor   (may not be eax/edx)   -1
 577   //
 578   // output: rax: quotient  (= rax idiv reg)       min_long
 579   //         rdx: remainder (= rax irem reg)       0
 580   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 581   static const int64_t min_long = 0x8000000000000000;
 582   Label normal_case, special_case;
 583 
 584   // check for special case
 585   cmp64(rax, ExternalAddress((address) &min_long));
 586   jcc(Assembler::notEqual, normal_case);
 587   xorl(rdx, rdx); // prepare rdx for possible special case (where
 588                   // remainder = 0)
 589   cmpq(reg, -1);
 590   jcc(Assembler::equal, special_case);
 591 
 592   // handle normal case
 593   bind(normal_case);
 594   cdqq();
 595   int idivq_offset = offset();
 596   idivq(reg);
 597 
 598   // normal and special case exit
 599   bind(special_case);
 600 
 601   return idivq_offset;
 602 }
 603 
 604 void MacroAssembler::decrementq(Register reg, int value) {
 605   if (value == min_jint) { subq(reg, value); return; }
 606   if (value <  0) { incrementq(reg, -value); return; }
 607   if (value == 0) {                        ; return; }
 608   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 609   /* else */      { subq(reg, value)       ; return; }
 610 }
 611 
 612 void MacroAssembler::decrementq(Address dst, int value) {
 613   if (value == min_jint) { subq(dst, value); return; }
 614   if (value <  0) { incrementq(dst, -value); return; }
 615   if (value == 0) {                        ; return; }
 616   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 617   /* else */      { subq(dst, value)       ; return; }
 618 }
 619 
 620 void MacroAssembler::incrementq(AddressLiteral dst) {
 621   if (reachable(dst)) {
 622     incrementq(as_Address(dst));
 623   } else {
 624     lea(rscratch1, dst);
 625     incrementq(Address(rscratch1, 0));
 626   }
 627 }
 628 
 629 void MacroAssembler::incrementq(Register reg, int value) {
 630   if (value == min_jint) { addq(reg, value); return; }
 631   if (value <  0) { decrementq(reg, -value); return; }
 632   if (value == 0) {                        ; return; }
 633   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 634   /* else */      { addq(reg, value)       ; return; }
 635 }
 636 
 637 void MacroAssembler::incrementq(Address dst, int value) {
 638   if (value == min_jint) { addq(dst, value); return; }
 639   if (value <  0) { decrementq(dst, -value); return; }
 640   if (value == 0) {                        ; return; }
 641   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 642   /* else */      { addq(dst, value)       ; return; }
 643 }
 644 
 645 // 32bit can do a case table jump in one instruction but we no longer allow the base
 646 // to be installed in the Address class
 647 void MacroAssembler::jump(ArrayAddress entry) {
 648   lea(rscratch1, entry.base());
 649   Address dispatch = entry.index();
 650   assert(dispatch._base == noreg, "must be");
 651   dispatch._base = rscratch1;
 652   jmp(dispatch);
 653 }
 654 
 655 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 656   ShouldNotReachHere(); // 64bit doesn't use two regs
 657   cmpq(x_lo, y_lo);
 658 }
 659 
 660 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 661     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 662 }
 663 
 664 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 665   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 666   movptr(dst, rscratch1);
 667 }
 668 
 669 void MacroAssembler::leave() {
 670   // %%% is this really better? Why not on 32bit too?
 671   emit_int8((unsigned char)0xC9); // LEAVE
 672 }
 673 
 674 void MacroAssembler::lneg(Register hi, Register lo) {
 675   ShouldNotReachHere(); // 64bit doesn't use two regs
 676   negq(lo);
 677 }
 678 
 679 void MacroAssembler::movoop(Register dst, jobject obj) {
 680   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 681 }
 682 
 683 void MacroAssembler::movoop(Address dst, jobject obj) {
 684   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 685   movq(dst, rscratch1);
 686 }
 687 
 688 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 689   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 690 }
 691 
 692 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 693   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 694   movq(dst, rscratch1);
 695 }
 696 
 697 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 698   if (src.is_lval()) {
 699     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 700   } else {
 701     if (reachable(src)) {
 702       movq(dst, as_Address(src));
 703     } else {
 704       lea(scratch, src);
 705       movq(dst, Address(scratch, 0));
 706     }
 707   }
 708 }
 709 
 710 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 711   movq(as_Address(dst), src);
 712 }
 713 
 714 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 715   movq(dst, as_Address(src));
 716 }
 717 
 718 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 719 void MacroAssembler::movptr(Address dst, intptr_t src) {
 720   mov64(rscratch1, src);
 721   movq(dst, rscratch1);
 722 }
 723 
 724 // These are mostly for initializing NULL
 725 void MacroAssembler::movptr(Address dst, int32_t src) {
 726   movslq(dst, src);
 727 }
 728 
 729 void MacroAssembler::movptr(Register dst, int32_t src) {
 730   mov64(dst, (intptr_t)src);
 731 }
 732 
 733 void MacroAssembler::pushoop(jobject obj) {
 734   movoop(rscratch1, obj);
 735   push(rscratch1);
 736 }
 737 
 738 void MacroAssembler::pushklass(Metadata* obj) {
 739   mov_metadata(rscratch1, obj);
 740   push(rscratch1);
 741 }
 742 
 743 void MacroAssembler::pushptr(AddressLiteral src) {
 744   lea(rscratch1, src);
 745   if (src.is_lval()) {
 746     push(rscratch1);
 747   } else {
 748     pushq(Address(rscratch1, 0));
 749   }
 750 }
 751 
 752 void MacroAssembler::reset_last_Java_frame(bool clear_fp,
 753                                            bool clear_pc) {
 754   // we must set sp to zero to clear frame
 755   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 756   // must clear fp, so that compiled frames are not confused; it is
 757   // possible that we need it only for debugging
 758   if (clear_fp) {
 759     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 760   }
 761 
 762   if (clear_pc) {
 763     movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 764   }
 765 }
 766 
 767 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 768                                          Register last_java_fp,
 769                                          address  last_java_pc) {
 770   // determine last_java_sp register
 771   if (!last_java_sp->is_valid()) {
 772     last_java_sp = rsp;
 773   }
 774 
 775   // last_java_fp is optional
 776   if (last_java_fp->is_valid()) {
 777     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 778            last_java_fp);
 779   }
 780 
 781   // last_java_pc is optional
 782   if (last_java_pc != NULL) {
 783     Address java_pc(r15_thread,
 784                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 785     lea(rscratch1, InternalAddress(last_java_pc));
 786     movptr(java_pc, rscratch1);
 787   }
 788 
 789   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 790 }
 791 
 792 static void pass_arg0(MacroAssembler* masm, Register arg) {
 793   if (c_rarg0 != arg ) {
 794     masm->mov(c_rarg0, arg);
 795   }
 796 }
 797 
 798 static void pass_arg1(MacroAssembler* masm, Register arg) {
 799   if (c_rarg1 != arg ) {
 800     masm->mov(c_rarg1, arg);
 801   }
 802 }
 803 
 804 static void pass_arg2(MacroAssembler* masm, Register arg) {
 805   if (c_rarg2 != arg ) {
 806     masm->mov(c_rarg2, arg);
 807   }
 808 }
 809 
 810 static void pass_arg3(MacroAssembler* masm, Register arg) {
 811   if (c_rarg3 != arg ) {
 812     masm->mov(c_rarg3, arg);
 813   }
 814 }
 815 
 816 void MacroAssembler::stop(const char* msg) {
 817   address rip = pc();
 818   pusha(); // get regs on stack
 819   lea(c_rarg0, ExternalAddress((address) msg));
 820   lea(c_rarg1, InternalAddress(rip));
 821   movq(c_rarg2, rsp); // pass pointer to regs array
 822   andq(rsp, -16); // align stack as required by ABI
 823   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 824   hlt();
 825 }
 826 
 827 void MacroAssembler::warn(const char* msg) {
 828   push(rbp);
 829   movq(rbp, rsp);
 830   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 831   push_CPU_state();   // keeps alignment at 16 bytes
 832   lea(c_rarg0, ExternalAddress((address) msg));
 833   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 834   pop_CPU_state();
 835   mov(rsp, rbp);
 836   pop(rbp);
 837 }
 838 
 839 void MacroAssembler::print_state() {
 840   address rip = pc();
 841   pusha();            // get regs on stack
 842   push(rbp);
 843   movq(rbp, rsp);
 844   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 845   push_CPU_state();   // keeps alignment at 16 bytes
 846 
 847   lea(c_rarg0, InternalAddress(rip));
 848   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 849   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 850 
 851   pop_CPU_state();
 852   mov(rsp, rbp);
 853   pop(rbp);
 854   popa();
 855 }
 856 
 857 #ifndef PRODUCT
 858 extern "C" void findpc(intptr_t x);
 859 #endif
 860 
 861 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 862   // In order to get locks to work, we need to fake a in_VM state
 863   if (ShowMessageBoxOnError) {
 864     JavaThread* thread = JavaThread::current();
 865     JavaThreadState saved_state = thread->thread_state();
 866     thread->set_thread_state(_thread_in_vm);
 867 #ifndef PRODUCT
 868     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 869       ttyLocker ttyl;
 870       BytecodeCounter::print();
 871     }
 872 #endif
 873     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 874     // XXX correct this offset for amd64
 875     // This is the value of eip which points to where verify_oop will return.
 876     if (os::message_box(msg, "Execution stopped, print registers?")) {
 877       print_state64(pc, regs);
 878       BREAKPOINT;
 879       assert(false, "start up GDB");
 880     }
 881     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 882   } else {
 883     ttyLocker ttyl;
 884     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 885                     msg);
 886     assert(false, err_msg("DEBUG MESSAGE: %s", msg));
 887   }
 888 }
 889 
 890 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 891   ttyLocker ttyl;
 892   FlagSetting fs(Debugging, true);
 893   tty->print_cr("rip = 0x%016lx", pc);
 894 #ifndef PRODUCT
 895   tty->cr();
 896   findpc(pc);
 897   tty->cr();
 898 #endif
 899 #define PRINT_REG(rax, value) \
 900   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 901   PRINT_REG(rax, regs[15]);
 902   PRINT_REG(rbx, regs[12]);
 903   PRINT_REG(rcx, regs[14]);
 904   PRINT_REG(rdx, regs[13]);
 905   PRINT_REG(rdi, regs[8]);
 906   PRINT_REG(rsi, regs[9]);
 907   PRINT_REG(rbp, regs[10]);
 908   PRINT_REG(rsp, regs[11]);
 909   PRINT_REG(r8 , regs[7]);
 910   PRINT_REG(r9 , regs[6]);
 911   PRINT_REG(r10, regs[5]);
 912   PRINT_REG(r11, regs[4]);
 913   PRINT_REG(r12, regs[3]);
 914   PRINT_REG(r13, regs[2]);
 915   PRINT_REG(r14, regs[1]);
 916   PRINT_REG(r15, regs[0]);
 917 #undef PRINT_REG
 918   // Print some words near top of staack.
 919   int64_t* rsp = (int64_t*) regs[11];
 920   int64_t* dump_sp = rsp;
 921   for (int col1 = 0; col1 < 8; col1++) {
 922     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 923     os::print_location(tty, *dump_sp++);
 924   }
 925   for (int row = 0; row < 25; row++) {
 926     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 927     for (int col = 0; col < 4; col++) {
 928       tty->print(" 0x%016lx", *dump_sp++);
 929     }
 930     tty->cr();
 931   }
 932   // Print some instructions around pc:
 933   Disassembler::decode((address)pc-64, (address)pc);
 934   tty->print_cr("--------");
 935   Disassembler::decode((address)pc, (address)pc+32);
 936 }
 937 
 938 #endif // _LP64
 939 
 940 // Now versions that are common to 32/64 bit
 941 
 942 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 943   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 944 }
 945 
 946 void MacroAssembler::addptr(Register dst, Register src) {
 947   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 948 }
 949 
 950 void MacroAssembler::addptr(Address dst, Register src) {
 951   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 952 }
 953 
 954 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 955   if (reachable(src)) {
 956     Assembler::addsd(dst, as_Address(src));
 957   } else {
 958     lea(rscratch1, src);
 959     Assembler::addsd(dst, Address(rscratch1, 0));
 960   }
 961 }
 962 
 963 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 964   if (reachable(src)) {
 965     addss(dst, as_Address(src));
 966   } else {
 967     lea(rscratch1, src);
 968     addss(dst, Address(rscratch1, 0));
 969   }
 970 }
 971 
 972 void MacroAssembler::align(int modulus) {
 973   align(modulus, offset());
 974 }
 975 
 976 void MacroAssembler::align(int modulus, int target) {
 977   if (target % modulus != 0) {
 978     nop(modulus - (target % modulus));
 979   }
 980 }
 981 
 982 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 983   // Used in sign-masking with aligned address.
 984   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 985   if (reachable(src)) {
 986     Assembler::andpd(dst, as_Address(src));
 987   } else {
 988     lea(rscratch1, src);
 989     Assembler::andpd(dst, Address(rscratch1, 0));
 990   }
 991 }
 992 
 993 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
 994   // Used in sign-masking with aligned address.
 995   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 996   if (reachable(src)) {
 997     Assembler::andps(dst, as_Address(src));
 998   } else {
 999     lea(rscratch1, src);
1000     Assembler::andps(dst, Address(rscratch1, 0));
1001   }
1002 }
1003 
1004 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1005   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1006 }
1007 
1008 void MacroAssembler::atomic_incl(Address counter_addr) {
1009   if (os::is_MP())
1010     lock();
1011   incrementl(counter_addr);
1012 }
1013 
1014 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1015   if (reachable(counter_addr)) {
1016     atomic_incl(as_Address(counter_addr));
1017   } else {
1018     lea(scr, counter_addr);
1019     atomic_incl(Address(scr, 0));
1020   }
1021 }
1022 
1023 #ifdef _LP64
1024 void MacroAssembler::atomic_incq(Address counter_addr) {
1025   if (os::is_MP())
1026     lock();
1027   incrementq(counter_addr);
1028 }
1029 
1030 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1031   if (reachable(counter_addr)) {
1032     atomic_incq(as_Address(counter_addr));
1033   } else {
1034     lea(scr, counter_addr);
1035     atomic_incq(Address(scr, 0));
1036   }
1037 }
1038 #endif
1039 
1040 // Writes to stack successive pages until offset reached to check for
1041 // stack overflow + shadow pages.  This clobbers tmp.
1042 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1043   movptr(tmp, rsp);
1044   // Bang stack for total size given plus shadow page size.
1045   // Bang one page at a time because large size can bang beyond yellow and
1046   // red zones.
1047   Label loop;
1048   bind(loop);
1049   movl(Address(tmp, (-os::vm_page_size())), size );
1050   subptr(tmp, os::vm_page_size());
1051   subl(size, os::vm_page_size());
1052   jcc(Assembler::greater, loop);
1053 
1054   // Bang down shadow pages too.
1055   // At this point, (tmp-0) is the last address touched, so don't
1056   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1057   // was post-decremented.)  Skip this address by starting at i=1, and
1058   // touch a few more pages below.  N.B.  It is important to touch all
1059   // the way down to and including i=StackShadowPages.
1060   for (int i = 1; i < StackShadowPages; i++) {
1061     // this could be any sized move but this is can be a debugging crumb
1062     // so the bigger the better.
1063     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1064   }
1065 }
1066 
1067 int MacroAssembler::biased_locking_enter(Register lock_reg,
1068                                          Register obj_reg,
1069                                          Register swap_reg,
1070                                          Register tmp_reg,
1071                                          bool swap_reg_contains_mark,
1072                                          Label& done,
1073                                          Label* slow_case,
1074                                          BiasedLockingCounters* counters) {
1075   assert(UseBiasedLocking, "why call this otherwise?");
1076   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1077   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1078   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1079   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1080   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1081   Address saved_mark_addr(lock_reg, 0);
1082 
1083   if (PrintBiasedLockingStatistics && counters == NULL) {
1084     counters = BiasedLocking::counters();
1085   }
1086   // Biased locking
1087   // See whether the lock is currently biased toward our thread and
1088   // whether the epoch is still valid
1089   // Note that the runtime guarantees sufficient alignment of JavaThread
1090   // pointers to allow age to be placed into low bits
1091   // First check to see whether biasing is even enabled for this object
1092   Label cas_label;
1093   int null_check_offset = -1;
1094   if (!swap_reg_contains_mark) {
1095     null_check_offset = offset();
1096     movptr(swap_reg, mark_addr);
1097   }
1098   movptr(tmp_reg, swap_reg);
1099   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1100   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1101   jcc(Assembler::notEqual, cas_label);
1102   // The bias pattern is present in the object's header. Need to check
1103   // whether the bias owner and the epoch are both still current.
1104 #ifndef _LP64
1105   // Note that because there is no current thread register on x86_32 we
1106   // need to store off the mark word we read out of the object to
1107   // avoid reloading it and needing to recheck invariants below. This
1108   // store is unfortunate but it makes the overall code shorter and
1109   // simpler.
1110   movptr(saved_mark_addr, swap_reg);
1111 #endif
1112   if (swap_reg_contains_mark) {
1113     null_check_offset = offset();
1114   }
1115   load_prototype_header(tmp_reg, obj_reg);
1116 #ifdef _LP64
1117   orptr(tmp_reg, r15_thread);
1118   xorptr(tmp_reg, swap_reg);
1119   Register header_reg = tmp_reg;
1120 #else
1121   xorptr(tmp_reg, swap_reg);
1122   get_thread(swap_reg);
1123   xorptr(swap_reg, tmp_reg);
1124   Register header_reg = swap_reg;
1125 #endif
1126   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1127   if (counters != NULL) {
1128     cond_inc32(Assembler::zero,
1129                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1130   }
1131   jcc(Assembler::equal, done);
1132 
1133   Label try_revoke_bias;
1134   Label try_rebias;
1135 
1136   // At this point we know that the header has the bias pattern and
1137   // that we are not the bias owner in the current epoch. We need to
1138   // figure out more details about the state of the header in order to
1139   // know what operations can be legally performed on the object's
1140   // header.
1141 
1142   // If the low three bits in the xor result aren't clear, that means
1143   // the prototype header is no longer biased and we have to revoke
1144   // the bias on this object.
1145   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1146   jccb(Assembler::notZero, try_revoke_bias);
1147 
1148   // Biasing is still enabled for this data type. See whether the
1149   // epoch of the current bias is still valid, meaning that the epoch
1150   // bits of the mark word are equal to the epoch bits of the
1151   // prototype header. (Note that the prototype header's epoch bits
1152   // only change at a safepoint.) If not, attempt to rebias the object
1153   // toward the current thread. Note that we must be absolutely sure
1154   // that the current epoch is invalid in order to do this because
1155   // otherwise the manipulations it performs on the mark word are
1156   // illegal.
1157   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1158   jccb(Assembler::notZero, try_rebias);
1159 
1160   // The epoch of the current bias is still valid but we know nothing
1161   // about the owner; it might be set or it might be clear. Try to
1162   // acquire the bias of the object using an atomic operation. If this
1163   // fails we will go in to the runtime to revoke the object's bias.
1164   // Note that we first construct the presumed unbiased header so we
1165   // don't accidentally blow away another thread's valid bias.
1166   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1167   andptr(swap_reg,
1168          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1169 #ifdef _LP64
1170   movptr(tmp_reg, swap_reg);
1171   orptr(tmp_reg, r15_thread);
1172 #else
1173   get_thread(tmp_reg);
1174   orptr(tmp_reg, swap_reg);
1175 #endif
1176   if (os::is_MP()) {
1177     lock();
1178   }
1179   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1180   // If the biasing toward our thread failed, this means that
1181   // another thread succeeded in biasing it toward itself and we
1182   // need to revoke that bias. The revocation will occur in the
1183   // interpreter runtime in the slow case.
1184   if (counters != NULL) {
1185     cond_inc32(Assembler::zero,
1186                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1187   }
1188   if (slow_case != NULL) {
1189     jcc(Assembler::notZero, *slow_case);
1190   }
1191   jmp(done);
1192 
1193   bind(try_rebias);
1194   // At this point we know the epoch has expired, meaning that the
1195   // current "bias owner", if any, is actually invalid. Under these
1196   // circumstances _only_, we are allowed to use the current header's
1197   // value as the comparison value when doing the cas to acquire the
1198   // bias in the current epoch. In other words, we allow transfer of
1199   // the bias from one thread to another directly in this situation.
1200   //
1201   // FIXME: due to a lack of registers we currently blow away the age
1202   // bits in this situation. Should attempt to preserve them.
1203   load_prototype_header(tmp_reg, obj_reg);
1204 #ifdef _LP64
1205   orptr(tmp_reg, r15_thread);
1206 #else
1207   get_thread(swap_reg);
1208   orptr(tmp_reg, swap_reg);
1209   movptr(swap_reg, saved_mark_addr);
1210 #endif
1211   if (os::is_MP()) {
1212     lock();
1213   }
1214   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1215   // If the biasing toward our thread failed, then another thread
1216   // succeeded in biasing it toward itself and we need to revoke that
1217   // bias. The revocation will occur in the runtime in the slow case.
1218   if (counters != NULL) {
1219     cond_inc32(Assembler::zero,
1220                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1221   }
1222   if (slow_case != NULL) {
1223     jcc(Assembler::notZero, *slow_case);
1224   }
1225   jmp(done);
1226 
1227   bind(try_revoke_bias);
1228   // The prototype mark in the klass doesn't have the bias bit set any
1229   // more, indicating that objects of this data type are not supposed
1230   // to be biased any more. We are going to try to reset the mark of
1231   // this object to the prototype value and fall through to the
1232   // CAS-based locking scheme. Note that if our CAS fails, it means
1233   // that another thread raced us for the privilege of revoking the
1234   // bias of this particular object, so it's okay to continue in the
1235   // normal locking code.
1236   //
1237   // FIXME: due to a lack of registers we currently blow away the age
1238   // bits in this situation. Should attempt to preserve them.
1239   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1240   load_prototype_header(tmp_reg, obj_reg);
1241   if (os::is_MP()) {
1242     lock();
1243   }
1244   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1245   // Fall through to the normal CAS-based lock, because no matter what
1246   // the result of the above CAS, some thread must have succeeded in
1247   // removing the bias bit from the object's header.
1248   if (counters != NULL) {
1249     cond_inc32(Assembler::zero,
1250                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1251   }
1252 
1253   bind(cas_label);
1254 
1255   return null_check_offset;
1256 }
1257 
1258 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1259   assert(UseBiasedLocking, "why call this otherwise?");
1260 
1261   // Check for biased locking unlock case, which is a no-op
1262   // Note: we do not have to check the thread ID for two reasons.
1263   // First, the interpreter checks for IllegalMonitorStateException at
1264   // a higher level. Second, if the bias was revoked while we held the
1265   // lock, the object could not be rebiased toward another thread, so
1266   // the bias bit would be clear.
1267   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1268   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1269   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1270   jcc(Assembler::equal, done);
1271 }
1272 
1273 #ifdef COMPILER2
1274 
1275 #if INCLUDE_RTM_OPT
1276 
1277 // Update rtm_counters based on abort status
1278 // input: abort_status
1279 //        rtm_counters (RTMLockingCounters*)
1280 // flags are killed
1281 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1282 
1283   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1284   if (PrintPreciseRTMLockingStatistics) {
1285     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1286       Label check_abort;
1287       testl(abort_status, (1<<i));
1288       jccb(Assembler::equal, check_abort);
1289       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1290       bind(check_abort);
1291     }
1292   }
1293 }
1294 
1295 // Branch if (random & (count-1) != 0), count is 2^n
1296 // tmp, scr and flags are killed
1297 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1298   assert(tmp == rax, "");
1299   assert(scr == rdx, "");
1300   rdtsc(); // modifies EDX:EAX
1301   andptr(tmp, count-1);
1302   jccb(Assembler::notZero, brLabel);
1303 }
1304 
1305 // Perform abort ratio calculation, set no_rtm bit if high ratio
1306 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1307 // tmpReg, rtm_counters_Reg and flags are killed
1308 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1309                                                  Register rtm_counters_Reg,
1310                                                  RTMLockingCounters* rtm_counters,
1311                                                  Metadata* method_data) {
1312   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1313 
1314   if (RTMLockingCalculationDelay > 0) {
1315     // Delay calculation
1316     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1317     testptr(tmpReg, tmpReg);
1318     jccb(Assembler::equal, L_done);
1319   }
1320   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1321   //   Aborted transactions = abort_count * 100
1322   //   All transactions = total_count *  RTMTotalCountIncrRate
1323   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1324 
1325   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1326   cmpptr(tmpReg, RTMAbortThreshold);
1327   jccb(Assembler::below, L_check_always_rtm2);
1328   imulptr(tmpReg, tmpReg, 100);
1329 
1330   Register scrReg = rtm_counters_Reg;
1331   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1332   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1333   imulptr(scrReg, scrReg, RTMAbortRatio);
1334   cmpptr(tmpReg, scrReg);
1335   jccb(Assembler::below, L_check_always_rtm1);
1336   if (method_data != NULL) {
1337     // set rtm_state to "no rtm" in MDO
1338     mov_metadata(tmpReg, method_data);
1339     if (os::is_MP()) {
1340       lock();
1341     }
1342     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1343   }
1344   jmpb(L_done);
1345   bind(L_check_always_rtm1);
1346   // Reload RTMLockingCounters* address
1347   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1348   bind(L_check_always_rtm2);
1349   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1350   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1351   jccb(Assembler::below, L_done);
1352   if (method_data != NULL) {
1353     // set rtm_state to "always rtm" in MDO
1354     mov_metadata(tmpReg, method_data);
1355     if (os::is_MP()) {
1356       lock();
1357     }
1358     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1359   }
1360   bind(L_done);
1361 }
1362 
1363 // Update counters and perform abort ratio calculation
1364 // input:  abort_status_Reg
1365 // rtm_counters_Reg, flags are killed
1366 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1367                                    Register rtm_counters_Reg,
1368                                    RTMLockingCounters* rtm_counters,
1369                                    Metadata* method_data,
1370                                    bool profile_rtm) {
1371 
1372   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1373   // update rtm counters based on rax value at abort
1374   // reads abort_status_Reg, updates flags
1375   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1376   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1377   if (profile_rtm) {
1378     // Save abort status because abort_status_Reg is used by following code.
1379     if (RTMRetryCount > 0) {
1380       push(abort_status_Reg);
1381     }
1382     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1383     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1384     // restore abort status
1385     if (RTMRetryCount > 0) {
1386       pop(abort_status_Reg);
1387     }
1388   }
1389 }
1390 
1391 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1392 // inputs: retry_count_Reg
1393 //       : abort_status_Reg
1394 // output: retry_count_Reg decremented by 1
1395 // flags are killed
1396 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1397   Label doneRetry;
1398   assert(abort_status_Reg == rax, "");
1399   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1400   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1401   // if reason is in 0x6 and retry count != 0 then retry
1402   andptr(abort_status_Reg, 0x6);
1403   jccb(Assembler::zero, doneRetry);
1404   testl(retry_count_Reg, retry_count_Reg);
1405   jccb(Assembler::zero, doneRetry);
1406   pause();
1407   decrementl(retry_count_Reg);
1408   jmp(retryLabel);
1409   bind(doneRetry);
1410 }
1411 
1412 // Spin and retry if lock is busy,
1413 // inputs: box_Reg (monitor address)
1414 //       : retry_count_Reg
1415 // output: retry_count_Reg decremented by 1
1416 //       : clear z flag if retry count exceeded
1417 // tmp_Reg, scr_Reg, flags are killed
1418 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1419                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1420   Label SpinLoop, SpinExit, doneRetry;
1421   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1422 
1423   testl(retry_count_Reg, retry_count_Reg);
1424   jccb(Assembler::zero, doneRetry);
1425   decrementl(retry_count_Reg);
1426   movptr(scr_Reg, RTMSpinLoopCount);
1427 
1428   bind(SpinLoop);
1429   pause();
1430   decrementl(scr_Reg);
1431   jccb(Assembler::lessEqual, SpinExit);
1432   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1433   testptr(tmp_Reg, tmp_Reg);
1434   jccb(Assembler::notZero, SpinLoop);
1435 
1436   bind(SpinExit);
1437   jmp(retryLabel);
1438   bind(doneRetry);
1439   incrementl(retry_count_Reg); // clear z flag
1440 }
1441 
1442 // Use RTM for normal stack locks
1443 // Input: objReg (object to lock)
1444 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1445                                        Register retry_on_abort_count_Reg,
1446                                        RTMLockingCounters* stack_rtm_counters,
1447                                        Metadata* method_data, bool profile_rtm,
1448                                        Label& DONE_LABEL, Label& IsInflated) {
1449   assert(UseRTMForStackLocks, "why call this otherwise?");
1450   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1451   assert(tmpReg == rax, "");
1452   assert(scrReg == rdx, "");
1453   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1454 
1455   if (RTMRetryCount > 0) {
1456     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1457     bind(L_rtm_retry);
1458   }
1459   movptr(tmpReg, Address(objReg, 0));
1460   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1461   jcc(Assembler::notZero, IsInflated);
1462 
1463   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1464     Label L_noincrement;
1465     if (RTMTotalCountIncrRate > 1) {
1466       // tmpReg, scrReg and flags are killed
1467       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1468     }
1469     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1470     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1471     bind(L_noincrement);
1472   }
1473   xbegin(L_on_abort);
1474   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1475   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1476   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1477   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1478 
1479   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1480   if (UseRTMXendForLockBusy) {
1481     xend();
1482     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1483     jmp(L_decrement_retry);
1484   }
1485   else {
1486     xabort(0);
1487   }
1488   bind(L_on_abort);
1489   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1490     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1491   }
1492   bind(L_decrement_retry);
1493   if (RTMRetryCount > 0) {
1494     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1495     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1496   }
1497 }
1498 
1499 // Use RTM for inflating locks
1500 // inputs: objReg (object to lock)
1501 //         boxReg (on-stack box address (displaced header location) - KILLED)
1502 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1503 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1504                                           Register scrReg, Register retry_on_busy_count_Reg,
1505                                           Register retry_on_abort_count_Reg,
1506                                           RTMLockingCounters* rtm_counters,
1507                                           Metadata* method_data, bool profile_rtm,
1508                                           Label& DONE_LABEL) {
1509   assert(UseRTMLocking, "why call this otherwise?");
1510   assert(tmpReg == rax, "");
1511   assert(scrReg == rdx, "");
1512   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1513   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1514 
1515   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1516   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1517   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1518 
1519   if (RTMRetryCount > 0) {
1520     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1521     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1522     bind(L_rtm_retry);
1523   }
1524   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1525     Label L_noincrement;
1526     if (RTMTotalCountIncrRate > 1) {
1527       // tmpReg, scrReg and flags are killed
1528       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1529     }
1530     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1531     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1532     bind(L_noincrement);
1533   }
1534   xbegin(L_on_abort);
1535   movptr(tmpReg, Address(objReg, 0));
1536   movptr(tmpReg, Address(tmpReg, owner_offset));
1537   testptr(tmpReg, tmpReg);
1538   jcc(Assembler::zero, DONE_LABEL);
1539   if (UseRTMXendForLockBusy) {
1540     xend();
1541     jmp(L_decrement_retry);
1542   }
1543   else {
1544     xabort(0);
1545   }
1546   bind(L_on_abort);
1547   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1548   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1549     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1550   }
1551   if (RTMRetryCount > 0) {
1552     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1553     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1554   }
1555 
1556   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1557   testptr(tmpReg, tmpReg) ;
1558   jccb(Assembler::notZero, L_decrement_retry) ;
1559 
1560   // Appears unlocked - try to swing _owner from null to non-null.
1561   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1562 #ifdef _LP64
1563   Register threadReg = r15_thread;
1564 #else
1565   get_thread(scrReg);
1566   Register threadReg = scrReg;
1567 #endif
1568   if (os::is_MP()) {
1569     lock();
1570   }
1571   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1572 
1573   if (RTMRetryCount > 0) {
1574     // success done else retry
1575     jccb(Assembler::equal, DONE_LABEL) ;
1576     bind(L_decrement_retry);
1577     // Spin and retry if lock is busy.
1578     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1579   }
1580   else {
1581     bind(L_decrement_retry);
1582   }
1583 }
1584 
1585 #endif //  INCLUDE_RTM_OPT
1586 
1587 // Fast_Lock and Fast_Unlock used by C2
1588 
1589 // Because the transitions from emitted code to the runtime
1590 // monitorenter/exit helper stubs are so slow it's critical that
1591 // we inline both the stack-locking fast-path and the inflated fast path.
1592 //
1593 // See also: cmpFastLock and cmpFastUnlock.
1594 //
1595 // What follows is a specialized inline transliteration of the code
1596 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1597 // another option would be to emit TrySlowEnter and TrySlowExit methods
1598 // at startup-time.  These methods would accept arguments as
1599 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1600 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1601 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1602 // In practice, however, the # of lock sites is bounded and is usually small.
1603 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1604 // if the processor uses simple bimodal branch predictors keyed by EIP
1605 // Since the helper routines would be called from multiple synchronization
1606 // sites.
1607 //
1608 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1609 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1610 // to those specialized methods.  That'd give us a mostly platform-independent
1611 // implementation that the JITs could optimize and inline at their pleasure.
1612 // Done correctly, the only time we'd need to cross to native could would be
1613 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1614 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1615 // (b) explicit barriers or fence operations.
1616 //
1617 // TODO:
1618 //
1619 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1620 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1621 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1622 //    the lock operators would typically be faster than reifying Self.
1623 //
1624 // *  Ideally I'd define the primitives as:
1625 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1626 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1627 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1628 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1629 //    Furthermore the register assignments are overconstrained, possibly resulting in
1630 //    sub-optimal code near the synchronization site.
1631 //
1632 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1633 //    Alternately, use a better sp-proximity test.
1634 //
1635 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1636 //    Either one is sufficient to uniquely identify a thread.
1637 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1638 //
1639 // *  Intrinsify notify() and notifyAll() for the common cases where the
1640 //    object is locked by the calling thread but the waitlist is empty.
1641 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1642 //
1643 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1644 //    But beware of excessive branch density on AMD Opterons.
1645 //
1646 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1647 //    or failure of the fast-path.  If the fast-path fails then we pass
1648 //    control to the slow-path, typically in C.  In Fast_Lock and
1649 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1650 //    will emit a conditional branch immediately after the node.
1651 //    So we have branches to branches and lots of ICC.ZF games.
1652 //    Instead, it might be better to have C2 pass a "FailureLabel"
1653 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1654 //    will drop through the node.  ICC.ZF is undefined at exit.
1655 //    In the case of failure, the node will branch directly to the
1656 //    FailureLabel
1657 
1658 
1659 // obj: object to lock
1660 // box: on-stack box address (displaced header location) - KILLED
1661 // rax,: tmp -- KILLED
1662 // scr: tmp -- KILLED
1663 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1664                                Register scrReg, Register cx1Reg, Register cx2Reg,
1665                                BiasedLockingCounters* counters,
1666                                RTMLockingCounters* rtm_counters,
1667                                RTMLockingCounters* stack_rtm_counters,
1668                                Metadata* method_data,
1669                                bool use_rtm, bool profile_rtm) {
1670   // Ensure the register assignents are disjoint
1671   assert(tmpReg == rax, "");
1672 
1673   if (use_rtm) {
1674     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1675   } else {
1676     assert(cx1Reg == noreg, "");
1677     assert(cx2Reg == noreg, "");
1678     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1679   }
1680 
1681   if (counters != NULL) {
1682     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1683   }
1684   if (EmitSync & 1) {
1685       // set box->dhw = markOopDesc::unused_mark()
1686       // Force all sync thru slow-path: slow_enter() and slow_exit()
1687       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1688       cmpptr (rsp, (int32_t)NULL_WORD);
1689   } else {
1690     // Possible cases that we'll encounter in fast_lock
1691     // ------------------------------------------------
1692     // * Inflated
1693     //    -- unlocked
1694     //    -- Locked
1695     //       = by self
1696     //       = by other
1697     // * biased
1698     //    -- by Self
1699     //    -- by other
1700     // * neutral
1701     // * stack-locked
1702     //    -- by self
1703     //       = sp-proximity test hits
1704     //       = sp-proximity test generates false-negative
1705     //    -- by other
1706     //
1707 
1708     Label IsInflated, DONE_LABEL;
1709 
1710     // it's stack-locked, biased or neutral
1711     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1712     // order to reduce the number of conditional branches in the most common cases.
1713     // Beware -- there's a subtle invariant that fetch of the markword
1714     // at [FETCH], below, will never observe a biased encoding (*101b).
1715     // If this invariant is not held we risk exclusion (safety) failure.
1716     if (UseBiasedLocking && !UseOptoBiasInlining) {
1717       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1718     }
1719 
1720 #if INCLUDE_RTM_OPT
1721     if (UseRTMForStackLocks && use_rtm) {
1722       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1723                         stack_rtm_counters, method_data, profile_rtm,
1724                         DONE_LABEL, IsInflated);
1725     }
1726 #endif // INCLUDE_RTM_OPT
1727 
1728     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1729     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1730     jccb(Assembler::notZero, IsInflated);
1731 
1732     // Attempt stack-locking ...
1733     orptr (tmpReg, markOopDesc::unlocked_value);
1734     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1735     if (os::is_MP()) {
1736       lock();
1737     }
1738     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1739     if (counters != NULL) {
1740       cond_inc32(Assembler::equal,
1741                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1742     }
1743     jcc(Assembler::equal, DONE_LABEL);           // Success
1744 
1745     // Recursive locking.
1746     // The object is stack-locked: markword contains stack pointer to BasicLock.
1747     // Locked by current thread if difference with current SP is less than one page.
1748     subptr(tmpReg, rsp);
1749     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1750     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1751     movptr(Address(boxReg, 0), tmpReg);
1752     if (counters != NULL) {
1753       cond_inc32(Assembler::equal,
1754                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1755     }
1756     jmp(DONE_LABEL);
1757 
1758     bind(IsInflated);
1759     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1760 
1761 #if INCLUDE_RTM_OPT
1762     // Use the same RTM locking code in 32- and 64-bit VM.
1763     if (use_rtm) {
1764       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1765                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1766     } else {
1767 #endif // INCLUDE_RTM_OPT
1768 
1769 #ifndef _LP64
1770     // The object is inflated.
1771 
1772     // boxReg refers to the on-stack BasicLock in the current frame.
1773     // We'd like to write:
1774     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1775     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1776     // additional latency as we have another ST in the store buffer that must drain.
1777 
1778     if (EmitSync & 8192) {
1779        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1780        get_thread (scrReg);
1781        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1782        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1783        if (os::is_MP()) {
1784          lock();
1785        }
1786        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1787     } else
1788     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1789        // register juggle because we need tmpReg for cmpxchgptr below
1790        movptr(scrReg, boxReg);
1791        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1792 
1793        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1794        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1795           // prefetchw [eax + Offset(_owner)-2]
1796           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1797        }
1798 
1799        if ((EmitSync & 64) == 0) {
1800          // Optimistic form: consider XORL tmpReg,tmpReg
1801          movptr(tmpReg, NULL_WORD);
1802        } else {
1803          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1804          // Test-And-CAS instead of CAS
1805          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1806          testptr(tmpReg, tmpReg);                   // Locked ?
1807          jccb  (Assembler::notZero, DONE_LABEL);
1808        }
1809 
1810        // Appears unlocked - try to swing _owner from null to non-null.
1811        // Ideally, I'd manifest "Self" with get_thread and then attempt
1812        // to CAS the register containing Self into m->Owner.
1813        // But we don't have enough registers, so instead we can either try to CAS
1814        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1815        // we later store "Self" into m->Owner.  Transiently storing a stack address
1816        // (rsp or the address of the box) into  m->owner is harmless.
1817        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1818        if (os::is_MP()) {
1819          lock();
1820        }
1821        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1822        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1823        // If we weren't able to swing _owner from NULL to the BasicLock
1824        // then take the slow path.
1825        jccb  (Assembler::notZero, DONE_LABEL);
1826        // update _owner from BasicLock to thread
1827        get_thread (scrReg);                    // beware: clobbers ICCs
1828        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1829        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1830 
1831        // If the CAS fails we can either retry or pass control to the slow-path.
1832        // We use the latter tactic.
1833        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1834        // If the CAS was successful ...
1835        //   Self has acquired the lock
1836        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1837        // Intentional fall-through into DONE_LABEL ...
1838     } else {
1839        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1840        movptr(boxReg, tmpReg);
1841 
1842        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1843        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1844           // prefetchw [eax + Offset(_owner)-2]
1845           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1846        }
1847 
1848        if ((EmitSync & 64) == 0) {
1849          // Optimistic form
1850          xorptr  (tmpReg, tmpReg);
1851        } else {
1852          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1853          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1854          testptr(tmpReg, tmpReg);                   // Locked ?
1855          jccb  (Assembler::notZero, DONE_LABEL);
1856        }
1857 
1858        // Appears unlocked - try to swing _owner from null to non-null.
1859        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1860        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1861        get_thread (scrReg);
1862        if (os::is_MP()) {
1863          lock();
1864        }
1865        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1866 
1867        // If the CAS fails we can either retry or pass control to the slow-path.
1868        // We use the latter tactic.
1869        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1870        // If the CAS was successful ...
1871        //   Self has acquired the lock
1872        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1873        // Intentional fall-through into DONE_LABEL ...
1874     }
1875 #else // _LP64
1876     // It's inflated
1877     movq(scrReg, tmpReg);
1878     xorq(tmpReg, tmpReg);
1879 
1880     if (os::is_MP()) {
1881       lock();
1882     }
1883     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1884     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1885     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1886     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1887     // Intentional fall-through into DONE_LABEL ...
1888     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1889 #endif // _LP64
1890 #if INCLUDE_RTM_OPT
1891     } // use_rtm()
1892 #endif
1893     // DONE_LABEL is a hot target - we'd really like to place it at the
1894     // start of cache line by padding with NOPs.
1895     // See the AMD and Intel software optimization manuals for the
1896     // most efficient "long" NOP encodings.
1897     // Unfortunately none of our alignment mechanisms suffice.
1898     bind(DONE_LABEL);
1899 
1900     // At DONE_LABEL the icc ZFlag is set as follows ...
1901     // Fast_Unlock uses the same protocol.
1902     // ZFlag == 1 -> Success
1903     // ZFlag == 0 -> Failure - force control through the slow-path
1904   }
1905 }
1906 
1907 // obj: object to unlock
1908 // box: box address (displaced header location), killed.  Must be EAX.
1909 // tmp: killed, cannot be obj nor box.
1910 //
1911 // Some commentary on balanced locking:
1912 //
1913 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1914 // Methods that don't have provably balanced locking are forced to run in the
1915 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1916 // The interpreter provides two properties:
1917 // I1:  At return-time the interpreter automatically and quietly unlocks any
1918 //      objects acquired the current activation (frame).  Recall that the
1919 //      interpreter maintains an on-stack list of locks currently held by
1920 //      a frame.
1921 // I2:  If a method attempts to unlock an object that is not held by the
1922 //      the frame the interpreter throws IMSX.
1923 //
1924 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1925 // B() doesn't have provably balanced locking so it runs in the interpreter.
1926 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1927 // is still locked by A().
1928 //
1929 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1930 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1931 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1932 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1933 // Arguably given that the spec legislates the JNI case as undefined our implementation
1934 // could reasonably *avoid* checking owner in Fast_Unlock().
1935 // In the interest of performance we elide m->Owner==Self check in unlock.
1936 // A perfectly viable alternative is to elide the owner check except when
1937 // Xcheck:jni is enabled.
1938 
1939 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1940   assert(boxReg == rax, "");
1941   assert_different_registers(objReg, boxReg, tmpReg);
1942 
1943   if (EmitSync & 4) {
1944     // Disable - inhibit all inlining.  Force control through the slow-path
1945     cmpptr (rsp, 0);
1946   } else {
1947     Label DONE_LABEL, Stacked, CheckSucc;
1948 
1949     // Critically, the biased locking test must have precedence over
1950     // and appear before the (box->dhw == 0) recursive stack-lock test.
1951     if (UseBiasedLocking && !UseOptoBiasInlining) {
1952        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1953     }
1954 
1955 #if INCLUDE_RTM_OPT
1956     if (UseRTMForStackLocks && use_rtm) {
1957       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1958       Label L_regular_unlock;
1959       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1960       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1961       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1962       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1963       xend();                                       // otherwise end...
1964       jmp(DONE_LABEL);                              // ... and we're done
1965       bind(L_regular_unlock);
1966     }
1967 #endif
1968 
1969     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1970     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1971     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
1972     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1973     jccb  (Assembler::zero, Stacked);
1974 
1975     // It's inflated.
1976 #if INCLUDE_RTM_OPT
1977     if (use_rtm) {
1978       Label L_regular_inflated_unlock;
1979       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1980       movptr(boxReg, Address(tmpReg, owner_offset));
1981       testptr(boxReg, boxReg);
1982       jccb(Assembler::notZero, L_regular_inflated_unlock);
1983       xend();
1984       jmpb(DONE_LABEL);
1985       bind(L_regular_inflated_unlock);
1986     }
1987 #endif
1988 
1989     // Despite our balanced locking property we still check that m->_owner == Self
1990     // as java routines or native JNI code called by this thread might
1991     // have released the lock.
1992     // Refer to the comments in synchronizer.cpp for how we might encode extra
1993     // state in _succ so we can avoid fetching EntryList|cxq.
1994     //
1995     // I'd like to add more cases in fast_lock() and fast_unlock() --
1996     // such as recursive enter and exit -- but we have to be wary of
1997     // I$ bloat, T$ effects and BP$ effects.
1998     //
1999     // If there's no contention try a 1-0 exit.  That is, exit without
2000     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2001     // we detect and recover from the race that the 1-0 exit admits.
2002     //
2003     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2004     // before it STs null into _owner, releasing the lock.  Updates
2005     // to data protected by the critical section must be visible before
2006     // we drop the lock (and thus before any other thread could acquire
2007     // the lock and observe the fields protected by the lock).
2008     // IA32's memory-model is SPO, so STs are ordered with respect to
2009     // each other and there's no need for an explicit barrier (fence).
2010     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2011 #ifndef _LP64
2012     get_thread (boxReg);
2013     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2014       // prefetchw [ebx + Offset(_owner)-2]
2015       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2016     }
2017 
2018     // Note that we could employ various encoding schemes to reduce
2019     // the number of loads below (currently 4) to just 2 or 3.
2020     // Refer to the comments in synchronizer.cpp.
2021     // In practice the chain of fetches doesn't seem to impact performance, however.
2022     xorptr(boxReg, boxReg);
2023     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2024        // Attempt to reduce branch density - AMD's branch predictor.
2025        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2026        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2027        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2028        jccb  (Assembler::notZero, DONE_LABEL);
2029        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2030        jmpb  (DONE_LABEL);
2031     } else {
2032        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2033        jccb  (Assembler::notZero, DONE_LABEL);
2034        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2035        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2036        jccb  (Assembler::notZero, CheckSucc);
2037        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2038        jmpb  (DONE_LABEL);
2039     }
2040 
2041     // The Following code fragment (EmitSync & 65536) improves the performance of
2042     // contended applications and contended synchronization microbenchmarks.
2043     // Unfortunately the emission of the code - even though not executed - causes regressions
2044     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2045     // with an equal number of never-executed NOPs results in the same regression.
2046     // We leave it off by default.
2047 
2048     if ((EmitSync & 65536) != 0) {
2049        Label LSuccess, LGoSlowPath ;
2050 
2051        bind  (CheckSucc);
2052 
2053        // Optional pre-test ... it's safe to elide this
2054        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2055        jccb(Assembler::zero, LGoSlowPath);
2056 
2057        // We have a classic Dekker-style idiom:
2058        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2059        // There are a number of ways to implement the barrier:
2060        // (1) lock:andl &m->_owner, 0
2061        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2062        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2063        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2064        // (2) If supported, an explicit MFENCE is appealing.
2065        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2066        //     particularly if the write-buffer is full as might be the case if
2067        //     if stores closely precede the fence or fence-equivalent instruction.
2068        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2069        //     as the situation has changed with Nehalem and Shanghai.
2070        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2071        //     The $lines underlying the top-of-stack should be in M-state.
2072        //     The locked add instruction is serializing, of course.
2073        // (4) Use xchg, which is serializing
2074        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2075        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2076        //     The integer condition codes will tell us if succ was 0.
2077        //     Since _succ and _owner should reside in the same $line and
2078        //     we just stored into _owner, it's likely that the $line
2079        //     remains in M-state for the lock:orl.
2080        //
2081        // We currently use (3), although it's likely that switching to (2)
2082        // is correct for the future.
2083 
2084        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2085        if (os::is_MP()) {
2086          lock(); addptr(Address(rsp, 0), 0);
2087        }
2088        // Ratify _succ remains non-null
2089        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2090        jccb  (Assembler::notZero, LSuccess);
2091 
2092        xorptr(boxReg, boxReg);                  // box is really EAX
2093        if (os::is_MP()) { lock(); }
2094        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2095        // There's no successor so we tried to regrab the lock with the
2096        // placeholder value. If that didn't work, then another thread
2097        // grabbed the lock so we're done (and exit was a success).
2098        jccb  (Assembler::notEqual, LSuccess);
2099        // Since we're low on registers we installed rsp as a placeholding in _owner.
2100        // Now install Self over rsp.  This is safe as we're transitioning from
2101        // non-null to non=null
2102        get_thread (boxReg);
2103        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2104        // Intentional fall-through into LGoSlowPath ...
2105 
2106        bind  (LGoSlowPath);
2107        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2108        jmpb  (DONE_LABEL);
2109 
2110        bind  (LSuccess);
2111        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2112        jmpb  (DONE_LABEL);
2113     }
2114 
2115     bind (Stacked);
2116     // It's not inflated and it's not recursively stack-locked and it's not biased.
2117     // It must be stack-locked.
2118     // Try to reset the header to displaced header.
2119     // The "box" value on the stack is stable, so we can reload
2120     // and be assured we observe the same value as above.
2121     movptr(tmpReg, Address(boxReg, 0));
2122     if (os::is_MP()) {
2123       lock();
2124     }
2125     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2126     // Intention fall-thru into DONE_LABEL
2127 
2128     // DONE_LABEL is a hot target - we'd really like to place it at the
2129     // start of cache line by padding with NOPs.
2130     // See the AMD and Intel software optimization manuals for the
2131     // most efficient "long" NOP encodings.
2132     // Unfortunately none of our alignment mechanisms suffice.
2133     if ((EmitSync & 65536) == 0) {
2134        bind (CheckSucc);
2135     }
2136 #else // _LP64
2137     // It's inflated
2138     if (EmitSync & 1024) {
2139       // Emit code to check that _owner == Self
2140       // We could fold the _owner test into subsequent code more efficiently
2141       // than using a stand-alone check, but since _owner checking is off by
2142       // default we don't bother. We also might consider predicating the
2143       // _owner==Self check on Xcheck:jni or running on a debug build.
2144       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2145       xorptr(boxReg, r15_thread);
2146     } else {
2147       xorptr(boxReg, boxReg);
2148     }
2149     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2150     jccb  (Assembler::notZero, DONE_LABEL);
2151     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2152     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2153     jccb  (Assembler::notZero, CheckSucc);
2154     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2155     jmpb  (DONE_LABEL);
2156 
2157     if ((EmitSync & 65536) == 0) {
2158       // Try to avoid passing control into the slow_path ...
2159       Label LSuccess, LGoSlowPath ;
2160       bind  (CheckSucc);
2161 
2162       // The following optional optimization can be elided if necessary
2163       // Effectively: if (succ == null) goto SlowPath
2164       // The code reduces the window for a race, however,
2165       // and thus benefits performance.
2166       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2167       jccb  (Assembler::zero, LGoSlowPath);
2168 
2169       if ((EmitSync & 16) && os::is_MP()) {
2170         orptr(boxReg, boxReg);
2171         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2172       } else {
2173         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2174         if (os::is_MP()) {
2175           // Memory barrier/fence
2176           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2177           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2178           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2179           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2180           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2181           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2182           lock(); addl(Address(rsp, 0), 0);
2183         }
2184       }
2185       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2186       jccb  (Assembler::notZero, LSuccess);
2187 
2188       // Rare inopportune interleaving - race.
2189       // The successor vanished in the small window above.
2190       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2191       // We need to ensure progress and succession.
2192       // Try to reacquire the lock.
2193       // If that fails then the new owner is responsible for succession and this
2194       // thread needs to take no further action and can exit via the fast path (success).
2195       // If the re-acquire succeeds then pass control into the slow path.
2196       // As implemented, this latter mode is horrible because we generated more
2197       // coherence traffic on the lock *and* artifically extended the critical section
2198       // length while by virtue of passing control into the slow path.
2199 
2200       // box is really RAX -- the following CMPXCHG depends on that binding
2201       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2202       movptr(boxReg, (int32_t)NULL_WORD);
2203       if (os::is_MP()) { lock(); }
2204       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2205       // There's no successor so we tried to regrab the lock.
2206       // If that didn't work, then another thread grabbed the
2207       // lock so we're done (and exit was a success).
2208       jccb  (Assembler::notEqual, LSuccess);
2209       // Intentional fall-through into slow-path
2210 
2211       bind  (LGoSlowPath);
2212       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2213       jmpb  (DONE_LABEL);
2214 
2215       bind  (LSuccess);
2216       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2217       jmpb  (DONE_LABEL);
2218     }
2219 
2220     bind  (Stacked);
2221     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2222     if (os::is_MP()) { lock(); }
2223     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2224 
2225     if (EmitSync & 65536) {
2226        bind (CheckSucc);
2227     }
2228 #endif
2229     bind(DONE_LABEL);
2230   }
2231 }
2232 #endif // COMPILER2
2233 
2234 void MacroAssembler::c2bool(Register x) {
2235   // implements x == 0 ? 0 : 1
2236   // note: must only look at least-significant byte of x
2237   //       since C-style booleans are stored in one byte
2238   //       only! (was bug)
2239   andl(x, 0xFF);
2240   setb(Assembler::notZero, x);
2241 }
2242 
2243 // Wouldn't need if AddressLiteral version had new name
2244 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2245   Assembler::call(L, rtype);
2246 }
2247 
2248 void MacroAssembler::call(Register entry) {
2249   Assembler::call(entry);
2250 }
2251 
2252 void MacroAssembler::call(AddressLiteral entry) {
2253   if (reachable(entry)) {
2254     Assembler::call_literal(entry.target(), entry.rspec());
2255   } else {
2256     lea(rscratch1, entry);
2257     Assembler::call(rscratch1);
2258   }
2259 }
2260 
2261 void MacroAssembler::ic_call(address entry) {
2262   RelocationHolder rh = virtual_call_Relocation::spec(pc());
2263   movptr(rax, (intptr_t)Universe::non_oop_word());
2264   call(AddressLiteral(entry, rh));
2265 }
2266 
2267 // Implementation of call_VM versions
2268 
2269 void MacroAssembler::call_VM(Register oop_result,
2270                              address entry_point,
2271                              bool check_exceptions) {
2272   Label C, E;
2273   call(C, relocInfo::none);
2274   jmp(E);
2275 
2276   bind(C);
2277   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2278   ret(0);
2279 
2280   bind(E);
2281 }
2282 
2283 void MacroAssembler::call_VM(Register oop_result,
2284                              address entry_point,
2285                              Register arg_1,
2286                              bool check_exceptions) {
2287   Label C, E;
2288   call(C, relocInfo::none);
2289   jmp(E);
2290 
2291   bind(C);
2292   pass_arg1(this, arg_1);
2293   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2294   ret(0);
2295 
2296   bind(E);
2297 }
2298 
2299 void MacroAssembler::call_VM(Register oop_result,
2300                              address entry_point,
2301                              Register arg_1,
2302                              Register arg_2,
2303                              bool check_exceptions) {
2304   Label C, E;
2305   call(C, relocInfo::none);
2306   jmp(E);
2307 
2308   bind(C);
2309 
2310   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2311 
2312   pass_arg2(this, arg_2);
2313   pass_arg1(this, arg_1);
2314   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2315   ret(0);
2316 
2317   bind(E);
2318 }
2319 
2320 void MacroAssembler::call_VM(Register oop_result,
2321                              address entry_point,
2322                              Register arg_1,
2323                              Register arg_2,
2324                              Register arg_3,
2325                              bool check_exceptions) {
2326   Label C, E;
2327   call(C, relocInfo::none);
2328   jmp(E);
2329 
2330   bind(C);
2331 
2332   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2333   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2334   pass_arg3(this, arg_3);
2335 
2336   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2337   pass_arg2(this, arg_2);
2338 
2339   pass_arg1(this, arg_1);
2340   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2341   ret(0);
2342 
2343   bind(E);
2344 }
2345 
2346 void MacroAssembler::call_VM(Register oop_result,
2347                              Register last_java_sp,
2348                              address entry_point,
2349                              int number_of_arguments,
2350                              bool check_exceptions) {
2351   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2352   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2353 }
2354 
2355 void MacroAssembler::call_VM(Register oop_result,
2356                              Register last_java_sp,
2357                              address entry_point,
2358                              Register arg_1,
2359                              bool check_exceptions) {
2360   pass_arg1(this, arg_1);
2361   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2362 }
2363 
2364 void MacroAssembler::call_VM(Register oop_result,
2365                              Register last_java_sp,
2366                              address entry_point,
2367                              Register arg_1,
2368                              Register arg_2,
2369                              bool check_exceptions) {
2370 
2371   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2372   pass_arg2(this, arg_2);
2373   pass_arg1(this, arg_1);
2374   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2375 }
2376 
2377 void MacroAssembler::call_VM(Register oop_result,
2378                              Register last_java_sp,
2379                              address entry_point,
2380                              Register arg_1,
2381                              Register arg_2,
2382                              Register arg_3,
2383                              bool check_exceptions) {
2384   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2385   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2386   pass_arg3(this, arg_3);
2387   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2388   pass_arg2(this, arg_2);
2389   pass_arg1(this, arg_1);
2390   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2391 }
2392 
2393 void MacroAssembler::super_call_VM(Register oop_result,
2394                                    Register last_java_sp,
2395                                    address entry_point,
2396                                    int number_of_arguments,
2397                                    bool check_exceptions) {
2398   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2399   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2400 }
2401 
2402 void MacroAssembler::super_call_VM(Register oop_result,
2403                                    Register last_java_sp,
2404                                    address entry_point,
2405                                    Register arg_1,
2406                                    bool check_exceptions) {
2407   pass_arg1(this, arg_1);
2408   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2409 }
2410 
2411 void MacroAssembler::super_call_VM(Register oop_result,
2412                                    Register last_java_sp,
2413                                    address entry_point,
2414                                    Register arg_1,
2415                                    Register arg_2,
2416                                    bool check_exceptions) {
2417 
2418   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2419   pass_arg2(this, arg_2);
2420   pass_arg1(this, arg_1);
2421   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2422 }
2423 
2424 void MacroAssembler::super_call_VM(Register oop_result,
2425                                    Register last_java_sp,
2426                                    address entry_point,
2427                                    Register arg_1,
2428                                    Register arg_2,
2429                                    Register arg_3,
2430                                    bool check_exceptions) {
2431   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2432   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2433   pass_arg3(this, arg_3);
2434   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2435   pass_arg2(this, arg_2);
2436   pass_arg1(this, arg_1);
2437   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2438 }
2439 
2440 void MacroAssembler::call_VM_base(Register oop_result,
2441                                   Register java_thread,
2442                                   Register last_java_sp,
2443                                   address  entry_point,
2444                                   int      number_of_arguments,
2445                                   bool     check_exceptions) {
2446   // determine java_thread register
2447   if (!java_thread->is_valid()) {
2448 #ifdef _LP64
2449     java_thread = r15_thread;
2450 #else
2451     java_thread = rdi;
2452     get_thread(java_thread);
2453 #endif // LP64
2454   }
2455   // determine last_java_sp register
2456   if (!last_java_sp->is_valid()) {
2457     last_java_sp = rsp;
2458   }
2459   // debugging support
2460   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2461   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2462 #ifdef ASSERT
2463   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2464   // r12 is the heapbase.
2465   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2466 #endif // ASSERT
2467 
2468   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2469   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2470 
2471   // push java thread (becomes first argument of C function)
2472 
2473   NOT_LP64(push(java_thread); number_of_arguments++);
2474   LP64_ONLY(mov(c_rarg0, r15_thread));
2475 
2476   // set last Java frame before call
2477   assert(last_java_sp != rbp, "can't use ebp/rbp");
2478 
2479   // Only interpreter should have to set fp
2480   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2481 
2482   // do the call, remove parameters
2483   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2484 
2485   // restore the thread (cannot use the pushed argument since arguments
2486   // may be overwritten by C code generated by an optimizing compiler);
2487   // however can use the register value directly if it is callee saved.
2488   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2489     // rdi & rsi (also r15) are callee saved -> nothing to do
2490 #ifdef ASSERT
2491     guarantee(java_thread != rax, "change this code");
2492     push(rax);
2493     { Label L;
2494       get_thread(rax);
2495       cmpptr(java_thread, rax);
2496       jcc(Assembler::equal, L);
2497       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2498       bind(L);
2499     }
2500     pop(rax);
2501 #endif
2502   } else {
2503     get_thread(java_thread);
2504   }
2505   // reset last Java frame
2506   // Only interpreter should have to clear fp
2507   reset_last_Java_frame(java_thread, true, false);
2508 
2509 #ifndef CC_INTERP
2510    // C++ interp handles this in the interpreter
2511   check_and_handle_popframe(java_thread);
2512   check_and_handle_earlyret(java_thread);
2513 #endif /* CC_INTERP */
2514 
2515   if (check_exceptions) {
2516     // check for pending exceptions (java_thread is set upon return)
2517     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2518 #ifndef _LP64
2519     jump_cc(Assembler::notEqual,
2520             RuntimeAddress(StubRoutines::forward_exception_entry()));
2521 #else
2522     // This used to conditionally jump to forward_exception however it is
2523     // possible if we relocate that the branch will not reach. So we must jump
2524     // around so we can always reach
2525 
2526     Label ok;
2527     jcc(Assembler::equal, ok);
2528     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2529     bind(ok);
2530 #endif // LP64
2531   }
2532 
2533   // get oop result if there is one and reset the value in the thread
2534   if (oop_result->is_valid()) {
2535     get_vm_result(oop_result, java_thread);
2536   }
2537 }
2538 
2539 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2540 
2541   // Calculate the value for last_Java_sp
2542   // somewhat subtle. call_VM does an intermediate call
2543   // which places a return address on the stack just under the
2544   // stack pointer as the user finsihed with it. This allows
2545   // use to retrieve last_Java_pc from last_Java_sp[-1].
2546   // On 32bit we then have to push additional args on the stack to accomplish
2547   // the actual requested call. On 64bit call_VM only can use register args
2548   // so the only extra space is the return address that call_VM created.
2549   // This hopefully explains the calculations here.
2550 
2551 #ifdef _LP64
2552   // We've pushed one address, correct last_Java_sp
2553   lea(rax, Address(rsp, wordSize));
2554 #else
2555   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2556 #endif // LP64
2557 
2558   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2559 
2560 }
2561 
2562 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2563   call_VM_leaf_base(entry_point, number_of_arguments);
2564 }
2565 
2566 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2567   pass_arg0(this, arg_0);
2568   call_VM_leaf(entry_point, 1);
2569 }
2570 
2571 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2572 
2573   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2574   pass_arg1(this, arg_1);
2575   pass_arg0(this, arg_0);
2576   call_VM_leaf(entry_point, 2);
2577 }
2578 
2579 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2580   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2581   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2582   pass_arg2(this, arg_2);
2583   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2584   pass_arg1(this, arg_1);
2585   pass_arg0(this, arg_0);
2586   call_VM_leaf(entry_point, 3);
2587 }
2588 
2589 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2590   pass_arg0(this, arg_0);
2591   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2592 }
2593 
2594 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2595 
2596   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2597   pass_arg1(this, arg_1);
2598   pass_arg0(this, arg_0);
2599   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2600 }
2601 
2602 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2603   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2604   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2605   pass_arg2(this, arg_2);
2606   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2607   pass_arg1(this, arg_1);
2608   pass_arg0(this, arg_0);
2609   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2610 }
2611 
2612 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2613   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2614   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2615   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2616   pass_arg3(this, arg_3);
2617   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2618   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2619   pass_arg2(this, arg_2);
2620   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2621   pass_arg1(this, arg_1);
2622   pass_arg0(this, arg_0);
2623   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2624 }
2625 
2626 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2627   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2628   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2629   verify_oop(oop_result, "broken oop in call_VM_base");
2630 }
2631 
2632 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2633   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2634   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2635 }
2636 
2637 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2638 }
2639 
2640 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2641 }
2642 
2643 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2644   if (reachable(src1)) {
2645     cmpl(as_Address(src1), imm);
2646   } else {
2647     lea(rscratch1, src1);
2648     cmpl(Address(rscratch1, 0), imm);
2649   }
2650 }
2651 
2652 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2653   assert(!src2.is_lval(), "use cmpptr");
2654   if (reachable(src2)) {
2655     cmpl(src1, as_Address(src2));
2656   } else {
2657     lea(rscratch1, src2);
2658     cmpl(src1, Address(rscratch1, 0));
2659   }
2660 }
2661 
2662 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2663   Assembler::cmpl(src1, imm);
2664 }
2665 
2666 void MacroAssembler::cmp32(Register src1, Address src2) {
2667   Assembler::cmpl(src1, src2);
2668 }
2669 
2670 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2671   ucomisd(opr1, opr2);
2672 
2673   Label L;
2674   if (unordered_is_less) {
2675     movl(dst, -1);
2676     jcc(Assembler::parity, L);
2677     jcc(Assembler::below , L);
2678     movl(dst, 0);
2679     jcc(Assembler::equal , L);
2680     increment(dst);
2681   } else { // unordered is greater
2682     movl(dst, 1);
2683     jcc(Assembler::parity, L);
2684     jcc(Assembler::above , L);
2685     movl(dst, 0);
2686     jcc(Assembler::equal , L);
2687     decrementl(dst);
2688   }
2689   bind(L);
2690 }
2691 
2692 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2693   ucomiss(opr1, opr2);
2694 
2695   Label L;
2696   if (unordered_is_less) {
2697     movl(dst, -1);
2698     jcc(Assembler::parity, L);
2699     jcc(Assembler::below , L);
2700     movl(dst, 0);
2701     jcc(Assembler::equal , L);
2702     increment(dst);
2703   } else { // unordered is greater
2704     movl(dst, 1);
2705     jcc(Assembler::parity, L);
2706     jcc(Assembler::above , L);
2707     movl(dst, 0);
2708     jcc(Assembler::equal , L);
2709     decrementl(dst);
2710   }
2711   bind(L);
2712 }
2713 
2714 
2715 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2716   if (reachable(src1)) {
2717     cmpb(as_Address(src1), imm);
2718   } else {
2719     lea(rscratch1, src1);
2720     cmpb(Address(rscratch1, 0), imm);
2721   }
2722 }
2723 
2724 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2725 #ifdef _LP64
2726   if (src2.is_lval()) {
2727     movptr(rscratch1, src2);
2728     Assembler::cmpq(src1, rscratch1);
2729   } else if (reachable(src2)) {
2730     cmpq(src1, as_Address(src2));
2731   } else {
2732     lea(rscratch1, src2);
2733     Assembler::cmpq(src1, Address(rscratch1, 0));
2734   }
2735 #else
2736   if (src2.is_lval()) {
2737     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2738   } else {
2739     cmpl(src1, as_Address(src2));
2740   }
2741 #endif // _LP64
2742 }
2743 
2744 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2745   assert(src2.is_lval(), "not a mem-mem compare");
2746 #ifdef _LP64
2747   // moves src2's literal address
2748   movptr(rscratch1, src2);
2749   Assembler::cmpq(src1, rscratch1);
2750 #else
2751   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2752 #endif // _LP64
2753 }
2754 
2755 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2756   if (reachable(adr)) {
2757     if (os::is_MP())
2758       lock();
2759     cmpxchgptr(reg, as_Address(adr));
2760   } else {
2761     lea(rscratch1, adr);
2762     if (os::is_MP())
2763       lock();
2764     cmpxchgptr(reg, Address(rscratch1, 0));
2765   }
2766 }
2767 
2768 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2769   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2770 }
2771 
2772 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2773   if (reachable(src)) {
2774     Assembler::comisd(dst, as_Address(src));
2775   } else {
2776     lea(rscratch1, src);
2777     Assembler::comisd(dst, Address(rscratch1, 0));
2778   }
2779 }
2780 
2781 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2782   if (reachable(src)) {
2783     Assembler::comiss(dst, as_Address(src));
2784   } else {
2785     lea(rscratch1, src);
2786     Assembler::comiss(dst, Address(rscratch1, 0));
2787   }
2788 }
2789 
2790 
2791 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2792   Condition negated_cond = negate_condition(cond);
2793   Label L;
2794   jcc(negated_cond, L);
2795   pushf(); // Preserve flags
2796   atomic_incl(counter_addr);
2797   popf();
2798   bind(L);
2799 }
2800 
2801 int MacroAssembler::corrected_idivl(Register reg) {
2802   // Full implementation of Java idiv and irem; checks for
2803   // special case as described in JVM spec., p.243 & p.271.
2804   // The function returns the (pc) offset of the idivl
2805   // instruction - may be needed for implicit exceptions.
2806   //
2807   //         normal case                           special case
2808   //
2809   // input : rax,: dividend                         min_int
2810   //         reg: divisor   (may not be rax,/rdx)   -1
2811   //
2812   // output: rax,: quotient  (= rax, idiv reg)       min_int
2813   //         rdx: remainder (= rax, irem reg)       0
2814   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2815   const int min_int = 0x80000000;
2816   Label normal_case, special_case;
2817 
2818   // check for special case
2819   cmpl(rax, min_int);
2820   jcc(Assembler::notEqual, normal_case);
2821   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2822   cmpl(reg, -1);
2823   jcc(Assembler::equal, special_case);
2824 
2825   // handle normal case
2826   bind(normal_case);
2827   cdql();
2828   int idivl_offset = offset();
2829   idivl(reg);
2830 
2831   // normal and special case exit
2832   bind(special_case);
2833 
2834   return idivl_offset;
2835 }
2836 
2837 
2838 
2839 void MacroAssembler::decrementl(Register reg, int value) {
2840   if (value == min_jint) {subl(reg, value) ; return; }
2841   if (value <  0) { incrementl(reg, -value); return; }
2842   if (value == 0) {                        ; return; }
2843   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2844   /* else */      { subl(reg, value)       ; return; }
2845 }
2846 
2847 void MacroAssembler::decrementl(Address dst, int value) {
2848   if (value == min_jint) {subl(dst, value) ; return; }
2849   if (value <  0) { incrementl(dst, -value); return; }
2850   if (value == 0) {                        ; return; }
2851   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2852   /* else */      { subl(dst, value)       ; return; }
2853 }
2854 
2855 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2856   assert (shift_value > 0, "illegal shift value");
2857   Label _is_positive;
2858   testl (reg, reg);
2859   jcc (Assembler::positive, _is_positive);
2860   int offset = (1 << shift_value) - 1 ;
2861 
2862   if (offset == 1) {
2863     incrementl(reg);
2864   } else {
2865     addl(reg, offset);
2866   }
2867 
2868   bind (_is_positive);
2869   sarl(reg, shift_value);
2870 }
2871 
2872 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2873   if (reachable(src)) {
2874     Assembler::divsd(dst, as_Address(src));
2875   } else {
2876     lea(rscratch1, src);
2877     Assembler::divsd(dst, Address(rscratch1, 0));
2878   }
2879 }
2880 
2881 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2882   if (reachable(src)) {
2883     Assembler::divss(dst, as_Address(src));
2884   } else {
2885     lea(rscratch1, src);
2886     Assembler::divss(dst, Address(rscratch1, 0));
2887   }
2888 }
2889 
2890 // !defined(COMPILER2) is because of stupid core builds
2891 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2)
2892 void MacroAssembler::empty_FPU_stack() {
2893   if (VM_Version::supports_mmx()) {
2894     emms();
2895   } else {
2896     for (int i = 8; i-- > 0; ) ffree(i);
2897   }
2898 }
2899 #endif // !LP64 || C1 || !C2
2900 
2901 
2902 // Defines obj, preserves var_size_in_bytes
2903 void MacroAssembler::eden_allocate(Register obj,
2904                                    Register var_size_in_bytes,
2905                                    int con_size_in_bytes,
2906                                    Register t1,
2907                                    Label& slow_case) {
2908   assert(obj == rax, "obj must be in rax, for cmpxchg");
2909   assert_different_registers(obj, var_size_in_bytes, t1);
2910   if (!Universe::heap()->supports_inline_contig_alloc()) {
2911     jmp(slow_case);
2912   } else {
2913     Register end = t1;
2914     Label retry;
2915     bind(retry);
2916     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2917     movptr(obj, heap_top);
2918     if (var_size_in_bytes == noreg) {
2919       lea(end, Address(obj, con_size_in_bytes));
2920     } else {
2921       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2922     }
2923     // if end < obj then we wrapped around => object too long => slow case
2924     cmpptr(end, obj);
2925     jcc(Assembler::below, slow_case);
2926     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2927     jcc(Assembler::above, slow_case);
2928     // Compare obj with the top addr, and if still equal, store the new top addr in
2929     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2930     // it otherwise. Use lock prefix for atomicity on MPs.
2931     locked_cmpxchgptr(end, heap_top);
2932     jcc(Assembler::notEqual, retry);
2933   }
2934 }
2935 
2936 void MacroAssembler::enter() {
2937   push(rbp);
2938   mov(rbp, rsp);
2939 }
2940 
2941 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2942 void MacroAssembler::fat_nop() {
2943   if (UseAddressNop) {
2944     addr_nop_5();
2945   } else {
2946     emit_int8(0x26); // es:
2947     emit_int8(0x2e); // cs:
2948     emit_int8(0x64); // fs:
2949     emit_int8(0x65); // gs:
2950     emit_int8((unsigned char)0x90);
2951   }
2952 }
2953 
2954 void MacroAssembler::fcmp(Register tmp) {
2955   fcmp(tmp, 1, true, true);
2956 }
2957 
2958 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2959   assert(!pop_right || pop_left, "usage error");
2960   if (VM_Version::supports_cmov()) {
2961     assert(tmp == noreg, "unneeded temp");
2962     if (pop_left) {
2963       fucomip(index);
2964     } else {
2965       fucomi(index);
2966     }
2967     if (pop_right) {
2968       fpop();
2969     }
2970   } else {
2971     assert(tmp != noreg, "need temp");
2972     if (pop_left) {
2973       if (pop_right) {
2974         fcompp();
2975       } else {
2976         fcomp(index);
2977       }
2978     } else {
2979       fcom(index);
2980     }
2981     // convert FPU condition into eflags condition via rax,
2982     save_rax(tmp);
2983     fwait(); fnstsw_ax();
2984     sahf();
2985     restore_rax(tmp);
2986   }
2987   // condition codes set as follows:
2988   //
2989   // CF (corresponds to C0) if x < y
2990   // PF (corresponds to C2) if unordered
2991   // ZF (corresponds to C3) if x = y
2992 }
2993 
2994 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
2995   fcmp2int(dst, unordered_is_less, 1, true, true);
2996 }
2997 
2998 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
2999   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3000   Label L;
3001   if (unordered_is_less) {
3002     movl(dst, -1);
3003     jcc(Assembler::parity, L);
3004     jcc(Assembler::below , L);
3005     movl(dst, 0);
3006     jcc(Assembler::equal , L);
3007     increment(dst);
3008   } else { // unordered is greater
3009     movl(dst, 1);
3010     jcc(Assembler::parity, L);
3011     jcc(Assembler::above , L);
3012     movl(dst, 0);
3013     jcc(Assembler::equal , L);
3014     decrementl(dst);
3015   }
3016   bind(L);
3017 }
3018 
3019 void MacroAssembler::fld_d(AddressLiteral src) {
3020   fld_d(as_Address(src));
3021 }
3022 
3023 void MacroAssembler::fld_s(AddressLiteral src) {
3024   fld_s(as_Address(src));
3025 }
3026 
3027 void MacroAssembler::fld_x(AddressLiteral src) {
3028   Assembler::fld_x(as_Address(src));
3029 }
3030 
3031 void MacroAssembler::fldcw(AddressLiteral src) {
3032   Assembler::fldcw(as_Address(src));
3033 }
3034 
3035 void MacroAssembler::pow_exp_core_encoding() {
3036   // kills rax, rcx, rdx
3037   subptr(rsp,sizeof(jdouble));
3038   // computes 2^X. Stack: X ...
3039   // f2xm1 computes 2^X-1 but only operates on -1<=X<=1. Get int(X) and
3040   // keep it on the thread's stack to compute 2^int(X) later
3041   // then compute 2^(X-int(X)) as (2^(X-int(X)-1+1)
3042   // final result is obtained with: 2^X = 2^int(X) * 2^(X-int(X))
3043   fld_s(0);                 // Stack: X X ...
3044   frndint();                // Stack: int(X) X ...
3045   fsuba(1);                 // Stack: int(X) X-int(X) ...
3046   fistp_s(Address(rsp,0));  // move int(X) as integer to thread's stack. Stack: X-int(X) ...
3047   f2xm1();                  // Stack: 2^(X-int(X))-1 ...
3048   fld1();                   // Stack: 1 2^(X-int(X))-1 ...
3049   faddp(1);                 // Stack: 2^(X-int(X))
3050   // computes 2^(int(X)): add exponent bias (1023) to int(X), then
3051   // shift int(X)+1023 to exponent position.
3052   // Exponent is limited to 11 bits if int(X)+1023 does not fit in 11
3053   // bits, set result to NaN. 0x000 and 0x7FF are reserved exponent
3054   // values so detect them and set result to NaN.
3055   movl(rax,Address(rsp,0));
3056   movl(rcx, -2048); // 11 bit mask and valid NaN binary encoding
3057   addl(rax, 1023);
3058   movl(rdx,rax);
3059   shll(rax,20);
3060   // Check that 0 < int(X)+1023 < 2047. Otherwise set rax to NaN.
3061   addl(rdx,1);
3062   // Check that 1 < int(X)+1023+1 < 2048
3063   // in 3 steps:
3064   // 1- (int(X)+1023+1)&-2048 == 0 => 0 <= int(X)+1023+1 < 2048
3065   // 2- (int(X)+1023+1)&-2048 != 0
3066   // 3- (int(X)+1023+1)&-2048 != 1
3067   // Do 2- first because addl just updated the flags.
3068   cmov32(Assembler::equal,rax,rcx);
3069   cmpl(rdx,1);
3070   cmov32(Assembler::equal,rax,rcx);
3071   testl(rdx,rcx);
3072   cmov32(Assembler::notEqual,rax,rcx);
3073   movl(Address(rsp,4),rax);
3074   movl(Address(rsp,0),0);
3075   fmul_d(Address(rsp,0));   // Stack: 2^X ...
3076   addptr(rsp,sizeof(jdouble));
3077 }
3078 
3079 void MacroAssembler::increase_precision() {
3080   subptr(rsp, BytesPerWord);
3081   fnstcw(Address(rsp, 0));
3082   movl(rax, Address(rsp, 0));
3083   orl(rax, 0x300);
3084   push(rax);
3085   fldcw(Address(rsp, 0));
3086   pop(rax);
3087 }
3088 
3089 void MacroAssembler::restore_precision() {
3090   fldcw(Address(rsp, 0));
3091   addptr(rsp, BytesPerWord);
3092 }
3093 
3094 void MacroAssembler::fast_pow() {
3095   // computes X^Y = 2^(Y * log2(X))
3096   // if fast computation is not possible, result is NaN. Requires
3097   // fallback from user of this macro.
3098   // increase precision for intermediate steps of the computation
3099   BLOCK_COMMENT("fast_pow {");
3100   increase_precision();
3101   fyl2x();                 // Stack: (Y*log2(X)) ...
3102   pow_exp_core_encoding(); // Stack: exp(X) ...
3103   restore_precision();
3104   BLOCK_COMMENT("} fast_pow");
3105 }
3106 
3107 void MacroAssembler::fast_exp() {
3108   // computes exp(X) = 2^(X * log2(e))
3109   // if fast computation is not possible, result is NaN. Requires
3110   // fallback from user of this macro.
3111   // increase precision for intermediate steps of the computation
3112   increase_precision();
3113   fldl2e();                // Stack: log2(e) X ...
3114   fmulp(1);                // Stack: (X*log2(e)) ...
3115   pow_exp_core_encoding(); // Stack: exp(X) ...
3116   restore_precision();
3117 }
3118 
3119 void MacroAssembler::pow_or_exp(bool is_exp, int num_fpu_regs_in_use) {
3120   // kills rax, rcx, rdx
3121   // pow and exp needs 2 extra registers on the fpu stack.
3122   Label slow_case, done;
3123   Register tmp = noreg;
3124   if (!VM_Version::supports_cmov()) {
3125     // fcmp needs a temporary so preserve rdx,
3126     tmp = rdx;
3127   }
3128   Register tmp2 = rax;
3129   Register tmp3 = rcx;
3130 
3131   if (is_exp) {
3132     // Stack: X
3133     fld_s(0);                   // duplicate argument for runtime call. Stack: X X
3134     fast_exp();                 // Stack: exp(X) X
3135     fcmp(tmp, 0, false, false); // Stack: exp(X) X
3136     // exp(X) not equal to itself: exp(X) is NaN go to slow case.
3137     jcc(Assembler::parity, slow_case);
3138     // get rid of duplicate argument. Stack: exp(X)
3139     if (num_fpu_regs_in_use > 0) {
3140       fxch();
3141       fpop();
3142     } else {
3143       ffree(1);
3144     }
3145     jmp(done);
3146   } else {
3147     // Stack: X Y
3148     Label x_negative, y_not_2;
3149 
3150     static double two = 2.0;
3151     ExternalAddress two_addr((address)&two);
3152 
3153     // constant maybe too far on 64 bit
3154     lea(tmp2, two_addr);
3155     fld_d(Address(tmp2, 0));    // Stack: 2 X Y
3156     fcmp(tmp, 2, true, false);  // Stack: X Y
3157     jcc(Assembler::parity, y_not_2);
3158     jcc(Assembler::notEqual, y_not_2);
3159 
3160     fxch(); fpop();             // Stack: X
3161     fmul(0);                    // Stack: X*X
3162 
3163     jmp(done);
3164 
3165     bind(y_not_2);
3166 
3167     fldz();                     // Stack: 0 X Y
3168     fcmp(tmp, 1, true, false);  // Stack: X Y
3169     jcc(Assembler::above, x_negative);
3170 
3171     // X >= 0
3172 
3173     fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3174     fld_s(1);                   // Stack: X Y X Y
3175     fast_pow();                 // Stack: X^Y X Y
3176     fcmp(tmp, 0, false, false); // Stack: X^Y X Y
3177     // X^Y not equal to itself: X^Y is NaN go to slow case.
3178     jcc(Assembler::parity, slow_case);
3179     // get rid of duplicate arguments. Stack: X^Y
3180     if (num_fpu_regs_in_use > 0) {
3181       fxch(); fpop();
3182       fxch(); fpop();
3183     } else {
3184       ffree(2);
3185       ffree(1);
3186     }
3187     jmp(done);
3188 
3189     // X <= 0
3190     bind(x_negative);
3191 
3192     fld_s(1);                   // Stack: Y X Y
3193     frndint();                  // Stack: int(Y) X Y
3194     fcmp(tmp, 2, false, false); // Stack: int(Y) X Y
3195     jcc(Assembler::notEqual, slow_case);
3196 
3197     subptr(rsp, 8);
3198 
3199     // For X^Y, when X < 0, Y has to be an integer and the final
3200     // result depends on whether it's odd or even. We just checked
3201     // that int(Y) == Y.  We move int(Y) to gp registers as a 64 bit
3202     // integer to test its parity. If int(Y) is huge and doesn't fit
3203     // in the 64 bit integer range, the integer indefinite value will
3204     // end up in the gp registers. Huge numbers are all even, the
3205     // integer indefinite number is even so it's fine.
3206 
3207 #ifdef ASSERT
3208     // Let's check we don't end up with an integer indefinite number
3209     // when not expected. First test for huge numbers: check whether
3210     // int(Y)+1 == int(Y) which is true for very large numbers and
3211     // those are all even. A 64 bit integer is guaranteed to not
3212     // overflow for numbers where y+1 != y (when precision is set to
3213     // double precision).
3214     Label y_not_huge;
3215 
3216     fld1();                     // Stack: 1 int(Y) X Y
3217     fadd(1);                    // Stack: 1+int(Y) int(Y) X Y
3218 
3219 #ifdef _LP64
3220     // trip to memory to force the precision down from double extended
3221     // precision
3222     fstp_d(Address(rsp, 0));
3223     fld_d(Address(rsp, 0));
3224 #endif
3225 
3226     fcmp(tmp, 1, true, false);  // Stack: int(Y) X Y
3227 #endif
3228 
3229     // move int(Y) as 64 bit integer to thread's stack
3230     fistp_d(Address(rsp,0));    // Stack: X Y
3231 
3232 #ifdef ASSERT
3233     jcc(Assembler::notEqual, y_not_huge);
3234 
3235     // Y is huge so we know it's even. It may not fit in a 64 bit
3236     // integer and we don't want the debug code below to see the
3237     // integer indefinite value so overwrite int(Y) on the thread's
3238     // stack with 0.
3239     movl(Address(rsp, 0), 0);
3240     movl(Address(rsp, 4), 0);
3241 
3242     bind(y_not_huge);
3243 #endif
3244 
3245     fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3246     fld_s(1);                   // Stack: X Y X Y
3247     fabs();                     // Stack: abs(X) Y X Y
3248     fast_pow();                 // Stack: abs(X)^Y X Y
3249     fcmp(tmp, 0, false, false); // Stack: abs(X)^Y X Y
3250     // abs(X)^Y not equal to itself: abs(X)^Y is NaN go to slow case.
3251 
3252     pop(tmp2);
3253     NOT_LP64(pop(tmp3));
3254     jcc(Assembler::parity, slow_case);
3255 
3256 #ifdef ASSERT
3257     // Check that int(Y) is not integer indefinite value (int
3258     // overflow). Shouldn't happen because for values that would
3259     // overflow, 1+int(Y)==Y which was tested earlier.
3260 #ifndef _LP64
3261     {
3262       Label integer;
3263       testl(tmp2, tmp2);
3264       jcc(Assembler::notZero, integer);
3265       cmpl(tmp3, 0x80000000);
3266       jcc(Assembler::notZero, integer);
3267       STOP("integer indefinite value shouldn't be seen here");
3268       bind(integer);
3269     }
3270 #else
3271     {
3272       Label integer;
3273       mov(tmp3, tmp2); // preserve tmp2 for parity check below
3274       shlq(tmp3, 1);
3275       jcc(Assembler::carryClear, integer);
3276       jcc(Assembler::notZero, integer);
3277       STOP("integer indefinite value shouldn't be seen here");
3278       bind(integer);
3279     }
3280 #endif
3281 #endif
3282 
3283     // get rid of duplicate arguments. Stack: X^Y
3284     if (num_fpu_regs_in_use > 0) {
3285       fxch(); fpop();
3286       fxch(); fpop();
3287     } else {
3288       ffree(2);
3289       ffree(1);
3290     }
3291 
3292     testl(tmp2, 1);
3293     jcc(Assembler::zero, done); // X <= 0, Y even: X^Y = abs(X)^Y
3294     // X <= 0, Y even: X^Y = -abs(X)^Y
3295 
3296     fchs();                     // Stack: -abs(X)^Y Y
3297     jmp(done);
3298   }
3299 
3300   // slow case: runtime call
3301   bind(slow_case);
3302 
3303   fpop();                       // pop incorrect result or int(Y)
3304 
3305   fp_runtime_fallback(is_exp ? CAST_FROM_FN_PTR(address, SharedRuntime::dexp) : CAST_FROM_FN_PTR(address, SharedRuntime::dpow),
3306                       is_exp ? 1 : 2, num_fpu_regs_in_use);
3307 
3308   // Come here with result in F-TOS
3309   bind(done);
3310 }
3311 
3312 void MacroAssembler::fpop() {
3313   ffree();
3314   fincstp();
3315 }
3316 
3317 void MacroAssembler::load_float(Address src) {
3318   if (UseSSE >= 1) {
3319     movflt(xmm0, src);
3320   } else {
3321     LP64_ONLY(ShouldNotReachHere());
3322     NOT_LP64(fld_s(src));
3323   }
3324 }
3325 
3326 void MacroAssembler::store_float(Address dst) {
3327   if (UseSSE >= 1) {
3328     movflt(dst, xmm0);
3329   } else {
3330     LP64_ONLY(ShouldNotReachHere());
3331     NOT_LP64(fstp_s(dst));
3332   }
3333 }
3334 
3335 void MacroAssembler::load_double(Address src) {
3336   if (UseSSE >= 2) {
3337     movdbl(xmm0, src);
3338   } else {
3339     LP64_ONLY(ShouldNotReachHere());
3340     NOT_LP64(fld_d(src));
3341   }
3342 }
3343 
3344 void MacroAssembler::store_double(Address dst) {
3345   if (UseSSE >= 2) {
3346     movdbl(dst, xmm0);
3347   } else {
3348     LP64_ONLY(ShouldNotReachHere());
3349     NOT_LP64(fstp_d(dst));
3350   }
3351 }
3352 
3353 void MacroAssembler::fremr(Register tmp) {
3354   save_rax(tmp);
3355   { Label L;
3356     bind(L);
3357     fprem();
3358     fwait(); fnstsw_ax();
3359 #ifdef _LP64
3360     testl(rax, 0x400);
3361     jcc(Assembler::notEqual, L);
3362 #else
3363     sahf();
3364     jcc(Assembler::parity, L);
3365 #endif // _LP64
3366   }
3367   restore_rax(tmp);
3368   // Result is in ST0.
3369   // Note: fxch & fpop to get rid of ST1
3370   // (otherwise FPU stack could overflow eventually)
3371   fxch(1);
3372   fpop();
3373 }
3374 
3375 
3376 void MacroAssembler::incrementl(AddressLiteral dst) {
3377   if (reachable(dst)) {
3378     incrementl(as_Address(dst));
3379   } else {
3380     lea(rscratch1, dst);
3381     incrementl(Address(rscratch1, 0));
3382   }
3383 }
3384 
3385 void MacroAssembler::incrementl(ArrayAddress dst) {
3386   incrementl(as_Address(dst));
3387 }
3388 
3389 void MacroAssembler::incrementl(Register reg, int value) {
3390   if (value == min_jint) {addl(reg, value) ; return; }
3391   if (value <  0) { decrementl(reg, -value); return; }
3392   if (value == 0) {                        ; return; }
3393   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3394   /* else */      { addl(reg, value)       ; return; }
3395 }
3396 
3397 void MacroAssembler::incrementl(Address dst, int value) {
3398   if (value == min_jint) {addl(dst, value) ; return; }
3399   if (value <  0) { decrementl(dst, -value); return; }
3400   if (value == 0) {                        ; return; }
3401   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3402   /* else */      { addl(dst, value)       ; return; }
3403 }
3404 
3405 void MacroAssembler::jump(AddressLiteral dst) {
3406   if (reachable(dst)) {
3407     jmp_literal(dst.target(), dst.rspec());
3408   } else {
3409     lea(rscratch1, dst);
3410     jmp(rscratch1);
3411   }
3412 }
3413 
3414 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3415   if (reachable(dst)) {
3416     InstructionMark im(this);
3417     relocate(dst.reloc());
3418     const int short_size = 2;
3419     const int long_size = 6;
3420     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3421     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3422       // 0111 tttn #8-bit disp
3423       emit_int8(0x70 | cc);
3424       emit_int8((offs - short_size) & 0xFF);
3425     } else {
3426       // 0000 1111 1000 tttn #32-bit disp
3427       emit_int8(0x0F);
3428       emit_int8((unsigned char)(0x80 | cc));
3429       emit_int32(offs - long_size);
3430     }
3431   } else {
3432 #ifdef ASSERT
3433     warning("reversing conditional branch");
3434 #endif /* ASSERT */
3435     Label skip;
3436     jccb(reverse[cc], skip);
3437     lea(rscratch1, dst);
3438     Assembler::jmp(rscratch1);
3439     bind(skip);
3440   }
3441 }
3442 
3443 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3444   if (reachable(src)) {
3445     Assembler::ldmxcsr(as_Address(src));
3446   } else {
3447     lea(rscratch1, src);
3448     Assembler::ldmxcsr(Address(rscratch1, 0));
3449   }
3450 }
3451 
3452 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3453   int off;
3454   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3455     off = offset();
3456     movsbl(dst, src); // movsxb
3457   } else {
3458     off = load_unsigned_byte(dst, src);
3459     shll(dst, 24);
3460     sarl(dst, 24);
3461   }
3462   return off;
3463 }
3464 
3465 // Note: load_signed_short used to be called load_signed_word.
3466 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3467 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3468 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3469 int MacroAssembler::load_signed_short(Register dst, Address src) {
3470   int off;
3471   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3472     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3473     // version but this is what 64bit has always done. This seems to imply
3474     // that users are only using 32bits worth.
3475     off = offset();
3476     movswl(dst, src); // movsxw
3477   } else {
3478     off = load_unsigned_short(dst, src);
3479     shll(dst, 16);
3480     sarl(dst, 16);
3481   }
3482   return off;
3483 }
3484 
3485 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3486   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3487   // and "3.9 Partial Register Penalties", p. 22).
3488   int off;
3489   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3490     off = offset();
3491     movzbl(dst, src); // movzxb
3492   } else {
3493     xorl(dst, dst);
3494     off = offset();
3495     movb(dst, src);
3496   }
3497   return off;
3498 }
3499 
3500 // Note: load_unsigned_short used to be called load_unsigned_word.
3501 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3502   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3503   // and "3.9 Partial Register Penalties", p. 22).
3504   int off;
3505   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3506     off = offset();
3507     movzwl(dst, src); // movzxw
3508   } else {
3509     xorl(dst, dst);
3510     off = offset();
3511     movw(dst, src);
3512   }
3513   return off;
3514 }
3515 
3516 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3517   switch (size_in_bytes) {
3518 #ifndef _LP64
3519   case  8:
3520     assert(dst2 != noreg, "second dest register required");
3521     movl(dst,  src);
3522     movl(dst2, src.plus_disp(BytesPerInt));
3523     break;
3524 #else
3525   case  8:  movq(dst, src); break;
3526 #endif
3527   case  4:  movl(dst, src); break;
3528   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3529   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3530   default:  ShouldNotReachHere();
3531   }
3532 }
3533 
3534 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3535   switch (size_in_bytes) {
3536 #ifndef _LP64
3537   case  8:
3538     assert(src2 != noreg, "second source register required");
3539     movl(dst,                        src);
3540     movl(dst.plus_disp(BytesPerInt), src2);
3541     break;
3542 #else
3543   case  8:  movq(dst, src); break;
3544 #endif
3545   case  4:  movl(dst, src); break;
3546   case  2:  movw(dst, src); break;
3547   case  1:  movb(dst, src); break;
3548   default:  ShouldNotReachHere();
3549   }
3550 }
3551 
3552 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3553   if (reachable(dst)) {
3554     movl(as_Address(dst), src);
3555   } else {
3556     lea(rscratch1, dst);
3557     movl(Address(rscratch1, 0), src);
3558   }
3559 }
3560 
3561 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3562   if (reachable(src)) {
3563     movl(dst, as_Address(src));
3564   } else {
3565     lea(rscratch1, src);
3566     movl(dst, Address(rscratch1, 0));
3567   }
3568 }
3569 
3570 // C++ bool manipulation
3571 
3572 void MacroAssembler::movbool(Register dst, Address src) {
3573   if(sizeof(bool) == 1)
3574     movb(dst, src);
3575   else if(sizeof(bool) == 2)
3576     movw(dst, src);
3577   else if(sizeof(bool) == 4)
3578     movl(dst, src);
3579   else
3580     // unsupported
3581     ShouldNotReachHere();
3582 }
3583 
3584 void MacroAssembler::movbool(Address dst, bool boolconst) {
3585   if(sizeof(bool) == 1)
3586     movb(dst, (int) boolconst);
3587   else if(sizeof(bool) == 2)
3588     movw(dst, (int) boolconst);
3589   else if(sizeof(bool) == 4)
3590     movl(dst, (int) boolconst);
3591   else
3592     // unsupported
3593     ShouldNotReachHere();
3594 }
3595 
3596 void MacroAssembler::movbool(Address dst, Register src) {
3597   if(sizeof(bool) == 1)
3598     movb(dst, src);
3599   else if(sizeof(bool) == 2)
3600     movw(dst, src);
3601   else if(sizeof(bool) == 4)
3602     movl(dst, src);
3603   else
3604     // unsupported
3605     ShouldNotReachHere();
3606 }
3607 
3608 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3609   movb(as_Address(dst), src);
3610 }
3611 
3612 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3613   if (reachable(src)) {
3614     movdl(dst, as_Address(src));
3615   } else {
3616     lea(rscratch1, src);
3617     movdl(dst, Address(rscratch1, 0));
3618   }
3619 }
3620 
3621 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3622   if (reachable(src)) {
3623     movq(dst, as_Address(src));
3624   } else {
3625     lea(rscratch1, src);
3626     movq(dst, Address(rscratch1, 0));
3627   }
3628 }
3629 
3630 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3631   if (reachable(src)) {
3632     if (UseXmmLoadAndClearUpper) {
3633       movsd (dst, as_Address(src));
3634     } else {
3635       movlpd(dst, as_Address(src));
3636     }
3637   } else {
3638     lea(rscratch1, src);
3639     if (UseXmmLoadAndClearUpper) {
3640       movsd (dst, Address(rscratch1, 0));
3641     } else {
3642       movlpd(dst, Address(rscratch1, 0));
3643     }
3644   }
3645 }
3646 
3647 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3648   if (reachable(src)) {
3649     movss(dst, as_Address(src));
3650   } else {
3651     lea(rscratch1, src);
3652     movss(dst, Address(rscratch1, 0));
3653   }
3654 }
3655 
3656 void MacroAssembler::movptr(Register dst, Register src) {
3657   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3658 }
3659 
3660 void MacroAssembler::movptr(Register dst, Address src) {
3661   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3662 }
3663 
3664 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3665 void MacroAssembler::movptr(Register dst, intptr_t src) {
3666   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3667 }
3668 
3669 void MacroAssembler::movptr(Address dst, Register src) {
3670   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3671 }
3672 
3673 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3674   if (reachable(src)) {
3675     Assembler::movdqu(dst, as_Address(src));
3676   } else {
3677     lea(rscratch1, src);
3678     Assembler::movdqu(dst, Address(rscratch1, 0));
3679   }
3680 }
3681 
3682 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3683   if (reachable(src)) {
3684     Assembler::movdqa(dst, as_Address(src));
3685   } else {
3686     lea(rscratch1, src);
3687     Assembler::movdqa(dst, Address(rscratch1, 0));
3688   }
3689 }
3690 
3691 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3692   if (reachable(src)) {
3693     Assembler::movsd(dst, as_Address(src));
3694   } else {
3695     lea(rscratch1, src);
3696     Assembler::movsd(dst, Address(rscratch1, 0));
3697   }
3698 }
3699 
3700 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3701   if (reachable(src)) {
3702     Assembler::movss(dst, as_Address(src));
3703   } else {
3704     lea(rscratch1, src);
3705     Assembler::movss(dst, Address(rscratch1, 0));
3706   }
3707 }
3708 
3709 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3710   if (reachable(src)) {
3711     Assembler::mulsd(dst, as_Address(src));
3712   } else {
3713     lea(rscratch1, src);
3714     Assembler::mulsd(dst, Address(rscratch1, 0));
3715   }
3716 }
3717 
3718 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3719   if (reachable(src)) {
3720     Assembler::mulss(dst, as_Address(src));
3721   } else {
3722     lea(rscratch1, src);
3723     Assembler::mulss(dst, Address(rscratch1, 0));
3724   }
3725 }
3726 
3727 void MacroAssembler::null_check(Register reg, int offset) {
3728   if (needs_explicit_null_check(offset)) {
3729     // provoke OS NULL exception if reg = NULL by
3730     // accessing M[reg] w/o changing any (non-CC) registers
3731     // NOTE: cmpl is plenty here to provoke a segv
3732     cmpptr(rax, Address(reg, 0));
3733     // Note: should probably use testl(rax, Address(reg, 0));
3734     //       may be shorter code (however, this version of
3735     //       testl needs to be implemented first)
3736   } else {
3737     // nothing to do, (later) access of M[reg + offset]
3738     // will provoke OS NULL exception if reg = NULL
3739   }
3740 }
3741 
3742 void MacroAssembler::os_breakpoint() {
3743   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3744   // (e.g., MSVC can't call ps() otherwise)
3745   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3746 }
3747 
3748 void MacroAssembler::pop_CPU_state() {
3749   pop_FPU_state();
3750   pop_IU_state();
3751 }
3752 
3753 void MacroAssembler::pop_FPU_state() {
3754   NOT_LP64(frstor(Address(rsp, 0));)
3755   LP64_ONLY(fxrstor(Address(rsp, 0));)
3756   addptr(rsp, FPUStateSizeInWords * wordSize);
3757 }
3758 
3759 void MacroAssembler::pop_IU_state() {
3760   popa();
3761   LP64_ONLY(addq(rsp, 8));
3762   popf();
3763 }
3764 
3765 // Save Integer and Float state
3766 // Warning: Stack must be 16 byte aligned (64bit)
3767 void MacroAssembler::push_CPU_state() {
3768   push_IU_state();
3769   push_FPU_state();
3770 }
3771 
3772 void MacroAssembler::push_FPU_state() {
3773   subptr(rsp, FPUStateSizeInWords * wordSize);
3774 #ifndef _LP64
3775   fnsave(Address(rsp, 0));
3776   fwait();
3777 #else
3778   fxsave(Address(rsp, 0));
3779 #endif // LP64
3780 }
3781 
3782 void MacroAssembler::push_IU_state() {
3783   // Push flags first because pusha kills them
3784   pushf();
3785   // Make sure rsp stays 16-byte aligned
3786   LP64_ONLY(subq(rsp, 8));
3787   pusha();
3788 }
3789 
3790 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3791   // determine java_thread register
3792   if (!java_thread->is_valid()) {
3793     java_thread = rdi;
3794     get_thread(java_thread);
3795   }
3796   // we must set sp to zero to clear frame
3797   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3798   if (clear_fp) {
3799     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3800   }
3801 
3802   if (clear_pc)
3803     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3804 
3805 }
3806 
3807 void MacroAssembler::restore_rax(Register tmp) {
3808   if (tmp == noreg) pop(rax);
3809   else if (tmp != rax) mov(rax, tmp);
3810 }
3811 
3812 void MacroAssembler::round_to(Register reg, int modulus) {
3813   addptr(reg, modulus - 1);
3814   andptr(reg, -modulus);
3815 }
3816 
3817 void MacroAssembler::save_rax(Register tmp) {
3818   if (tmp == noreg) push(rax);
3819   else if (tmp != rax) mov(tmp, rax);
3820 }
3821 
3822 // Write serialization page so VM thread can do a pseudo remote membar.
3823 // We use the current thread pointer to calculate a thread specific
3824 // offset to write to within the page. This minimizes bus traffic
3825 // due to cache line collision.
3826 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3827   movl(tmp, thread);
3828   shrl(tmp, os::get_serialize_page_shift_count());
3829   andl(tmp, (os::vm_page_size() - sizeof(int)));
3830 
3831   Address index(noreg, tmp, Address::times_1);
3832   ExternalAddress page(os::get_memory_serialize_page());
3833 
3834   // Size of store must match masking code above
3835   movl(as_Address(ArrayAddress(page, index)), tmp);
3836 }
3837 
3838 // Calls to C land
3839 //
3840 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3841 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3842 // has to be reset to 0. This is required to allow proper stack traversal.
3843 void MacroAssembler::set_last_Java_frame(Register java_thread,
3844                                          Register last_java_sp,
3845                                          Register last_java_fp,
3846                                          address  last_java_pc) {
3847   // determine java_thread register
3848   if (!java_thread->is_valid()) {
3849     java_thread = rdi;
3850     get_thread(java_thread);
3851   }
3852   // determine last_java_sp register
3853   if (!last_java_sp->is_valid()) {
3854     last_java_sp = rsp;
3855   }
3856 
3857   // last_java_fp is optional
3858 
3859   if (last_java_fp->is_valid()) {
3860     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3861   }
3862 
3863   // last_java_pc is optional
3864 
3865   if (last_java_pc != NULL) {
3866     lea(Address(java_thread,
3867                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3868         InternalAddress(last_java_pc));
3869 
3870   }
3871   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3872 }
3873 
3874 void MacroAssembler::shlptr(Register dst, int imm8) {
3875   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3876 }
3877 
3878 void MacroAssembler::shrptr(Register dst, int imm8) {
3879   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3880 }
3881 
3882 void MacroAssembler::sign_extend_byte(Register reg) {
3883   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3884     movsbl(reg, reg); // movsxb
3885   } else {
3886     shll(reg, 24);
3887     sarl(reg, 24);
3888   }
3889 }
3890 
3891 void MacroAssembler::sign_extend_short(Register reg) {
3892   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3893     movswl(reg, reg); // movsxw
3894   } else {
3895     shll(reg, 16);
3896     sarl(reg, 16);
3897   }
3898 }
3899 
3900 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3901   assert(reachable(src), "Address should be reachable");
3902   testl(dst, as_Address(src));
3903 }
3904 
3905 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
3906   if (reachable(src)) {
3907     Assembler::sqrtsd(dst, as_Address(src));
3908   } else {
3909     lea(rscratch1, src);
3910     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3911   }
3912 }
3913 
3914 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
3915   if (reachable(src)) {
3916     Assembler::sqrtss(dst, as_Address(src));
3917   } else {
3918     lea(rscratch1, src);
3919     Assembler::sqrtss(dst, Address(rscratch1, 0));
3920   }
3921 }
3922 
3923 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
3924   if (reachable(src)) {
3925     Assembler::subsd(dst, as_Address(src));
3926   } else {
3927     lea(rscratch1, src);
3928     Assembler::subsd(dst, Address(rscratch1, 0));
3929   }
3930 }
3931 
3932 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
3933   if (reachable(src)) {
3934     Assembler::subss(dst, as_Address(src));
3935   } else {
3936     lea(rscratch1, src);
3937     Assembler::subss(dst, Address(rscratch1, 0));
3938   }
3939 }
3940 
3941 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
3942   if (reachable(src)) {
3943     Assembler::ucomisd(dst, as_Address(src));
3944   } else {
3945     lea(rscratch1, src);
3946     Assembler::ucomisd(dst, Address(rscratch1, 0));
3947   }
3948 }
3949 
3950 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
3951   if (reachable(src)) {
3952     Assembler::ucomiss(dst, as_Address(src));
3953   } else {
3954     lea(rscratch1, src);
3955     Assembler::ucomiss(dst, Address(rscratch1, 0));
3956   }
3957 }
3958 
3959 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
3960   // Used in sign-bit flipping with aligned address.
3961   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3962   if (reachable(src)) {
3963     Assembler::xorpd(dst, as_Address(src));
3964   } else {
3965     lea(rscratch1, src);
3966     Assembler::xorpd(dst, Address(rscratch1, 0));
3967   }
3968 }
3969 
3970 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
3971   // Used in sign-bit flipping with aligned address.
3972   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3973   if (reachable(src)) {
3974     Assembler::xorps(dst, as_Address(src));
3975   } else {
3976     lea(rscratch1, src);
3977     Assembler::xorps(dst, Address(rscratch1, 0));
3978   }
3979 }
3980 
3981 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
3982   // Used in sign-bit flipping with aligned address.
3983   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
3984   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
3985   if (reachable(src)) {
3986     Assembler::pshufb(dst, as_Address(src));
3987   } else {
3988     lea(rscratch1, src);
3989     Assembler::pshufb(dst, Address(rscratch1, 0));
3990   }
3991 }
3992 
3993 // AVX 3-operands instructions
3994 
3995 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3996   if (reachable(src)) {
3997     vaddsd(dst, nds, as_Address(src));
3998   } else {
3999     lea(rscratch1, src);
4000     vaddsd(dst, nds, Address(rscratch1, 0));
4001   }
4002 }
4003 
4004 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4005   if (reachable(src)) {
4006     vaddss(dst, nds, as_Address(src));
4007   } else {
4008     lea(rscratch1, src);
4009     vaddss(dst, nds, Address(rscratch1, 0));
4010   }
4011 }
4012 
4013 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4014   if (reachable(src)) {
4015     vandpd(dst, nds, as_Address(src), vector_len);
4016   } else {
4017     lea(rscratch1, src);
4018     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
4019   }
4020 }
4021 
4022 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4023   if (reachable(src)) {
4024     vandps(dst, nds, as_Address(src), vector_len);
4025   } else {
4026     lea(rscratch1, src);
4027     vandps(dst, nds, Address(rscratch1, 0), vector_len);
4028   }
4029 }
4030 
4031 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4032   if (reachable(src)) {
4033     vdivsd(dst, nds, as_Address(src));
4034   } else {
4035     lea(rscratch1, src);
4036     vdivsd(dst, nds, Address(rscratch1, 0));
4037   }
4038 }
4039 
4040 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4041   if (reachable(src)) {
4042     vdivss(dst, nds, as_Address(src));
4043   } else {
4044     lea(rscratch1, src);
4045     vdivss(dst, nds, Address(rscratch1, 0));
4046   }
4047 }
4048 
4049 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4050   if (reachable(src)) {
4051     vmulsd(dst, nds, as_Address(src));
4052   } else {
4053     lea(rscratch1, src);
4054     vmulsd(dst, nds, Address(rscratch1, 0));
4055   }
4056 }
4057 
4058 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4059   if (reachable(src)) {
4060     vmulss(dst, nds, as_Address(src));
4061   } else {
4062     lea(rscratch1, src);
4063     vmulss(dst, nds, Address(rscratch1, 0));
4064   }
4065 }
4066 
4067 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4068   if (reachable(src)) {
4069     vsubsd(dst, nds, as_Address(src));
4070   } else {
4071     lea(rscratch1, src);
4072     vsubsd(dst, nds, Address(rscratch1, 0));
4073   }
4074 }
4075 
4076 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4077   if (reachable(src)) {
4078     vsubss(dst, nds, as_Address(src));
4079   } else {
4080     lea(rscratch1, src);
4081     vsubss(dst, nds, Address(rscratch1, 0));
4082   }
4083 }
4084 
4085 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4086   if (reachable(src)) {
4087     vxorpd(dst, nds, as_Address(src), vector_len);
4088   } else {
4089     lea(rscratch1, src);
4090     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
4091   }
4092 }
4093 
4094 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4095   if (reachable(src)) {
4096     vxorps(dst, nds, as_Address(src), vector_len);
4097   } else {
4098     lea(rscratch1, src);
4099     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
4100   }
4101 }
4102 
4103 
4104 //////////////////////////////////////////////////////////////////////////////////
4105 #if INCLUDE_ALL_GCS
4106 
4107 void MacroAssembler::g1_write_barrier_pre(Register obj,
4108                                           Register pre_val,
4109                                           Register thread,
4110                                           Register tmp,
4111                                           bool tosca_live,
4112                                           bool expand_call) {
4113 
4114   // If expand_call is true then we expand the call_VM_leaf macro
4115   // directly to skip generating the check by
4116   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
4117 
4118 #ifdef _LP64
4119   assert(thread == r15_thread, "must be");
4120 #endif // _LP64
4121 
4122   Label done;
4123   Label runtime;
4124 
4125   assert(pre_val != noreg, "check this code");
4126 
4127   if (obj != noreg) {
4128     assert_different_registers(obj, pre_val, tmp);
4129     assert(pre_val != rax, "check this code");
4130   }
4131 
4132   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4133                                        PtrQueue::byte_offset_of_active()));
4134   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4135                                        PtrQueue::byte_offset_of_index()));
4136   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4137                                        PtrQueue::byte_offset_of_buf()));
4138 
4139 
4140   // Is marking active?
4141   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
4142     cmpl(in_progress, 0);
4143   } else {
4144     assert(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
4145     cmpb(in_progress, 0);
4146   }
4147   jcc(Assembler::equal, done);
4148 
4149   // Do we need to load the previous value?
4150   if (obj != noreg) {
4151     load_heap_oop(pre_val, Address(obj, 0));
4152   }
4153 
4154   // Is the previous value null?
4155   cmpptr(pre_val, (int32_t) NULL_WORD);
4156   jcc(Assembler::equal, done);
4157 
4158   // Can we store original value in the thread's buffer?
4159   // Is index == 0?
4160   // (The index field is typed as size_t.)
4161 
4162   movptr(tmp, index);                   // tmp := *index_adr
4163   cmpptr(tmp, 0);                       // tmp == 0?
4164   jcc(Assembler::equal, runtime);       // If yes, goto runtime
4165 
4166   subptr(tmp, wordSize);                // tmp := tmp - wordSize
4167   movptr(index, tmp);                   // *index_adr := tmp
4168   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
4169 
4170   // Record the previous value
4171   movptr(Address(tmp, 0), pre_val);
4172   jmp(done);
4173 
4174   bind(runtime);
4175   // save the live input values
4176   if(tosca_live) push(rax);
4177 
4178   if (obj != noreg && obj != rax)
4179     push(obj);
4180 
4181   if (pre_val != rax)
4182     push(pre_val);
4183 
4184   // Calling the runtime using the regular call_VM_leaf mechanism generates
4185   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
4186   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
4187   //
4188   // If we care generating the pre-barrier without a frame (e.g. in the
4189   // intrinsified Reference.get() routine) then ebp might be pointing to
4190   // the caller frame and so this check will most likely fail at runtime.
4191   //
4192   // Expanding the call directly bypasses the generation of the check.
4193   // So when we do not have have a full interpreter frame on the stack
4194   // expand_call should be passed true.
4195 
4196   NOT_LP64( push(thread); )
4197 
4198   if (expand_call) {
4199     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
4200     pass_arg1(this, thread);
4201     pass_arg0(this, pre_val);
4202     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
4203   } else {
4204     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
4205   }
4206 
4207   NOT_LP64( pop(thread); )
4208 
4209   // save the live input values
4210   if (pre_val != rax)
4211     pop(pre_val);
4212 
4213   if (obj != noreg && obj != rax)
4214     pop(obj);
4215 
4216   if(tosca_live) pop(rax);
4217 
4218   bind(done);
4219 }
4220 
4221 void MacroAssembler::g1_write_barrier_post(Register store_addr,
4222                                            Register new_val,
4223                                            Register thread,
4224                                            Register tmp,
4225                                            Register tmp2) {
4226 #ifdef _LP64
4227   assert(thread == r15_thread, "must be");
4228 #endif // _LP64
4229 
4230   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
4231                                        PtrQueue::byte_offset_of_index()));
4232   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
4233                                        PtrQueue::byte_offset_of_buf()));
4234 
4235   CardTableModRefBS* ct =
4236     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
4237   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
4238 
4239   Label done;
4240   Label runtime;
4241 
4242   // Does store cross heap regions?
4243 
4244   movptr(tmp, store_addr);
4245   xorptr(tmp, new_val);
4246   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
4247   jcc(Assembler::equal, done);
4248 
4249   // crosses regions, storing NULL?
4250 
4251   cmpptr(new_val, (int32_t) NULL_WORD);
4252   jcc(Assembler::equal, done);
4253 
4254   // storing region crossing non-NULL, is card already dirty?
4255 
4256   const Register card_addr = tmp;
4257   const Register cardtable = tmp2;
4258 
4259   movptr(card_addr, store_addr);
4260   shrptr(card_addr, CardTableModRefBS::card_shift);
4261   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
4262   // a valid address and therefore is not properly handled by the relocation code.
4263   movptr(cardtable, (intptr_t)ct->byte_map_base);
4264   addptr(card_addr, cardtable);
4265 
4266   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
4267   jcc(Assembler::equal, done);
4268 
4269   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
4270   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
4271   jcc(Assembler::equal, done);
4272 
4273 
4274   // storing a region crossing, non-NULL oop, card is clean.
4275   // dirty card and log.
4276 
4277   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
4278 
4279   cmpl(queue_index, 0);
4280   jcc(Assembler::equal, runtime);
4281   subl(queue_index, wordSize);
4282   movptr(tmp2, buffer);
4283 #ifdef _LP64
4284   movslq(rscratch1, queue_index);
4285   addq(tmp2, rscratch1);
4286   movq(Address(tmp2, 0), card_addr);
4287 #else
4288   addl(tmp2, queue_index);
4289   movl(Address(tmp2, 0), card_addr);
4290 #endif
4291   jmp(done);
4292 
4293   bind(runtime);
4294   // save the live input values
4295   push(store_addr);
4296   push(new_val);
4297 #ifdef _LP64
4298   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
4299 #else
4300   push(thread);
4301   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
4302   pop(thread);
4303 #endif
4304   pop(new_val);
4305   pop(store_addr);
4306 
4307   bind(done);
4308 }
4309 
4310 #endif // INCLUDE_ALL_GCS
4311 //////////////////////////////////////////////////////////////////////////////////
4312 
4313 
4314 void MacroAssembler::store_check(Register obj, Address dst) {
4315   store_check(obj);
4316 }
4317 
4318 void MacroAssembler::store_check(Register obj) {
4319   // Does a store check for the oop in register obj. The content of
4320   // register obj is destroyed afterwards.
4321 
4322   BarrierSet* bs = Universe::heap()->barrier_set();
4323   assert(bs->kind() == BarrierSet::CardTableForRS ||
4324          bs->kind() == BarrierSet::CardTableExtension,
4325          "Wrong barrier set kind");
4326 
4327   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
4328   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
4329 
4330   shrptr(obj, CardTableModRefBS::card_shift);
4331 
4332   Address card_addr;
4333 
4334   // The calculation for byte_map_base is as follows:
4335   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
4336   // So this essentially converts an address to a displacement and it will
4337   // never need to be relocated. On 64bit however the value may be too
4338   // large for a 32bit displacement.
4339   intptr_t disp = (intptr_t) ct->byte_map_base;
4340   if (is_simm32(disp)) {
4341     card_addr = Address(noreg, obj, Address::times_1, disp);
4342   } else {
4343     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
4344     // displacement and done in a single instruction given favorable mapping and a
4345     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
4346     // entry and that entry is not properly handled by the relocation code.
4347     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
4348     Address index(noreg, obj, Address::times_1);
4349     card_addr = as_Address(ArrayAddress(cardtable, index));
4350   }
4351 
4352   int dirty = CardTableModRefBS::dirty_card_val();
4353   if (UseCondCardMark) {
4354     Label L_already_dirty;
4355     if (UseConcMarkSweepGC) {
4356       membar(Assembler::StoreLoad);
4357     }
4358     cmpb(card_addr, dirty);
4359     jcc(Assembler::equal, L_already_dirty);
4360     movb(card_addr, dirty);
4361     bind(L_already_dirty);
4362   } else {
4363     movb(card_addr, dirty);
4364   }
4365 }
4366 
4367 void MacroAssembler::subptr(Register dst, int32_t imm32) {
4368   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
4369 }
4370 
4371 // Force generation of a 4 byte immediate value even if it fits into 8bit
4372 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
4373   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
4374 }
4375 
4376 void MacroAssembler::subptr(Register dst, Register src) {
4377   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
4378 }
4379 
4380 // C++ bool manipulation
4381 void MacroAssembler::testbool(Register dst) {
4382   if(sizeof(bool) == 1)
4383     testb(dst, 0xff);
4384   else if(sizeof(bool) == 2) {
4385     // testw implementation needed for two byte bools
4386     ShouldNotReachHere();
4387   } else if(sizeof(bool) == 4)
4388     testl(dst, dst);
4389   else
4390     // unsupported
4391     ShouldNotReachHere();
4392 }
4393 
4394 void MacroAssembler::testptr(Register dst, Register src) {
4395   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
4396 }
4397 
4398 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4399 void MacroAssembler::tlab_allocate(Register obj,
4400                                    Register var_size_in_bytes,
4401                                    int con_size_in_bytes,
4402                                    Register t1,
4403                                    Register t2,
4404                                    Label& slow_case) {
4405   assert_different_registers(obj, t1, t2);
4406   assert_different_registers(obj, var_size_in_bytes, t1);
4407   Register end = t2;
4408   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
4409 
4410   verify_tlab();
4411 
4412   NOT_LP64(get_thread(thread));
4413 
4414   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
4415   if (var_size_in_bytes == noreg) {
4416     lea(end, Address(obj, con_size_in_bytes));
4417   } else {
4418     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
4419   }
4420   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
4421   jcc(Assembler::above, slow_case);
4422 
4423   // update the tlab top pointer
4424   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
4425 
4426   // recover var_size_in_bytes if necessary
4427   if (var_size_in_bytes == end) {
4428     subptr(var_size_in_bytes, obj);
4429   }
4430   verify_tlab();
4431 }
4432 
4433 // Preserves rbx, and rdx.
4434 Register MacroAssembler::tlab_refill(Label& retry,
4435                                      Label& try_eden,
4436                                      Label& slow_case) {
4437   Register top = rax;
4438   Register t1  = rcx;
4439   Register t2  = rsi;
4440   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
4441   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
4442   Label do_refill, discard_tlab;
4443 
4444   if (!Universe::heap()->supports_inline_contig_alloc()) {
4445     // No allocation in the shared eden.
4446     jmp(slow_case);
4447   }
4448 
4449   NOT_LP64(get_thread(thread_reg));
4450 
4451   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4452   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
4453 
4454   // calculate amount of free space
4455   subptr(t1, top);
4456   shrptr(t1, LogHeapWordSize);
4457 
4458   // Retain tlab and allocate object in shared space if
4459   // the amount free in the tlab is too large to discard.
4460   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
4461   jcc(Assembler::lessEqual, discard_tlab);
4462 
4463   // Retain
4464   // %%% yuck as movptr...
4465   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
4466   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
4467   if (TLABStats) {
4468     // increment number of slow_allocations
4469     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
4470   }
4471   jmp(try_eden);
4472 
4473   bind(discard_tlab);
4474   if (TLABStats) {
4475     // increment number of refills
4476     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
4477     // accumulate wastage -- t1 is amount free in tlab
4478     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
4479   }
4480 
4481   // if tlab is currently allocated (top or end != null) then
4482   // fill [top, end + alignment_reserve) with array object
4483   testptr(top, top);
4484   jcc(Assembler::zero, do_refill);
4485 
4486   // set up the mark word
4487   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
4488   // set the length to the remaining space
4489   subptr(t1, typeArrayOopDesc::header_size(T_INT));
4490   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
4491   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
4492   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
4493   // set klass to intArrayKlass
4494   // dubious reloc why not an oop reloc?
4495   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
4496   // store klass last.  concurrent gcs assumes klass length is valid if
4497   // klass field is not null.
4498   store_klass(top, t1);
4499 
4500   movptr(t1, top);
4501   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
4502   incr_allocated_bytes(thread_reg, t1, 0);
4503 
4504   // refill the tlab with an eden allocation
4505   bind(do_refill);
4506   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
4507   shlptr(t1, LogHeapWordSize);
4508   // allocate new tlab, address returned in top
4509   eden_allocate(top, t1, 0, t2, slow_case);
4510 
4511   // Check that t1 was preserved in eden_allocate.
4512 #ifdef ASSERT
4513   if (UseTLAB) {
4514     Label ok;
4515     Register tsize = rsi;
4516     assert_different_registers(tsize, thread_reg, t1);
4517     push(tsize);
4518     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
4519     shlptr(tsize, LogHeapWordSize);
4520     cmpptr(t1, tsize);
4521     jcc(Assembler::equal, ok);
4522     STOP("assert(t1 != tlab size)");
4523     should_not_reach_here();
4524 
4525     bind(ok);
4526     pop(tsize);
4527   }
4528 #endif
4529   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
4530   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
4531   addptr(top, t1);
4532   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
4533   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
4534   verify_tlab();
4535   jmp(retry);
4536 
4537   return thread_reg; // for use by caller
4538 }
4539 
4540 void MacroAssembler::incr_allocated_bytes(Register thread,
4541                                           Register var_size_in_bytes,
4542                                           int con_size_in_bytes,
4543                                           Register t1) {
4544   if (!thread->is_valid()) {
4545 #ifdef _LP64
4546     thread = r15_thread;
4547 #else
4548     assert(t1->is_valid(), "need temp reg");
4549     thread = t1;
4550     get_thread(thread);
4551 #endif
4552   }
4553 
4554 #ifdef _LP64
4555   if (var_size_in_bytes->is_valid()) {
4556     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
4557   } else {
4558     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
4559   }
4560 #else
4561   if (var_size_in_bytes->is_valid()) {
4562     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
4563   } else {
4564     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
4565   }
4566   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
4567 #endif
4568 }
4569 
4570 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
4571   pusha();
4572 
4573   // if we are coming from c1, xmm registers may be live
4574   int off = 0;
4575   if (UseSSE == 1)  {
4576     subptr(rsp, sizeof(jdouble)*8);
4577     movflt(Address(rsp,off++*sizeof(jdouble)),xmm0);
4578     movflt(Address(rsp,off++*sizeof(jdouble)),xmm1);
4579     movflt(Address(rsp,off++*sizeof(jdouble)),xmm2);
4580     movflt(Address(rsp,off++*sizeof(jdouble)),xmm3);
4581     movflt(Address(rsp,off++*sizeof(jdouble)),xmm4);
4582     movflt(Address(rsp,off++*sizeof(jdouble)),xmm5);
4583     movflt(Address(rsp,off++*sizeof(jdouble)),xmm6);
4584     movflt(Address(rsp,off++*sizeof(jdouble)),xmm7);
4585   } else if (UseSSE >= 2)  {
4586     if (UseAVX > 2) {
4587       movl(rbx, 0xffff);
4588 #ifdef _LP64
4589       kmovql(k1, rbx);
4590 #else
4591       kmovdl(k1, rbx);
4592 #endif
4593     }
4594 #ifdef COMPILER2
4595     if (MaxVectorSize > 16) {
4596       assert(UseAVX > 0, "256bit vectors are supported only with AVX");
4597       // Save upper half of YMM registes
4598       subptr(rsp, 16 * LP64_ONLY(16) NOT_LP64(8));
4599       vextractf128h(Address(rsp,  0),xmm0);
4600       vextractf128h(Address(rsp, 16),xmm1);
4601       vextractf128h(Address(rsp, 32),xmm2);
4602       vextractf128h(Address(rsp, 48),xmm3);
4603       vextractf128h(Address(rsp, 64),xmm4);
4604       vextractf128h(Address(rsp, 80),xmm5);
4605       vextractf128h(Address(rsp, 96),xmm6);
4606       vextractf128h(Address(rsp,112),xmm7);
4607 #ifdef _LP64
4608       vextractf128h(Address(rsp,128),xmm8);
4609       vextractf128h(Address(rsp,144),xmm9);
4610       vextractf128h(Address(rsp,160),xmm10);
4611       vextractf128h(Address(rsp,176),xmm11);
4612       vextractf128h(Address(rsp,192),xmm12);
4613       vextractf128h(Address(rsp,208),xmm13);
4614       vextractf128h(Address(rsp,224),xmm14);
4615       vextractf128h(Address(rsp,240),xmm15);
4616 #endif
4617     }
4618 #endif
4619     // Save whole 128bit (16 bytes) XMM regiters
4620     subptr(rsp, 16 * LP64_ONLY(16) NOT_LP64(8));
4621     movdqu(Address(rsp,off++*16),xmm0);
4622     movdqu(Address(rsp,off++*16),xmm1);
4623     movdqu(Address(rsp,off++*16),xmm2);
4624     movdqu(Address(rsp,off++*16),xmm3);
4625     movdqu(Address(rsp,off++*16),xmm4);
4626     movdqu(Address(rsp,off++*16),xmm5);
4627     movdqu(Address(rsp,off++*16),xmm6);
4628     movdqu(Address(rsp,off++*16),xmm7);
4629 #ifdef _LP64
4630     movdqu(Address(rsp,off++*16),xmm8);
4631     movdqu(Address(rsp,off++*16),xmm9);
4632     movdqu(Address(rsp,off++*16),xmm10);
4633     movdqu(Address(rsp,off++*16),xmm11);
4634     movdqu(Address(rsp,off++*16),xmm12);
4635     movdqu(Address(rsp,off++*16),xmm13);
4636     movdqu(Address(rsp,off++*16),xmm14);
4637     movdqu(Address(rsp,off++*16),xmm15);
4638 #endif
4639   }
4640 
4641   // Preserve registers across runtime call
4642   int incoming_argument_and_return_value_offset = -1;
4643   if (num_fpu_regs_in_use > 1) {
4644     // Must preserve all other FPU regs (could alternatively convert
4645     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
4646     // FPU state, but can not trust C compiler)
4647     NEEDS_CLEANUP;
4648     // NOTE that in this case we also push the incoming argument(s) to
4649     // the stack and restore it later; we also use this stack slot to
4650     // hold the return value from dsin, dcos etc.
4651     for (int i = 0; i < num_fpu_regs_in_use; i++) {
4652       subptr(rsp, sizeof(jdouble));
4653       fstp_d(Address(rsp, 0));
4654     }
4655     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
4656     for (int i = nb_args-1; i >= 0; i--) {
4657       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
4658     }
4659   }
4660 
4661   subptr(rsp, nb_args*sizeof(jdouble));
4662   for (int i = 0; i < nb_args; i++) {
4663     fstp_d(Address(rsp, i*sizeof(jdouble)));
4664   }
4665 
4666 #ifdef _LP64
4667   if (nb_args > 0) {
4668     movdbl(xmm0, Address(rsp, 0));
4669   }
4670   if (nb_args > 1) {
4671     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
4672   }
4673   assert(nb_args <= 2, "unsupported number of args");
4674 #endif // _LP64
4675 
4676   // NOTE: we must not use call_VM_leaf here because that requires a
4677   // complete interpreter frame in debug mode -- same bug as 4387334
4678   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
4679   // do proper 64bit abi
4680 
4681   NEEDS_CLEANUP;
4682   // Need to add stack banging before this runtime call if it needs to
4683   // be taken; however, there is no generic stack banging routine at
4684   // the MacroAssembler level
4685 
4686   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
4687 
4688 #ifdef _LP64
4689   movsd(Address(rsp, 0), xmm0);
4690   fld_d(Address(rsp, 0));
4691 #endif // _LP64
4692   addptr(rsp, sizeof(jdouble) * nb_args);
4693   if (num_fpu_regs_in_use > 1) {
4694     // Must save return value to stack and then restore entire FPU
4695     // stack except incoming arguments
4696     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
4697     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
4698       fld_d(Address(rsp, 0));
4699       addptr(rsp, sizeof(jdouble));
4700     }
4701     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
4702     addptr(rsp, sizeof(jdouble) * nb_args);
4703   }
4704 
4705   off = 0;
4706   if (UseSSE == 1)  {
4707     movflt(xmm0, Address(rsp,off++*sizeof(jdouble)));
4708     movflt(xmm1, Address(rsp,off++*sizeof(jdouble)));
4709     movflt(xmm2, Address(rsp,off++*sizeof(jdouble)));
4710     movflt(xmm3, Address(rsp,off++*sizeof(jdouble)));
4711     movflt(xmm4, Address(rsp,off++*sizeof(jdouble)));
4712     movflt(xmm5, Address(rsp,off++*sizeof(jdouble)));
4713     movflt(xmm6, Address(rsp,off++*sizeof(jdouble)));
4714     movflt(xmm7, Address(rsp,off++*sizeof(jdouble)));
4715     addptr(rsp, sizeof(jdouble)*8);
4716   } else if (UseSSE >= 2)  {
4717     // Restore whole 128bit (16 bytes) XMM regiters
4718     movdqu(xmm0, Address(rsp,off++*16));
4719     movdqu(xmm1, Address(rsp,off++*16));
4720     movdqu(xmm2, Address(rsp,off++*16));
4721     movdqu(xmm3, Address(rsp,off++*16));
4722     movdqu(xmm4, Address(rsp,off++*16));
4723     movdqu(xmm5, Address(rsp,off++*16));
4724     movdqu(xmm6, Address(rsp,off++*16));
4725     movdqu(xmm7, Address(rsp,off++*16));
4726 #ifdef _LP64
4727     movdqu(xmm8, Address(rsp,off++*16));
4728     movdqu(xmm9, Address(rsp,off++*16));
4729     movdqu(xmm10, Address(rsp,off++*16));
4730     movdqu(xmm11, Address(rsp,off++*16));
4731     movdqu(xmm12, Address(rsp,off++*16));
4732     movdqu(xmm13, Address(rsp,off++*16));
4733     movdqu(xmm14, Address(rsp,off++*16));
4734     movdqu(xmm15, Address(rsp,off++*16));
4735 #endif
4736     addptr(rsp, 16 * LP64_ONLY(16) NOT_LP64(8));
4737 #ifdef COMPILER2
4738     if (MaxVectorSize > 16) {
4739       // Restore upper half of YMM registes.
4740       vinsertf128h(xmm0, Address(rsp,  0));
4741       vinsertf128h(xmm1, Address(rsp, 16));
4742       vinsertf128h(xmm2, Address(rsp, 32));
4743       vinsertf128h(xmm3, Address(rsp, 48));
4744       vinsertf128h(xmm4, Address(rsp, 64));
4745       vinsertf128h(xmm5, Address(rsp, 80));
4746       vinsertf128h(xmm6, Address(rsp, 96));
4747       vinsertf128h(xmm7, Address(rsp,112));
4748 #ifdef _LP64
4749       vinsertf128h(xmm8, Address(rsp,128));
4750       vinsertf128h(xmm9, Address(rsp,144));
4751       vinsertf128h(xmm10, Address(rsp,160));
4752       vinsertf128h(xmm11, Address(rsp,176));
4753       vinsertf128h(xmm12, Address(rsp,192));
4754       vinsertf128h(xmm13, Address(rsp,208));
4755       vinsertf128h(xmm14, Address(rsp,224));
4756       vinsertf128h(xmm15, Address(rsp,240));
4757 #endif
4758       addptr(rsp, 16 * LP64_ONLY(16) NOT_LP64(8));
4759     }
4760 #endif
4761   }
4762   popa();
4763 }
4764 
4765 static const double     pi_4 =  0.7853981633974483;
4766 
4767 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
4768   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
4769   // was attempted in this code; unfortunately it appears that the
4770   // switch to 80-bit precision and back causes this to be
4771   // unprofitable compared with simply performing a runtime call if
4772   // the argument is out of the (-pi/4, pi/4) range.
4773 
4774   Register tmp = noreg;
4775   if (!VM_Version::supports_cmov()) {
4776     // fcmp needs a temporary so preserve rbx,
4777     tmp = rbx;
4778     push(tmp);
4779   }
4780 
4781   Label slow_case, done;
4782 
4783   ExternalAddress pi4_adr = (address)&pi_4;
4784   if (reachable(pi4_adr)) {
4785     // x ?<= pi/4
4786     fld_d(pi4_adr);
4787     fld_s(1);                // Stack:  X  PI/4  X
4788     fabs();                  // Stack: |X| PI/4  X
4789     fcmp(tmp);
4790     jcc(Assembler::above, slow_case);
4791 
4792     // fastest case: -pi/4 <= x <= pi/4
4793     switch(trig) {
4794     case 's':
4795       fsin();
4796       break;
4797     case 'c':
4798       fcos();
4799       break;
4800     case 't':
4801       ftan();
4802       break;
4803     default:
4804       assert(false, "bad intrinsic");
4805       break;
4806     }
4807     jmp(done);
4808   }
4809 
4810   // slow case: runtime call
4811   bind(slow_case);
4812 
4813   switch(trig) {
4814   case 's':
4815     {
4816       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
4817     }
4818     break;
4819   case 'c':
4820     {
4821       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
4822     }
4823     break;
4824   case 't':
4825     {
4826       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
4827     }
4828     break;
4829   default:
4830     assert(false, "bad intrinsic");
4831     break;
4832   }
4833 
4834   // Come here with result in F-TOS
4835   bind(done);
4836 
4837   if (tmp != noreg) {
4838     pop(tmp);
4839   }
4840 }
4841 
4842 
4843 // Look up the method for a megamorphic invokeinterface call.
4844 // The target method is determined by <intf_klass, itable_index>.
4845 // The receiver klass is in recv_klass.
4846 // On success, the result will be in method_result, and execution falls through.
4847 // On failure, execution transfers to the given label.
4848 void MacroAssembler::lookup_interface_method(Register recv_klass,
4849                                              Register intf_klass,
4850                                              RegisterOrConstant itable_index,
4851                                              Register method_result,
4852                                              Register scan_temp,
4853                                              Label& L_no_such_interface) {
4854   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
4855   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
4856          "caller must use same register for non-constant itable index as for method");
4857 
4858   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
4859   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
4860   int itentry_off = itableMethodEntry::method_offset_in_bytes();
4861   int scan_step   = itableOffsetEntry::size() * wordSize;
4862   int vte_size    = vtableEntry::size() * wordSize;
4863   Address::ScaleFactor times_vte_scale = Address::times_ptr;
4864   assert(vte_size == wordSize, "else adjust times_vte_scale");
4865 
4866   movl(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
4867 
4868   // %%% Could store the aligned, prescaled offset in the klassoop.
4869   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
4870   if (HeapWordsPerLong > 1) {
4871     // Round up to align_object_offset boundary
4872     // see code for InstanceKlass::start_of_itable!
4873     round_to(scan_temp, BytesPerLong);
4874   }
4875 
4876   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
4877   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
4878   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
4879 
4880   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
4881   //   if (scan->interface() == intf) {
4882   //     result = (klass + scan->offset() + itable_index);
4883   //   }
4884   // }
4885   Label search, found_method;
4886 
4887   for (int peel = 1; peel >= 0; peel--) {
4888     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
4889     cmpptr(intf_klass, method_result);
4890 
4891     if (peel) {
4892       jccb(Assembler::equal, found_method);
4893     } else {
4894       jccb(Assembler::notEqual, search);
4895       // (invert the test to fall through to found_method...)
4896     }
4897 
4898     if (!peel)  break;
4899 
4900     bind(search);
4901 
4902     // Check that the previous entry is non-null.  A null entry means that
4903     // the receiver class doesn't implement the interface, and wasn't the
4904     // same as when the caller was compiled.
4905     testptr(method_result, method_result);
4906     jcc(Assembler::zero, L_no_such_interface);
4907     addptr(scan_temp, scan_step);
4908   }
4909 
4910   bind(found_method);
4911 
4912   // Got a hit.
4913   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
4914   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
4915 }
4916 
4917 
4918 // virtual method calling
4919 void MacroAssembler::lookup_virtual_method(Register recv_klass,
4920                                            RegisterOrConstant vtable_index,
4921                                            Register method_result) {
4922   const int base = InstanceKlass::vtable_start_offset() * wordSize;
4923   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
4924   Address vtable_entry_addr(recv_klass,
4925                             vtable_index, Address::times_ptr,
4926                             base + vtableEntry::method_offset_in_bytes());
4927   movptr(method_result, vtable_entry_addr);
4928 }
4929 
4930 
4931 void MacroAssembler::check_klass_subtype(Register sub_klass,
4932                            Register super_klass,
4933                            Register temp_reg,
4934                            Label& L_success) {
4935   Label L_failure;
4936   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
4937   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
4938   bind(L_failure);
4939 }
4940 
4941 
4942 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
4943                                                    Register super_klass,
4944                                                    Register temp_reg,
4945                                                    Label* L_success,
4946                                                    Label* L_failure,
4947                                                    Label* L_slow_path,
4948                                         RegisterOrConstant super_check_offset) {
4949   assert_different_registers(sub_klass, super_klass, temp_reg);
4950   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
4951   if (super_check_offset.is_register()) {
4952     assert_different_registers(sub_klass, super_klass,
4953                                super_check_offset.as_register());
4954   } else if (must_load_sco) {
4955     assert(temp_reg != noreg, "supply either a temp or a register offset");
4956   }
4957 
4958   Label L_fallthrough;
4959   int label_nulls = 0;
4960   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
4961   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
4962   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
4963   assert(label_nulls <= 1, "at most one NULL in the batch");
4964 
4965   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
4966   int sco_offset = in_bytes(Klass::super_check_offset_offset());
4967   Address super_check_offset_addr(super_klass, sco_offset);
4968 
4969   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
4970   // range of a jccb.  If this routine grows larger, reconsider at
4971   // least some of these.
4972 #define local_jcc(assembler_cond, label)                                \
4973   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
4974   else                             jcc( assembler_cond, label) /*omit semi*/
4975 
4976   // Hacked jmp, which may only be used just before L_fallthrough.
4977 #define final_jmp(label)                                                \
4978   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
4979   else                            jmp(label)                /*omit semi*/
4980 
4981   // If the pointers are equal, we are done (e.g., String[] elements).
4982   // This self-check enables sharing of secondary supertype arrays among
4983   // non-primary types such as array-of-interface.  Otherwise, each such
4984   // type would need its own customized SSA.
4985   // We move this check to the front of the fast path because many
4986   // type checks are in fact trivially successful in this manner,
4987   // so we get a nicely predicted branch right at the start of the check.
4988   cmpptr(sub_klass, super_klass);
4989   local_jcc(Assembler::equal, *L_success);
4990 
4991   // Check the supertype display:
4992   if (must_load_sco) {
4993     // Positive movl does right thing on LP64.
4994     movl(temp_reg, super_check_offset_addr);
4995     super_check_offset = RegisterOrConstant(temp_reg);
4996   }
4997   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
4998   cmpptr(super_klass, super_check_addr); // load displayed supertype
4999 
5000   // This check has worked decisively for primary supers.
5001   // Secondary supers are sought in the super_cache ('super_cache_addr').
5002   // (Secondary supers are interfaces and very deeply nested subtypes.)
5003   // This works in the same check above because of a tricky aliasing
5004   // between the super_cache and the primary super display elements.
5005   // (The 'super_check_addr' can address either, as the case requires.)
5006   // Note that the cache is updated below if it does not help us find
5007   // what we need immediately.
5008   // So if it was a primary super, we can just fail immediately.
5009   // Otherwise, it's the slow path for us (no success at this point).
5010 
5011   if (super_check_offset.is_register()) {
5012     local_jcc(Assembler::equal, *L_success);
5013     cmpl(super_check_offset.as_register(), sc_offset);
5014     if (L_failure == &L_fallthrough) {
5015       local_jcc(Assembler::equal, *L_slow_path);
5016     } else {
5017       local_jcc(Assembler::notEqual, *L_failure);
5018       final_jmp(*L_slow_path);
5019     }
5020   } else if (super_check_offset.as_constant() == sc_offset) {
5021     // Need a slow path; fast failure is impossible.
5022     if (L_slow_path == &L_fallthrough) {
5023       local_jcc(Assembler::equal, *L_success);
5024     } else {
5025       local_jcc(Assembler::notEqual, *L_slow_path);
5026       final_jmp(*L_success);
5027     }
5028   } else {
5029     // No slow path; it's a fast decision.
5030     if (L_failure == &L_fallthrough) {
5031       local_jcc(Assembler::equal, *L_success);
5032     } else {
5033       local_jcc(Assembler::notEqual, *L_failure);
5034       final_jmp(*L_success);
5035     }
5036   }
5037 
5038   bind(L_fallthrough);
5039 
5040 #undef local_jcc
5041 #undef final_jmp
5042 }
5043 
5044 
5045 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5046                                                    Register super_klass,
5047                                                    Register temp_reg,
5048                                                    Register temp2_reg,
5049                                                    Label* L_success,
5050                                                    Label* L_failure,
5051                                                    bool set_cond_codes) {
5052   assert_different_registers(sub_klass, super_klass, temp_reg);
5053   if (temp2_reg != noreg)
5054     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5055 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5056 
5057   Label L_fallthrough;
5058   int label_nulls = 0;
5059   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5060   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5061   assert(label_nulls <= 1, "at most one NULL in the batch");
5062 
5063   // a couple of useful fields in sub_klass:
5064   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5065   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5066   Address secondary_supers_addr(sub_klass, ss_offset);
5067   Address super_cache_addr(     sub_klass, sc_offset);
5068 
5069   // Do a linear scan of the secondary super-klass chain.
5070   // This code is rarely used, so simplicity is a virtue here.
5071   // The repne_scan instruction uses fixed registers, which we must spill.
5072   // Don't worry too much about pre-existing connections with the input regs.
5073 
5074   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5075   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5076 
5077   // Get super_klass value into rax (even if it was in rdi or rcx).
5078   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5079   if (super_klass != rax || UseCompressedOops) {
5080     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5081     mov(rax, super_klass);
5082   }
5083   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5084   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5085 
5086 #ifndef PRODUCT
5087   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5088   ExternalAddress pst_counter_addr((address) pst_counter);
5089   NOT_LP64(  incrementl(pst_counter_addr) );
5090   LP64_ONLY( lea(rcx, pst_counter_addr) );
5091   LP64_ONLY( incrementl(Address(rcx, 0)) );
5092 #endif //PRODUCT
5093 
5094   // We will consult the secondary-super array.
5095   movptr(rdi, secondary_supers_addr);
5096   // Load the array length.  (Positive movl does right thing on LP64.)
5097   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5098   // Skip to start of data.
5099   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5100 
5101   // Scan RCX words at [RDI] for an occurrence of RAX.
5102   // Set NZ/Z based on last compare.
5103   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5104   // not change flags (only scas instruction which is repeated sets flags).
5105   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5106 
5107     testptr(rax,rax); // Set Z = 0
5108     repne_scan();
5109 
5110   // Unspill the temp. registers:
5111   if (pushed_rdi)  pop(rdi);
5112   if (pushed_rcx)  pop(rcx);
5113   if (pushed_rax)  pop(rax);
5114 
5115   if (set_cond_codes) {
5116     // Special hack for the AD files:  rdi is guaranteed non-zero.
5117     assert(!pushed_rdi, "rdi must be left non-NULL");
5118     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5119   }
5120 
5121   if (L_failure == &L_fallthrough)
5122         jccb(Assembler::notEqual, *L_failure);
5123   else  jcc(Assembler::notEqual, *L_failure);
5124 
5125   // Success.  Cache the super we found and proceed in triumph.
5126   movptr(super_cache_addr, super_klass);
5127 
5128   if (L_success != &L_fallthrough) {
5129     jmp(*L_success);
5130   }
5131 
5132 #undef IS_A_TEMP
5133 
5134   bind(L_fallthrough);
5135 }
5136 
5137 
5138 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5139   if (VM_Version::supports_cmov()) {
5140     cmovl(cc, dst, src);
5141   } else {
5142     Label L;
5143     jccb(negate_condition(cc), L);
5144     movl(dst, src);
5145     bind(L);
5146   }
5147 }
5148 
5149 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5150   if (VM_Version::supports_cmov()) {
5151     cmovl(cc, dst, src);
5152   } else {
5153     Label L;
5154     jccb(negate_condition(cc), L);
5155     movl(dst, src);
5156     bind(L);
5157   }
5158 }
5159 
5160 void MacroAssembler::verify_oop(Register reg, const char* s) {
5161   if (!VerifyOops) return;
5162 
5163   // Pass register number to verify_oop_subroutine
5164   const char* b = NULL;
5165   {
5166     ResourceMark rm;
5167     stringStream ss;
5168     ss.print("verify_oop: %s: %s", reg->name(), s);
5169     b = code_string(ss.as_string());
5170   }
5171   BLOCK_COMMENT("verify_oop {");
5172 #ifdef _LP64
5173   push(rscratch1);                    // save r10, trashed by movptr()
5174 #endif
5175   push(rax);                          // save rax,
5176   push(reg);                          // pass register argument
5177   ExternalAddress buffer((address) b);
5178   // avoid using pushptr, as it modifies scratch registers
5179   // and our contract is not to modify anything
5180   movptr(rax, buffer.addr());
5181   push(rax);
5182   // call indirectly to solve generation ordering problem
5183   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5184   call(rax);
5185   // Caller pops the arguments (oop, message) and restores rax, r10
5186   BLOCK_COMMENT("} verify_oop");
5187 }
5188 
5189 
5190 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5191                                                       Register tmp,
5192                                                       int offset) {
5193   intptr_t value = *delayed_value_addr;
5194   if (value != 0)
5195     return RegisterOrConstant(value + offset);
5196 
5197   // load indirectly to solve generation ordering problem
5198   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5199 
5200 #ifdef ASSERT
5201   { Label L;
5202     testptr(tmp, tmp);
5203     if (WizardMode) {
5204       const char* buf = NULL;
5205       {
5206         ResourceMark rm;
5207         stringStream ss;
5208         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5209         buf = code_string(ss.as_string());
5210       }
5211       jcc(Assembler::notZero, L);
5212       STOP(buf);
5213     } else {
5214       jccb(Assembler::notZero, L);
5215       hlt();
5216     }
5217     bind(L);
5218   }
5219 #endif
5220 
5221   if (offset != 0)
5222     addptr(tmp, offset);
5223 
5224   return RegisterOrConstant(tmp);
5225 }
5226 
5227 
5228 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5229                                          int extra_slot_offset) {
5230   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5231   int stackElementSize = Interpreter::stackElementSize;
5232   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5233 #ifdef ASSERT
5234   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5235   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5236 #endif
5237   Register             scale_reg    = noreg;
5238   Address::ScaleFactor scale_factor = Address::no_scale;
5239   if (arg_slot.is_constant()) {
5240     offset += arg_slot.as_constant() * stackElementSize;
5241   } else {
5242     scale_reg    = arg_slot.as_register();
5243     scale_factor = Address::times(stackElementSize);
5244   }
5245   offset += wordSize;           // return PC is on stack
5246   return Address(rsp, scale_reg, scale_factor, offset);
5247 }
5248 
5249 
5250 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5251   if (!VerifyOops) return;
5252 
5253   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5254   // Pass register number to verify_oop_subroutine
5255   const char* b = NULL;
5256   {
5257     ResourceMark rm;
5258     stringStream ss;
5259     ss.print("verify_oop_addr: %s", s);
5260     b = code_string(ss.as_string());
5261   }
5262 #ifdef _LP64
5263   push(rscratch1);                    // save r10, trashed by movptr()
5264 #endif
5265   push(rax);                          // save rax,
5266   // addr may contain rsp so we will have to adjust it based on the push
5267   // we just did (and on 64 bit we do two pushes)
5268   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5269   // stores rax into addr which is backwards of what was intended.
5270   if (addr.uses(rsp)) {
5271     lea(rax, addr);
5272     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5273   } else {
5274     pushptr(addr);
5275   }
5276 
5277   ExternalAddress buffer((address) b);
5278   // pass msg argument
5279   // avoid using pushptr, as it modifies scratch registers
5280   // and our contract is not to modify anything
5281   movptr(rax, buffer.addr());
5282   push(rax);
5283 
5284   // call indirectly to solve generation ordering problem
5285   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5286   call(rax);
5287   // Caller pops the arguments (addr, message) and restores rax, r10.
5288 }
5289 
5290 void MacroAssembler::verify_tlab() {
5291 #ifdef ASSERT
5292   if (UseTLAB && VerifyOops) {
5293     Label next, ok;
5294     Register t1 = rsi;
5295     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5296 
5297     push(t1);
5298     NOT_LP64(push(thread_reg));
5299     NOT_LP64(get_thread(thread_reg));
5300 
5301     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5302     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5303     jcc(Assembler::aboveEqual, next);
5304     STOP("assert(top >= start)");
5305     should_not_reach_here();
5306 
5307     bind(next);
5308     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5309     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5310     jcc(Assembler::aboveEqual, ok);
5311     STOP("assert(top <= end)");
5312     should_not_reach_here();
5313 
5314     bind(ok);
5315     NOT_LP64(pop(thread_reg));
5316     pop(t1);
5317   }
5318 #endif
5319 }
5320 
5321 class ControlWord {
5322  public:
5323   int32_t _value;
5324 
5325   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5326   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5327   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5328   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5329   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5330   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5331   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5332   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5333 
5334   void print() const {
5335     // rounding control
5336     const char* rc;
5337     switch (rounding_control()) {
5338       case 0: rc = "round near"; break;
5339       case 1: rc = "round down"; break;
5340       case 2: rc = "round up  "; break;
5341       case 3: rc = "chop      "; break;
5342     };
5343     // precision control
5344     const char* pc;
5345     switch (precision_control()) {
5346       case 0: pc = "24 bits "; break;
5347       case 1: pc = "reserved"; break;
5348       case 2: pc = "53 bits "; break;
5349       case 3: pc = "64 bits "; break;
5350     };
5351     // flags
5352     char f[9];
5353     f[0] = ' ';
5354     f[1] = ' ';
5355     f[2] = (precision   ()) ? 'P' : 'p';
5356     f[3] = (underflow   ()) ? 'U' : 'u';
5357     f[4] = (overflow    ()) ? 'O' : 'o';
5358     f[5] = (zero_divide ()) ? 'Z' : 'z';
5359     f[6] = (denormalized()) ? 'D' : 'd';
5360     f[7] = (invalid     ()) ? 'I' : 'i';
5361     f[8] = '\x0';
5362     // output
5363     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
5364   }
5365 
5366 };
5367 
5368 class StatusWord {
5369  public:
5370   int32_t _value;
5371 
5372   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
5373   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
5374   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
5375   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
5376   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
5377   int  top() const                     { return  (_value >> 11) & 7      ; }
5378   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
5379   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
5380   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5381   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5382   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5383   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5384   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5385   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5386 
5387   void print() const {
5388     // condition codes
5389     char c[5];
5390     c[0] = (C3()) ? '3' : '-';
5391     c[1] = (C2()) ? '2' : '-';
5392     c[2] = (C1()) ? '1' : '-';
5393     c[3] = (C0()) ? '0' : '-';
5394     c[4] = '\x0';
5395     // flags
5396     char f[9];
5397     f[0] = (error_status()) ? 'E' : '-';
5398     f[1] = (stack_fault ()) ? 'S' : '-';
5399     f[2] = (precision   ()) ? 'P' : '-';
5400     f[3] = (underflow   ()) ? 'U' : '-';
5401     f[4] = (overflow    ()) ? 'O' : '-';
5402     f[5] = (zero_divide ()) ? 'Z' : '-';
5403     f[6] = (denormalized()) ? 'D' : '-';
5404     f[7] = (invalid     ()) ? 'I' : '-';
5405     f[8] = '\x0';
5406     // output
5407     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
5408   }
5409 
5410 };
5411 
5412 class TagWord {
5413  public:
5414   int32_t _value;
5415 
5416   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
5417 
5418   void print() const {
5419     printf("%04x", _value & 0xFFFF);
5420   }
5421 
5422 };
5423 
5424 class FPU_Register {
5425  public:
5426   int32_t _m0;
5427   int32_t _m1;
5428   int16_t _ex;
5429 
5430   bool is_indefinite() const           {
5431     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
5432   }
5433 
5434   void print() const {
5435     char  sign = (_ex < 0) ? '-' : '+';
5436     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
5437     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
5438   };
5439 
5440 };
5441 
5442 class FPU_State {
5443  public:
5444   enum {
5445     register_size       = 10,
5446     number_of_registers =  8,
5447     register_mask       =  7
5448   };
5449 
5450   ControlWord  _control_word;
5451   StatusWord   _status_word;
5452   TagWord      _tag_word;
5453   int32_t      _error_offset;
5454   int32_t      _error_selector;
5455   int32_t      _data_offset;
5456   int32_t      _data_selector;
5457   int8_t       _register[register_size * number_of_registers];
5458 
5459   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
5460   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
5461 
5462   const char* tag_as_string(int tag) const {
5463     switch (tag) {
5464       case 0: return "valid";
5465       case 1: return "zero";
5466       case 2: return "special";
5467       case 3: return "empty";
5468     }
5469     ShouldNotReachHere();
5470     return NULL;
5471   }
5472 
5473   void print() const {
5474     // print computation registers
5475     { int t = _status_word.top();
5476       for (int i = 0; i < number_of_registers; i++) {
5477         int j = (i - t) & register_mask;
5478         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
5479         st(j)->print();
5480         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
5481       }
5482     }
5483     printf("\n");
5484     // print control registers
5485     printf("ctrl = "); _control_word.print(); printf("\n");
5486     printf("stat = "); _status_word .print(); printf("\n");
5487     printf("tags = "); _tag_word    .print(); printf("\n");
5488   }
5489 
5490 };
5491 
5492 class Flag_Register {
5493  public:
5494   int32_t _value;
5495 
5496   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
5497   bool direction() const               { return ((_value >> 10) & 1) != 0; }
5498   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
5499   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
5500   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
5501   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
5502   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
5503 
5504   void print() const {
5505     // flags
5506     char f[8];
5507     f[0] = (overflow       ()) ? 'O' : '-';
5508     f[1] = (direction      ()) ? 'D' : '-';
5509     f[2] = (sign           ()) ? 'S' : '-';
5510     f[3] = (zero           ()) ? 'Z' : '-';
5511     f[4] = (auxiliary_carry()) ? 'A' : '-';
5512     f[5] = (parity         ()) ? 'P' : '-';
5513     f[6] = (carry          ()) ? 'C' : '-';
5514     f[7] = '\x0';
5515     // output
5516     printf("%08x  flags = %s", _value, f);
5517   }
5518 
5519 };
5520 
5521 class IU_Register {
5522  public:
5523   int32_t _value;
5524 
5525   void print() const {
5526     printf("%08x  %11d", _value, _value);
5527   }
5528 
5529 };
5530 
5531 class IU_State {
5532  public:
5533   Flag_Register _eflags;
5534   IU_Register   _rdi;
5535   IU_Register   _rsi;
5536   IU_Register   _rbp;
5537   IU_Register   _rsp;
5538   IU_Register   _rbx;
5539   IU_Register   _rdx;
5540   IU_Register   _rcx;
5541   IU_Register   _rax;
5542 
5543   void print() const {
5544     // computation registers
5545     printf("rax,  = "); _rax.print(); printf("\n");
5546     printf("rbx,  = "); _rbx.print(); printf("\n");
5547     printf("rcx  = "); _rcx.print(); printf("\n");
5548     printf("rdx  = "); _rdx.print(); printf("\n");
5549     printf("rdi  = "); _rdi.print(); printf("\n");
5550     printf("rsi  = "); _rsi.print(); printf("\n");
5551     printf("rbp,  = "); _rbp.print(); printf("\n");
5552     printf("rsp  = "); _rsp.print(); printf("\n");
5553     printf("\n");
5554     // control registers
5555     printf("flgs = "); _eflags.print(); printf("\n");
5556   }
5557 };
5558 
5559 
5560 class CPU_State {
5561  public:
5562   FPU_State _fpu_state;
5563   IU_State  _iu_state;
5564 
5565   void print() const {
5566     printf("--------------------------------------------------\n");
5567     _iu_state .print();
5568     printf("\n");
5569     _fpu_state.print();
5570     printf("--------------------------------------------------\n");
5571   }
5572 
5573 };
5574 
5575 
5576 static void _print_CPU_state(CPU_State* state) {
5577   state->print();
5578 };
5579 
5580 
5581 void MacroAssembler::print_CPU_state() {
5582   push_CPU_state();
5583   push(rsp);                // pass CPU state
5584   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
5585   addptr(rsp, wordSize);       // discard argument
5586   pop_CPU_state();
5587 }
5588 
5589 
5590 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
5591   static int counter = 0;
5592   FPU_State* fs = &state->_fpu_state;
5593   counter++;
5594   // For leaf calls, only verify that the top few elements remain empty.
5595   // We only need 1 empty at the top for C2 code.
5596   if( stack_depth < 0 ) {
5597     if( fs->tag_for_st(7) != 3 ) {
5598       printf("FPR7 not empty\n");
5599       state->print();
5600       assert(false, "error");
5601       return false;
5602     }
5603     return true;                // All other stack states do not matter
5604   }
5605 
5606   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
5607          "bad FPU control word");
5608 
5609   // compute stack depth
5610   int i = 0;
5611   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
5612   int d = i;
5613   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
5614   // verify findings
5615   if (i != FPU_State::number_of_registers) {
5616     // stack not contiguous
5617     printf("%s: stack not contiguous at ST%d\n", s, i);
5618     state->print();
5619     assert(false, "error");
5620     return false;
5621   }
5622   // check if computed stack depth corresponds to expected stack depth
5623   if (stack_depth < 0) {
5624     // expected stack depth is -stack_depth or less
5625     if (d > -stack_depth) {
5626       // too many elements on the stack
5627       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
5628       state->print();
5629       assert(false, "error");
5630       return false;
5631     }
5632   } else {
5633     // expected stack depth is stack_depth
5634     if (d != stack_depth) {
5635       // wrong stack depth
5636       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
5637       state->print();
5638       assert(false, "error");
5639       return false;
5640     }
5641   }
5642   // everything is cool
5643   return true;
5644 }
5645 
5646 
5647 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
5648   if (!VerifyFPU) return;
5649   push_CPU_state();
5650   push(rsp);                // pass CPU state
5651   ExternalAddress msg((address) s);
5652   // pass message string s
5653   pushptr(msg.addr());
5654   push(stack_depth);        // pass stack depth
5655   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
5656   addptr(rsp, 3 * wordSize);   // discard arguments
5657   // check for error
5658   { Label L;
5659     testl(rax, rax);
5660     jcc(Assembler::notZero, L);
5661     int3();                  // break if error condition
5662     bind(L);
5663   }
5664   pop_CPU_state();
5665 }
5666 
5667 void MacroAssembler::restore_cpu_control_state_after_jni() {
5668   // Either restore the MXCSR register after returning from the JNI Call
5669   // or verify that it wasn't changed (with -Xcheck:jni flag).
5670   if (VM_Version::supports_sse()) {
5671     if (RestoreMXCSROnJNICalls) {
5672       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
5673     } else if (CheckJNICalls) {
5674       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
5675     }
5676   }
5677   if (VM_Version::supports_avx()) {
5678     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
5679     vzeroupper();
5680   }
5681 
5682 #ifndef _LP64
5683   // Either restore the x87 floating pointer control word after returning
5684   // from the JNI call or verify that it wasn't changed.
5685   if (CheckJNICalls) {
5686     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
5687   }
5688 #endif // _LP64
5689 }
5690 
5691 
5692 void MacroAssembler::load_klass(Register dst, Register src) {
5693 #ifdef _LP64
5694   if (UseCompressedClassPointers) {
5695     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5696     decode_klass_not_null(dst);
5697   } else
5698 #endif
5699     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5700 }
5701 
5702 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5703   load_klass(dst, src);
5704   movptr(dst, Address(dst, Klass::prototype_header_offset()));
5705 }
5706 
5707 void MacroAssembler::store_klass(Register dst, Register src) {
5708 #ifdef _LP64
5709   if (UseCompressedClassPointers) {
5710     encode_klass_not_null(src);
5711     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5712   } else
5713 #endif
5714     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5715 }
5716 
5717 void MacroAssembler::load_heap_oop(Register dst, Address src) {
5718 #ifdef _LP64
5719   // FIXME: Must change all places where we try to load the klass.
5720   if (UseCompressedOops) {
5721     movl(dst, src);
5722     decode_heap_oop(dst);
5723   } else
5724 #endif
5725     movptr(dst, src);
5726 }
5727 
5728 // Doesn't do verfication, generates fixed size code
5729 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
5730 #ifdef _LP64
5731   if (UseCompressedOops) {
5732     movl(dst, src);
5733     decode_heap_oop_not_null(dst);
5734   } else
5735 #endif
5736     movptr(dst, src);
5737 }
5738 
5739 void MacroAssembler::store_heap_oop(Address dst, Register src) {
5740 #ifdef _LP64
5741   if (UseCompressedOops) {
5742     assert(!dst.uses(src), "not enough registers");
5743     encode_heap_oop(src);
5744     movl(dst, src);
5745   } else
5746 #endif
5747     movptr(dst, src);
5748 }
5749 
5750 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
5751   assert_different_registers(src1, tmp);
5752 #ifdef _LP64
5753   if (UseCompressedOops) {
5754     bool did_push = false;
5755     if (tmp == noreg) {
5756       tmp = rax;
5757       push(tmp);
5758       did_push = true;
5759       assert(!src2.uses(rsp), "can't push");
5760     }
5761     load_heap_oop(tmp, src2);
5762     cmpptr(src1, tmp);
5763     if (did_push)  pop(tmp);
5764   } else
5765 #endif
5766     cmpptr(src1, src2);
5767 }
5768 
5769 // Used for storing NULLs.
5770 void MacroAssembler::store_heap_oop_null(Address dst) {
5771 #ifdef _LP64
5772   if (UseCompressedOops) {
5773     movl(dst, (int32_t)NULL_WORD);
5774   } else {
5775     movslq(dst, (int32_t)NULL_WORD);
5776   }
5777 #else
5778   movl(dst, (int32_t)NULL_WORD);
5779 #endif
5780 }
5781 
5782 #ifdef _LP64
5783 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5784   if (UseCompressedClassPointers) {
5785     // Store to klass gap in destination
5786     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
5787   }
5788 }
5789 
5790 #ifdef ASSERT
5791 void MacroAssembler::verify_heapbase(const char* msg) {
5792   assert (UseCompressedOops, "should be compressed");
5793   assert (Universe::heap() != NULL, "java heap should be initialized");
5794   if (CheckCompressedOops) {
5795     Label ok;
5796     push(rscratch1); // cmpptr trashes rscratch1
5797     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
5798     jcc(Assembler::equal, ok);
5799     STOP(msg);
5800     bind(ok);
5801     pop(rscratch1);
5802   }
5803 }
5804 #endif
5805 
5806 // Algorithm must match oop.inline.hpp encode_heap_oop.
5807 void MacroAssembler::encode_heap_oop(Register r) {
5808 #ifdef ASSERT
5809   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5810 #endif
5811   verify_oop(r, "broken oop in encode_heap_oop");
5812   if (Universe::narrow_oop_base() == NULL) {
5813     if (Universe::narrow_oop_shift() != 0) {
5814       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5815       shrq(r, LogMinObjAlignmentInBytes);
5816     }
5817     return;
5818   }
5819   testq(r, r);
5820   cmovq(Assembler::equal, r, r12_heapbase);
5821   subq(r, r12_heapbase);
5822   shrq(r, LogMinObjAlignmentInBytes);
5823 }
5824 
5825 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5826 #ifdef ASSERT
5827   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5828   if (CheckCompressedOops) {
5829     Label ok;
5830     testq(r, r);
5831     jcc(Assembler::notEqual, ok);
5832     STOP("null oop passed to encode_heap_oop_not_null");
5833     bind(ok);
5834   }
5835 #endif
5836   verify_oop(r, "broken oop in encode_heap_oop_not_null");
5837   if (Universe::narrow_oop_base() != NULL) {
5838     subq(r, r12_heapbase);
5839   }
5840   if (Universe::narrow_oop_shift() != 0) {
5841     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5842     shrq(r, LogMinObjAlignmentInBytes);
5843   }
5844 }
5845 
5846 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5847 #ifdef ASSERT
5848   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5849   if (CheckCompressedOops) {
5850     Label ok;
5851     testq(src, src);
5852     jcc(Assembler::notEqual, ok);
5853     STOP("null oop passed to encode_heap_oop_not_null2");
5854     bind(ok);
5855   }
5856 #endif
5857   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
5858   if (dst != src) {
5859     movq(dst, src);
5860   }
5861   if (Universe::narrow_oop_base() != NULL) {
5862     subq(dst, r12_heapbase);
5863   }
5864   if (Universe::narrow_oop_shift() != 0) {
5865     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5866     shrq(dst, LogMinObjAlignmentInBytes);
5867   }
5868 }
5869 
5870 void  MacroAssembler::decode_heap_oop(Register r) {
5871 #ifdef ASSERT
5872   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5873 #endif
5874   if (Universe::narrow_oop_base() == NULL) {
5875     if (Universe::narrow_oop_shift() != 0) {
5876       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5877       shlq(r, LogMinObjAlignmentInBytes);
5878     }
5879   } else {
5880     Label done;
5881     shlq(r, LogMinObjAlignmentInBytes);
5882     jccb(Assembler::equal, done);
5883     addq(r, r12_heapbase);
5884     bind(done);
5885   }
5886   verify_oop(r, "broken oop in decode_heap_oop");
5887 }
5888 
5889 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5890   // Note: it will change flags
5891   assert (UseCompressedOops, "should only be used for compressed headers");
5892   assert (Universe::heap() != NULL, "java heap should be initialized");
5893   // Cannot assert, unverified entry point counts instructions (see .ad file)
5894   // vtableStubs also counts instructions in pd_code_size_limit.
5895   // Also do not verify_oop as this is called by verify_oop.
5896   if (Universe::narrow_oop_shift() != 0) {
5897     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5898     shlq(r, LogMinObjAlignmentInBytes);
5899     if (Universe::narrow_oop_base() != NULL) {
5900       addq(r, r12_heapbase);
5901     }
5902   } else {
5903     assert (Universe::narrow_oop_base() == NULL, "sanity");
5904   }
5905 }
5906 
5907 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5908   // Note: it will change flags
5909   assert (UseCompressedOops, "should only be used for compressed headers");
5910   assert (Universe::heap() != NULL, "java heap should be initialized");
5911   // Cannot assert, unverified entry point counts instructions (see .ad file)
5912   // vtableStubs also counts instructions in pd_code_size_limit.
5913   // Also do not verify_oop as this is called by verify_oop.
5914   if (Universe::narrow_oop_shift() != 0) {
5915     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5916     if (LogMinObjAlignmentInBytes == Address::times_8) {
5917       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
5918     } else {
5919       if (dst != src) {
5920         movq(dst, src);
5921       }
5922       shlq(dst, LogMinObjAlignmentInBytes);
5923       if (Universe::narrow_oop_base() != NULL) {
5924         addq(dst, r12_heapbase);
5925       }
5926     }
5927   } else {
5928     assert (Universe::narrow_oop_base() == NULL, "sanity");
5929     if (dst != src) {
5930       movq(dst, src);
5931     }
5932   }
5933 }
5934 
5935 void MacroAssembler::encode_klass_not_null(Register r) {
5936   if (Universe::narrow_klass_base() != NULL) {
5937     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5938     assert(r != r12_heapbase, "Encoding a klass in r12");
5939     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
5940     subq(r, r12_heapbase);
5941   }
5942   if (Universe::narrow_klass_shift() != 0) {
5943     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5944     shrq(r, LogKlassAlignmentInBytes);
5945   }
5946   if (Universe::narrow_klass_base() != NULL) {
5947     reinit_heapbase();
5948   }
5949 }
5950 
5951 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5952   if (dst == src) {
5953     encode_klass_not_null(src);
5954   } else {
5955     if (Universe::narrow_klass_base() != NULL) {
5956       mov64(dst, (int64_t)Universe::narrow_klass_base());
5957       negq(dst);
5958       addq(dst, src);
5959     } else {
5960       movptr(dst, src);
5961     }
5962     if (Universe::narrow_klass_shift() != 0) {
5963       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5964       shrq(dst, LogKlassAlignmentInBytes);
5965     }
5966   }
5967 }
5968 
5969 // Function instr_size_for_decode_klass_not_null() counts the instructions
5970 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
5971 // when (Universe::heap() != NULL).  Hence, if the instructions they
5972 // generate change, then this method needs to be updated.
5973 int MacroAssembler::instr_size_for_decode_klass_not_null() {
5974   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
5975   if (Universe::narrow_klass_base() != NULL) {
5976     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
5977     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
5978   } else {
5979     // longest load decode klass function, mov64, leaq
5980     return 16;
5981   }
5982 }
5983 
5984 // !!! If the instructions that get generated here change then function
5985 // instr_size_for_decode_klass_not_null() needs to get updated.
5986 void  MacroAssembler::decode_klass_not_null(Register r) {
5987   // Note: it will change flags
5988   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5989   assert(r != r12_heapbase, "Decoding a klass in r12");
5990   // Cannot assert, unverified entry point counts instructions (see .ad file)
5991   // vtableStubs also counts instructions in pd_code_size_limit.
5992   // Also do not verify_oop as this is called by verify_oop.
5993   if (Universe::narrow_klass_shift() != 0) {
5994     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5995     shlq(r, LogKlassAlignmentInBytes);
5996   }
5997   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5998   if (Universe::narrow_klass_base() != NULL) {
5999     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6000     addq(r, r12_heapbase);
6001     reinit_heapbase();
6002   }
6003 }
6004 
6005 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6006   // Note: it will change flags
6007   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6008   if (dst == src) {
6009     decode_klass_not_null(dst);
6010   } else {
6011     // Cannot assert, unverified entry point counts instructions (see .ad file)
6012     // vtableStubs also counts instructions in pd_code_size_limit.
6013     // Also do not verify_oop as this is called by verify_oop.
6014     mov64(dst, (int64_t)Universe::narrow_klass_base());
6015     if (Universe::narrow_klass_shift() != 0) {
6016       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6017       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6018       leaq(dst, Address(dst, src, Address::times_8, 0));
6019     } else {
6020       addq(dst, src);
6021     }
6022   }
6023 }
6024 
6025 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6026   assert (UseCompressedOops, "should only be used for compressed headers");
6027   assert (Universe::heap() != NULL, "java heap should be initialized");
6028   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6029   int oop_index = oop_recorder()->find_index(obj);
6030   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6031   mov_narrow_oop(dst, oop_index, rspec);
6032 }
6033 
6034 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6035   assert (UseCompressedOops, "should only be used for compressed headers");
6036   assert (Universe::heap() != NULL, "java heap should be initialized");
6037   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6038   int oop_index = oop_recorder()->find_index(obj);
6039   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6040   mov_narrow_oop(dst, oop_index, rspec);
6041 }
6042 
6043 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6044   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6045   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6046   int klass_index = oop_recorder()->find_index(k);
6047   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6048   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6049 }
6050 
6051 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6052   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6053   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6054   int klass_index = oop_recorder()->find_index(k);
6055   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6056   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6057 }
6058 
6059 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6060   assert (UseCompressedOops, "should only be used for compressed headers");
6061   assert (Universe::heap() != NULL, "java heap should be initialized");
6062   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6063   int oop_index = oop_recorder()->find_index(obj);
6064   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6065   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6066 }
6067 
6068 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6069   assert (UseCompressedOops, "should only be used for compressed headers");
6070   assert (Universe::heap() != NULL, "java heap should be initialized");
6071   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6072   int oop_index = oop_recorder()->find_index(obj);
6073   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6074   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6075 }
6076 
6077 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6078   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6079   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6080   int klass_index = oop_recorder()->find_index(k);
6081   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6082   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6083 }
6084 
6085 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6086   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6087   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6088   int klass_index = oop_recorder()->find_index(k);
6089   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6090   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6091 }
6092 
6093 void MacroAssembler::reinit_heapbase() {
6094   if (UseCompressedOops || UseCompressedClassPointers) {
6095     if (Universe::heap() != NULL) {
6096       if (Universe::narrow_oop_base() == NULL) {
6097         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6098       } else {
6099         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6100       }
6101     } else {
6102       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6103     }
6104   }
6105 }
6106 
6107 #endif // _LP64
6108 
6109 
6110 // C2 compiled method's prolog code.
6111 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6112 
6113   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6114   // NativeJump::patch_verified_entry will be able to patch out the entry
6115   // code safely. The push to verify stack depth is ok at 5 bytes,
6116   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6117   // stack bang then we must use the 6 byte frame allocation even if
6118   // we have no frame. :-(
6119   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6120 
6121   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6122   // Remove word for return addr
6123   framesize -= wordSize;
6124   stack_bang_size -= wordSize;
6125 
6126   // Calls to C2R adapters often do not accept exceptional returns.
6127   // We require that their callers must bang for them.  But be careful, because
6128   // some VM calls (such as call site linkage) can use several kilobytes of
6129   // stack.  But the stack safety zone should account for that.
6130   // See bugs 4446381, 4468289, 4497237.
6131   if (stack_bang_size > 0) {
6132     generate_stack_overflow_check(stack_bang_size);
6133 
6134     // We always push rbp, so that on return to interpreter rbp, will be
6135     // restored correctly and we can correct the stack.
6136     push(rbp);
6137     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6138     if (PreserveFramePointer) {
6139       mov(rbp, rsp);
6140     }
6141     // Remove word for ebp
6142     framesize -= wordSize;
6143 
6144     // Create frame
6145     if (framesize) {
6146       subptr(rsp, framesize);
6147     }
6148   } else {
6149     // Create frame (force generation of a 4 byte immediate value)
6150     subptr_imm32(rsp, framesize);
6151 
6152     // Save RBP register now.
6153     framesize -= wordSize;
6154     movptr(Address(rsp, framesize), rbp);
6155     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6156     if (PreserveFramePointer) {
6157       movptr(rbp, rsp);
6158       addptr(rbp, framesize + wordSize);
6159     }
6160   }
6161 
6162   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6163     framesize -= wordSize;
6164     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6165   }
6166 
6167 #ifndef _LP64
6168   // If method sets FPU control word do it now
6169   if (fp_mode_24b) {
6170     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6171   }
6172   if (UseSSE >= 2 && VerifyFPU) {
6173     verify_FPU(0, "FPU stack must be clean on entry");
6174   }
6175 #endif
6176 
6177 #ifdef ASSERT
6178   if (VerifyStackAtCalls) {
6179     Label L;
6180     push(rax);
6181     mov(rax, rsp);
6182     andptr(rax, StackAlignmentInBytes-1);
6183     cmpptr(rax, StackAlignmentInBytes-wordSize);
6184     pop(rax);
6185     jcc(Assembler::equal, L);
6186     STOP("Stack is not properly aligned!");
6187     bind(L);
6188   }
6189 #endif
6190 
6191 }
6192 
6193 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
6194   // cnt - number of qwords (8-byte words).
6195   // base - start address, qword aligned.
6196   assert(base==rdi, "base register must be edi for rep stos");
6197   assert(tmp==rax,   "tmp register must be eax for rep stos");
6198   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6199 
6200   xorptr(tmp, tmp);
6201   if (UseFastStosb) {
6202     shlptr(cnt,3); // convert to number of bytes
6203     rep_stosb();
6204   } else {
6205     NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
6206     rep_stos();
6207   }
6208 }
6209 
6210 // IndexOf for constant substrings with size >= 8 chars
6211 // which don't need to be loaded through stack.
6212 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6213                                       Register cnt1, Register cnt2,
6214                                       int int_cnt2,  Register result,
6215                                       XMMRegister vec, Register tmp) {
6216   ShortBranchVerifier sbv(this);
6217   assert(UseSSE42Intrinsics, "SSE4.2 is required");
6218 
6219   // This method uses pcmpestri instruction with bound registers
6220   //   inputs:
6221   //     xmm - substring
6222   //     rax - substring length (elements count)
6223   //     mem - scanned string
6224   //     rdx - string length (elements count)
6225   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6226   //   outputs:
6227   //     rcx - matched index in string
6228   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6229 
6230   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6231         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6232         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6233 
6234   // Note, inline_string_indexOf() generates checks:
6235   // if (substr.count > string.count) return -1;
6236   // if (substr.count == 0) return 0;
6237   assert(int_cnt2 >= 8, "this code isused only for cnt2 >= 8 chars");
6238 
6239   // Load substring.
6240   movdqu(vec, Address(str2, 0));
6241   movl(cnt2, int_cnt2);
6242   movptr(result, str1); // string addr
6243 
6244   if (int_cnt2 > 8) {
6245     jmpb(SCAN_TO_SUBSTR);
6246 
6247     // Reload substr for rescan, this code
6248     // is executed only for large substrings (> 8 chars)
6249     bind(RELOAD_SUBSTR);
6250     movdqu(vec, Address(str2, 0));
6251     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6252 
6253     bind(RELOAD_STR);
6254     // We came here after the beginning of the substring was
6255     // matched but the rest of it was not so we need to search
6256     // again. Start from the next element after the previous match.
6257 
6258     // cnt2 is number of substring reminding elements and
6259     // cnt1 is number of string reminding elements when cmp failed.
6260     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6261     subl(cnt1, cnt2);
6262     addl(cnt1, int_cnt2);
6263     movl(cnt2, int_cnt2); // Now restore cnt2
6264 
6265     decrementl(cnt1);     // Shift to next element
6266     cmpl(cnt1, cnt2);
6267     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6268 
6269     addptr(result, 2);
6270 
6271   } // (int_cnt2 > 8)
6272 
6273   // Scan string for start of substr in 16-byte vectors
6274   bind(SCAN_TO_SUBSTR);
6275   pcmpestri(vec, Address(result, 0), 0x0d);
6276   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6277   subl(cnt1, 8);
6278   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6279   cmpl(cnt1, cnt2);
6280   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6281   addptr(result, 16);
6282   jmpb(SCAN_TO_SUBSTR);
6283 
6284   // Found a potential substr
6285   bind(FOUND_CANDIDATE);
6286   // Matched whole vector if first element matched (tmp(rcx) == 0).
6287   if (int_cnt2 == 8) {
6288     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6289   } else { // int_cnt2 > 8
6290     jccb(Assembler::overflow, FOUND_SUBSTR);
6291   }
6292   // After pcmpestri tmp(rcx) contains matched element index
6293   // Compute start addr of substr
6294   lea(result, Address(result, tmp, Address::times_2));
6295 
6296   // Make sure string is still long enough
6297   subl(cnt1, tmp);
6298   cmpl(cnt1, cnt2);
6299   if (int_cnt2 == 8) {
6300     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6301   } else { // int_cnt2 > 8
6302     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6303   }
6304   // Left less then substring.
6305 
6306   bind(RET_NOT_FOUND);
6307   movl(result, -1);
6308   jmpb(EXIT);
6309 
6310   if (int_cnt2 > 8) {
6311     // This code is optimized for the case when whole substring
6312     // is matched if its head is matched.
6313     bind(MATCH_SUBSTR_HEAD);
6314     pcmpestri(vec, Address(result, 0), 0x0d);
6315     // Reload only string if does not match
6316     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
6317 
6318     Label CONT_SCAN_SUBSTR;
6319     // Compare the rest of substring (> 8 chars).
6320     bind(FOUND_SUBSTR);
6321     // First 8 chars are already matched.
6322     negptr(cnt2);
6323     addptr(cnt2, 8);
6324 
6325     bind(SCAN_SUBSTR);
6326     subl(cnt1, 8);
6327     cmpl(cnt2, -8); // Do not read beyond substring
6328     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6329     // Back-up strings to avoid reading beyond substring:
6330     // cnt1 = cnt1 - cnt2 + 8
6331     addl(cnt1, cnt2); // cnt2 is negative
6332     addl(cnt1, 8);
6333     movl(cnt2, 8); negptr(cnt2);
6334     bind(CONT_SCAN_SUBSTR);
6335     if (int_cnt2 < (int)G) {
6336       movdqu(vec, Address(str2, cnt2, Address::times_2, int_cnt2*2));
6337       pcmpestri(vec, Address(result, cnt2, Address::times_2, int_cnt2*2), 0x0d);
6338     } else {
6339       // calculate index in register to avoid integer overflow (int_cnt2*2)
6340       movl(tmp, int_cnt2);
6341       addptr(tmp, cnt2);
6342       movdqu(vec, Address(str2, tmp, Address::times_2, 0));
6343       pcmpestri(vec, Address(result, tmp, Address::times_2, 0), 0x0d);
6344     }
6345     // Need to reload strings pointers if not matched whole vector
6346     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6347     addptr(cnt2, 8);
6348     jcc(Assembler::negative, SCAN_SUBSTR);
6349     // Fall through if found full substring
6350 
6351   } // (int_cnt2 > 8)
6352 
6353   bind(RET_FOUND);
6354   // Found result if we matched full small substring.
6355   // Compute substr offset
6356   subptr(result, str1);
6357   shrl(result, 1); // index
6358   bind(EXIT);
6359 
6360 } // string_indexofC8
6361 
6362 // Small strings are loaded through stack if they cross page boundary.
6363 void MacroAssembler::string_indexof(Register str1, Register str2,
6364                                     Register cnt1, Register cnt2,
6365                                     int int_cnt2,  Register result,
6366                                     XMMRegister vec, Register tmp) {
6367   ShortBranchVerifier sbv(this);
6368   assert(UseSSE42Intrinsics, "SSE4.2 is required");
6369   //
6370   // int_cnt2 is length of small (< 8 chars) constant substring
6371   // or (-1) for non constant substring in which case its length
6372   // is in cnt2 register.
6373   //
6374   // Note, inline_string_indexOf() generates checks:
6375   // if (substr.count > string.count) return -1;
6376   // if (substr.count == 0) return 0;
6377   //
6378   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < 8), "should be != 0");
6379 
6380   // This method uses pcmpestri instruction with bound registers
6381   //   inputs:
6382   //     xmm - substring
6383   //     rax - substring length (elements count)
6384   //     mem - scanned string
6385   //     rdx - string length (elements count)
6386   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6387   //   outputs:
6388   //     rcx - matched index in string
6389   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6390 
6391   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
6392         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
6393         FOUND_CANDIDATE;
6394 
6395   { //========================================================
6396     // We don't know where these strings are located
6397     // and we can't read beyond them. Load them through stack.
6398     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
6399 
6400     movptr(tmp, rsp); // save old SP
6401 
6402     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
6403       if (int_cnt2 == 1) {  // One char
6404         load_unsigned_short(result, Address(str2, 0));
6405         movdl(vec, result); // move 32 bits
6406       } else if (int_cnt2 == 2) { // Two chars
6407         movdl(vec, Address(str2, 0)); // move 32 bits
6408       } else if (int_cnt2 == 4) { // Four chars
6409         movq(vec, Address(str2, 0));  // move 64 bits
6410       } else { // cnt2 = { 3, 5, 6, 7 }
6411         // Array header size is 12 bytes in 32-bit VM
6412         // + 6 bytes for 3 chars == 18 bytes,
6413         // enough space to load vec and shift.
6414         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
6415         movdqu(vec, Address(str2, (int_cnt2*2)-16));
6416         psrldq(vec, 16-(int_cnt2*2));
6417       }
6418     } else { // not constant substring
6419       cmpl(cnt2, 8);
6420       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
6421 
6422       // We can read beyond string if srt+16 does not cross page boundary
6423       // since heaps are aligned and mapped by pages.
6424       assert(os::vm_page_size() < (int)G, "default page should be small");
6425       movl(result, str2); // We need only low 32 bits
6426       andl(result, (os::vm_page_size()-1));
6427       cmpl(result, (os::vm_page_size()-16));
6428       jccb(Assembler::belowEqual, CHECK_STR);
6429 
6430       // Move small strings to stack to allow load 16 bytes into vec.
6431       subptr(rsp, 16);
6432       int stk_offset = wordSize-2;
6433       push(cnt2);
6434 
6435       bind(COPY_SUBSTR);
6436       load_unsigned_short(result, Address(str2, cnt2, Address::times_2, -2));
6437       movw(Address(rsp, cnt2, Address::times_2, stk_offset), result);
6438       decrement(cnt2);
6439       jccb(Assembler::notZero, COPY_SUBSTR);
6440 
6441       pop(cnt2);
6442       movptr(str2, rsp);  // New substring address
6443     } // non constant
6444 
6445     bind(CHECK_STR);
6446     cmpl(cnt1, 8);
6447     jccb(Assembler::aboveEqual, BIG_STRINGS);
6448 
6449     // Check cross page boundary.
6450     movl(result, str1); // We need only low 32 bits
6451     andl(result, (os::vm_page_size()-1));
6452     cmpl(result, (os::vm_page_size()-16));
6453     jccb(Assembler::belowEqual, BIG_STRINGS);
6454 
6455     subptr(rsp, 16);
6456     int stk_offset = -2;
6457     if (int_cnt2 < 0) { // not constant
6458       push(cnt2);
6459       stk_offset += wordSize;
6460     }
6461     movl(cnt2, cnt1);
6462 
6463     bind(COPY_STR);
6464     load_unsigned_short(result, Address(str1, cnt2, Address::times_2, -2));
6465     movw(Address(rsp, cnt2, Address::times_2, stk_offset), result);
6466     decrement(cnt2);
6467     jccb(Assembler::notZero, COPY_STR);
6468 
6469     if (int_cnt2 < 0) { // not constant
6470       pop(cnt2);
6471     }
6472     movptr(str1, rsp);  // New string address
6473 
6474     bind(BIG_STRINGS);
6475     // Load substring.
6476     if (int_cnt2 < 0) { // -1
6477       movdqu(vec, Address(str2, 0));
6478       push(cnt2);       // substr count
6479       push(str2);       // substr addr
6480       push(str1);       // string addr
6481     } else {
6482       // Small (< 8 chars) constant substrings are loaded already.
6483       movl(cnt2, int_cnt2);
6484     }
6485     push(tmp);  // original SP
6486 
6487   } // Finished loading
6488 
6489   //========================================================
6490   // Start search
6491   //
6492 
6493   movptr(result, str1); // string addr
6494 
6495   if (int_cnt2  < 0) {  // Only for non constant substring
6496     jmpb(SCAN_TO_SUBSTR);
6497 
6498     // SP saved at sp+0
6499     // String saved at sp+1*wordSize
6500     // Substr saved at sp+2*wordSize
6501     // Substr count saved at sp+3*wordSize
6502 
6503     // Reload substr for rescan, this code
6504     // is executed only for large substrings (> 8 chars)
6505     bind(RELOAD_SUBSTR);
6506     movptr(str2, Address(rsp, 2*wordSize));
6507     movl(cnt2, Address(rsp, 3*wordSize));
6508     movdqu(vec, Address(str2, 0));
6509     // We came here after the beginning of the substring was
6510     // matched but the rest of it was not so we need to search
6511     // again. Start from the next element after the previous match.
6512     subptr(str1, result); // Restore counter
6513     shrl(str1, 1);
6514     addl(cnt1, str1);
6515     decrementl(cnt1);   // Shift to next element
6516     cmpl(cnt1, cnt2);
6517     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6518 
6519     addptr(result, 2);
6520   } // non constant
6521 
6522   // Scan string for start of substr in 16-byte vectors
6523   bind(SCAN_TO_SUBSTR);
6524   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6525   pcmpestri(vec, Address(result, 0), 0x0d);
6526   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6527   subl(cnt1, 8);
6528   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6529   cmpl(cnt1, cnt2);
6530   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6531   addptr(result, 16);
6532 
6533   bind(ADJUST_STR);
6534   cmpl(cnt1, 8); // Do not read beyond string
6535   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6536   // Back-up string to avoid reading beyond string.
6537   lea(result, Address(result, cnt1, Address::times_2, -16));
6538   movl(cnt1, 8);
6539   jmpb(SCAN_TO_SUBSTR);
6540 
6541   // Found a potential substr
6542   bind(FOUND_CANDIDATE);
6543   // After pcmpestri tmp(rcx) contains matched element index
6544 
6545   // Make sure string is still long enough
6546   subl(cnt1, tmp);
6547   cmpl(cnt1, cnt2);
6548   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
6549   // Left less then substring.
6550 
6551   bind(RET_NOT_FOUND);
6552   movl(result, -1);
6553   jmpb(CLEANUP);
6554 
6555   bind(FOUND_SUBSTR);
6556   // Compute start addr of substr
6557   lea(result, Address(result, tmp, Address::times_2));
6558 
6559   if (int_cnt2 > 0) { // Constant substring
6560     // Repeat search for small substring (< 8 chars)
6561     // from new point without reloading substring.
6562     // Have to check that we don't read beyond string.
6563     cmpl(tmp, 8-int_cnt2);
6564     jccb(Assembler::greater, ADJUST_STR);
6565     // Fall through if matched whole substring.
6566   } else { // non constant
6567     assert(int_cnt2 == -1, "should be != 0");
6568 
6569     addl(tmp, cnt2);
6570     // Found result if we matched whole substring.
6571     cmpl(tmp, 8);
6572     jccb(Assembler::lessEqual, RET_FOUND);
6573 
6574     // Repeat search for small substring (<= 8 chars)
6575     // from new point 'str1' without reloading substring.
6576     cmpl(cnt2, 8);
6577     // Have to check that we don't read beyond string.
6578     jccb(Assembler::lessEqual, ADJUST_STR);
6579 
6580     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
6581     // Compare the rest of substring (> 8 chars).
6582     movptr(str1, result);
6583 
6584     cmpl(tmp, cnt2);
6585     // First 8 chars are already matched.
6586     jccb(Assembler::equal, CHECK_NEXT);
6587 
6588     bind(SCAN_SUBSTR);
6589     pcmpestri(vec, Address(str1, 0), 0x0d);
6590     // Need to reload strings pointers if not matched whole vector
6591     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6592 
6593     bind(CHECK_NEXT);
6594     subl(cnt2, 8);
6595     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
6596     addptr(str1, 16);
6597     addptr(str2, 16);
6598     subl(cnt1, 8);
6599     cmpl(cnt2, 8); // Do not read beyond substring
6600     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
6601     // Back-up strings to avoid reading beyond substring.
6602     lea(str2, Address(str2, cnt2, Address::times_2, -16));
6603     lea(str1, Address(str1, cnt2, Address::times_2, -16));
6604     subl(cnt1, cnt2);
6605     movl(cnt2, 8);
6606     addl(cnt1, 8);
6607     bind(CONT_SCAN_SUBSTR);
6608     movdqu(vec, Address(str2, 0));
6609     jmpb(SCAN_SUBSTR);
6610 
6611     bind(RET_FOUND_LONG);
6612     movptr(str1, Address(rsp, wordSize));
6613   } // non constant
6614 
6615   bind(RET_FOUND);
6616   // Compute substr offset
6617   subptr(result, str1);
6618   shrl(result, 1); // index
6619 
6620   bind(CLEANUP);
6621   pop(rsp); // restore SP
6622 
6623 } // string_indexof
6624 
6625 // Compare strings.
6626 void MacroAssembler::string_compare(Register str1, Register str2,
6627                                     Register cnt1, Register cnt2, Register result,
6628                                     XMMRegister vec1) {
6629   ShortBranchVerifier sbv(this);
6630   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
6631 
6632   // Compute the minimum of the string lengths and the
6633   // difference of the string lengths (stack).
6634   // Do the conditional move stuff
6635   movl(result, cnt1);
6636   subl(cnt1, cnt2);
6637   push(cnt1);
6638   cmov32(Assembler::lessEqual, cnt2, result);
6639 
6640   // Is the minimum length zero?
6641   testl(cnt2, cnt2);
6642   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6643 
6644   // Compare first characters
6645   load_unsigned_short(result, Address(str1, 0));
6646   load_unsigned_short(cnt1, Address(str2, 0));
6647   subl(result, cnt1);
6648   jcc(Assembler::notZero,  POP_LABEL);
6649   cmpl(cnt2, 1);
6650   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6651 
6652   // Check if the strings start at the same location.
6653   cmpptr(str1, str2);
6654   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6655 
6656   Address::ScaleFactor scale = Address::times_2;
6657   int stride = 8;
6658 
6659   if (UseAVX >= 2 && UseSSE42Intrinsics) {
6660     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
6661     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
6662     Label COMPARE_TAIL_LONG;
6663     int pcmpmask = 0x19;
6664 
6665     // Setup to compare 16-chars (32-bytes) vectors,
6666     // start from first character again because it has aligned address.
6667     int stride2 = 16;
6668     int adr_stride  = stride  << scale;
6669 
6670     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
6671     // rax and rdx are used by pcmpestri as elements counters
6672     movl(result, cnt2);
6673     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
6674     jcc(Assembler::zero, COMPARE_TAIL_LONG);
6675 
6676     // fast path : compare first 2 8-char vectors.
6677     bind(COMPARE_16_CHARS);
6678     movdqu(vec1, Address(str1, 0));
6679     pcmpestri(vec1, Address(str2, 0), pcmpmask);
6680     jccb(Assembler::below, COMPARE_INDEX_CHAR);
6681 
6682     movdqu(vec1, Address(str1, adr_stride));
6683     pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
6684     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
6685     addl(cnt1, stride);
6686 
6687     // Compare the characters at index in cnt1
6688     bind(COMPARE_INDEX_CHAR); //cnt1 has the offset of the mismatching character
6689     load_unsigned_short(result, Address(str1, cnt1, scale));
6690     load_unsigned_short(cnt2, Address(str2, cnt1, scale));
6691     subl(result, cnt2);
6692     jmp(POP_LABEL);
6693 
6694     // Setup the registers to start vector comparison loop
6695     bind(COMPARE_WIDE_VECTORS);
6696     lea(str1, Address(str1, result, scale));
6697     lea(str2, Address(str2, result, scale));
6698     subl(result, stride2);
6699     subl(cnt2, stride2);
6700     jccb(Assembler::zero, COMPARE_WIDE_TAIL);
6701     negptr(result);
6702 
6703     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
6704     bind(COMPARE_WIDE_VECTORS_LOOP);
6705     vmovdqu(vec1, Address(str1, result, scale));
6706     vpxor(vec1, Address(str2, result, scale));
6707     vptest(vec1, vec1);
6708     jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
6709     addptr(result, stride2);
6710     subl(cnt2, stride2);
6711     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
6712     // clean upper bits of YMM registers
6713     vpxor(vec1, vec1);
6714 
6715     // compare wide vectors tail
6716     bind(COMPARE_WIDE_TAIL);
6717     testptr(result, result);
6718     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
6719 
6720     movl(result, stride2);
6721     movl(cnt2, result);
6722     negptr(result);
6723     jmpb(COMPARE_WIDE_VECTORS_LOOP);
6724 
6725     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
6726     bind(VECTOR_NOT_EQUAL);
6727     // clean upper bits of YMM registers
6728     vpxor(vec1, vec1);
6729     lea(str1, Address(str1, result, scale));
6730     lea(str2, Address(str2, result, scale));
6731     jmp(COMPARE_16_CHARS);
6732 
6733     // Compare tail chars, length between 1 to 15 chars
6734     bind(COMPARE_TAIL_LONG);
6735     movl(cnt2, result);
6736     cmpl(cnt2, stride);
6737     jccb(Assembler::less, COMPARE_SMALL_STR);
6738 
6739     movdqu(vec1, Address(str1, 0));
6740     pcmpestri(vec1, Address(str2, 0), pcmpmask);
6741     jcc(Assembler::below, COMPARE_INDEX_CHAR);
6742     subptr(cnt2, stride);
6743     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
6744     lea(str1, Address(str1, result, scale));
6745     lea(str2, Address(str2, result, scale));
6746     negptr(cnt2);
6747     jmpb(WHILE_HEAD_LABEL);
6748 
6749     bind(COMPARE_SMALL_STR);
6750   } else if (UseSSE42Intrinsics) {
6751     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
6752     int pcmpmask = 0x19;
6753     // Setup to compare 8-char (16-byte) vectors,
6754     // start from first character again because it has aligned address.
6755     movl(result, cnt2);
6756     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
6757     jccb(Assembler::zero, COMPARE_TAIL);
6758 
6759     lea(str1, Address(str1, result, scale));
6760     lea(str2, Address(str2, result, scale));
6761     negptr(result);
6762 
6763     // pcmpestri
6764     //   inputs:
6765     //     vec1- substring
6766     //     rax - negative string length (elements count)
6767     //     mem - scanned string
6768     //     rdx - string length (elements count)
6769     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
6770     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
6771     //   outputs:
6772     //     rcx - first mismatched element index
6773     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
6774 
6775     bind(COMPARE_WIDE_VECTORS);
6776     movdqu(vec1, Address(str1, result, scale));
6777     pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
6778     // After pcmpestri cnt1(rcx) contains mismatched element index
6779 
6780     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
6781     addptr(result, stride);
6782     subptr(cnt2, stride);
6783     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
6784 
6785     // compare wide vectors tail
6786     testptr(result, result);
6787     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
6788 
6789     movl(cnt2, stride);
6790     movl(result, stride);
6791     negptr(result);
6792     movdqu(vec1, Address(str1, result, scale));
6793     pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
6794     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
6795 
6796     // Mismatched characters in the vectors
6797     bind(VECTOR_NOT_EQUAL);
6798     addptr(cnt1, result);
6799     load_unsigned_short(result, Address(str1, cnt1, scale));
6800     load_unsigned_short(cnt2, Address(str2, cnt1, scale));
6801     subl(result, cnt2);
6802     jmpb(POP_LABEL);
6803 
6804     bind(COMPARE_TAIL); // limit is zero
6805     movl(cnt2, result);
6806     // Fallthru to tail compare
6807   }
6808   // Shift str2 and str1 to the end of the arrays, negate min
6809   lea(str1, Address(str1, cnt2, scale));
6810   lea(str2, Address(str2, cnt2, scale));
6811   decrementl(cnt2);  // first character was compared already
6812   negptr(cnt2);
6813 
6814   // Compare the rest of the elements
6815   bind(WHILE_HEAD_LABEL);
6816   load_unsigned_short(result, Address(str1, cnt2, scale, 0));
6817   load_unsigned_short(cnt1, Address(str2, cnt2, scale, 0));
6818   subl(result, cnt1);
6819   jccb(Assembler::notZero, POP_LABEL);
6820   increment(cnt2);
6821   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
6822 
6823   // Strings are equal up to min length.  Return the length difference.
6824   bind(LENGTH_DIFF_LABEL);
6825   pop(result);
6826   jmpb(DONE_LABEL);
6827 
6828   // Discard the stored length difference
6829   bind(POP_LABEL);
6830   pop(cnt1);
6831 
6832   // That's it
6833   bind(DONE_LABEL);
6834 }
6835 
6836 // Compare char[] arrays aligned to 4 bytes or substrings.
6837 void MacroAssembler::char_arrays_equals(bool is_array_equ, Register ary1, Register ary2,
6838                                         Register limit, Register result, Register chr,
6839                                         XMMRegister vec1, XMMRegister vec2) {
6840   ShortBranchVerifier sbv(this);
6841   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR;
6842 
6843   int length_offset  = arrayOopDesc::length_offset_in_bytes();
6844   int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
6845 
6846   // Check the input args
6847   cmpptr(ary1, ary2);
6848   jcc(Assembler::equal, TRUE_LABEL);
6849 
6850   if (is_array_equ) {
6851     // Need additional checks for arrays_equals.
6852     testptr(ary1, ary1);
6853     jcc(Assembler::zero, FALSE_LABEL);
6854     testptr(ary2, ary2);
6855     jcc(Assembler::zero, FALSE_LABEL);
6856 
6857     // Check the lengths
6858     movl(limit, Address(ary1, length_offset));
6859     cmpl(limit, Address(ary2, length_offset));
6860     jcc(Assembler::notEqual, FALSE_LABEL);
6861   }
6862 
6863   // count == 0
6864   testl(limit, limit);
6865   jcc(Assembler::zero, TRUE_LABEL);
6866 
6867   if (is_array_equ) {
6868     // Load array address
6869     lea(ary1, Address(ary1, base_offset));
6870     lea(ary2, Address(ary2, base_offset));
6871   }
6872 
6873   shll(limit, 1);      // byte count != 0
6874   movl(result, limit); // copy
6875 
6876   if (UseAVX >= 2) {
6877     // With AVX2, use 32-byte vector compare
6878     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
6879 
6880     // Compare 32-byte vectors
6881     andl(result, 0x0000001e);  //   tail count (in bytes)
6882     andl(limit, 0xffffffe0);   // vector count (in bytes)
6883     jccb(Assembler::zero, COMPARE_TAIL);
6884 
6885     lea(ary1, Address(ary1, limit, Address::times_1));
6886     lea(ary2, Address(ary2, limit, Address::times_1));
6887     negptr(limit);
6888 
6889     bind(COMPARE_WIDE_VECTORS);
6890     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
6891     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
6892     vpxor(vec1, vec2);
6893 
6894     vptest(vec1, vec1);
6895     jccb(Assembler::notZero, FALSE_LABEL);
6896     addptr(limit, 32);
6897     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
6898 
6899     testl(result, result);
6900     jccb(Assembler::zero, TRUE_LABEL);
6901 
6902     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
6903     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
6904     vpxor(vec1, vec2);
6905 
6906     vptest(vec1, vec1);
6907     jccb(Assembler::notZero, FALSE_LABEL);
6908     jmpb(TRUE_LABEL);
6909 
6910     bind(COMPARE_TAIL); // limit is zero
6911     movl(limit, result);
6912     // Fallthru to tail compare
6913   } else if (UseSSE42Intrinsics) {
6914     // With SSE4.2, use double quad vector compare
6915     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
6916 
6917     // Compare 16-byte vectors
6918     andl(result, 0x0000000e);  //   tail count (in bytes)
6919     andl(limit, 0xfffffff0);   // vector count (in bytes)
6920     jccb(Assembler::zero, COMPARE_TAIL);
6921 
6922     lea(ary1, Address(ary1, limit, Address::times_1));
6923     lea(ary2, Address(ary2, limit, Address::times_1));
6924     negptr(limit);
6925 
6926     bind(COMPARE_WIDE_VECTORS);
6927     movdqu(vec1, Address(ary1, limit, Address::times_1));
6928     movdqu(vec2, Address(ary2, limit, Address::times_1));
6929     pxor(vec1, vec2);
6930 
6931     ptest(vec1, vec1);
6932     jccb(Assembler::notZero, FALSE_LABEL);
6933     addptr(limit, 16);
6934     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
6935 
6936     testl(result, result);
6937     jccb(Assembler::zero, TRUE_LABEL);
6938 
6939     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
6940     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
6941     pxor(vec1, vec2);
6942 
6943     ptest(vec1, vec1);
6944     jccb(Assembler::notZero, FALSE_LABEL);
6945     jmpb(TRUE_LABEL);
6946 
6947     bind(COMPARE_TAIL); // limit is zero
6948     movl(limit, result);
6949     // Fallthru to tail compare
6950   }
6951 
6952   // Compare 4-byte vectors
6953   andl(limit, 0xfffffffc); // vector count (in bytes)
6954   jccb(Assembler::zero, COMPARE_CHAR);
6955 
6956   lea(ary1, Address(ary1, limit, Address::times_1));
6957   lea(ary2, Address(ary2, limit, Address::times_1));
6958   negptr(limit);
6959 
6960   bind(COMPARE_VECTORS);
6961   movl(chr, Address(ary1, limit, Address::times_1));
6962   cmpl(chr, Address(ary2, limit, Address::times_1));
6963   jccb(Assembler::notEqual, FALSE_LABEL);
6964   addptr(limit, 4);
6965   jcc(Assembler::notZero, COMPARE_VECTORS);
6966 
6967   // Compare trailing char (final 2 bytes), if any
6968   bind(COMPARE_CHAR);
6969   testl(result, 0x2);   // tail  char
6970   jccb(Assembler::zero, TRUE_LABEL);
6971   load_unsigned_short(chr, Address(ary1, 0));
6972   load_unsigned_short(limit, Address(ary2, 0));
6973   cmpl(chr, limit);
6974   jccb(Assembler::notEqual, FALSE_LABEL);
6975 
6976   bind(TRUE_LABEL);
6977   movl(result, 1);   // return true
6978   jmpb(DONE);
6979 
6980   bind(FALSE_LABEL);
6981   xorl(result, result); // return false
6982 
6983   // That's it
6984   bind(DONE);
6985   if (UseAVX >= 2) {
6986     // clean upper bits of YMM registers
6987     vpxor(vec1, vec1);
6988     vpxor(vec2, vec2);
6989   }
6990 }
6991 
6992 void MacroAssembler::generate_fill(BasicType t, bool aligned,
6993                                    Register to, Register value, Register count,
6994                                    Register rtmp, XMMRegister xtmp) {
6995   ShortBranchVerifier sbv(this);
6996   assert_different_registers(to, value, count, rtmp);
6997   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
6998   Label L_fill_2_bytes, L_fill_4_bytes;
6999 
7000   int shift = -1;
7001   switch (t) {
7002     case T_BYTE:
7003       shift = 2;
7004       break;
7005     case T_SHORT:
7006       shift = 1;
7007       break;
7008     case T_INT:
7009       shift = 0;
7010       break;
7011     default: ShouldNotReachHere();
7012   }
7013 
7014   if (t == T_BYTE) {
7015     andl(value, 0xff);
7016     movl(rtmp, value);
7017     shll(rtmp, 8);
7018     orl(value, rtmp);
7019   }
7020   if (t == T_SHORT) {
7021     andl(value, 0xffff);
7022   }
7023   if (t == T_BYTE || t == T_SHORT) {
7024     movl(rtmp, value);
7025     shll(rtmp, 16);
7026     orl(value, rtmp);
7027   }
7028 
7029   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
7030   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
7031   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
7032     // align source address at 4 bytes address boundary
7033     if (t == T_BYTE) {
7034       // One byte misalignment happens only for byte arrays
7035       testptr(to, 1);
7036       jccb(Assembler::zero, L_skip_align1);
7037       movb(Address(to, 0), value);
7038       increment(to);
7039       decrement(count);
7040       BIND(L_skip_align1);
7041     }
7042     // Two bytes misalignment happens only for byte and short (char) arrays
7043     testptr(to, 2);
7044     jccb(Assembler::zero, L_skip_align2);
7045     movw(Address(to, 0), value);
7046     addptr(to, 2);
7047     subl(count, 1<<(shift-1));
7048     BIND(L_skip_align2);
7049   }
7050   if (UseSSE < 2) {
7051     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7052     // Fill 32-byte chunks
7053     subl(count, 8 << shift);
7054     jcc(Assembler::less, L_check_fill_8_bytes);
7055     align(16);
7056 
7057     BIND(L_fill_32_bytes_loop);
7058 
7059     for (int i = 0; i < 32; i += 4) {
7060       movl(Address(to, i), value);
7061     }
7062 
7063     addptr(to, 32);
7064     subl(count, 8 << shift);
7065     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7066     BIND(L_check_fill_8_bytes);
7067     addl(count, 8 << shift);
7068     jccb(Assembler::zero, L_exit);
7069     jmpb(L_fill_8_bytes);
7070 
7071     //
7072     // length is too short, just fill qwords
7073     //
7074     BIND(L_fill_8_bytes_loop);
7075     movl(Address(to, 0), value);
7076     movl(Address(to, 4), value);
7077     addptr(to, 8);
7078     BIND(L_fill_8_bytes);
7079     subl(count, 1 << (shift + 1));
7080     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7081     // fall through to fill 4 bytes
7082   } else {
7083     Label L_fill_32_bytes;
7084     if (!UseUnalignedLoadStores) {
7085       // align to 8 bytes, we know we are 4 byte aligned to start
7086       testptr(to, 4);
7087       jccb(Assembler::zero, L_fill_32_bytes);
7088       movl(Address(to, 0), value);
7089       addptr(to, 4);
7090       subl(count, 1<<shift);
7091     }
7092     BIND(L_fill_32_bytes);
7093     {
7094       assert( UseSSE >= 2, "supported cpu only" );
7095       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7096       if (UseAVX > 2) {
7097         movl(rtmp, 0xffff);
7098 #ifdef _LP64
7099         kmovql(k1, rtmp);
7100 #else
7101         kmovdl(k1, rtmp);
7102 #endif
7103       }
7104       movdl(xtmp, value);
7105       if (UseAVX > 2 && UseUnalignedLoadStores) {
7106         // Fill 64-byte chunks
7107         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7108         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
7109 
7110         subl(count, 16 << shift);
7111         jcc(Assembler::less, L_check_fill_32_bytes);
7112         align(16);
7113 
7114         BIND(L_fill_64_bytes_loop);
7115         evmovdqu(Address(to, 0), xtmp, Assembler::AVX_512bit);
7116         addptr(to, 64);
7117         subl(count, 16 << shift);
7118         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7119 
7120         BIND(L_check_fill_32_bytes);
7121         addl(count, 8 << shift);
7122         jccb(Assembler::less, L_check_fill_8_bytes);
7123         evmovdqu(Address(to, 0), xtmp, Assembler::AVX_256bit);
7124         addptr(to, 32);
7125         subl(count, 8 << shift);
7126 
7127         BIND(L_check_fill_8_bytes);
7128       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
7129         // Fill 64-byte chunks
7130         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7131         vpbroadcastd(xtmp, xtmp);
7132 
7133         subl(count, 16 << shift);
7134         jcc(Assembler::less, L_check_fill_32_bytes);
7135         align(16);
7136 
7137         BIND(L_fill_64_bytes_loop);
7138         vmovdqu(Address(to, 0), xtmp);
7139         vmovdqu(Address(to, 32), xtmp);
7140         addptr(to, 64);
7141         subl(count, 16 << shift);
7142         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7143 
7144         BIND(L_check_fill_32_bytes);
7145         addl(count, 8 << shift);
7146         jccb(Assembler::less, L_check_fill_8_bytes);
7147         vmovdqu(Address(to, 0), xtmp);
7148         addptr(to, 32);
7149         subl(count, 8 << shift);
7150 
7151         BIND(L_check_fill_8_bytes);
7152         // clean upper bits of YMM registers
7153         movdl(xtmp, value);
7154         pshufd(xtmp, xtmp, 0);
7155       } else {
7156         // Fill 32-byte chunks
7157         pshufd(xtmp, xtmp, 0);
7158 
7159         subl(count, 8 << shift);
7160         jcc(Assembler::less, L_check_fill_8_bytes);
7161         align(16);
7162 
7163         BIND(L_fill_32_bytes_loop);
7164 
7165         if (UseUnalignedLoadStores) {
7166           movdqu(Address(to, 0), xtmp);
7167           movdqu(Address(to, 16), xtmp);
7168         } else {
7169           movq(Address(to, 0), xtmp);
7170           movq(Address(to, 8), xtmp);
7171           movq(Address(to, 16), xtmp);
7172           movq(Address(to, 24), xtmp);
7173         }
7174 
7175         addptr(to, 32);
7176         subl(count, 8 << shift);
7177         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7178 
7179         BIND(L_check_fill_8_bytes);
7180       }
7181       addl(count, 8 << shift);
7182       jccb(Assembler::zero, L_exit);
7183       jmpb(L_fill_8_bytes);
7184 
7185       //
7186       // length is too short, just fill qwords
7187       //
7188       BIND(L_fill_8_bytes_loop);
7189       movq(Address(to, 0), xtmp);
7190       addptr(to, 8);
7191       BIND(L_fill_8_bytes);
7192       subl(count, 1 << (shift + 1));
7193       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7194     }
7195   }
7196   // fill trailing 4 bytes
7197   BIND(L_fill_4_bytes);
7198   testl(count, 1<<shift);
7199   jccb(Assembler::zero, L_fill_2_bytes);
7200   movl(Address(to, 0), value);
7201   if (t == T_BYTE || t == T_SHORT) {
7202     addptr(to, 4);
7203     BIND(L_fill_2_bytes);
7204     // fill trailing 2 bytes
7205     testl(count, 1<<(shift-1));
7206     jccb(Assembler::zero, L_fill_byte);
7207     movw(Address(to, 0), value);
7208     if (t == T_BYTE) {
7209       addptr(to, 2);
7210       BIND(L_fill_byte);
7211       // fill trailing byte
7212       testl(count, 1);
7213       jccb(Assembler::zero, L_exit);
7214       movb(Address(to, 0), value);
7215     } else {
7216       BIND(L_fill_byte);
7217     }
7218   } else {
7219     BIND(L_fill_2_bytes);
7220   }
7221   BIND(L_exit);
7222 }
7223 
7224 // encode char[] to byte[] in ISO_8859_1
7225 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
7226                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
7227                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
7228                                       Register tmp5, Register result) {
7229   // rsi: src
7230   // rdi: dst
7231   // rdx: len
7232   // rcx: tmp5
7233   // rax: result
7234   ShortBranchVerifier sbv(this);
7235   assert_different_registers(src, dst, len, tmp5, result);
7236   Label L_done, L_copy_1_char, L_copy_1_char_exit;
7237 
7238   // set result
7239   xorl(result, result);
7240   // check for zero length
7241   testl(len, len);
7242   jcc(Assembler::zero, L_done);
7243   movl(result, len);
7244 
7245   // Setup pointers
7246   lea(src, Address(src, len, Address::times_2)); // char[]
7247   lea(dst, Address(dst, len, Address::times_1)); // byte[]
7248   negptr(len);
7249 
7250   if (UseSSE42Intrinsics || UseAVX >= 2) {
7251     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
7252     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
7253 
7254     if (UseAVX >= 2) {
7255       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
7256       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
7257       movdl(tmp1Reg, tmp5);
7258       vpbroadcastd(tmp1Reg, tmp1Reg);
7259       jmpb(L_chars_32_check);
7260 
7261       bind(L_copy_32_chars);
7262       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
7263       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
7264       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
7265       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
7266       jccb(Assembler::notZero, L_copy_32_chars_exit);
7267       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
7268       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
7269       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
7270 
7271       bind(L_chars_32_check);
7272       addptr(len, 32);
7273       jccb(Assembler::lessEqual, L_copy_32_chars);
7274 
7275       bind(L_copy_32_chars_exit);
7276       subptr(len, 16);
7277       jccb(Assembler::greater, L_copy_16_chars_exit);
7278 
7279     } else if (UseSSE42Intrinsics) {
7280       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
7281       movdl(tmp1Reg, tmp5);
7282       pshufd(tmp1Reg, tmp1Reg, 0);
7283       jmpb(L_chars_16_check);
7284     }
7285 
7286     bind(L_copy_16_chars);
7287     if (UseAVX >= 2) {
7288       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
7289       vptest(tmp2Reg, tmp1Reg);
7290       jccb(Assembler::notZero, L_copy_16_chars_exit);
7291       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
7292       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
7293     } else {
7294       if (UseAVX > 0) {
7295         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
7296         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
7297         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
7298       } else {
7299         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
7300         por(tmp2Reg, tmp3Reg);
7301         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
7302         por(tmp2Reg, tmp4Reg);
7303       }
7304       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
7305       jccb(Assembler::notZero, L_copy_16_chars_exit);
7306       packuswb(tmp3Reg, tmp4Reg);
7307     }
7308     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
7309 
7310     bind(L_chars_16_check);
7311     addptr(len, 16);
7312     jccb(Assembler::lessEqual, L_copy_16_chars);
7313 
7314     bind(L_copy_16_chars_exit);
7315     if (UseAVX >= 2) {
7316       // clean upper bits of YMM registers
7317       vpxor(tmp2Reg, tmp2Reg);
7318       vpxor(tmp3Reg, tmp3Reg);
7319       vpxor(tmp4Reg, tmp4Reg);
7320       movdl(tmp1Reg, tmp5);
7321       pshufd(tmp1Reg, tmp1Reg, 0);
7322     }
7323     subptr(len, 8);
7324     jccb(Assembler::greater, L_copy_8_chars_exit);
7325 
7326     bind(L_copy_8_chars);
7327     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
7328     ptest(tmp3Reg, tmp1Reg);
7329     jccb(Assembler::notZero, L_copy_8_chars_exit);
7330     packuswb(tmp3Reg, tmp1Reg);
7331     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
7332     addptr(len, 8);
7333     jccb(Assembler::lessEqual, L_copy_8_chars);
7334 
7335     bind(L_copy_8_chars_exit);
7336     subptr(len, 8);
7337     jccb(Assembler::zero, L_done);
7338   }
7339 
7340   bind(L_copy_1_char);
7341   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
7342   testl(tmp5, 0xff00);      // check if Unicode char
7343   jccb(Assembler::notZero, L_copy_1_char_exit);
7344   movb(Address(dst, len, Address::times_1, 0), tmp5);
7345   addptr(len, 1);
7346   jccb(Assembler::less, L_copy_1_char);
7347 
7348   bind(L_copy_1_char_exit);
7349   addptr(result, len); // len is negative count of not processed elements
7350   bind(L_done);
7351 }
7352 
7353 #ifdef _LP64
7354 /**
7355  * Helper for multiply_to_len().
7356  */
7357 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
7358   addq(dest_lo, src1);
7359   adcq(dest_hi, 0);
7360   addq(dest_lo, src2);
7361   adcq(dest_hi, 0);
7362 }
7363 
7364 /**
7365  * Multiply 64 bit by 64 bit first loop.
7366  */
7367 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
7368                                            Register y, Register y_idx, Register z,
7369                                            Register carry, Register product,
7370                                            Register idx, Register kdx) {
7371   //
7372   //  jlong carry, x[], y[], z[];
7373   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
7374   //    huge_128 product = y[idx] * x[xstart] + carry;
7375   //    z[kdx] = (jlong)product;
7376   //    carry  = (jlong)(product >>> 64);
7377   //  }
7378   //  z[xstart] = carry;
7379   //
7380 
7381   Label L_first_loop, L_first_loop_exit;
7382   Label L_one_x, L_one_y, L_multiply;
7383 
7384   decrementl(xstart);
7385   jcc(Assembler::negative, L_one_x);
7386 
7387   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
7388   rorq(x_xstart, 32); // convert big-endian to little-endian
7389 
7390   bind(L_first_loop);
7391   decrementl(idx);
7392   jcc(Assembler::negative, L_first_loop_exit);
7393   decrementl(idx);
7394   jcc(Assembler::negative, L_one_y);
7395   movq(y_idx, Address(y, idx, Address::times_4,  0));
7396   rorq(y_idx, 32); // convert big-endian to little-endian
7397   bind(L_multiply);
7398   movq(product, x_xstart);
7399   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
7400   addq(product, carry);
7401   adcq(rdx, 0);
7402   subl(kdx, 2);
7403   movl(Address(z, kdx, Address::times_4,  4), product);
7404   shrq(product, 32);
7405   movl(Address(z, kdx, Address::times_4,  0), product);
7406   movq(carry, rdx);
7407   jmp(L_first_loop);
7408 
7409   bind(L_one_y);
7410   movl(y_idx, Address(y,  0));
7411   jmp(L_multiply);
7412 
7413   bind(L_one_x);
7414   movl(x_xstart, Address(x,  0));
7415   jmp(L_first_loop);
7416 
7417   bind(L_first_loop_exit);
7418 }
7419 
7420 /**
7421  * Multiply 64 bit by 64 bit and add 128 bit.
7422  */
7423 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
7424                                             Register yz_idx, Register idx,
7425                                             Register carry, Register product, int offset) {
7426   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
7427   //     z[kdx] = (jlong)product;
7428 
7429   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
7430   rorq(yz_idx, 32); // convert big-endian to little-endian
7431   movq(product, x_xstart);
7432   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
7433   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
7434   rorq(yz_idx, 32); // convert big-endian to little-endian
7435 
7436   add2_with_carry(rdx, product, carry, yz_idx);
7437 
7438   movl(Address(z, idx, Address::times_4,  offset+4), product);
7439   shrq(product, 32);
7440   movl(Address(z, idx, Address::times_4,  offset), product);
7441 
7442 }
7443 
7444 /**
7445  * Multiply 128 bit by 128 bit. Unrolled inner loop.
7446  */
7447 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
7448                                              Register yz_idx, Register idx, Register jdx,
7449                                              Register carry, Register product,
7450                                              Register carry2) {
7451   //   jlong carry, x[], y[], z[];
7452   //   int kdx = ystart+1;
7453   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
7454   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
7455   //     z[kdx+idx+1] = (jlong)product;
7456   //     jlong carry2  = (jlong)(product >>> 64);
7457   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
7458   //     z[kdx+idx] = (jlong)product;
7459   //     carry  = (jlong)(product >>> 64);
7460   //   }
7461   //   idx += 2;
7462   //   if (idx > 0) {
7463   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
7464   //     z[kdx+idx] = (jlong)product;
7465   //     carry  = (jlong)(product >>> 64);
7466   //   }
7467   //
7468 
7469   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
7470 
7471   movl(jdx, idx);
7472   andl(jdx, 0xFFFFFFFC);
7473   shrl(jdx, 2);
7474 
7475   bind(L_third_loop);
7476   subl(jdx, 1);
7477   jcc(Assembler::negative, L_third_loop_exit);
7478   subl(idx, 4);
7479 
7480   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
7481   movq(carry2, rdx);
7482 
7483   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
7484   movq(carry, rdx);
7485   jmp(L_third_loop);
7486 
7487   bind (L_third_loop_exit);
7488 
7489   andl (idx, 0x3);
7490   jcc(Assembler::zero, L_post_third_loop_done);
7491 
7492   Label L_check_1;
7493   subl(idx, 2);
7494   jcc(Assembler::negative, L_check_1);
7495 
7496   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
7497   movq(carry, rdx);
7498 
7499   bind (L_check_1);
7500   addl (idx, 0x2);
7501   andl (idx, 0x1);
7502   subl(idx, 1);
7503   jcc(Assembler::negative, L_post_third_loop_done);
7504 
7505   movl(yz_idx, Address(y, idx, Address::times_4,  0));
7506   movq(product, x_xstart);
7507   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
7508   movl(yz_idx, Address(z, idx, Address::times_4,  0));
7509 
7510   add2_with_carry(rdx, product, yz_idx, carry);
7511 
7512   movl(Address(z, idx, Address::times_4,  0), product);
7513   shrq(product, 32);
7514 
7515   shlq(rdx, 32);
7516   orq(product, rdx);
7517   movq(carry, product);
7518 
7519   bind(L_post_third_loop_done);
7520 }
7521 
7522 /**
7523  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
7524  *
7525  */
7526 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
7527                                                   Register carry, Register carry2,
7528                                                   Register idx, Register jdx,
7529                                                   Register yz_idx1, Register yz_idx2,
7530                                                   Register tmp, Register tmp3, Register tmp4) {
7531   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
7532 
7533   //   jlong carry, x[], y[], z[];
7534   //   int kdx = ystart+1;
7535   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
7536   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
7537   //     jlong carry2  = (jlong)(tmp3 >>> 64);
7538   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
7539   //     carry  = (jlong)(tmp4 >>> 64);
7540   //     z[kdx+idx+1] = (jlong)tmp3;
7541   //     z[kdx+idx] = (jlong)tmp4;
7542   //   }
7543   //   idx += 2;
7544   //   if (idx > 0) {
7545   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
7546   //     z[kdx+idx] = (jlong)yz_idx1;
7547   //     carry  = (jlong)(yz_idx1 >>> 64);
7548   //   }
7549   //
7550 
7551   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
7552 
7553   movl(jdx, idx);
7554   andl(jdx, 0xFFFFFFFC);
7555   shrl(jdx, 2);
7556 
7557   bind(L_third_loop);
7558   subl(jdx, 1);
7559   jcc(Assembler::negative, L_third_loop_exit);
7560   subl(idx, 4);
7561 
7562   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
7563   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
7564   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
7565   rorxq(yz_idx2, yz_idx2, 32);
7566 
7567   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
7568   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
7569 
7570   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
7571   rorxq(yz_idx1, yz_idx1, 32);
7572   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
7573   rorxq(yz_idx2, yz_idx2, 32);
7574 
7575   if (VM_Version::supports_adx()) {
7576     adcxq(tmp3, carry);
7577     adoxq(tmp3, yz_idx1);
7578 
7579     adcxq(tmp4, tmp);
7580     adoxq(tmp4, yz_idx2);
7581 
7582     movl(carry, 0); // does not affect flags
7583     adcxq(carry2, carry);
7584     adoxq(carry2, carry);
7585   } else {
7586     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
7587     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
7588   }
7589   movq(carry, carry2);
7590 
7591   movl(Address(z, idx, Address::times_4, 12), tmp3);
7592   shrq(tmp3, 32);
7593   movl(Address(z, idx, Address::times_4,  8), tmp3);
7594 
7595   movl(Address(z, idx, Address::times_4,  4), tmp4);
7596   shrq(tmp4, 32);
7597   movl(Address(z, idx, Address::times_4,  0), tmp4);
7598 
7599   jmp(L_third_loop);
7600 
7601   bind (L_third_loop_exit);
7602 
7603   andl (idx, 0x3);
7604   jcc(Assembler::zero, L_post_third_loop_done);
7605 
7606   Label L_check_1;
7607   subl(idx, 2);
7608   jcc(Assembler::negative, L_check_1);
7609 
7610   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
7611   rorxq(yz_idx1, yz_idx1, 32);
7612   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
7613   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
7614   rorxq(yz_idx2, yz_idx2, 32);
7615 
7616   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
7617 
7618   movl(Address(z, idx, Address::times_4,  4), tmp3);
7619   shrq(tmp3, 32);
7620   movl(Address(z, idx, Address::times_4,  0), tmp3);
7621   movq(carry, tmp4);
7622 
7623   bind (L_check_1);
7624   addl (idx, 0x2);
7625   andl (idx, 0x1);
7626   subl(idx, 1);
7627   jcc(Assembler::negative, L_post_third_loop_done);
7628   movl(tmp4, Address(y, idx, Address::times_4,  0));
7629   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
7630   movl(tmp4, Address(z, idx, Address::times_4,  0));
7631 
7632   add2_with_carry(carry2, tmp3, tmp4, carry);
7633 
7634   movl(Address(z, idx, Address::times_4,  0), tmp3);
7635   shrq(tmp3, 32);
7636 
7637   shlq(carry2, 32);
7638   orq(tmp3, carry2);
7639   movq(carry, tmp3);
7640 
7641   bind(L_post_third_loop_done);
7642 }
7643 
7644 /**
7645  * Code for BigInteger::multiplyToLen() instrinsic.
7646  *
7647  * rdi: x
7648  * rax: xlen
7649  * rsi: y
7650  * rcx: ylen
7651  * r8:  z
7652  * r11: zlen
7653  * r12: tmp1
7654  * r13: tmp2
7655  * r14: tmp3
7656  * r15: tmp4
7657  * rbx: tmp5
7658  *
7659  */
7660 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
7661                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
7662   ShortBranchVerifier sbv(this);
7663   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
7664 
7665   push(tmp1);
7666   push(tmp2);
7667   push(tmp3);
7668   push(tmp4);
7669   push(tmp5);
7670 
7671   push(xlen);
7672   push(zlen);
7673 
7674   const Register idx = tmp1;
7675   const Register kdx = tmp2;
7676   const Register xstart = tmp3;
7677 
7678   const Register y_idx = tmp4;
7679   const Register carry = tmp5;
7680   const Register product  = xlen;
7681   const Register x_xstart = zlen;  // reuse register
7682 
7683   // First Loop.
7684   //
7685   //  final static long LONG_MASK = 0xffffffffL;
7686   //  int xstart = xlen - 1;
7687   //  int ystart = ylen - 1;
7688   //  long carry = 0;
7689   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
7690   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
7691   //    z[kdx] = (int)product;
7692   //    carry = product >>> 32;
7693   //  }
7694   //  z[xstart] = (int)carry;
7695   //
7696 
7697   movl(idx, ylen);      // idx = ylen;
7698   movl(kdx, zlen);      // kdx = xlen+ylen;
7699   xorq(carry, carry);   // carry = 0;
7700 
7701   Label L_done;
7702 
7703   movl(xstart, xlen);
7704   decrementl(xstart);
7705   jcc(Assembler::negative, L_done);
7706 
7707   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
7708 
7709   Label L_second_loop;
7710   testl(kdx, kdx);
7711   jcc(Assembler::zero, L_second_loop);
7712 
7713   Label L_carry;
7714   subl(kdx, 1);
7715   jcc(Assembler::zero, L_carry);
7716 
7717   movl(Address(z, kdx, Address::times_4,  0), carry);
7718   shrq(carry, 32);
7719   subl(kdx, 1);
7720 
7721   bind(L_carry);
7722   movl(Address(z, kdx, Address::times_4,  0), carry);
7723 
7724   // Second and third (nested) loops.
7725   //
7726   // for (int i = xstart-1; i >= 0; i--) { // Second loop
7727   //   carry = 0;
7728   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
7729   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
7730   //                    (z[k] & LONG_MASK) + carry;
7731   //     z[k] = (int)product;
7732   //     carry = product >>> 32;
7733   //   }
7734   //   z[i] = (int)carry;
7735   // }
7736   //
7737   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
7738 
7739   const Register jdx = tmp1;
7740 
7741   bind(L_second_loop);
7742   xorl(carry, carry);    // carry = 0;
7743   movl(jdx, ylen);       // j = ystart+1
7744 
7745   subl(xstart, 1);       // i = xstart-1;
7746   jcc(Assembler::negative, L_done);
7747 
7748   push (z);
7749 
7750   Label L_last_x;
7751   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
7752   subl(xstart, 1);       // i = xstart-1;
7753   jcc(Assembler::negative, L_last_x);
7754 
7755   if (UseBMI2Instructions) {
7756     movq(rdx,  Address(x, xstart, Address::times_4,  0));
7757     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
7758   } else {
7759     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
7760     rorq(x_xstart, 32);  // convert big-endian to little-endian
7761   }
7762 
7763   Label L_third_loop_prologue;
7764   bind(L_third_loop_prologue);
7765 
7766   push (x);
7767   push (xstart);
7768   push (ylen);
7769 
7770 
7771   if (UseBMI2Instructions) {
7772     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
7773   } else { // !UseBMI2Instructions
7774     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
7775   }
7776 
7777   pop(ylen);
7778   pop(xlen);
7779   pop(x);
7780   pop(z);
7781 
7782   movl(tmp3, xlen);
7783   addl(tmp3, 1);
7784   movl(Address(z, tmp3, Address::times_4,  0), carry);
7785   subl(tmp3, 1);
7786   jccb(Assembler::negative, L_done);
7787 
7788   shrq(carry, 32);
7789   movl(Address(z, tmp3, Address::times_4,  0), carry);
7790   jmp(L_second_loop);
7791 
7792   // Next infrequent code is moved outside loops.
7793   bind(L_last_x);
7794   if (UseBMI2Instructions) {
7795     movl(rdx, Address(x,  0));
7796   } else {
7797     movl(x_xstart, Address(x,  0));
7798   }
7799   jmp(L_third_loop_prologue);
7800 
7801   bind(L_done);
7802 
7803   pop(zlen);
7804   pop(xlen);
7805 
7806   pop(tmp5);
7807   pop(tmp4);
7808   pop(tmp3);
7809   pop(tmp2);
7810   pop(tmp1);
7811 }
7812 
7813 //Helper functions for square_to_len()
7814 
7815 /**
7816  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
7817  * Preserves x and z and modifies rest of the registers.
7818  */
7819 
7820 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
7821   // Perform square and right shift by 1
7822   // Handle odd xlen case first, then for even xlen do the following
7823   // jlong carry = 0;
7824   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
7825   //     huge_128 product = x[j:j+1] * x[j:j+1];
7826   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
7827   //     z[i+2:i+3] = (jlong)(product >>> 1);
7828   //     carry = (jlong)product;
7829   // }
7830 
7831   xorq(tmp5, tmp5);     // carry
7832   xorq(rdxReg, rdxReg);
7833   xorl(tmp1, tmp1);     // index for x
7834   xorl(tmp4, tmp4);     // index for z
7835 
7836   Label L_first_loop, L_first_loop_exit;
7837 
7838   testl(xlen, 1);
7839   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
7840 
7841   // Square and right shift by 1 the odd element using 32 bit multiply
7842   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
7843   imulq(raxReg, raxReg);
7844   shrq(raxReg, 1);
7845   adcq(tmp5, 0);
7846   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
7847   incrementl(tmp1);
7848   addl(tmp4, 2);
7849 
7850   // Square and  right shift by 1 the rest using 64 bit multiply
7851   bind(L_first_loop);
7852   cmpptr(tmp1, xlen);
7853   jccb(Assembler::equal, L_first_loop_exit);
7854 
7855   // Square
7856   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
7857   rorq(raxReg, 32);    // convert big-endian to little-endian
7858   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
7859 
7860   // Right shift by 1 and save carry
7861   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
7862   rcrq(rdxReg, 1);
7863   rcrq(raxReg, 1);
7864   adcq(tmp5, 0);
7865 
7866   // Store result in z
7867   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
7868   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
7869 
7870   // Update indices for x and z
7871   addl(tmp1, 2);
7872   addl(tmp4, 4);
7873   jmp(L_first_loop);
7874 
7875   bind(L_first_loop_exit);
7876 }
7877 
7878 
7879 /**
7880  * Perform the following multiply add operation using BMI2 instructions
7881  * carry:sum = sum + op1*op2 + carry
7882  * op2 should be in rdx
7883  * op2 is preserved, all other registers are modified
7884  */
7885 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
7886   // assert op2 is rdx
7887   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
7888   addq(sum, carry);
7889   adcq(tmp2, 0);
7890   addq(sum, op1);
7891   adcq(tmp2, 0);
7892   movq(carry, tmp2);
7893 }
7894 
7895 /**
7896  * Perform the following multiply add operation:
7897  * carry:sum = sum + op1*op2 + carry
7898  * Preserves op1, op2 and modifies rest of registers
7899  */
7900 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
7901   // rdx:rax = op1 * op2
7902   movq(raxReg, op2);
7903   mulq(op1);
7904 
7905   //  rdx:rax = sum + carry + rdx:rax
7906   addq(sum, carry);
7907   adcq(rdxReg, 0);
7908   addq(sum, raxReg);
7909   adcq(rdxReg, 0);
7910 
7911   // carry:sum = rdx:sum
7912   movq(carry, rdxReg);
7913 }
7914 
7915 /**
7916  * Add 64 bit long carry into z[] with carry propogation.
7917  * Preserves z and carry register values and modifies rest of registers.
7918  *
7919  */
7920 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
7921   Label L_fourth_loop, L_fourth_loop_exit;
7922 
7923   movl(tmp1, 1);
7924   subl(zlen, 2);
7925   addq(Address(z, zlen, Address::times_4, 0), carry);
7926 
7927   bind(L_fourth_loop);
7928   jccb(Assembler::carryClear, L_fourth_loop_exit);
7929   subl(zlen, 2);
7930   jccb(Assembler::negative, L_fourth_loop_exit);
7931   addq(Address(z, zlen, Address::times_4, 0), tmp1);
7932   jmp(L_fourth_loop);
7933   bind(L_fourth_loop_exit);
7934 }
7935 
7936 /**
7937  * Shift z[] left by 1 bit.
7938  * Preserves x, len, z and zlen registers and modifies rest of the registers.
7939  *
7940  */
7941 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
7942 
7943   Label L_fifth_loop, L_fifth_loop_exit;
7944 
7945   // Fifth loop
7946   // Perform primitiveLeftShift(z, zlen, 1)
7947 
7948   const Register prev_carry = tmp1;
7949   const Register new_carry = tmp4;
7950   const Register value = tmp2;
7951   const Register zidx = tmp3;
7952 
7953   // int zidx, carry;
7954   // long value;
7955   // carry = 0;
7956   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
7957   //    (carry:value)  = (z[i] << 1) | carry ;
7958   //    z[i] = value;
7959   // }
7960 
7961   movl(zidx, zlen);
7962   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
7963 
7964   bind(L_fifth_loop);
7965   decl(zidx);  // Use decl to preserve carry flag
7966   decl(zidx);
7967   jccb(Assembler::negative, L_fifth_loop_exit);
7968 
7969   if (UseBMI2Instructions) {
7970      movq(value, Address(z, zidx, Address::times_4, 0));
7971      rclq(value, 1);
7972      rorxq(value, value, 32);
7973      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
7974   }
7975   else {
7976     // clear new_carry
7977     xorl(new_carry, new_carry);
7978 
7979     // Shift z[i] by 1, or in previous carry and save new carry
7980     movq(value, Address(z, zidx, Address::times_4, 0));
7981     shlq(value, 1);
7982     adcl(new_carry, 0);
7983 
7984     orq(value, prev_carry);
7985     rorq(value, 0x20);
7986     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
7987 
7988     // Set previous carry = new carry
7989     movl(prev_carry, new_carry);
7990   }
7991   jmp(L_fifth_loop);
7992 
7993   bind(L_fifth_loop_exit);
7994 }
7995 
7996 
7997 /**
7998  * Code for BigInteger::squareToLen() intrinsic
7999  *
8000  * rdi: x
8001  * rsi: len
8002  * r8:  z
8003  * rcx: zlen
8004  * r12: tmp1
8005  * r13: tmp2
8006  * r14: tmp3
8007  * r15: tmp4
8008  * rbx: tmp5
8009  *
8010  */
8011 void MacroAssembler::square_to_len(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8012 
8013   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, fifth_loop, fifth_loop_exit, L_last_x, L_multiply;
8014   push(tmp1);
8015   push(tmp2);
8016   push(tmp3);
8017   push(tmp4);
8018   push(tmp5);
8019 
8020   // First loop
8021   // Store the squares, right shifted one bit (i.e., divided by 2).
8022   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
8023 
8024   // Add in off-diagonal sums.
8025   //
8026   // Second, third (nested) and fourth loops.
8027   // zlen +=2;
8028   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
8029   //    carry = 0;
8030   //    long op2 = x[xidx:xidx+1];
8031   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
8032   //       k -= 2;
8033   //       long op1 = x[j:j+1];
8034   //       long sum = z[k:k+1];
8035   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
8036   //       z[k:k+1] = sum;
8037   //    }
8038   //    add_one_64(z, k, carry, tmp_regs);
8039   // }
8040 
8041   const Register carry = tmp5;
8042   const Register sum = tmp3;
8043   const Register op1 = tmp4;
8044   Register op2 = tmp2;
8045 
8046   push(zlen);
8047   push(len);
8048   addl(zlen,2);
8049   bind(L_second_loop);
8050   xorq(carry, carry);
8051   subl(zlen, 4);
8052   subl(len, 2);
8053   push(zlen);
8054   push(len);
8055   cmpl(len, 0);
8056   jccb(Assembler::lessEqual, L_second_loop_exit);
8057 
8058   // Multiply an array by one 64 bit long.
8059   if (UseBMI2Instructions) {
8060     op2 = rdxReg;
8061     movq(op2, Address(x, len, Address::times_4,  0));
8062     rorxq(op2, op2, 32);
8063   }
8064   else {
8065     movq(op2, Address(x, len, Address::times_4,  0));
8066     rorq(op2, 32);
8067   }
8068 
8069   bind(L_third_loop);
8070   decrementl(len);
8071   jccb(Assembler::negative, L_third_loop_exit);
8072   decrementl(len);
8073   jccb(Assembler::negative, L_last_x);
8074 
8075   movq(op1, Address(x, len, Address::times_4,  0));
8076   rorq(op1, 32);
8077 
8078   bind(L_multiply);
8079   subl(zlen, 2);
8080   movq(sum, Address(z, zlen, Address::times_4,  0));
8081 
8082   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
8083   if (UseBMI2Instructions) {
8084     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
8085   }
8086   else {
8087     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8088   }
8089 
8090   movq(Address(z, zlen, Address::times_4, 0), sum);
8091 
8092   jmp(L_third_loop);
8093   bind(L_third_loop_exit);
8094 
8095   // Fourth loop
8096   // Add 64 bit long carry into z with carry propogation.
8097   // Uses offsetted zlen.
8098   add_one_64(z, zlen, carry, tmp1);
8099 
8100   pop(len);
8101   pop(zlen);
8102   jmp(L_second_loop);
8103 
8104   // Next infrequent code is moved outside loops.
8105   bind(L_last_x);
8106   movl(op1, Address(x, 0));
8107   jmp(L_multiply);
8108 
8109   bind(L_second_loop_exit);
8110   pop(len);
8111   pop(zlen);
8112   pop(len);
8113   pop(zlen);
8114 
8115   // Fifth loop
8116   // Shift z left 1 bit.
8117   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
8118 
8119   // z[zlen-1] |= x[len-1] & 1;
8120   movl(tmp3, Address(x, len, Address::times_4, -4));
8121   andl(tmp3, 1);
8122   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
8123 
8124   pop(tmp5);
8125   pop(tmp4);
8126   pop(tmp3);
8127   pop(tmp2);
8128   pop(tmp1);
8129 }
8130 
8131 /**
8132  * Helper function for mul_add()
8133  * Multiply the in[] by int k and add to out[] starting at offset offs using
8134  * 128 bit by 32 bit multiply and return the carry in tmp5.
8135  * Only quad int aligned length of in[] is operated on in this function.
8136  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
8137  * This function preserves out, in and k registers.
8138  * len and offset point to the appropriate index in "in" & "out" correspondingly
8139  * tmp5 has the carry.
8140  * other registers are temporary and are modified.
8141  *
8142  */
8143 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
8144   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
8145   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8146 
8147   Label L_first_loop, L_first_loop_exit;
8148 
8149   movl(tmp1, len);
8150   shrl(tmp1, 2);
8151 
8152   bind(L_first_loop);
8153   subl(tmp1, 1);
8154   jccb(Assembler::negative, L_first_loop_exit);
8155 
8156   subl(len, 4);
8157   subl(offset, 4);
8158 
8159   Register op2 = tmp2;
8160   const Register sum = tmp3;
8161   const Register op1 = tmp4;
8162   const Register carry = tmp5;
8163 
8164   if (UseBMI2Instructions) {
8165     op2 = rdxReg;
8166   }
8167 
8168   movq(op1, Address(in, len, Address::times_4,  8));
8169   rorq(op1, 32);
8170   movq(sum, Address(out, offset, Address::times_4,  8));
8171   rorq(sum, 32);
8172   if (UseBMI2Instructions) {
8173     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8174   }
8175   else {
8176     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8177   }
8178   // Store back in big endian from little endian
8179   rorq(sum, 0x20);
8180   movq(Address(out, offset, Address::times_4,  8), sum);
8181 
8182   movq(op1, Address(in, len, Address::times_4,  0));
8183   rorq(op1, 32);
8184   movq(sum, Address(out, offset, Address::times_4,  0));
8185   rorq(sum, 32);
8186   if (UseBMI2Instructions) {
8187     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8188   }
8189   else {
8190     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8191   }
8192   // Store back in big endian from little endian
8193   rorq(sum, 0x20);
8194   movq(Address(out, offset, Address::times_4,  0), sum);
8195 
8196   jmp(L_first_loop);
8197   bind(L_first_loop_exit);
8198 }
8199 
8200 /**
8201  * Code for BigInteger::mulAdd() intrinsic
8202  *
8203  * rdi: out
8204  * rsi: in
8205  * r11: offs (out.length - offset)
8206  * rcx: len
8207  * r8:  k
8208  * r12: tmp1
8209  * r13: tmp2
8210  * r14: tmp3
8211  * r15: tmp4
8212  * rbx: tmp5
8213  * Multiply the in[] by word k and add to out[], return the carry in rax
8214  */
8215 void MacroAssembler::mul_add(Register out, Register in, Register offs,
8216    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
8217    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8218 
8219   Label L_carry, L_last_in, L_done;
8220 
8221 // carry = 0;
8222 // for (int j=len-1; j >= 0; j--) {
8223 //    long product = (in[j] & LONG_MASK) * kLong +
8224 //                   (out[offs] & LONG_MASK) + carry;
8225 //    out[offs--] = (int)product;
8226 //    carry = product >>> 32;
8227 // }
8228 //
8229   push(tmp1);
8230   push(tmp2);
8231   push(tmp3);
8232   push(tmp4);
8233   push(tmp5);
8234 
8235   Register op2 = tmp2;
8236   const Register sum = tmp3;
8237   const Register op1 = tmp4;
8238   const Register carry =  tmp5;
8239 
8240   if (UseBMI2Instructions) {
8241     op2 = rdxReg;
8242     movl(op2, k);
8243   }
8244   else {
8245     movl(op2, k);
8246   }
8247 
8248   xorq(carry, carry);
8249 
8250   //First loop
8251 
8252   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
8253   //The carry is in tmp5
8254   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
8255 
8256   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
8257   decrementl(len);
8258   jccb(Assembler::negative, L_carry);
8259   decrementl(len);
8260   jccb(Assembler::negative, L_last_in);
8261 
8262   movq(op1, Address(in, len, Address::times_4,  0));
8263   rorq(op1, 32);
8264 
8265   subl(offs, 2);
8266   movq(sum, Address(out, offs, Address::times_4,  0));
8267   rorq(sum, 32);
8268 
8269   if (UseBMI2Instructions) {
8270     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8271   }
8272   else {
8273     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8274   }
8275 
8276   // Store back in big endian from little endian
8277   rorq(sum, 0x20);
8278   movq(Address(out, offs, Address::times_4,  0), sum);
8279 
8280   testl(len, len);
8281   jccb(Assembler::zero, L_carry);
8282 
8283   //Multiply the last in[] entry, if any
8284   bind(L_last_in);
8285   movl(op1, Address(in, 0));
8286   movl(sum, Address(out, offs, Address::times_4,  -4));
8287 
8288   movl(raxReg, k);
8289   mull(op1); //tmp4 * eax -> edx:eax
8290   addl(sum, carry);
8291   adcl(rdxReg, 0);
8292   addl(sum, raxReg);
8293   adcl(rdxReg, 0);
8294   movl(carry, rdxReg);
8295 
8296   movl(Address(out, offs, Address::times_4,  -4), sum);
8297 
8298   bind(L_carry);
8299   //return tmp5/carry as carry in rax
8300   movl(rax, carry);
8301 
8302   bind(L_done);
8303   pop(tmp5);
8304   pop(tmp4);
8305   pop(tmp3);
8306   pop(tmp2);
8307   pop(tmp1);
8308 }
8309 #endif
8310 
8311 /**
8312  * Emits code to update CRC-32 with a byte value according to constants in table
8313  *
8314  * @param [in,out]crc   Register containing the crc.
8315  * @param [in]val       Register containing the byte to fold into the CRC.
8316  * @param [in]table     Register containing the table of crc constants.
8317  *
8318  * uint32_t crc;
8319  * val = crc_table[(val ^ crc) & 0xFF];
8320  * crc = val ^ (crc >> 8);
8321  *
8322  */
8323 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
8324   xorl(val, crc);
8325   andl(val, 0xFF);
8326   shrl(crc, 8); // unsigned shift
8327   xorl(crc, Address(table, val, Address::times_4, 0));
8328 }
8329 
8330 /**
8331  * Fold 128-bit data chunk
8332  */
8333 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
8334   if (UseAVX > 0) {
8335     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
8336     vpclmulldq(xcrc, xK, xcrc); // [63:0]
8337     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
8338     pxor(xcrc, xtmp);
8339   } else {
8340     movdqa(xtmp, xcrc);
8341     pclmulhdq(xtmp, xK);   // [123:64]
8342     pclmulldq(xcrc, xK);   // [63:0]
8343     pxor(xcrc, xtmp);
8344     movdqu(xtmp, Address(buf, offset));
8345     pxor(xcrc, xtmp);
8346   }
8347 }
8348 
8349 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
8350   if (UseAVX > 0) {
8351     vpclmulhdq(xtmp, xK, xcrc);
8352     vpclmulldq(xcrc, xK, xcrc);
8353     pxor(xcrc, xbuf);
8354     pxor(xcrc, xtmp);
8355   } else {
8356     movdqa(xtmp, xcrc);
8357     pclmulhdq(xtmp, xK);
8358     pclmulldq(xcrc, xK);
8359     pxor(xcrc, xbuf);
8360     pxor(xcrc, xtmp);
8361   }
8362 }
8363 
8364 /**
8365  * 8-bit folds to compute 32-bit CRC
8366  *
8367  * uint64_t xcrc;
8368  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
8369  */
8370 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
8371   movdl(tmp, xcrc);
8372   andl(tmp, 0xFF);
8373   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
8374   psrldq(xcrc, 1); // unsigned shift one byte
8375   pxor(xcrc, xtmp);
8376 }
8377 
8378 /**
8379  * uint32_t crc;
8380  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
8381  */
8382 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
8383   movl(tmp, crc);
8384   andl(tmp, 0xFF);
8385   shrl(crc, 8);
8386   xorl(crc, Address(table, tmp, Address::times_4, 0));
8387 }
8388 
8389 /**
8390  * @param crc   register containing existing CRC (32-bit)
8391  * @param buf   register pointing to input byte buffer (byte*)
8392  * @param len   register containing number of bytes
8393  * @param table register that will contain address of CRC table
8394  * @param tmp   scratch register
8395  */
8396 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
8397   assert_different_registers(crc, buf, len, table, tmp, rax);
8398 
8399   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
8400   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
8401 
8402   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
8403   notl(crc); // ~crc
8404   cmpl(len, 16);
8405   jcc(Assembler::less, L_tail);
8406 
8407   // Align buffer to 16 bytes
8408   movl(tmp, buf);
8409   andl(tmp, 0xF);
8410   jccb(Assembler::zero, L_aligned);
8411   subl(tmp,  16);
8412   addl(len, tmp);
8413 
8414   align(4);
8415   BIND(L_align_loop);
8416   movsbl(rax, Address(buf, 0)); // load byte with sign extension
8417   update_byte_crc32(crc, rax, table);
8418   increment(buf);
8419   incrementl(tmp);
8420   jccb(Assembler::less, L_align_loop);
8421 
8422   BIND(L_aligned);
8423   movl(tmp, len); // save
8424   shrl(len, 4);
8425   jcc(Assembler::zero, L_tail_restore);
8426 
8427   // Fold crc into first bytes of vector
8428   movdqa(xmm1, Address(buf, 0));
8429   movdl(rax, xmm1);
8430   xorl(crc, rax);
8431   pinsrd(xmm1, crc, 0);
8432   addptr(buf, 16);
8433   subl(len, 4); // len > 0
8434   jcc(Assembler::less, L_fold_tail);
8435 
8436   movdqa(xmm2, Address(buf,  0));
8437   movdqa(xmm3, Address(buf, 16));
8438   movdqa(xmm4, Address(buf, 32));
8439   addptr(buf, 48);
8440   subl(len, 3);
8441   jcc(Assembler::lessEqual, L_fold_512b);
8442 
8443   // Fold total 512 bits of polynomial on each iteration,
8444   // 128 bits per each of 4 parallel streams.
8445   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
8446 
8447   align(32);
8448   BIND(L_fold_512b_loop);
8449   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
8450   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
8451   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
8452   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
8453   addptr(buf, 64);
8454   subl(len, 4);
8455   jcc(Assembler::greater, L_fold_512b_loop);
8456 
8457   // Fold 512 bits to 128 bits.
8458   BIND(L_fold_512b);
8459   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
8460   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
8461   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
8462   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
8463 
8464   // Fold the rest of 128 bits data chunks
8465   BIND(L_fold_tail);
8466   addl(len, 3);
8467   jccb(Assembler::lessEqual, L_fold_128b);
8468   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
8469 
8470   BIND(L_fold_tail_loop);
8471   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
8472   addptr(buf, 16);
8473   decrementl(len);
8474   jccb(Assembler::greater, L_fold_tail_loop);
8475 
8476   // Fold 128 bits in xmm1 down into 32 bits in crc register.
8477   BIND(L_fold_128b);
8478   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
8479   if (UseAVX > 0) {
8480     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
8481     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
8482     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
8483   } else {
8484     movdqa(xmm2, xmm0);
8485     pclmulqdq(xmm2, xmm1, 0x1);
8486     movdqa(xmm3, xmm0);
8487     pand(xmm3, xmm2);
8488     pclmulqdq(xmm0, xmm3, 0x1);
8489   }
8490   psrldq(xmm1, 8);
8491   psrldq(xmm2, 4);
8492   pxor(xmm0, xmm1);
8493   pxor(xmm0, xmm2);
8494 
8495   // 8 8-bit folds to compute 32-bit CRC.
8496   for (int j = 0; j < 4; j++) {
8497     fold_8bit_crc32(xmm0, table, xmm1, rax);
8498   }
8499   movdl(crc, xmm0); // mov 32 bits to general register
8500   for (int j = 0; j < 4; j++) {
8501     fold_8bit_crc32(crc, table, rax);
8502   }
8503 
8504   BIND(L_tail_restore);
8505   movl(len, tmp); // restore
8506   BIND(L_tail);
8507   andl(len, 0xf);
8508   jccb(Assembler::zero, L_exit);
8509 
8510   // Fold the rest of bytes
8511   align(4);
8512   BIND(L_tail_loop);
8513   movsbl(rax, Address(buf, 0)); // load byte with sign extension
8514   update_byte_crc32(crc, rax, table);
8515   increment(buf);
8516   decrementl(len);
8517   jccb(Assembler::greater, L_tail_loop);
8518 
8519   BIND(L_exit);
8520   notl(crc); // ~c
8521 }
8522 
8523 #undef BIND
8524 #undef BLOCK_COMMENT
8525 
8526 
8527 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
8528   switch (cond) {
8529     // Note some conditions are synonyms for others
8530     case Assembler::zero:         return Assembler::notZero;
8531     case Assembler::notZero:      return Assembler::zero;
8532     case Assembler::less:         return Assembler::greaterEqual;
8533     case Assembler::lessEqual:    return Assembler::greater;
8534     case Assembler::greater:      return Assembler::lessEqual;
8535     case Assembler::greaterEqual: return Assembler::less;
8536     case Assembler::below:        return Assembler::aboveEqual;
8537     case Assembler::belowEqual:   return Assembler::above;
8538     case Assembler::above:        return Assembler::belowEqual;
8539     case Assembler::aboveEqual:   return Assembler::below;
8540     case Assembler::overflow:     return Assembler::noOverflow;
8541     case Assembler::noOverflow:   return Assembler::overflow;
8542     case Assembler::negative:     return Assembler::positive;
8543     case Assembler::positive:     return Assembler::negative;
8544     case Assembler::parity:       return Assembler::noParity;
8545     case Assembler::noParity:     return Assembler::parity;
8546   }
8547   ShouldNotReachHere(); return Assembler::overflow;
8548 }
8549 
8550 SkipIfEqual::SkipIfEqual(
8551     MacroAssembler* masm, const bool* flag_addr, bool value) {
8552   _masm = masm;
8553   _masm->cmp8(ExternalAddress((address)flag_addr), value);
8554   _masm->jcc(Assembler::equal, _label);
8555 }
8556 
8557 SkipIfEqual::~SkipIfEqual() {
8558   _masm->bind(_label);
8559 }