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